diff --git a/.changeset/cli-command-completions.md b/.changeset/cli-command-completions.md new file mode 100644 index 0000000000..ca4e9f1694 --- /dev/null +++ b/.changeset/cli-command-completions.md @@ -0,0 +1,5 @@ +--- +"cf": minor +--- + +Suggest commands and flags from the CLI's parser when you press Tab. Existing bash, zsh, fish and PowerShell completion scripts keep working. Generated command help and suggestions no longer load the selected command's API handler. diff --git a/.changeset/stricli-parser.md b/.changeset/stricli-parser.md new file mode 100644 index 0000000000..b06f7caecc --- /dev/null +++ b/.changeset/stricli-parser.md @@ -0,0 +1,7 @@ +--- +"cf": minor +--- + +Parse CLI arguments with Stricli instead of yargs. + +Keep the existing command names, flags, and boolean coercion. Only an affirmative force switch bypasses destructive confirmation. diff --git a/.changeset/suggest-local-auth-profiles.md b/.changeset/suggest-local-auth-profiles.md new file mode 100644 index 0000000000..5c10985eb3 --- /dev/null +++ b/.changeset/suggest-local-auth-profiles.md @@ -0,0 +1,7 @@ +--- +"cf": minor +--- + +Complete saved auth profile names when pressing Tab. + +Use the existing shell integration to complete `--profile` values or named profiles for `cf auth activate`, `create`, and `delete`. Suggestions come from local profile names; no credentials or Cloudflare API calls are needed. diff --git a/.github/workflows/packed-cli-parity.yml b/.github/workflows/packed-cli-parity.yml new file mode 100644 index 0000000000..69117b360c --- /dev/null +++ b/.github/workflows/packed-cli-parity.yml @@ -0,0 +1,53 @@ +name: Packed CLI parity + +on: + pull_request: + paths: + - "packages/cli/src/lib/stricli*.ts" + - "scripts/compare-packed-cli.mjs" + - ".github/workflows/packed-cli-parity.yml" + +permissions: + contents: read + +jobs: + compare: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 20 + steps: + - name: Preserve launcher shebangs and allow long paths on Windows + if: runner.os == 'Windows' + run: | + git config --global core.autocrlf false + git config --system core.longpaths true + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + path: head + persist-credentials: false + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + path: base + ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: false + - uses: $/.github/actions/install-dependencies + with: + working-directory: head + - uses: $/.github/actions/install-dependencies + with: + working-directory: base + - name: Build, pack and install both CLIs outside their workspaces + shell: bash + run: | + set -euo pipefail + for side in base head; do + mkdir "install-$side" + (cd "$side" && pnpm --filter cf build) + (cd "$side/packages/cli" && pnpm pack --pack-destination "../../../install-$side") + (cd "install-$side" && npm install --ignore-scripts --no-audit --no-fund ./*.tgz) + done + - name: Compare installed commands, including their exit status + run: node head/scripts/compare-packed-cli.mjs install-base install-head diff --git a/AGENTS.md b/AGENTS.md index d23059b2a8..513d04dc78 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -124,7 +124,7 @@ In the rules below, `src/` means `packages/cli/src/`. - Keep the hand-written registry import-free plain data; root lazy loaders and telemetry belong in `root-commands.ts`. Keep each command's `meta.ts` sidecar and the typed `hand-written-meta.ts` list in sync. -- Let strict yargs own unknown-option validation. Keep emitter options and +- Keep unknown-option validation in the shared command parser. Keep emitter options and metadata synchronized. Reserve a new cross-cutting flag in `src/lib/global-options.ts` before introducing it; generation fails on any API field that would take a flag cf owns. diff --git a/docs/architecture.md b/docs/architecture.md index 6230c3eea7..1431663703 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -22,7 +22,7 @@ Paths below are relative to the repository root unless a section uses the cf/ ├── packages/cli/ # cf — CLI + generator │ ├── src/ -│ │ ├── index.ts # yargs entry; registers lazy-loaded generated +│ │ ├── index.ts # Stricli entry; registers lazy-loaded generated │ │ │ # commands + hand-written commands │ │ ├── dev.ts # tsx entry wrapper (maps CliExit → process.exit); │ │ │ # NOT the `cf dev` command @@ -155,7 +155,7 @@ the document; the command generator is a forge plugin that lives here, in WebAssembly component that forge runs. It walks forge's model of the operations, each top-level group's commands in turn, and emits: -- `src/commands/_generated///.ts` — yargs command modules +- `src/commands/_generated///.ts` — Stricli API command declarations - `src/commands/_generated/_operations///.ts` — one module per method, at its path in the group tree, whose default export is its `Operation` (`d1.database.query` in `_operations/d1/database/query.ts`); @@ -191,10 +191,7 @@ literal says where each goes, how the response is read, and which status errors the operation declares. Commands whose request can't be expressed that way send a passthrough `requestApi` call instead. -Shell completions are no longer generated — `cf complete` is backed by -`@bomb.sh/tab`, which parses the command/option tree at runtime from -the complete generated and hand-written `_meta/commands.json` catalogue (see -`src/commands/completions/index.ts`). +`cf complete` uses the same route resolution and flag declarations as the parser. Stricli suggests the next command, alias, flag or enum value. For `--profile` and named profile arguments to `auth activate`, `create`, and `delete`, it also suggests matching local profile names. Completion lists filenames only: it does not read credentials, contact the API, or require a working profile store. `@bomb.sh/tab` supplies the bash, zsh, fish and PowerShell scripts; their callback protocol is unchanged. `pnpm build` runs Vite+ Pack, which: @@ -210,7 +207,7 @@ the complete generated and hand-written `_meta/commands.json` catalogue (see | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Add/fix a generated command | Overlay files in `@cloudflare/forge` — NOT in this repo. Edit forge; Renovate picks up the next tagged release. | | Add a generated-command rule | `packages/cli/generator/plugin/` — emits handler body, arg shapes, body validation, confirm prompts, etc.; rerun `pnpm generate` | -| New cross-product flag | yargs middleware in `packages/cli/src/index.ts` (`--zone`, `--profile`, `--quiet`, `--local`, `--persist-to`) | +| New cross-product flag | startup hook in `packages/cli/src/index.ts` (`--zone`, `--profile`, `--quiet`, `--local`, `--persist-to`) | | Hand-written command | roots under `packages/cli/src/commands/{auth,build,cli,completions,dev,deploy,init,previews}/` plus `schema.ts` and `tools.ts`; generated-tree exceptions under `{access,ai,registrar,d1,observability,tunnels,workers}/`; register every one in `src/commands/hand-written.ts` | | Hand-written metadata/emit | per-command `meta.ts`, `packages/cli/src/commands/{hand-written,hand-written-meta,root-commands}.ts` | | `cf init` scaffold / setup | `packages/cli/src/commands/init/{index,workers,template}.ts` | @@ -220,7 +217,7 @@ the complete generated and hand-written `_meta/commands.json` catalogue (see | Auth / OAuth | `packages/cli/src/lib/auth.ts`, `packages/cli/src/lib/oauth/` | | `cloudflare.config.ts` settings | `packages/cli/src/lib/project-settings.ts` | | Global CLI state | `packages/cli/src/lib/state.ts` (shell-completion and telemetry state under workers-auth's canonical cf config directory) | -| Help formatting | yargs built-in (cf no longer overrides help) | +| Help formatting | declaration-driven renderer in `packages/cli/src/lib/stricli.ts` | | `--local` request routing | `packages/cli/src/lib/{local,local-runtime}.ts` | | Local-install delegation | `packages/cli/src/lib/delegate.ts` | | Output / spinner / errors | `packages/cli/src/lib/{output,progress,errors,prompt}.ts`, `lib/ui/` | @@ -269,7 +266,7 @@ the complete generated and hand-written `_meta/commands.json` catalogue (see | `ui/theme.ts` | background-neutral semantic colour palette and Chalk wrapper | | `ui/format.ts` | one-line `success`, `warning`, and `hint` helpers | | `ui/log.ts` | stderr messages: clack notices (hidden by `--quiet`), warnings and flow lines, each notice or warning optionally followed by copyable commands; not re-exported from `ui/index.ts` | -| `input-validation.ts` | yargs-time arg coercion + `resolveFileToken(value, fieldName, format)` for `@` ingestion; runtime body/path validation | +| `input-validation.ts` | parse-time arg coercion + `resolveFileToken(value, fieldName, format)` for `@` ingestion; runtime body/path validation | | `resolve.ts` | URL templating (path-param substitution), `isId`, `isValidDomainName` | ## Critical Invariants @@ -357,22 +354,19 @@ Practical extensions of this rule: ### Lazy command registration -Each generated top-level root and each hand-written root is registered via `lazyCommand` (`src/lib/lazy-command.ts`). The outer shell exposes only the `command` + `describe` strings yargs needs; selecting a root dynamically imports its root module/chunk. Within that selected generated root, index files statically import and register the full subtree. Without the outer lazy boundary, `cf --help` / `cf --version` / any command would eagerly load every generated root, the complete command catalogue, the API client, and every helper. +Each generated top-level root and each hand-written root is registered via `lazyCommand` (`src/lib/lazy-command.ts`). The outer shell exposes only the `command` + `describe` strings the router needs; selecting a root dynamically imports its root module/chunk. Within the selected generated root, index files import the subtree’s command definitions. Each generated definition uses a Stricli loader to import its `.handler.ts` sibling only for execution; its argument type comes from the definition via a type-only import. Without the outer lazy boundary, `cf --help` / `cf --version` / any command would eagerly load every generated root, the complete command catalogue, the API client, and every helper. Vite+ Pack preserves those dynamic root imports as code-split chunks (and may factor shared dependencies into additional chunks), so do not assume a strict one-chunk-per-root correspondence. Don't reintroduce eager top-level imports of `_generated/index.ts` from anywhere besides the lazy shell registration in `src/index.ts`. ### Generator output (DO NOT EDIT) -- `packages/cli/src/commands/_generated/` — yargs modules, `_operations/` +- `packages/cli/src/commands/_generated/` — Stricli command and route-map modules, `_operations/` operation literals, and `_meta/` JSON Tracked in git and never safe to patch by hand. Every `pnpm generate` cleans, rewrites, and Vite+-formats `_generated/`. Make changes in Forge's OpenAPI or in the generator plugin (`packages/cli/generator/plugin/`), then regenerate and commit the resulting artifacts. GitHub collapses `_generated/` by default because it is marked `linguist-generated`, but AI reviewers must still review every changed file there. -Shell-completion scripts are no longer generated — `cf complete` -(`@bomb.sh/tab`) reads `_meta/commands.json` at runtime. - ### OpenAPI compatibility overlay `generate.ts` applies `generator/cli-compat.overlay.yaml` to both downloaded @@ -577,7 +571,7 @@ to know before editing `generator/plugin/`. fail with a clear "--body is required" error instead of an opaque EOF API error. - Per-field-flag `demandOption: true` is suppressed when `--body` is - also supported (so `--body @file` isn't rejected by yargs for + also supported (so `--body @file` isn't rejected during parsing for missing required fields — handler-time enforcement instead). - Required body positionals remain mandatory when `--body` is supplied, even when the JSON contains the same fields. Body positionals merge into JSON @@ -710,7 +704,7 @@ Hand-written commands with no generated parent (`auth/`, `build/`, `cli/`, `schema.ts` and `tools.ts`) are `kind: "root"` entries and must not collide with a generated product name. -Generation merges every hand-written leaf into the complete `_meta/commands.json` consumed by completions and tools. Generation additionally emits `_meta/hand-written-commands.json`, repeating only executable entries with their `root` / `leafOverride` / `leaf` / `subgroup` provenance and source directory. Presentation-only `parentOverride` entries do not represent commands and are not emitted there. +Generation merges every hand-written leaf into the complete `_meta/commands.json` consumed by discovery tools. Generation additionally emits `_meta/hand-written-commands.json`, repeating only executable entries with their `root` / `leafOverride` / `leaf` / `subgroup` provenance and source directory. Presentation-only `parentOverride` entries do not represent commands and are not emitted there. Container SSH is a bounded hand-written leaf in `src/commands/containers/ssh`, registered in `hand-written.ts`. It adapts cf authentication to the same `@cloudflare/containers-shared` SSH options and transport used by Wrangler. @@ -755,10 +749,9 @@ break at sunset; surfacing them encourages users to adopt doomed paths. each accepted body in one request. No automatic batching is inferred from schema limits. -### Strict yargs +### Argument parsing -`yargs.strict()` handles unknown flags. There are no pre-yargs -allowlists — yargs is authoritative. Keep it that way. +`src/lib/api-command.ts` builds Stricli commands and route maps from generated declarations. Flag kinds, parsers, defaults, variadic flags, and named operands determine generated handler input types. `src/lib/stricli.ts` preserves cf help, error messages, aliases, and token spellings that Stricli does not accept natively. Hand-written commands can still use builder declarations and yargs types; neither path loads the yargs runtime. Unknown options are rejected before startup unless a command explicitly accepts or forwards them. ### Output @@ -802,7 +795,7 @@ pass its `cursor` value to `cf zero-trust casb findings list --cursor `. Required fields inside an optional request-body object are validated only when a flag supplies that object. Omitting the object leaves those nested fields -optional. Because yargs performs this validation before the handler, missing +optional. Because the parser performs this validation before the handler, missing fields in a supplied optional object are rejected rather than prompted for. For other required body fields, when stdin is a TTY and the field is not supplied: @@ -867,7 +860,7 @@ These have stabilised this repo's voice; preserve them. (the commands passed to `log.info` / `log.warn`); other commands in a message are styled as code. `--quiet` hides notices and success lines, never warnings, fixes or prompts. -- **Splash screen:** bare `cf` prints the headline, a short getting-started list, and the docs link. Yargs owns root, group, and command help rendering. +- **Splash screen:** bare `cf` prints the headline, a short getting-started list, and the docs link. The cf declaration adapter renders root, group, and command help. ## Global Flags diff --git a/packages/cli/AGENTS.md b/packages/cli/AGENTS.md index 7cc598ec67..c4aef78e93 100644 --- a/packages/cli/AGENTS.md +++ b/packages/cli/AGENTS.md @@ -1,6 +1,6 @@ # cf (`packages/cli`) -Cloudflare CLI. Yargs-based, TypeScript, ESM, Node ≥ 22. +Cloudflare CLI. Generated commands and the hand-written `auth` family use native Stricli declarations; other hand-written families use the compatibility builder. TypeScript, ESM, Node ≥ 22. This package IS the CLI. It also owns the generator that produces its per-API command surface: the forge plugin in `generator/plugin/`, which @@ -11,7 +11,7 @@ forge runs (`forge generate --target wasm://...`) to write `src/commands/_genera The cross-cutting runtime (`src/index.ts` and generic helpers under `src/lib/`) must remain a generic shell over whatever commands the generator emits into `src/commands/_generated/`. Product-specific behavior belongs in Forge unless it is one of the deliberately bounded hand-written exceptions below or the universal zone-name resolver used by global `--zone`. - `src/index.ts` imports `generatedCommands` and registers them in a loop -- each generated top-level command root is registered through `lazyCommand`; selecting it loads the root's statically imported group/leaf subtree +- each generated top-level command root is registered through `lazyCommand`; selecting it loads the product’s command definitions; generated execution handlers load separately, on invocation - Adding a new API product is a forge change, not a cf change If a generic runtime or generator change starts branching on a product name, first look for a Forge/OpenAPI annotation. The existing Worker-name derivation is a narrowly scoped generator exception; `context.ts` / `project-settings.ts` resolve an omitted Worker from source config for that helper. The zone runtime exception is likewise contained: `context.ts` delegates non-ID global zone values to `resolve.ts`, which validates the domain and calls `client.zones.list()` for the selected account. Do not use these as permission to spread product checks through the runtime. @@ -49,10 +49,10 @@ second consumer. | Global CLI state | `src/lib/state.ts` | | Local request routing | `src/lib/local.ts`, `src/lib/local-runtime.ts` | | Build/deploy conversion | `src/lib/{build-output,deploy-context,deploy-input}.ts` | -| Help labels and flag groups | yargs configuration in `src/index.ts` (no custom renderer) | +| Help labels and flag groups | declaration-driven help in `src/lib/stricli.ts` | | Generator output shape | `generator/plugin/` (rerun `pnpm generate`) | | Metadata JSON shape | `generator/plugin/files.ts` | -| Shell completions | `src/commands/completions/index.ts` (`@bomb.sh/tab`, backed by complete `commands.json` metadata) | +| Shell completions | `src/commands/completions/index.ts` (shell scripts from `@bomb.sh/tab`, suggestions from the runtime parser) | ## Build @@ -181,10 +181,10 @@ cf resolves account parameters itself. ## Generated (DO NOT EDIT) -- `src/commands/_generated/` — yargs command files, `_operations/` operation +- `src/commands/_generated/` — Stricli command and route-map files, `_operations/` operation literals, and `_meta/*.json` -The output is tracked in git, owned by `pnpm generate`, and must not be hand-edited. Shell-completion scripts are no longer generated — `cf complete` (backed by `@bomb.sh/tab`) reads the complete generated and hand-written command tree from `_meta/commands.json`. `_meta/hand-written-commands.json` republishes the hand-written subset with root/leaf/subgroup/override provenance. +The output is tracked in git, owned by `pnpm generate`, and must not be hand-edited. `cf complete` uses Stricli suggestions from the registered commands and flags; `@bomb.sh/tab` supplies the four shell integrations. `_meta/hand-written-commands.json` republishes the hand-written subset with root/leaf/subgroup/override provenance. ## Generator plugin diff --git a/packages/cli/generator/plugin/emit/builder.ts b/packages/cli/generator/plugin/emit/builder.ts index 14aa27bd83..a901428f5b 100644 --- a/packages/cli/generator/plugin/emit/builder.ts +++ b/packages/cli/generator/plugin/emit/builder.ts @@ -1,4 +1,3 @@ -/** Emits a command's yargs builder: a port of cf's `emit/builder.ts`. */ import { fileFormat, hasChoices, @@ -12,16 +11,6 @@ import { import { kebab, obj, stringify, type Value } from "../js.js"; import { type Ctx, escapeSingle } from "./index.js"; -function option(name: string, fields: [string, Value | undefined][]): string { - const map = obj(); - for (const [k, v] of fields) { - if (v !== undefined) { - map[k] = v; - } - } - return `.option('${name}', ${stringify(map)})`; -} - const quoted = (v: readonly string[]) => v.map((c) => `'${c}'`).join(", "); export const JSON_BODY_DESCRIPTION = @@ -44,29 +33,51 @@ export function bodyOptionDescription(op: Ctx["op"]): string { : JSON_BODY_DESCRIPTION; } -/** `generateBuilderLines`. */ -export function builderLines(ctx: Ctx): string[] { +export function parameterSource(ctx: Ctx) { const d = ctx.derived; const op = ctx.op; const positional = positionals(d); const options = optionArgs(d); const defaults = optionDefaults(d, op); - const lines: string[] = []; + const flags = new Map(); + const operands: string[] = []; + const rules: string[] = []; + function emitFlag( + name: string, + type: string, + description: string, + extras: Record = {}, + coerce?: string + ) { + const { choices, array, required, ...rest } = extras; + const nativeEnum = + type === "string" && Array.isArray(choices) && choices.length && !coerce; + const kind = + type === "boolean" ? "boolean" : nativeEnum ? "enum" : "parsed"; + const spec = obj([ + ["kind", kind], + ["brief", description], + ]); + if (nativeEnum) spec.values = choices; + if (array) spec.variadic = true; + if (!required && rest.default === undefined) spec.optional = true; + for (const [key, value] of Object.entries(rest)) + if (value !== undefined) spec[key] = value; + if (!nativeEnum && choices !== undefined) spec.choices = choices; + if (kind === "parsed" && spec.default !== undefined) + spec.default = String(spec.default); + const properties = [stringify(spec).slice(1, -1)]; + if (kind === "parsed") + properties.push(`parse: ${type === "number" ? "Number" : "String"}`); + if (coerce) properties.push(`coerce: ${coerce}`); + flags.set(name, `${stringify(name)}: {${properties.join(", ")}},`); + } for (const arg of positional) { - lines.push(` .positional('${kebab(arg.name)}', {`); - lines.push( - ` type: '${arg.type === "number" || arg.type === "boolean" ? arg.type : "string"}',` - ); - if (arg.type === "array") { - lines.push(" array: true,"); - } const base = escapeSingle(arg.description); const desc = arg.isZone ? `${base} (or use --zone flag)` : base; - lines.push(` description: '${desc}',`); - if (arg.required && !arg.isZone && !arg.isWorkerName) { - lines.push(" demandOption: true,"); - } - lines.push(" })"); + operands.push( + `{placeholder: '${kebab(arg.name)}', brief: '${desc}', parse: ${arg.type === "number" ? "Number" : "String"}, ${arg.required && !arg.isZone && !arg.isWorkerName ? "" : "optional: true,"} ${arg.type === "array" ? "rest: true," : ""}${arg.type === "boolean" ? "booleanLabel: true," : ""}},` + ); } for (const arg of options) { const name = kebab(arg.name); @@ -84,17 +95,7 @@ export function builderLines(ctx: Ctx): string[] { : "string"; const demand = arg.required && !arg.isZone && !arg.isWorkerName && !skipDemand; - lines.push( - option(name, [ - ["type", type], - ["array", scalarArray ? true : undefined], - ["alias", arg.isWorkerName ? WORKER_ALIASES : undefined], - ["description", arg.description], - ["choices", arg.choices], - ["default", defaults.get(arg.name)], - ["demandOption", demand ? true : undefined], - ]) - ); + let coerce: string | undefined; if (scalarArray && arg.origin.in === "query" && hasChoices(arg)) { const commaChoices = arg.choices?.filter((value) => value.includes(",")) ?? []; @@ -102,45 +103,59 @@ export function builderLines(ctx: Ctx): string[] { commaChoices.length > 0 ? `${stringify(commaChoices)}.includes(value) ? [value] : value.split(",")` : 'value.split(",")'; - lines.push( - `.coerce(${stringify(name)}, (values: string[]) => values.flatMap((value) => ${split}))` - ); + coerce = `(values: string[]) => values.flatMap((value) => ${split})`; } - if (arg.isWorkerName && arg.positional) { - lines.push(`.group(${stringify(name)}, theme.brand('Options'))`); - } - // Resolve `@file` before yargs validates `choices` against the value, + // Resolve `@file` before cf validates `choices` against the value, // so the handler gets the file's contents without reading it twice. if (arg.fromFile !== undefined && hasChoices(arg)) { - lines.push( - `.coerce(${stringify(name)}, (value) => resolveFileToken(value, ${stringify(name)}, ${fileFormat(arg)}))` - ); + coerce = `(value: string) => resolveFileToken(value, ${stringify(name)}, ${fileFormat(arg)})`; } + emitFlag( + name, + type, + arg.description, + { + array: scalarArray, + required: demand, + choices: arg.choices, + default: defaults.get(arg.name), + alias: arg.isWorkerName ? WORKER_ALIASES : undefined, + grouped: (arg.isWorkerName && arg.positional) || undefined, + }, + coerce + ); } - lines.push( - `.option("dry-run", {"type":"boolean","description":"Validate and show what would happen without executing","default":false})` + emitFlag( + "dry-run", + "boolean", + "Validate and show what would happen without executing", + { default: false } ); if (ctx.isDelete) { - lines.push( - `.option("force", {"type":"boolean","alias":"f","description":"Skip confirmation (useful in scripts and CI)","default":false})` + emitFlag( + "force", + "boolean", + "Skip confirmation (useful in scripts and CI)", + { alias: "f", default: false } ); } if (d.hasBody) { - const desc = bodyOptionDescription(op); - lines.push(" .option('body', {"); - lines.push(" type: 'string',"); - lines.push(` description: '${escapeSingle(desc)}',`); - lines.push(" })"); + emitFlag( + "body", + "string", + bodyOptionDescription(op).replace(/[\r\n\u2028\u2029]/g, " ") + ); } if (ctx.outputKind === "binary") { - lines.push( - `.option("text", {"type":"boolean","description":"Decode the response body as UTF-8 text instead of writing raw bytes","default":false})` + emitFlag( + "text", + "boolean", + "Decode the response body as UTF-8 text instead of writing raw bytes", + { default: false } ); } if (d.hasFileUpload) { - lines.push( - `.option("file", {"type":"string","description":"Path to a file to upload as the request body"})` - ); + emitFlag("file", "string", "Path to a file to upload as the request body"); } for (const { field, flag } of d.multipartFlagFields) { if ([...options, ...positional].some((a) => kebab(a.name) === flag)) { @@ -152,20 +167,13 @@ export function builderLines(ctx: Ctx): string[] { : field.type === "boolean" ? "boolean" : "string"; - lines.push(` .option('${flag}', {`); - lines.push(` type: '${type}',`); - lines.push(` description: '${escapeSingle(field.description)}',`); - lines.push(" })"); + emitFlag(flag, type, field.description.replace(/[\r\n\u2028\u2029]/g, " ")); } for (const { field, flag } of d.multipartFileFields) { - lines.push( - option(flag, [ - ["type", "string"], - ["array", field.type === "array" ? true : undefined], - ["requiresArg", field.type === "array" ? true : undefined], - ["description", multipartFileFlagDescription(field)], - ]) - ); + emitFlag(flag, "string", multipartFileFlagDescription(field), { + array: field.type === "array", + requiresArg: field.type === "array" || undefined, + }); } for (const arg of d.args) { if (!isBody(arg) || arg.positional) { @@ -173,13 +181,13 @@ export function builderLines(ctx: Ctx): string[] { } const me = kebab(arg.name); if (arg.conflicts !== undefined && arg.conflicts.length > 0) { - lines.push( - ` .conflicts('${me}', [${quoted(arg.conflicts.map(kebab))}])` + rules.push( + `rules.conflicts('${me}', [${quoted(arg.conflicts.map(kebab))}]);` ); } if (arg.implies !== undefined && arg.implies.length > 0) { - lines.push( - ` .implies('${me}', [${quoted(arg.implies.map(kebab))}])` + rules.push( + `rules.implies('${me}', [${quoted(arg.implies.map(kebab))}]);` ); } } @@ -222,32 +230,38 @@ export function builderLines(ctx: Ctx): string[] { conflictsByFlag.find(([k]) => k === f)?.[1] ?? [], ]) .filter(([, c]) => c.length > 0); - lines.push(" .check((argv) => {"); - lines.push( + rules.push("rules.check((argv) => {"); + rules.push( ` const groupSet = ${set}.some((k) => argv[k] !== undefined);` ); - lines.push(" if (!argv.body && groupSet) {"); + rules.push(" if (!argv.body && groupSet) {"); if (pairs.length === 0) { - lines.push( + rules.push( ` const missing = ${required}.filter((k) => argv[k] === undefined);` ); } else { const map = pairs.map(([f, c]) => `'${f}': [${quoted(c)}]`).join(", "); - lines.push( + rules.push( ` const requiredConflicts: Record = { ${map} };` ); - lines.push( + rules.push( ` const missing = ${required}.filter((k) => argv[k] === undefined && !(requiredConflicts[k] ?? []).some((x) => argv[x] !== undefined));` ); } - lines.push(" if (missing.length > 0) {"); - lines.push( + rules.push(" if (missing.length > 0) {"); + rules.push( ` throw new Error(\`\${missing.map((m) => '--' + m).join(', ')} \${missing.length === 1 ? 'is' : 'are'} required when ${groupFlags} is set\`);` ); - lines.push(" }"); - lines.push(" }"); - lines.push(" return true;"); - lines.push(" })"); + rules.push(" }"); + rules.push(" }"); + rules.push(" return true;"); + rules.push("});"); } - return lines; + return [ + `flags: {`, + ...flags.values(), + `},`, + `operands: [${operands.join("\n")}],`, + ...(rules.length ? [`rules(rules) {`, ...rules, `},`] : []), + ]; } diff --git a/packages/cli/generator/plugin/emit/handler.ts b/packages/cli/generator/plugin/emit/handler.ts index 1900543aeb..a6ab6269d1 100644 --- a/packages/cli/generator/plugin/emit/handler.ts +++ b/packages/cli/generator/plugin/emit/handler.ts @@ -1162,8 +1162,6 @@ export function imports(ctx: Ctx): Imports { const d = ctx.derived; const i = new Imports(); const lib = "#lib"; - i.typeFrom("yargs", ["Argv", "CommandModule"]); - i.typeFrom(`${lib}/cli-types.js`, ["CommonYargsOptions", "InferArgs"]); const authNames = ["createCommandClient"]; if (ctx.needsAccountId) { authNames.push("getAccountId", "resolveAccountIdSilent"); @@ -1183,9 +1181,6 @@ export function imports(ctx: Ctx): Imports { } i.from(`${lib}/output.js`, ["formatOutput"]); i.from(`${lib}/dry-run.js`, ["formatDryRun"]); - if (positionals(d).some((arg) => arg.isWorkerName)) { - i.from(`${lib}/ui/theme.js`, ["theme"]); - } if ((ctx.op.bodyUnions?.length ?? 0) > 0 && d.hasBodyParams) { i.from(`${lib}/body-unions.js`, ["validateBodyUnions"]); } @@ -1197,7 +1192,9 @@ export function imports(ctx: Ctx): Imports { } const bodyFlags = bodyOptions(d); const bodyArgs = [...bodyFlags, ...bodyFieldArgs(ctx).map(([arg]) => arg)]; - const flagsNeedToken = bodyArgs.some((a) => a.fromFile !== undefined); + const flagsNeedToken = bodyArgs.some( + (a) => a.fromFile !== undefined && !hasChoices(a) + ); const nonJsonBody = d.hasBody && !acceptsJson(ctx); const needsToken = flagsNeedToken || diff --git a/packages/cli/generator/plugin/files.ts b/packages/cli/generator/plugin/files.ts index 36c63c39b8..4c8e2016ba 100644 --- a/packages/cli/generator/plugin/files.ts +++ b/packages/cli/generator/plugin/files.ts @@ -9,6 +9,7 @@ import { type Arg, derive, downgradeOptionalParents, + hasChoices, isBody, isZonePathParam, multipartFileFlagDescription, @@ -21,7 +22,7 @@ import { import { requiresConfirmation } from "./confirmation.js"; import { bodyOptionDescription, - builderLines, + parameterSource, isPlainTextBody, JSON_BODY_DESCRIPTION, } from "./emit/builder.js"; @@ -475,7 +476,7 @@ class Walk { ); const handlerLines = handler(ctx); const importSet = imports(ctx); - const builder = builderLines(ctx); + const parameters = parameterSource(ctx); const usage = leafUsage( method, resource, @@ -483,12 +484,10 @@ class Walk { command, ctx.hasAccountOrZoneScope ); - const builderBody = `return yargs\n .usage(${quote(usage)})\n${builder.join("\n")};`; const declarations = - "type Args = InferArgs;\n" + - ((op.bodyUnions?.length ?? 0) > 0 && ctx.derived.hasBodyParams + (op.bodyUnions?.length ?? 0) > 0 && ctx.derived.hasBodyParams ? `const bodyUnions: Parameters[1] = ${stringify(op.bodyUnions ?? [])};\n` - : ""); + : ""; const telemetryPath = group !== undefined && group !== "" ? `${resource} ${group.replaceAll("/", " ")} ${method.name}` @@ -502,33 +501,47 @@ class Walk { const aliases = ctx.isDelete ? ", shortFlagAliases: { f: { canonical: 'force', type: 'boolean' } }" : ""; - return `/** - * ${method.name} command - * @generated from apis/overlays/${resource}.ts - */ + const basename = trimEndMatches( + emitPath.slice(emitPath.lastIndexOf("/") + 1), + ".ts" + ); + this.files.push({ + path: emitPath.replace(/\.ts$/, ".handler.ts"), + content: `import type { Args } from './${basename}.js'; ${importSet.render().join("\n")} - -function builder(yargs: Argv) { - ${builderBody} -} - ${declarations} -const command: CommandModule = { - command: '${command}', - describe: '${escapeSingle(summary(method))}', - builder, - handler: async (argv): Promise => - runWithTelemetry( +export default async function handle(argv: Args): Promise { + return runWithTelemetry( { command: '${escapeSingle(telemetryPath)}', - classification: { safeFlags: ${safe}${aliases} } satisfies ArgClassification, + classification: { safeFlags: ${safe}${aliases} } satisfies ArgClassification, }, argv as Record, async () => { ${handlerLines.join("\n")} }, - ), -}; + ); +} +`, + }); + return `/** + * ${method.name} command + * @generated from apis/overlays/${resource}.ts + */ +import { apiCommand, type ApiInputs, type ApiParameters } from '#lib/api-command.js'; +${optionArgs(ctx.derived).some((arg) => arg.fromFile !== undefined && hasChoices(arg)) ? "import { resolveFileToken } from '#lib/input-validation.js';" : ""} + +const parameters = { + ${parameters.join("\n")} +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ + command: '${command}', + describe: '${escapeSingle(summary(method))}', + usage: ${quote(usage)}, + ...parameters, + loader: () => import('./${basename}.handler.js'), +}); export default command; `; @@ -669,14 +682,14 @@ export default command; // A hand-written command handles `--dry-run` by the strategy it // chose, which the index wraps it with. let wraps = false; - const register = (v: string, dryRun: DryRun | undefined) => { + const register = (name: string, v: string, dryRun: DryRun | undefined) => { if (dryRun === undefined) { - registrations.push(` .command(${v})`); + registrations.push(` '${name}': ${v},`); return; } wraps = true; registrations.push( - ` .command(withHandWrittenDryRun(${v}, '${String(dryRun)}'))` + ` '${name}': withHandWrittenDryRun(${v}, '${String(dryRun)}'),` ); }; const parent = trimEndMatches(prefix, "/"); @@ -691,7 +704,7 @@ export default command; : `./${cmd}.js`); importLines.push(`import ${v} from '${module}';`); const leaf = this.hand.leaves(parent).find((l) => l.name === cmd); - register(v, leaf?.dryRun); + register(cmd, v, leaf?.dryRun); } for (const [name, handWritten] of subgroups) { const v = `$${name.replaceAll("-", "")}`; @@ -700,7 +713,7 @@ export default command; ? `#commands/${handWritten.dir}/index.js` : `./${name}/index.js`; importLines.push(`import ${v} from '${module}';`); - register(v, handWritten?.dryRun); + register(name, v, handWritten?.dryRun); } const wrapper = wraps ? "import { withHandWrittenDryRun } from '#lib/hand-written-dry-run.js';" @@ -709,23 +722,18 @@ export default command; * ${header} * @generated from apis/overlays/${resource}.ts */ -import type { CommandModule } from 'yargs'; -import type { CommonYargsOptions } from '#lib/cli-types.js'; +import { apiGroup } from '#lib/api-command.js'; ${wrapper} ${importLines.join("\n")} -const command: CommandModule = { +const command = apiGroup({ command: '${command}', describe: '${escapeSingle(describe)}', - builder: (yargs) => { - return yargs + routes: { ${registrations.join("\n")} - .demandCommand(1, "Please specify a subcommand"); }, - - handler: () => {}, -}; +}); export default command; `; diff --git a/packages/cli/package.json b/packages/cli/package.json index 803d711b91..1d46124bfc 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -89,6 +89,7 @@ "@cloudflare/workers-auth": "0.18.8", "@cloudflare/workers-utils": "0.57.0", "@redocly/openapi-core": "2.82.0", + "@stricli/core": "1.3.0", "@types/node": "26.6.6", "@types/semver": "7.8.0", "@types/shell-quote": "^1.7.5", @@ -96,6 +97,7 @@ "@types/yargs": "17.0.35", "chalk": "6.0.1", "ci-info": "^4.5.0", + "cliui": "9.0.1", "esbuild": "0.28.2", "figures": "6.1.0", "minimatch": "11.0.9", @@ -109,8 +111,7 @@ "tsx": "4.21.0", "undici": "8.13.0", "vite-plus": "catalog:", - "ws": "8.23.0", - "yargs": "18.2.0" + "ws": "8.23.0" }, "config": { "openApiVersion": "3359e90fa19e8e250ab5a402b0f9dbe65bbe82a3" diff --git a/packages/cli/src/__tests__/command-descriptions.test.ts b/packages/cli/src/__tests__/command-descriptions.test.ts index 90e789f63c..1e19d5e70b 100644 --- a/packages/cli/src/__tests__/command-descriptions.test.ts +++ b/packages/cli/src/__tests__/command-descriptions.test.ts @@ -6,7 +6,7 @@ import { it, vi, } from "vite-plus/test"; -import { getCompletionDescription } from "../commands/completions/index.js"; +import { buildCli } from "../index.js"; import { captureOutput } from "./helpers/capture-output.js"; import { runCf } from "./helpers/run-cf.js"; import type { CommandMeta } from "../lib/metadata.js"; @@ -51,18 +51,11 @@ describe("generated command descriptions", () => { ); }); - it("uses summaries in completions with a legacy metadata fallback", () => { - expect(getCompletionDescription(zonesList as CommandMeta)).toBe( - "List Zones" + it("uses the parser summary in shell completions", async () => { + expect(await buildCli([]).cli.complete(["zones", "li"])).toContainEqual( + expect.objectContaining({ completion: "list", brief: "List Zones" }) ); - expect( - getCompletionDescription({ - description: "Full description", - } as CommandMeta) - ).toBe("Full description"); - expect(getCompletionDescription({} as CommandMeta)).toBe(""); }); - it("uses full descriptions in leaf help", async () => { await expect(runCf(["zones", "list", "--help"])).resolves.toEqual({ exitCode: 0, diff --git a/packages/cli/src/__tests__/commands/auth/profiles.test.ts b/packages/cli/src/__tests__/commands/auth/profiles.test.ts index b51c6aaa9e..7b4014d445 100644 --- a/packages/cli/src/__tests__/commands/auth/profiles.test.ts +++ b/packages/cli/src/__tests__/commands/auth/profiles.test.ts @@ -1,6 +1,9 @@ import { randomUUID } from "node:crypto"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; import { createCfProfileStore, + getAuthConfigFilePath, writeAuthConfigFile, } from "@cloudflare/workers-auth/cf"; import { runInTempDir } from "@cloudflare/workers-utils/test-helpers"; @@ -41,6 +44,63 @@ describe("cf auth profiles", () => { ); }); + it("completes local names without resolving a profile or exposing credentials", async () => { + createProfile("work"); + createProfile("personal"); + createProfile("default"); + vi.stubEnv("CLOUDFLARE_AUTH_PROFILE", "not a valid profile!"); + for (const words of [ + ["auth", "activate", "wo"], + ["auth", "delete", "wo"], + ["auth", "create", "wo"], + ["zones", "list", "--profile", "wo"], + ["--profile=wo"], + ]) { + expect(await runCf(["complete", "--", ...words])).toEqual({ + exitCode: 0, + }); + expect(std.getAndClearOut()).toBe("work\twork\n:4"); + expect(std.getAndClearErr()).toBe(""); + } + for (const words of [ + ["auth", "activate", "def"], + ["auth", "activate", "work", "wo"], + ["auth", "list", "--profile", "wo"], + ]) { + await runCf(["complete", "--", ...words]); + expect(std.getAndClearOut()).toBe(":4"); + } + await runCf(["complete", "--", "auth", "whoami", "--profile", "def"]); + expect(std.getAndClearOut()).toBe("default\tdefault\n:4"); + }); + + it("suggests safe encrypted profile filenames without opening the files", async () => { + const directory = dirname(getAuthConfigFilePath()); + mkdirSync(directory, { recursive: true }); + for (const file of [ + "work.enc", + "work.json", + "work space.json", + "staging.json", + ]) { + writeFileSync(join(directory, file), "not credential data"); + } + await runCf(["complete", "--", "auth", "activate", ""]); + expect(std.getAndClearOut()).toBe("work\twork\n:4"); + expect(std.getAndClearErr()).toBe(""); + }); + + it("returns no suggestions when the profile directory cannot be listed", async () => { + const directory = dirname(getAuthConfigFilePath()); + mkdirSync(dirname(directory), { recursive: true }); + writeFileSync(directory, "not a directory"); + expect(await runCf(["complete", "--", "auth", "activate", "wo"])).toEqual({ + exitCode: 0, + }); + expect(std.getAndClearOut()).toBe(":4"); + expect(std.getAndClearErr()).toBe(""); + }); + it("activates, lists, and deactivates a named profile", async () => { const cwd = process.cwd(); diff --git a/packages/cli/src/__tests__/commands/completions.test.ts b/packages/cli/src/__tests__/commands/completions.test.ts index 6418c35b5f..0a8d7c3ba6 100644 --- a/packages/cli/src/__tests__/commands/completions.test.ts +++ b/packages/cli/src/__tests__/commands/completions.test.ts @@ -1,69 +1,43 @@ -import { RootCommand } from "@bomb.sh/tab"; -import { afterEach, describe, expect, it, vi } from "vite-plus/test"; -import { registerCompletions } from "../../commands/completions/index.js"; -import type { CommandMeta } from "../../lib/metadata.js"; - -const TCP_META = { - command: "cf access tcp", - name: "tcp", - fullPath: ["access", "tcp"], - aliases: ["ssh", "rdp", "smb"], - description: "Proxy a TCP connection through Access", - usage: "cf access tcp [options]", - arguments: [], - options: [ - { - name: "log-level", - alias: ["loglevel", "log"], - type: "string", - required: false, - description: "cloudflared log level", - enum: ["debug", "info"], - }, - ], -} satisfies CommandMeta; - -function parseCompletions(root: RootCommand, args: string[]): string[] { - const lines: string[] = []; - vi.spyOn(console, "log").mockImplementation((line) => { - lines.push(String(line)); +import { describe, expect, it } from "vite-plus/test"; +import { buildCli } from "../../index.js"; +import { mockOutputStreams } from "../helpers/capture-output.js"; +import { runCf } from "../helpers/run-cf.js"; +const values = async (...words: string[]) => + (await buildCli([]).cli.complete(words)).map((entry) => entry.completion); +describe("parser-backed completions", () => { + const output = mockOutputStreams(); + it.each([ + ["bash", "complete -F __cf_complete cf"], + ["zsh", "compdef _cf cf"], + ["fish", "complete -c cf"], + ["powershell", "Register-ArgumentCompleter"], + ])("keeps the %s shell integration", async (shell, registration) => { + expect(await runCf(["complete", shell])).toEqual({ exitCode: 0 }); + expect(output.out).toContain(registration); }); - root.parse(args); - return lines; -} - -describe("metadata-backed completions", () => { - afterEach(() => { - vi.restoreAllMocks(); + it("writes shell candidates and the no-file-completion directive", async () => { + await runCf(["complete", "--", "zones", "list", "--direction", "d"]); + expect(output.out).toBe("desc\tdesc\n:4"); }); - - it("registers command aliases as sibling leaves", () => { - const root = new RootCommand(); - registerCompletions(root, [TCP_META]); - - expect(parseCompletions(root, ["access", "s"])).toEqual( - expect.arrayContaining([ - "ssh\tProxy a TCP connection through Access", - "smb\tProxy a TCP connection through Access", - ]) + it("follows routes, including command aliases", async () => { + expect(await values("access", "s")).toEqual( + expect.arrayContaining(["ssh", "smb"]) ); }); - - it("registers option aliases and their enum candidates on aliases", () => { - const root = new RootCommand(); - registerCompletions(root, [TCP_META]); - - expect(parseCompletions(root, ["access", "ssh", "--log"])).toEqual( - expect.arrayContaining([ - "--log-level\tcloudflared log level", - "--loglevel\tcloudflared log level", - "--log\tcloudflared log level", - ]) + it("suggests real flags on aliased routes", async () => { + expect((await values("access", "ssh", "--log")).sort()).toEqual( + ["--log-level", "--loglevel"].sort() ); - - vi.restoreAllMocks(); - expect(parseCompletions(root, ["access", "ssh", "--loglevel", ""])).toEqual( - expect.arrayContaining(["debug\tdebug", "info\tinfo"]) + }); + it("completes enum values in either shell spelling", async () => { + for (const words of [["--direction", "d"], ["--direction=d"]]) { + expect(await values("zones", "list", ...words)).toEqual(["desc"]); + } + }); + it("resolves global options before the route and excludes hidden flags", async () => { + expect(await values("--profile", "work", "zones", "li")).toContain("list"); + expect(await values("zones", "list", "--temp")).not.toContain( + "--temporary-account" ); }); }); diff --git a/packages/cli/src/__tests__/commands/hand-written-leaf-commands.test.ts b/packages/cli/src/__tests__/commands/hand-written-leaf-commands.test.ts index a3c718810d..5afabbbddc 100644 --- a/packages/cli/src/__tests__/commands/hand-written-leaf-commands.test.ts +++ b/packages/cli/src/__tests__/commands/hand-written-leaf-commands.test.ts @@ -34,7 +34,7 @@ describe("hand-written leaf commands", () => { "import $run from '#commands/ai/run/index.js';" ); expect(generated).not.toContain("import $run from './run.js';"); - expect(generated).toContain(".command($run)"); + expect(generated).toContain("'run': $run,"); }); it("registers a leaf command against its generated product", () => { @@ -254,12 +254,12 @@ describe("hand-written leaf commands", () => { ); expect(generated).toContain("describe: 'Manage Worker Previews'"); if (leaves.length > 0) { - expect(generated).toContain(".command($delete)"); + expect(generated).toContain("'delete': $delete,"); } else { - expect(generated).not.toContain(".command($delete)"); + expect(generated).not.toContain("'delete': $delete,"); } expect(generated).toContain( - ".command(withHandWrittenDryRun($deploy, 'preview'))" + "'deploy': withHandWrittenDryRun($deploy, 'preview')," ); }); @@ -315,16 +315,16 @@ describe("hand-written leaf commands", () => { expect(generated).toContain( "import $delete from '#commands/workers/delete/index.js';" ); - expect(generated).toContain(".command($delete)"); + expect(generated).toContain("'delete': $delete,"); expect(generated).toContain( - ".command(withHandWrittenDryRun($check, 'preview'))" + "'check': withHandWrittenDryRun($check, 'preview')," ); expect(generated).toContain( - ".command(withHandWrittenDryRun($types, 'preview'))" + "'types': withHandWrittenDryRun($types, 'preview')," ); expect( - generated.indexOf(".command(withHandWrittenDryRun($check, 'preview'))") - ).toBeLessThan(generated.indexOf(".command($versions)")); + generated.indexOf("'check': withHandWrittenDryRun($check, 'preview'),") + ).toBeLessThan(generated.indexOf("'versions': $versions,")); }); it("splices a nested leaf into its generated group index", () => { @@ -344,11 +344,11 @@ describe("hand-written leaf commands", () => { "import $create from '#commands/workers/versions/create/index.js';" ); expect(generated).toContain( - ".command(withHandWrittenDryRun($create, 'native'))" + "'create': withHandWrittenDryRun($create, 'native')," ); expect( - generated.indexOf(".command(withHandWrittenDryRun($create, 'native'))") - ).toBeLessThan(generated.indexOf(".command($delete)")); + generated.indexOf("'create': withHandWrittenDryRun($create, 'native'),") + ).toBeLessThan(generated.indexOf("'delete': $delete,")); }); it.each([ @@ -423,7 +423,7 @@ describe("nested hand-written image leaves", () => { ); expect(output).toContain("#commands/containers/images/list/index.js"); expect(output).toContain("#commands/containers/images/delete/index.js"); - expect(output).toContain(".command($prepare)"); + expect(output).toContain("'prepare': $prepare,"); expect(handWrittenLeafCommandModule("containers/images/list")).toBe( "#commands/containers/images/list/index.js" ); diff --git a/packages/cli/src/__tests__/generator/plugin/body-description.test.ts b/packages/cli/src/__tests__/generator/plugin/body-description.test.ts index e05c52e580..d0c1d4e7ab 100644 --- a/packages/cli/src/__tests__/generator/plugin/body-description.test.ts +++ b/packages/cli/src/__tests__/generator/plugin/body-description.test.ts @@ -1,9 +1,11 @@ import { stripTypeScriptTypes } from "node:module"; import { Script } from "node:vm"; import { describe, expect, it } from "vite-plus/test"; -import yargs, { type CommandModule } from "yargs"; import { generateFiles } from "../../helpers/cli-plugin.js"; +import { commandParser } from "../../helpers/command-parser.js"; import type { CommandMeta } from "../../../lib/command-meta.js"; +import type { CommandModule } from "yargs"; +import { apiCommand } from "#lib/api-command.js"; const JSON_BODY = "Raw JSON request body (bypasses individual flags)"; const PLAIN = "Send the workflow name as plain text, without JSON quotes."; @@ -40,8 +42,10 @@ async function bodyDescriptions(contentTypes: string[], description?: string) { const source = stripTypeScriptTypes(files.get("things/update.ts") ?? "") .replace(/^import[\s\S]*?;\n/gm, "") .replace("export default command;", "command;"); - const command = new Script(source).runInNewContext() as CommandModule; - const help = await yargs(["update"]).command(command).wrap(null).getHelp(); + const command = new Script(source).runInNewContext({ + apiCommand, + }) as CommandModule; + const help = await commandParser(["update"], command).getHelp(); return { metadata: bodyDescription, help }; } diff --git a/packages/cli/src/__tests__/generator/plugin/body-positionals.test.ts b/packages/cli/src/__tests__/generator/plugin/body-positionals.test.ts index 3993f32a8b..c53fadca4a 100644 --- a/packages/cli/src/__tests__/generator/plugin/body-positionals.test.ts +++ b/packages/cli/src/__tests__/generator/plugin/body-positionals.test.ts @@ -2,11 +2,13 @@ import { stripTypeScriptTypes } from "node:module"; import { Script } from "node:vm"; import { runInTempDir, seed } from "@cloudflare/workers-utils/test-helpers"; import { beforeAll, describe, expect, it, vi } from "vite-plus/test"; -import yargs, { type CommandModule } from "yargs"; import * as bodyParser from "../../../lib/body-parser.js"; import { resolveFileToken } from "../../../lib/input-validation.js"; import { generateFiles } from "../../helpers/cli-plugin.js"; +import { commandParser } from "../../helpers/command-parser.js"; import type { CommandMeta } from "../../../lib/command-meta.js"; +import type { CommandModule } from "yargs"; +import { apiCommand } from "#lib/api-command.js"; function setup(code: string) { const send = vi.fn(async () => undefined); @@ -14,10 +16,11 @@ function setup(code: string) { const formatDryRun = vi.fn(); const source = stripTypeScriptTypes( code - .slice(code.indexOf("function builder")) + .replace(/^import[\s\S]*?;\n/gm, "") .replace("export default command;", "command;") ); const command = new Script(source).runInNewContext({ + apiCommand, ...bodyParser, resolveFileToken, operation: {}, @@ -36,14 +39,7 @@ function setup(code: string) { createCommandClient, formatDryRun, run: async (args: string[]) => - yargs(["save", ...args]) - .exitProcess(false) - .command(command) - .strict() - .fail((message, error) => { - throw error ?? new Error(message); - }) - .parseAsync(), + commandParser(["save", ...args], command).parse(), }; } diff --git a/packages/cli/src/__tests__/generator/plugin/emit.test.ts b/packages/cli/src/__tests__/generator/plugin/emit.test.ts index 9c56bca21e..65a1399b43 100644 --- a/packages/cli/src/__tests__/generator/plugin/emit.test.ts +++ b/packages/cli/src/__tests__/generator/plugin/emit.test.ts @@ -1,8 +1,5 @@ -import { stripTypeScriptTypes } from "node:module"; -import { Script } from "node:vm"; import { describe, expect, it } from "vite-plus/test"; -import yargs, { type Argv } from "yargs"; -import { builderLines } from "../../../../generator/plugin/emit/builder.js"; +import { parameterSource } from "../../../../generator/plugin/emit/builder.js"; import { ACCOUNT_OR_ZONE_HELP, bodyObject, @@ -27,6 +24,10 @@ import { param, wire, } from "../../helpers/cli-plugin.js"; +import { + generatedParameters, + commandParser, +} from "../../helpers/command-parser.js"; import type { Arg, ArgType } from "../../../../generator/plugin/args.js"; import type { Method } from "../../../../generator/plugin/commands.js"; import type { OperationInfo } from "../../../../generator/plugin/operation.js"; @@ -169,10 +170,10 @@ describe("an API force parameter on a delete", () => { "things", op() ); - const builder = builderLines(ctx).join("\n"); - expect(builder).toContain('.option(\'force-delete\', {"type":"boolean"'); + const builder = parameterSource(ctx).join("\n"); + expect(builder).toContain('"force-delete": {"kind":"boolean"'); expect(builder).toContain( - '.option("force", {"type":"boolean","alias":"f","description":"Skip confirmation (useful in scripts and CI)","default":false})' + '"force": {"kind":"boolean","brief":"Skip confirmation (useful in scripts and CI)","alias":"f","default":false}' ); const code = handler(ctx).join("\n"); expect(code).toContain(`'force': argv["force-delete"]`); @@ -367,7 +368,7 @@ describe("variant prompts", () => { }); describe("optional joined query enums", () => { - it("leaves an omitted optional array unset", () => { + it("leaves an omitted optional array unset", async () => { const ctx = context( method("list", "example-list"), "example", @@ -382,10 +383,15 @@ describe("optional joined query enums", () => { wire: wire({ joined: ["selector"] }), }) ); - const parser = new Script( - stripTypeScriptTypes(`yargs${builderLines(ctx).join("\n")}`) - ).runInNewContext({ yargs: yargs([]).exitProcess(false) }) as Argv; - expect(parser.parseSync().selector).toBeUndefined(); + const params = generatedParameters(parameterSource(ctx)); + expect( + ( + await commandParser(["list"], { + ...params, + command: "list", + }).parse() + ).selector + ).toBeUndefined(); }); }); @@ -408,15 +414,14 @@ describe("file-backed enum arguments", () => { requestContentTypes: ["application/json"], }) ); - const builder = builderLines(ctx).join("\n"); + const builder = parameterSource(ctx).join("\n"); const body = bodyObject(ctx, "").join("\n"); expect(builder).toContain('"choices":["first","second"]'); expect(builder).toContain( - '.coerce("selection", (value) => resolveFileToken(value, "selection", "text"))' + 'coerce: (value: string) => resolveFileToken(value, "selection", "text")' ); - expect(builder).not.toContain('.coerce("sort"'); - expect(builder).not.toContain('.coerce("description"'); + expect(builder).not.toMatch(/"(?:sort|description)": \{[^\n]*coerce:/); expect(body).toContain('selection: argv["selection"]'); expect(body).toContain('resolveFileToken(argv["description"]'); }); @@ -452,18 +457,9 @@ describe("optional body-object validation", () => { requestContentTypes: ["application/json"], }) ); - const builder = new Script( - `(yargs) => yargs\n${builderLines(ctx).join("\n")}` - ).runInNewContext() as (args: Argv) => Argv; + const params = generatedParameters(parameterSource(ctx)); const parse = async (args: string[]) => - yargs(args) - .exitProcess(false) - .fail((message, error) => { - throw error ?? new Error(message); - }) - .command("create", "", builder, () => {}) - .strict() - .parseAsync(); + commandParser(args, { ...params, command: "create" }).parse(); await expect( parse(["create", "--parameters-order-by-order", "asc"]) @@ -556,19 +552,19 @@ describe("object-array bodies", () => { const ctx = context(createMethod, "tests", create(true)); expect(find(ctx.derived.args, "versions").type).toBe("objectArray"); expect(find(ctx.derived.args, "tags").type).toBe("array"); - const lines = builderLines(ctx); + const lines = parameterSource(ctx); const option = (name: string) => { - const line = lines.find((l) => l.startsWith(`.option('${name}'`)); + const line = lines.find((l) => l.startsWith(`"${name}": {`)); if (line === undefined) { throw new Error(`no --${name} in ${lines.join("\n")}`); } return line; }; - expect(option("versions")).toContain(`"type":"string"`); - expect(option("versions")).not.toContain(`"array":true`); - expect(option("versions")).not.toContain(`"demandOption":true`); - expect(option("tags")).toContain(`"type":"string"`); - expect(option("tags")).toContain(`"array":true`); + expect(option("versions")).toContain(`parse: String`); + expect(option("versions")).not.toContain(`"variadic":true`); + expect(option("versions")).toContain(`"optional":true`); + expect(option("tags")).toContain(`parse: String`); + expect(option("tags")).toContain(`"variadic":true`); }); it("parses the complete JSON value when assembling the body", () => { @@ -610,7 +606,7 @@ describe("Fern names", () => { const ctx = context(m, "example", op); return { handler: handler(ctx).join("\n"), - builder: builderLines(ctx).join("\n"), + builder: parameterSource(ctx).join("\n"), resolvedRequestPath: ctx.resolvedRequestPath, }; }; @@ -628,18 +624,12 @@ describe("Fern names", () => { "./" ); expect(command).toBe(required ? "get " : "get [consumer]"); - const builder = new Script( - `(yargs) => yargs\n${builderLines(ctx).join("\n")}` - ).runInNewContext() as (args: Argv) => Argv; + const params = generatedParameters(parameterSource(ctx)); const parse = async (args: string[]) => - yargs(args) - .exitProcess(false) - .fail((message, error) => { - throw error ?? new Error(message); - }) - .command(command, "", builder, () => {}) - .strict() - .parseAsync(); + commandParser(args, { + ...params, + command: command, + }).parse(); expect( await parse(["get", "consumer-1", "--queue", "queue-1"]) ).toMatchObject({ consumer: "consumer-1", queue: "queue-1" }); @@ -659,8 +649,8 @@ describe("Fern names", () => { ...renamedConsumerGet(), wire: wire({ hasRequest: true }), }); - expect(builder).toContain(".positional('consumer'"); - expect(builder).toContain(".option('queue'"); + expect(builder).toContain("placeholder: 'consumer'"); + expect(builder).toContain('"queue": {'); expect(builder).not.toContain("queue-id"); expect(builder).not.toContain("consumer-id"); @@ -733,8 +723,8 @@ describe("Fern names", () => { method("create", "example-without-sdk-entry"), op ); - expect(builder).toContain(".option('mtls-certificate-id'"); - expect(builder).toContain(".option('token'"); + expect(builder).toContain('"mtls-certificate-id": {'); + expect(builder).toContain('"token": {'); expect(builder).toContain(".conflicts('mtls-certificate-id', ['token'])"); expect(builder).toContain(".conflicts('token', ['mtls-certificate-id'])"); expect(h).toContain( diff --git a/packages/cli/src/__tests__/generator/plugin/forge-model.test.ts b/packages/cli/src/__tests__/generator/plugin/forge-model.test.ts index ce5d6ba3c0..298e82d8bb 100644 --- a/packages/cli/src/__tests__/generator/plugin/forge-model.test.ts +++ b/packages/cli/src/__tests__/generator/plugin/forge-model.test.ts @@ -4,6 +4,7 @@ */ import { describe, expect, it } from "vite-plus/test"; import { generateFiles } from "../../helpers/cli-plugin.js"; +import { generatedOptions } from "../../helpers/command-parser.js"; type Json = Record; @@ -160,9 +161,10 @@ describe("the forge model", () => { ); const code = files.get("uploads/create.ts") ?? ""; for (const field of ["files", "attachments"]) { - expect(code).toContain( - `.option('${field}', {"type":"string","array":true` - ); + expect(generatedOptions(code)[field]).toMatchObject({ + array: true, + type: "string", + }); expect(code).toContain(`for (const value of argv["${field}"])`); } expect(code).toContain( @@ -195,10 +197,10 @@ describe("the forge model", () => { ) ); const code = files.get("things/create.ts") ?? ""; - expect(code).toContain('.option(\'id\', {"type":"string"'); - expect(code).toContain('.option(\'parent-id\', {"type":"string"'); - expect(code).toContain( - '.option(\'dataset-ids\', {"type":"string","array":true' + expect(code).toContain('"id": {"kind":"parsed"'); + expect(code).toContain('"parent-id": {"kind":"parsed"'); + expect(code).toMatch( + /"dataset-ids": \{[^}]*"variadic":true[^}]*parse: String/ ); expect(code).toContain("promptForRequiredField('id'"); expect(code).toContain('id: resolveFileToken(argv["id"]'); @@ -227,9 +229,7 @@ describe("the forge model", () => { const files = generateFiles(listing(schema)); const schemas = JSON.parse(files.get("_meta/schemas.json") ?? "{}"); expect(schemas.schemas["things list"].queryParams[0].type).toBe("string"); - expect(files.get("things/list.ts")).toContain( - '.option(\'status\', {"type":"string"' - ); + expect(files.get("things/list.ts")).toContain('"status": {"kind":"parsed"'); }); it("retains required and optional scalar intersections and their enum constraints", () => { @@ -263,7 +263,7 @@ describe("the forge model", () => { ); const files = generateFiles(d); const code = files.get("things/create.ts") ?? ""; - expect(code).toContain(".option('vendor'"); + expect(code).toContain('"vendor": {'); expect(code).toContain('"choices":["GITHUB","SLACK"]'); expect(code).toContain('"choices":["High","Low"]'); expect(code).toContain("promptForRequiredEnumField('vendor'"); @@ -324,7 +324,7 @@ describe("the forge model", () => { ) ); const code = files.get("things/create.ts") ?? ""; - expect(code).toContain(".option('fallback'"); + expect(code).toContain('"fallback": {'); expect(code).toContain("parseScalarValue"); expect(code).toContain( 'fallback: parseScalarValue(argv["fallback"], "fallback")' @@ -419,14 +419,15 @@ describe("the forge model", () => { "things/create.ts" ); expect(code).toContain( - `.option('display-name', {"type":"string","description":"The name."})` + `"display-name": {"kind":"parsed","brief":"The name."` ); // A nullable integer is still a number. - expect(code).toContain(`.option('ttl-seconds', {"type":"number"`); - expect(code).toContain(".option('secret-token'"); + const options = generatedOptions(code); + expect(options["ttl-seconds"]).toMatchObject({ type: "number" }); + expect(code).toContain('"secret-token": {'); expect(code).toContain(`sensitiveBodyPaths: [["token_value"]]`); expect(code).not.toContain("'id'"); - expect(code).toContain(`"choices":["a","b"],"default":"a"`); + expect(options.kind).toMatchObject({ choices: ["a", "b"], default: "a" }); expect(code).toContain("promptForRequiredField('display-name'"); }); @@ -714,7 +715,7 @@ describe("the forge model", () => { }), "things/get.ts" ); - expect(code).toContain(".positional('thing'"); + expect(code).toContain("placeholder: 'thing'"); expect(code).toContain(`requestApi(client, "GET"`); expect(code).not.toContain("const operation"); }); @@ -1028,11 +1029,11 @@ describe("the forge model", () => { "tunnels/create.ts" ); expect(code).toContain( - `.option('config-source', {"type":"string","description":"Where the tunnel is configured.",` + `"config-source": {"kind":"parsed","brief":"Where the tunnel is configured.",` ); // A field's own description wins. expect(code).toContain( - `.option('name', {"type":"string","description":"Its own description.",` + `"name": {"kind":"parsed","brief":"Its own description.",` ); }); @@ -1060,7 +1061,7 @@ describe("the forge model", () => { "things/list.ts" ); expect(code).toContain( - `.option('jurisdiction', {"type":"string","description":"The cf-r2-jurisdiction header"})` + `"jurisdiction": {"kind":"parsed","brief":"The cf-r2-jurisdiction header"` ); expect(code).toContain( `headers['cf-r2-jurisdiction'] = String(argv["jurisdiction"])` @@ -1145,14 +1146,12 @@ describe("the forge model", () => { "things/list.ts" ); expect(code).toMatch( - /\.option\('cf-storage-class', \{[^}]*"description":"Storage class for new objects\."/ - ); - expect(code).toMatch( - /\.option\('class', \{[^}]*"description":"Storage class for new objects\."/ + /"cf-storage-class": \{[^}]*"brief":"Storage class for new objects\."/ ); expect(code).toMatch( - /\.option\('described', \{[^}]*"description":"Its own\."/ + /"class": \{[^}]*"brief":"Storage class for new objects\."/ ); + expect(code).toMatch(/"described": \{[^}]*"brief":"Its own\."/); }); it("leaves the members of an anyOf to the body", () => { @@ -1174,7 +1173,7 @@ describe("the forge model", () => { expect(code).not.toContain("'tags'"); expect(code).not.toContain("'hosts'"); expect(code).not.toContain(".conflicts("); - expect(code).toContain(".option('body'"); + expect(code).toContain('"body": {'); }); it("still sends an object body without properties", () => { @@ -1182,7 +1181,7 @@ describe("the forge model", () => { create({ type: "object", required: ["id"] }), "things/create.ts" ); - expect(code).toContain(".option('body'"); + expect(code).toContain('"body": {'); }); it("describes a body by its schema, never its title", () => { @@ -1195,7 +1194,7 @@ describe("the forge model", () => { }), "things/create.ts" ) - ).toContain("description: 'Some names.',"); + ).toContain('"brief":"Some names."'); const code = file( create( @@ -1211,7 +1210,7 @@ describe("the forge model", () => { "things/create.ts" ); expect(code).toContain( - "description: 'Raw JSON request body (bypasses individual flags)'," + '"brief":"Raw JSON request body (bypasses individual flags)"' ); expect(code).not.toContain("Thing Input"); }); @@ -1237,7 +1236,7 @@ describe("the forge model", () => { anyOf: [values, { type: "array", items: values }], }); expect(file(anyOf, "things/list.ts")).toContain( - `"choices":["running","done"]` + `"values":["running","done"]` ); expect(queryType(anyOf)).toBe("string"); }); @@ -1306,7 +1305,7 @@ describe("the forge model", () => { }), "things/create.ts" ); - expect(code).toContain(".option('filters'"); + expect(code).toContain('"filters": {'); }); it("publishes an object array as one string option in command metadata", () => { diff --git a/packages/cli/src/__tests__/generator/plugin/hand-written-roots.test.ts b/packages/cli/src/__tests__/generator/plugin/hand-written-roots.test.ts index d884c189dc..24e7dae43f 100644 --- a/packages/cli/src/__tests__/generator/plugin/hand-written-roots.test.ts +++ b/packages/cli/src/__tests__/generator/plugin/hand-written-roots.test.ts @@ -88,9 +88,9 @@ describe("created roots", () => { previews() ); const index = read(files, "previews/index.ts"); - expect(index).toContain(".command($delete)"); + expect(index).toContain("'delete': $delete,"); expect(index).toContain( - ".command(withHandWrittenDryRun($deploy, 'preview'))" + "'deploy': withHandWrittenDryRun($deploy, 'preview')," ); const root = read(files, "index.ts"); expect(root.match(/lazyCommand\('previews'/g)).toEqual([ diff --git a/packages/cli/src/__tests__/generator/plugin/json-shape.test.ts b/packages/cli/src/__tests__/generator/plugin/json-shape.test.ts index 96d0712941..c3d09ffe50 100644 --- a/packages/cli/src/__tests__/generator/plugin/json-shape.test.ts +++ b/packages/cli/src/__tests__/generator/plugin/json-shape.test.ts @@ -1,11 +1,13 @@ import { stripTypeScriptTypes } from "node:module"; import { Script } from "node:vm"; import { describe, expect, it } from "vite-plus/test"; -import yargs, { type CommandModule } from "yargs"; import { jsonShape } from "../../../../generator/plugin/json-shape.js"; import { generateFiles } from "../../helpers/cli-plugin.js"; +import { commandParser } from "../../helpers/command-parser.js"; import type { CommandMeta } from "../../../lib/command-meta.js"; import type { ObjectType, Type } from "@cloudflare/forge/plugin"; +import type { CommandModule } from "yargs"; +import { apiCommand } from "#lib/api-command.js"; describe("JSON parameter shapes", () => { const files = generateFiles({ @@ -122,7 +124,9 @@ describe("JSON parameter shapes", () => { const source = stripTypeScriptTypes(files.get("things/create.ts") ?? "") .replace(/^import[\s\S]*?;\n/gm, "") .replace("export default command;", "command;"); - const command = new Script(source).runInNewContext() as CommandModule; + const command = new Script(source).runInNewContext({ + apiCommand, + }) as CommandModule; it("shows the same first-level wire shape in help, command metadata, and cf schema", async () => { const description = @@ -141,7 +145,7 @@ describe("JSON parameter shapes", () => { (field) => field.name === "actions" )?.description ).toBe(description); - const help = await yargs(["create"]).command(command).wrap(null).getHelp(); + const help = await commandParser(["create"], command).getHelp(); expect(help).toContain(description); }); diff --git a/packages/cli/src/__tests__/generator/plugin/metadata-defaults.test.ts b/packages/cli/src/__tests__/generator/plugin/metadata-defaults.test.ts index d0669d4c88..887f8e980a 100644 --- a/packages/cli/src/__tests__/generator/plugin/metadata-defaults.test.ts +++ b/packages/cli/src/__tests__/generator/plugin/metadata-defaults.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; import { generateFiles } from "../../helpers/cli-plugin.js"; +import { generatedOptions } from "../../helpers/command-parser.js"; import type { CommandMeta } from "../../../lib/command-meta.js"; type Json = Record; @@ -48,12 +49,11 @@ function expectDefault( value: unknown ) { const metadata = generated.command.options.find((o) => o.name === flag); - const match = generated.code.match( - new RegExp(`\\.option\\('${flag}', (\\{[^\\n]*\\})\\)`) - ); + const builder = generatedOptions(generated.code)[flag]; expect(metadata, `metadata for --${flag}`).toBeDefined(); - expect(match, `builder for --${flag}`).not.toBeNull(); - const builder = JSON.parse(match?.[1] ?? "") as Json; + if (!builder) { + throw new Error(`missing flag: ${flag}`); + } for (const option of [metadata, builder]) { if (value === undefined) { expect(option).not.toHaveProperty("default"); diff --git a/packages/cli/src/__tests__/generator/plugin/metadata-force.test.ts b/packages/cli/src/__tests__/generator/plugin/metadata-force.test.ts index 98cb69d30a..792591ed18 100644 --- a/packages/cli/src/__tests__/generator/plugin/metadata-force.test.ts +++ b/packages/cli/src/__tests__/generator/plugin/metadata-force.test.ts @@ -32,10 +32,11 @@ function generate(httpMethod: string, requireConfirmation?: string) { }; const meta = metadata.commands.find((c) => c.command === "cf things update"); const code = files.get("things/update.ts"); - if (meta === undefined || code === undefined) { + const handler = files.get("things/update.handler.ts"); + if (meta === undefined || code === undefined || handler === undefined) { throw new Error("Missing generated things update command"); } - return { meta, code }; + return { meta, code, handler }; } describe("command metadata force option", () => { @@ -47,7 +48,7 @@ describe("command metadata force option", () => { ])( "matches the runtime option for %s with confirmation %s", (verb, message) => { - const { meta, code } = generate(verb, message); + const { meta, code, handler } = generate(verb, message); expect(meta.options.filter((option) => option.name === "force")).toEqual([ { name: "force", @@ -59,32 +60,32 @@ describe("command metadata force option", () => { }, ]); expect(code).toContain( - '.option("force", {"type":"boolean","alias":"f","description":"Skip confirmation (useful in scripts and CI)","default":false})' + '"force": {"kind":"boolean","brief":"Skip confirmation (useful in scripts and CI)","alias":"f","default":false}' ); - expect(code).toContain("confirmDelete({ force: Boolean(argv.force)"); - expect(code).toContain("shortFlagAliases: { f:"); - expect(code).toContain("safeFlags: ['dry-run', 'force']"); + expect(handler).toContain("confirmDelete({ force: Boolean(argv.force)"); + expect(handler).toContain("shortFlagAliases: { f:"); + expect(handler).toContain("safeFlags: ['dry-run', 'force']"); } ); it.each(["get", "post", "put", "patch"])( "omits force from metadata and runtime for an ordinary %s operation", (verb) => { - const { meta, code } = generate(verb); + const { meta, code, handler } = generate(verb); expect(meta.options.some((option) => option.name === "force")).toBe( false ); - expect(code).not.toContain('.option("force"'); - expect(code).not.toContain("confirmDelete"); - expect(code).not.toContain("shortFlagAliases"); + expect(code).not.toContain('"force": {'); + expect(handler).not.toContain("confirmDelete"); + expect(handler).not.toContain("shortFlagAliases"); } ); it("ignores an empty confirmation annotation consistently", () => { - const { meta, code } = generate("put", ""); + const { meta, code, handler } = generate("put", ""); expect(meta.options.some((option) => option.name === "force")).toBe(false); - expect(code).not.toContain('.option("force"'); - expect(code).not.toContain("confirmDelete"); - expect(code).not.toContain("shortFlagAliases"); + expect(code).not.toContain('"force": {'); + expect(handler).not.toContain("confirmDelete"); + expect(handler).not.toContain("shortFlagAliases"); }); }); diff --git a/packages/cli/src/__tests__/generator/plugin/metadata-multipart.test.ts b/packages/cli/src/__tests__/generator/plugin/metadata-multipart.test.ts index 4110507b78..98d02d8204 100644 --- a/packages/cli/src/__tests__/generator/plugin/metadata-multipart.test.ts +++ b/packages/cli/src/__tests__/generator/plugin/metadata-multipart.test.ts @@ -5,6 +5,7 @@ import { } from "../../../../generator/plugin/files.js"; import { HandWritten } from "../../../../generator/plugin/hand-written.js"; import { bodyParam, method, operation } from "../../helpers/cli-plugin.js"; +import { generatedOptions } from "../../helpers/command-parser.js"; import type { Command } from "../../../../generator/plugin/commands.js"; import type { MultipartField } from "../../../../generator/plugin/operation.js"; import type { CommandMeta } from "../../../lib/command-meta.js"; @@ -73,11 +74,9 @@ function generate() { describe("command metadata multipart form options", () => { it("lists the same flags as the runtime builder", () => { const { meta, code } = generate(); - const runtime = [ - ...code.matchAll( - /\.option\(['"]([^'"]+)['"], \{\s*(?:"type":"|type: ')(\w+)/g - ), - ].map(([, name, type]) => ({ name, type })); + const runtime = Object.entries(generatedOptions(code)).map( + ([name, { type }]) => ({ name, type }) + ); expect(meta.options.map(({ name, type }) => ({ name, type }))).toEqual( runtime ); diff --git a/packages/cli/src/__tests__/generator/plugin/metadata-text.test.ts b/packages/cli/src/__tests__/generator/plugin/metadata-text.test.ts index 27baa7ce37..d15ea361ab 100644 --- a/packages/cli/src/__tests__/generator/plugin/metadata-text.test.ts +++ b/packages/cli/src/__tests__/generator/plugin/metadata-text.test.ts @@ -5,6 +5,7 @@ import { } from "../../../../generator/plugin/files.js"; import { HandWritten } from "../../../../generator/plugin/hand-written.js"; import { method, operation } from "../../helpers/cli-plugin.js"; +import { generatedOptions } from "../../helpers/command-parser.js"; import type { Command } from "../../../../generator/plugin/commands.js"; import type { CommandMeta } from "../../../lib/command-meta.js"; @@ -50,9 +51,7 @@ describe("command metadata text option", () => { "matches the runtime option for %s responses", (contentType) => { const { meta, code } = generate(contentType); - const match = code.match(/\.option\("text", (\{[^\n]*\})\)/); - expect(match).not.toBeNull(); - const runtime = JSON.parse(match?.[1] ?? "") as Record; + const runtime = generatedOptions(code).text; expect(runtime).toMatchObject({ type: "boolean", default: false }); expect(meta.options.filter((option) => option.name === "text")).toEqual([ { name: "text", required: false, ...runtime }, @@ -69,7 +68,7 @@ describe("command metadata text option", () => { (contentType, status) => { const { meta, code } = generate(contentType, status); expect(meta.options.some((option) => option.name === "text")).toBe(false); - expect(code).not.toContain('.option("text"'); + expect(code).not.toContain('"text": {'); } ); }); diff --git a/packages/cli/src/__tests__/generator/plugin/multipart-files.test.ts b/packages/cli/src/__tests__/generator/plugin/multipart-files.test.ts index a9554baa80..e08c6074ae 100644 --- a/packages/cli/src/__tests__/generator/plugin/multipart-files.test.ts +++ b/packages/cli/src/__tests__/generator/plugin/multipart-files.test.ts @@ -2,7 +2,7 @@ import { stripTypeScriptTypes } from "node:module"; import { Script } from "node:vm"; import { describe, expect, it, vi } from "vite-plus/test"; import { derive } from "../../../../generator/plugin/args.js"; -import { builderLines } from "../../../../generator/plugin/emit/builder.js"; +import { parameterSource } from "../../../../generator/plugin/emit/builder.js"; import { dryRun, handler } from "../../../../generator/plugin/emit/handler.js"; import { bodyParam, @@ -244,7 +244,7 @@ describe("multipart field flag names", () => { "example", op ); - expect(builderLines(ctx).join("\n")).toContain(".option('form-label', {"); + expect(parameterSource(ctx).join("\n")).toContain('"form-label": {'); const code = handler(ctx).join("\n"); expect(code).toContain( "if (argv[\"form-label\"] !== undefined) formData.append('label'" @@ -261,8 +261,8 @@ describe("multipart field flag names", () => { "example", op ); - const builder = builderLines(ctx).join("\n"); - expect(builder.match(/\.option\('display-label'/g)).toHaveLength(1); + const builder = parameterSource(ctx).join("\n"); + expect(builder.match(/"display-label": \{/g)).toHaveLength(1); expect(builder).not.toContain("'label'"); expect(handler(ctx).join("\n")).toContain( "if (argv[\"display-label\"] !== undefined) formData.append('label'" diff --git a/packages/cli/src/__tests__/generator/plugin/nested-array-flags.test.ts b/packages/cli/src/__tests__/generator/plugin/nested-array-flags.test.ts index 64f61fa50d..e00dcd9585 100644 --- a/packages/cli/src/__tests__/generator/plugin/nested-array-flags.test.ts +++ b/packages/cli/src/__tests__/generator/plugin/nested-array-flags.test.ts @@ -2,7 +2,6 @@ import { stripTypeScriptTypes } from "node:module"; import { Script } from "node:vm"; import { runInTempDir, seed } from "@cloudflare/workers-utils/test-helpers"; import { describe, expect, it, vi } from "vite-plus/test"; -import yargs, { type CommandModule } from "yargs"; import { compactBody, parseBody, @@ -12,7 +11,10 @@ import { } from "../../../lib/body-parser.js"; import { resolveFileToken } from "../../../lib/input-validation.js"; import { generateFiles } from "../../helpers/cli-plugin.js"; +import { commandParser } from "../../helpers/command-parser.js"; import type { CommandMeta } from "../../../lib/command-meta.js"; +import type { CommandModule } from "yargs"; +import { apiCommand } from "#lib/api-command.js"; function generate(typed: boolean) { const schema = { @@ -117,6 +119,7 @@ describe.each([true, false])( const requestApi = vi.fn(async () => undefined); const formatDryRun = vi.fn(); const command = new Script(source).runInNewContext({ + apiCommand, compactBody, parseBody, parseNestedArray, @@ -137,14 +140,7 @@ describe.each([true, false])( ) => run(), }) as CommandModule; const parse = async (flags: string[]) => - yargs([method, "--name", "thing", ...flags]) - .exitProcess(false) - .command(command) - .strict() - .fail((message, error) => { - throw error ?? new Error(message); - }) - .parseAsync(); + commandParser([method, "--name", "thing", ...flags], command).parse(); return { parse, send, requestApi, formatDryRun }; }; diff --git a/packages/cli/src/__tests__/generator/plugin/nested-body-overrides.test.ts b/packages/cli/src/__tests__/generator/plugin/nested-body-overrides.test.ts index ce15449bfb..44b36acf1f 100644 --- a/packages/cli/src/__tests__/generator/plugin/nested-body-overrides.test.ts +++ b/packages/cli/src/__tests__/generator/plugin/nested-body-overrides.test.ts @@ -2,7 +2,6 @@ import { stripTypeScriptTypes } from "node:module"; import { Script } from "node:vm"; import { runInTempDir, seed } from "@cloudflare/workers-utils/test-helpers"; import { describe, expect, it, vi } from "vite-plus/test"; -import yargs, { type CommandModule } from "yargs"; import { derive } from "../../../../generator/plugin/args.js"; import { compactBody, parseBody } from "../../../lib/body-parser.js"; import { resolveFileToken } from "../../../lib/input-validation.js"; @@ -13,8 +12,11 @@ import { method, operation, } from "../../helpers/cli-plugin.js"; +import { commandParser } from "../../helpers/command-parser.js"; import type { Method } from "../../../../generator/plugin/commands.js"; import type { CommandMeta } from "../../../lib/command-meta.js"; +import type { CommandModule } from "yargs"; +import { apiCommand } from "#lib/api-command.js"; describe("exact body-field overrides", () => { const op = operation("post", "/things", { @@ -216,6 +218,7 @@ describe("emitted nested overrides and metadata", () => { .replace("export default command;", "command;"); const formatDryRun = vi.fn(); const command = new Script(source).runInNewContext({ + apiCommand, compactBody, parseBody, resolveFileToken, @@ -227,14 +230,7 @@ describe("emitted nested overrides and metadata", () => { ) => run(), }) as CommandModule; const parse = async (flags: string[]) => - yargs(["create", "--dry-run", ...flags]) - .exitProcess(false) - .command(command) - .strict() - .fail((message, error) => { - throw error ?? new Error(message); - }) - .parseAsync(); + commandParser(["create", "--dry-run", ...flags], command).parse(); for (const [flag, value] of [ ["settings-label", "child"], ["settings-sibling", "sibling"], diff --git a/packages/cli/src/__tests__/generator/plugin/nested-unions.test.ts b/packages/cli/src/__tests__/generator/plugin/nested-unions.test.ts index 252460025f..53e4452091 100644 --- a/packages/cli/src/__tests__/generator/plugin/nested-unions.test.ts +++ b/packages/cli/src/__tests__/generator/plugin/nested-unions.test.ts @@ -1,7 +1,6 @@ import { stripTypeScriptTypes } from "node:module"; import { Script } from "node:vm"; import { beforeAll, describe, expect, it, vi } from "vite-plus/test"; -import yargs, { type CommandModule } from "yargs"; import { compactBody, parseBody, @@ -10,6 +9,9 @@ import { import { validateBodyUnions } from "../../../lib/body-unions.js"; import { resolveFileToken } from "../../../lib/input-validation.js"; import { generateFiles } from "../../helpers/cli-plugin.js"; +import { commandParser } from "../../helpers/command-parser.js"; +import type { CommandModule } from "yargs"; +import { apiCommand } from "#lib/api-command.js"; type Json = Record; const id = "b07a1f7c-1b34-4fba-9c57-f8033b913973"; @@ -83,10 +85,11 @@ function command(code: string) { const preview = vi.fn((_detail: { body: unknown }) => {}); const source = stripTypeScriptTypes( code - .slice(code.indexOf("function builder")) + .replace(/^import[\s\S]*?;\n/gm, "") .replace("export default command;", "command;") ); const module = new Script(source).runInNewContext({ + apiCommand, compactBody, parseBody, setNestedValue, @@ -113,15 +116,7 @@ function command(code: string) { return { send, preview, - run: async (argv: string[]) => - yargs(argv) - .exitProcess(false) - .command(module) - .strict() - .fail((message, error) => { - throw error ?? new Error(message); - }) - .parseAsync(), + run: async (argv: string[]) => commandParser(argv, module).parse(), }; } @@ -261,7 +256,7 @@ describe("read-only request properties", () => { }); const code = files.get("things/create.ts") ?? ""; expect(code).not.toContain("server_top"); - expect(code).not.toContain(".option('settings-scope-server-id'"); + expect(code).not.toContain('"settings-scope-server-id": {'); const start = code.indexOf("const bodyUnions:"); const definition = code.slice(start, code.indexOf(";\n", start) + 1); const constraints = new Script( @@ -309,7 +304,7 @@ describe("read-only request properties", () => { }); const code = files.get("things/create.ts") ?? ""; expect(code).not.toContain("validateBodyUnions"); - expect(code).not.toContain(".option('settings-scope-kind'"); + expect(code).not.toContain('"settings-scope-kind": {'); const c = command(code); await c.run([ "create", diff --git a/packages/cli/src/__tests__/generator/plugin/normalization.test.ts b/packages/cli/src/__tests__/generator/plugin/normalization.test.ts index b88ebd66a8..63b2f9978d 100644 --- a/packages/cli/src/__tests__/generator/plugin/normalization.test.ts +++ b/packages/cli/src/__tests__/generator/plugin/normalization.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; import { generateFiles } from "../../helpers/cli-plugin.js"; +import { generatedOptions } from "../../helpers/command-parser.js"; import type { CommandMeta } from "../../../lib/command-meta.js"; describe("Forge metadata normalization", () => { @@ -79,10 +80,7 @@ describe("Forge metadata normalization", () => { (entry) => entry.command === "cf things create" ); const code = files.get("things/create.ts") ?? ""; - const builderNames = Array.from( - code.matchAll(/\.option\(['"]([^'"]+)['"],/g), - (match) => match[1] - ); + const builderNames = Object.keys(generatedOptions(code)); expect(command?.options.map((option) => option.name)).toEqual(builderNames); expect(builderNames).toEqual( diff --git a/packages/cli/src/__tests__/generator/plugin/oneof-body-flags.test.ts b/packages/cli/src/__tests__/generator/plugin/oneof-body-flags.test.ts index 6f8856e565..3d093ab721 100644 --- a/packages/cli/src/__tests__/generator/plugin/oneof-body-flags.test.ts +++ b/packages/cli/src/__tests__/generator/plugin/oneof-body-flags.test.ts @@ -1,7 +1,6 @@ import { stripTypeScriptTypes } from "node:module"; import { Script } from "node:vm"; import { describe, expect, it, vi } from "vite-plus/test"; -import yargs, { type CommandModule } from "yargs"; import { compactBody, parseBody, @@ -9,6 +8,9 @@ import { } from "../../../lib/body-parser.js"; import { resolveFileToken } from "../../../lib/input-validation.js"; import { generateFiles } from "../../helpers/cli-plugin.js"; +import { commandParser } from "../../helpers/command-parser.js"; +import type { CommandModule } from "yargs"; +import { apiCommand } from "#lib/api-command.js"; const network = { type: "object", @@ -114,6 +116,7 @@ function setup(code: string, initialFlags: string[] = []) { const requestBody = vi.fn(); const formatDryRun = vi.fn(); const command = new Script(source).runInNewContext({ + apiCommand, compactBody, parseBody, setNestedValue, @@ -139,15 +142,7 @@ function setup(code: string, initialFlags: string[] = []) { ) => run(), }) as CommandModule; const parse = async (flags: string[]) => - yargs(["create", ...initialFlags, ...flags]) - .locale("en") - .exitProcess(false) - .command(command) - .strict() - .fail((message, error) => { - throw error ?? new Error(message); - }) - .parseAsync(); + commandParser(["create", ...initialFlags, ...flags], command).parse(); return { parse, requestBody, formatDryRun }; } diff --git a/packages/cli/src/__tests__/generator/plugin/path-parameter-overrides.test.ts b/packages/cli/src/__tests__/generator/plugin/path-parameter-overrides.test.ts index 2c84d5b71c..2061a423d6 100644 --- a/packages/cli/src/__tests__/generator/plugin/path-parameter-overrides.test.ts +++ b/packages/cli/src/__tests__/generator/plugin/path-parameter-overrides.test.ts @@ -1,5 +1,6 @@ import { beforeAll, describe, expect, it } from "vite-plus/test"; import { generateFiles } from "../../helpers/cli-plugin.js"; +import { generatedOptions } from "../../helpers/command-parser.js"; import type { CommandMeta } from "../../../lib/metadata.js"; const spec = { @@ -74,19 +75,13 @@ describe("path parameter overrides in generated commands", () => { it("registers a defaulted namespace flag beside the sole instance positional", () => { const code = read("ai-search/create.ts"); - const namespaceLine = code - .split("\n") - .map((line) => line.trim()) - .find((line) => line.startsWith(".option('namespace',")); - expect(namespaceLine).toBeDefined(); - const json = namespaceLine?.slice(".option('namespace', ".length, -1) ?? ""; - expect(JSON.parse(json)).toEqual({ + expect(generatedOptions(code).namespace).toEqual({ type: "string", description: "Name", default: "default", }); expect(code).toContain("command: 'create '"); - expect(code).not.toContain(".positional('namespace'"); + expect(code).not.toContain("placeholder: 'namespace'"); }); it("keeps the default and positional placement consistent with metadata, requests, and previews", () => { diff --git a/packages/cli/src/__tests__/generator/plugin/query-array-flags.test.ts b/packages/cli/src/__tests__/generator/plugin/query-array-flags.test.ts index bb49c92793..c3451aef9f 100644 --- a/packages/cli/src/__tests__/generator/plugin/query-array-flags.test.ts +++ b/packages/cli/src/__tests__/generator/plugin/query-array-flags.test.ts @@ -1,11 +1,13 @@ import { stripTypeScriptTypes } from "node:module"; import { Script } from "node:vm"; import { describe, expect, it } from "vite-plus/test"; -import yargs, { type CommandModule } from "yargs"; import { Client, type Operation } from "../../../api/client.js"; import { path } from "../../../api/path.js"; import { generateFiles } from "../../helpers/cli-plugin.js"; +import { commandParser } from "../../helpers/command-parser.js"; import type { CommandsMetadata } from "../../../lib/command-meta.js"; +import type { CommandModule } from "yargs"; +import { apiCommand } from "#lib/api-command.js"; const enumValues = ["001", "a/b &c", "literal,comma"]; const enumSchema = { type: "string", enum: enumValues }; @@ -111,6 +113,7 @@ describe.each( }, }); const command = new Script(source).runInNewContext({ + apiCommand, operation, createCommandClient: async () => client, formatOutput: () => {}, @@ -122,19 +125,14 @@ describe.each( task: () => Promise ) => task(), }) as CommandModule; - const argv = await yargs(["list", ...flags]) - .exitProcess(false) - .command(command) - .strict() - .fail((message, error) => { - throw error ?? new Error(message); - }) - .parseAsync(); + const argv = await commandParser(["list", ...flags], command).parse(); return { argv, urls }; } it("preserves the array type and publishes item choices", () => { - expect(source).toContain('"type":"string","array":true'); + expect(source).toMatch( + /"indicator-ids": \{[^}]*"variadic":true[^}]*parse: String/ + ); if (choices === undefined) { expect(source).not.toContain('"choices"'); } else { @@ -149,9 +147,9 @@ describe.each( expect(option).toMatchObject({ type: "string", required: true }); expect(option?.enum).toEqual(choices); if (choices !== undefined) { - expect(source).toContain('.coerce("indicator-ids"'); + expect(source).toContain("coerce: (values"); } else { - expect(source).not.toContain(".coerce("); + expect(source).not.toContain("coerce:"); } }); diff --git a/packages/cli/src/__tests__/generator/plugin/required-raw-bodies.test.ts b/packages/cli/src/__tests__/generator/plugin/required-raw-bodies.test.ts index f29268858b..29d52fd4bf 100644 --- a/packages/cli/src/__tests__/generator/plugin/required-raw-bodies.test.ts +++ b/packages/cli/src/__tests__/generator/plugin/required-raw-bodies.test.ts @@ -2,12 +2,14 @@ import { stripTypeScriptTypes } from "node:module"; import { Script } from "node:vm"; import { runInTempDir, seed } from "@cloudflare/workers-utils/test-helpers"; import { describe, expect, it, vi } from "vite-plus/test"; -import yargs, { type CommandModule } from "yargs"; import { readFileForFlag, resolveFileToken, } from "../../../lib/input-validation.js"; import { generateFiles } from "../../helpers/cli-plugin.js"; +import { commandParser } from "../../helpers/command-parser.js"; +import type { CommandModule } from "yargs"; +import { apiCommand } from "#lib/api-command.js"; function setup(files: Map, name = "update") { const source = stripTypeScriptTypes(files.get(`things/${name}.ts`) ?? "") @@ -27,6 +29,7 @@ function setup(files: Map, name = "update") { const formatOutput = vi.fn(); const formatDryRun = vi.fn(); const command = new Script(source).runInNewContext({ + apiCommand, Blob, FormData, operation: {}, @@ -47,14 +50,7 @@ function setup(files: Map, name = "update") { ) => task(), }) as CommandModule; const run = (flags: string[] = []) => - yargs([name, ...flags]) - .exitProcess(false) - .command(command) - .strict() - .fail((message, error) => { - throw error ?? new Error(message); - }) - .parseAsync(); + commandParser([name, ...flags], command).parse(); return { run, client, @@ -340,7 +336,7 @@ describe("multipart bodies", () => { ); const code = files.get("things/update.ts") ?? ""; for (const field of Object.keys(readOnlyFields)) { - expect(code).not.toContain(`.option('${field}',`); + expect(code).not.toContain(`"${field}": {`); expect(code).not.toContain(`formData.append('${field}',`); } await seed({ "payload.txt": "writable content" }); diff --git a/packages/cli/src/__tests__/generator/plugin/scalar-union-positionals.test.ts b/packages/cli/src/__tests__/generator/plugin/scalar-union-positionals.test.ts index e699c81883..7fcb5af93a 100644 --- a/packages/cli/src/__tests__/generator/plugin/scalar-union-positionals.test.ts +++ b/packages/cli/src/__tests__/generator/plugin/scalar-union-positionals.test.ts @@ -2,8 +2,7 @@ import { stripTypeScriptTypes } from "node:module"; import { Script } from "node:vm"; import { runInTempDir, seed } from "@cloudflare/workers-utils/test-helpers"; import { describe, expect, it, vi } from "vite-plus/test"; -import yargs, { type Argv } from "yargs"; -import { builderLines } from "../../../../generator/plugin/emit/builder.js"; +import { parameterSource } from "../../../../generator/plugin/emit/builder.js"; import { handler, imports } from "../../../../generator/plugin/emit/handler.js"; import { context as emitContext } from "../../../../generator/plugin/emit/index.js"; import { @@ -18,6 +17,10 @@ import { operation, wire, } from "../../helpers/cli-plugin.js"; +import { + generatedParameters, + commandParser, +} from "../../helpers/command-parser.js"; describe.each([true, false])( "scalar-union positionals (typed request: %s)", @@ -37,9 +40,7 @@ describe.each([true, false])( }), "./" ); - const builder = new Script( - `(yargs) => yargs\n${builderLines(ctx).join("\n")}` - ).runInNewContext() as (args: Argv) => Argv; + const params = generatedParameters(parameterSource(ctx)); const source = stripTypeScriptTypes( `(async (argv) => {\n${handler(ctx).join("\n")}\n})` ); @@ -85,18 +86,10 @@ describe.each([true, false])( ) => task(), formatOutput: () => {}, }) as (argv: Record) => Promise; - const argv = await yargs([ - "create", - ...args, - ...(dryRun ? ["--dry-run"] : []), - ]) - .exitProcess(false) - .command(command, "", builder, () => {}) - .strict() - .fail((message, error) => { - throw error ?? new Error(message); - }) - .parseAsync(); + const argv = await commandParser( + ["create", ...args, ...(dryRun ? ["--dry-run"] : [])], + { ...params, command: command } + ).parse(); await run(argv); if (dryRun) { expect(formatDryRun).toHaveBeenCalledWith( diff --git a/packages/cli/src/__tests__/generator/plugin/variant-descriptions.test.ts b/packages/cli/src/__tests__/generator/plugin/variant-descriptions.test.ts index 6dc6bb73cd..434c4bea85 100644 --- a/packages/cli/src/__tests__/generator/plugin/variant-descriptions.test.ts +++ b/packages/cli/src/__tests__/generator/plugin/variant-descriptions.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; import { generateFiles } from "../../helpers/cli-plugin.js"; +import { generatedOptions } from "../../helpers/command-parser.js"; import type { CommandMeta } from "../../../lib/command-meta.js"; type Json = Record; @@ -36,12 +37,11 @@ function generate(schema: Json, schemas: Json = {}) { function option(generated: ReturnType, flag: string) { const metadata = generated.command.options.find((o) => o.name === flag); - const match = generated.code.match( - new RegExp(`\\.option\\('${flag}', (\\{[^\\n]*\\})\\)`) - ); + const builder = generatedOptions(generated.code)[flag]; expect(metadata, `metadata for --${flag}`).toBeDefined(); - expect(match, `builder for --${flag}`).not.toBeNull(); - const builder = JSON.parse(match?.[1] ?? "") as Json; + if (!builder) { + throw new Error(`missing flag: ${flag}`); + } expect(builder["description"]).toBe(metadata?.description); return { metadata, builder }; } diff --git a/packages/cli/src/__tests__/helpers/cli-plugin.ts b/packages/cli/src/__tests__/helpers/cli-plugin.ts index aecfa25557..093fa58656 100644 --- a/packages/cli/src/__tests__/helpers/cli-plugin.ts +++ b/packages/cli/src/__tests__/helpers/cli-plugin.ts @@ -9,7 +9,7 @@ import { context as emitContext, type Ctx, } from "../../../generator/plugin/emit/index.js"; -import { generateFiles } from "./forge-cli.js"; +import { generateFiles as generateModules } from "./forge-cli.js"; import type { Arg, ArgType, Origin } from "../../../generator/plugin/args.js"; import type { Method } from "../../../generator/plugin/commands.js"; import type { @@ -20,7 +20,32 @@ import type { Wire, } from "../../../generator/plugin/operation.js"; -export { generateFiles }; +export function generateFiles(...args: Parameters) { + const files = generateModules(...args); + for (const [path, source] of files) { + if (!path.endsWith(".handler.ts")) { + continue; + } + const key = path.replace(/\.handler\.ts$/, ".ts"); + const definition = files.get(key); + if (!definition) { + throw new Error(`Missing command definition for ${path}`); + } + const handler = source + .replace(/^import type \{ Args \}[^\n]+\n/, "") + .replace("export default async function handle", "async function handle"); + files.set( + key, + handler + + "\n" + + definition.replace( + /loader: \(\) => import\('[^']+\.handler.js'\)/, + "handler: handle" + ) + ); + } + return files; +} /** A method named `name` for the operation `operationId`. */ export function method( diff --git a/packages/cli/src/__tests__/helpers/command-parser.ts b/packages/cli/src/__tests__/helpers/command-parser.ts new file mode 100644 index 0000000000..f2d33c5b90 --- /dev/null +++ b/packages/cli/src/__tests__/helpers/command-parser.ts @@ -0,0 +1,76 @@ +import { stripTypeScriptTypes } from "node:module"; +import { Script } from "node:vm"; +import type { CommandModule } from "yargs"; +import type { Options } from "yargs"; +import { apiCommand } from "#lib/api-command.js"; +import { createParser } from "#lib/stricli.js"; + +export function generatedParameters(lines: string[]) { + const parameters = new Script( + stripTypeScriptTypes(`({${lines.join("\n")}})`) + ).runInNewContext() as Pick< + Parameters[0], + "flags" | "operands" | "rules" + >; + return apiCommand({ + command: "test", + describe: "test", + usage: "", + ...parameters, + async handler() {}, + }); +} + +export function generatedOptions(source: string) { + const code = stripTypeScriptTypes(source) + .replace(/^import[\s\S]*?;\n/gm, "") + .replace("export default command;", "command;"); + const command = new Script(code).runInNewContext({ + apiCommand, + }) as ReturnType; + const flags: Record = {}; + command.configure({ + usage() {}, + positional() {}, + group() {}, + check() {}, + implies() {}, + conflicts() {}, + option(name, options) { + flags[name] = Object.fromEntries( + Object.entries(options).filter( + ([key, value]) => + value !== undefined && !(key === "demandOption" && !value) + ) + ); + }, + }); + return flags; +} + +export function commandParser( + args: string[], + command: CommandModule +) { + let parsed: Record = {}; + const parser = createParser(args, [command as unknown as CommandModule], { + resolve() {}, + helpWidth: Infinity, + help: (text) => text, + shown() {}, + fail(message) { + throw new Error(message); + }, + async startup(argv) { + parsed = argv; + }, + }); + return { + getHelp: parser.getHelp, + complete: parser.complete, + async parse() { + await parser.parse(); + return parsed; + }, + }; +} diff --git a/packages/cli/src/__tests__/lib/hand-written-dry-run.test.ts b/packages/cli/src/__tests__/lib/hand-written-dry-run.test.ts index 560856d959..f2e1fcba7e 100644 --- a/packages/cli/src/__tests__/lib/hand-written-dry-run.test.ts +++ b/packages/cli/src/__tests__/lib/hand-written-dry-run.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it, vi } from "vite-plus/test"; -import yargs from "yargs"; import { withHandWrittenDryRun } from "../../lib/hand-written-dry-run.js"; +import { commandParser } from "../helpers/command-parser.js"; import { generateFiles } from "../helpers/forge-cli.js"; import { runCf } from "../helpers/run-cf.js"; import type { OptionMeta } from "../../lib/metadata.js"; @@ -38,11 +38,10 @@ describe("hand-written dry runs", () => { let error: unknown; try { - await yargs(["group", "delete", "item-1", "--dry-run"]) - .command(group) - .strict() - .exitProcess(false) - .parseAsync(); + await commandParser( + ["group", "delete", "item-1", "--dry-run"], + group + ).parse(); } catch (caught) { error = caught; } @@ -76,11 +75,10 @@ describe("hand-written dry runs", () => { ); await expect(async () => { - await yargs(["dev", "--dry-run", "--token", "secret-value"]) - .command(command) - .strict() - .exitProcess(false) - .parseAsync(); + await commandParser( + ["dev", "--dry-run", "--token", "secret-value"], + command + ).parse(); }).rejects.toMatchObject({ code: 0 }); expect(handler).not.toHaveBeenCalled(); expect(output).toHaveBeenCalledTimes(1); @@ -93,11 +91,7 @@ describe("hand-written dry runs", () => { { command: "deploy", describe: "Deploy", handler }, "native" ); - await yargs(["deploy", "--dry-run"]) - .command(command) - .strict() - .exitProcess(false) - .parseAsync(); + await commandParser(["deploy", "--dry-run"], command).parse(); expect(handler).toHaveBeenCalledWith( expect.objectContaining({ dryRun: true }) ); diff --git a/packages/cli/src/__tests__/lib/stricli.test.ts b/packages/cli/src/__tests__/lib/stricli.test.ts new file mode 100644 index 0000000000..8693f934e3 --- /dev/null +++ b/packages/cli/src/__tests__/lib/stricli.test.ts @@ -0,0 +1,148 @@ +import { describe, expect, expectTypeOf, it, vi } from "vite-plus/test"; +import { apiCommand, apiGroup } from "../../lib/api-command.js"; +import { commandParser } from "../helpers/command-parser.js"; +import type { CommandModule } from "yargs"; + +describe("Stricli command boundary", () => { + it("derives handler inputs from native parameters and dispatches the same native leaf through its group", async () => { + const execute = vi.fn(); + const leaf = apiCommand({ + command: "list ", + describe: "List items", + usage: "", + flags: { + limit: { + kind: "parsed", + parse: Number, + brief: "Limit", + optional: true, + }, + order: { + kind: "enum", + values: ["asc", "desc"], + default: "asc", + brief: "Order", + }, + "dry-run": { kind: "boolean", default: false, brief: "Preview" }, + tags: { + kind: "parsed", + parse: String, + variadic: true, + optional: true, + brief: "Tags", + }, + }, + operands: [{ placeholder: "bucket-id", brief: "Bucket", parse: String }], + async handler(argv) { + expectTypeOf(argv.limit).toEqualTypeOf(); + expectTypeOf(argv.order).toEqualTypeOf<"asc" | "desc">(); + expectTypeOf(argv.dryRun).toEqualTypeOf(); + expectTypeOf(argv.tags).toEqualTypeOf(); + expectTypeOf(argv.bucketId).toEqualTypeOf(); + expectTypeOf().extract<"misspelled">().toBeNever(); + execute(argv); + }, + }); + const group = apiGroup({ + command: "items", + describe: "Items", + routes: { list: leaf }, + }); + expect(group.routeMap().getRoutingTargetForInput("list")).toBe( + leaf.native() + ); + await commandParser( + ["items", "list", "a", "--tags", "one", "two", "--limit=4"], + group + ).parse(); + expect(execute).toHaveBeenCalledWith( + expect.objectContaining({ + bucketId: "a", + order: "asc", + dryRun: false, + limit: 4, + tags: ["one", "two"], + }) + ); + }); + it("loads the generated handler only for execution", async () => { + const execute = vi.fn(async () => {}); + const loader = vi.fn(async () => ({ default: execute })); + const command = apiCommand({ + command: "list", + describe: "List items", + usage: "", + flags: { + order: { + kind: "enum", + brief: "Order", + values: ["asc", "desc"], + optional: true, + }, + }, + operands: [], + loader, + }); + const parser = commandParser(["list"], command); + await parser.getHelp(); + expect(await parser.complete(["list", "--order", "d"])).toContainEqual( + expect.objectContaining({ completion: "desc" }) + ); + expect(loader).not.toHaveBeenCalled(); + await parser.parse(); + expect(loader).toHaveBeenCalledTimes(1); + expect(execute).toHaveBeenCalledTimes(1); + }); + const handler = vi.fn(); + const command: CommandModule = { + command: "remove ", + builder: (args) => + args + .option("force", { type: "boolean", alias: "f" }) + .option("label", { type: "string" }), + handler, + }; + it("does not interpret an invalid confirmation as true", async () => { + handler.mockClear(); + await expect( + commandParser(["remove", "id", "--force=maybe"], command).parse() + ).resolves.toMatchObject({ force: false }); + expect(handler).toHaveBeenCalledWith( + expect.objectContaining({ force: false }) + ); + }); + it("preserves grouped switches and an explicit dash-prefixed value", async () => { + await expect( + commandParser(["remove", "id", "-qf", "--label=--force"], command).parse() + ).resolves.toMatchObject({ + id: "id", + quiet: true, + force: true, + label: "--force", + }); + }); + it("binds camel-case command operands to the declared kebab-case positional", async () => { + await expect( + commandParser(["get", "example"], { + command: "get ", + builder: (args) => args.positional("resource-id", { type: "string" }), + handler, + }).parse() + ).resolves.toMatchObject({ + resourceId: "example", + "resource-id": "example", + }); + }); + it("distinguishes omitted, empty and malformed numeric values", async () => { + await expect( + commandParser( + ["--count", "2", "get", "--count", "--count=", "--count=bad"], + { + command: "get", + builder: (args) => args.option("count", { type: "number" }), + handler, + } + ).parse() + ).resolves.toMatchObject({ count: [2, undefined, 0, NaN] }); + }); +}); diff --git a/packages/cli/src/commands/_generated/abuse-reports/appeals/eligibility.handler.ts b/packages/cli/src/commands/_generated/abuse-reports/appeals/eligibility.handler.ts new file mode 100644 index 0000000000..fd0a2be469 --- /dev/null +++ b/packages/cli/src/commands/_generated/abuse-reports/appeals/eligibility.handler.ts @@ -0,0 +1,49 @@ +import operation from "../../_operations/abuse-reports/appeals/eligibility.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./eligibility.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "abuse-reports appeals eligibility", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf abuse-reports appeals eligibility", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/abuse-reports/${argv["report-id"] == null ? "" : encodeURIComponent(String(argv["report-id"]))}/appeals/eligibility`, + pathParams: { "report-id": String(argv["report-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + report_id: argv["report-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/abuse-reports/appeals/eligibility.ts b/packages/cli/src/commands/_generated/abuse-reports/appeals/eligibility.ts index 7243a6edc1..ff7b45e1e5 100644 --- a/packages/cli/src/commands/_generated/abuse-reports/appeals/eligibility.ts +++ b/packages/cli/src/commands/_generated/abuse-reports/appeals/eligibility.ts @@ -1,79 +1,33 @@ -import operation from "../../_operations/abuse-reports/appeals/eligibility.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * eligibility command * @generated from apis/overlays/abuse-reports.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 abuse-reports appeals eligibility \n\nReturns whether the report is currently appealable, along with the signals behind that decision: whether it already has an open appeal, how many appeals have been submitted against it, and whether it has at least one mitigation that an appeal could reverse. Report-level appeals are currently available only for DMCA (copyright) reports. For other report types this operation returns the same `404 Report not found` response as a report that does not exist for the account." - ) - .positional("report-id", { - type: "string", - description: "Abuse Report ID", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "report-id", brief: "Abuse Report ID", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "eligibility ", describe: "Check whether a report can be appealed", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "abuse-reports appeals eligibility", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf abuse-reports appeals eligibility", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/abuse-reports/${argv["report-id"] == null ? "" : encodeURIComponent(String(argv["report-id"]))}/appeals/eligibility`, - pathParams: { "report-id": String(argv["report-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - report_id: argv["report-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 abuse-reports appeals eligibility \n\nReturns whether the report is currently appealable, along with the signals behind that decision: whether it already has an open appeal, how many appeals have been submitted against it, and whether it has at least one mitigation that an appeal could reverse. Report-level appeals are currently available only for DMCA (copyright) reports. For other report types this operation returns the same `404 Report not found` response as a report that does not exist for the account.", + ...parameters, + loader: () => import("./eligibility.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/abuse-reports/appeals/index.ts b/packages/cli/src/commands/_generated/abuse-reports/appeals/index.ts index 8161a1b535..e519748885 100644 --- a/packages/cli/src/commands/_generated/abuse-reports/appeals/index.ts +++ b/packages/cli/src/commands/_generated/abuse-reports/appeals/index.ts @@ -1,22 +1,17 @@ import $eligibility from "./eligibility.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * appeals command group * @generated from apis/overlays/abuse-reports.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "appeals", describe: "Appeal eligibility for abuse reports", - builder: (yargs) => { - return yargs - .command($eligibility) - .demandCommand(1, "Please specify a subcommand"); + routes: { + eligibility: $eligibility, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/abuse-reports/create.handler.ts b/packages/cli/src/commands/_generated/abuse-reports/create.handler.ts new file mode 100644 index 0000000000..ff9af4e986 --- /dev/null +++ b/packages/cli/src/commands/_generated/abuse-reports/create.handler.ts @@ -0,0 +1,594 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, setNestedValue } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { + promptForRequiredEnumField, + promptForRequiredField, +} from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "abuse-reports create", + classification: { + safeFlags: [ + "act", + "host-notification", + "owner-notification", + "ncmec-notification", + "reg-who-request-reg-who-good-faith-affirmation", + "reg-who-request-reg-who-lawful-processing-agreement", + "reg-who-request-reg-who-request-type", + "reg-who-request-reg-who-requestor-type", + "ncsei-subject-representation", + "dry-run", + ], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["act"] === undefined) { + argv["act"] = await promptForRequiredEnumField( + "act", + "The act field", + [ + "abuse_dmca", + "abuse_trademark", + "abuse_general", + "abuse_phishing", + "abuse_children", + "abuse_threat", + "abuse_registrar_whois", + "abuse_ncsei", + ] as const + ); + } + if (argv["email"] === undefined) { + argv["email"] = await promptForRequiredField( + "email", + "A valid email of the abuse reporter. This field may be released by Cloudflare to third parties such as the Lumen Database (https://lumendatabase.org/)." + ); + } + if (argv["email2"] === undefined) { + argv["email2"] = await promptForRequiredField( + "email2", + "Should match the value provided in \`email\`" + ); + } + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField( + "name", + "Text not exceeding 255 characters. This field may be released by Cloudflare to third parties such as the Lumen Database (https://lumendatabase.org/)." + ); + } + if (argv["urls"] === undefined) { + argv["urls"] = await promptForRequiredField( + "urls", + "A list of valid URLs separated by ‘\\n’ (new line character). The list of the URLs should not exceed 250 URLs. All URLs should have the same hostname. Each URL should be unique. This field may be released by Cloudflare to third parties such as the Lumen Database (https://lumendatabase.org/)." + ); + } + if (argv["owner-notification"] === undefined) { + argv["owner-notification"] = await promptForRequiredEnumField( + "owner-notification", + "Notification type based on the abuse type. For delegated reports, the report—including contact information and comments—will be forwarded to the customer in full regardless of this value. NOTE: Copyright (DMCA) and Trademark reports cannot be anonymous.", + ["send", "send-anon", "none"] as const + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf abuse-reports create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/abuse-reports/${argv["report-type"] == null ? "" : encodeURIComponent(String(argv["report-type"]))}`, + pathParams: { "report-type": String(argv["report-type"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + act: argv["act"], + comments: resolveFileToken( + argv["comments"] as string | undefined, + "comments", + "text" + ), + company: resolveFileToken( + argv["company"] as string | undefined, + "company", + "text" + ), + email: resolveFileToken( + argv["email"] as string | undefined, + "email", + "text" + ), + email2: resolveFileToken( + argv["email2"] as string | undefined, + "email2", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + reported_country: resolveFileToken( + argv["reported-country"] as string | undefined, + "reported-country", + "text" + ), + reported_user_agent: resolveFileToken( + argv["reported-user-agent"] as string | undefined, + "reported-user-agent", + "text" + ), + tele: resolveFileToken( + argv["tele"] as string | undefined, + "tele", + "text" + ), + title: resolveFileToken( + argv["title"] as string | undefined, + "title", + "text" + ), + urls: resolveFileToken( + argv["urls"] as string | undefined, + "urls", + "text" + ), + address1: resolveFileToken( + argv["address1"] as string | undefined, + "address1", + "text" + ), + agent_name: resolveFileToken( + argv["agent-name"] as string | undefined, + "agent-name", + "text" + ), + agree: argv["agree"], + city: resolveFileToken( + argv["city"] as string | undefined, + "city", + "text" + ), + country: resolveFileToken( + argv["country"] as string | undefined, + "country", + "text" + ), + host_notification: argv["host-notification"], + original_work: resolveFileToken( + argv["original-work"] as string | undefined, + "original-work", + "text" + ), + owner_notification: argv["owner-notification"], + signature: resolveFileToken( + argv["signature"] as string | undefined, + "signature", + "text" + ), + state: resolveFileToken( + argv["state"] as string | undefined, + "state", + "text" + ), + justification: resolveFileToken( + argv["justification"] as string | undefined, + "justification", + "text" + ), + trademark_number: resolveFileToken( + argv["trademark-number"] as string | undefined, + "trademark-number", + "text" + ), + trademark_office: resolveFileToken( + argv["trademark-office"] as string | undefined, + "trademark-office", + "text" + ), + trademark_symbol: resolveFileToken( + argv["trademark-symbol"] as string | undefined, + "trademark-symbol", + "text" + ), + destination_ips: resolveFileToken( + argv["destination-ips"] as string | undefined, + "destination-ips", + "text" + ), + ports_protocols: resolveFileToken( + argv["ports-protocols"] as string | undefined, + "ports-protocols", + "text" + ), + source_ips: resolveFileToken( + argv["source-ips"] as string | undefined, + "source-ips", + "text" + ), + ncmec_notification: argv["ncmec-notification"], + reg_who_request: { + reg_who_authorization_statement: resolveFileToken( + argv[ + "reg-who-request-reg-who-authorization-statement" + ] as string | undefined, + "reg-who-request-reg-who-authorization-statement", + "text" + ), + reg_who_good_faith_affirmation: + argv["reg-who-request-reg-who-good-faith-affirmation"], + reg_who_lawful_processing_agreement: + argv[ + "reg-who-request-reg-who-lawful-processing-agreement" + ], + reg_who_legal_basis: resolveFileToken( + argv["reg-who-request-reg-who-legal-basis"] as + | string + | undefined, + "reg-who-request-reg-who-legal-basis", + "text" + ), + reg_who_request_type: + argv["reg-who-request-reg-who-request-type"], + reg_who_requested_data_elements: + argv["reg-who-request-reg-who-requested-data-elements"], + reg_who_requestor_type: + argv["reg-who-request-reg-who-requestor-type"], + }, + ncsei_subject_representation: + argv["ncsei-subject-representation"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/abuse-reports/${encodeURIComponent(String(argv["report-type"]))}`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData: Record = {}; + if (argv["act"] !== undefined) + setNestedValue(bodyData, ["act"], argv["act"]); + if (argv["comments"] !== undefined) + setNestedValue( + bodyData, + ["comments"], + resolveFileToken( + argv["comments"] as string | undefined, + "comments", + "text" + ) + ); + if (argv["company"] !== undefined) + setNestedValue( + bodyData, + ["company"], + resolveFileToken( + argv["company"] as string | undefined, + "company", + "text" + ) + ); + if (argv["email"] !== undefined) + setNestedValue( + bodyData, + ["email"], + resolveFileToken(argv["email"] as string | undefined, "email", "text") + ); + if (argv["email2"] !== undefined) + setNestedValue( + bodyData, + ["email2"], + resolveFileToken( + argv["email2"] as string | undefined, + "email2", + "text" + ) + ); + if (argv["name"] !== undefined) + setNestedValue( + bodyData, + ["name"], + resolveFileToken(argv["name"] as string | undefined, "name", "text") + ); + if (argv["reported-country"] !== undefined) + setNestedValue( + bodyData, + ["reported_country"], + resolveFileToken( + argv["reported-country"] as string | undefined, + "reported-country", + "text" + ) + ); + if (argv["reported-user-agent"] !== undefined) + setNestedValue( + bodyData, + ["reported_user_agent"], + resolveFileToken( + argv["reported-user-agent"] as string | undefined, + "reported-user-agent", + "text" + ) + ); + if (argv["tele"] !== undefined) + setNestedValue( + bodyData, + ["tele"], + resolveFileToken(argv["tele"] as string | undefined, "tele", "text") + ); + if (argv["title"] !== undefined) + setNestedValue( + bodyData, + ["title"], + resolveFileToken(argv["title"] as string | undefined, "title", "text") + ); + if (argv["urls"] !== undefined) + setNestedValue( + bodyData, + ["urls"], + resolveFileToken(argv["urls"] as string | undefined, "urls", "text") + ); + if (argv["address1"] !== undefined) + setNestedValue( + bodyData, + ["address1"], + resolveFileToken( + argv["address1"] as string | undefined, + "address1", + "text" + ) + ); + if (argv["agent-name"] !== undefined) + setNestedValue( + bodyData, + ["agent_name"], + resolveFileToken( + argv["agent-name"] as string | undefined, + "agent-name", + "text" + ) + ); + if (argv["agree"] !== undefined) + setNestedValue(bodyData, ["agree"], argv["agree"]); + if (argv["city"] !== undefined) + setNestedValue( + bodyData, + ["city"], + resolveFileToken(argv["city"] as string | undefined, "city", "text") + ); + if (argv["country"] !== undefined) + setNestedValue( + bodyData, + ["country"], + resolveFileToken( + argv["country"] as string | undefined, + "country", + "text" + ) + ); + if (argv["host-notification"] !== undefined) + setNestedValue( + bodyData, + ["host_notification"], + argv["host-notification"] + ); + if (argv["original-work"] !== undefined) + setNestedValue( + bodyData, + ["original_work"], + resolveFileToken( + argv["original-work"] as string | undefined, + "original-work", + "text" + ) + ); + if (argv["owner-notification"] !== undefined) + setNestedValue( + bodyData, + ["owner_notification"], + argv["owner-notification"] + ); + if (argv["signature"] !== undefined) + setNestedValue( + bodyData, + ["signature"], + resolveFileToken( + argv["signature"] as string | undefined, + "signature", + "text" + ) + ); + if (argv["state"] !== undefined) + setNestedValue( + bodyData, + ["state"], + resolveFileToken(argv["state"] as string | undefined, "state", "text") + ); + if (argv["justification"] !== undefined) + setNestedValue( + bodyData, + ["justification"], + resolveFileToken( + argv["justification"] as string | undefined, + "justification", + "text" + ) + ); + if (argv["trademark-number"] !== undefined) + setNestedValue( + bodyData, + ["trademark_number"], + resolveFileToken( + argv["trademark-number"] as string | undefined, + "trademark-number", + "text" + ) + ); + if (argv["trademark-office"] !== undefined) + setNestedValue( + bodyData, + ["trademark_office"], + resolveFileToken( + argv["trademark-office"] as string | undefined, + "trademark-office", + "text" + ) + ); + if (argv["trademark-symbol"] !== undefined) + setNestedValue( + bodyData, + ["trademark_symbol"], + resolveFileToken( + argv["trademark-symbol"] as string | undefined, + "trademark-symbol", + "text" + ) + ); + if (argv["destination-ips"] !== undefined) + setNestedValue( + bodyData, + ["destination_ips"], + resolveFileToken( + argv["destination-ips"] as string | undefined, + "destination-ips", + "text" + ) + ); + if (argv["ports-protocols"] !== undefined) + setNestedValue( + bodyData, + ["ports_protocols"], + resolveFileToken( + argv["ports-protocols"] as string | undefined, + "ports-protocols", + "text" + ) + ); + if (argv["source-ips"] !== undefined) + setNestedValue( + bodyData, + ["source_ips"], + resolveFileToken( + argv["source-ips"] as string | undefined, + "source-ips", + "text" + ) + ); + if (argv["ncmec-notification"] !== undefined) + setNestedValue( + bodyData, + ["ncmec_notification"], + argv["ncmec-notification"] + ); + if (argv["reg-who-request-reg-who-authorization-statement"] !== undefined) + setNestedValue( + bodyData, + ["reg_who_request", "reg_who_authorization_statement"], + resolveFileToken( + argv["reg-who-request-reg-who-authorization-statement"] as + | string + | undefined, + "reg-who-request-reg-who-authorization-statement", + "text" + ) + ); + if (argv["reg-who-request-reg-who-good-faith-affirmation"] !== undefined) + setNestedValue( + bodyData, + ["reg_who_request", "reg_who_good_faith_affirmation"], + argv["reg-who-request-reg-who-good-faith-affirmation"] + ); + if ( + argv["reg-who-request-reg-who-lawful-processing-agreement"] !== + undefined + ) + setNestedValue( + bodyData, + ["reg_who_request", "reg_who_lawful_processing_agreement"], + argv["reg-who-request-reg-who-lawful-processing-agreement"] + ); + if (argv["reg-who-request-reg-who-legal-basis"] !== undefined) + setNestedValue( + bodyData, + ["reg_who_request", "reg_who_legal_basis"], + resolveFileToken( + argv["reg-who-request-reg-who-legal-basis"] as string | undefined, + "reg-who-request-reg-who-legal-basis", + "text" + ) + ); + if (argv["reg-who-request-reg-who-request-type"] !== undefined) + setNestedValue( + bodyData, + ["reg_who_request", "reg_who_request_type"], + argv["reg-who-request-reg-who-request-type"] + ); + if (argv["reg-who-request-reg-who-requested-data-elements"] !== undefined) + setNestedValue( + bodyData, + ["reg_who_request", "reg_who_requested_data_elements"], + argv["reg-who-request-reg-who-requested-data-elements"] + ); + if (argv["reg-who-request-reg-who-requestor-type"] !== undefined) + setNestedValue( + bodyData, + ["reg_who_request", "reg_who_requestor_type"], + argv["reg-who-request-reg-who-requestor-type"] + ); + if (argv["ncsei-subject-representation"] !== undefined) + setNestedValue( + bodyData, + ["ncsei_subject_representation"], + argv["ncsei-subject-representation"] + ); + const result = await withProgress(`Creating`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/abuse-reports/${encodeURIComponent(String(argv["report-type"]))}`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/abuse-reports/create.ts b/packages/cli/src/commands/_generated/abuse-reports/create.ts index cdbf95d652..f6d931f30f 100644 --- a/packages/cli/src/commands/_generated/abuse-reports/create.ts +++ b/packages/cli/src/commands/_generated/abuse-reports/create.ts @@ -1,41 +1,20 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/abuse-reports.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, setNestedValue } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { - promptForRequiredEnumField, - promptForRequiredField, -} from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 abuse-reports create \n\nSubmit an abuse report of a particular type. Requires the abuse-reports entitlement on the account (Enterprise accounts have it by default; other accounts must request access) and an API token with the `Trust and Safety Write` permission. If the account is not entitled, the request is rejected with an HTTP `401` response (see below). Delegated reports: In limited circumstances, Cloudflare delegates processing of abuse reports to select customers who have established abuse-handling programs. For these customers, Cloudflare may forward abuse reports directly and in full—including reporter contact information, comments, and supporting evidence—without redaction or preprocessing by Cloudflare. This allows the customer to investigate and respond using their own policies and processes. For delegated reports, the report—including contact information and comments—will be forwarded to the customer in full regardless of the `host_notification` and `owner_notification` values." - ) - .positional("report-type", { - type: "string", - description: "The report type to be submitted. Example: abuse_general", - demandOption: true, - }) - .option("act", { - type: "string", - description: "The act field", +const parameters = { + flags: { + act: { + kind: "parsed", + brief: "The act field", + optional: true, choices: [ "abuse_dmca", "abuse_trademark", @@ -46,210 +25,289 @@ function builder(yargs: Argv) { "abuse_registrar_whois", "abuse_ncsei", ], - }) - .coerce("act", (value) => resolveFileToken(value, "act", "text")) - .option("comments", { - type: "string", - description: + parse: String, + coerce: (value: string) => resolveFileToken(value, "act", "text"), + }, + comments: { + kind: "parsed", + brief: "Any additional comments about the infringement not exceeding 2000 characters. With the exception of delegated reports, comments are kept internal to Cloudflare and not shared with the host or customer as part of regular processing. For the limited circumstances where we delegate reports to customers with established abuse-handling programs, comments may be shared in full.", - }) - .option("company", { - type: "string", - description: + optional: true, + parse: String, + }, + company: { + kind: "parsed", + brief: "Text not exceeding 100 characters. This field may be released by Cloudflare to third parties such as the Lumen Database (https://lumendatabase.org/).", - }) - .option("email", { - type: "string", - description: + optional: true, + parse: String, + }, + email: { + kind: "parsed", + brief: "A valid email of the abuse reporter. This field may be released by Cloudflare to third parties such as the Lumen Database (https://lumendatabase.org/).", - }) - .option("email2", { - type: "string", - description: "Should match the value provided in `email`", - }) - .option("name", { - type: "string", - description: + optional: true, + parse: String, + }, + email2: { + kind: "parsed", + brief: "Should match the value provided in `email`", + optional: true, + parse: String, + }, + name: { + kind: "parsed", + brief: "Text not exceeding 255 characters. This field may be released by Cloudflare to third parties such as the Lumen Database (https://lumendatabase.org/).", - }) - .option("reported-country", { - type: "string", - description: "Text containing 2 characters", - }) - .option("reported-user-agent", { - type: "string", - description: "Text not exceeding 255 characters", - }) - .option("tele", { - type: "string", - description: + optional: true, + parse: String, + }, + "reported-country": { + kind: "parsed", + brief: "Text containing 2 characters", + optional: true, + parse: String, + }, + "reported-user-agent": { + kind: "parsed", + brief: "Text not exceeding 255 characters", + optional: true, + parse: String, + }, + tele: { + kind: "parsed", + brief: "Text not exceeding 20 characters. This field may be released by Cloudflare to third parties such as the Lumen Database (https://lumendatabase.org/).", - }) - .option("title", { - type: "string", - description: "Text not exceeding 255 characters", - }) - .option("urls", { - type: "string", - description: + optional: true, + parse: String, + }, + title: { + kind: "parsed", + brief: "Text not exceeding 255 characters", + optional: true, + parse: String, + }, + urls: { + kind: "parsed", + brief: "A list of valid URLs separated by ‘\\n’ (new line character). The list of the URLs should not exceed 250 URLs. All URLs should have the same hostname. Each URL should be unique. This field may be released by Cloudflare to third parties such as the Lumen Database (https://lumendatabase.org/).", - }) - .option("address1", { - type: "string", - description: + optional: true, + parse: String, + }, + address1: { + kind: "parsed", + brief: "Text not exceeding 100 characters. This field may be released by Cloudflare to third parties such as the Lumen Database (https://lumendatabase.org/).", - }) - .option("agent-name", { - type: "string", - description: + optional: true, + parse: String, + }, + "agent-name": { + kind: "parsed", + brief: "The name of the copyright holder. Text not exceeding 60 characters. This field may be released by Cloudflare to third parties such as the Lumen Database (https://lumendatabase.org/).", - }) - .option("agree", { - type: "number", - description: + optional: true, + parse: String, + }, + agree: { + kind: "parsed", + brief: "Can be `0` for false or `1` for true. Must be value: 1 for DMCA reports", - }) - .option("city", { - type: "string", - description: + optional: true, + parse: Number, + }, + city: { + kind: "parsed", + brief: "Text not exceeding 255 characters. This field may be released by Cloudflare to third parties such as the Lumen Database (https://lumendatabase.org/).", - }) - .option("country", { - type: "string", - description: + optional: true, + parse: String, + }, + country: { + kind: "parsed", + brief: "Text not exceeding 255 characters. This field may be released by Cloudflare to third parties such as the Lumen Database (https://lumendatabase.org/).", - }) - .option("host-notification", { - type: "string", - description: + optional: true, + parse: String, + }, + "host-notification": { + kind: "parsed", + brief: "Notification type based on the abuse type. For delegated reports, the report—including contact information and comments—will be forwarded to the customer in full regardless of this value. NOTE: Copyright (DMCA) and Trademark reports cannot be anonymous.", + optional: true, choices: ["send", "send-anon"], - }) - .coerce("host-notification", (value) => - resolveFileToken(value, "host-notification", "text") - ) - .option("original-work", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "host-notification", "text"), + }, + "original-work": { + kind: "parsed", + brief: "Text not exceeding 255 characters. This field may be released by Cloudflare to third parties such as the Lumen Database (https://lumendatabase.org/).", - }) - .option("owner-notification", { - type: "string", - description: + optional: true, + parse: String, + }, + "owner-notification": { + kind: "parsed", + brief: "Notification type based on the abuse type. For delegated reports, the report—including contact information and comments—will be forwarded to the customer in full regardless of this value. NOTE: Copyright (DMCA) and Trademark reports cannot be anonymous.", + optional: true, choices: ["send", "send-anon", "none"], - }) - .coerce("owner-notification", (value) => - resolveFileToken(value, "owner-notification", "text") - ) - .option("signature", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "owner-notification", "text"), + }, + signature: { + kind: "parsed", + brief: "Required for DMCA reports, should be same as Name. An affirmation that all information in the report is true and accurate while agreeing to the policies of Cloudflare's abuse reports", - }) - .option("state", { - type: "string", - description: + optional: true, + parse: String, + }, + state: { + kind: "parsed", + brief: "Text not exceeding 255 characters. This field may be released by Cloudflare to third parties such as the Lumen Database (https://lumendatabase.org/).", - }) - .option("justification", { - type: "string", - description: + optional: true, + parse: String, + }, + justification: { + kind: "parsed", + brief: "A detailed description of the infringement, including any necessary access details and the exact steps needed to view the content, not exceeding 5000 characters.", - }) - .option("trademark-number", { - type: "string", - description: "Text not exceeding 1000 characters", - }) - .option("trademark-office", { - type: "string", - description: "Text not exceeding 1000 characters", - }) - .option("trademark-symbol", { - type: "string", - description: "Text not exceeding 1000 characters", - }) - .option("destination-ips", { - type: "string", - description: + optional: true, + parse: String, + }, + "trademark-number": { + kind: "parsed", + brief: "Text not exceeding 1000 characters", + optional: true, + parse: String, + }, + "trademark-office": { + kind: "parsed", + brief: "Text not exceeding 1000 characters", + optional: true, + parse: String, + }, + "trademark-symbol": { + kind: "parsed", + brief: "Text not exceeding 1000 characters", + optional: true, + parse: String, + }, + "destination-ips": { + kind: "parsed", + brief: "A list of IP addresses separated by ‘\\n’ (new line character). The list of destination IPs should not exceed 30 IP addresses. Each one of the IP addresses ought to be unique.", - }) - .option("ports-protocols", { - type: "string", - description: + optional: true, + parse: String, + }, + "ports-protocols": { + kind: "parsed", + brief: "A comma separated list of ports and protocols e.g. 80/TCP, 22/UDP. The total size of the field should not exceed 2000 characters. Each individual port/protocol should not exceed 100 characters. The list should not have more than 30 unique ports and protocols.", - }) - .option("source-ips", { - type: "string", - description: + optional: true, + parse: String, + }, + "source-ips": { + kind: "parsed", + brief: "A list of IP addresses separated by ‘\\n’ (new line character). The list of source IPs should not exceed 30 IP addresses. Each one of the IP addresses ought to be unique.", - }) - .option("ncmec-notification", { - type: "string", - description: + optional: true, + parse: String, + }, + "ncmec-notification": { + kind: "parsed", + brief: "Notification type based on the abuse type. NOTE: Copyright (DMCA) and Trademark reports cannot be anonymous.\n", + optional: true, choices: ["send", "send-anon"], - }) - .coerce("ncmec-notification", (value) => - resolveFileToken(value, "ncmec-notification", "text") - ) - .option("reg-who-request-reg-who-authorization-statement", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "ncmec-notification", "text"), + }, + "reg-who-request-reg-who-authorization-statement": { + kind: "parsed", + brief: "Optional authorization statement or power of attorney per RDP 10.2.1.3.", - }) - .option("reg-who-request-reg-who-good-faith-affirmation", { - type: "boolean", - description: + optional: true, + parse: String, + }, + "reg-who-request-reg-who-good-faith-affirmation": { + kind: "boolean", + brief: "Affirmation that the request is made in good faith per RDP 10.2.4. Must be true.", - }) - .option("reg-who-request-reg-who-lawful-processing-agreement", { - type: "boolean", - description: - "Agreement to process data lawfully per RDP 10.2.5. Must be true.", - }) - .option("reg-who-request-reg-who-legal-basis", { - type: "string", - description: + optional: true, + }, + "reg-who-request-reg-who-lawful-processing-agreement": { + kind: "boolean", + brief: "Agreement to process data lawfully per RDP 10.2.5. Must be true.", + optional: true, + }, + "reg-who-request-reg-who-legal-basis": { + kind: "parsed", + brief: "Legal rights and rationale for the request per RDP 10.2.3. Required for all WHOIS requests.", - }) - .option("reg-who-request-reg-who-request-type", { - type: "string", - description: "The type of WHOIS data request per RDP procedure.", + optional: true, + parse: String, + }, + "reg-who-request-reg-who-request-type": { + kind: "parsed", + brief: "The type of WHOIS data request per RDP procedure.", + optional: true, choices: ["disclosure", "invalid_whois"], - }) - .coerce("reg-who-request-reg-who-request-type", (value) => - resolveFileToken(value, "reg-who-request-reg-who-request-type", "text") - ) - .option("reg-who-request-reg-who-requested-data-elements", { - type: "string", - array: true, - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "reg-who-request-reg-who-request-type", "text"), + }, + "reg-who-request-reg-who-requested-data-elements": { + kind: "parsed", + brief: "The specific WHOIS data elements being requested per RDP 10.2.2. Required for all WHOIS requests.", - }) - .option("reg-who-request-reg-who-requestor-type", { - type: "string", - description: "The nature of the requestor per RDP 10.2.1.2.", + variadic: true, + optional: true, + parse: String, + }, + "reg-who-request-reg-who-requestor-type": { + kind: "parsed", + brief: "The nature of the requestor per RDP 10.2.1.2.", + optional: true, choices: ["government", "corporation", "individual"], - }) - .coerce("reg-who-request-reg-who-requestor-type", (value) => - resolveFileToken(value, "reg-who-request-reg-who-requestor-type", "text") - ) - .option("ncsei-subject-representation", { - type: "boolean", - description: + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "reg-who-request-reg-who-requestor-type", + "text" + ), + }, + "ncsei-subject-representation": { + kind: "boolean", + brief: "If the submitter is the target of NCSEI in the URLs of the abuse report.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }) - .conflicts("address1", [ + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "report-type", + brief: "The report type to be submitted. Example: abuse_general", + parse: String, + }, + ], + rules(rules) { + rules.conflicts("address1", [ "justification", "trademark-number", "trademark-office", @@ -266,8 +324,8 @@ function builder(yargs: Argv) { "reg-who-request-reg-who-requested-data-elements", "reg-who-request-reg-who-requestor-type", "ncsei-subject-representation", - ]) - .implies("address1", [ + ]); + rules.implies("address1", [ "agent-name", "agree", "city", @@ -276,8 +334,8 @@ function builder(yargs: Argv) { "original-work", "signature", "state", - ]) - .conflicts("agent-name", [ + ]); + rules.conflicts("agent-name", [ "justification", "trademark-number", "trademark-office", @@ -294,8 +352,8 @@ function builder(yargs: Argv) { "reg-who-request-reg-who-requested-data-elements", "reg-who-request-reg-who-requestor-type", "ncsei-subject-representation", - ]) - .implies("agent-name", [ + ]); + rules.implies("agent-name", [ "address1", "agree", "city", @@ -304,8 +362,8 @@ function builder(yargs: Argv) { "original-work", "signature", "state", - ]) - .conflicts("agree", [ + ]); + rules.conflicts("agree", [ "justification", "trademark-number", "trademark-office", @@ -322,8 +380,8 @@ function builder(yargs: Argv) { "reg-who-request-reg-who-requested-data-elements", "reg-who-request-reg-who-requestor-type", "ncsei-subject-representation", - ]) - .implies("agree", [ + ]); + rules.implies("agree", [ "address1", "agent-name", "city", @@ -332,8 +390,8 @@ function builder(yargs: Argv) { "original-work", "signature", "state", - ]) - .conflicts("city", [ + ]); + rules.conflicts("city", [ "justification", "trademark-number", "trademark-office", @@ -350,8 +408,8 @@ function builder(yargs: Argv) { "reg-who-request-reg-who-requested-data-elements", "reg-who-request-reg-who-requestor-type", "ncsei-subject-representation", - ]) - .implies("city", [ + ]); + rules.implies("city", [ "address1", "agent-name", "agree", @@ -360,8 +418,8 @@ function builder(yargs: Argv) { "original-work", "signature", "state", - ]) - .conflicts("country", [ + ]); + rules.conflicts("country", [ "trademark-number", "trademark-office", "trademark-symbol", @@ -375,9 +433,9 @@ function builder(yargs: Argv) { "reg-who-request-reg-who-request-type", "reg-who-request-reg-who-requested-data-elements", "reg-who-request-reg-who-requestor-type", - ]) - .implies("country", ["host-notification"]) - .conflicts("host-notification", [ + ]); + rules.implies("country", ["host-notification"]); + rules.conflicts("host-notification", [ "reg-who-request-reg-who-authorization-statement", "reg-who-request-reg-who-good-faith-affirmation", "reg-who-request-reg-who-lawful-processing-agreement", @@ -385,8 +443,8 @@ function builder(yargs: Argv) { "reg-who-request-reg-who-request-type", "reg-who-request-reg-who-requested-data-elements", "reg-who-request-reg-who-requestor-type", - ]) - .conflicts("original-work", [ + ]); + rules.conflicts("original-work", [ "trademark-number", "trademark-office", "trademark-symbol", @@ -402,9 +460,9 @@ function builder(yargs: Argv) { "reg-who-request-reg-who-requested-data-elements", "reg-who-request-reg-who-requestor-type", "ncsei-subject-representation", - ]) - .implies("original-work", ["host-notification"]) - .conflicts("signature", [ + ]); + rules.implies("original-work", ["host-notification"]); + rules.conflicts("signature", [ "justification", "trademark-number", "trademark-office", @@ -421,8 +479,8 @@ function builder(yargs: Argv) { "reg-who-request-reg-who-requested-data-elements", "reg-who-request-reg-who-requestor-type", "ncsei-subject-representation", - ]) - .implies("signature", [ + ]); + rules.implies("signature", [ "address1", "agent-name", "agree", @@ -431,8 +489,8 @@ function builder(yargs: Argv) { "host-notification", "original-work", "state", - ]) - .conflicts("state", [ + ]); + rules.conflicts("state", [ "justification", "trademark-number", "trademark-office", @@ -449,8 +507,8 @@ function builder(yargs: Argv) { "reg-who-request-reg-who-requested-data-elements", "reg-who-request-reg-who-requestor-type", "ncsei-subject-representation", - ]) - .implies("state", [ + ]); + rules.implies("state", [ "address1", "agent-name", "agree", @@ -459,8 +517,8 @@ function builder(yargs: Argv) { "host-notification", "original-work", "signature", - ]) - .conflicts("justification", [ + ]); + rules.conflicts("justification", [ "address1", "agent-name", "agree", @@ -475,9 +533,9 @@ function builder(yargs: Argv) { "reg-who-request-reg-who-requested-data-elements", "reg-who-request-reg-who-requestor-type", "ncsei-subject-representation", - ]) - .implies("justification", ["host-notification"]) - .conflicts("trademark-number", [ + ]); + rules.implies("justification", ["host-notification"]); + rules.conflicts("trademark-number", [ "address1", "agent-name", "agree", @@ -498,14 +556,14 @@ function builder(yargs: Argv) { "reg-who-request-reg-who-requested-data-elements", "reg-who-request-reg-who-requestor-type", "ncsei-subject-representation", - ]) - .implies("trademark-number", [ + ]); + rules.implies("trademark-number", [ "host-notification", "justification", "trademark-office", "trademark-symbol", - ]) - .conflicts("trademark-office", [ + ]); + rules.conflicts("trademark-office", [ "address1", "agent-name", "agree", @@ -526,14 +584,14 @@ function builder(yargs: Argv) { "reg-who-request-reg-who-requested-data-elements", "reg-who-request-reg-who-requestor-type", "ncsei-subject-representation", - ]) - .implies("trademark-office", [ + ]); + rules.implies("trademark-office", [ "host-notification", "justification", "trademark-number", "trademark-symbol", - ]) - .conflicts("trademark-symbol", [ + ]); + rules.conflicts("trademark-symbol", [ "address1", "agent-name", "agree", @@ -554,14 +612,14 @@ function builder(yargs: Argv) { "reg-who-request-reg-who-requested-data-elements", "reg-who-request-reg-who-requestor-type", "ncsei-subject-representation", - ]) - .implies("trademark-symbol", [ + ]); + rules.implies("trademark-symbol", [ "host-notification", "justification", "trademark-number", "trademark-office", - ]) - .conflicts("destination-ips", [ + ]); + rules.conflicts("destination-ips", [ "address1", "agent-name", "agree", @@ -582,9 +640,9 @@ function builder(yargs: Argv) { "reg-who-request-reg-who-requested-data-elements", "reg-who-request-reg-who-requestor-type", "ncsei-subject-representation", - ]) - .implies("destination-ips", ["host-notification", "justification"]) - .conflicts("ports-protocols", [ + ]); + rules.implies("destination-ips", ["host-notification", "justification"]); + rules.conflicts("ports-protocols", [ "address1", "agent-name", "agree", @@ -605,9 +663,9 @@ function builder(yargs: Argv) { "reg-who-request-reg-who-requested-data-elements", "reg-who-request-reg-who-requestor-type", "ncsei-subject-representation", - ]) - .implies("ports-protocols", ["host-notification", "justification"]) - .conflicts("source-ips", [ + ]); + rules.implies("ports-protocols", ["host-notification", "justification"]); + rules.conflicts("source-ips", [ "address1", "agent-name", "agree", @@ -628,9 +686,9 @@ function builder(yargs: Argv) { "reg-who-request-reg-who-requested-data-elements", "reg-who-request-reg-who-requestor-type", "ncsei-subject-representation", - ]) - .implies("source-ips", ["host-notification", "justification"]) - .conflicts("ncmec-notification", [ + ]); + rules.implies("source-ips", ["host-notification", "justification"]); + rules.conflicts("ncmec-notification", [ "address1", "agent-name", "agree", @@ -652,9 +710,9 @@ function builder(yargs: Argv) { "reg-who-request-reg-who-requested-data-elements", "reg-who-request-reg-who-requestor-type", "ncsei-subject-representation", - ]) - .implies("ncmec-notification", ["host-notification", "justification"]) - .conflicts("reg-who-request-reg-who-authorization-statement", [ + ]); + rules.implies("ncmec-notification", ["host-notification", "justification"]); + rules.conflicts("reg-who-request-reg-who-authorization-statement", [ "address1", "agent-name", "agree", @@ -673,15 +731,15 @@ function builder(yargs: Argv) { "source-ips", "ncmec-notification", "ncsei-subject-representation", - ]) - .implies("reg-who-request-reg-who-authorization-statement", [ + ]); + rules.implies("reg-who-request-reg-who-authorization-statement", [ "reg-who-request-reg-who-good-faith-affirmation", "reg-who-request-reg-who-lawful-processing-agreement", "reg-who-request-reg-who-legal-basis", "reg-who-request-reg-who-request-type", "reg-who-request-reg-who-requested-data-elements", - ]) - .conflicts("reg-who-request-reg-who-good-faith-affirmation", [ + ]); + rules.conflicts("reg-who-request-reg-who-good-faith-affirmation", [ "address1", "agent-name", "agree", @@ -700,14 +758,14 @@ function builder(yargs: Argv) { "source-ips", "ncmec-notification", "ncsei-subject-representation", - ]) - .implies("reg-who-request-reg-who-good-faith-affirmation", [ + ]); + rules.implies("reg-who-request-reg-who-good-faith-affirmation", [ "reg-who-request-reg-who-lawful-processing-agreement", "reg-who-request-reg-who-legal-basis", "reg-who-request-reg-who-request-type", "reg-who-request-reg-who-requested-data-elements", - ]) - .conflicts("reg-who-request-reg-who-lawful-processing-agreement", [ + ]); + rules.conflicts("reg-who-request-reg-who-lawful-processing-agreement", [ "address1", "agent-name", "agree", @@ -726,14 +784,14 @@ function builder(yargs: Argv) { "source-ips", "ncmec-notification", "ncsei-subject-representation", - ]) - .implies("reg-who-request-reg-who-lawful-processing-agreement", [ + ]); + rules.implies("reg-who-request-reg-who-lawful-processing-agreement", [ "reg-who-request-reg-who-good-faith-affirmation", "reg-who-request-reg-who-legal-basis", "reg-who-request-reg-who-request-type", "reg-who-request-reg-who-requested-data-elements", - ]) - .conflicts("reg-who-request-reg-who-legal-basis", [ + ]); + rules.conflicts("reg-who-request-reg-who-legal-basis", [ "address1", "agent-name", "agree", @@ -752,14 +810,14 @@ function builder(yargs: Argv) { "source-ips", "ncmec-notification", "ncsei-subject-representation", - ]) - .implies("reg-who-request-reg-who-legal-basis", [ + ]); + rules.implies("reg-who-request-reg-who-legal-basis", [ "reg-who-request-reg-who-good-faith-affirmation", "reg-who-request-reg-who-lawful-processing-agreement", "reg-who-request-reg-who-request-type", "reg-who-request-reg-who-requested-data-elements", - ]) - .conflicts("reg-who-request-reg-who-request-type", [ + ]); + rules.conflicts("reg-who-request-reg-who-request-type", [ "address1", "agent-name", "agree", @@ -778,14 +836,14 @@ function builder(yargs: Argv) { "source-ips", "ncmec-notification", "ncsei-subject-representation", - ]) - .implies("reg-who-request-reg-who-request-type", [ + ]); + rules.implies("reg-who-request-reg-who-request-type", [ "reg-who-request-reg-who-good-faith-affirmation", "reg-who-request-reg-who-lawful-processing-agreement", "reg-who-request-reg-who-legal-basis", "reg-who-request-reg-who-requested-data-elements", - ]) - .conflicts("reg-who-request-reg-who-requested-data-elements", [ + ]); + rules.conflicts("reg-who-request-reg-who-requested-data-elements", [ "address1", "agent-name", "agree", @@ -804,14 +862,14 @@ function builder(yargs: Argv) { "source-ips", "ncmec-notification", "ncsei-subject-representation", - ]) - .implies("reg-who-request-reg-who-requested-data-elements", [ + ]); + rules.implies("reg-who-request-reg-who-requested-data-elements", [ "reg-who-request-reg-who-good-faith-affirmation", "reg-who-request-reg-who-lawful-processing-agreement", "reg-who-request-reg-who-legal-basis", "reg-who-request-reg-who-request-type", - ]) - .conflicts("reg-who-request-reg-who-requestor-type", [ + ]); + rules.conflicts("reg-who-request-reg-who-requestor-type", [ "address1", "agent-name", "agree", @@ -830,15 +888,15 @@ function builder(yargs: Argv) { "source-ips", "ncmec-notification", "ncsei-subject-representation", - ]) - .implies("reg-who-request-reg-who-requestor-type", [ + ]); + rules.implies("reg-who-request-reg-who-requestor-type", [ "reg-who-request-reg-who-good-faith-affirmation", "reg-who-request-reg-who-lawful-processing-agreement", "reg-who-request-reg-who-legal-basis", "reg-who-request-reg-who-request-type", "reg-who-request-reg-who-requested-data-elements", - ]) - .conflicts("ncsei-subject-representation", [ + ]); + rules.conflicts("ncsei-subject-representation", [ "address1", "agent-name", "agree", @@ -861,607 +919,18 @@ function builder(yargs: Argv) { "reg-who-request-reg-who-request-type", "reg-who-request-reg-who-requested-data-elements", "reg-who-request-reg-who-requestor-type", - ]) - .implies("ncsei-subject-representation", ["host-notification"]); -} - -type Args = InferArgs; - -const command: CommandModule = { + ]); + rules.implies("ncsei-subject-representation", ["host-notification"]); + }, +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Submit an abuse report", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "abuse-reports create", - classification: { - safeFlags: [ - "act", - "host-notification", - "owner-notification", - "ncmec-notification", - "reg-who-request-reg-who-good-faith-affirmation", - "reg-who-request-reg-who-lawful-processing-agreement", - "reg-who-request-reg-who-request-type", - "reg-who-request-reg-who-requestor-type", - "ncsei-subject-representation", - "dry-run", - ], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["act"] === undefined) { - argv["act"] = await promptForRequiredEnumField( - "act", - "The act field", - [ - "abuse_dmca", - "abuse_trademark", - "abuse_general", - "abuse_phishing", - "abuse_children", - "abuse_threat", - "abuse_registrar_whois", - "abuse_ncsei", - ] as const - ); - } - if (argv["email"] === undefined) { - argv["email"] = await promptForRequiredField( - "email", - "A valid email of the abuse reporter. This field may be released by Cloudflare to third parties such as the Lumen Database (https://lumendatabase.org/)." - ); - } - if (argv["email2"] === undefined) { - argv["email2"] = await promptForRequiredField( - "email2", - "Should match the value provided in \`email\`" - ); - } - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "Text not exceeding 255 characters. This field may be released by Cloudflare to third parties such as the Lumen Database (https://lumendatabase.org/)." - ); - } - if (argv["urls"] === undefined) { - argv["urls"] = await promptForRequiredField( - "urls", - "A list of valid URLs separated by ‘\\n’ (new line character). The list of the URLs should not exceed 250 URLs. All URLs should have the same hostname. Each URL should be unique. This field may be released by Cloudflare to third parties such as the Lumen Database (https://lumendatabase.org/)." - ); - } - if (argv["owner-notification"] === undefined) { - argv["owner-notification"] = await promptForRequiredEnumField( - "owner-notification", - "Notification type based on the abuse type. For delegated reports, the report—including contact information and comments—will be forwarded to the customer in full regardless of this value. NOTE: Copyright (DMCA) and Trademark reports cannot be anonymous.", - ["send", "send-anon", "none"] as const - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf abuse-reports create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/abuse-reports/${argv["report-type"] == null ? "" : encodeURIComponent(String(argv["report-type"]))}`, - pathParams: { "report-type": String(argv["report-type"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - act: argv["act"], - comments: resolveFileToken( - argv["comments"] as string | undefined, - "comments", - "text" - ), - company: resolveFileToken( - argv["company"] as string | undefined, - "company", - "text" - ), - email: resolveFileToken( - argv["email"] as string | undefined, - "email", - "text" - ), - email2: resolveFileToken( - argv["email2"] as string | undefined, - "email2", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - reported_country: resolveFileToken( - argv["reported-country"] as string | undefined, - "reported-country", - "text" - ), - reported_user_agent: resolveFileToken( - argv["reported-user-agent"] as string | undefined, - "reported-user-agent", - "text" - ), - tele: resolveFileToken( - argv["tele"] as string | undefined, - "tele", - "text" - ), - title: resolveFileToken( - argv["title"] as string | undefined, - "title", - "text" - ), - urls: resolveFileToken( - argv["urls"] as string | undefined, - "urls", - "text" - ), - address1: resolveFileToken( - argv["address1"] as string | undefined, - "address1", - "text" - ), - agent_name: resolveFileToken( - argv["agent-name"] as string | undefined, - "agent-name", - "text" - ), - agree: argv["agree"], - city: resolveFileToken( - argv["city"] as string | undefined, - "city", - "text" - ), - country: resolveFileToken( - argv["country"] as string | undefined, - "country", - "text" - ), - host_notification: argv["host-notification"], - original_work: resolveFileToken( - argv["original-work"] as string | undefined, - "original-work", - "text" - ), - owner_notification: argv["owner-notification"], - signature: resolveFileToken( - argv["signature"] as string | undefined, - "signature", - "text" - ), - state: resolveFileToken( - argv["state"] as string | undefined, - "state", - "text" - ), - justification: resolveFileToken( - argv["justification"] as string | undefined, - "justification", - "text" - ), - trademark_number: resolveFileToken( - argv["trademark-number"] as string | undefined, - "trademark-number", - "text" - ), - trademark_office: resolveFileToken( - argv["trademark-office"] as string | undefined, - "trademark-office", - "text" - ), - trademark_symbol: resolveFileToken( - argv["trademark-symbol"] as string | undefined, - "trademark-symbol", - "text" - ), - destination_ips: resolveFileToken( - argv["destination-ips"] as string | undefined, - "destination-ips", - "text" - ), - ports_protocols: resolveFileToken( - argv["ports-protocols"] as string | undefined, - "ports-protocols", - "text" - ), - source_ips: resolveFileToken( - argv["source-ips"] as string | undefined, - "source-ips", - "text" - ), - ncmec_notification: argv["ncmec-notification"], - reg_who_request: { - reg_who_authorization_statement: resolveFileToken( - argv[ - "reg-who-request-reg-who-authorization-statement" - ] as string | undefined, - "reg-who-request-reg-who-authorization-statement", - "text" - ), - reg_who_good_faith_affirmation: - argv["reg-who-request-reg-who-good-faith-affirmation"], - reg_who_lawful_processing_agreement: - argv[ - "reg-who-request-reg-who-lawful-processing-agreement" - ], - reg_who_legal_basis: resolveFileToken( - argv["reg-who-request-reg-who-legal-basis"] as - | string - | undefined, - "reg-who-request-reg-who-legal-basis", - "text" - ), - reg_who_request_type: - argv["reg-who-request-reg-who-request-type"], - reg_who_requested_data_elements: - argv["reg-who-request-reg-who-requested-data-elements"], - reg_who_requestor_type: - argv["reg-who-request-reg-who-requestor-type"], - }, - ncsei_subject_representation: - argv["ncsei-subject-representation"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/abuse-reports/${encodeURIComponent(String(argv["report-type"]))}`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData: Record = {}; - if (argv["act"] !== undefined) - setNestedValue(bodyData, ["act"], argv["act"]); - if (argv["comments"] !== undefined) - setNestedValue( - bodyData, - ["comments"], - resolveFileToken( - argv["comments"] as string | undefined, - "comments", - "text" - ) - ); - if (argv["company"] !== undefined) - setNestedValue( - bodyData, - ["company"], - resolveFileToken( - argv["company"] as string | undefined, - "company", - "text" - ) - ); - if (argv["email"] !== undefined) - setNestedValue( - bodyData, - ["email"], - resolveFileToken( - argv["email"] as string | undefined, - "email", - "text" - ) - ); - if (argv["email2"] !== undefined) - setNestedValue( - bodyData, - ["email2"], - resolveFileToken( - argv["email2"] as string | undefined, - "email2", - "text" - ) - ); - if (argv["name"] !== undefined) - setNestedValue( - bodyData, - ["name"], - resolveFileToken(argv["name"] as string | undefined, "name", "text") - ); - if (argv["reported-country"] !== undefined) - setNestedValue( - bodyData, - ["reported_country"], - resolveFileToken( - argv["reported-country"] as string | undefined, - "reported-country", - "text" - ) - ); - if (argv["reported-user-agent"] !== undefined) - setNestedValue( - bodyData, - ["reported_user_agent"], - resolveFileToken( - argv["reported-user-agent"] as string | undefined, - "reported-user-agent", - "text" - ) - ); - if (argv["tele"] !== undefined) - setNestedValue( - bodyData, - ["tele"], - resolveFileToken(argv["tele"] as string | undefined, "tele", "text") - ); - if (argv["title"] !== undefined) - setNestedValue( - bodyData, - ["title"], - resolveFileToken( - argv["title"] as string | undefined, - "title", - "text" - ) - ); - if (argv["urls"] !== undefined) - setNestedValue( - bodyData, - ["urls"], - resolveFileToken(argv["urls"] as string | undefined, "urls", "text") - ); - if (argv["address1"] !== undefined) - setNestedValue( - bodyData, - ["address1"], - resolveFileToken( - argv["address1"] as string | undefined, - "address1", - "text" - ) - ); - if (argv["agent-name"] !== undefined) - setNestedValue( - bodyData, - ["agent_name"], - resolveFileToken( - argv["agent-name"] as string | undefined, - "agent-name", - "text" - ) - ); - if (argv["agree"] !== undefined) - setNestedValue(bodyData, ["agree"], argv["agree"]); - if (argv["city"] !== undefined) - setNestedValue( - bodyData, - ["city"], - resolveFileToken(argv["city"] as string | undefined, "city", "text") - ); - if (argv["country"] !== undefined) - setNestedValue( - bodyData, - ["country"], - resolveFileToken( - argv["country"] as string | undefined, - "country", - "text" - ) - ); - if (argv["host-notification"] !== undefined) - setNestedValue( - bodyData, - ["host_notification"], - argv["host-notification"] - ); - if (argv["original-work"] !== undefined) - setNestedValue( - bodyData, - ["original_work"], - resolveFileToken( - argv["original-work"] as string | undefined, - "original-work", - "text" - ) - ); - if (argv["owner-notification"] !== undefined) - setNestedValue( - bodyData, - ["owner_notification"], - argv["owner-notification"] - ); - if (argv["signature"] !== undefined) - setNestedValue( - bodyData, - ["signature"], - resolveFileToken( - argv["signature"] as string | undefined, - "signature", - "text" - ) - ); - if (argv["state"] !== undefined) - setNestedValue( - bodyData, - ["state"], - resolveFileToken( - argv["state"] as string | undefined, - "state", - "text" - ) - ); - if (argv["justification"] !== undefined) - setNestedValue( - bodyData, - ["justification"], - resolveFileToken( - argv["justification"] as string | undefined, - "justification", - "text" - ) - ); - if (argv["trademark-number"] !== undefined) - setNestedValue( - bodyData, - ["trademark_number"], - resolveFileToken( - argv["trademark-number"] as string | undefined, - "trademark-number", - "text" - ) - ); - if (argv["trademark-office"] !== undefined) - setNestedValue( - bodyData, - ["trademark_office"], - resolveFileToken( - argv["trademark-office"] as string | undefined, - "trademark-office", - "text" - ) - ); - if (argv["trademark-symbol"] !== undefined) - setNestedValue( - bodyData, - ["trademark_symbol"], - resolveFileToken( - argv["trademark-symbol"] as string | undefined, - "trademark-symbol", - "text" - ) - ); - if (argv["destination-ips"] !== undefined) - setNestedValue( - bodyData, - ["destination_ips"], - resolveFileToken( - argv["destination-ips"] as string | undefined, - "destination-ips", - "text" - ) - ); - if (argv["ports-protocols"] !== undefined) - setNestedValue( - bodyData, - ["ports_protocols"], - resolveFileToken( - argv["ports-protocols"] as string | undefined, - "ports-protocols", - "text" - ) - ); - if (argv["source-ips"] !== undefined) - setNestedValue( - bodyData, - ["source_ips"], - resolveFileToken( - argv["source-ips"] as string | undefined, - "source-ips", - "text" - ) - ); - if (argv["ncmec-notification"] !== undefined) - setNestedValue( - bodyData, - ["ncmec_notification"], - argv["ncmec-notification"] - ); - if ( - argv["reg-who-request-reg-who-authorization-statement"] !== undefined - ) - setNestedValue( - bodyData, - ["reg_who_request", "reg_who_authorization_statement"], - resolveFileToken( - argv["reg-who-request-reg-who-authorization-statement"] as - | string - | undefined, - "reg-who-request-reg-who-authorization-statement", - "text" - ) - ); - if ( - argv["reg-who-request-reg-who-good-faith-affirmation"] !== undefined - ) - setNestedValue( - bodyData, - ["reg_who_request", "reg_who_good_faith_affirmation"], - argv["reg-who-request-reg-who-good-faith-affirmation"] - ); - if ( - argv["reg-who-request-reg-who-lawful-processing-agreement"] !== - undefined - ) - setNestedValue( - bodyData, - ["reg_who_request", "reg_who_lawful_processing_agreement"], - argv["reg-who-request-reg-who-lawful-processing-agreement"] - ); - if (argv["reg-who-request-reg-who-legal-basis"] !== undefined) - setNestedValue( - bodyData, - ["reg_who_request", "reg_who_legal_basis"], - resolveFileToken( - argv["reg-who-request-reg-who-legal-basis"] as string | undefined, - "reg-who-request-reg-who-legal-basis", - "text" - ) - ); - if (argv["reg-who-request-reg-who-request-type"] !== undefined) - setNestedValue( - bodyData, - ["reg_who_request", "reg_who_request_type"], - argv["reg-who-request-reg-who-request-type"] - ); - if ( - argv["reg-who-request-reg-who-requested-data-elements"] !== undefined - ) - setNestedValue( - bodyData, - ["reg_who_request", "reg_who_requested_data_elements"], - argv["reg-who-request-reg-who-requested-data-elements"] - ); - if (argv["reg-who-request-reg-who-requestor-type"] !== undefined) - setNestedValue( - bodyData, - ["reg_who_request", "reg_who_requestor_type"], - argv["reg-who-request-reg-who-requestor-type"] - ); - if (argv["ncsei-subject-representation"] !== undefined) - setNestedValue( - bodyData, - ["ncsei_subject_representation"], - argv["ncsei-subject-representation"] - ); - const result = await withProgress(`Creating`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/abuse-reports/${encodeURIComponent(String(argv["report-type"]))}`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 abuse-reports create \n\nSubmit an abuse report of a particular type. Requires the abuse-reports entitlement on the account (Enterprise accounts have it by default; other accounts must request access) and an API token with the `Trust and Safety Write` permission. If the account is not entitled, the request is rejected with an HTTP `401` response (see below). Delegated reports: In limited circumstances, Cloudflare delegates processing of abuse reports to select customers who have established abuse-handling programs. For these customers, Cloudflare may forward abuse reports directly and in full—including reporter contact information, comments, and supporting evidence—without redaction or preprocessing by Cloudflare. This allows the customer to investigate and respond using their own policies and processes. For delegated reports, the report—including contact information and comments—will be forwarded to the customer in full regardless of the `host_notification` and `owner_notification` values.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/abuse-reports/emails/index.ts b/packages/cli/src/commands/_generated/abuse-reports/emails/index.ts index 93b43d08b1..be85f2fb38 100644 --- a/packages/cli/src/commands/_generated/abuse-reports/emails/index.ts +++ b/packages/cli/src/commands/_generated/abuse-reports/emails/index.ts @@ -1,24 +1,19 @@ import $listsubmitted from "./list-submitted.js"; import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * emails command group * @generated from apis/overlays/abuse-reports.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "emails", describe: "Emails sent for abuse reports", - builder: (yargs) => { - return yargs - .command($list) - .command($listsubmitted) - .demandCommand(1, "Please specify a subcommand"); + routes: { + list: $list, + "list-submitted": $listsubmitted, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/abuse-reports/emails/list-submitted.handler.ts b/packages/cli/src/commands/_generated/abuse-reports/emails/list-submitted.handler.ts new file mode 100644 index 0000000000..c28750706f --- /dev/null +++ b/packages/cli/src/commands/_generated/abuse-reports/emails/list-submitted.handler.ts @@ -0,0 +1,55 @@ +import operation from "../../_operations/abuse-reports/emails/list-submitted.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list-submitted.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "abuse-reports emails list-submitted", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf abuse-reports emails list-submitted", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/abuse-reports/submitted/${argv["report-id"] == null ? "" : encodeURIComponent(String(argv["report-id"]))}/emails`, + pathParams: { "report-id": String(argv["report-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + report_id: argv["report-id"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/abuse-reports/emails/list-submitted.ts b/packages/cli/src/commands/_generated/abuse-reports/emails/list-submitted.ts index cd4ebe1e26..820ac7663c 100644 --- a/packages/cli/src/commands/_generated/abuse-reports/emails/list-submitted.ts +++ b/packages/cli/src/commands/_generated/abuse-reports/emails/list-submitted.ts @@ -1,93 +1,45 @@ -import operation from "../../_operations/abuse-reports/emails/list-submitted.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list-submitted command * @generated from apis/overlays/abuse-reports.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 abuse-reports emails list-submitted \n\nList successful emails sent to the submitter of a report submitted by the account. Does not include emails sent to customers or hosts." - ) - .positional("report-id", { - type: "string", - description: "Public report code.", - demandOption: true, - }) - .option("page", { - type: "number", - description: "Page number to retrieve (default 1).", - }) - .option("per-page", { - type: "number", - description: "Number of emails per page (default 20, max 100).", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + page: { + kind: "parsed", + brief: "Page number to retrieve (default 1).", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Number of emails per page (default 20, max 100).", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "report-id", brief: "Public report code.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list-submitted ", describe: "List emails sent to an abuse report submitter", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "abuse-reports emails list-submitted", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf abuse-reports emails list-submitted", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/abuse-reports/submitted/${argv["report-id"] == null ? "" : encodeURIComponent(String(argv["report-id"]))}/emails`, - pathParams: { "report-id": String(argv["report-id"] ?? "") }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - report_id: argv["report-id"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 abuse-reports emails list-submitted \n\nList successful emails sent to the submitter of a report submitted by the account. Does not include emails sent to customers or hosts.", + ...parameters, + loader: () => import("./list-submitted.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/abuse-reports/emails/list.handler.ts b/packages/cli/src/commands/_generated/abuse-reports/emails/list.handler.ts new file mode 100644 index 0000000000..eb7526963d --- /dev/null +++ b/packages/cli/src/commands/_generated/abuse-reports/emails/list.handler.ts @@ -0,0 +1,55 @@ +import operation from "../../_operations/abuse-reports/emails/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "abuse-reports emails list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf abuse-reports emails list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/abuse-reports/${argv["report-id"] == null ? "" : encodeURIComponent(String(argv["report-id"]))}/emails`, + pathParams: { "report-id": String(argv["report-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + report_id: argv["report-id"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/abuse-reports/emails/list.ts b/packages/cli/src/commands/_generated/abuse-reports/emails/list.ts index 194f415fe5..b8b4c3a51a 100644 --- a/packages/cli/src/commands/_generated/abuse-reports/emails/list.ts +++ b/packages/cli/src/commands/_generated/abuse-reports/emails/list.ts @@ -1,93 +1,44 @@ -import operation from "../../_operations/abuse-reports/emails/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/abuse-reports.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 abuse-reports emails list\n\nList emails sent to the customer for an abuse report. Returns all successful customer emails sent for the specified abuse report. Does not include emails sent to hosts or submitters." - ) - .option("report-id", { - type: "string", - description: "Abuse Report ID", - demandOption: true, - }) - .option("page", { - type: "number", - description: "Page number to retrieve (default 1)", - }) - .option("per-page", { - type: "number", - description: "Number of emails per page (default 20, max 100)", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "report-id": { kind: "parsed", brief: "Abuse Report ID", parse: String }, + page: { + kind: "parsed", + brief: "Page number to retrieve (default 1)", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Number of emails per page (default 20, max 100)", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List abuse report emails", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "abuse-reports emails list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf abuse-reports emails list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/abuse-reports/${argv["report-id"] == null ? "" : encodeURIComponent(String(argv["report-id"]))}/emails`, - pathParams: { "report-id": String(argv["report-id"] ?? "") }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - report_id: argv["report-id"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 abuse-reports emails list\n\nList emails sent to the customer for an abuse report. Returns all successful customer emails sent for the specified abuse report. Does not include emails sent to hosts or submitters.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/abuse-reports/get-submitted.handler.ts b/packages/cli/src/commands/_generated/abuse-reports/get-submitted.handler.ts new file mode 100644 index 0000000000..5f946c0ada --- /dev/null +++ b/packages/cli/src/commands/_generated/abuse-reports/get-submitted.handler.ts @@ -0,0 +1,49 @@ +import operation from "../_operations/abuse-reports/get-submitted.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get-submitted.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "abuse-reports get-submitted", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf abuse-reports get-submitted", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/abuse-reports/submitted/${argv["report-id"] == null ? "" : encodeURIComponent(String(argv["report-id"]))}`, + pathParams: { "report-id": String(argv["report-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + report_id: argv["report-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/abuse-reports/get-submitted.ts b/packages/cli/src/commands/_generated/abuse-reports/get-submitted.ts index 693cb10f75..a6cb36330e 100644 --- a/packages/cli/src/commands/_generated/abuse-reports/get-submitted.ts +++ b/packages/cli/src/commands/_generated/abuse-reports/get-submitted.ts @@ -1,79 +1,33 @@ -import operation from "../_operations/abuse-reports/get-submitted.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get-submitted command * @generated from apis/overlays/abuse-reports.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 abuse-reports get-submitted \n\nRetrieve a report submitted by the account." - ) - .positional("report-id", { - type: "string", - description: "Public report code.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "report-id", brief: "Public report code.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get-submitted ", describe: "Get a submitted abuse report", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "abuse-reports get-submitted", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf abuse-reports get-submitted", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/abuse-reports/submitted/${argv["report-id"] == null ? "" : encodeURIComponent(String(argv["report-id"]))}`, - pathParams: { "report-id": String(argv["report-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - report_id: argv["report-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 abuse-reports get-submitted \n\nRetrieve a report submitted by the account.", + ...parameters, + loader: () => import("./get-submitted.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/abuse-reports/get.handler.ts b/packages/cli/src/commands/_generated/abuse-reports/get.handler.ts new file mode 100644 index 0000000000..949f679a9b --- /dev/null +++ b/packages/cli/src/commands/_generated/abuse-reports/get.handler.ts @@ -0,0 +1,50 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "abuse-reports get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf abuse-reports get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/abuse-reports/${argv["report-id"] == null ? "" : encodeURIComponent(String(argv["report-id"]))}`, + pathParams: { "report-id": String(argv["report-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + requestApi( + client, + "GET", + `/accounts/${accountId}/abuse-reports/${encodeURIComponent(String(argv["report-id"]))}` + ) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/abuse-reports/get.ts b/packages/cli/src/commands/_generated/abuse-reports/get.ts index 20e9a34d59..38e8b8e3e8 100644 --- a/packages/cli/src/commands/_generated/abuse-reports/get.ts +++ b/packages/cli/src/commands/_generated/abuse-reports/get.ts @@ -1,80 +1,33 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/abuse-reports.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 abuse-reports get \n\nRetrieve the details of an abuse report made against a domain or other content associated with the account. To retrieve a report that the account submitted, use the submitted abuse report endpoint instead." - ) - .positional("report-id", { - type: "string", - description: "Public report ID.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "report-id", brief: "Public report ID.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get an abuse report against the account", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "abuse-reports get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf abuse-reports get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/abuse-reports/${argv["report-id"] == null ? "" : encodeURIComponent(String(argv["report-id"]))}`, - pathParams: { "report-id": String(argv["report-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - requestApi( - client, - "GET", - `/accounts/${accountId}/abuse-reports/${encodeURIComponent(String(argv["report-id"]))}` - ) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 abuse-reports get \n\nRetrieve the details of an abuse report made against a domain or other content associated with the account. To retrieve a report that the account submitted, use the submitted abuse report endpoint instead.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/abuse-reports/index.ts b/packages/cli/src/commands/_generated/abuse-reports/index.ts index 72b6eaaae5..f8bccab6a2 100644 --- a/packages/cli/src/commands/_generated/abuse-reports/index.ts +++ b/packages/cli/src/commands/_generated/abuse-reports/index.ts @@ -6,32 +6,27 @@ import $get from "./get.js"; import $listsubmitted from "./list-submitted.js"; import $list from "./list.js"; import $mitigations from "./mitigations/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * abuse-reports command * @generated from apis/overlays/abuse-reports.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "abuse-reports", describe: "Submit and track abuse reports for phishing, malware, and other policy violations on Cloudflare-proxied sites", - builder: (yargs) => { - return yargs - .command($create) - .command($get) - .command($getsubmitted) - .command($list) - .command($listsubmitted) - .command($appeals) - .command($emails) - .command($mitigations) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + get: $get, + "get-submitted": $getsubmitted, + list: $list, + "list-submitted": $listsubmitted, + appeals: $appeals, + emails: $emails, + mitigations: $mitigations, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/abuse-reports/list-submitted.handler.ts b/packages/cli/src/commands/_generated/abuse-reports/list-submitted.handler.ts new file mode 100644 index 0000000000..6542ab649e --- /dev/null +++ b/packages/cli/src/commands/_generated/abuse-reports/list-submitted.handler.ts @@ -0,0 +1,58 @@ +import operation from "../_operations/abuse-reports/list-submitted.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list-submitted.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "abuse-reports list-submitted", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + sort: argv["sort"], + id: argv["id"], + domain: argv["domain"], + created_before: argv["created-before"], + created_after: argv["created-after"], + status: argv["status"], + type: argv["type"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf abuse-reports list-submitted", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/abuse-reports/submitted`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/abuse-reports/list-submitted.ts b/packages/cli/src/commands/_generated/abuse-reports/list-submitted.ts index d615fe1e2b..651b437729 100644 --- a/packages/cli/src/commands/_generated/abuse-reports/list-submitted.ts +++ b/packages/cli/src/commands/_generated/abuse-reports/list-submitted.ts @@ -1,70 +1,76 @@ -import operation from "../_operations/abuse-reports/list-submitted.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list-submitted command * @generated from apis/overlays/abuse-reports.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 abuse-reports list-submitted\n\nList abuse reports submitted by the account." - ) - .option("page", { - type: "number", - description: "Page of submitted reports to return.", - }) - .option("per-page", { - type: "number", - description: "Number of submitted reports per page.", - }) - .option("sort", { - type: "string", - description: +const parameters = { + flags: { + page: { + kind: "parsed", + brief: "Page of submitted reports to return.", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Number of submitted reports per page.", + optional: true, + parse: Number, + }, + sort: { + kind: "parsed", + brief: "A property and direction to sort by (id, cdate, domain, type, status).", - }) - .option("id", { type: "string", description: "Filter by report code." }) - .option("domain", { - type: "string", - array: true, - description: + optional: true, + parse: String, + }, + id: { + kind: "parsed", + brief: "Filter by report code.", + optional: true, + parse: String, + }, + domain: { + kind: "parsed", + brief: "Filter by reported domain. This parameter can be specified multiple times.", - }) - .option("created-before", { - type: "string", - description: "Return reports submitted before this time.", - }) - .option("created-after", { - type: "string", - description: "Return reports submitted after this time.", - }) - .option("status", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + "created-before": { + kind: "parsed", + brief: "Return reports submitted before this time.", + optional: true, + parse: String, + }, + "created-after": { + kind: "parsed", + brief: "Return reports submitted after this time.", + optional: true, + parse: String, + }, + status: { + kind: "parsed", + brief: "Filter by submitter-facing status. This parameter can be specified multiple times.", + variadic: true, + optional: true, choices: ["submitted", "accepted", "denied"], - }) - .coerce("status", (values: string[]) => - values.flatMap((value) => value.split(",")) - ) - .option("type", { - type: "string", - array: true, - description: + parse: String, + coerce: (values: string[]) => values.flatMap((value) => value.split(",")), + }, + type: { + kind: "parsed", + brief: "Filter by report type. This parameter can be specified multiple times.", + variadic: true, + optional: true, choices: [ "PHISH", "GEN", @@ -76,66 +82,25 @@ function builder(yargs: Argv) { "NCSEI", "NETWORK", ], - }) - .coerce("type", (values: string[]) => - values.flatMap((value) => value.split(",")) - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (values: string[]) => values.flatMap((value) => value.split(",")), + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list-submitted", describe: "List submitted abuse reports", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "abuse-reports list-submitted", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - sort: argv["sort"], - id: argv["id"], - domain: argv["domain"], - created_before: argv["created-before"], - created_after: argv["created-after"], - status: argv["status"], - type: argv["type"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf abuse-reports list-submitted", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/abuse-reports/submitted`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 abuse-reports list-submitted\n\nList abuse reports submitted by the account.", + ...parameters, + loader: () => import("./list-submitted.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/abuse-reports/list.handler.ts b/packages/cli/src/commands/_generated/abuse-reports/list.handler.ts new file mode 100644 index 0000000000..56abbc8459 --- /dev/null +++ b/packages/cli/src/commands/_generated/abuse-reports/list.handler.ts @@ -0,0 +1,66 @@ +import operation from "../_operations/abuse-reports/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "abuse-reports list", + classification: { + safeFlags: [ + "status", + "type", + "mitigation-status", + "pending-notice", + "dry-run", + ], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + sort: argv["sort"], + search: argv["search"], + domain: argv["domain"], + created_before: argv["created-before"], + created_after: argv["created-after"], + status: argv["status"], + type: argv["type"], + mitigation_status: argv["mitigation-status"], + pending_notice: argv["pending-notice"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf abuse-reports list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/abuse-reports`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/abuse-reports/list.ts b/packages/cli/src/commands/_generated/abuse-reports/list.ts index 423176976b..83635185a1 100644 --- a/packages/cli/src/commands/_generated/abuse-reports/list.ts +++ b/packages/cli/src/commands/_generated/abuse-reports/list.ts @@ -1,66 +1,69 @@ -import operation from "../_operations/abuse-reports/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/abuse-reports.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 abuse-reports list\n\nList abuse reports made against domains or other content associated with the account. To list reports that the account submitted, use the submitted abuse reports endpoint instead." - ) - .option("page", { - type: "number", - description: "Where in pagination to start listing abuse reports", - }) - .option("per-page", { - type: "number", - description: "How many abuse reports per page to list", - }) - .option("sort", { - type: "string", - description: +const parameters = { + flags: { + page: { + kind: "parsed", + brief: "Where in pagination to start listing abuse reports", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "How many abuse reports per page to list", + optional: true, + parse: Number, + }, + sort: { + kind: "parsed", + brief: "A property to sort by, followed by the order (id, cdate, domain, type, status)", - }) - .option("search", { - type: "string", - description: + optional: true, + parse: String, + }, + search: { + kind: "parsed", + brief: "Free-text search. Returns reports whose report ID starts with the term or whose domain contains the term, both case-insensitively. Surrounding whitespace is ignored, and an empty value is treated as absent. Combined with the other filters using AND.", - }) - .option("domain", { - type: "string", - description: "Filter by domain name related to the abuse report", - }) - .option("created-before", { - type: "string", - description: "Returns reports created before the specified date", - }) - .option("created-after", { - type: "string", - description: "Returns reports created after the specified date", - }) - .option("status", { - type: "string", - description: "Filter by the status of the report.", - choices: ["accepted", "in_review"], - }) - .option("type", { - type: "string", - description: "Filter by the type of the report.", - choices: [ + optional: true, + parse: String, + }, + domain: { + kind: "parsed", + brief: "Filter by domain name related to the abuse report", + optional: true, + parse: String, + }, + "created-before": { + kind: "parsed", + brief: "Returns reports created before the specified date", + optional: true, + parse: String, + }, + "created-after": { + kind: "parsed", + brief: "Returns reports created after the specified date", + optional: true, + parse: String, + }, + status: { + kind: "enum", + brief: "Filter by the status of the report.", + values: ["accepted", "in_review"], + optional: true, + }, + type: { + kind: "enum", + brief: "Filter by the type of the report.", + values: [ "PHISH", "GEN", "THREAT", @@ -71,82 +74,36 @@ function builder(yargs: Argv) { "NCSEI", "NETWORK", ], - }) - .option("mitigation-status", { - type: "string", - description: - "Filter reports that have any mitigations in the given status.", - choices: ["pending", "active", "in_review", "cancelled", "removed"], - }) - .option("pending-notice", { - type: "boolean", - description: + optional: true, + }, + "mitigation-status": { + kind: "enum", + brief: "Filter reports that have any mitigations in the given status.", + values: ["pending", "active", "in_review", "cancelled", "removed"], + optional: true, + }, + "pending-notice": { + kind: "boolean", + brief: "Also include reports in an open Notice and Takedown notice period. Combined with mitigation_status using OR, e.g. ?mitigation_status=active&pending_notice=true.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List abuse reports against the account", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "abuse-reports list", - classification: { - safeFlags: [ - "status", - "type", - "mitigation-status", - "pending-notice", - "dry-run", - ], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - sort: argv["sort"], - search: argv["search"], - domain: argv["domain"], - created_before: argv["created-before"], - created_after: argv["created-after"], - status: argv["status"], - type: argv["type"], - mitigation_status: argv["mitigation-status"], - pending_notice: argv["pending-notice"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf abuse-reports list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/abuse-reports`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 abuse-reports list\n\nList abuse reports made against domains or other content associated with the account. To list reports that the account submitted, use the submitted abuse reports endpoint instead.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/abuse-reports/mitigations/index.ts b/packages/cli/src/commands/_generated/abuse-reports/mitigations/index.ts index c06d993e61..ce965534cb 100644 --- a/packages/cli/src/commands/_generated/abuse-reports/mitigations/index.ts +++ b/packages/cli/src/commands/_generated/abuse-reports/mitigations/index.ts @@ -1,24 +1,19 @@ import $list from "./list.js"; import $review from "./review.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * mitigations command group * @generated from apis/overlays/abuse-reports.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "mitigations", describe: "Mitigation actions taken in response to abuse reports", - builder: (yargs) => { - return yargs - .command($list) - .command($review) - .demandCommand(1, "Please specify a subcommand"); + routes: { + list: $list, + review: $review, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/abuse-reports/mitigations/list.handler.ts b/packages/cli/src/commands/_generated/abuse-reports/mitigations/list.handler.ts new file mode 100644 index 0000000000..ec71f1918a --- /dev/null +++ b/packages/cli/src/commands/_generated/abuse-reports/mitigations/list.handler.ts @@ -0,0 +1,61 @@ +import operation from "../../_operations/abuse-reports/mitigations/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "abuse-reports mitigations list", + classification: { + safeFlags: ["sort", "status", "entity-type", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + sort: argv["sort"], + type: argv["type"], + effective_before: argv["effective-before"], + effective_after: argv["effective-after"], + status: argv["status"], + entity_type: argv["entity-type"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf abuse-reports mitigations list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/abuse-reports/${argv["report-id"] == null ? "" : encodeURIComponent(String(argv["report-id"]))}/mitigations`, + pathParams: { "report-id": String(argv["report-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + report_id: argv["report-id"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/abuse-reports/mitigations/list.ts b/packages/cli/src/commands/_generated/abuse-reports/mitigations/list.ts index 4d2ab8f47f..3477350da2 100644 --- a/packages/cli/src/commands/_generated/abuse-reports/mitigations/list.ts +++ b/packages/cli/src/commands/_generated/abuse-reports/mitigations/list.ts @@ -1,44 +1,32 @@ -import operation from "../../_operations/abuse-reports/mitigations/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/abuse-reports.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 abuse-reports mitigations list\n\nList mitigations done to remediate the abuse report." - ) - .option("report-id", { - type: "string", - description: "Abuse Report ID", - demandOption: true, - }) - .option("page", { - type: "number", - description: "Where in pagination to start listing abuse reports", - }) - .option("per-page", { - type: "number", - description: "How many abuse reports per page to list", - }) - .option("sort", { - type: "string", - description: "A property to sort by, followed by the order", - choices: [ +const parameters = { + flags: { + "report-id": { kind: "parsed", brief: "Abuse Report ID", parse: String }, + page: { + kind: "parsed", + brief: "Where in pagination to start listing abuse reports", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "How many abuse reports per page to list", + optional: true, + parse: Number, + }, + sort: { + kind: "enum", + brief: "A property to sort by, followed by the order", + values: [ "type,asc", "type,desc", "effective_date,asc", @@ -48,97 +36,55 @@ function builder(yargs: Argv) { "entity_type,asc", "entity_type,desc", ], - }) - .option("type", { - type: "string", - description: + optional: true, + }, + type: { + kind: "parsed", + brief: "Filter by the type of mitigation. This filter parameter can be specified multiple times to include multiple types of mitigations in the result set.", - }) - .option("effective-before", { - type: "string", - description: - "Returns mitigations that were dispatched before the given date", - }) - .option("effective-after", { - type: "string", - description: - "Returns mitigation that were dispatched after the given date", - }) - .option("status", { - type: "string", - description: "Filter by the status of the mitigation.", - choices: ["pending", "active", "in_review", "cancelled", "removed"], - }) - .option("entity-type", { - type: "string", - description: "Filter by the type of entity the mitigation impacts.", - choices: [ - "url_pattern", - "account", - "zone", - "domain", - "custom_expression", - ], - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "effective-before": { + kind: "parsed", + brief: "Returns mitigations that were dispatched before the given date", + optional: true, + parse: String, + }, + "effective-after": { + kind: "parsed", + brief: "Returns mitigation that were dispatched after the given date", + optional: true, + parse: String, + }, + status: { + kind: "enum", + brief: "Filter by the status of the mitigation.", + values: ["pending", "active", "in_review", "cancelled", "removed"], + optional: true, + }, + "entity-type": { + kind: "enum", + brief: "Filter by the type of entity the mitigation impacts.", + values: ["url_pattern", "account", "zone", "domain", "custom_expression"], + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List abuse report mitigations", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "abuse-reports mitigations list", - classification: { - safeFlags: ["sort", "status", "entity-type", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - sort: argv["sort"], - type: argv["type"], - effective_before: argv["effective-before"], - effective_after: argv["effective-after"], - status: argv["status"], - entity_type: argv["entity-type"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf abuse-reports mitigations list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/abuse-reports/${argv["report-id"] == null ? "" : encodeURIComponent(String(argv["report-id"]))}/mitigations`, - pathParams: { "report-id": String(argv["report-id"] ?? "") }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - report_id: argv["report-id"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 abuse-reports mitigations list\n\nList mitigations done to remediate the abuse report.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/abuse-reports/mitigations/review.handler.ts b/packages/cli/src/commands/_generated/abuse-reports/mitigations/review.handler.ts new file mode 100644 index 0000000000..be64e63744 --- /dev/null +++ b/packages/cli/src/commands/_generated/abuse-reports/mitigations/review.handler.ts @@ -0,0 +1,216 @@ +import operation from "../../_operations/abuse-reports/mitigations/review.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./review.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "abuse-reports mitigations review", + classification: { + safeFlags: [ + "data-jurisdiction-consent", + "data-perjury-attestation", + "type", + "dry-run", + ], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf abuse-reports mitigations review", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/abuse-reports/${argv["report-id"] == null ? "" : encodeURIComponent(String(argv["report-id"]))}/mitigations/appeal`, + pathParams: { "report-id": String(argv["report-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + appeals: parseObjectArray(argv["appeals"], "appeals"), + data: { + city: resolveFileToken( + argv["data-city"] as string | undefined, + "data-city", + "text" + ), + company: resolveFileToken( + argv["data-company"] as string | undefined, + "data-company", + "text" + ), + counter_notice_response: resolveFileToken( + argv["data-counter-notice-response"] as + | string + | undefined, + "data-counter-notice-response", + "text" + ), + country: resolveFileToken( + argv["data-country"] as string | undefined, + "data-country", + "text" + ), + email: resolveFileToken( + argv["data-email"] as string | undefined, + "data-email", + "text" + ), + full_name: resolveFileToken( + argv["data-full-name"] as string | undefined, + "data-full-name", + "text" + ), + jurisdiction_consent: argv["data-jurisdiction-consent"], + perjury_attestation: argv["data-perjury-attestation"], + phone_number: resolveFileToken( + argv["data-phone-number"] as string | undefined, + "data-phone-number", + "text" + ), + signature: resolveFileToken( + argv["data-signature"] as string | undefined, + "data-signature", + "text" + ), + state: resolveFileToken( + argv["data-state"] as string | undefined, + "data-state", + "text" + ), + street_address: resolveFileToken( + argv["data-street-address"] as string | undefined, + "data-street-address", + "text" + ), + urls: argv["data-urls"], + zip_code: resolveFileToken( + argv["data-zip-code"] as string | undefined, + "data-zip-code", + "text" + ), + }, + explanation: resolveFileToken( + argv["explanation"] as string | undefined, + "explanation", + "text" + ), + type: argv["type"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + report_id: argv["report-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + appeals: parseObjectArray(argv["appeals"], "appeals"), + data: { + city: resolveFileToken( + argv["data-city"] as string | undefined, + "data-city", + "text" + ), + company: resolveFileToken( + argv["data-company"] as string | undefined, + "data-company", + "text" + ), + counter_notice_response: resolveFileToken( + argv["data-counter-notice-response"] as string | undefined, + "data-counter-notice-response", + "text" + ), + country: resolveFileToken( + argv["data-country"] as string | undefined, + "data-country", + "text" + ), + email: resolveFileToken( + argv["data-email"] as string | undefined, + "data-email", + "text" + ), + full_name: resolveFileToken( + argv["data-full-name"] as string | undefined, + "data-full-name", + "text" + ), + jurisdiction_consent: argv["data-jurisdiction-consent"], + perjury_attestation: argv["data-perjury-attestation"], + phone_number: resolveFileToken( + argv["data-phone-number"] as string | undefined, + "data-phone-number", + "text" + ), + signature: resolveFileToken( + argv["data-signature"] as string | undefined, + "data-signature", + "text" + ), + state: resolveFileToken( + argv["data-state"] as string | undefined, + "data-state", + "text" + ), + street_address: resolveFileToken( + argv["data-street-address"] as string | undefined, + "data-street-address", + "text" + ), + urls: argv["data-urls"], + zip_code: resolveFileToken( + argv["data-zip-code"] as string | undefined, + "data-zip-code", + "text" + ), + }, + explanation: resolveFileToken( + argv["explanation"] as string | undefined, + "explanation", + "text" + ), + type: argv["type"], + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + report_id: argv["report-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/abuse-reports/mitigations/review.ts b/packages/cli/src/commands/_generated/abuse-reports/mitigations/review.ts index 387c6b86fd..a0aa955d33 100644 --- a/packages/cli/src/commands/_generated/abuse-reports/mitigations/review.ts +++ b/packages/cli/src/commands/_generated/abuse-reports/mitigations/review.ts @@ -1,115 +1,139 @@ -import operation from "../../_operations/abuse-reports/mitigations/review.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * review command * @generated from apis/overlays/abuse-reports.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 abuse-reports mitigations review \n\nRequest a review of mitigations applied because of an abuse report, or submit a report-level appeal. - To request a review of specific mitigations, send `appeals` with the mitigation IDs and reasons. Repeating a request for a mitigation with an unresolved appeal is idempotent and returns that mitigation in the in-review state. - To submit a report-level appeal, send `type` and, for a `counter_notice`, the counter-notice details in `data`. Report-level appeals are currently available only for DMCA (copyright) reports." - ) - .positional("report-id", { - type: "string", - description: "Abuse Report ID", - demandOption: true, - }) - .option("appeals", { - type: "string", - description: +const parameters = { + flags: { + appeals: { + kind: "parsed", + brief: 'List of mitigations to appeal. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"id": string, "reason": "removed" | "misclassified"}].', - }) - .option("data-city", { type: "string", description: "The data.city field" }) - .option("data-company", { - type: "string", - description: "The data.company field", - }) - .option("data-counter-notice-response", { - type: "string", - description: "The data.counter_notice_response field", - }) - .option("data-country", { - type: "string", - description: "The data.country field", - }) - .option("data-email", { - type: "string", - description: "The data.email field", - }) - .option("data-full-name", { - type: "string", - description: "The data.full_name field", - }) - .option("data-jurisdiction-consent", { - type: "boolean", - description: "The data.jurisdiction_consent field", - }) - .option("data-perjury-attestation", { - type: "boolean", - description: "The data.perjury_attestation field", - }) - .option("data-phone-number", { - type: "string", - description: "The data.phone_number field", - }) - .option("data-signature", { - type: "string", - description: "The data.signature field", - }) - .option("data-state", { - type: "string", - description: "The data.state field", - }) - .option("data-street-address", { - type: "string", - description: "The data.street_address field", - }) - .option("data-urls", { - type: "string", - array: true, - description: "The data.urls field", - }) - .option("data-zip-code", { - type: "string", - description: "The data.zip_code field", - }) - .option("explanation", { - type: "string", - description: + optional: true, + parse: String, + }, + "data-city": { + kind: "parsed", + brief: "The data.city field", + optional: true, + parse: String, + }, + "data-company": { + kind: "parsed", + brief: "The data.company field", + optional: true, + parse: String, + }, + "data-counter-notice-response": { + kind: "parsed", + brief: "The data.counter_notice_response field", + optional: true, + parse: String, + }, + "data-country": { + kind: "parsed", + brief: "The data.country field", + optional: true, + parse: String, + }, + "data-email": { + kind: "parsed", + brief: "The data.email field", + optional: true, + parse: String, + }, + "data-full-name": { + kind: "parsed", + brief: "The data.full_name field", + optional: true, + parse: String, + }, + "data-jurisdiction-consent": { + kind: "boolean", + brief: "The data.jurisdiction_consent field", + optional: true, + }, + "data-perjury-attestation": { + kind: "boolean", + brief: "The data.perjury_attestation field", + optional: true, + }, + "data-phone-number": { + kind: "parsed", + brief: "The data.phone_number field", + optional: true, + parse: String, + }, + "data-signature": { + kind: "parsed", + brief: "The data.signature field", + optional: true, + parse: String, + }, + "data-state": { + kind: "parsed", + brief: "The data.state field", + optional: true, + parse: String, + }, + "data-street-address": { + kind: "parsed", + brief: "The data.street_address field", + optional: true, + parse: String, + }, + "data-urls": { + kind: "parsed", + brief: "The data.urls field", + variadic: true, + optional: true, + parse: String, + }, + "data-zip-code": { + kind: "parsed", + brief: "The data.zip_code field", + optional: true, + parse: String, + }, + explanation: { + kind: "parsed", + brief: 'Optional explanation for a "content_removed" appeal, such as how the content was removed. Not accepted for other appeal types.', - }) - .option("type", { - type: "string", - description: "The type of appeal being submitted.", + optional: true, + parse: String, + }, + type: { + kind: "parsed", + brief: "The type of appeal being submitted.", + optional: true, choices: ["counter_notice", "content_removed"], - }) - .coerce("type", (value) => resolveFileToken(value, "type", "text")) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => resolveFileToken(value, "type", "text"), + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: - 'Submit an appeal for a report. Provide either a list of mitigations to appeal, or an appeal type with its supporting details, but not both. When type is "counter_notice", the counter-notice details are required. A "content_removed" appeal takes an optional explanation instead and is accepted only while the report is in its Notice and Takedown notice period (\`has_pending_notice\` on the eligibility response). Reports that allow a single appeal (\`max_appeals\` of 1) never have a notice period and accept it whenever \`appealable\` is true.', - }) - .check((argv) => { + }, + body: { + kind: "parsed", + brief: + 'Submit an appeal for a report. Provide either a list of mitigations to appeal, or an appeal type with its supporting details, but not both. When type is "counter_notice", the counter-notice details are required. A "content_removed" appeal takes an optional explanation instead and is accepted only while the report is in its Notice and Takedown notice period (`has_pending_notice` on the eligibility response). Reports that allow a single appeal (`max_appeals` of 1) never have a notice period and accept it whenever `appealable` is true.', + optional: true, + parse: String, + }, + }, + operands: [ + { placeholder: "report-id", brief: "Abuse Report ID", parse: String }, + ], + rules(rules) { + rules.check((argv) => { const groupSet = [ "data-city", "data-company", @@ -149,213 +173,16 @@ function builder(yargs: Argv) { } return true; }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "review ", describe: "Request review on mitigations", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "abuse-reports mitigations review", - classification: { - safeFlags: [ - "data-jurisdiction-consent", - "data-perjury-attestation", - "type", - "dry-run", - ], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf abuse-reports mitigations review", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/abuse-reports/${argv["report-id"] == null ? "" : encodeURIComponent(String(argv["report-id"]))}/mitigations/appeal`, - pathParams: { "report-id": String(argv["report-id"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - appeals: parseObjectArray(argv["appeals"], "appeals"), - data: { - city: resolveFileToken( - argv["data-city"] as string | undefined, - "data-city", - "text" - ), - company: resolveFileToken( - argv["data-company"] as string | undefined, - "data-company", - "text" - ), - counter_notice_response: resolveFileToken( - argv["data-counter-notice-response"] as - | string - | undefined, - "data-counter-notice-response", - "text" - ), - country: resolveFileToken( - argv["data-country"] as string | undefined, - "data-country", - "text" - ), - email: resolveFileToken( - argv["data-email"] as string | undefined, - "data-email", - "text" - ), - full_name: resolveFileToken( - argv["data-full-name"] as string | undefined, - "data-full-name", - "text" - ), - jurisdiction_consent: argv["data-jurisdiction-consent"], - perjury_attestation: argv["data-perjury-attestation"], - phone_number: resolveFileToken( - argv["data-phone-number"] as string | undefined, - "data-phone-number", - "text" - ), - signature: resolveFileToken( - argv["data-signature"] as string | undefined, - "data-signature", - "text" - ), - state: resolveFileToken( - argv["data-state"] as string | undefined, - "data-state", - "text" - ), - street_address: resolveFileToken( - argv["data-street-address"] as string | undefined, - "data-street-address", - "text" - ), - urls: argv["data-urls"], - zip_code: resolveFileToken( - argv["data-zip-code"] as string | undefined, - "data-zip-code", - "text" - ), - }, - explanation: resolveFileToken( - argv["explanation"] as string | undefined, - "explanation", - "text" - ), - type: argv["type"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - report_id: argv["report-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - appeals: parseObjectArray(argv["appeals"], "appeals"), - data: { - city: resolveFileToken( - argv["data-city"] as string | undefined, - "data-city", - "text" - ), - company: resolveFileToken( - argv["data-company"] as string | undefined, - "data-company", - "text" - ), - counter_notice_response: resolveFileToken( - argv["data-counter-notice-response"] as string | undefined, - "data-counter-notice-response", - "text" - ), - country: resolveFileToken( - argv["data-country"] as string | undefined, - "data-country", - "text" - ), - email: resolveFileToken( - argv["data-email"] as string | undefined, - "data-email", - "text" - ), - full_name: resolveFileToken( - argv["data-full-name"] as string | undefined, - "data-full-name", - "text" - ), - jurisdiction_consent: argv["data-jurisdiction-consent"], - perjury_attestation: argv["data-perjury-attestation"], - phone_number: resolveFileToken( - argv["data-phone-number"] as string | undefined, - "data-phone-number", - "text" - ), - signature: resolveFileToken( - argv["data-signature"] as string | undefined, - "data-signature", - "text" - ), - state: resolveFileToken( - argv["data-state"] as string | undefined, - "data-state", - "text" - ), - street_address: resolveFileToken( - argv["data-street-address"] as string | undefined, - "data-street-address", - "text" - ), - urls: argv["data-urls"], - zip_code: resolveFileToken( - argv["data-zip-code"] as string | undefined, - "data-zip-code", - "text" - ), - }, - explanation: resolveFileToken( - argv["explanation"] as string | undefined, - "explanation", - "text" - ), - type: argv["type"], - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - report_id: argv["report-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 abuse-reports mitigations review \n\nRequest a review of mitigations applied because of an abuse report, or submit a report-level appeal. - To request a review of specific mitigations, send `appeals` with the mitigation IDs and reasons. Repeating a request for a mitigation with an unresolved appeal is idempotent and returns that mitigation in the in-review state. - To submit a report-level appeal, send `type` and, for a `counter_notice`, the counter-notice details in `data`. Report-level appeals are currently available only for DMCA (copyright) reports.", + ...parameters, + loader: () => import("./review.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/access/index.ts b/packages/cli/src/commands/_generated/access/index.ts index 770fe340bc..8ec686062d 100644 --- a/packages/cli/src/commands/_generated/access/index.ts +++ b/packages/cli/src/commands/_generated/access/index.ts @@ -1,33 +1,28 @@ -import type { CommonYargsOptions } from "#lib/cli-types.js"; -/** - * access command - * @generated from apis/overlays/access.ts - */ -import type { CommandModule } from "yargs"; import $curl from "#commands/access/curl/index.js"; import $login from "#commands/access/login/index.js"; import $sshconfig from "#commands/access/ssh-config/index.js"; import $sshgen from "#commands/access/ssh-gen/index.js"; import $tcp from "#commands/access/tcp/index.js"; import $token from "#commands/access/token/index.js"; +/** + * access command + * @generated from apis/overlays/access.ts + */ +import { apiGroup } from "#lib/api-command.js"; import { withHandWrittenDryRun } from "#lib/hand-written-dry-run.js"; -const command: CommandModule = { +const command = apiGroup({ command: "access", describe: "Access protected applications and services", - builder: (yargs) => { - return yargs - .command(withHandWrittenDryRun($curl, "preview")) - .command(withHandWrittenDryRun($login, "preview")) - .command(withHandWrittenDryRun($sshconfig, "preview")) - .command(withHandWrittenDryRun($sshgen, "preview")) - .command(withHandWrittenDryRun($tcp, "preview")) - .command(withHandWrittenDryRun($token, "preview")) - .demandCommand(1, "Please specify a subcommand"); + routes: { + curl: withHandWrittenDryRun($curl, "preview"), + login: withHandWrittenDryRun($login, "preview"), + "ssh-config": withHandWrittenDryRun($sshconfig, "preview"), + "ssh-gen": withHandWrittenDryRun($sshgen, "preview"), + tcp: withHandWrittenDryRun($tcp, "preview"), + token: withHandWrittenDryRun($token, "preview"), }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/applications/create.handler.ts b/packages/cli/src/commands/_generated/accounts/applications/create.handler.ts new file mode 100644 index 0000000000..9dffeec941 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/applications/create.handler.ts @@ -0,0 +1,121 @@ +import operation from "../../_operations/accounts/applications/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts applications create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["category-id"] === undefined) { + throw new Error( + "--category-id is required (or pass --body with this field set)." + ); + } + if (argv["human-id"] === undefined) { + argv["human-id"] = await promptForRequiredField( + "human-id", + "Human-readable identifier for the application." + ); + } + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField( + "name", + "Application name." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts applications create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/resource-library/applications`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + category_id: argv["category-id"], + hostnames: argv["hostnames"], + human_id: resolveFileToken( + argv["human-id"] as string | undefined, + "human-id", + "text" + ), + ip_subnets: argv["ip-subnets"], + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + port_protocols: argv["port-protocols"], + support_domains: argv["support-domains"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + category_id: argv["category-id"], + hostnames: argv["hostnames"], + human_id: resolveFileToken( + argv["human-id"] as string | undefined, + "human-id", + "text" + ), + ip_subnets: argv["ip-subnets"], + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + port_protocols: argv["port-protocols"], + support_domains: argv["support-domains"], + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/applications/create.ts b/packages/cli/src/commands/_generated/accounts/applications/create.ts index d6b395ae05..3cf688bc00 100644 --- a/packages/cli/src/commands/_generated/accounts/applications/create.ts +++ b/packages/cli/src/commands/_generated/accounts/applications/create.ts @@ -1,182 +1,86 @@ -import operation from "../../_operations/accounts/applications/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts applications create\n\nCreate a custom application for an account from a name, category, and optional network matchers." - ) - .option("category-id", { - type: "number", - description: "Numeric identifier for an application category.", - }) - .option("hostnames", { - type: "string", - array: true, - description: "Hostnames matched by the application.", - }) - .option("human-id", { - type: "string", - description: "Human-readable identifier for the application.", - }) - .option("ip-subnets", { - type: "string", - array: true, - description: +const parameters = { + flags: { + "category-id": { + kind: "parsed", + brief: "Numeric identifier for an application category.", + optional: true, + parse: Number, + }, + hostnames: { + kind: "parsed", + brief: "Hostnames matched by the application.", + variadic: true, + optional: true, + parse: String, + }, + "human-id": { + kind: "parsed", + brief: "Human-readable identifier for the application.", + optional: true, + parse: String, + }, + "ip-subnets": { + kind: "parsed", + brief: "IP subnets for this application. Custom application create and update requests accept IPv4 prefix lengths /8 through /32 and IPv6 prefix lengths /32 through /128.", - }) - .option("name", { type: "string", description: "Application name." }) - .option("port-protocols", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + name: { + kind: "parsed", + brief: "Application name.", + optional: true, + parse: String, + }, + "port-protocols": { + kind: "parsed", + brief: "Ports matched by the application, in `protocol/port` or inclusive `protocol/start-end` format (for example, `tcp/443` or `udp/10000-20000`). TCP and UDP ports must be between 0 and 65535.", - }) - .option("support-domains", { - type: "string", - array: true, - description: "Support domains matched by the application.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + variadic: true, + optional: true, + parse: String, + }, + "support-domains": { + kind: "parsed", + brief: "Support domains matched by the application.", + variadic: true, + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: - "Defines a custom application. At least one hostname or IP subnet is required. Support domains and port/protocol pairs do not satisfy this requirement. A NUL character (U+0000) in any string value returns \`400\`. ", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: + "Defines a custom application. At least one hostname or IP subnet is required. Support domains and port/protocol pairs do not satisfy this requirement. A NUL character (U+0000) in any string value returns `400`. ", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Create application", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts applications create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["category-id"] === undefined) { - throw new Error( - "--category-id is required (or pass --body with this field set)." - ); - } - if (argv["human-id"] === undefined) { - argv["human-id"] = await promptForRequiredField( - "human-id", - "Human-readable identifier for the application." - ); - } - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "Application name." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts applications create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/resource-library/applications`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - category_id: argv["category-id"], - hostnames: argv["hostnames"], - human_id: resolveFileToken( - argv["human-id"] as string | undefined, - "human-id", - "text" - ), - ip_subnets: argv["ip-subnets"], - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - port_protocols: argv["port-protocols"], - support_domains: argv["support-domains"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - category_id: argv["category-id"], - hostnames: argv["hostnames"], - human_id: resolveFileToken( - argv["human-id"] as string | undefined, - "human-id", - "text" - ), - ip_subnets: argv["ip-subnets"], - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - port_protocols: argv["port-protocols"], - support_domains: argv["support-domains"], - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 accounts applications create\n\nCreate a custom application for an account from a name, category, and optional network matchers.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/applications/delete.handler.ts b/packages/cli/src/commands/_generated/accounts/applications/delete.handler.ts new file mode 100644 index 0000000000..85ab629791 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/applications/delete.handler.ts @@ -0,0 +1,57 @@ +import operation from "../../_operations/accounts/applications/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts applications delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts applications delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/resource-library/applications/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, + pathParams: { id: String(argv["id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This operation deletes the custom application and all of its versions. This action cannot be undone.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { account_id: accountId, id: argv["id"] }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/applications/delete.ts b/packages/cli/src/commands/_generated/accounts/applications/delete.ts index c33ea56191..8dc28145e7 100644 --- a/packages/cli/src/commands/_generated/accounts/applications/delete.ts +++ b/packages/cli/src/commands/_generated/accounts/applications/delete.ts @@ -1,93 +1,37 @@ -import operation from "../../_operations/accounts/applications/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts applications delete \n\nDelete a custom application and all of its versions. Deletion is rejected when other resources reference the application." - ) - .positional("id", { - type: "string", - description: "Application ID.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "id", brief: "Application ID.", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete application", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts applications delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts applications delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/resource-library/applications/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, - pathParams: { id: String(argv["id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This operation deletes the custom application and all of its versions. This action cannot be undone.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { account_id: accountId, id: argv["id"] }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 accounts applications delete \n\nDelete a custom application and all of its versions. Deletion is rejected when other resources reference the application.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/applications/get.handler.ts b/packages/cli/src/commands/_generated/accounts/applications/get.handler.ts new file mode 100644 index 0000000000..3fda16cf5e --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/applications/get.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/accounts/applications/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts applications get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts applications get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/resource-library/applications/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, + pathParams: { id: String(argv["id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, id: argv["id"] }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/applications/get.ts b/packages/cli/src/commands/_generated/accounts/applications/get.ts index 886f95ada3..fe57d3eb1c 100644 --- a/packages/cli/src/commands/_generated/accounts/applications/get.ts +++ b/packages/cli/src/commands/_generated/accounts/applications/get.ts @@ -1,76 +1,31 @@ -import operation from "../../_operations/accounts/applications/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts applications get \n\nRetrieve an application available to the account by its numeric application ID." - ) - .positional("id", { - type: "string", - description: "Application ID.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "id", brief: "Application ID.", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get application", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts applications get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts applications get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/resource-library/applications/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, - pathParams: { id: String(argv["id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, id: argv["id"] }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts applications get \n\nRetrieve an application available to the account by its numeric application ID.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/applications/index.ts b/packages/cli/src/commands/_generated/accounts/applications/index.ts index 387e1b2602..338985f467 100644 --- a/packages/cli/src/commands/_generated/accounts/applications/index.ts +++ b/packages/cli/src/commands/_generated/accounts/applications/index.ts @@ -5,31 +5,26 @@ import $list from "./list.js"; import $lookup from "./lookup.js"; import $references from "./references.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * applications command group * @generated from apis/overlays/accounts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "applications", describe: "List Cloudflare-curated and custom applications, and manage custom applications", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .command($list) - .command($lookup) - .command($references) - .command($update) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, + list: $list, + lookup: $lookup, + references: $references, + update: $update, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/applications/list.handler.ts b/packages/cli/src/commands/_generated/accounts/applications/list.handler.ts new file mode 100644 index 0000000000..5939bf0903 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/applications/list.handler.ts @@ -0,0 +1,57 @@ +import operation from "../../_operations/accounts/applications/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts applications list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + filter: argv["filter"], + limit: argv["limit"], + offset: argv["offset"], + cursor: argv["cursor"], + order_by: argv["order-by"], + search: argv["search"], + lookup: argv["lookup"], + fields: argv["fields"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts applications list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/resource-library/applications`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/applications/list.ts b/packages/cli/src/commands/_generated/accounts/applications/list.ts index 7e46fdbfb1..7fced56093 100644 --- a/packages/cli/src/commands/_generated/accounts/applications/list.ts +++ b/packages/cli/src/commands/_generated/accounts/applications/list.ts @@ -1,122 +1,87 @@ -import operation from "../../_operations/accounts/applications/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts applications list\n\nList the applications available to an account, both the applications Cloudflare curates and the custom applications the account has defined. Results are paginated. Page with `cursor` so that applications added or removed between requests do not make other results repeat or go missing; `offset` paging can repeat or miss results when the list changes between requests. Use `filter` and `search` to narrow the list, `order_by` to sort it, and `fields` to reduce each result to only the properties you need. Use `lookup` to find complete application names mentioned in a rule sentence, ignoring case. Lookup does not correct misspellings. It ranks matches by relevance and uses the same filters, fields, and pagination as listing. `lookup` cannot be combined with `search`. Invalid UTF-8 or a NUL character (U+0000) in any query parameter name or value returns `400`. The authenticated principal must have access to the account identified by `account_id`." - ) - .option("filter", { - type: "string", - description: +const parameters = { + flags: { + filter: { + kind: "parsed", + brief: "Filter applications using `key:value` format. Supported filter keys:\n- `name`: application name (for example, `name:HR`).\n- `id`: application ID (for example, `id:498`).\n- `human_id`: human-readable ID (for example, `human_id:HR`).\n- `hostname`: hostname or support domain (for example, `hostname:portal.example.com`).\n- `source`: application source name (for example, `source:cloudflare`).\n- `ip_subnet`: CIDR containment; returns applications where a stored subnet contains the search value (for example, `ip_subnet:10.0.1.5/32` matches `10.0.0.0/16`).\n- `category_id`: category ID (for example, `category_id:12`).\n- `category_name`: category name (for example, `category_name:HR`).\n- `supported`: supported Cloudflare product. Values: `GATEWAY`, `ACCESS`, `CASB`.\n- `review_status`: account-specific Gateway review status. Values: `approved`, `unapproved`, `in_review`, `unreviewed`.", - }) - .option("limit", { - type: "number", - description: + optional: true, + parse: String, + }, + limit: { + kind: "parsed", + brief: "Number of results to return. Defaults to 25; values are clamped to 1–250.", - }) - .option("offset", { - type: "number", - description: + optional: true, + parse: Number, + }, + offset: { + kind: "parsed", + brief: "Number of results to skip. Defaults to 0; negative values are clamped to 0. Ignored when `cursor` is provided.", - }) - .option("cursor", { - type: "string", - description: + optional: true, + parse: Number, + }, + cursor: { + kind: "parsed", + brief: "Opaque value from `result_info.cursor` of the previous response. Returns the\nresults that follow it. Send the same `filter`, `search`, `lookup`, and\n`order_by` values as the request that returned it; `limit` and `fields` may\nchange. An empty value is the same as no cursor. A modified cursor, or one used\nwith different values, returns `400`.", - }) - .option("order-by", { - type: "string", - description: + optional: true, + parse: String, + }, + "order-by": { + kind: "parsed", + brief: "Order results using field:direction format. Supported fields are name, id, human_id,\ncategory_id, application_type, application_confidence_score, and gen_ai_score.\nSupported directions are asc and desc. name and application_type ignore the case of\nthe letters A to Z, and ties sort by id. Ignored when search is provided; results are\nranked by relevance instead. Also ignored when lookup is provided.", - }) - .option("search", { - type: "string", - description: + optional: true, + parse: String, + }, + search: { + kind: "parsed", + brief: "Fuzzy search across application name and hostnames. Results are ranked by relevance. Must be between 2 and 200 characters. Can be combined with filter parameters.", - }) - .option("lookup", { - type: "string", - description: + optional: true, + parse: String, + }, + lookup: { + kind: "parsed", + brief: "Find complete, case-insensitive application name mentions in a phrase or\nrule sentence. Misspelled names do not match. Returns matching applications\nranked by relevance. Must be between 2 and 1000 characters, with no control\ncharacters other than tab and line breaks. Uses the same\nfilters, fields, and pagination as listing. `search` cannot be combined\nwith lookup. Results are ranked by relevance, so `order_by` is ignored.\nTo keep the text out of URLs, send it to `POST .../applications/lookup` instead.", - }) - .option("fields", { - type: "string", - description: + optional: true, + parse: String, + }, + fields: { + kind: "parsed", + brief: "Return only the listed properties on each application, as a comma-separated list.\nUse this to keep responses small when you only need part of each application, for\nexample populating a picker with `fields=id,name` instead of downloading every\nhostname and IP subnet.\n\nOmit this parameter to receive the full application object, including\nwhen lookup is used.\n\n`id` is always returned.\n\nSelectable properties: `id`, `name`, `human_id`, `version`, `hostnames`,\n`support_domains`, `ip_subnets`, `port_protocols`, `supported`, `gen_ai_score`,\n`application_confidence_score`, `created_at`, `updated_at`, `review_status`.\n\nUnknown or empty property names return `400`.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List applications", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts applications list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - filter: argv["filter"], - limit: argv["limit"], - offset: argv["offset"], - cursor: argv["cursor"], - order_by: argv["order-by"], - search: argv["search"], - lookup: argv["lookup"], - fields: argv["fields"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts applications list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/resource-library/applications`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts applications list\n\nList the applications available to an account, both the applications Cloudflare curates and the custom applications the account has defined. Results are paginated. Page with `cursor` so that applications added or removed between requests do not make other results repeat or go missing; `offset` paging can repeat or miss results when the list changes between requests. Use `filter` and `search` to narrow the list, `order_by` to sort it, and `fields` to reduce each result to only the properties you need. Use `lookup` to find complete application names mentioned in a rule sentence, ignoring case. Lookup does not correct misspellings. It ranks matches by relevance and uses the same filters, fields, and pagination as listing. `lookup` cannot be combined with `search`. Invalid UTF-8 or a NUL character (U+0000) in any query parameter name or value returns `400`. The authenticated principal must have access to the account identified by `account_id`.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/applications/lookup.handler.ts b/packages/cli/src/commands/_generated/accounts/applications/lookup.handler.ts new file mode 100644 index 0000000000..f0d4f5e740 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/applications/lookup.handler.ts @@ -0,0 +1,114 @@ +import operation from "../../_operations/accounts/applications/lookup.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./lookup.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts applications lookup", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + filter: argv["filter"], + limit: argv["limit"], + fields: argv["fields"], + }; + const resolveRequiredFields = async (): Promise => { + if (argv["lookup"] === undefined) { + argv["lookup"] = await promptForRequiredField( + "lookup", + "Rule sentence to search for complete application names. Leading and trailing whitespace is trimmed before the length is checked. Control characters other than tab and line breaks return \`400\`. " + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts applications lookup", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/resource-library/applications/lookup`, + pathParams: {}, + query: queryParams, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + lookup: resolveFileToken( + argv["lookup"] as string | undefined, + "lookup", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const qs = new URLSearchParams( + Object.entries(queryParams) + .filter(([, v]) => v !== undefined) + .map(([k, v]) => [k, String(v)]) + ).toString(); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + lookup: resolveFileToken( + argv["lookup"] as string | undefined, + "lookup", + "text" + ), + }); + const qs = new URLSearchParams( + Object.entries(queryParams) + .filter(([, v]) => v !== undefined) + .map(([k, v]) => [k, String(v)]) + ).toString(); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/applications/lookup.ts b/packages/cli/src/commands/_generated/accounts/applications/lookup.ts index f6ecb580fa..ef7ecba470 100644 --- a/packages/cli/src/commands/_generated/accounts/applications/lookup.ts +++ b/packages/cli/src/commands/_generated/accounts/applications/lookup.ts @@ -1,163 +1,65 @@ -import operation from "../../_operations/accounts/applications/lookup.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * lookup command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts applications lookup\n\nFind complete application names mentioned in a rule sentence, ignoring case. Lookup does not correct misspellings. Matches are ranked by relevance. This endpoint takes the rule sentence in the request body, so the text stays out of URLs and request logs. Use it instead of the `lookup` query parameter on the list endpoint when the text may contain sensitive content. `fields`, `limit`, and `filter` work the same way as on the list endpoint and are passed as query parameters. Results are not paged: `offset`, `cursor`, `order_by`, `search`, and `lookup` query parameters return `400`. Unknown request body properties also return `400`. Invalid UTF-8 or a NUL character (U+0000) in any query parameter name or value returns `400`. The authenticated principal must have access to the account identified by `account_id`." - ) - .option("filter", { - type: "string", - description: +const parameters = { + flags: { + filter: { + kind: "parsed", + brief: "Filter matches using the same `key:value` filters as the list endpoint.", - }) - .option("limit", { - type: "number", - description: + optional: true, + parse: String, + }, + limit: { + kind: "parsed", + brief: "Maximum number of matches to return. Defaults to 25; values are clamped to 1–250.", - }) - .option("fields", { - type: "string", - description: + optional: true, + parse: Number, + }, + fields: { + kind: "parsed", + brief: "Return only the listed properties on each application, as a comma-separated list.\nAccepts the same properties as the list endpoint. `id` is always returned.\nOmit this parameter to receive the full application object.", - }) - .option("lookup", { - type: "string", - description: + optional: true, + parse: String, + }, + lookup: { + kind: "parsed", + brief: "Rule sentence to search for complete application names. Leading and trailing\nwhitespace is trimmed before the length is checked. Control characters other\nthan tab and line breaks return `400`.\n", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "lookup", describe: "Look up applications in a rule sentence", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts applications lookup", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - filter: argv["filter"], - limit: argv["limit"], - fields: argv["fields"], - }; - const resolveRequiredFields = async (): Promise => { - if (argv["lookup"] === undefined) { - argv["lookup"] = await promptForRequiredField( - "lookup", - "Rule sentence to search for complete application names. Leading and trailing whitespace is trimmed before the length is checked. Control characters other than tab and line breaks return \`400\`. " - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts applications lookup", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/resource-library/applications/lookup`, - pathParams: {}, - query: queryParams, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - lookup: resolveFileToken( - argv["lookup"] as string | undefined, - "lookup", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const qs = new URLSearchParams( - Object.entries(queryParams) - .filter(([, v]) => v !== undefined) - .map(([k, v]) => [k, String(v)]) - ).toString(); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - lookup: resolveFileToken( - argv["lookup"] as string | undefined, - "lookup", - "text" - ), - }); - const qs = new URLSearchParams( - Object.entries(queryParams) - .filter(([, v]) => v !== undefined) - .map(([k, v]) => [k, String(v)]) - ).toString(); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 accounts applications lookup\n\nFind complete application names mentioned in a rule sentence, ignoring case. Lookup does not correct misspellings. Matches are ranked by relevance. This endpoint takes the rule sentence in the request body, so the text stays out of URLs and request logs. Use it instead of the `lookup` query parameter on the list endpoint when the text may contain sensitive content. `fields`, `limit`, and `filter` work the same way as on the list endpoint and are passed as query parameters. Results are not paged: `offset`, `cursor`, `order_by`, `search`, and `lookup` query parameters return `400`. Unknown request body properties also return `400`. Invalid UTF-8 or a NUL character (U+0000) in any query parameter name or value returns `400`. The authenticated principal must have access to the account identified by `account_id`.", + ...parameters, + loader: () => import("./lookup.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/applications/references.handler.ts b/packages/cli/src/commands/_generated/accounts/applications/references.handler.ts new file mode 100644 index 0000000000..b2aef408d5 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/applications/references.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/accounts/applications/references.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./references.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts applications references", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts applications references", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/resource-library/applications/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}/references`, + pathParams: { id: String(argv["id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, id: argv["id"] }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/applications/references.ts b/packages/cli/src/commands/_generated/accounts/applications/references.ts index f0dd4cbb93..9b2b4c5e73 100644 --- a/packages/cli/src/commands/_generated/accounts/applications/references.ts +++ b/packages/cli/src/commands/_generated/accounts/applications/references.ts @@ -1,76 +1,37 @@ -import operation from "../../_operations/accounts/applications/references.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * references command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts applications references \n\nList the resources in the account that reference a custom application, such as Gateway rules. This is the same list a delete of the application returns when it is rejected. A delete checks the references again, so the list can change before the delete runs." - ) - .positional("id", { - type: "string", - description: "Application ID of a custom application in the account.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "id", + brief: "Application ID of a custom application in the account.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "references ", describe: "Get application references", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts applications references", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts applications references", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/resource-library/applications/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}/references`, - pathParams: { id: String(argv["id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, id: argv["id"] }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts applications references \n\nList the resources in the account that reference a custom application, such as Gateway rules. This is the same list a delete of the application returns when it is rejected. A delete checks the references again, so the list can change before the delete runs.", + ...parameters, + loader: () => import("./references.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/applications/update.handler.ts b/packages/cli/src/commands/_generated/accounts/applications/update.handler.ts new file mode 100644 index 0000000000..ebd5004a34 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/applications/update.handler.ts @@ -0,0 +1,82 @@ +import operation from "../../_operations/accounts/applications/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts applications update", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts applications update", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/resource-library/applications/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, + pathParams: { id: String(argv["id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + hostnames: argv["hostnames"], + ip_subnets: argv["ip-subnets"], + port_protocols: argv["port-protocols"], + support_domains: argv["support-domains"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + hostnames: argv["hostnames"], + ip_subnets: argv["ip-subnets"], + port_protocols: argv["port-protocols"], + support_domains: argv["support-domains"], + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/applications/update.ts b/packages/cli/src/commands/_generated/accounts/applications/update.ts index 28004d2282..465dc3df62 100644 --- a/packages/cli/src/commands/_generated/accounts/applications/update.ts +++ b/packages/cli/src/commands/_generated/accounts/applications/update.ts @@ -1,139 +1,68 @@ -import operation from "../../_operations/accounts/applications/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts applications update \n\nReplace the supplied network matchers for a custom application and create a new version. Omitted matcher lists remain unchanged; send an empty list to clear a matcher type." - ) - .positional("id", { - type: "string", - description: "Application ID.", - demandOption: true, - }) - .option("hostnames", { - type: "string", - array: true, - description: "Hostnames matched by the application.", - }) - .option("ip-subnets", { - type: "string", - array: true, - description: +const parameters = { + flags: { + hostnames: { + kind: "parsed", + brief: "Hostnames matched by the application.", + variadic: true, + optional: true, + parse: String, + }, + "ip-subnets": { + kind: "parsed", + brief: "IP subnets for this application. Custom application create and update requests accept IPv4 prefix lengths /8 through /32 and IPv6 prefix lengths /32 through /128.", - }) - .option("port-protocols", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + "port-protocols": { + kind: "parsed", + brief: "Ports matched by the application, in `protocol/port` or inclusive `protocol/start-end` format (for example, `tcp/443` or `udp/10000-20000`). TCP and UDP ports must be between 0 and 65535.", - }) - .option("support-domains", { - type: "string", - array: true, - description: "Support domains matched by the application.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + variadic: true, + optional: true, + parse: String, + }, + "support-domains": { + kind: "parsed", + brief: "Support domains matched by the application.", + variadic: true, + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: - "Update the network matchers for the application. The service preserves omitted matcher lists; send an empty array to clear a list. The resulting application must contain at least one hostname or IP subnet. Support domains and port/protocol pairs do not satisfy this requirement. A NUL character (U+0000) in any string value returns \`400\`. ", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: + "Update the network matchers for the application. The service preserves omitted matcher lists; send an empty array to clear a list. The resulting application must contain at least one hostname or IP subnet. Support domains and port/protocol pairs do not satisfy this requirement. A NUL character (U+0000) in any string value returns `400`. ", + optional: true, + parse: String, + }, + }, + operands: [{ placeholder: "id", brief: "Application ID.", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update ", describe: "Update application", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts applications update", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts applications update", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/resource-library/applications/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, - pathParams: { id: String(argv["id"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - hostnames: argv["hostnames"], - ip_subnets: argv["ip-subnets"], - port_protocols: argv["port-protocols"], - support_domains: argv["support-domains"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - hostnames: argv["hostnames"], - ip_subnets: argv["ip-subnets"], - port_protocols: argv["port-protocols"], - support_domains: argv["support-domains"], - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 accounts applications update \n\nReplace the supplied network matchers for a custom application and create a new version. Omitted matcher lists remain unchanged; send an empty list to clear a matcher type.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/billing/create-setup-intent.handler.ts b/packages/cli/src/commands/_generated/accounts/billing/create-setup-intent.handler.ts new file mode 100644 index 0000000000..57117e43af --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/billing/create-setup-intent.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/accounts/billing/create-setup-intent.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create-setup-intent.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts billing create-setup-intent", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts billing create-setup-intent", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/client-secret`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Creating`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/billing/create-setup-intent.ts b/packages/cli/src/commands/_generated/accounts/billing/create-setup-intent.ts index 6826cda8c7..21c86b5c87 100644 --- a/packages/cli/src/commands/_generated/accounts/billing/create-setup-intent.ts +++ b/packages/cli/src/commands/_generated/accounts/billing/create-setup-intent.ts @@ -1,71 +1,31 @@ -import operation from "../../_operations/accounts/billing/create-setup-intent.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create-setup-intent command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts billing create-setup-intent\n\nCreates a Stripe setup intent for adding a payment method to an account. Returns a client secret for frontend payment method collection." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create-setup-intent", describe: "Create Setup Intent", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts billing create-setup-intent", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts billing create-setup-intent", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/client-secret`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Creating`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 accounts billing create-setup-intent\n\nCreates a Stripe setup intent for adding a payment method to an account. Returns a client secret for frontend payment method collection.", + ...parameters, + loader: () => import("./create-setup-intent.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/billing/get-bad-debt.handler.ts b/packages/cli/src/commands/_generated/accounts/billing/get-bad-debt.handler.ts new file mode 100644 index 0000000000..e514369e3d --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/billing/get-bad-debt.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/accounts/billing/get-bad-debt.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get-bad-debt.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts billing get-bad-debt", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts billing get-bad-debt", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/bad-debt`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/billing/get-bad-debt.ts b/packages/cli/src/commands/_generated/accounts/billing/get-bad-debt.ts index dfbab77b6c..e240ba5680 100644 --- a/packages/cli/src/commands/_generated/accounts/billing/get-bad-debt.ts +++ b/packages/cli/src/commands/_generated/accounts/billing/get-bad-debt.ts @@ -1,71 +1,31 @@ -import operation from "../../_operations/accounts/billing/get-bad-debt.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get-bad-debt command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts billing get-bad-debt\n\nGets bad debt information for an account, including outstanding invoices and total debt amount." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get-bad-debt", describe: "Get Account Bad Debt", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts billing get-bad-debt", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts billing get-bad-debt", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/bad-debt`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts billing get-bad-debt\n\nGets bad debt information for an account, including outstanding invoices and total debt amount.", + ...parameters, + loader: () => import("./get-bad-debt.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/billing/get-credits.handler.ts b/packages/cli/src/commands/_generated/accounts/billing/get-credits.handler.ts new file mode 100644 index 0000000000..5f8ae94415 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/billing/get-credits.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/accounts/billing/get-credits.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get-credits.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts billing get-credits", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts billing get-credits", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/credits`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/billing/get-credits.ts b/packages/cli/src/commands/_generated/accounts/billing/get-credits.ts index b33e4800d5..af57b6867c 100644 --- a/packages/cli/src/commands/_generated/accounts/billing/get-credits.ts +++ b/packages/cli/src/commands/_generated/accounts/billing/get-credits.ts @@ -1,71 +1,31 @@ -import operation from "../../_operations/accounts/billing/get-credits.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get-credits command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts billing get-credits\n\nGets the credit balance and eligibility for an account." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get-credits", describe: "Get Account Credits", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts billing get-credits", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts billing get-credits", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/credits`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts billing get-credits\n\nGets the credit balance and eligibility for an account.", + ...parameters, + loader: () => import("./get-credits.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/billing/get-receipt-pdf.handler.ts b/packages/cli/src/commands/_generated/accounts/billing/get-receipt-pdf.handler.ts new file mode 100644 index 0000000000..b93fa0b6be --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/billing/get-receipt-pdf.handler.ts @@ -0,0 +1,65 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get-receipt-pdf.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { fetchRawBytes, writeRawOutput } from "#lib/raw-fetch.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts billing get-receipt-pdf", + classification: { + safeFlags: ["dry-run", "text"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + doctype: argv["doctype"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts billing get-receipt-pdf", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/receipts/${argv["receipt-id"] == null ? "" : encodeURIComponent(String(argv["receipt-id"]))}/pdf`, + pathParams: { "receipt-id": String(argv["receipt-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const qs = new URLSearchParams( + Object.entries(queryParams) + .filter(([, v]) => v !== undefined) + .map(([k, v]) => [k, String(v)]) + ).toString(); + const __cfRawBytes = await withProgress(`Loading`, async () => + fetchRawBytes( + `/accounts/${accountId}/receipts/${encodeURIComponent(String(argv["receipt-id"]))}/pdf${qs ? "?" + qs : ""}`, + { + method: "GET", + local: argv.local === true, + persistTo: argv.persistTo as string | undefined, + } + ) + ); + writeRawOutput( + argv.text === true ? __cfRawBytes.toString("utf-8") : __cfRawBytes + ); + return; + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/billing/get-receipt-pdf.ts b/packages/cli/src/commands/_generated/accounts/billing/get-receipt-pdf.ts index eacd75aee6..0e413075e2 100644 --- a/packages/cli/src/commands/_generated/accounts/billing/get-receipt-pdf.ts +++ b/packages/cli/src/commands/_generated/accounts/billing/get-receipt-pdf.ts @@ -1,105 +1,45 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get-receipt-pdf command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { fetchRawBytes, writeRawOutput } from "#lib/raw-fetch.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts billing get-receipt-pdf \n\nDownloads a receipt as a PDF document." - ) - .positional("receipt-id", { - type: "string", - description: "Receipt identifier.", - demandOption: true, - }) - .option("doctype", { - type: "string", - description: "The document type to generate.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + doctype: { + kind: "parsed", + brief: "The document type to generate.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("text", { - type: "boolean", - description: + }, + text: { + kind: "boolean", + brief: "Decode the response body as UTF-8 text instead of writing raw bytes", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "receipt-id", brief: "Receipt identifier.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get-receipt-pdf ", describe: "Get Receipt PDF", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts billing get-receipt-pdf", - classification: { - safeFlags: ["dry-run", "text"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - doctype: argv["doctype"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts billing get-receipt-pdf", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/receipts/${argv["receipt-id"] == null ? "" : encodeURIComponent(String(argv["receipt-id"]))}/pdf`, - pathParams: { "receipt-id": String(argv["receipt-id"] ?? "") }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const qs = new URLSearchParams( - Object.entries(queryParams) - .filter(([, v]) => v !== undefined) - .map(([k, v]) => [k, String(v)]) - ).toString(); - const __cfRawBytes = await withProgress(`Loading`, async () => - fetchRawBytes( - `/accounts/${accountId}/receipts/${encodeURIComponent(String(argv["receipt-id"]))}/pdf${qs ? "?" + qs : ""}`, - { - method: "GET", - local: argv.local === true, - persistTo: argv.persistTo as string | undefined, - } - ) - ); - writeRawOutput( - argv.text === true ? __cfRawBytes.toString("utf-8") : __cfRawBytes - ); - return; - } - ), -}; + usage: + "$0 accounts billing get-receipt-pdf \n\nDownloads a receipt as a PDF document.", + ...parameters, + loader: () => import("./get-receipt-pdf.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/billing/get-unpaid-invoices.handler.ts b/packages/cli/src/commands/_generated/accounts/billing/get-unpaid-invoices.handler.ts new file mode 100644 index 0000000000..69a06e1032 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/billing/get-unpaid-invoices.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/accounts/billing/get-unpaid-invoices.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get-unpaid-invoices.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts billing get-unpaid-invoices", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts billing get-unpaid-invoices", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/unpaid-invoice`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/billing/get-unpaid-invoices.ts b/packages/cli/src/commands/_generated/accounts/billing/get-unpaid-invoices.ts index baafbc1141..30c6a50d36 100644 --- a/packages/cli/src/commands/_generated/accounts/billing/get-unpaid-invoices.ts +++ b/packages/cli/src/commands/_generated/accounts/billing/get-unpaid-invoices.ts @@ -1,71 +1,31 @@ -import operation from "../../_operations/accounts/billing/get-unpaid-invoices.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get-unpaid-invoices command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts billing get-unpaid-invoices\n\nGets unpaid invoice information for an account." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get-unpaid-invoices", describe: "Get Unpaid Invoices", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts billing get-unpaid-invoices", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts billing get-unpaid-invoices", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/unpaid-invoice`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts billing get-unpaid-invoices\n\nGets unpaid invoice information for an account.", + ...parameters, + loader: () => import("./get-unpaid-invoices.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/billing/history/index.ts b/packages/cli/src/commands/_generated/accounts/billing/history/index.ts index 686486e6ce..e9deab3946 100644 --- a/packages/cli/src/commands/_generated/accounts/billing/history/index.ts +++ b/packages/cli/src/commands/_generated/accounts/billing/history/index.ts @@ -1,20 +1,17 @@ import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * history command group * @generated from apis/overlays/accounts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "history", describe: "Operations for billing.history", - builder: (yargs) => { - return yargs.command($list).demandCommand(1, "Please specify a subcommand"); + routes: { + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/billing/history/list.handler.ts b/packages/cli/src/commands/_generated/accounts/billing/history/list.handler.ts new file mode 100644 index 0000000000..dc8ef6c2e8 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/billing/history/list.handler.ts @@ -0,0 +1,52 @@ +import operation from "../../../_operations/accounts/billing/history/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts billing history list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + status: argv["status"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts billing history list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/history`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/billing/history/list.ts b/packages/cli/src/commands/_generated/accounts/billing/history/list.ts index 9347ceca7a..3366322884 100644 --- a/packages/cli/src/commands/_generated/accounts/billing/history/list.ts +++ b/packages/cli/src/commands/_generated/accounts/billing/history/list.ts @@ -1,89 +1,49 @@ -import operation from "../../../_operations/accounts/billing/history/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts billing history list\n\nGets the billing history for an account." - ) - .option("page", { - type: "number", - description: "Page number of paginated results.", - }) - .option("per-page", { - type: "number", - description: "Number of items per page.", - }) - .option("status", { - type: "string", - description: "Filter billing history by status.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + page: { + kind: "parsed", + brief: "Page number of paginated results.", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Number of items per page.", + optional: true, + parse: Number, + }, + status: { + kind: "parsed", + brief: "Filter billing history by status.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "Get Account Billing History", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts billing history list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - status: argv["status"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts billing history list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/history`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts billing history list\n\nGets the billing history for an account.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/billing/index.ts b/packages/cli/src/commands/_generated/accounts/billing/index.ts index d9a8b05458..b20ceed183 100644 --- a/packages/cli/src/commands/_generated/accounts/billing/index.ts +++ b/packages/cli/src/commands/_generated/accounts/billing/index.ts @@ -7,32 +7,27 @@ import $history from "./history/index.js"; import $payinvoice from "./pay-invoice.js"; import $paymentmethods from "./payment-methods/index.js"; import $togglepdfinvoices from "./toggle-pdf-invoices.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * billing command group * @generated from apis/overlays/accounts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "billing", describe: "Operations for billing", - builder: (yargs) => { - return yargs - .command($createsetupintent) - .command($getbaddebt) - .command($getcredits) - .command($getreceiptpdf) - .command($getunpaidinvoices) - .command($payinvoice) - .command($togglepdfinvoices) - .command($history) - .command($paymentmethods) - .demandCommand(1, "Please specify a subcommand"); + routes: { + "create-setup-intent": $createsetupintent, + "get-bad-debt": $getbaddebt, + "get-credits": $getcredits, + "get-receipt-pdf": $getreceiptpdf, + "get-unpaid-invoices": $getunpaidinvoices, + "pay-invoice": $payinvoice, + "toggle-pdf-invoices": $togglepdfinvoices, + history: $history, + "payment-methods": $paymentmethods, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/billing/pay-invoice.handler.ts b/packages/cli/src/commands/_generated/accounts/billing/pay-invoice.handler.ts new file mode 100644 index 0000000000..4e2c853aff --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/billing/pay-invoice.handler.ts @@ -0,0 +1,89 @@ +import operation from "../../_operations/accounts/billing/pay-invoice.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./pay-invoice.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts billing pay-invoice", + classification: { + safeFlags: ["validate-payment-method", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts billing pay-invoice", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/pay-invoice`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + invoice_id: resolveFileToken( + argv["invoice-id"] as string | undefined, + "invoice-id", + "text" + ), + payment_method_id: resolveFileToken( + argv["payment-method-id"] as string | undefined, + "payment-method-id", + "text" + ), + validate_payment_method: argv["validate-payment-method"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + invoice_id: resolveFileToken( + argv["invoice-id"] as string | undefined, + "invoice-id", + "text" + ), + payment_method_id: resolveFileToken( + argv["payment-method-id"] as string | undefined, + "payment-method-id", + "text" + ), + validate_payment_method: argv["validate-payment-method"], + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/billing/pay-invoice.ts b/packages/cli/src/commands/_generated/accounts/billing/pay-invoice.ts index e623cc34ee..3c2be91861 100644 --- a/packages/cli/src/commands/_generated/accounts/billing/pay-invoice.ts +++ b/packages/cli/src/commands/_generated/accounts/billing/pay-invoice.ts @@ -1,131 +1,55 @@ -import operation from "../../_operations/accounts/billing/pay-invoice.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * pay-invoice command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts billing pay-invoice\n\nPays an outstanding invoice for an account. Returns a Stripe client secret when Strong Customer Authentication (SCA) is required to complete the payment." - ) - .option("invoice-id", { - type: "string", - description: "The identifier of the invoice to pay.", - }) - .option("payment-method-id", { - type: "string", - description: +const parameters = { + flags: { + "invoice-id": { + kind: "parsed", + brief: "The identifier of the invoice to pay.", + optional: true, + parse: String, + }, + "payment-method-id": { + kind: "parsed", + brief: "The payment method to use. If omitted, the default payment method is used.", - }) - .option("validate-payment-method", { - type: "boolean", - description: "Whether to validate the payment method before processing.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "validate-payment-method": { + kind: "boolean", + brief: "Whether to validate the payment method before processing.", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "pay-invoice", describe: "Pay Invoice", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts billing pay-invoice", - classification: { - safeFlags: ["validate-payment-method", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts billing pay-invoice", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/pay-invoice`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - invoice_id: resolveFileToken( - argv["invoice-id"] as string | undefined, - "invoice-id", - "text" - ), - payment_method_id: resolveFileToken( - argv["payment-method-id"] as string | undefined, - "payment-method-id", - "text" - ), - validate_payment_method: argv["validate-payment-method"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - invoice_id: resolveFileToken( - argv["invoice-id"] as string | undefined, - "invoice-id", - "text" - ), - payment_method_id: resolveFileToken( - argv["payment-method-id"] as string | undefined, - "payment-method-id", - "text" - ), - validate_payment_method: argv["validate-payment-method"], - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 accounts billing pay-invoice\n\nPays an outstanding invoice for an account. Returns a Stripe client secret when Strong Customer Authentication (SCA) is required to complete the payment.", + ...parameters, + loader: () => import("./pay-invoice.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/billing/payment-methods/create.handler.ts b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/create.handler.ts new file mode 100644 index 0000000000..98783d3cab --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/create.handler.ts @@ -0,0 +1,271 @@ +import operation from "../../../_operations/accounts/billing/payment-methods/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts billing payment-methods create", + classification: { + safeFlags: ["default", "type", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts billing payment-methods create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/payment-methods`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + address: resolveFileToken( + argv["address"] as string | undefined, + "address", + "text" + ), + address2: resolveFileToken( + argv["address2"] as string | undefined, + "address2", + "text" + ), + bank_account_type: resolveFileToken( + argv["bank-account-type"] as string | undefined, + "bank-account-type", + "text" + ), + bank_code: resolveFileToken( + argv["bank-code"] as string | undefined, + "bank-code", + "text" + ), + bank_country: resolveFileToken( + argv["bank-country"] as string | undefined, + "bank-country", + "text" + ), + bank_name: resolveFileToken( + argv["bank-name"] as string | undefined, + "bank-name", + "text" + ), + bank_routing_number: resolveFileToken( + argv["bank-routing-number"] as string | undefined, + "bank-routing-number", + "text" + ), + cashapp_cash_tag: resolveFileToken( + argv["cashapp-cash-tag"] as string | undefined, + "cashapp-cash-tag", + "text" + ), + city: resolveFileToken( + argv["city"] as string | undefined, + "city", + "text" + ), + country: resolveFileToken( + argv["country"] as string | undefined, + "country", + "text" + ), + default: argv["default"], + device_data: resolveFileToken( + argv["device-data"] as string | undefined, + "device-data", + "text" + ), + first_name: resolveFileToken( + argv["first-name"] as string | undefined, + "first-name", + "text" + ), + last_name: resolveFileToken( + argv["last-name"] as string | undefined, + "last-name", + "text" + ), + nick_name: resolveFileToken( + argv["nick-name"] as string | undefined, + "nick-name", + "text" + ), + payment_account_email: resolveFileToken( + argv["payment-account-email"] as string | undefined, + "payment-account-email", + "text" + ), + payment_email: resolveFileToken( + argv["payment-email"] as string | undefined, + "payment-email", + "text" + ), + payment_gateway: resolveFileToken( + argv["payment-gateway"] as string | undefined, + "payment-gateway", + "text" + ), + payment_nonce: resolveFileToken( + argv["payment-nonce"] as string | undefined, + "payment-nonce", + "text" + ), + state: resolveFileToken( + argv["state"] as string | undefined, + "state", + "text" + ), + type: argv["type"], + zipcode: resolveFileToken( + argv["zipcode"] as string | undefined, + "zipcode", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + address: resolveFileToken( + argv["address"] as string | undefined, + "address", + "text" + ), + address2: resolveFileToken( + argv["address2"] as string | undefined, + "address2", + "text" + ), + bank_account_type: resolveFileToken( + argv["bank-account-type"] as string | undefined, + "bank-account-type", + "text" + ), + bank_code: resolveFileToken( + argv["bank-code"] as string | undefined, + "bank-code", + "text" + ), + bank_country: resolveFileToken( + argv["bank-country"] as string | undefined, + "bank-country", + "text" + ), + bank_name: resolveFileToken( + argv["bank-name"] as string | undefined, + "bank-name", + "text" + ), + bank_routing_number: resolveFileToken( + argv["bank-routing-number"] as string | undefined, + "bank-routing-number", + "text" + ), + cashapp_cash_tag: resolveFileToken( + argv["cashapp-cash-tag"] as string | undefined, + "cashapp-cash-tag", + "text" + ), + city: resolveFileToken( + argv["city"] as string | undefined, + "city", + "text" + ), + country: resolveFileToken( + argv["country"] as string | undefined, + "country", + "text" + ), + default: argv["default"], + device_data: resolveFileToken( + argv["device-data"] as string | undefined, + "device-data", + "text" + ), + first_name: resolveFileToken( + argv["first-name"] as string | undefined, + "first-name", + "text" + ), + last_name: resolveFileToken( + argv["last-name"] as string | undefined, + "last-name", + "text" + ), + nick_name: resolveFileToken( + argv["nick-name"] as string | undefined, + "nick-name", + "text" + ), + payment_account_email: resolveFileToken( + argv["payment-account-email"] as string | undefined, + "payment-account-email", + "text" + ), + payment_email: resolveFileToken( + argv["payment-email"] as string | undefined, + "payment-email", + "text" + ), + payment_gateway: resolveFileToken( + argv["payment-gateway"] as string | undefined, + "payment-gateway", + "text" + ), + payment_nonce: resolveFileToken( + argv["payment-nonce"] as string | undefined, + "payment-nonce", + "text" + ), + state: resolveFileToken( + argv["state"] as string | undefined, + "state", + "text" + ), + type: argv["type"], + zipcode: resolveFileToken( + argv["zipcode"] as string | undefined, + "zipcode", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/billing/payment-methods/create.ts b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/create.ts index 244be71854..3a232be98e 100644 --- a/packages/cli/src/commands/_generated/accounts/billing/payment-methods/create.ts +++ b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/create.ts @@ -1,94 +1,139 @@ -import operation from "../../../_operations/accounts/billing/payment-methods/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts billing payment-methods create\n\nCreates a new payment method for an account." - ) - .option("address", { - type: "string", - description: "Billing address line 1.", - }) - .option("address2", { - type: "string", - description: "Billing address line 2.", - }) - .option("bank-account-type", { - type: "string", - description: "Bank account type.", - }) - .option("bank-code", { type: "string", description: "Bank code." }) - .option("bank-country", { type: "string", description: "Bank country." }) - .option("bank-name", { - type: "string", - description: "Bank name for bank-based payment methods.", - }) - .option("bank-routing-number", { - type: "string", - description: "Bank routing number.", - }) - .option("cashapp-cash-tag", { - type: "string", - description: "Cash App cash tag.", - }) - .option("city", { type: "string", description: "Billing city." }) - .option("country", { type: "string", description: "Billing country." }) - .option("default", { - type: "boolean", - description: "Whether this is the default payment method.", - }) - .option("device-data", { - type: "string", - description: "Device data for fraud prevention.", - }) - .option("first-name", { - type: "string", - description: "Billing first name.", - }) - .option("last-name", { type: "string", description: "Billing last name." }) - .option("nick-name", { - type: "string", - description: "A nickname for the payment method.", - }) - .option("payment-account-email", { - type: "string", - description: "Email associated with the payment account.", - }) - .option("payment-email", { - type: "string", - description: "Payment email address.", - }) - .option("payment-gateway", { - type: "string", - description: "The payment gateway used.", - }) - .option("payment-nonce", { - type: "string", - description: "Payment nonce for tokenized payments.", - }) - .option("state", { type: "string", description: "Billing state." }) - .option("type", { - type: "string", - description: "The payment method type.", +const parameters = { + flags: { + address: { + kind: "parsed", + brief: "Billing address line 1.", + optional: true, + parse: String, + }, + address2: { + kind: "parsed", + brief: "Billing address line 2.", + optional: true, + parse: String, + }, + "bank-account-type": { + kind: "parsed", + brief: "Bank account type.", + optional: true, + parse: String, + }, + "bank-code": { + kind: "parsed", + brief: "Bank code.", + optional: true, + parse: String, + }, + "bank-country": { + kind: "parsed", + brief: "Bank country.", + optional: true, + parse: String, + }, + "bank-name": { + kind: "parsed", + brief: "Bank name for bank-based payment methods.", + optional: true, + parse: String, + }, + "bank-routing-number": { + kind: "parsed", + brief: "Bank routing number.", + optional: true, + parse: String, + }, + "cashapp-cash-tag": { + kind: "parsed", + brief: "Cash App cash tag.", + optional: true, + parse: String, + }, + city: { + kind: "parsed", + brief: "Billing city.", + optional: true, + parse: String, + }, + country: { + kind: "parsed", + brief: "Billing country.", + optional: true, + parse: String, + }, + default: { + kind: "boolean", + brief: "Whether this is the default payment method.", + optional: true, + }, + "device-data": { + kind: "parsed", + brief: "Device data for fraud prevention.", + optional: true, + parse: String, + }, + "first-name": { + kind: "parsed", + brief: "Billing first name.", + optional: true, + parse: String, + }, + "last-name": { + kind: "parsed", + brief: "Billing last name.", + optional: true, + parse: String, + }, + "nick-name": { + kind: "parsed", + brief: "A nickname for the payment method.", + optional: true, + parse: String, + }, + "payment-account-email": { + kind: "parsed", + brief: "Email associated with the payment account.", + optional: true, + parse: String, + }, + "payment-email": { + kind: "parsed", + brief: "Payment email address.", + optional: true, + parse: String, + }, + "payment-gateway": { + kind: "parsed", + brief: "The payment gateway used.", + optional: true, + parse: String, + }, + "payment-nonce": { + kind: "parsed", + brief: "Payment nonce for tokenized payments.", + optional: true, + parse: String, + }, + state: { + kind: "parsed", + brief: "Billing state.", + optional: true, + parse: String, + }, + type: { + kind: "parsed", + brief: "The payment method type.", + optional: true, choices: [ "CREDIT_CARD", "PAYPAL", @@ -97,280 +142,37 @@ function builder(yargs: Argv) { "LINK", "ACH_DIRECT_DEBIT", ], - }) - .coerce("type", (value) => resolveFileToken(value, "type", "text")) - .option("zipcode", { type: "string", description: "Billing zip code." }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => resolveFileToken(value, "type", "text"), + }, + zipcode: { + kind: "parsed", + brief: "Billing zip code.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Create Payment Method", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts billing payment-methods create", - classification: { - safeFlags: ["default", "type", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts billing payment-methods create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/payment-methods`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - address: resolveFileToken( - argv["address"] as string | undefined, - "address", - "text" - ), - address2: resolveFileToken( - argv["address2"] as string | undefined, - "address2", - "text" - ), - bank_account_type: resolveFileToken( - argv["bank-account-type"] as string | undefined, - "bank-account-type", - "text" - ), - bank_code: resolveFileToken( - argv["bank-code"] as string | undefined, - "bank-code", - "text" - ), - bank_country: resolveFileToken( - argv["bank-country"] as string | undefined, - "bank-country", - "text" - ), - bank_name: resolveFileToken( - argv["bank-name"] as string | undefined, - "bank-name", - "text" - ), - bank_routing_number: resolveFileToken( - argv["bank-routing-number"] as string | undefined, - "bank-routing-number", - "text" - ), - cashapp_cash_tag: resolveFileToken( - argv["cashapp-cash-tag"] as string | undefined, - "cashapp-cash-tag", - "text" - ), - city: resolveFileToken( - argv["city"] as string | undefined, - "city", - "text" - ), - country: resolveFileToken( - argv["country"] as string | undefined, - "country", - "text" - ), - default: argv["default"], - device_data: resolveFileToken( - argv["device-data"] as string | undefined, - "device-data", - "text" - ), - first_name: resolveFileToken( - argv["first-name"] as string | undefined, - "first-name", - "text" - ), - last_name: resolveFileToken( - argv["last-name"] as string | undefined, - "last-name", - "text" - ), - nick_name: resolveFileToken( - argv["nick-name"] as string | undefined, - "nick-name", - "text" - ), - payment_account_email: resolveFileToken( - argv["payment-account-email"] as string | undefined, - "payment-account-email", - "text" - ), - payment_email: resolveFileToken( - argv["payment-email"] as string | undefined, - "payment-email", - "text" - ), - payment_gateway: resolveFileToken( - argv["payment-gateway"] as string | undefined, - "payment-gateway", - "text" - ), - payment_nonce: resolveFileToken( - argv["payment-nonce"] as string | undefined, - "payment-nonce", - "text" - ), - state: resolveFileToken( - argv["state"] as string | undefined, - "state", - "text" - ), - type: argv["type"], - zipcode: resolveFileToken( - argv["zipcode"] as string | undefined, - "zipcode", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - address: resolveFileToken( - argv["address"] as string | undefined, - "address", - "text" - ), - address2: resolveFileToken( - argv["address2"] as string | undefined, - "address2", - "text" - ), - bank_account_type: resolveFileToken( - argv["bank-account-type"] as string | undefined, - "bank-account-type", - "text" - ), - bank_code: resolveFileToken( - argv["bank-code"] as string | undefined, - "bank-code", - "text" - ), - bank_country: resolveFileToken( - argv["bank-country"] as string | undefined, - "bank-country", - "text" - ), - bank_name: resolveFileToken( - argv["bank-name"] as string | undefined, - "bank-name", - "text" - ), - bank_routing_number: resolveFileToken( - argv["bank-routing-number"] as string | undefined, - "bank-routing-number", - "text" - ), - cashapp_cash_tag: resolveFileToken( - argv["cashapp-cash-tag"] as string | undefined, - "cashapp-cash-tag", - "text" - ), - city: resolveFileToken( - argv["city"] as string | undefined, - "city", - "text" - ), - country: resolveFileToken( - argv["country"] as string | undefined, - "country", - "text" - ), - default: argv["default"], - device_data: resolveFileToken( - argv["device-data"] as string | undefined, - "device-data", - "text" - ), - first_name: resolveFileToken( - argv["first-name"] as string | undefined, - "first-name", - "text" - ), - last_name: resolveFileToken( - argv["last-name"] as string | undefined, - "last-name", - "text" - ), - nick_name: resolveFileToken( - argv["nick-name"] as string | undefined, - "nick-name", - "text" - ), - payment_account_email: resolveFileToken( - argv["payment-account-email"] as string | undefined, - "payment-account-email", - "text" - ), - payment_email: resolveFileToken( - argv["payment-email"] as string | undefined, - "payment-email", - "text" - ), - payment_gateway: resolveFileToken( - argv["payment-gateway"] as string | undefined, - "payment-gateway", - "text" - ), - payment_nonce: resolveFileToken( - argv["payment-nonce"] as string | undefined, - "payment-nonce", - "text" - ), - state: resolveFileToken( - argv["state"] as string | undefined, - "state", - "text" - ), - type: argv["type"], - zipcode: resolveFileToken( - argv["zipcode"] as string | undefined, - "zipcode", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 accounts billing payment-methods create\n\nCreates a new payment method for an account.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/billing/payment-methods/delete.handler.ts b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/delete.handler.ts new file mode 100644 index 0000000000..fa35b759bb --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/delete.handler.ts @@ -0,0 +1,57 @@ +import operation from "../../../_operations/accounts/billing/payment-methods/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts billing payment-methods delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts billing payment-methods delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/payment-methods/${argv["payment-method-id"] == null ? "" : encodeURIComponent(String(argv["payment-method-id"]))}`, + pathParams: { + "payment-method-id": String(argv["payment-method-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + payment_method_id: argv["payment-method-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/billing/payment-methods/delete.ts b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/delete.ts index 505432c5b0..6a6837d130 100644 --- a/packages/cli/src/commands/_generated/accounts/billing/payment-methods/delete.ts +++ b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/delete.ts @@ -1,93 +1,43 @@ -import operation from "../../../_operations/accounts/billing/payment-methods/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts billing payment-methods delete \n\nDeletes a payment method from an account." - ) - .positional("payment-method-id", { - type: "string", - description: "Payment method identifier.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "payment-method-id", + brief: "Payment method identifier.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete Payment Method", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts billing payment-methods delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts billing payment-methods delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/payment-methods/${argv["payment-method-id"] == null ? "" : encodeURIComponent(String(argv["payment-method-id"]))}`, - pathParams: { - "payment-method-id": String(argv["payment-method-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - payment_method_id: argv["payment-method-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 accounts billing payment-methods delete \n\nDeletes a payment method from an account.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/billing/payment-methods/get.handler.ts b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/get.handler.ts new file mode 100644 index 0000000000..71bbde9f0e --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/get.handler.ts @@ -0,0 +1,51 @@ +import operation from "../../../_operations/accounts/billing/payment-methods/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts billing payment-methods get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts billing payment-methods get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/payment-methods/${argv["payment-method-id"] == null ? "" : encodeURIComponent(String(argv["payment-method-id"]))}`, + pathParams: { + "payment-method-id": String(argv["payment-method-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + payment_method_id: argv["payment-method-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/billing/payment-methods/get.ts b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/get.ts index 5ad81f0b48..abbf98b428 100644 --- a/packages/cli/src/commands/_generated/accounts/billing/payment-methods/get.ts +++ b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/get.ts @@ -1,81 +1,37 @@ -import operation from "../../../_operations/accounts/billing/payment-methods/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts billing payment-methods get \n\nGets a specific payment method for an account." - ) - .positional("payment-method-id", { - type: "string", - description: "Payment method identifier.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "payment-method-id", + brief: "Payment method identifier.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get Payment Method", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts billing payment-methods get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts billing payment-methods get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/payment-methods/${argv["payment-method-id"] == null ? "" : encodeURIComponent(String(argv["payment-method-id"]))}`, - pathParams: { - "payment-method-id": String(argv["payment-method-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - payment_method_id: argv["payment-method-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts billing payment-methods get \n\nGets a specific payment method for an account.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/billing/payment-methods/index.ts b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/index.ts index e39499b1bd..671e789c8d 100644 --- a/packages/cli/src/commands/_generated/accounts/billing/payment-methods/index.ts +++ b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/index.ts @@ -4,29 +4,24 @@ import $get from "./get.js"; import $list from "./list.js"; import $setdefault from "./set-default.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * payment-methods command group * @generated from apis/overlays/accounts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "payment-methods", describe: "Operations for billing.payment-methods", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .command($list) - .command($setdefault) - .command($update) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, + list: $list, + "set-default": $setdefault, + update: $update, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/billing/payment-methods/list.handler.ts b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/list.handler.ts new file mode 100644 index 0000000000..d0bc735627 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/list.handler.ts @@ -0,0 +1,51 @@ +import operation from "../../../_operations/accounts/billing/payment-methods/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts billing payment-methods list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts billing payment-methods list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/payment-methods`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/billing/payment-methods/list.ts b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/list.ts index 031a558b15..d08e24cbd6 100644 --- a/packages/cli/src/commands/_generated/accounts/billing/payment-methods/list.ts +++ b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/list.ts @@ -1,84 +1,43 @@ -import operation from "../../../_operations/accounts/billing/payment-methods/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts billing payment-methods list\n\nLists all payment methods for an account." - ) - .option("page", { - type: "number", - description: "Page number of paginated results.", - }) - .option("per-page", { - type: "number", - description: "Number of items per page.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + page: { + kind: "parsed", + brief: "Page number of paginated results.", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Number of items per page.", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Payment Methods", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts billing payment-methods list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts billing payment-methods list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/payment-methods`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts billing payment-methods list\n\nLists all payment methods for an account.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/billing/payment-methods/set-default.handler.ts b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/set-default.handler.ts new file mode 100644 index 0000000000..fb688f2d5d --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/set-default.handler.ts @@ -0,0 +1,51 @@ +import operation from "../../../_operations/accounts/billing/payment-methods/set-default.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./set-default.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts billing payment-methods set-default", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts billing payment-methods set-default", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/payment-methods/${argv["payment-method-id"] == null ? "" : encodeURIComponent(String(argv["payment-method-id"]))}/set-as-default`, + pathParams: { + "payment-method-id": String(argv["payment-method-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Creating`, async () => + client.send(operation, { + account_id: accountId, + payment_method_id: argv["payment-method-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/billing/payment-methods/set-default.ts b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/set-default.ts index 0dd4145331..d7c58bfb8f 100644 --- a/packages/cli/src/commands/_generated/accounts/billing/payment-methods/set-default.ts +++ b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/set-default.ts @@ -1,81 +1,37 @@ -import operation from "../../../_operations/accounts/billing/payment-methods/set-default.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * set-default command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts billing payment-methods set-default \n\nSets a payment method as the default for an account." - ) - .positional("payment-method-id", { - type: "string", - description: "Payment method identifier.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "payment-method-id", + brief: "Payment method identifier.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "set-default ", describe: "Set Default Payment Method", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts billing payment-methods set-default", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts billing payment-methods set-default", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/payment-methods/${argv["payment-method-id"] == null ? "" : encodeURIComponent(String(argv["payment-method-id"]))}/set-as-default`, - pathParams: { - "payment-method-id": String(argv["payment-method-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Creating`, async () => - client.send(operation, { - account_id: accountId, - payment_method_id: argv["payment-method-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 accounts billing payment-methods set-default \n\nSets a payment method as the default for an account.", + ...parameters, + loader: () => import("./set-default.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/billing/payment-methods/update.handler.ts b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/update.handler.ts new file mode 100644 index 0000000000..fecdc35954 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/update.handler.ts @@ -0,0 +1,281 @@ +import operation from "../../../_operations/accounts/billing/payment-methods/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts billing payment-methods update", + classification: { + safeFlags: ["default", "type", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts billing payment-methods update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/payment-methods/${argv["payment-method-id"] == null ? "" : encodeURIComponent(String(argv["payment-method-id"]))}`, + pathParams: { + "payment-method-id": String(argv["payment-method-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + address: resolveFileToken( + argv["address"] as string | undefined, + "address", + "text" + ), + address2: resolveFileToken( + argv["address2"] as string | undefined, + "address2", + "text" + ), + bank_account_type: resolveFileToken( + argv["bank-account-type"] as string | undefined, + "bank-account-type", + "text" + ), + bank_code: resolveFileToken( + argv["bank-code"] as string | undefined, + "bank-code", + "text" + ), + bank_country: resolveFileToken( + argv["bank-country"] as string | undefined, + "bank-country", + "text" + ), + bank_name: resolveFileToken( + argv["bank-name"] as string | undefined, + "bank-name", + "text" + ), + bank_routing_number: resolveFileToken( + argv["bank-routing-number"] as string | undefined, + "bank-routing-number", + "text" + ), + cashapp_cash_tag: resolveFileToken( + argv["cashapp-cash-tag"] as string | undefined, + "cashapp-cash-tag", + "text" + ), + city: resolveFileToken( + argv["city"] as string | undefined, + "city", + "text" + ), + country: resolveFileToken( + argv["country"] as string | undefined, + "country", + "text" + ), + default: argv["default"], + device_data: resolveFileToken( + argv["device-data"] as string | undefined, + "device-data", + "text" + ), + first_name: resolveFileToken( + argv["first-name"] as string | undefined, + "first-name", + "text" + ), + last_name: resolveFileToken( + argv["last-name"] as string | undefined, + "last-name", + "text" + ), + nick_name: resolveFileToken( + argv["nick-name"] as string | undefined, + "nick-name", + "text" + ), + payment_account_email: resolveFileToken( + argv["payment-account-email"] as string | undefined, + "payment-account-email", + "text" + ), + payment_email: resolveFileToken( + argv["payment-email"] as string | undefined, + "payment-email", + "text" + ), + payment_gateway: resolveFileToken( + argv["payment-gateway"] as string | undefined, + "payment-gateway", + "text" + ), + payment_nonce: resolveFileToken( + argv["payment-nonce"] as string | undefined, + "payment-nonce", + "text" + ), + state: resolveFileToken( + argv["state"] as string | undefined, + "state", + "text" + ), + type: argv["type"], + zipcode: resolveFileToken( + argv["zipcode"] as string | undefined, + "zipcode", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + payment_method_id: argv["payment-method-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + address: resolveFileToken( + argv["address"] as string | undefined, + "address", + "text" + ), + address2: resolveFileToken( + argv["address2"] as string | undefined, + "address2", + "text" + ), + bank_account_type: resolveFileToken( + argv["bank-account-type"] as string | undefined, + "bank-account-type", + "text" + ), + bank_code: resolveFileToken( + argv["bank-code"] as string | undefined, + "bank-code", + "text" + ), + bank_country: resolveFileToken( + argv["bank-country"] as string | undefined, + "bank-country", + "text" + ), + bank_name: resolveFileToken( + argv["bank-name"] as string | undefined, + "bank-name", + "text" + ), + bank_routing_number: resolveFileToken( + argv["bank-routing-number"] as string | undefined, + "bank-routing-number", + "text" + ), + cashapp_cash_tag: resolveFileToken( + argv["cashapp-cash-tag"] as string | undefined, + "cashapp-cash-tag", + "text" + ), + city: resolveFileToken( + argv["city"] as string | undefined, + "city", + "text" + ), + country: resolveFileToken( + argv["country"] as string | undefined, + "country", + "text" + ), + default: argv["default"], + device_data: resolveFileToken( + argv["device-data"] as string | undefined, + "device-data", + "text" + ), + first_name: resolveFileToken( + argv["first-name"] as string | undefined, + "first-name", + "text" + ), + last_name: resolveFileToken( + argv["last-name"] as string | undefined, + "last-name", + "text" + ), + nick_name: resolveFileToken( + argv["nick-name"] as string | undefined, + "nick-name", + "text" + ), + payment_account_email: resolveFileToken( + argv["payment-account-email"] as string | undefined, + "payment-account-email", + "text" + ), + payment_email: resolveFileToken( + argv["payment-email"] as string | undefined, + "payment-email", + "text" + ), + payment_gateway: resolveFileToken( + argv["payment-gateway"] as string | undefined, + "payment-gateway", + "text" + ), + payment_nonce: resolveFileToken( + argv["payment-nonce"] as string | undefined, + "payment-nonce", + "text" + ), + state: resolveFileToken( + argv["state"] as string | undefined, + "state", + "text" + ), + type: argv["type"], + zipcode: resolveFileToken( + argv["zipcode"] as string | undefined, + "zipcode", + "text" + ), + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + payment_method_id: argv["payment-method-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/billing/payment-methods/update.ts b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/update.ts index 713896d1b9..01e71989f9 100644 --- a/packages/cli/src/commands/_generated/accounts/billing/payment-methods/update.ts +++ b/packages/cli/src/commands/_generated/accounts/billing/payment-methods/update.ts @@ -1,99 +1,139 @@ -import operation from "../../../_operations/accounts/billing/payment-methods/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts billing payment-methods update \n\nUpdates a payment method for an account." - ) - .positional("payment-method-id", { - type: "string", - description: "Payment method identifier.", - demandOption: true, - }) - .option("address", { - type: "string", - description: "Billing address line 1.", - }) - .option("address2", { - type: "string", - description: "Billing address line 2.", - }) - .option("bank-account-type", { - type: "string", - description: "Bank account type.", - }) - .option("bank-code", { type: "string", description: "Bank code." }) - .option("bank-country", { type: "string", description: "Bank country." }) - .option("bank-name", { - type: "string", - description: "Bank name for bank-based payment methods.", - }) - .option("bank-routing-number", { - type: "string", - description: "Bank routing number.", - }) - .option("cashapp-cash-tag", { - type: "string", - description: "Cash App cash tag.", - }) - .option("city", { type: "string", description: "Billing city." }) - .option("country", { type: "string", description: "Billing country." }) - .option("default", { - type: "boolean", - description: "Whether this is the default payment method.", - }) - .option("device-data", { - type: "string", - description: "Device data for fraud prevention.", - }) - .option("first-name", { - type: "string", - description: "Billing first name.", - }) - .option("last-name", { type: "string", description: "Billing last name." }) - .option("nick-name", { - type: "string", - description: "A nickname for the payment method.", - }) - .option("payment-account-email", { - type: "string", - description: "Email associated with the payment account.", - }) - .option("payment-email", { - type: "string", - description: "Payment email address.", - }) - .option("payment-gateway", { - type: "string", - description: "The payment gateway used.", - }) - .option("payment-nonce", { - type: "string", - description: "Payment nonce for tokenized payments.", - }) - .option("state", { type: "string", description: "Billing state." }) - .option("type", { - type: "string", - description: "The payment method type.", +const parameters = { + flags: { + address: { + kind: "parsed", + brief: "Billing address line 1.", + optional: true, + parse: String, + }, + address2: { + kind: "parsed", + brief: "Billing address line 2.", + optional: true, + parse: String, + }, + "bank-account-type": { + kind: "parsed", + brief: "Bank account type.", + optional: true, + parse: String, + }, + "bank-code": { + kind: "parsed", + brief: "Bank code.", + optional: true, + parse: String, + }, + "bank-country": { + kind: "parsed", + brief: "Bank country.", + optional: true, + parse: String, + }, + "bank-name": { + kind: "parsed", + brief: "Bank name for bank-based payment methods.", + optional: true, + parse: String, + }, + "bank-routing-number": { + kind: "parsed", + brief: "Bank routing number.", + optional: true, + parse: String, + }, + "cashapp-cash-tag": { + kind: "parsed", + brief: "Cash App cash tag.", + optional: true, + parse: String, + }, + city: { + kind: "parsed", + brief: "Billing city.", + optional: true, + parse: String, + }, + country: { + kind: "parsed", + brief: "Billing country.", + optional: true, + parse: String, + }, + default: { + kind: "boolean", + brief: "Whether this is the default payment method.", + optional: true, + }, + "device-data": { + kind: "parsed", + brief: "Device data for fraud prevention.", + optional: true, + parse: String, + }, + "first-name": { + kind: "parsed", + brief: "Billing first name.", + optional: true, + parse: String, + }, + "last-name": { + kind: "parsed", + brief: "Billing last name.", + optional: true, + parse: String, + }, + "nick-name": { + kind: "parsed", + brief: "A nickname for the payment method.", + optional: true, + parse: String, + }, + "payment-account-email": { + kind: "parsed", + brief: "Email associated with the payment account.", + optional: true, + parse: String, + }, + "payment-email": { + kind: "parsed", + brief: "Payment email address.", + optional: true, + parse: String, + }, + "payment-gateway": { + kind: "parsed", + brief: "The payment gateway used.", + optional: true, + parse: String, + }, + "payment-nonce": { + kind: "parsed", + brief: "Payment nonce for tokenized payments.", + optional: true, + parse: String, + }, + state: { + kind: "parsed", + brief: "Billing state.", + optional: true, + parse: String, + }, + type: { + kind: "parsed", + brief: "The payment method type.", + optional: true, choices: [ "CREDIT_CARD", "PAYPAL", @@ -102,290 +142,43 @@ function builder(yargs: Argv) { "LINK", "ACH_DIRECT_DEBIT", ], - }) - .coerce("type", (value) => resolveFileToken(value, "type", "text")) - .option("zipcode", { type: "string", description: "Billing zip code." }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => resolveFileToken(value, "type", "text"), + }, + zipcode: { + kind: "parsed", + brief: "Billing zip code.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "payment-method-id", + brief: "Payment method identifier.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update ", describe: "Update Payment Method", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts billing payment-methods update", - classification: { - safeFlags: ["default", "type", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts billing payment-methods update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/payment-methods/${argv["payment-method-id"] == null ? "" : encodeURIComponent(String(argv["payment-method-id"]))}`, - pathParams: { - "payment-method-id": String(argv["payment-method-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - address: resolveFileToken( - argv["address"] as string | undefined, - "address", - "text" - ), - address2: resolveFileToken( - argv["address2"] as string | undefined, - "address2", - "text" - ), - bank_account_type: resolveFileToken( - argv["bank-account-type"] as string | undefined, - "bank-account-type", - "text" - ), - bank_code: resolveFileToken( - argv["bank-code"] as string | undefined, - "bank-code", - "text" - ), - bank_country: resolveFileToken( - argv["bank-country"] as string | undefined, - "bank-country", - "text" - ), - bank_name: resolveFileToken( - argv["bank-name"] as string | undefined, - "bank-name", - "text" - ), - bank_routing_number: resolveFileToken( - argv["bank-routing-number"] as string | undefined, - "bank-routing-number", - "text" - ), - cashapp_cash_tag: resolveFileToken( - argv["cashapp-cash-tag"] as string | undefined, - "cashapp-cash-tag", - "text" - ), - city: resolveFileToken( - argv["city"] as string | undefined, - "city", - "text" - ), - country: resolveFileToken( - argv["country"] as string | undefined, - "country", - "text" - ), - default: argv["default"], - device_data: resolveFileToken( - argv["device-data"] as string | undefined, - "device-data", - "text" - ), - first_name: resolveFileToken( - argv["first-name"] as string | undefined, - "first-name", - "text" - ), - last_name: resolveFileToken( - argv["last-name"] as string | undefined, - "last-name", - "text" - ), - nick_name: resolveFileToken( - argv["nick-name"] as string | undefined, - "nick-name", - "text" - ), - payment_account_email: resolveFileToken( - argv["payment-account-email"] as string | undefined, - "payment-account-email", - "text" - ), - payment_email: resolveFileToken( - argv["payment-email"] as string | undefined, - "payment-email", - "text" - ), - payment_gateway: resolveFileToken( - argv["payment-gateway"] as string | undefined, - "payment-gateway", - "text" - ), - payment_nonce: resolveFileToken( - argv["payment-nonce"] as string | undefined, - "payment-nonce", - "text" - ), - state: resolveFileToken( - argv["state"] as string | undefined, - "state", - "text" - ), - type: argv["type"], - zipcode: resolveFileToken( - argv["zipcode"] as string | undefined, - "zipcode", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - payment_method_id: argv["payment-method-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - address: resolveFileToken( - argv["address"] as string | undefined, - "address", - "text" - ), - address2: resolveFileToken( - argv["address2"] as string | undefined, - "address2", - "text" - ), - bank_account_type: resolveFileToken( - argv["bank-account-type"] as string | undefined, - "bank-account-type", - "text" - ), - bank_code: resolveFileToken( - argv["bank-code"] as string | undefined, - "bank-code", - "text" - ), - bank_country: resolveFileToken( - argv["bank-country"] as string | undefined, - "bank-country", - "text" - ), - bank_name: resolveFileToken( - argv["bank-name"] as string | undefined, - "bank-name", - "text" - ), - bank_routing_number: resolveFileToken( - argv["bank-routing-number"] as string | undefined, - "bank-routing-number", - "text" - ), - cashapp_cash_tag: resolveFileToken( - argv["cashapp-cash-tag"] as string | undefined, - "cashapp-cash-tag", - "text" - ), - city: resolveFileToken( - argv["city"] as string | undefined, - "city", - "text" - ), - country: resolveFileToken( - argv["country"] as string | undefined, - "country", - "text" - ), - default: argv["default"], - device_data: resolveFileToken( - argv["device-data"] as string | undefined, - "device-data", - "text" - ), - first_name: resolveFileToken( - argv["first-name"] as string | undefined, - "first-name", - "text" - ), - last_name: resolveFileToken( - argv["last-name"] as string | undefined, - "last-name", - "text" - ), - nick_name: resolveFileToken( - argv["nick-name"] as string | undefined, - "nick-name", - "text" - ), - payment_account_email: resolveFileToken( - argv["payment-account-email"] as string | undefined, - "payment-account-email", - "text" - ), - payment_email: resolveFileToken( - argv["payment-email"] as string | undefined, - "payment-email", - "text" - ), - payment_gateway: resolveFileToken( - argv["payment-gateway"] as string | undefined, - "payment-gateway", - "text" - ), - payment_nonce: resolveFileToken( - argv["payment-nonce"] as string | undefined, - "payment-nonce", - "text" - ), - state: resolveFileToken( - argv["state"] as string | undefined, - "state", - "text" - ), - type: argv["type"], - zipcode: resolveFileToken( - argv["zipcode"] as string | undefined, - "zipcode", - "text" - ), - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - payment_method_id: argv["payment-method-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 accounts billing payment-methods update \n\nUpdates a payment method for an account.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/billing/toggle-pdf-invoices.handler.ts b/packages/cli/src/commands/_generated/accounts/billing/toggle-pdf-invoices.handler.ts new file mode 100644 index 0000000000..587dd1a897 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/billing/toggle-pdf-invoices.handler.ts @@ -0,0 +1,68 @@ +import operation from "../../_operations/accounts/billing/toggle-pdf-invoices.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./toggle-pdf-invoices.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts billing toggle-pdf-invoices", + classification: { + safeFlags: ["toggle", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts billing toggle-pdf-invoices", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/invoices`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + toggle: argv["toggle"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + toggle: argv["toggle"], + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/billing/toggle-pdf-invoices.ts b/packages/cli/src/commands/_generated/accounts/billing/toggle-pdf-invoices.ts index 342ac13570..44600030e6 100644 --- a/packages/cli/src/commands/_generated/accounts/billing/toggle-pdf-invoices.ts +++ b/packages/cli/src/commands/_generated/accounts/billing/toggle-pdf-invoices.ts @@ -1,101 +1,42 @@ -import operation from "../../_operations/accounts/billing/toggle-pdf-invoices.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * toggle-pdf-invoices command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts billing toggle-pdf-invoices\n\nToggles PDF invoice generation for an account." - ) - .option("toggle", { - type: "boolean", - description: "Whether to enable or disable PDF invoice generation.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + toggle: { + kind: "boolean", + brief: "Whether to enable or disable PDF invoice generation.", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "toggle-pdf-invoices", describe: "Toggle PDF Invoices", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts billing toggle-pdf-invoices", - classification: { - safeFlags: ["toggle", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts billing toggle-pdf-invoices", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/invoices`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - toggle: argv["toggle"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - toggle: argv["toggle"], - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 accounts billing toggle-pdf-invoices\n\nToggles PDF invoice generation for an account.", + ...parameters, + loader: () => import("./toggle-pdf-invoices.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/categories/get.handler.ts b/packages/cli/src/commands/_generated/accounts/categories/get.handler.ts new file mode 100644 index 0000000000..7430b00f83 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/categories/get.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/accounts/categories/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts categories get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts categories get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/resource-library/categories/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, + pathParams: { id: String(argv["id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, id: argv["id"] }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/categories/get.ts b/packages/cli/src/commands/_generated/accounts/categories/get.ts index d25a318e99..29545f2616 100644 --- a/packages/cli/src/commands/_generated/accounts/categories/get.ts +++ b/packages/cli/src/commands/_generated/accounts/categories/get.ts @@ -1,76 +1,33 @@ -import operation from "../../_operations/accounts/categories/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts categories get \n\nRetrieve an application category by its numeric ID." - ) - .positional("id", { - type: "string", - description: "Application category ID.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "id", brief: "Application category ID.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get application category", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts categories get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts categories get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/resource-library/categories/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, - pathParams: { id: String(argv["id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, id: argv["id"] }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts categories get \n\nRetrieve an application category by its numeric ID.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/categories/index.ts b/packages/cli/src/commands/_generated/accounts/categories/index.ts index 2b53f0c117..19584457fe 100644 --- a/packages/cli/src/commands/_generated/accounts/categories/index.ts +++ b/packages/cli/src/commands/_generated/accounts/categories/index.ts @@ -1,24 +1,19 @@ import $get from "./get.js"; import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * categories command group * @generated from apis/overlays/accounts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "categories", describe: "Browse the categories used to classify applications", - builder: (yargs) => { - return yargs - .command($get) - .command($list) - .demandCommand(1, "Please specify a subcommand"); + routes: { + get: $get, + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/categories/list.handler.ts b/packages/cli/src/commands/_generated/accounts/categories/list.handler.ts new file mode 100644 index 0000000000..cd3dc5b301 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/categories/list.handler.ts @@ -0,0 +1,52 @@ +import operation from "../../_operations/accounts/categories/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts categories list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + limit: argv["limit"], + offset: argv["offset"], + cursor: argv["cursor"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts categories list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/resource-library/categories`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/categories/list.ts b/packages/cli/src/commands/_generated/accounts/categories/list.ts index 458950452e..f35f29be32 100644 --- a/packages/cli/src/commands/_generated/accounts/categories/list.ts +++ b/packages/cli/src/commands/_generated/accounts/categories/list.ts @@ -1,92 +1,52 @@ -import operation from "../../_operations/accounts/categories/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts categories list\n\nList the categories available for classifying applications, ordered by name, ignoring the case of the letters A to Z. Results are paginated by `offset` or `cursor`." - ) - .option("limit", { - type: "number", - description: +const parameters = { + flags: { + limit: { + kind: "parsed", + brief: "Number of results to return. Defaults to 25; values are clamped to 1–250.", - }) - .option("offset", { - type: "number", - description: + optional: true, + parse: Number, + }, + offset: { + kind: "parsed", + brief: "Number of results to skip. Defaults to 0; negative values are clamped to 0. Ignored when `cursor` is provided.", - }) - .option("cursor", { - type: "string", - description: + optional: true, + parse: Number, + }, + cursor: { + kind: "parsed", + brief: "Opaque value from `result_info.cursor` of the previous response. Returns the\ncategories that follow it. `limit` may change between requests. An empty value\nis the same as no cursor. A modified cursor, or one returned by a different list,\nreturns `400`.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List application categories", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts categories list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - limit: argv["limit"], - offset: argv["offset"], - cursor: argv["cursor"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts categories list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/resource-library/categories`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts categories list\n\nList the categories available for classifying applications, ordered by name, ignoring the case of the letters A to Z. Results are paginated by `offset` or `cursor`.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/create.handler.ts b/packages/cli/src/commands/_generated/accounts/create.handler.ts new file mode 100644 index 0000000000..1e33391f22 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/create.handler.ts @@ -0,0 +1,113 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { createCommandClient, requestApi } from "#lib/auth.js"; +import { compactBody, parseBody, setNestedValue } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts create", + classification: { + safeFlags: ["standalone", "type", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const headers: Record = {}; + if (argv["idempotency-key"] !== undefined) + headers["Idempotency-Key"] = String(argv["idempotency-key"]); + const resolveRequiredFields = async (): Promise => { + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField( + "name", + "Account name, limited to 65 UTF-8 bytes." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + formatDryRun({ + command: "cf accounts create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + standalone: argv["standalone"], + type: argv["type"], + unit: { + id: resolveFileToken( + argv["unit-id"] as string | undefined, + "unit-id", + "text" + ), + }, + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + requestApi(client, "POST", `/accounts`, { + body: bodyData, + headers: Object.keys(headers).length > 0 ? headers : undefined, + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData: Record = {}; + if (argv["name"] !== undefined) + setNestedValue( + bodyData, + ["name"], + resolveFileToken(argv["name"] as string | undefined, "name", "text") + ); + if (argv["standalone"] !== undefined) + setNestedValue(bodyData, ["standalone"], argv["standalone"]); + if (argv["type"] !== undefined) + setNestedValue(bodyData, ["type"], argv["type"]); + if (argv["unit-id"] !== undefined) + setNestedValue( + bodyData, + ["unit", "id"], + resolveFileToken( + argv["unit-id"] as string | undefined, + "unit-id", + "text" + ) + ); + const result = await withProgress(`Creating`, async () => + requestApi(client, "POST", `/accounts`, { + body: bodyData, + headers: Object.keys(headers).length > 0 ? headers : undefined, + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/create.ts b/packages/cli/src/commands/_generated/accounts/create.ts index fde8bd38b0..8dfec12517 100644 --- a/packages/cli/src/commands/_generated/accounts/create.ts +++ b/packages/cli/src/commands/_generated/accounts/create.ts @@ -1,165 +1,72 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, requestApi } from "#lib/auth.js"; -import { compactBody, parseBody, setNestedValue } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts create\n\nCreate an Account. To create the Account within an Organization, provide `unit.id` and omit `standalone`. To create a standalone Free Account, provide `standalone: true` and omit `unit`. Providing both fields is invalid. If you omit both fields, Cloudflare can determine the destination only when the User is an administrator of exactly one Organization. Cloudflare creates the Account in that Organization; otherwise, the request returns an error. Account names are limited to 65 UTF-8 bytes." - ) - .option("idempotency-key", { - type: "string", - description: +const parameters = { + flags: { + "idempotency-key": { + kind: "parsed", + brief: "Optional key that identifies an Account-creation request. Free Account creation can require exactly one valid key, so API clients should send a key with every Account-creation request. Reuse the same key when retrying the same request.", - }) - .option("name", { - type: "string", - description: "Account name, limited to 65 UTF-8 bytes.", - }) - .option("standalone", { - type: "boolean", - description: + optional: true, + parse: String, + }, + name: { + kind: "parsed", + brief: "Account name, limited to 65 UTF-8 bytes.", + optional: true, + parse: String, + }, + standalone: { + kind: "boolean", + brief: "Set to `true` and omit `unit` to create a standalone Free Account. If provided, this field must be `true`.", - }) - .option("type", { - type: "string", - description: + optional: true, + }, + type: { + kind: "parsed", + brief: "the type of account being created. For self-serve customers, use standard. for enterprise customers, use enterprise.", - choices: ["standard", "enterprise"], default: "standard", - }) - .coerce("type", (value) => resolveFileToken(value, "type", "text")) - .option("unit-id", { type: "string", description: "Tenant unit ID" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + choices: ["standard", "enterprise"], + parse: String, + coerce: (value: string) => resolveFileToken(value, "type", "text"), + }, + "unit-id": { + kind: "parsed", + brief: "Tenant unit ID", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Parameters for account creation", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Parameters for account creation", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Create an Account", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts create", - classification: { - safeFlags: ["standalone", "type", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const headers: Record = {}; - if (argv["idempotency-key"] !== undefined) - headers["Idempotency-Key"] = String(argv["idempotency-key"]); - const resolveRequiredFields = async (): Promise => { - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "Account name, limited to 65 UTF-8 bytes." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - formatDryRun({ - command: "cf accounts create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - standalone: argv["standalone"], - type: argv["type"], - unit: { - id: resolveFileToken( - argv["unit-id"] as string | undefined, - "unit-id", - "text" - ), - }, - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - requestApi(client, "POST", `/accounts`, { - body: bodyData, - headers: Object.keys(headers).length > 0 ? headers : undefined, - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData: Record = {}; - if (argv["name"] !== undefined) - setNestedValue( - bodyData, - ["name"], - resolveFileToken(argv["name"] as string | undefined, "name", "text") - ); - if (argv["standalone"] !== undefined) - setNestedValue(bodyData, ["standalone"], argv["standalone"]); - if (argv["type"] !== undefined) - setNestedValue(bodyData, ["type"], argv["type"]); - if (argv["unit-id"] !== undefined) - setNestedValue( - bodyData, - ["unit", "id"], - resolveFileToken( - argv["unit-id"] as string | undefined, - "unit-id", - "text" - ) - ); - const result = await withProgress(`Creating`, async () => - requestApi(client, "POST", `/accounts`, { - body: bodyData, - headers: Object.keys(headers).length > 0 ? headers : undefined, - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 accounts create\n\nCreate an Account. To create the Account within an Organization, provide `unit.id` and omit `standalone`. To create a standalone Free Account, provide `standalone: true` and omit `unit`. Providing both fields is invalid. If you omit both fields, Cloudflare can determine the destination only when the User is an administrator of exactly one Organization. Cloudflare creates the Account in that Organization; otherwise, the request returns an error. Account names are limited to 65 UTF-8 bytes.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/delete.handler.ts b/packages/cli/src/commands/_generated/accounts/delete.handler.ts new file mode 100644 index 0000000000..d2a72a12df --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/delete.handler.ts @@ -0,0 +1,57 @@ +import operation from "../_operations/accounts/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `Are you sure? This action cannot be undone.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/delete.ts b/packages/cli/src/commands/_generated/accounts/delete.ts index 863f84ee32..9a690dbf23 100644 --- a/packages/cli/src/commands/_generated/accounts/delete.ts +++ b/packages/cli/src/commands/_generated/accounts/delete.ts @@ -1,88 +1,37 @@ -import operation from "../_operations/accounts/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts delete\n\nDelete a specific account (only available for tenant admins at this time). This is a permanent operation that will delete any zones or other resources under the account" - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete", describe: "Delete a specific account", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `Are you sure? This action cannot be undone.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 accounts delete\n\nDelete a specific account (only available for tenant admins at this time). This is a permanent operation that will delete any zones or other resources under the account", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/entitlements/get.handler.ts b/packages/cli/src/commands/_generated/accounts/entitlements/get.handler.ts new file mode 100644 index 0000000000..b76bc2786f --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/entitlements/get.handler.ts @@ -0,0 +1,67 @@ +import operation from "../../_operations/accounts/entitlements/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + getZoneId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts entitlements get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = + argv.zone === undefined ? await resolveAccountIdSilent() : undefined; + const accountOrZone = argv.zone === undefined ? "accounts" : "zones"; + const accountOrZoneId = + argv.zone ?? __cfDryRunAccountId ?? ""; + formatDryRun({ + command: "cf accounts entitlements get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/${accountOrZone}/${accountOrZoneId}/entitlements`, + pathParams: { + "account-or-zone": String(accountOrZone), + "account-or-zone-id": String(accountOrZoneId), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountOrZone = argv.zone === undefined ? "accounts" : "zones"; + const accountOrZoneId = + accountOrZone === "zones" + ? await getZoneId({ zone: argv.zone }, client, { quiet: argv.quiet }) + : argv.local + ? LOCAL_ACCOUNT_ID + : await getAccountId(); + if (accountOrZone === "zones") { + argv.zoneId = accountOrZoneId; + } else { + argv.accountId = accountOrZoneId; + } + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_or_zone: accountOrZone, + account_or_zone_id: accountOrZoneId, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/entitlements/get.ts b/packages/cli/src/commands/_generated/accounts/entitlements/get.ts index 1d18fdc4e6..e9413e6aa3 100644 --- a/packages/cli/src/commands/_generated/accounts/entitlements/get.ts +++ b/packages/cli/src/commands/_generated/accounts/entitlements/get.ts @@ -1,96 +1,31 @@ -import operation from "../../_operations/accounts/entitlements/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - getZoneId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts entitlements get\n\nReturns the list of entitlements (features and their allocations) for a given account or zone. Each entitlement describes a product feature the account or zone is permitted to use and the allocation value (boolean, count, range, enum, or string) that governs its behaviour.\n\nRuns against your account. Pass --zone to run against a zone instead. CLOUDFLARE_ZONE_ID is ignored." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "Get account or zone Entitlements", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts entitlements get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = - argv.zone === undefined - ? await resolveAccountIdSilent() - : undefined; - const accountOrZone = argv.zone === undefined ? "accounts" : "zones"; - const accountOrZoneId = - argv.zone ?? __cfDryRunAccountId ?? ""; - formatDryRun({ - command: "cf accounts entitlements get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/${accountOrZone}/${accountOrZoneId}/entitlements`, - pathParams: { - "account-or-zone": String(accountOrZone), - "account-or-zone-id": String(accountOrZoneId), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountOrZone = argv.zone === undefined ? "accounts" : "zones"; - const accountOrZoneId = - accountOrZone === "zones" - ? await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }) - : argv.local - ? LOCAL_ACCOUNT_ID - : await getAccountId(); - if (accountOrZone === "zones") { - argv.zoneId = accountOrZoneId; - } else { - argv.accountId = accountOrZoneId; - } - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_or_zone: accountOrZone, - account_or_zone_id: accountOrZoneId, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts entitlements get\n\nReturns the list of entitlements (features and their allocations) for a given account or zone. Each entitlement describes a product feature the account or zone is permitted to use and the allocation value (boolean, count, range, enum, or string) that governs its behaviour.\n\nRuns against your account. Pass --zone to run against a zone instead. CLOUDFLARE_ZONE_ID is ignored.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/entitlements/index.ts b/packages/cli/src/commands/_generated/accounts/entitlements/index.ts index 335b9d6433..8ca6d1763d 100644 --- a/packages/cli/src/commands/_generated/accounts/entitlements/index.ts +++ b/packages/cli/src/commands/_generated/accounts/entitlements/index.ts @@ -1,20 +1,17 @@ import $get from "./get.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * entitlements command group * @generated from apis/overlays/accounts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "entitlements", describe: "Operations for entitlements", - builder: (yargs) => { - return yargs.command($get).demandCommand(1, "Please specify a subcommand"); + routes: { + get: $get, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/get.handler.ts b/packages/cli/src/commands/_generated/accounts/get.handler.ts new file mode 100644 index 0000000000..631a6f56c0 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/get.handler.ts @@ -0,0 +1,46 @@ +import operation from "../_operations/accounts/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/get.ts b/packages/cli/src/commands/_generated/accounts/get.ts index c683ee0901..4cbe953334 100644 --- a/packages/cli/src/commands/_generated/accounts/get.ts +++ b/packages/cli/src/commands/_generated/accounts/get.ts @@ -1,71 +1,31 @@ -import operation from "../_operations/accounts/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts get\n\nGet information about a specific account that you are a member of." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "Account Details", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts get\n\nGet information about a specific account that you are a member of.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/index.ts b/packages/cli/src/commands/_generated/accounts/index.ts index cfba7e6254..ac3b85392a 100644 --- a/packages/cli/src/commands/_generated/accounts/index.ts +++ b/packages/cli/src/commands/_generated/accounts/index.ts @@ -16,42 +16,37 @@ import $tokens from "./tokens/index.js"; import $transformations from "./transformations/index.js"; import $update from "./update.js"; import $utbilling from "./ut-billing/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * accounts command * @generated from apis/overlays/accounts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "accounts", describe: "Account settings, members, roles, subscriptions, and API tokens for your Cloudflare account", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .command($list) - .command($move) - .command($update) - .command($applications) - .command($billing) - .command($categories) - .command($entitlements) - .command($logs) - .command($members) - .command($organizations) - .command($profile) - .command($subscriptions) - .command($tokens) - .command($transformations) - .command($utbilling) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, + list: $list, + move: $move, + update: $update, + applications: $applications, + billing: $billing, + categories: $categories, + entitlements: $entitlements, + logs: $logs, + members: $members, + organizations: $organizations, + profile: $profile, + subscriptions: $subscriptions, + tokens: $tokens, + transformations: $transformations, + "ut-billing": $utbilling, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/list.handler.ts b/packages/cli/src/commands/_generated/accounts/list.handler.ts new file mode 100644 index 0000000000..ba774f4827 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/list.handler.ts @@ -0,0 +1,45 @@ +import operation from "../_operations/accounts/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { createCommandClient } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts list", + classification: { + safeFlags: ["direction", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + name: argv["name"], + page: argv["page"], + per_page: argv["per-page"], + direction: argv["direction"], + }; + if (argv.dryRun) { + formatDryRun({ + command: "cf accounts list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + + const result = await withProgress(`Loading`, async () => + client.send(operation, queryParams) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/list.ts b/packages/cli/src/commands/_generated/accounts/list.ts index 630d1278f6..813c5a3c07 100644 --- a/packages/cli/src/commands/_generated/accounts/list.ts +++ b/packages/cli/src/commands/_generated/accounts/list.ts @@ -1,84 +1,55 @@ -import operation from "../_operations/accounts/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts list\n\nList all accounts you have ownership or verified access to." - ) - .option("name", { type: "string", description: "Name of the account." }) - .option("page", { - type: "number", - description: "Page number of paginated results.", - }) - .option("per-page", { - type: "number", - description: "Maximum number of results per page.", - }) - .option("direction", { - type: "string", - description: "Direction to order results.", - choices: ["asc", "desc"], - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + name: { + kind: "parsed", + brief: "Name of the account.", + optional: true, + parse: String, + }, + page: { + kind: "parsed", + brief: "Page number of paginated results.", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Maximum number of results per page.", + optional: true, + parse: Number, + }, + direction: { + kind: "enum", + brief: "Direction to order results.", + values: ["asc", "desc"], + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Accounts", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts list", - classification: { - safeFlags: ["direction", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - name: argv["name"], - page: argv["page"], - per_page: argv["per-page"], - direction: argv["direction"], - }; - if (argv.dryRun) { - formatDryRun({ - command: "cf accounts list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - - const result = await withProgress(`Loading`, async () => - client.send(operation, queryParams) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts list\n\nList all accounts you have ownership or verified access to.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/logs/audit/history.handler.ts b/packages/cli/src/commands/_generated/accounts/logs/audit/history.handler.ts new file mode 100644 index 0000000000..02ce7dd6d7 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/logs/audit/history.handler.ts @@ -0,0 +1,59 @@ +import operation from "../../../_operations/accounts/logs/audit/history.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./history.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts logs audit history", + classification: { + safeFlags: ["direction", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + action_time: argv["action-time"], + since: argv["since"], + before: argv["before"], + direction: argv["direction"], + limit: argv["limit"], + cursor: argv["cursor"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts logs audit history", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/logs/audit/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}/history`, + pathParams: { id: String(argv["id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + id: argv["id"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/logs/audit/history.ts b/packages/cli/src/commands/_generated/accounts/logs/audit/history.ts index 9b27e3ec73..6ad3f74656 100644 --- a/packages/cli/src/commands/_generated/accounts/logs/audit/history.ts +++ b/packages/cli/src/commands/_generated/accounts/logs/audit/history.ts @@ -1,123 +1,76 @@ -import operation from "../../../_operations/accounts/logs/audit/history.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * history command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts logs audit history \n\nReturns the chronological change history for the resource identified by the given audit log entry. The endpoint first locates the source audit log entry by `id` (using `action_time` to narrow the lookup window), derives identifying filters from that entry, and then returns matching audit logs within the `since`/`before` window. The `result_info.history_status` field indicates the quality of the resource identification used: - `exact`: Resource was identified by the resource URI. - `approximate`: Resource was identified without the resource URI. - `unavailable`: The source audit log entry did not contain enough information to identify the resource; an empty result is returned." - ) - .positional("id", { - type: "string", - description: "The ID of the audit log to fetch resource history for.", - demandOption: true, - }) - .option("action-time", { - type: "string", - description: +const parameters = { + flags: { + "action-time": { + kind: "parsed", + brief: "RFC3339 timestamp of the source audit log entry's action time. Used to narrow the source-entry lookup window. Provide the `action.time` value from the audit log identified by `id`.", - demandOption: true, - }) - .option("since", { - type: "string", - description: + parse: String, + }, + since: { + kind: "parsed", + brief: "Limits the returned results to logs newer than the specified date. This can be a date string 2019-04-30 (interpreted in UTC) or an absolute timestamp that conforms to RFC3339.", - demandOption: true, - }) - .option("before", { - type: "string", - description: + parse: String, + }, + before: { + kind: "parsed", + brief: "Limits the returned results to logs older than the specified date. This can be a date string 2019-04-30 (interpreted in UTC) or an absolute timestamp that conforms to RFC3339.", - demandOption: true, - }) - .option("direction", { - type: "string", - description: "Sets sorting order.", - choices: ["desc", "asc"], - }) - .option("limit", { - type: "number", - description: + parse: String, + }, + direction: { + kind: "enum", + brief: "Sets sorting order.", + values: ["desc", "asc"], + optional: true, + }, + limit: { + kind: "parsed", + brief: "The number limits the objects to return. The cursor attribute may be used to iterate over the next batch of objects if there are more than the limit.", - }) - .option("cursor", { - type: "string", - description: + optional: true, + parse: Number, + }, + cursor: { + kind: "parsed", + brief: "The cursor is an opaque token used to paginate through large sets of records. It indicates the position from which to continue when requesting the next set of records. A valid cursor value can be obtained from the cursor object in the result_info structure of a previous response.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "id", + brief: "The ID of the audit log to fetch resource history for.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "history ", describe: "Get resource change history from an account audit log entry (Version 2)", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts logs audit history", - classification: { - safeFlags: ["direction", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - action_time: argv["action-time"], - since: argv["since"], - before: argv["before"], - direction: argv["direction"], - limit: argv["limit"], - cursor: argv["cursor"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts logs audit history", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/logs/audit/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}/history`, - pathParams: { id: String(argv["id"] ?? "") }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - id: argv["id"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts logs audit history \n\nReturns the chronological change history for the resource identified by the given audit log entry. The endpoint first locates the source audit log entry by `id` (using `action_time` to narrow the lookup window), derives identifying filters from that entry, and then returns matching audit logs within the `since`/`before` window. The `result_info.history_status` field indicates the quality of the resource identification used: - `exact`: Resource was identified by the resource URI. - `approximate`: Resource was identified without the resource URI. - `unavailable`: The source audit log entry did not contain enough information to identify the resource; an empty result is returned.", + ...parameters, + loader: () => import("./history.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/logs/audit/index.ts b/packages/cli/src/commands/_generated/accounts/logs/audit/index.ts index 14e4539240..9a11c9b75e 100644 --- a/packages/cli/src/commands/_generated/accounts/logs/audit/index.ts +++ b/packages/cli/src/commands/_generated/accounts/logs/audit/index.ts @@ -1,26 +1,21 @@ import $history from "./history.js"; import $list from "./list.js"; import $productcategories from "./product-categories.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * audit command group * @generated from apis/overlays/accounts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "audit", describe: "Operations for logs.audit", - builder: (yargs) => { - return yargs - .command($history) - .command($list) - .command($productcategories) - .demandCommand(1, "Please specify a subcommand"); + routes: { + history: $history, + list: $list, + "product-categories": $productcategories, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/logs/audit/list.handler.ts b/packages/cli/src/commands/_generated/accounts/logs/audit/list.handler.ts new file mode 100644 index 0000000000..7a69bae118 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/logs/audit/list.handler.ts @@ -0,0 +1,99 @@ +import operation from "../../../_operations/accounts/logs/audit/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts logs audit list", + classification: { + safeFlags: ["direction", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + account_name: argv["account-name"], + action_result: argv["action-result"], + action_type: argv["action-type"], + actor_context: argv["actor-context"], + actor_email: argv["actor-email"], + actor_id: argv["actor-id"], + actor_ip_address: argv["actor-ip-address"], + actor_token_id: argv["actor-token-id"], + actor_token_name: argv["actor-token-name"], + actor_type: argv["actor-type"], + audit_log_id: argv["audit-log-id"], + id: argv["id"], + raw_cf_ray_id: argv["raw-cf-ray-id"], + raw_method: argv["raw-method"], + raw_status_code: argv["raw-status-code"], + raw_uri: argv["raw-uri"], + resource_id: argv["resource-id"], + resource_product: argv["resource-product"], + resource_type: argv["resource-type"], + resource_scope: argv["resource-scope"], + product_category: argv["product-category"], + zone_id: argv["zone-id"], + zone_name: argv["zone-name"], + "account_name.not": argv["account-name-not"], + "action_result.not": argv["action-result-not"], + "action_type.not": argv["action-type-not"], + "actor_context.not": argv["actor-context-not"], + "actor_email.not": argv["actor-email-not"], + "actor_id.not": argv["actor-id-not"], + "actor_ip_address.not": argv["actor-ip-address-not"], + "actor_token_id.not": argv["actor-token-id-not"], + "actor_token_name.not": argv["actor-token-name-not"], + "actor_type.not": argv["actor-type-not"], + "audit_log_id.not": argv["audit-log-id-not"], + "id.not": argv["id-not"], + "raw_cf_ray_id.not": argv["raw-cf-ray-id-not"], + "raw_method.not": argv["raw-method-not"], + "raw_status_code.not": argv["raw-status-code-not"], + "raw_uri.not": argv["raw-uri-not"], + "resource_id.not": argv["resource-id-not"], + "resource_product.not": argv["resource-product-not"], + "resource_type.not": argv["resource-type-not"], + "resource_scope.not": argv["resource-scope-not"], + "zone_id.not": argv["zone-id-not"], + "zone_name.not": argv["zone-name-not"], + since: argv["since"], + before: argv["before"], + direction: argv["direction"], + limit: argv["limit"], + cursor: argv["cursor"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts logs audit list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/logs/audit`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/logs/audit/list.ts b/packages/cli/src/commands/_generated/accounts/logs/audit/list.ts index bf4ea3e262..2ed2129289 100644 --- a/packages/cli/src/commands/_generated/accounts/logs/audit/list.ts +++ b/packages/cli/src/commands/_generated/accounts/logs/audit/list.ts @@ -1,55 +1,46 @@ -import operation from "../../../_operations/accounts/logs/audit/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts logs audit list\n\nGets a list of audit logs for an account." - ) - .option("account-name", { - type: "string", - array: true, - description: "Filters by the account name.", - }) - .option("action-result", { - type: "string", - array: true, - description: "Filters by whether the action was successful or not.", +const parameters = { + flags: { + "account-name": { + kind: "parsed", + brief: "Filters by the account name.", + variadic: true, + optional: true, + parse: String, + }, + "action-result": { + kind: "parsed", + brief: "Filters by whether the action was successful or not.", + variadic: true, + optional: true, choices: ["success", "failure"], - }) - .coerce("action-result", (values: string[]) => - values.flatMap((value) => value.split(",")) - ) - .option("action-type", { - type: "string", - array: true, - description: "Filters by the action type.", + parse: String, + coerce: (values: string[]) => values.flatMap((value) => value.split(",")), + }, + "action-type": { + kind: "parsed", + brief: "Filters by the action type.", + variadic: true, + optional: true, choices: ["create", "delete", "view", "update"], - }) - .coerce("action-type", (values: string[]) => - values.flatMap((value) => value.split(",")) - ) - .option("actor-context", { - type: "string", - array: true, - description: + parse: String, + coerce: (values: string[]) => values.flatMap((value) => value.split(",")), + }, + "actor-context": { + kind: "parsed", + brief: "Filters by the actor context.\n- `api`: The action was performed through the API. The specific credential type was not recorded.\n- `api_key`: The action was authenticated with a Cloudflare Global API Key.\n- `api_token`: The action was authenticated with an API token.\n- `dash`: The action was performed through the Cloudflare dashboard.\n- `oauth`: The action was authenticated with an OAuth token.\n- `origin_ca_key`: The action was authenticated with an Origin CA key.", + variadic: true, + optional: true, choices: [ "api", "api_key", @@ -58,42 +49,52 @@ function builder(yargs: Argv) { "oauth", "origin_ca_key", ], - }) - .coerce("actor-context", (values: string[]) => - values.flatMap((value) => value.split(",")) - ) - .option("actor-email", { - type: "string", - array: true, - description: "Filters by the actor's email address.", - }) - .option("actor-id", { - type: "string", - array: true, - description: + parse: String, + coerce: (values: string[]) => values.flatMap((value) => value.split(",")), + }, + "actor-email": { + kind: "parsed", + brief: "Filters by the actor's email address.", + variadic: true, + optional: true, + parse: String, + }, + "actor-id": { + kind: "parsed", + brief: "Filters by the actor ID. This can be either the Account ID or User ID.", - }) - .option("actor-ip-address", { - type: "string", - array: true, - description: "The IP address where the action was initiated.", - }) - .option("actor-token-id", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + "actor-ip-address": { + kind: "parsed", + brief: "The IP address where the action was initiated.", + variadic: true, + optional: true, + parse: String, + }, + "actor-token-id": { + kind: "parsed", + brief: "Filters by the API token ID when the actor context is an api_token or oauth.", - }) - .option("actor-token-name", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + "actor-token-name": { + kind: "parsed", + brief: "Filters by the API token name when the actor context is an api_token or oauth.", - }) - .option("actor-type", { - type: "string", - array: true, - description: "Filters by the actor type.", + variadic: true, + optional: true, + parse: String, + }, + "actor-type": { + kind: "parsed", + brief: "Filters by the actor type.", + variadic: true, + optional: true, choices: [ "account", "cloudflare_admin", @@ -101,112 +102,138 @@ function builder(yargs: Argv) { "system", "user", ], - }) - .coerce("actor-type", (values: string[]) => - values.flatMap((value) => value.split(",")) - ) - .option("audit-log-id", { - type: "string", - array: true, - description: "Finds a specific log by its ID.", - }) - .option("id", { - type: "string", - array: true, - description: "Finds a specific log by its ID.", - }) - .option("raw-cf-ray-id", { - type: "string", - array: true, - description: "Filters by the response CF Ray ID.", - }) - .option("raw-method", { - type: "string", - array: true, - description: "The HTTP method for the API call.", - }) - .option("raw-status-code", { - type: "string", - array: true, - description: "The response status code that was returned.", - }) - .option("raw-uri", { - type: "string", - array: true, - description: "Filters by the request URI.", - }) - .option("resource-id", { - type: "string", - array: true, - description: "Filters by the resource ID.", - }) - .option("resource-product", { - type: "string", - array: true, - description: + parse: String, + coerce: (values: string[]) => values.flatMap((value) => value.split(",")), + }, + "audit-log-id": { + kind: "parsed", + brief: "Finds a specific log by its ID.", + variadic: true, + optional: true, + parse: String, + }, + id: { + kind: "parsed", + brief: "Finds a specific log by its ID.", + variadic: true, + optional: true, + parse: String, + }, + "raw-cf-ray-id": { + kind: "parsed", + brief: "Filters by the response CF Ray ID.", + variadic: true, + optional: true, + parse: String, + }, + "raw-method": { + kind: "parsed", + brief: "The HTTP method for the API call.", + variadic: true, + optional: true, + parse: String, + }, + "raw-status-code": { + kind: "parsed", + brief: "The response status code that was returned.", + variadic: true, + optional: true, + parse: String, + }, + "raw-uri": { + kind: "parsed", + brief: "Filters by the request URI.", + variadic: true, + optional: true, + parse: String, + }, + "resource-id": { + kind: "parsed", + brief: "Filters by the resource ID.", + variadic: true, + optional: true, + parse: String, + }, + "resource-product": { + kind: "parsed", + brief: "Filters audit logs by the Cloudflare product associated with the changed resource.", - }) - .option("resource-type", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + "resource-type": { + kind: "parsed", + brief: "Filters audit logs based on the unique type of resource changed by the action.", - }) - .option("resource-scope", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + "resource-scope": { + kind: "parsed", + brief: "Filters by the resource scope, specifying whether the resource is associated with an user, an account, a zone, or a membership.", + variadic: true, + optional: true, choices: ["accounts", "user", "zones", "memberships"], - }) - .coerce("resource-scope", (values: string[]) => - values.flatMap((value) => value.split(",")) - ) - .option("product-category", { - type: "string", - array: true, - description: + parse: String, + coerce: (values: string[]) => values.flatMap((value) => value.split(",")), + }, + "product-category": { + kind: "parsed", + brief: "Filters audit logs by one or more predefined product categories. Each product category expands into a curated set of resource_product values and is unioned with any explicit resource_product filter. Matched case-insensitively; unknown product categories return 400. Repeatable. Use the audit log product categories endpoint to discover the available values.", - }) - .option("zone-id", { - type: "string", - array: true, - description: "Filters by the zone ID.", - }) - .option("zone-name", { - type: "string", - array: true, - description: "Filters by the zone name associated with the change.", - }) - .option("account-name-not", { - type: "string", - array: true, - description: "Filters out audit logs by the account name.", - }) - .option("action-result-not", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + "zone-id": { + kind: "parsed", + brief: "Filters by the zone ID.", + variadic: true, + optional: true, + parse: String, + }, + "zone-name": { + kind: "parsed", + brief: "Filters by the zone name associated with the change.", + variadic: true, + optional: true, + parse: String, + }, + "account-name-not": { + kind: "parsed", + brief: "Filters out audit logs by the account name.", + variadic: true, + optional: true, + parse: String, + }, + "action-result-not": { + kind: "parsed", + brief: "Filters out audit logs by whether the action was successful or not.", + variadic: true, + optional: true, choices: ["success", "failure"], - }) - .coerce("action-result-not", (values: string[]) => - values.flatMap((value) => value.split(",")) - ) - .option("action-type-not", { - type: "string", - array: true, - description: "Filters out audit logs by the action type.", + parse: String, + coerce: (values: string[]) => values.flatMap((value) => value.split(",")), + }, + "action-type-not": { + kind: "parsed", + brief: "Filters out audit logs by the action type.", + variadic: true, + optional: true, choices: ["create", "delete", "view", "update"], - }) - .coerce("action-type-not", (values: string[]) => - values.flatMap((value) => value.split(",")) - ) - .option("actor-context-not", { - type: "string", - array: true, - description: + parse: String, + coerce: (values: string[]) => values.flatMap((value) => value.split(",")), + }, + "actor-context-not": { + kind: "parsed", + brief: "Filters out audit logs by the actor context.\n- `api`: The action was performed through the API. The specific credential type was not recorded.\n- `api_key`: The action was authenticated with a Cloudflare Global API Key.\n- `api_token`: The action was authenticated with an API token.\n- `dash`: The action was performed through the Cloudflare dashboard.\n- `oauth`: The action was authenticated with an OAuth token.\n- `origin_ca_key`: The action was authenticated with an Origin CA key.", + variadic: true, + optional: true, choices: [ "api", "api_key", @@ -215,43 +242,53 @@ function builder(yargs: Argv) { "oauth", "origin_ca_key", ], - }) - .coerce("actor-context-not", (values: string[]) => - values.flatMap((value) => value.split(",")) - ) - .option("actor-email-not", { - type: "string", - array: true, - description: "Filters out audit logs by the actor's email address.", - }) - .option("actor-id-not", { - type: "string", - array: true, - description: + parse: String, + coerce: (values: string[]) => values.flatMap((value) => value.split(",")), + }, + "actor-email-not": { + kind: "parsed", + brief: "Filters out audit logs by the actor's email address.", + variadic: true, + optional: true, + parse: String, + }, + "actor-id-not": { + kind: "parsed", + brief: "Filters out audit logs by the actor ID. This can be either the Account ID or User ID.", - }) - .option("actor-ip-address-not", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + "actor-ip-address-not": { + kind: "parsed", + brief: "Filters out audit logs IP address where the action was initiated.", - }) - .option("actor-token-id-not", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + "actor-token-id-not": { + kind: "parsed", + brief: "Filters out audit logs by the API token ID when the actor context is an api_token or oauth.", - }) - .option("actor-token-name-not", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + "actor-token-name-not": { + kind: "parsed", + brief: "Filters out audit logs by the API token name when the actor context is an api_token or oauth.", - }) - .option("actor-type-not", { - type: "string", - array: true, - description: "Filters out audit logs by the actor type.", + variadic: true, + optional: true, + parse: String, + }, + "actor-type-not": { + kind: "parsed", + brief: "Filters out audit logs by the actor type.", + variadic: true, + optional: true, choices: [ "account", "cloudflare_admin", @@ -259,204 +296,148 @@ function builder(yargs: Argv) { "system", "user", ], - }) - .coerce("actor-type-not", (values: string[]) => - values.flatMap((value) => value.split(",")) - ) - .option("audit-log-id-not", { - type: "string", - array: true, - description: "Filters out audit logs by their IDs.", - }) - .option("id-not", { - type: "string", - array: true, - description: "Filters out audit logs by their IDs.", - }) - .option("raw-cf-ray-id-not", { - type: "string", - array: true, - description: "Filters out audit logs by the response CF Ray ID.", - }) - .option("raw-method-not", { - type: "string", - array: true, - description: - "Filters out audit logs by the HTTP method for the API call.", - }) - .option("raw-status-code-not", { - type: "string", - array: true, - description: + parse: String, + coerce: (values: string[]) => values.flatMap((value) => value.split(",")), + }, + "audit-log-id-not": { + kind: "parsed", + brief: "Filters out audit logs by their IDs.", + variadic: true, + optional: true, + parse: String, + }, + "id-not": { + kind: "parsed", + brief: "Filters out audit logs by their IDs.", + variadic: true, + optional: true, + parse: String, + }, + "raw-cf-ray-id-not": { + kind: "parsed", + brief: "Filters out audit logs by the response CF Ray ID.", + variadic: true, + optional: true, + parse: String, + }, + "raw-method-not": { + kind: "parsed", + brief: "Filters out audit logs by the HTTP method for the API call.", + variadic: true, + optional: true, + parse: String, + }, + "raw-status-code-not": { + kind: "parsed", + brief: "Filters out audit logs by the response status code that was returned.", - }) - .option("raw-uri-not", { - type: "string", - array: true, - description: "Filters out audit logs by the request URI.", - }) - .option("resource-id-not", { - type: "string", - array: true, - description: "Filters out audit logs by the resource ID.", - }) - .option("resource-product-not", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + "raw-uri-not": { + kind: "parsed", + brief: "Filters out audit logs by the request URI.", + variadic: true, + optional: true, + parse: String, + }, + "resource-id-not": { + kind: "parsed", + brief: "Filters out audit logs by the resource ID.", + variadic: true, + optional: true, + parse: String, + }, + "resource-product-not": { + kind: "parsed", + brief: "Filters out audit logs by the Cloudflare product associated with the changed resource.", - }) - .option("resource-type-not", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + "resource-type-not": { + kind: "parsed", + brief: "Filters out audit logs based on the unique type of resource changed by the action.", - }) - .option("resource-scope-not", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + "resource-scope-not": { + kind: "parsed", + brief: "Filters out audit logs by the resource scope, specifying whether the resource is associated with an user, an account, a zone, or a membership.", + variadic: true, + optional: true, choices: ["accounts", "user", "zones", "memberships"], - }) - .coerce("resource-scope-not", (values: string[]) => - values.flatMap((value) => value.split(",")) - ) - .option("zone-id-not", { - type: "string", - array: true, - description: "Filters out audit logs by the zone ID.", - }) - .option("zone-name-not", { - type: "string", - array: true, - description: + parse: String, + coerce: (values: string[]) => values.flatMap((value) => value.split(",")), + }, + "zone-id-not": { + kind: "parsed", + brief: "Filters out audit logs by the zone ID.", + variadic: true, + optional: true, + parse: String, + }, + "zone-name-not": { + kind: "parsed", + brief: "Filters out audit logs by the zone name associated with the change.", - }) - .option("since", { - type: "string", - description: + variadic: true, + optional: true, + parse: String, + }, + since: { + kind: "parsed", + brief: "Limits the returned results to logs newer than the specified date. This can be a date string 2019-04-30 (interpreted in UTC) or an absolute timestamp that conforms to RFC3339.", - demandOption: true, - }) - .option("before", { - type: "string", - description: + parse: String, + }, + before: { + kind: "parsed", + brief: "Limits the returned results to logs older than the specified date. This can be a date string 2019-04-30 (interpreted in UTC) or an absolute timestamp that conforms to RFC3339.", - demandOption: true, - }) - .option("direction", { - type: "string", - description: "Sets sorting order.", - choices: ["desc", "asc"], - }) - .option("limit", { - type: "number", - description: + parse: String, + }, + direction: { + kind: "enum", + brief: "Sets sorting order.", + values: ["desc", "asc"], + optional: true, + }, + limit: { + kind: "parsed", + brief: "The number limits the objects to return. The cursor attribute may be used to iterate over the next batch of objects if there are more than the limit.", - }) - .option("cursor", { - type: "string", - description: + optional: true, + parse: Number, + }, + cursor: { + kind: "parsed", + brief: "The cursor is an opaque token used to paginate through large sets of records. It indicates the position from which to continue when requesting the next set of records. A valid cursor value can be obtained from the cursor object in the result_info structure of a previous response.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "Get account audit logs (Version 2)", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts logs audit list", - classification: { - safeFlags: ["direction", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - account_name: argv["account-name"], - action_result: argv["action-result"], - action_type: argv["action-type"], - actor_context: argv["actor-context"], - actor_email: argv["actor-email"], - actor_id: argv["actor-id"], - actor_ip_address: argv["actor-ip-address"], - actor_token_id: argv["actor-token-id"], - actor_token_name: argv["actor-token-name"], - actor_type: argv["actor-type"], - audit_log_id: argv["audit-log-id"], - id: argv["id"], - raw_cf_ray_id: argv["raw-cf-ray-id"], - raw_method: argv["raw-method"], - raw_status_code: argv["raw-status-code"], - raw_uri: argv["raw-uri"], - resource_id: argv["resource-id"], - resource_product: argv["resource-product"], - resource_type: argv["resource-type"], - resource_scope: argv["resource-scope"], - product_category: argv["product-category"], - zone_id: argv["zone-id"], - zone_name: argv["zone-name"], - "account_name.not": argv["account-name-not"], - "action_result.not": argv["action-result-not"], - "action_type.not": argv["action-type-not"], - "actor_context.not": argv["actor-context-not"], - "actor_email.not": argv["actor-email-not"], - "actor_id.not": argv["actor-id-not"], - "actor_ip_address.not": argv["actor-ip-address-not"], - "actor_token_id.not": argv["actor-token-id-not"], - "actor_token_name.not": argv["actor-token-name-not"], - "actor_type.not": argv["actor-type-not"], - "audit_log_id.not": argv["audit-log-id-not"], - "id.not": argv["id-not"], - "raw_cf_ray_id.not": argv["raw-cf-ray-id-not"], - "raw_method.not": argv["raw-method-not"], - "raw_status_code.not": argv["raw-status-code-not"], - "raw_uri.not": argv["raw-uri-not"], - "resource_id.not": argv["resource-id-not"], - "resource_product.not": argv["resource-product-not"], - "resource_type.not": argv["resource-type-not"], - "resource_scope.not": argv["resource-scope-not"], - "zone_id.not": argv["zone-id-not"], - "zone_name.not": argv["zone-name-not"], - since: argv["since"], - before: argv["before"], - direction: argv["direction"], - limit: argv["limit"], - cursor: argv["cursor"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts logs audit list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/logs/audit`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts logs audit list\n\nGets a list of audit logs for an account.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/logs/audit/product-categories.handler.ts b/packages/cli/src/commands/_generated/accounts/logs/audit/product-categories.handler.ts new file mode 100644 index 0000000000..cfdd4307a7 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/logs/audit/product-categories.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../../_operations/accounts/logs/audit/product-categories.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./product-categories.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts logs audit product-categories", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts logs audit product-categories", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/logs/audit/product_categories`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/logs/audit/product-categories.ts b/packages/cli/src/commands/_generated/accounts/logs/audit/product-categories.ts index 56f9eb55ab..afa0f19189 100644 --- a/packages/cli/src/commands/_generated/accounts/logs/audit/product-categories.ts +++ b/packages/cli/src/commands/_generated/accounts/logs/audit/product-categories.ts @@ -1,71 +1,31 @@ -import operation from "../../../_operations/accounts/logs/audit/product-categories.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * product-categories command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts logs audit product-categories\n\nLists the available audit log product categories and the resource products each one expands to. Use these values with the product_category filter on the account audit logs endpoint." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "product-categories", describe: "List account audit log product categories (Version 2)", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts logs audit product-categories", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts logs audit product-categories", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/logs/audit/product_categories`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts logs audit product-categories\n\nLists the available audit log product categories and the resource products each one expands to. Use these values with the product_category filter on the account audit logs endpoint.", + ...parameters, + loader: () => import("./product-categories.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/logs/index.ts b/packages/cli/src/commands/_generated/accounts/logs/index.ts index 8315ac19d8..e31109bae8 100644 --- a/packages/cli/src/commands/_generated/accounts/logs/index.ts +++ b/packages/cli/src/commands/_generated/accounts/logs/index.ts @@ -1,22 +1,17 @@ import $audit from "./audit/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * logs command group * @generated from apis/overlays/accounts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "logs", describe: "Operations for logs", - builder: (yargs) => { - return yargs - .command($audit) - .demandCommand(1, "Please specify a subcommand"); + routes: { + audit: $audit, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/members/create.handler.ts b/packages/cli/src/commands/_generated/accounts/members/create.handler.ts new file mode 100644 index 0000000000..ad0fa9d2f3 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/members/create.handler.ts @@ -0,0 +1,96 @@ +import operation from "../../_operations/accounts/members/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts members create", + classification: { + safeFlags: ["status", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["email"] === undefined) { + argv["email"] = await promptForRequiredField( + "email", + "The contact email address of the user." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts members create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/members`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + email: resolveFileToken( + argv["email"] as string | undefined, + "email", + "text" + ), + roles: argv["roles"], + status: argv["status"], + policies: parseObjectArray(argv["policies"], "policies"), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + email: resolveFileToken( + argv["email"] as string | undefined, + "email", + "text" + ), + roles: argv["roles"], + status: argv["status"], + policies: parseObjectArray(argv["policies"], "policies"), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/members/create.ts b/packages/cli/src/commands/_generated/accounts/members/create.ts index e118faf817..57387351ff 100644 --- a/packages/cli/src/commands/_generated/accounts/members/create.ts +++ b/packages/cli/src/commands/_generated/accounts/members/create.ts @@ -1,148 +1,71 @@ -import operation from "../../_operations/accounts/members/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts members create\n\nAdd a user to the list of members for this account." - ) - .option("email", { - type: "string", - description: "The contact email address of the user.", - }) - .option("roles", { - type: "string", - array: true, - description: "Array of roles associated with this member.", - }) - .option("status", { - type: "string", - description: +const parameters = { + flags: { + email: { + kind: "parsed", + brief: "The contact email address of the user.", + optional: true, + parse: String, + }, + roles: { + kind: "parsed", + brief: "Array of roles associated with this member.", + variadic: true, + optional: true, + parse: String, + }, + status: { + kind: "parsed", + brief: "Status of the member invitation. If not provided during creation, defaults to 'pending'.\nChanging from 'accepted' back to 'pending' will trigger a replacement of the member resource in Terraform.", + optional: true, choices: ["accepted", "pending"], - }) - .coerce("status", (value) => resolveFileToken(value, "status", "text")) - .option("policies", { - type: "string", - description: + parse: String, + coerce: (value: string) => resolveFileToken(value, "status", "text"), + }, + policies: { + kind: "parsed", + brief: 'Array of policies associated with this member. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"access": "allow" | "deny", "permission_groups": [{...}], "resource_groups": [{...}]}].', - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }) - .conflicts("roles", ["policies"]) - .conflicts("policies", ["roles"]); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], + rules(rules) { + rules.conflicts("roles", ["policies"]); + rules.conflicts("policies", ["roles"]); + }, +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Add Member", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts members create", - classification: { - safeFlags: ["status", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["email"] === undefined) { - argv["email"] = await promptForRequiredField( - "email", - "The contact email address of the user." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts members create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/members`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - email: resolveFileToken( - argv["email"] as string | undefined, - "email", - "text" - ), - roles: argv["roles"], - status: argv["status"], - policies: parseObjectArray(argv["policies"], "policies"), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - email: resolveFileToken( - argv["email"] as string | undefined, - "email", - "text" - ), - roles: argv["roles"], - status: argv["status"], - policies: parseObjectArray(argv["policies"], "policies"), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 accounts members create\n\nAdd a user to the list of members for this account.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/members/delete.handler.ts b/packages/cli/src/commands/_generated/accounts/members/delete.handler.ts new file mode 100644 index 0000000000..489e6d17ac --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/members/delete.handler.ts @@ -0,0 +1,60 @@ +import operation from "../../_operations/accounts/members/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts members delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts members delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/members/${argv["member-id"] == null ? "" : encodeURIComponent(String(argv["member-id"]))}`, + pathParams: { "member-id": String(argv["member-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `Are you sure you want to remove this user from the account?`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + member_id: argv["member-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/members/delete.ts b/packages/cli/src/commands/_generated/accounts/members/delete.ts index d27759aaa8..b1c200e53b 100644 --- a/packages/cli/src/commands/_generated/accounts/members/delete.ts +++ b/packages/cli/src/commands/_generated/accounts/members/delete.ts @@ -1,96 +1,43 @@ -import operation from "../../_operations/accounts/members/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts members delete \n\nRemove a member from an account." - ) - .positional("member-id", { - type: "string", - description: "Membership identifier tag.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "member-id", + brief: "Membership identifier tag.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Remove Member", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts members delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts members delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/members/${argv["member-id"] == null ? "" : encodeURIComponent(String(argv["member-id"]))}`, - pathParams: { "member-id": String(argv["member-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `Are you sure you want to remove this user from the account?`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - member_id: argv["member-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 accounts members delete \n\nRemove a member from an account.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/members/get.handler.ts b/packages/cli/src/commands/_generated/accounts/members/get.handler.ts new file mode 100644 index 0000000000..29814fa00c --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/members/get.handler.ts @@ -0,0 +1,49 @@ +import operation from "../../_operations/accounts/members/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts members get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts members get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/members/${argv["member-id"] == null ? "" : encodeURIComponent(String(argv["member-id"]))}`, + pathParams: { "member-id": String(argv["member-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + member_id: argv["member-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/members/get.ts b/packages/cli/src/commands/_generated/accounts/members/get.ts index 557019f61a..9f87a6adf7 100644 --- a/packages/cli/src/commands/_generated/accounts/members/get.ts +++ b/packages/cli/src/commands/_generated/accounts/members/get.ts @@ -1,79 +1,37 @@ -import operation from "../../_operations/accounts/members/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts members get \n\nGet information about a specific member of an account." - ) - .positional("member-id", { - type: "string", - description: "Membership identifier tag.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "member-id", + brief: "Membership identifier tag.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Member Details", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts members get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts members get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/members/${argv["member-id"] == null ? "" : encodeURIComponent(String(argv["member-id"]))}`, - pathParams: { "member-id": String(argv["member-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - member_id: argv["member-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts members get \n\nGet information about a specific member of an account.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/members/index.ts b/packages/cli/src/commands/_generated/accounts/members/index.ts index 747ab5e424..2b6c877183 100644 --- a/packages/cli/src/commands/_generated/accounts/members/index.ts +++ b/packages/cli/src/commands/_generated/accounts/members/index.ts @@ -3,28 +3,23 @@ import $delete from "./delete.js"; import $get from "./get.js"; import $list from "./list.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * members command group * @generated from apis/overlays/accounts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "members", describe: "Operations for members", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .command($list) - .command($update) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, + list: $list, + update: $update, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/members/list.handler.ts b/packages/cli/src/commands/_generated/accounts/members/list.handler.ts new file mode 100644 index 0000000000..3f2cc3482b --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/members/list.handler.ts @@ -0,0 +1,54 @@ +import operation from "../../_operations/accounts/members/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts members list", + classification: { + safeFlags: ["order", "status", "direction", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + order: argv["order"], + status: argv["status"], + page: argv["page"], + per_page: argv["per-page"], + direction: argv["direction"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts members list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/members`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/members/list.ts b/packages/cli/src/commands/_generated/accounts/members/list.ts index 725ed66860..3d9622704a 100644 --- a/packages/cli/src/commands/_generated/accounts/members/list.ts +++ b/packages/cli/src/commands/_generated/accounts/members/list.ts @@ -1,100 +1,60 @@ -import operation from "../../_operations/accounts/members/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage("$0 accounts members list\n\nList all members of an account.") - .option("order", { - type: "string", - description: "Field to order results by.", - choices: ["user.first_name", "user.last_name", "user.email", "status"], - }) - .option("status", { - type: "string", - description: "A member's status in the account.", - choices: ["accepted", "pending", "rejected"], - }) - .option("page", { - type: "number", - description: "Page number of paginated results.", - }) - .option("per-page", { - type: "number", - description: "Maximum number of results per page.", - }) - .option("direction", { - type: "string", - description: "Direction to order results.", - choices: ["asc", "desc"], - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + order: { + kind: "enum", + brief: "Field to order results by.", + values: ["user.first_name", "user.last_name", "user.email", "status"], + optional: true, + }, + status: { + kind: "enum", + brief: "A member's status in the account.", + values: ["accepted", "pending", "rejected"], + optional: true, + }, + page: { + kind: "parsed", + brief: "Page number of paginated results.", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Maximum number of results per page.", + optional: true, + parse: Number, + }, + direction: { + kind: "enum", + brief: "Direction to order results.", + values: ["asc", "desc"], + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Members", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts members list", - classification: { - safeFlags: ["order", "status", "direction", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - order: argv["order"], - status: argv["status"], - page: argv["page"], - per_page: argv["per-page"], - direction: argv["direction"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts members list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/members`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: "$0 accounts members list\n\nList all members of an account.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/members/update.handler.ts b/packages/cli/src/commands/_generated/accounts/members/update.handler.ts new file mode 100644 index 0000000000..e9bd08bfef --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/members/update.handler.ts @@ -0,0 +1,78 @@ +import operation from "../../_operations/accounts/members/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts members update", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts members update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/members/${argv["member-id"] == null ? "" : encodeURIComponent(String(argv["member-id"]))}`, + pathParams: { "member-id": String(argv["member-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + roles: parseObjectArray(argv["roles"], "roles"), + policies: parseObjectArray(argv["policies"], "policies"), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + member_id: argv["member-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + roles: parseObjectArray(argv["roles"], "roles"), + policies: parseObjectArray(argv["policies"], "policies"), + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + member_id: argv["member-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/members/update.ts b/packages/cli/src/commands/_generated/accounts/members/update.ts index d68f4a39e0..ec67f573e3 100644 --- a/packages/cli/src/commands/_generated/accounts/members/update.ts +++ b/packages/cli/src/commands/_generated/accounts/members/update.ts @@ -1,124 +1,60 @@ -import operation from "../../_operations/accounts/members/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts members update \n\nModify an account member." - ) - .positional("member-id", { - type: "string", - description: "Membership identifier tag.", - demandOption: true, - }) - .option("roles", { - type: "string", - description: +const parameters = { + flags: { + roles: { + kind: "parsed", + brief: 'Roles assigned to this member. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"id": string}].', - }) - .option("policies", { - type: "string", - description: + optional: true, + parse: String, + }, + policies: { + kind: "parsed", + brief: 'Array of policies associated with this member. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"access": "allow" | "deny", "permission_groups": [{...}], "resource_groups": [{...}]}].', - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }) - .conflicts("roles", ["policies"]) - .conflicts("policies", ["roles"]); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "member-id", + brief: "Membership identifier tag.", + parse: String, + }, + ], + rules(rules) { + rules.conflicts("roles", ["policies"]); + rules.conflicts("policies", ["roles"]); + }, +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update ", describe: "Update Member", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts members update", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts members update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/members/${argv["member-id"] == null ? "" : encodeURIComponent(String(argv["member-id"]))}`, - pathParams: { "member-id": String(argv["member-id"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - roles: parseObjectArray(argv["roles"], "roles"), - policies: parseObjectArray(argv["policies"], "policies"), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - member_id: argv["member-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - roles: parseObjectArray(argv["roles"], "roles"), - policies: parseObjectArray(argv["policies"], "policies"), - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - member_id: argv["member-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: "$0 accounts members update \n\nModify an account member.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/move.handler.ts b/packages/cli/src/commands/_generated/accounts/move.handler.ts new file mode 100644 index 0000000000..9c0cd36d38 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/move.handler.ts @@ -0,0 +1,90 @@ +import operation from "../_operations/accounts/move.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./move.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts move", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["destination-organization-id"] === undefined) { + argv["destination-organization-id"] = await promptForRequiredField( + "destination-organization-id", + "The ID of the organization to move the account into." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts move", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/move`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + destination_organization_id: resolveFileToken( + argv["destination-organization-id"] as string | undefined, + "destination-organization-id", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + destination_organization_id: resolveFileToken( + argv["destination-organization-id"] as string | undefined, + "destination-organization-id", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/move.ts b/packages/cli/src/commands/_generated/accounts/move.ts index 05259d5b4a..75554de759 100644 --- a/packages/cli/src/commands/_generated/accounts/move.ts +++ b/packages/cli/src/commands/_generated/accounts/move.ts @@ -1,124 +1,44 @@ -import operation from "../_operations/accounts/move.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * move command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts move\n\nMove an account into a destination organization, either assigning a standalone account to an organization or moving it between organizations in the same hierarchy. Availability depends on the organization's capabilities." - ) - .option("destination-organization-id", { - type: "string", - description: "The ID of the organization to move the account into.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "destination-organization-id": { + kind: "parsed", + brief: "The ID of the organization to move the account into.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: + }, + body: { + kind: "parsed", + brief: "The destination organization ID is where the account is to be moved.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "move", describe: "Move account to organization", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts move", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["destination-organization-id"] === undefined) { - argv["destination-organization-id"] = await promptForRequiredField( - "destination-organization-id", - "The ID of the organization to move the account into." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts move", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/move`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - destination_organization_id: resolveFileToken( - argv["destination-organization-id"] as string | undefined, - "destination-organization-id", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - destination_organization_id: resolveFileToken( - argv["destination-organization-id"] as string | undefined, - "destination-organization-id", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 accounts move\n\nMove an account into a destination organization, either assigning a standalone account to an organization or moving it between organizations in the same hierarchy. Availability depends on the organization's capabilities.", + ...parameters, + loader: () => import("./move.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/organizations/index.ts b/packages/cli/src/commands/_generated/accounts/organizations/index.ts index cddca408bf..5a13239e7c 100644 --- a/packages/cli/src/commands/_generated/accounts/organizations/index.ts +++ b/packages/cli/src/commands/_generated/accounts/organizations/index.ts @@ -1,20 +1,17 @@ import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * organizations command group * @generated from apis/overlays/accounts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "organizations", describe: "View organizations associated with a Cloudflare account", - builder: (yargs) => { - return yargs.command($list).demandCommand(1, "Please specify a subcommand"); + routes: { + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/organizations/list.handler.ts b/packages/cli/src/commands/_generated/accounts/organizations/list.handler.ts new file mode 100644 index 0000000000..68ee549de5 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/organizations/list.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/accounts/organizations/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts organizations list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts organizations list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/organizations`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/organizations/list.ts b/packages/cli/src/commands/_generated/accounts/organizations/list.ts index 1c5bf9eb8f..a6f89d6594 100644 --- a/packages/cli/src/commands/_generated/accounts/organizations/list.ts +++ b/packages/cli/src/commands/_generated/accounts/organizations/list.ts @@ -1,71 +1,31 @@ -import operation from "../../_operations/accounts/organizations/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - '$0 accounts organizations list\n\nRetrieve a list of the organizations that "contain" this account or are managing it. The returned list will be in order from "root" to "leaf", where the "leaf" will be the organization that _immediately_ contains the specified account.' - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List account organizations", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts organizations list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts organizations list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/organizations`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + '$0 accounts organizations list\n\nRetrieve a list of the organizations that "contain" this account or are managing it. The returned list will be in order from "root" to "leaf", where the "leaf" will be the organization that _immediately_ contains the specified account.', + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/profile/get.handler.ts b/packages/cli/src/commands/_generated/accounts/profile/get.handler.ts new file mode 100644 index 0000000000..abc7b66b2c --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/profile/get.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/accounts/profile/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts profile get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts profile get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/profile`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/profile/get.ts b/packages/cli/src/commands/_generated/accounts/profile/get.ts index c2143f82ab..29fd98ef59 100644 --- a/packages/cli/src/commands/_generated/accounts/profile/get.ts +++ b/packages/cli/src/commands/_generated/accounts/profile/get.ts @@ -1,71 +1,31 @@ -import operation from "../../_operations/accounts/profile/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts profile get\n\nRetrieves the business profile (name, email, phone, address, and external metadata) associated with this account's customer record. Profiles can be shared across accounts and organizations. Only available to members of an organization that contains the account." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "Get account profile", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts profile get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts profile get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/profile`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts profile get\n\nRetrieves the business profile (name, email, phone, address, and external metadata) associated with this account's customer record. Profiles can be shared across accounts and organizations. Only available to members of an organization that contains the account.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/profile/index.ts b/packages/cli/src/commands/_generated/accounts/profile/index.ts index 036aa7be72..e53b0ed108 100644 --- a/packages/cli/src/commands/_generated/accounts/profile/index.ts +++ b/packages/cli/src/commands/_generated/accounts/profile/index.ts @@ -1,24 +1,19 @@ import $get from "./get.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * profile command group * @generated from apis/overlays/accounts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "profile", describe: "View and manage the profile for a Cloudflare account", - builder: (yargs) => { - return yargs - .command($get) - .command($update) - .demandCommand(1, "Please specify a subcommand"); + routes: { + get: $get, + update: $update, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/profile/update.handler.ts b/packages/cli/src/commands/_generated/accounts/profile/update.handler.ts new file mode 100644 index 0000000000..ef5e18ec96 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/profile/update.handler.ts @@ -0,0 +1,117 @@ +import operation from "../../_operations/accounts/profile/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts profile update", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts profile update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/profile`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + business_address: resolveFileToken( + argv["business-address"] as string | undefined, + "business-address", + "text" + ), + business_email: resolveFileToken( + argv["business-email"] as string | undefined, + "business-email", + "text" + ), + business_name: resolveFileToken( + argv["business-name"] as string | undefined, + "business-name", + "text" + ), + business_phone: resolveFileToken( + argv["business-phone"] as string | undefined, + "business-phone", + "text" + ), + external_metadata: resolveFileToken( + argv["external-metadata"] as string | undefined, + "external-metadata", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + business_address: resolveFileToken( + argv["business-address"] as string | undefined, + "business-address", + "text" + ), + business_email: resolveFileToken( + argv["business-email"] as string | undefined, + "business-email", + "text" + ), + business_name: resolveFileToken( + argv["business-name"] as string | undefined, + "business-name", + "text" + ), + business_phone: resolveFileToken( + argv["business-phone"] as string | undefined, + "business-phone", + "text" + ), + external_metadata: resolveFileToken( + argv["external-metadata"] as string | undefined, + "external-metadata", + "text" + ), + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/profile/update.ts b/packages/cli/src/commands/_generated/accounts/profile/update.ts index 7d90b0556d..68b820e07e 100644 --- a/packages/cli/src/commands/_generated/accounts/profile/update.ts +++ b/packages/cli/src/commands/_generated/accounts/profile/update.ts @@ -1,167 +1,68 @@ -import operation from "../../_operations/accounts/profile/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts profile update\n\nPartially updates the business profile (name, email, phone, address, and external metadata) associated with this account's parent organization customer record, creating the profile if it does not exist. Changes apply to every account and organization sharing that profile. Omitted, empty, or null fields are left unchanged. Each profile field is limited to 1,000 UTF-8 bytes. Only available to members of an organization that contains the account." - ) - .option("business-address", { - type: "string", - description: "The business_address field", - }) - .option("business-email", { - type: "string", - description: "The business_email field", - }) - .option("business-name", { - type: "string", - description: "The business_name field", - }) - .option("business-phone", { - type: "string", - description: "The business_phone field", - }) - .option("external-metadata", { - type: "string", - description: "The external_metadata field", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "business-address": { + kind: "parsed", + brief: "The business_address field", + optional: true, + parse: String, + }, + "business-email": { + kind: "parsed", + brief: "The business_email field", + optional: true, + parse: String, + }, + "business-name": { + kind: "parsed", + brief: "The business_name field", + optional: true, + parse: String, + }, + "business-phone": { + kind: "parsed", + brief: "The business_phone field", + optional: true, + parse: String, + }, + "external-metadata": { + kind: "parsed", + brief: "The external_metadata field", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: + }, + body: { + kind: "parsed", + brief: "Partial business profile update. Omitted, empty, or null fields remain unchanged. At least one of business name, address, phone, or email must be non-empty.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update", describe: "Update account profile", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts profile update", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts profile update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/profile`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - business_address: resolveFileToken( - argv["business-address"] as string | undefined, - "business-address", - "text" - ), - business_email: resolveFileToken( - argv["business-email"] as string | undefined, - "business-email", - "text" - ), - business_name: resolveFileToken( - argv["business-name"] as string | undefined, - "business-name", - "text" - ), - business_phone: resolveFileToken( - argv["business-phone"] as string | undefined, - "business-phone", - "text" - ), - external_metadata: resolveFileToken( - argv["external-metadata"] as string | undefined, - "external-metadata", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - business_address: resolveFileToken( - argv["business-address"] as string | undefined, - "business-address", - "text" - ), - business_email: resolveFileToken( - argv["business-email"] as string | undefined, - "business-email", - "text" - ), - business_name: resolveFileToken( - argv["business-name"] as string | undefined, - "business-name", - "text" - ), - business_phone: resolveFileToken( - argv["business-phone"] as string | undefined, - "business-phone", - "text" - ), - external_metadata: resolveFileToken( - argv["external-metadata"] as string | undefined, - "external-metadata", - "text" - ), - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 accounts profile update\n\nPartially updates the business profile (name, email, phone, address, and external metadata) associated with this account's parent organization customer record, creating the profile if it does not exist. Changes apply to every account and organization sharing that profile. Omitted, empty, or null fields are left unchanged. Each profile field is limited to 1,000 UTF-8 bytes. Only available to members of an organization that contains the account.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/subscriptions/cancel-delayed-downgrade.handler.ts b/packages/cli/src/commands/_generated/accounts/subscriptions/cancel-delayed-downgrade.handler.ts new file mode 100644 index 0000000000..986cec98d9 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/subscriptions/cancel-delayed-downgrade.handler.ts @@ -0,0 +1,68 @@ +import operation from "../../_operations/accounts/subscriptions/cancel-delayed-downgrade.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./cancel-delayed-downgrade.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts subscriptions cancel-delayed-downgrade", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts subscriptions cancel-delayed-downgrade", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/subscriptions/cancel-downgrade`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + subscription_ids: argv["subscription-ids"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + subscription_ids: argv["subscription-ids"], + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/subscriptions/cancel-delayed-downgrade.ts b/packages/cli/src/commands/_generated/accounts/subscriptions/cancel-delayed-downgrade.ts index a64b3c3b45..3d8e4607fc 100644 --- a/packages/cli/src/commands/_generated/accounts/subscriptions/cancel-delayed-downgrade.ts +++ b/packages/cli/src/commands/_generated/accounts/subscriptions/cancel-delayed-downgrade.ts @@ -1,102 +1,44 @@ -import operation from "../../_operations/accounts/subscriptions/cancel-delayed-downgrade.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * cancel-delayed-downgrade command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts subscriptions cancel-delayed-downgrade\n\nCancels pending delayed downgrades for the specified subscriptions." - ) - .option("subscription-ids", { - type: "string", - array: true, - description: "List of subscription identifiers to cancel downgrades for.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "subscription-ids": { + kind: "parsed", + brief: "List of subscription identifiers to cancel downgrades for.", + variadic: true, + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "cancel-delayed-downgrade", describe: "Cancel Delayed Downgrade", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts subscriptions cancel-delayed-downgrade", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts subscriptions cancel-delayed-downgrade", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/subscriptions/cancel-downgrade`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - subscription_ids: argv["subscription-ids"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - subscription_ids: argv["subscription-ids"], - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 accounts subscriptions cancel-delayed-downgrade\n\nCancels pending delayed downgrades for the specified subscriptions.", + ...parameters, + loader: () => import("./cancel-delayed-downgrade.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/subscriptions/create-cancel-reason.handler.ts b/packages/cli/src/commands/_generated/accounts/subscriptions/create-cancel-reason.handler.ts new file mode 100644 index 0000000000..8a63d9adcf --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/subscriptions/create-cancel-reason.handler.ts @@ -0,0 +1,91 @@ +import operation from "../../_operations/accounts/subscriptions/create-cancel-reason.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create-cancel-reason.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts subscriptions create-cancel-reason", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts subscriptions create-cancel-reason", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/subscriptions/${argv["subscription-identifier"] == null ? "" : encodeURIComponent(String(argv["subscription-identifier"]))}/cancel-reason`, + pathParams: { + "subscription-identifier": String( + argv["subscription-identifier"] ?? "" + ), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + other: resolveFileToken( + argv["other"] as string | undefined, + "other", + "text" + ), + reason_code: argv["reason-code"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + subscription_identifier: argv["subscription-identifier"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + other: resolveFileToken( + argv["other"] as string | undefined, + "other", + "text" + ), + reason_code: argv["reason-code"], + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + subscription_identifier: argv["subscription-identifier"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/subscriptions/create-cancel-reason.ts b/packages/cli/src/commands/_generated/accounts/subscriptions/create-cancel-reason.ts index 75c1896f22..f541a982dd 100644 --- a/packages/cli/src/commands/_generated/accounts/subscriptions/create-cancel-reason.ts +++ b/packages/cli/src/commands/_generated/accounts/subscriptions/create-cancel-reason.ts @@ -1,134 +1,56 @@ -import operation from "../../_operations/accounts/subscriptions/create-cancel-reason.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create-cancel-reason command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts subscriptions create-cancel-reason \n\nRecords a cancellation reason for an account subscription." - ) - .positional("subscription-identifier", { - type: "string", - description: "Subscription identifier tag.", - demandOption: true, - }) - .option("other", { - type: "string", - description: "Additional cancellation details.", - }) - .option("reason-code", { - type: "string", - array: true, - description: "The cancellation reason codes.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + other: { + kind: "parsed", + brief: "Additional cancellation details.", + optional: true, + parse: String, + }, + "reason-code": { + kind: "parsed", + brief: "The cancellation reason codes.", + variadic: true, + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "subscription-identifier", + brief: "Subscription identifier tag.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create-cancel-reason ", describe: "Create Cancel Reason", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts subscriptions create-cancel-reason", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts subscriptions create-cancel-reason", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/subscriptions/${argv["subscription-identifier"] == null ? "" : encodeURIComponent(String(argv["subscription-identifier"]))}/cancel-reason`, - pathParams: { - "subscription-identifier": String( - argv["subscription-identifier"] ?? "" - ), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - other: resolveFileToken( - argv["other"] as string | undefined, - "other", - "text" - ), - reason_code: argv["reason-code"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - subscription_identifier: argv["subscription-identifier"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - other: resolveFileToken( - argv["other"] as string | undefined, - "other", - "text" - ), - reason_code: argv["reason-code"], - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - subscription_identifier: argv["subscription-identifier"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 accounts subscriptions create-cancel-reason \n\nRecords a cancellation reason for an account subscription.", + ...parameters, + loader: () => import("./create-cancel-reason.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/subscriptions/create.handler.ts b/packages/cli/src/commands/_generated/accounts/subscriptions/create.handler.ts new file mode 100644 index 0000000000..a28e4c7573 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/subscriptions/create.handler.ts @@ -0,0 +1,172 @@ +import operation from "../../_operations/accounts/subscriptions/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + getZoneId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts subscriptions create", + classification: { + safeFlags: [ + "frequency", + "rate-plan-externally-managed", + "rate-plan-is-contract", + "dry-run", + ], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = + argv.zone === undefined ? await resolveAccountIdSilent() : undefined; + const accountOrZone = argv.zone === undefined ? "accounts" : "zones"; + const accountOrZoneId = + argv.zone ?? __cfDryRunAccountId ?? ""; + formatDryRun({ + command: "cf accounts subscriptions create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/${accountOrZone}/${accountOrZoneId}/subscriptions`, + pathParams: { + "account-or-zone": String(accountOrZone), + "account-or-zone-id": String(accountOrZoneId), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + app: { + install_id: resolveFileToken( + argv["app-install-id"] as string | undefined, + "app-install-id", + "text" + ), + }, + component_values: parseObjectArray( + argv["component-values"], + "component-values" + ), + frequency: argv["frequency"], + rate_plan: { + currency: resolveFileToken( + argv["rate-plan-currency"] as string | undefined, + "rate-plan-currency", + "text" + ), + externally_managed: argv["rate-plan-externally-managed"], + id: resolveFileToken( + argv["rate-plan-id"] as string | undefined, + "rate-plan-id", + "text" + ), + is_contract: argv["rate-plan-is-contract"], + public_name: resolveFileToken( + argv["rate-plan-public-name"] as string | undefined, + "rate-plan-public-name", + "text" + ), + scope: resolveFileToken( + argv["rate-plan-scope"] as string | undefined, + "rate-plan-scope", + "text" + ), + sets: argv["rate-plan-sets"], + }, + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountOrZone = argv.zone === undefined ? "accounts" : "zones"; + const accountOrZoneId = + accountOrZone === "zones" + ? await getZoneId({ zone: argv.zone }, client, { quiet: argv.quiet }) + : argv.local + ? LOCAL_ACCOUNT_ID + : await getAccountId(); + if (accountOrZone === "zones") { + argv.zoneId = accountOrZoneId; + } else { + argv.accountId = accountOrZoneId; + } + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_or_zone: accountOrZone, + account_or_zone_id: accountOrZoneId, + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + app: { + install_id: resolveFileToken( + argv["app-install-id"] as string | undefined, + "app-install-id", + "text" + ), + }, + component_values: parseObjectArray( + argv["component-values"], + "component-values" + ), + frequency: argv["frequency"], + rate_plan: { + currency: resolveFileToken( + argv["rate-plan-currency"] as string | undefined, + "rate-plan-currency", + "text" + ), + externally_managed: argv["rate-plan-externally-managed"], + id: resolveFileToken( + argv["rate-plan-id"] as string | undefined, + "rate-plan-id", + "text" + ), + is_contract: argv["rate-plan-is-contract"], + public_name: resolveFileToken( + argv["rate-plan-public-name"] as string | undefined, + "rate-plan-public-name", + "text" + ), + scope: resolveFileToken( + argv["rate-plan-scope"] as string | undefined, + "rate-plan-scope", + "text" + ), + sets: argv["rate-plan-sets"], + }, + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_or_zone: accountOrZone, + account_or_zone_id: accountOrZoneId, + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/subscriptions/create.ts b/packages/cli/src/commands/_generated/accounts/subscriptions/create.ts index b5bf34138f..91632ef551 100644 --- a/packages/cli/src/commands/_generated/accounts/subscriptions/create.ts +++ b/packages/cli/src/commands/_generated/accounts/subscriptions/create.ts @@ -1,254 +1,102 @@ -import operation from "../../_operations/accounts/subscriptions/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - getZoneId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts subscriptions create\n\nCreates an account or zone subscription.\n\nRuns against your account. Pass --zone to run against a zone instead. CLOUDFLARE_ZONE_ID is ignored." - ) - .option("app-install-id", { - type: "string", - description: "app install id.", - }) - .option("component-values", { - type: "string", - description: +const parameters = { + flags: { + "app-install-id": { + kind: "parsed", + brief: "app install id.", + optional: true, + parse: String, + }, + "component-values": { + kind: "parsed", + brief: 'Configurable component values for the subscription. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"default"?: number, "display_name"?: string, "kind"?: "enum" | "sum" | "usage", "name"?: string, "price"?: number, ...more}]. ? marks optional keys.', - }) - .option("frequency", { - type: "string", - description: "How often the subscription is renewed automatically.", + optional: true, + parse: String, + }, + frequency: { + kind: "parsed", + brief: "How often the subscription is renewed automatically.", + optional: true, choices: ["weekly", "monthly", "quarterly", "yearly"], - }) - .coerce("frequency", (value) => - resolveFileToken(value, "frequency", "text") - ) - .option("rate-plan-currency", { - type: "string", - description: "The currency applied to the rate plan subscription.", - }) - .option("rate-plan-externally-managed", { - type: "boolean", - description: - "Whether this rate plan is managed externally from Cloudflare.", - }) - .option("rate-plan-id", { - type: "string", - description: "The ID of the rate plan.", - }) - .option("rate-plan-is-contract", { - type: "boolean", - description: + parse: String, + coerce: (value: string) => resolveFileToken(value, "frequency", "text"), + }, + "rate-plan-currency": { + kind: "parsed", + brief: "The currency applied to the rate plan subscription.", + optional: true, + parse: String, + }, + "rate-plan-externally-managed": { + kind: "boolean", + brief: "Whether this rate plan is managed externally from Cloudflare.", + optional: true, + }, + "rate-plan-id": { + kind: "parsed", + brief: "The ID of the rate plan.", + optional: true, + parse: String, + }, + "rate-plan-is-contract": { + kind: "boolean", + brief: "Whether a rate plan is enterprise-based (or newly adopted term contract).", - }) - .option("rate-plan-public-name", { - type: "string", - description: "The full name of the rate plan.", - }) - .option("rate-plan-scope", { - type: "string", - description: "The scope that this rate plan applies to.", - }) - .option("rate-plan-sets", { - type: "string", - array: true, - description: + optional: true, + }, + "rate-plan-public-name": { + kind: "parsed", + brief: "The full name of the rate plan.", + optional: true, + parse: String, + }, + "rate-plan-scope": { + kind: "parsed", + brief: "The scope that this rate plan applies to.", + optional: true, + parse: String, + }, + "rate-plan-sets": { + kind: "parsed", + brief: "The list of sets this rate plan applies to. Returns array of strings.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + variadic: true, + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Create Subscription", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts subscriptions create", - classification: { - safeFlags: [ - "frequency", - "rate-plan-externally-managed", - "rate-plan-is-contract", - "dry-run", - ], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = - argv.zone === undefined - ? await resolveAccountIdSilent() - : undefined; - const accountOrZone = argv.zone === undefined ? "accounts" : "zones"; - const accountOrZoneId = - argv.zone ?? __cfDryRunAccountId ?? ""; - formatDryRun({ - command: "cf accounts subscriptions create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/${accountOrZone}/${accountOrZoneId}/subscriptions`, - pathParams: { - "account-or-zone": String(accountOrZone), - "account-or-zone-id": String(accountOrZoneId), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - app: { - install_id: resolveFileToken( - argv["app-install-id"] as string | undefined, - "app-install-id", - "text" - ), - }, - component_values: parseObjectArray( - argv["component-values"], - "component-values" - ), - frequency: argv["frequency"], - rate_plan: { - currency: resolveFileToken( - argv["rate-plan-currency"] as string | undefined, - "rate-plan-currency", - "text" - ), - externally_managed: argv["rate-plan-externally-managed"], - id: resolveFileToken( - argv["rate-plan-id"] as string | undefined, - "rate-plan-id", - "text" - ), - is_contract: argv["rate-plan-is-contract"], - public_name: resolveFileToken( - argv["rate-plan-public-name"] as string | undefined, - "rate-plan-public-name", - "text" - ), - scope: resolveFileToken( - argv["rate-plan-scope"] as string | undefined, - "rate-plan-scope", - "text" - ), - sets: argv["rate-plan-sets"], - }, - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountOrZone = argv.zone === undefined ? "accounts" : "zones"; - const accountOrZoneId = - accountOrZone === "zones" - ? await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }) - : argv.local - ? LOCAL_ACCOUNT_ID - : await getAccountId(); - if (accountOrZone === "zones") { - argv.zoneId = accountOrZoneId; - } else { - argv.accountId = accountOrZoneId; - } - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_or_zone: accountOrZone, - account_or_zone_id: accountOrZoneId, - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - app: { - install_id: resolveFileToken( - argv["app-install-id"] as string | undefined, - "app-install-id", - "text" - ), - }, - component_values: parseObjectArray( - argv["component-values"], - "component-values" - ), - frequency: argv["frequency"], - rate_plan: { - currency: resolveFileToken( - argv["rate-plan-currency"] as string | undefined, - "rate-plan-currency", - "text" - ), - externally_managed: argv["rate-plan-externally-managed"], - id: resolveFileToken( - argv["rate-plan-id"] as string | undefined, - "rate-plan-id", - "text" - ), - is_contract: argv["rate-plan-is-contract"], - public_name: resolveFileToken( - argv["rate-plan-public-name"] as string | undefined, - "rate-plan-public-name", - "text" - ), - scope: resolveFileToken( - argv["rate-plan-scope"] as string | undefined, - "rate-plan-scope", - "text" - ), - sets: argv["rate-plan-sets"], - }, - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_or_zone: accountOrZone, - account_or_zone_id: accountOrZoneId, - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 accounts subscriptions create\n\nCreates an account or zone subscription.\n\nRuns against your account. Pass --zone to run against a zone instead. CLOUDFLARE_ZONE_ID is ignored.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/subscriptions/delete.handler.ts b/packages/cli/src/commands/_generated/accounts/subscriptions/delete.handler.ts new file mode 100644 index 0000000000..02ea0f66c3 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/subscriptions/delete.handler.ts @@ -0,0 +1,59 @@ +import operation from "../../_operations/accounts/subscriptions/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts subscriptions delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts subscriptions delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/subscriptions/${argv["subscription-identifier"] == null ? "" : encodeURIComponent(String(argv["subscription-identifier"]))}`, + pathParams: { + "subscription-identifier": String( + argv["subscription-identifier"] ?? "" + ), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + subscription_identifier: argv["subscription-identifier"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/subscriptions/delete.ts b/packages/cli/src/commands/_generated/accounts/subscriptions/delete.ts index 9b4cd04156..4b62967b9d 100644 --- a/packages/cli/src/commands/_generated/accounts/subscriptions/delete.ts +++ b/packages/cli/src/commands/_generated/accounts/subscriptions/delete.ts @@ -1,95 +1,43 @@ -import operation from "../../_operations/accounts/subscriptions/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts subscriptions delete \n\nDeletes an account's subscription." - ) - .positional("subscription-identifier", { - type: "string", - description: "Subscription identifier tag.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "subscription-identifier", + brief: "Subscription identifier tag.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete Subscription", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts subscriptions delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts subscriptions delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/subscriptions/${argv["subscription-identifier"] == null ? "" : encodeURIComponent(String(argv["subscription-identifier"]))}`, - pathParams: { - "subscription-identifier": String( - argv["subscription-identifier"] ?? "" - ), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - subscription_identifier: argv["subscription-identifier"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 accounts subscriptions delete \n\nDeletes an account's subscription.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/subscriptions/get-by-identifier.handler.ts b/packages/cli/src/commands/_generated/accounts/subscriptions/get-by-identifier.handler.ts new file mode 100644 index 0000000000..00c836bea7 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/subscriptions/get-by-identifier.handler.ts @@ -0,0 +1,53 @@ +import operation from "../../_operations/accounts/subscriptions/get-by-identifier.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get-by-identifier.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts subscriptions get-by-identifier", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts subscriptions get-by-identifier", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/subscriptions/${argv["subscription-identifier"] == null ? "" : encodeURIComponent(String(argv["subscription-identifier"]))}`, + pathParams: { + "subscription-identifier": String( + argv["subscription-identifier"] ?? "" + ), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + subscription_identifier: argv["subscription-identifier"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/subscriptions/get-by-identifier.ts b/packages/cli/src/commands/_generated/accounts/subscriptions/get-by-identifier.ts index dcc89c2e7f..0988e78937 100644 --- a/packages/cli/src/commands/_generated/accounts/subscriptions/get-by-identifier.ts +++ b/packages/cli/src/commands/_generated/accounts/subscriptions/get-by-identifier.ts @@ -1,83 +1,37 @@ -import operation from "../../_operations/accounts/subscriptions/get-by-identifier.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get-by-identifier command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts subscriptions get-by-identifier \n\nGets an account subscription by identifier." - ) - .positional("subscription-identifier", { - type: "string", - description: "Subscription identifier tag.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "subscription-identifier", + brief: "Subscription identifier tag.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get-by-identifier ", describe: "Get Subscription", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts subscriptions get-by-identifier", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts subscriptions get-by-identifier", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/subscriptions/${argv["subscription-identifier"] == null ? "" : encodeURIComponent(String(argv["subscription-identifier"]))}`, - pathParams: { - "subscription-identifier": String( - argv["subscription-identifier"] ?? "" - ), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - subscription_identifier: argv["subscription-identifier"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts subscriptions get-by-identifier \n\nGets an account subscription by identifier.", + ...parameters, + loader: () => import("./get-by-identifier.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/subscriptions/get-cancel-reason.handler.ts b/packages/cli/src/commands/_generated/accounts/subscriptions/get-cancel-reason.handler.ts new file mode 100644 index 0000000000..44d9e2eee3 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/subscriptions/get-cancel-reason.handler.ts @@ -0,0 +1,53 @@ +import operation from "../../_operations/accounts/subscriptions/get-cancel-reason.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get-cancel-reason.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts subscriptions get-cancel-reason", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts subscriptions get-cancel-reason", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/subscriptions/${argv["subscription-identifier"] == null ? "" : encodeURIComponent(String(argv["subscription-identifier"]))}/cancel-reason`, + pathParams: { + "subscription-identifier": String( + argv["subscription-identifier"] ?? "" + ), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + subscription_identifier: argv["subscription-identifier"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/subscriptions/get-cancel-reason.ts b/packages/cli/src/commands/_generated/accounts/subscriptions/get-cancel-reason.ts index 5f0f94c58f..35bb4bee27 100644 --- a/packages/cli/src/commands/_generated/accounts/subscriptions/get-cancel-reason.ts +++ b/packages/cli/src/commands/_generated/accounts/subscriptions/get-cancel-reason.ts @@ -1,83 +1,37 @@ -import operation from "../../_operations/accounts/subscriptions/get-cancel-reason.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get-cancel-reason command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts subscriptions get-cancel-reason \n\nGets the cancellation reason for an account subscription." - ) - .positional("subscription-identifier", { - type: "string", - description: "Subscription identifier tag.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "subscription-identifier", + brief: "Subscription identifier tag.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get-cancel-reason ", describe: "Get Cancel Reason", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts subscriptions get-cancel-reason", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts subscriptions get-cancel-reason", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/subscriptions/${argv["subscription-identifier"] == null ? "" : encodeURIComponent(String(argv["subscription-identifier"]))}/cancel-reason`, - pathParams: { - "subscription-identifier": String( - argv["subscription-identifier"] ?? "" - ), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - subscription_identifier: argv["subscription-identifier"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts subscriptions get-cancel-reason \n\nGets the cancellation reason for an account subscription.", + ...parameters, + loader: () => import("./get-cancel-reason.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/subscriptions/get.handler.ts b/packages/cli/src/commands/_generated/accounts/subscriptions/get.handler.ts new file mode 100644 index 0000000000..23fed365da --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/subscriptions/get.handler.ts @@ -0,0 +1,67 @@ +import operation from "../../_operations/accounts/subscriptions/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + getZoneId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts subscriptions get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = + argv.zone === undefined ? await resolveAccountIdSilent() : undefined; + const accountOrZone = argv.zone === undefined ? "accounts" : "zones"; + const accountOrZoneId = + argv.zone ?? __cfDryRunAccountId ?? ""; + formatDryRun({ + command: "cf accounts subscriptions get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/${accountOrZone}/${accountOrZoneId}/subscriptions`, + pathParams: { + "account-or-zone": String(accountOrZone), + "account-or-zone-id": String(accountOrZoneId), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountOrZone = argv.zone === undefined ? "accounts" : "zones"; + const accountOrZoneId = + accountOrZone === "zones" + ? await getZoneId({ zone: argv.zone }, client, { quiet: argv.quiet }) + : argv.local + ? LOCAL_ACCOUNT_ID + : await getAccountId(); + if (accountOrZone === "zones") { + argv.zoneId = accountOrZoneId; + } else { + argv.accountId = accountOrZoneId; + } + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_or_zone: accountOrZone, + account_or_zone_id: accountOrZoneId, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/subscriptions/get.ts b/packages/cli/src/commands/_generated/accounts/subscriptions/get.ts index 0c795d5405..d42910708b 100644 --- a/packages/cli/src/commands/_generated/accounts/subscriptions/get.ts +++ b/packages/cli/src/commands/_generated/accounts/subscriptions/get.ts @@ -1,96 +1,31 @@ -import operation from "../../_operations/accounts/subscriptions/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - getZoneId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts subscriptions get\n\nLists all of an account or zone's subscriptions.\n\nRuns against your account. Pass --zone to run against a zone instead. CLOUDFLARE_ZONE_ID is ignored." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "List Subscriptions", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts subscriptions get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = - argv.zone === undefined - ? await resolveAccountIdSilent() - : undefined; - const accountOrZone = argv.zone === undefined ? "accounts" : "zones"; - const accountOrZoneId = - argv.zone ?? __cfDryRunAccountId ?? ""; - formatDryRun({ - command: "cf accounts subscriptions get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/${accountOrZone}/${accountOrZoneId}/subscriptions`, - pathParams: { - "account-or-zone": String(accountOrZone), - "account-or-zone-id": String(accountOrZoneId), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountOrZone = argv.zone === undefined ? "accounts" : "zones"; - const accountOrZoneId = - accountOrZone === "zones" - ? await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }) - : argv.local - ? LOCAL_ACCOUNT_ID - : await getAccountId(); - if (accountOrZone === "zones") { - argv.zoneId = accountOrZoneId; - } else { - argv.accountId = accountOrZoneId; - } - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_or_zone: accountOrZone, - account_or_zone_id: accountOrZoneId, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts subscriptions get\n\nLists all of an account or zone's subscriptions.\n\nRuns against your account. Pass --zone to run against a zone instead. CLOUDFLARE_ZONE_ID is ignored.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/subscriptions/index.ts b/packages/cli/src/commands/_generated/accounts/subscriptions/index.ts index f7ea3a6ceb..a4a17cb101 100644 --- a/packages/cli/src/commands/_generated/accounts/subscriptions/index.ts +++ b/packages/cli/src/commands/_generated/accounts/subscriptions/index.ts @@ -6,31 +6,26 @@ import $getbyidentifier from "./get-by-identifier.js"; import $getcancelreason from "./get-cancel-reason.js"; import $get from "./get.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * subscriptions command group * @generated from apis/overlays/accounts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "subscriptions", describe: "View and manage plan subscriptions attached to this account", - builder: (yargs) => { - return yargs - .command($canceldelayeddowngrade) - .command($create) - .command($createcancelreason) - .command($delete) - .command($get) - .command($getbyidentifier) - .command($getcancelreason) - .command($update) - .demandCommand(1, "Please specify a subcommand"); + routes: { + "cancel-delayed-downgrade": $canceldelayeddowngrade, + create: $create, + "create-cancel-reason": $createcancelreason, + delete: $delete, + get: $get, + "get-by-identifier": $getbyidentifier, + "get-cancel-reason": $getcancelreason, + update: $update, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/subscriptions/update.handler.ts b/packages/cli/src/commands/_generated/accounts/subscriptions/update.handler.ts new file mode 100644 index 0000000000..b10b432cd6 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/subscriptions/update.handler.ts @@ -0,0 +1,158 @@ +import operation from "../../_operations/accounts/subscriptions/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts subscriptions update", + classification: { + safeFlags: [ + "frequency", + "rate-plan-externally-managed", + "rate-plan-is-contract", + "dry-run", + ], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts subscriptions update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/subscriptions/${argv["subscription-identifier"] == null ? "" : encodeURIComponent(String(argv["subscription-identifier"]))}`, + pathParams: { + "subscription-identifier": String( + argv["subscription-identifier"] ?? "" + ), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + app: { + install_id: resolveFileToken( + argv["app-install-id"] as string | undefined, + "app-install-id", + "text" + ), + }, + component_values: parseObjectArray( + argv["component-values"], + "component-values" + ), + frequency: argv["frequency"], + rate_plan: { + currency: resolveFileToken( + argv["rate-plan-currency"] as string | undefined, + "rate-plan-currency", + "text" + ), + externally_managed: argv["rate-plan-externally-managed"], + id: resolveFileToken( + argv["rate-plan-id"] as string | undefined, + "rate-plan-id", + "text" + ), + is_contract: argv["rate-plan-is-contract"], + public_name: resolveFileToken( + argv["rate-plan-public-name"] as string | undefined, + "rate-plan-public-name", + "text" + ), + scope: resolveFileToken( + argv["rate-plan-scope"] as string | undefined, + "rate-plan-scope", + "text" + ), + sets: argv["rate-plan-sets"], + }, + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + subscription_identifier: argv["subscription-identifier"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + app: { + install_id: resolveFileToken( + argv["app-install-id"] as string | undefined, + "app-install-id", + "text" + ), + }, + component_values: parseObjectArray( + argv["component-values"], + "component-values" + ), + frequency: argv["frequency"], + rate_plan: { + currency: resolveFileToken( + argv["rate-plan-currency"] as string | undefined, + "rate-plan-currency", + "text" + ), + externally_managed: argv["rate-plan-externally-managed"], + id: resolveFileToken( + argv["rate-plan-id"] as string | undefined, + "rate-plan-id", + "text" + ), + is_contract: argv["rate-plan-is-contract"], + public_name: resolveFileToken( + argv["rate-plan-public-name"] as string | undefined, + "rate-plan-public-name", + "text" + ), + scope: resolveFileToken( + argv["rate-plan-scope"] as string | undefined, + "rate-plan-scope", + "text" + ), + sets: argv["rate-plan-sets"], + }, + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + subscription_identifier: argv["subscription-identifier"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/subscriptions/update.ts b/packages/cli/src/commands/_generated/accounts/subscriptions/update.ts index d825addf27..f172cfdf75 100644 --- a/packages/cli/src/commands/_generated/accounts/subscriptions/update.ts +++ b/packages/cli/src/commands/_generated/accounts/subscriptions/update.ts @@ -1,241 +1,108 @@ -import operation from "../../_operations/accounts/subscriptions/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts subscriptions update \n\nUpdates an account subscription." - ) - .positional("subscription-identifier", { - type: "string", - description: "Subscription identifier tag.", - demandOption: true, - }) - .option("app-install-id", { - type: "string", - description: "app install id.", - }) - .option("component-values", { - type: "string", - description: +const parameters = { + flags: { + "app-install-id": { + kind: "parsed", + brief: "app install id.", + optional: true, + parse: String, + }, + "component-values": { + kind: "parsed", + brief: 'Configurable component values for the subscription. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"default"?: number, "display_name"?: string, "kind"?: "enum" | "sum" | "usage", "name"?: string, "price"?: number, ...more}]. ? marks optional keys.', - }) - .option("frequency", { - type: "string", - description: "How often the subscription is renewed automatically.", + optional: true, + parse: String, + }, + frequency: { + kind: "parsed", + brief: "How often the subscription is renewed automatically.", + optional: true, choices: ["weekly", "monthly", "quarterly", "yearly"], - }) - .coerce("frequency", (value) => - resolveFileToken(value, "frequency", "text") - ) - .option("rate-plan-currency", { - type: "string", - description: "The currency applied to the rate plan subscription.", - }) - .option("rate-plan-externally-managed", { - type: "boolean", - description: - "Whether this rate plan is managed externally from Cloudflare.", - }) - .option("rate-plan-id", { - type: "string", - description: "The ID of the rate plan.", - }) - .option("rate-plan-is-contract", { - type: "boolean", - description: + parse: String, + coerce: (value: string) => resolveFileToken(value, "frequency", "text"), + }, + "rate-plan-currency": { + kind: "parsed", + brief: "The currency applied to the rate plan subscription.", + optional: true, + parse: String, + }, + "rate-plan-externally-managed": { + kind: "boolean", + brief: "Whether this rate plan is managed externally from Cloudflare.", + optional: true, + }, + "rate-plan-id": { + kind: "parsed", + brief: "The ID of the rate plan.", + optional: true, + parse: String, + }, + "rate-plan-is-contract": { + kind: "boolean", + brief: "Whether a rate plan is enterprise-based (or newly adopted term contract).", - }) - .option("rate-plan-public-name", { - type: "string", - description: "The full name of the rate plan.", - }) - .option("rate-plan-scope", { - type: "string", - description: "The scope that this rate plan applies to.", - }) - .option("rate-plan-sets", { - type: "string", - array: true, - description: + optional: true, + }, + "rate-plan-public-name": { + kind: "parsed", + brief: "The full name of the rate plan.", + optional: true, + parse: String, + }, + "rate-plan-scope": { + kind: "parsed", + brief: "The scope that this rate plan applies to.", + optional: true, + parse: String, + }, + "rate-plan-sets": { + kind: "parsed", + brief: "The list of sets this rate plan applies to. Returns array of strings.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + variadic: true, + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "subscription-identifier", + brief: "Subscription identifier tag.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update ", describe: "Update Subscription", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts subscriptions update", - classification: { - safeFlags: [ - "frequency", - "rate-plan-externally-managed", - "rate-plan-is-contract", - "dry-run", - ], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts subscriptions update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/subscriptions/${argv["subscription-identifier"] == null ? "" : encodeURIComponent(String(argv["subscription-identifier"]))}`, - pathParams: { - "subscription-identifier": String( - argv["subscription-identifier"] ?? "" - ), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - app: { - install_id: resolveFileToken( - argv["app-install-id"] as string | undefined, - "app-install-id", - "text" - ), - }, - component_values: parseObjectArray( - argv["component-values"], - "component-values" - ), - frequency: argv["frequency"], - rate_plan: { - currency: resolveFileToken( - argv["rate-plan-currency"] as string | undefined, - "rate-plan-currency", - "text" - ), - externally_managed: argv["rate-plan-externally-managed"], - id: resolveFileToken( - argv["rate-plan-id"] as string | undefined, - "rate-plan-id", - "text" - ), - is_contract: argv["rate-plan-is-contract"], - public_name: resolveFileToken( - argv["rate-plan-public-name"] as string | undefined, - "rate-plan-public-name", - "text" - ), - scope: resolveFileToken( - argv["rate-plan-scope"] as string | undefined, - "rate-plan-scope", - "text" - ), - sets: argv["rate-plan-sets"], - }, - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - subscription_identifier: argv["subscription-identifier"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - app: { - install_id: resolveFileToken( - argv["app-install-id"] as string | undefined, - "app-install-id", - "text" - ), - }, - component_values: parseObjectArray( - argv["component-values"], - "component-values" - ), - frequency: argv["frequency"], - rate_plan: { - currency: resolveFileToken( - argv["rate-plan-currency"] as string | undefined, - "rate-plan-currency", - "text" - ), - externally_managed: argv["rate-plan-externally-managed"], - id: resolveFileToken( - argv["rate-plan-id"] as string | undefined, - "rate-plan-id", - "text" - ), - is_contract: argv["rate-plan-is-contract"], - public_name: resolveFileToken( - argv["rate-plan-public-name"] as string | undefined, - "rate-plan-public-name", - "text" - ), - scope: resolveFileToken( - argv["rate-plan-scope"] as string | undefined, - "rate-plan-scope", - "text" - ), - sets: argv["rate-plan-sets"], - }, - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - subscription_identifier: argv["subscription-identifier"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 accounts subscriptions update \n\nUpdates an account subscription.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/tokens/create.handler.ts b/packages/cli/src/commands/_generated/accounts/tokens/create.handler.ts new file mode 100644 index 0000000000..9949e82ea6 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/tokens/create.handler.ts @@ -0,0 +1,126 @@ +import operation from "../../_operations/accounts/tokens/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts tokens create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField("name", "Token name."); + } + if (argv["policies"] === undefined) { + throw new Error( + "--policies is required (or pass --body with this field set)." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts tokens create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/tokens`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + condition: { + request_ip: { + in: argv["condition-request-ip-in"], + not_in: argv["condition-request-ip-not-in"], + }, + }, + expires_on: resolveFileToken( + argv["expires-on"] as string | undefined, + "expires-on", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + not_before: resolveFileToken( + argv["not-before"] as string | undefined, + "not-before", + "text" + ), + policies: parseObjectArray(argv["policies"], "policies"), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + condition: { + request_ip: { + in: argv["condition-request-ip-in"], + not_in: argv["condition-request-ip-not-in"], + }, + }, + expires_on: resolveFileToken( + argv["expires-on"] as string | undefined, + "expires-on", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + not_before: resolveFileToken( + argv["not-before"] as string | undefined, + "not-before", + "text" + ), + policies: parseObjectArray(argv["policies"], "policies"), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/tokens/create.ts b/packages/cli/src/commands/_generated/accounts/tokens/create.ts index 4ad2622241..7204c572f0 100644 --- a/packages/cli/src/commands/_generated/accounts/tokens/create.ts +++ b/packages/cli/src/commands/_generated/accounts/tokens/create.ts @@ -1,179 +1,77 @@ -import operation from "../../_operations/accounts/tokens/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage("$0 accounts tokens create\n\nCreate a new Account Owned API token.") - .option("condition-request-ip-in", { - type: "string", - array: true, - description: "List of IPv4/IPv6 CIDR addresses.", - }) - .option("condition-request-ip-not-in", { - type: "string", - array: true, - description: "List of IPv4/IPv6 CIDR addresses.", - }) - .option("expires-on", { - type: "string", - description: +const parameters = { + flags: { + "condition-request-ip-in": { + kind: "parsed", + brief: "List of IPv4/IPv6 CIDR addresses.", + variadic: true, + optional: true, + parse: String, + }, + "condition-request-ip-not-in": { + kind: "parsed", + brief: "List of IPv4/IPv6 CIDR addresses.", + variadic: true, + optional: true, + parse: String, + }, + "expires-on": { + kind: "parsed", + brief: "The expiration time on or after which the JWT MUST NOT be accepted for processing.", - }) - .option("name", { type: "string", description: "Token name." }) - .option("not-before", { - type: "string", - description: + optional: true, + parse: String, + }, + name: { + kind: "parsed", + brief: "Token name.", + optional: true, + parse: String, + }, + "not-before": { + kind: "parsed", + brief: "The time before which the token MUST NOT be accepted for processing.", - }) - .option("policies", { - type: "string", - description: + optional: true, + parse: String, + }, + policies: { + kind: "parsed", + brief: 'List of access policies assigned to the token. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"effect": "allow" | "deny", "permission_groups": [{...}], "resources": {...}}].', - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Create Token", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts tokens create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField("name", "Token name."); - } - if (argv["policies"] === undefined) { - throw new Error( - "--policies is required (or pass --body with this field set)." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts tokens create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/tokens`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - condition: { - request_ip: { - in: argv["condition-request-ip-in"], - not_in: argv["condition-request-ip-not-in"], - }, - }, - expires_on: resolveFileToken( - argv["expires-on"] as string | undefined, - "expires-on", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - not_before: resolveFileToken( - argv["not-before"] as string | undefined, - "not-before", - "text" - ), - policies: parseObjectArray(argv["policies"], "policies"), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - condition: { - request_ip: { - in: argv["condition-request-ip-in"], - not_in: argv["condition-request-ip-not-in"], - }, - }, - expires_on: resolveFileToken( - argv["expires-on"] as string | undefined, - "expires-on", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - not_before: resolveFileToken( - argv["not-before"] as string | undefined, - "not-before", - "text" - ), - policies: parseObjectArray(argv["policies"], "policies"), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: "$0 accounts tokens create\n\nCreate a new Account Owned API token.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/tokens/delete.handler.ts b/packages/cli/src/commands/_generated/accounts/tokens/delete.handler.ts new file mode 100644 index 0000000000..2ad7018acd --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/tokens/delete.handler.ts @@ -0,0 +1,60 @@ +import operation from "../../_operations/accounts/tokens/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts tokens delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts tokens delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/tokens/${argv["token-id"] == null ? "" : encodeURIComponent(String(argv["token-id"]))}`, + pathParams: { "token-id": String(argv["token-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `Are you sure? This action cannot be undone.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + token_id: argv["token-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/tokens/delete.ts b/packages/cli/src/commands/_generated/accounts/tokens/delete.ts index 4125ce4502..48f7788d89 100644 --- a/packages/cli/src/commands/_generated/accounts/tokens/delete.ts +++ b/packages/cli/src/commands/_generated/accounts/tokens/delete.ts @@ -1,96 +1,39 @@ -import operation from "../../_operations/accounts/tokens/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts tokens delete \n\nDestroy an Account Owned API token." - ) - .positional("token-id", { - type: "string", - description: "Token identifier tag.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "token-id", brief: "Token identifier tag.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete Token", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts tokens delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts tokens delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/tokens/${argv["token-id"] == null ? "" : encodeURIComponent(String(argv["token-id"]))}`, - pathParams: { "token-id": String(argv["token-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `Are you sure? This action cannot be undone.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - token_id: argv["token-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 accounts tokens delete \n\nDestroy an Account Owned API token.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/tokens/get.handler.ts b/packages/cli/src/commands/_generated/accounts/tokens/get.handler.ts new file mode 100644 index 0000000000..2d302a6d6c --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/tokens/get.handler.ts @@ -0,0 +1,49 @@ +import operation from "../../_operations/accounts/tokens/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts tokens get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts tokens get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/tokens/${argv["token-id"] == null ? "" : encodeURIComponent(String(argv["token-id"]))}`, + pathParams: { "token-id": String(argv["token-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + token_id: argv["token-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/tokens/get.ts b/packages/cli/src/commands/_generated/accounts/tokens/get.ts index f68456effa..4d7b1f0cb9 100644 --- a/packages/cli/src/commands/_generated/accounts/tokens/get.ts +++ b/packages/cli/src/commands/_generated/accounts/tokens/get.ts @@ -1,79 +1,33 @@ -import operation from "../../_operations/accounts/tokens/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts tokens get \n\nGet information about a specific Account Owned API token." - ) - .positional("token-id", { - type: "string", - description: "Token identifier tag.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "token-id", brief: "Token identifier tag.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Token Details", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts tokens get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts tokens get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/tokens/${argv["token-id"] == null ? "" : encodeURIComponent(String(argv["token-id"]))}`, - pathParams: { "token-id": String(argv["token-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - token_id: argv["token-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts tokens get \n\nGet information about a specific Account Owned API token.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/tokens/index.ts b/packages/cli/src/commands/_generated/accounts/tokens/index.ts index a88a22d463..6007bcea6b 100644 --- a/packages/cli/src/commands/_generated/accounts/tokens/index.ts +++ b/packages/cli/src/commands/_generated/accounts/tokens/index.ts @@ -6,32 +6,27 @@ import $permissiongroups from "./permission-groups/index.js"; import $roll from "./roll.js"; import $update from "./update.js"; import $verify from "./verify.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * tokens command group * @generated from apis/overlays/accounts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "tokens", describe: "Create and manage scoped API tokens for programmatic access to the Cloudflare API", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .command($list) - .command($roll) - .command($update) - .command($verify) - .command($permissiongroups) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, + list: $list, + roll: $roll, + update: $update, + verify: $verify, + "permission-groups": $permissiongroups, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/tokens/list.handler.ts b/packages/cli/src/commands/_generated/accounts/tokens/list.handler.ts new file mode 100644 index 0000000000..f3674d5ae0 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/tokens/list.handler.ts @@ -0,0 +1,53 @@ +import operation from "../../_operations/accounts/tokens/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts tokens list", + classification: { + safeFlags: ["direction", "include-expired", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + direction: argv["direction"], + include_expired: argv["include-expired"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts tokens list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/tokens`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/tokens/list.ts b/packages/cli/src/commands/_generated/accounts/tokens/list.ts index 746e295420..e09d539010 100644 --- a/packages/cli/src/commands/_generated/accounts/tokens/list.ts +++ b/packages/cli/src/commands/_generated/accounts/tokens/list.ts @@ -1,96 +1,54 @@ -import operation from "../../_operations/accounts/tokens/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts tokens list\n\nList Account Owned API tokens created for this account. Callers with `com.cloudflare.api.account.token.list_self` permission only receive tokens they created. Results include active, disabled, and recently-expired tokens when `include_expired` is set to true." - ) - .option("page", { - type: "number", - description: "Page number of paginated results.", - }) - .option("per-page", { - type: "number", - description: "Maximum number of results per page.", - }) - .option("direction", { - type: "string", - description: "Direction to order results.", - choices: ["asc", "desc"], - }) - .option("include-expired", { - type: "boolean", - description: - "When true, includes recently-expired tokens in the response.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + page: { + kind: "parsed", + brief: "Page number of paginated results.", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Maximum number of results per page.", + optional: true, + parse: Number, + }, + direction: { + kind: "enum", + brief: "Direction to order results.", + values: ["asc", "desc"], + optional: true, + }, + "include-expired": { + kind: "boolean", + brief: "When true, includes recently-expired tokens in the response.", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Tokens", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts tokens list", - classification: { - safeFlags: ["direction", "include-expired", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - direction: argv["direction"], - include_expired: argv["include-expired"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts tokens list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/tokens`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts tokens list\n\nList Account Owned API tokens created for this account. Callers with `com.cloudflare.api.account.token.list_self` permission only receive tokens they created. Results include active, disabled, and recently-expired tokens when `include_expired` is set to true.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/tokens/permission-groups/index.ts b/packages/cli/src/commands/_generated/accounts/tokens/permission-groups/index.ts index 3b60d2eaff..e740d40a0b 100644 --- a/packages/cli/src/commands/_generated/accounts/tokens/permission-groups/index.ts +++ b/packages/cli/src/commands/_generated/accounts/tokens/permission-groups/index.ts @@ -1,20 +1,17 @@ import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * permission-groups command group * @generated from apis/overlays/accounts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "permission-groups", describe: "Operations for tokens.permission-groups", - builder: (yargs) => { - return yargs.command($list).demandCommand(1, "Please specify a subcommand"); + routes: { + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/tokens/permission-groups/list.handler.ts b/packages/cli/src/commands/_generated/accounts/tokens/permission-groups/list.handler.ts new file mode 100644 index 0000000000..570fc7881f --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/tokens/permission-groups/list.handler.ts @@ -0,0 +1,51 @@ +import operation from "../../../_operations/accounts/tokens/permission-groups/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts tokens permission-groups list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + name: argv["name"], + scope: argv["scope"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts tokens permission-groups list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/tokens/permission_groups`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/tokens/permission-groups/list.ts b/packages/cli/src/commands/_generated/accounts/tokens/permission-groups/list.ts index c9e03f968c..307bf6cfa0 100644 --- a/packages/cli/src/commands/_generated/accounts/tokens/permission-groups/list.ts +++ b/packages/cli/src/commands/_generated/accounts/tokens/permission-groups/list.ts @@ -1,86 +1,45 @@ -import operation from "../../../_operations/accounts/tokens/permission-groups/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts tokens permission-groups list\n\nFind all available permission groups for Account Owned API Tokens. Each permission group indicates whether the caller can select it when creating a token. Token creation performs the authoritative permission check." - ) - .option("name", { - type: "string", - description: +const parameters = { + flags: { + name: { + kind: "parsed", + brief: "Filter by the name of the permission group.\nThe value must be URL-encoded.", - }) - .option("scope", { - type: "string", - description: + optional: true, + parse: String, + }, + scope: { + kind: "parsed", + brief: "Filter by the scope of the permission group.\nThe value must be URL-encoded.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Permission Groups", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts tokens permission-groups list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - name: argv["name"], - scope: argv["scope"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts tokens permission-groups list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/tokens/permission_groups`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts tokens permission-groups list\n\nFind all available permission groups for Account Owned API Tokens. Each permission group indicates whether the caller can select it when creating a token. Token creation performs the authoritative permission check.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/tokens/roll.handler.ts b/packages/cli/src/commands/_generated/accounts/tokens/roll.handler.ts new file mode 100644 index 0000000000..1c46b6f3e8 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/tokens/roll.handler.ts @@ -0,0 +1,60 @@ +import operation from "../../_operations/accounts/tokens/roll.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./roll.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts tokens roll", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts tokens roll", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/tokens/${argv["token-id"] == null ? "" : encodeURIComponent(String(argv["token-id"]))}/value`, + pathParams: { "token-id": String(argv["token-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `Rolling this token will invalidate the current secret and generate a new one. Any integrations using the current secret will stop working.`, + })) + ) { + return; + } + + const result = await withProgress(`Updating`, async () => + client.send(operation, { + account_id: accountId, + token_id: argv["token-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/tokens/roll.ts b/packages/cli/src/commands/_generated/accounts/tokens/roll.ts index cb161b5a38..50ec5630f5 100644 --- a/packages/cli/src/commands/_generated/accounts/tokens/roll.ts +++ b/packages/cli/src/commands/_generated/accounts/tokens/roll.ts @@ -1,96 +1,39 @@ -import operation from "../../_operations/accounts/tokens/roll.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * roll command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts tokens roll \n\nRoll the Account Owned API token secret." - ) - .positional("token-id", { - type: "string", - description: "Token identifier tag.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "token-id", brief: "Token identifier tag.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "roll ", describe: "Roll Token", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts tokens roll", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts tokens roll", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/tokens/${argv["token-id"] == null ? "" : encodeURIComponent(String(argv["token-id"]))}/value`, - pathParams: { "token-id": String(argv["token-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `Rolling this token will invalidate the current secret and generate a new one. Any integrations using the current secret will stop working.`, - })) - ) { - return; - } - - const result = await withProgress(`Updating`, async () => - client.send(operation, { - account_id: accountId, - token_id: argv["token-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 accounts tokens roll \n\nRoll the Account Owned API token secret.", + ...parameters, + loader: () => import("./roll.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/tokens/update.handler.ts b/packages/cli/src/commands/_generated/accounts/tokens/update.handler.ts new file mode 100644 index 0000000000..aaee11ced4 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/tokens/update.handler.ts @@ -0,0 +1,136 @@ +import operation from "../../_operations/accounts/tokens/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts tokens update", + classification: { + safeFlags: ["status", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField("name", "Token name."); + } + if (argv["policies"] === undefined) { + throw new Error( + "--policies is required (or pass --body with this field set)." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts tokens update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/tokens/${argv["token-id"] == null ? "" : encodeURIComponent(String(argv["token-id"]))}`, + pathParams: { "token-id": String(argv["token-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + condition: { + request_ip: { + in: argv["condition-request-ip-in"], + not_in: argv["condition-request-ip-not-in"], + }, + }, + expires_on: resolveFileToken( + argv["expires-on"] as string | undefined, + "expires-on", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + not_before: resolveFileToken( + argv["not-before"] as string | undefined, + "not-before", + "text" + ), + policies: parseObjectArray(argv["policies"], "policies"), + status: argv["status"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + token_id: argv["token-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + condition: { + request_ip: { + in: argv["condition-request-ip-in"], + not_in: argv["condition-request-ip-not-in"], + }, + }, + expires_on: resolveFileToken( + argv["expires-on"] as string | undefined, + "expires-on", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + not_before: resolveFileToken( + argv["not-before"] as string | undefined, + "not-before", + "text" + ), + policies: parseObjectArray(argv["policies"], "policies"), + status: argv["status"], + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + token_id: argv["token-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/tokens/update.ts b/packages/cli/src/commands/_generated/accounts/tokens/update.ts index ac9f7c704a..eec907b4c0 100644 --- a/packages/cli/src/commands/_generated/accounts/tokens/update.ts +++ b/packages/cli/src/commands/_generated/accounts/tokens/update.ts @@ -1,200 +1,88 @@ -import operation from "../../_operations/accounts/tokens/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage("$0 accounts tokens update \n\nUpdate an existing token.") - .positional("token-id", { - type: "string", - description: "Token identifier tag.", - demandOption: true, - }) - .option("condition-request-ip-in", { - type: "string", - array: true, - description: "List of IPv4/IPv6 CIDR addresses.", - }) - .option("condition-request-ip-not-in", { - type: "string", - array: true, - description: "List of IPv4/IPv6 CIDR addresses.", - }) - .option("expires-on", { - type: "string", - description: +const parameters = { + flags: { + "condition-request-ip-in": { + kind: "parsed", + brief: "List of IPv4/IPv6 CIDR addresses.", + variadic: true, + optional: true, + parse: String, + }, + "condition-request-ip-not-in": { + kind: "parsed", + brief: "List of IPv4/IPv6 CIDR addresses.", + variadic: true, + optional: true, + parse: String, + }, + "expires-on": { + kind: "parsed", + brief: "The expiration time on or after which the JWT MUST NOT be accepted for processing.", - }) - .option("name", { type: "string", description: "Token name." }) - .option("not-before", { - type: "string", - description: + optional: true, + parse: String, + }, + name: { + kind: "parsed", + brief: "Token name.", + optional: true, + parse: String, + }, + "not-before": { + kind: "parsed", + brief: "The time before which the token MUST NOT be accepted for processing.", - }) - .option("policies", { - type: "string", - description: + optional: true, + parse: String, + }, + policies: { + kind: "parsed", + brief: 'List of access policies assigned to the token. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"effect": "allow" | "deny", "permission_groups": [{...}], "resources": {...}}].', - }) - .option("status", { - type: "string", - description: "Status of the token.", + optional: true, + parse: String, + }, + status: { + kind: "parsed", + brief: "Status of the token.", + optional: true, choices: ["active", "disabled", "expired"], - }) - .coerce("status", (value) => resolveFileToken(value, "status", "text")) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => resolveFileToken(value, "status", "text"), + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { placeholder: "token-id", brief: "Token identifier tag.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update ", describe: "Update Token", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts tokens update", - classification: { - safeFlags: ["status", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField("name", "Token name."); - } - if (argv["policies"] === undefined) { - throw new Error( - "--policies is required (or pass --body with this field set)." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts tokens update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/tokens/${argv["token-id"] == null ? "" : encodeURIComponent(String(argv["token-id"]))}`, - pathParams: { "token-id": String(argv["token-id"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - condition: { - request_ip: { - in: argv["condition-request-ip-in"], - not_in: argv["condition-request-ip-not-in"], - }, - }, - expires_on: resolveFileToken( - argv["expires-on"] as string | undefined, - "expires-on", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - not_before: resolveFileToken( - argv["not-before"] as string | undefined, - "not-before", - "text" - ), - policies: parseObjectArray(argv["policies"], "policies"), - status: argv["status"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - token_id: argv["token-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - condition: { - request_ip: { - in: argv["condition-request-ip-in"], - not_in: argv["condition-request-ip-not-in"], - }, - }, - expires_on: resolveFileToken( - argv["expires-on"] as string | undefined, - "expires-on", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - not_before: resolveFileToken( - argv["not-before"] as string | undefined, - "not-before", - "text" - ), - policies: parseObjectArray(argv["policies"], "policies"), - status: argv["status"], - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - token_id: argv["token-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: "$0 accounts tokens update \n\nUpdate an existing token.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/tokens/verify.handler.ts b/packages/cli/src/commands/_generated/accounts/tokens/verify.handler.ts new file mode 100644 index 0000000000..965da51f74 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/tokens/verify.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/accounts/tokens/verify.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./verify.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts tokens verify", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts tokens verify", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/tokens/verify`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/tokens/verify.ts b/packages/cli/src/commands/_generated/accounts/tokens/verify.ts index e3a198bd89..67b949089f 100644 --- a/packages/cli/src/commands/_generated/accounts/tokens/verify.ts +++ b/packages/cli/src/commands/_generated/accounts/tokens/verify.ts @@ -1,69 +1,30 @@ -import operation from "../../_operations/accounts/tokens/verify.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * verify command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage("$0 accounts tokens verify\n\nTest whether a token works.") - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "verify", describe: "Verify Token", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts tokens verify", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts tokens verify", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/tokens/verify`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: "$0 accounts tokens verify\n\nTest whether a token works.", + ...parameters, + loader: () => import("./verify.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/transformations/index.ts b/packages/cli/src/commands/_generated/accounts/transformations/index.ts index 2451ccff97..8dcd2d0734 100644 --- a/packages/cli/src/commands/_generated/accounts/transformations/index.ts +++ b/packages/cli/src/commands/_generated/accounts/transformations/index.ts @@ -1,20 +1,17 @@ import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * transformations command group * @generated from apis/overlays/accounts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "transformations", describe: "Operations for transformations", - builder: (yargs) => { - return yargs.command($list).demandCommand(1, "Please specify a subcommand"); + routes: { + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/transformations/list.handler.ts b/packages/cli/src/commands/_generated/accounts/transformations/list.handler.ts new file mode 100644 index 0000000000..99c653547c --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/transformations/list.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/accounts/transformations/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts transformations list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts transformations list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/settings/transformations`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/transformations/list.ts b/packages/cli/src/commands/_generated/accounts/transformations/list.ts index 727bc8c2cf..b2a0029ddd 100644 --- a/packages/cli/src/commands/_generated/accounts/transformations/list.ts +++ b/packages/cli/src/commands/_generated/accounts/transformations/list.ts @@ -1,71 +1,31 @@ -import operation from "../../_operations/accounts/transformations/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts transformations list\n\nReturns a list of Image Resizing configurations across all zones for the account. This endpoint is useful for retrieving the transformations (image_resizing) state for all zones belonging to an account." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Image Resizing configurations for account", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts transformations list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts transformations list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/settings/transformations`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts transformations list\n\nReturns a list of Image Resizing configurations across all zones for the account. This endpoint is useful for retrieving the transformations (image_resizing) state for all zones belonging to an account.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/update.handler.ts b/packages/cli/src/commands/_generated/accounts/update.handler.ts new file mode 100644 index 0000000000..9d26724776 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/update.handler.ts @@ -0,0 +1,117 @@ +import operation from "../_operations/accounts/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts update", + classification: { + safeFlags: ["settings-enforce-twofactor", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["id"] === undefined) { + argv["id"] = await promptForRequiredField("id", "Identifier"); + } + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField( + "name", + "Account name. When creating or updating an account, the name is limited to 65 UTF-8 bytes." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + id: resolveFileToken( + argv["id"] as string | undefined, + "id", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + settings: { + abuse_contact_email: resolveFileToken( + argv["settings-abuse-contact-email"] as + | string + | undefined, + "settings-abuse-contact-email", + "text" + ), + enforce_twofactor: argv["settings-enforce-twofactor"], + }, + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + id: resolveFileToken(argv["id"] as string | undefined, "id", "text"), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + settings: { + abuse_contact_email: resolveFileToken( + argv["settings-abuse-contact-email"] as string | undefined, + "settings-abuse-contact-email", + "text" + ), + enforce_twofactor: argv["settings-enforce-twofactor"], + }, + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/update.ts b/packages/cli/src/commands/_generated/accounts/update.ts index 93679682b0..a9fd32d70f 100644 --- a/packages/cli/src/commands/_generated/accounts/update.ts +++ b/packages/cli/src/commands/_generated/accounts/update.ts @@ -1,161 +1,57 @@ -import operation from "../_operations/accounts/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts update\n\nUpdate an existing account. Account names are limited to 65 UTF-8 bytes." - ) - .option("id", { type: "string", description: "Identifier" }) - .option("name", { - type: "string", - description: +const parameters = { + flags: { + id: { kind: "parsed", brief: "Identifier", optional: true, parse: String }, + name: { + kind: "parsed", + brief: "Account name. When creating or updating an account, the name is limited to 65 UTF-8 bytes.", - }) - .option("settings-abuse-contact-email", { - type: "string", - description: "Sets an abuse contact email to notify for abuse reports.", - }) - .option("settings-enforce-twofactor", { - type: "boolean", - description: + optional: true, + parse: String, + }, + "settings-abuse-contact-email": { + kind: "parsed", + brief: "Sets an abuse contact email to notify for abuse reports.", + optional: true, + parse: String, + }, + "settings-enforce-twofactor": { + kind: "boolean", + brief: "Indicates whether membership in this account requires that\nTwo-Factor Authentication is enabled", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update", describe: "Update Account", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts update", - classification: { - safeFlags: ["settings-enforce-twofactor", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["id"] === undefined) { - argv["id"] = await promptForRequiredField("id", "Identifier"); - } - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "Account name. When creating or updating an account, the name is limited to 65 UTF-8 bytes." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - id: resolveFileToken( - argv["id"] as string | undefined, - "id", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - settings: { - abuse_contact_email: resolveFileToken( - argv["settings-abuse-contact-email"] as - | string - | undefined, - "settings-abuse-contact-email", - "text" - ), - enforce_twofactor: argv["settings-enforce-twofactor"], - }, - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - id: resolveFileToken(argv["id"] as string | undefined, "id", "text"), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - settings: { - abuse_contact_email: resolveFileToken( - argv["settings-abuse-contact-email"] as string | undefined, - "settings-abuse-contact-email", - "text" - ), - enforce_twofactor: argv["settings-enforce-twofactor"], - }, - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 accounts update\n\nUpdate an existing account. Account names are limited to 65 UTF-8 bytes.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/ut-billing/edit.handler.ts b/packages/cli/src/commands/_generated/accounts/ut-billing/edit.handler.ts new file mode 100644 index 0000000000..66da922981 --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/ut-billing/edit.handler.ts @@ -0,0 +1,82 @@ +import operation from "../../_operations/accounts/ut-billing/edit.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./edit.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredEnumField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts ut-billing edit", + classification: { + safeFlags: ["value", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["value"] === undefined) { + argv["value"] = await promptForRequiredEnumField( + "value", + 'Enables Unique Transformations billing for the account. Note: once enabled, this setting cannot be set back to "off". ', + ["on"] as const + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts ut-billing edit", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/settings/ut-billing`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + value: argv["value"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + value: argv["value"], + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/ut-billing/edit.ts b/packages/cli/src/commands/_generated/accounts/ut-billing/edit.ts index b3cc350220..b1fb4415e5 100644 --- a/packages/cli/src/commands/_generated/accounts/ut-billing/edit.ts +++ b/packages/cli/src/commands/_generated/accounts/ut-billing/edit.ts @@ -1,119 +1,47 @@ -import operation from "../../_operations/accounts/ut-billing/edit.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * edit command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredEnumField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - '$0 accounts ut-billing edit\n\nUpdates the Unique Transformations billing configuration for an account. When enabled, billing data is directed to the Transformations pipeline. Note: setting the value to "off" is not permitted once enabled.' - ) - .option("value", { - type: "string", - description: +const parameters = { + flags: { + value: { + kind: "parsed", + brief: 'Enables Unique Transformations billing for the account.\nNote: once enabled, this setting cannot be set back to "off".\n', + optional: true, choices: ["on"], - }) - .coerce("value", (value) => resolveFileToken(value, "value", "text")) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => resolveFileToken(value, "value", "text"), + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "edit", describe: "Change Unique Transformations billing setting", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts ut-billing edit", - classification: { - safeFlags: ["value", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["value"] === undefined) { - argv["value"] = await promptForRequiredEnumField( - "value", - 'Enables Unique Transformations billing for the account. Note: once enabled, this setting cannot be set back to "off". ', - ["on"] as const - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts ut-billing edit", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/settings/ut-billing`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - value: argv["value"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - value: argv["value"], - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + '$0 accounts ut-billing edit\n\nUpdates the Unique Transformations billing configuration for an account. When enabled, billing data is directed to the Transformations pipeline. Note: setting the value to "off" is not permitted once enabled.', + ...parameters, + loader: () => import("./edit.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/ut-billing/get.handler.ts b/packages/cli/src/commands/_generated/accounts/ut-billing/get.handler.ts new file mode 100644 index 0000000000..a42c13861c --- /dev/null +++ b/packages/cli/src/commands/_generated/accounts/ut-billing/get.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/accounts/ut-billing/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "accounts ut-billing get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf accounts ut-billing get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/settings/ut-billing`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/accounts/ut-billing/get.ts b/packages/cli/src/commands/_generated/accounts/ut-billing/get.ts index 12596e0b5b..a17accbc8e 100644 --- a/packages/cli/src/commands/_generated/accounts/ut-billing/get.ts +++ b/packages/cli/src/commands/_generated/accounts/ut-billing/get.ts @@ -1,71 +1,31 @@ -import operation from "../../_operations/accounts/ut-billing/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/accounts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 accounts ut-billing get\n\nRetrieves the Unique Transformations billing configuration for an account. When enabled, billing data is directed to the Transformations pipeline." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "Get Unique Transformations billing setting", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "accounts ut-billing get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf accounts ut-billing get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/settings/ut-billing`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 accounts ut-billing get\n\nRetrieves the Unique Transformations billing configuration for an account. When enabled, billing data is directed to the Transformations pipeline.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/accounts/ut-billing/index.ts b/packages/cli/src/commands/_generated/accounts/ut-billing/index.ts index 15955ea677..9580b0c2cf 100644 --- a/packages/cli/src/commands/_generated/accounts/ut-billing/index.ts +++ b/packages/cli/src/commands/_generated/accounts/ut-billing/index.ts @@ -1,24 +1,19 @@ import $edit from "./edit.js"; import $get from "./get.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * ut-billing command group * @generated from apis/overlays/accounts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "ut-billing", describe: "Operations for ut-billing", - builder: (yargs) => { - return yargs - .command($edit) - .command($get) - .demandCommand(1, "Please specify a subcommand"); + routes: { + edit: $edit, + get: $get, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/acm/custom-trust-store/create.handler.ts b/packages/cli/src/commands/_generated/acm/custom-trust-store/create.handler.ts new file mode 100644 index 0000000000..99e08be3a1 --- /dev/null +++ b/packages/cli/src/commands/_generated/acm/custom-trust-store/create.handler.ts @@ -0,0 +1,86 @@ +import operation from "../../_operations/acm/custom-trust-store/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "acm custom-trust-store create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["certificate"] === undefined) { + argv["certificate"] = await promptForRequiredField( + "certificate", + "The root CA certificate in PEM format. Only root CA certificates are accepted; intermediate and leaf certificates are not supported." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + formatDryRun({ + command: "cf acm custom-trust-store create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/acm/custom_trust_store`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + certificate: resolveFileToken( + argv["certificate"] as string | undefined, + "certificate", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + certificate: resolveFileToken( + argv["certificate"] as string | undefined, + "certificate", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/acm/custom-trust-store/create.ts b/packages/cli/src/commands/_generated/acm/custom-trust-store/create.ts index 5c27a52675..2bb24dd756 100644 --- a/packages/cli/src/commands/_generated/acm/custom-trust-store/create.ts +++ b/packages/cli/src/commands/_generated/acm/custom-trust-store/create.ts @@ -1,122 +1,44 @@ -import operation from "../../_operations/acm/custom-trust-store/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/acm.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 acm custom-trust-store create\n\nUpload a root CA certificate to the Custom Origin Trust Store for a Zone. Only root CA certificates are accepted." - ) - .option("certificate", { - type: "string", - description: +const parameters = { + flags: { + certificate: { + kind: "parsed", + brief: "The root CA certificate in PEM format. Only root CA certificates are accepted; intermediate and leaf certificates are not supported.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Upload Custom Origin Trust Store", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "acm custom-trust-store create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["certificate"] === undefined) { - argv["certificate"] = await promptForRequiredField( - "certificate", - "The root CA certificate in PEM format. Only root CA certificates are accepted; intermediate and leaf certificates are not supported." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - formatDryRun({ - command: "cf acm custom-trust-store create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/acm/custom_trust_store`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - certificate: resolveFileToken( - argv["certificate"] as string | undefined, - "certificate", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - certificate: resolveFileToken( - argv["certificate"] as string | undefined, - "certificate", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 acm custom-trust-store create\n\nUpload a root CA certificate to the Custom Origin Trust Store for a Zone. Only root CA certificates are accepted.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/acm/custom-trust-store/delete.handler.ts b/packages/cli/src/commands/_generated/acm/custom-trust-store/delete.handler.ts new file mode 100644 index 0000000000..3ae79c0d62 --- /dev/null +++ b/packages/cli/src/commands/_generated/acm/custom-trust-store/delete.handler.ts @@ -0,0 +1,56 @@ +import operation from "../../_operations/acm/custom-trust-store/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "acm custom-trust-store delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf acm custom-trust-store delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/acm/custom_trust_store/${argv["custom-origin-trust-store-id"] == null ? "" : encodeURIComponent(String(argv["custom-origin-trust-store-id"]))}`, + pathParams: { + "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), + "custom-origin-trust-store-id": String( + argv["custom-origin-trust-store-id"] ?? "" + ), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + zone_id: zoneId, + custom_origin_trust_store_id: argv["custom-origin-trust-store-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/acm/custom-trust-store/delete.ts b/packages/cli/src/commands/_generated/acm/custom-trust-store/delete.ts index 3d13efc1d3..69425eebea 100644 --- a/packages/cli/src/commands/_generated/acm/custom-trust-store/delete.ts +++ b/packages/cli/src/commands/_generated/acm/custom-trust-store/delete.ts @@ -1,92 +1,43 @@ -import operation from "../../_operations/acm/custom-trust-store/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/acm.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 acm custom-trust-store delete \n\nRemoves a root CA certificate from the custom origin trust store. Origins using certificates signed by this CA will no longer be trusted." - ) - .positional("custom-origin-trust-store-id", { - type: "string", - description: "Certificate identifier tag.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "custom-origin-trust-store-id", + brief: "Certificate identifier tag.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete Custom Origin Trust Store", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "acm custom-trust-store delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf acm custom-trust-store delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/acm/custom_trust_store/${argv["custom-origin-trust-store-id"] == null ? "" : encodeURIComponent(String(argv["custom-origin-trust-store-id"]))}`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - "custom-origin-trust-store-id": String( - argv["custom-origin-trust-store-id"] ?? "" - ), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - zone_id: zoneId, - custom_origin_trust_store_id: argv["custom-origin-trust-store-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 acm custom-trust-store delete \n\nRemoves a root CA certificate from the custom origin trust store. Origins using certificates signed by this CA will no longer be trusted.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/acm/custom-trust-store/get.handler.ts b/packages/cli/src/commands/_generated/acm/custom-trust-store/get.handler.ts new file mode 100644 index 0000000000..a532da0ee4 --- /dev/null +++ b/packages/cli/src/commands/_generated/acm/custom-trust-store/get.handler.ts @@ -0,0 +1,50 @@ +import operation from "../../_operations/acm/custom-trust-store/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "acm custom-trust-store get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf acm custom-trust-store get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/acm/custom_trust_store/${argv["custom-origin-trust-store-id"] == null ? "" : encodeURIComponent(String(argv["custom-origin-trust-store-id"]))}`, + pathParams: { + "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), + "custom-origin-trust-store-id": String( + argv["custom-origin-trust-store-id"] ?? "" + ), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + zone_id: zoneId, + custom_origin_trust_store_id: argv["custom-origin-trust-store-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/acm/custom-trust-store/get.ts b/packages/cli/src/commands/_generated/acm/custom-trust-store/get.ts index 044b855ff1..b3cef4f542 100644 --- a/packages/cli/src/commands/_generated/acm/custom-trust-store/get.ts +++ b/packages/cli/src/commands/_generated/acm/custom-trust-store/get.ts @@ -1,80 +1,37 @@ -import operation from "../../_operations/acm/custom-trust-store/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/acm.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 acm custom-trust-store get \n\nRetrieves details about a specific root CA certificate in the custom origin trust store, including expiration and subject information." - ) - .positional("custom-origin-trust-store-id", { - type: "string", - description: "Certificate identifier tag.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "custom-origin-trust-store-id", + brief: "Certificate identifier tag.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Custom Origin Trust Store Details", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "acm custom-trust-store get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf acm custom-trust-store get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/acm/custom_trust_store/${argv["custom-origin-trust-store-id"] == null ? "" : encodeURIComponent(String(argv["custom-origin-trust-store-id"]))}`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - "custom-origin-trust-store-id": String( - argv["custom-origin-trust-store-id"] ?? "" - ), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - zone_id: zoneId, - custom_origin_trust_store_id: argv["custom-origin-trust-store-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 acm custom-trust-store get \n\nRetrieves details about a specific root CA certificate in the custom origin trust store, including expiration and subject information.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/acm/custom-trust-store/index.ts b/packages/cli/src/commands/_generated/acm/custom-trust-store/index.ts index 46d2dfebe8..406e4bd23b 100644 --- a/packages/cli/src/commands/_generated/acm/custom-trust-store/index.ts +++ b/packages/cli/src/commands/_generated/acm/custom-trust-store/index.ts @@ -2,27 +2,22 @@ import $create from "./create.js"; import $delete from "./delete.js"; import $get from "./get.js"; import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * custom-trust-store command group * @generated from apis/overlays/acm.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "custom-trust-store", describe: "Operations for custom-trust-store", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .command($list) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/acm/custom-trust-store/list.handler.ts b/packages/cli/src/commands/_generated/acm/custom-trust-store/list.handler.ts new file mode 100644 index 0000000000..239488c38c --- /dev/null +++ b/packages/cli/src/commands/_generated/acm/custom-trust-store/list.handler.ts @@ -0,0 +1,49 @@ +import operation from "../../_operations/acm/custom-trust-store/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "acm custom-trust-store list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + limit: argv["limit"], + offset: argv["offset"], + }; + if (argv.dryRun) { + formatDryRun({ + command: "cf acm custom-trust-store list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/acm/custom_trust_store`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { zone_id: zoneId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/acm/custom-trust-store/list.ts b/packages/cli/src/commands/_generated/acm/custom-trust-store/list.ts index 24e826a6a3..5fdfad0398 100644 --- a/packages/cli/src/commands/_generated/acm/custom-trust-store/list.ts +++ b/packages/cli/src/commands/_generated/acm/custom-trust-store/list.ts @@ -1,89 +1,55 @@ -import operation from "../../_operations/acm/custom-trust-store/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/acm.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 acm custom-trust-store list\n\nGet Custom Origin Trust Store for a Zone." - ) - .option("page", { - type: "number", - description: "Page number of paginated results.", - }) - .option("per-page", { - type: "number", - description: "Number of records per page.", - }) - .option("limit", { - type: "number", - description: "Limit to the number of records returned.", - }) - .option("offset", { type: "number", description: "Offset the results." }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + page: { + kind: "parsed", + brief: "Page number of paginated results.", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Number of records per page.", + optional: true, + parse: Number, + }, + limit: { + kind: "parsed", + brief: "Limit to the number of records returned.", + optional: true, + parse: Number, + }, + offset: { + kind: "parsed", + brief: "Offset the results.", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Custom Origin Trust Store Details", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "acm custom-trust-store list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - limit: argv["limit"], - offset: argv["offset"], - }; - if (argv.dryRun) { - formatDryRun({ - command: "cf acm custom-trust-store list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/acm/custom_trust_store`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { zone_id: zoneId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 acm custom-trust-store list\n\nGet Custom Origin Trust Store for a Zone.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/acm/index.ts b/packages/cli/src/commands/_generated/acm/index.ts index d8b6d9fbb3..c848664093 100644 --- a/packages/cli/src/commands/_generated/acm/index.ts +++ b/packages/cli/src/commands/_generated/acm/index.ts @@ -1,24 +1,19 @@ import $customtruststore from "./custom-trust-store/index.js"; import $totaltls from "./total-tls/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * acm command * @generated from apis/overlays/acm.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "acm", describe: "acm", - builder: (yargs) => { - return yargs - .command($customtruststore) - .command($totaltls) - .demandCommand(1, "Please specify a subcommand"); + routes: { + "custom-trust-store": $customtruststore, + "total-tls": $totaltls, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/acm/total-tls/edit.handler.ts b/packages/cli/src/commands/_generated/acm/total-tls/edit.handler.ts new file mode 100644 index 0000000000..69692b6f03 --- /dev/null +++ b/packages/cli/src/commands/_generated/acm/total-tls/edit.handler.ts @@ -0,0 +1,77 @@ +import operation from "../../_operations/acm/total-tls/edit.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./edit.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "acm total-tls edit", + classification: { + safeFlags: ["certificate-authority", "enabled", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["enabled"] === undefined) { + throw new Error( + "--enabled is required (or pass --body with this field set)." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + formatDryRun({ + command: "cf acm total-tls edit", + method: "POST", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/acm/total_tls`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + certificate_authority: argv["certificate-authority"], + enabled: argv["enabled"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + certificate_authority: argv["certificate-authority"], + enabled: argv["enabled"], + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/acm/total-tls/edit.ts b/packages/cli/src/commands/_generated/acm/total-tls/edit.ts index ee6a28ade6..879df7bafe 100644 --- a/packages/cli/src/commands/_generated/acm/total-tls/edit.ts +++ b/packages/cli/src/commands/_generated/acm/total-tls/edit.ts @@ -1,123 +1,54 @@ -import operation from "../../_operations/acm/total-tls/edit.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * edit command * @generated from apis/overlays/acm.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 acm total-tls edit\n\nSet Total TLS Settings or disable the feature for a Zone." - ) - .option("certificate-authority", { - type: "string", - description: +const parameters = { + flags: { + "certificate-authority": { + kind: "parsed", + brief: "The Certificate Authority that Total TLS certificates will be issued through. Not returned in responses when Total TLS is disabled.", + optional: true, choices: ["google", "lets_encrypt", "ssl_com"], - }) - .coerce("certificate-authority", (value) => - resolveFileToken(value, "certificate-authority", "text") - ) - .option("enabled", { - type: "boolean", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "certificate-authority", "text"), + }, + enabled: { + kind: "boolean", + brief: "If enabled, Total TLS will order a hostname specific TLS certificate for any proxied A, AAAA, or CNAME record in your zone.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "edit", describe: "Enable or Disable Total TLS", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "acm total-tls edit", - classification: { - safeFlags: ["certificate-authority", "enabled", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["enabled"] === undefined) { - throw new Error( - "--enabled is required (or pass --body with this field set)." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - formatDryRun({ - command: "cf acm total-tls edit", - method: "POST", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/acm/total_tls`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - certificate_authority: argv["certificate-authority"], - enabled: argv["enabled"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - certificate_authority: argv["certificate-authority"], - enabled: argv["enabled"], - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 acm total-tls edit\n\nSet Total TLS Settings or disable the feature for a Zone.", + ...parameters, + loader: () => import("./edit.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/acm/total-tls/get.handler.ts b/packages/cli/src/commands/_generated/acm/total-tls/get.handler.ts new file mode 100644 index 0000000000..c7c1f265bc --- /dev/null +++ b/packages/cli/src/commands/_generated/acm/total-tls/get.handler.ts @@ -0,0 +1,42 @@ +import operation from "../../_operations/acm/total-tls/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "acm total-tls get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf acm total-tls get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/acm/total_tls`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/acm/total-tls/get.ts b/packages/cli/src/commands/_generated/acm/total-tls/get.ts index b342c0c7a5..7607552cd4 100644 --- a/packages/cli/src/commands/_generated/acm/total-tls/get.ts +++ b/packages/cli/src/commands/_generated/acm/total-tls/get.ts @@ -1,67 +1,30 @@ -import operation from "../../_operations/acm/total-tls/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/acm.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage("$0 acm total-tls get\n\nGet Total TLS Settings for a Zone.") - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "Total TLS Settings Details", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "acm total-tls get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf acm total-tls get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/acm/total_tls`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: "$0 acm total-tls get\n\nGet Total TLS Settings for a Zone.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/acm/total-tls/index.ts b/packages/cli/src/commands/_generated/acm/total-tls/index.ts index c264bed62b..7367485e15 100644 --- a/packages/cli/src/commands/_generated/acm/total-tls/index.ts +++ b/packages/cli/src/commands/_generated/acm/total-tls/index.ts @@ -1,24 +1,19 @@ import $edit from "./edit.js"; import $get from "./get.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * total-tls command group * @generated from apis/overlays/acm.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "total-tls", describe: "Operations for total-tls", - builder: (yargs) => { - return yargs - .command($edit) - .command($get) - .demandCommand(1, "Please specify a subcommand"); + routes: { + edit: $edit, + get: $get, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/accounts/create.handler.ts b/packages/cli/src/commands/_generated/addressing/address-maps/accounts/create.handler.ts new file mode 100644 index 0000000000..dc96716da3 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/address-maps/accounts/create.handler.ts @@ -0,0 +1,53 @@ +import operation from "../../../_operations/addressing/address-maps/accounts/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing address-maps accounts create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing address-maps accounts create", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}/accounts/${argv["member-account-id"] == null ? "" : encodeURIComponent(String(argv["member-account-id"]))}`, + pathParams: { + "address-map-id": String(argv["address-map-id"] ?? ""), + "member-account-id": String(argv["member-account-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Updating`, async () => + client.send(operation, { + account_id: accountId, + address_map_id: argv["address-map-id"], + member_account_id: argv["member-account-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/accounts/create.ts b/packages/cli/src/commands/_generated/addressing/address-maps/accounts/create.ts index baf86470fd..0486540614 100644 --- a/packages/cli/src/commands/_generated/addressing/address-maps/accounts/create.ts +++ b/packages/cli/src/commands/_generated/addressing/address-maps/accounts/create.ts @@ -1,88 +1,42 @@ -import operation from "../../../_operations/addressing/address-maps/accounts/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing address-maps accounts create \n\nAdd an account as a member of a particular address map." - ) - .positional("member-account-id", { - type: "string", - description: "Identifier of a Cloudflare account.", - demandOption: true, - }) - .option("address-map-id", { - type: "string", - description: "Identifier of an Address Map.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "address-map-id": { + kind: "parsed", + brief: "Identifier of an Address Map.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "member-account-id", + brief: "Identifier of a Cloudflare account.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Add an account membership to an Address Map", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing address-maps accounts create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing address-maps accounts create", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}/accounts/${argv["member-account-id"] == null ? "" : encodeURIComponent(String(argv["member-account-id"]))}`, - pathParams: { - "address-map-id": String(argv["address-map-id"] ?? ""), - "member-account-id": String(argv["member-account-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Updating`, async () => - client.send(operation, { - account_id: accountId, - address_map_id: argv["address-map-id"], - member_account_id: argv["member-account-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 addressing address-maps accounts create \n\nAdd an account as a member of a particular address map.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/accounts/delete.handler.ts b/packages/cli/src/commands/_generated/addressing/address-maps/accounts/delete.handler.ts new file mode 100644 index 0000000000..7c41ae53a0 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/address-maps/accounts/delete.handler.ts @@ -0,0 +1,59 @@ +import operation from "../../../_operations/addressing/address-maps/accounts/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing address-maps accounts delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing address-maps accounts delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}/accounts/${argv["member-account-id"] == null ? "" : encodeURIComponent(String(argv["member-account-id"]))}`, + pathParams: { + "address-map-id": String(argv["address-map-id"] ?? ""), + "member-account-id": String(argv["member-account-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + address_map_id: argv["address-map-id"], + member_account_id: argv["member-account-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/accounts/delete.ts b/packages/cli/src/commands/_generated/addressing/address-maps/accounts/delete.ts index f15dace858..8893f839b9 100644 --- a/packages/cli/src/commands/_generated/addressing/address-maps/accounts/delete.ts +++ b/packages/cli/src/commands/_generated/addressing/address-maps/accounts/delete.ts @@ -1,100 +1,48 @@ -import operation from "../../../_operations/addressing/address-maps/accounts/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing address-maps accounts delete \n\nRemove an account as a member of a particular address map." - ) - .positional("member-account-id", { - type: "string", - description: "Identifier of a Cloudflare account.", - demandOption: true, - }) - .option("address-map-id", { - type: "string", - description: "Identifier of an Address Map.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "address-map-id": { + kind: "parsed", + brief: "Identifier of an Address Map.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "member-account-id", + brief: "Identifier of a Cloudflare account.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Remove an account membership from an Address Map", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing address-maps accounts delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing address-maps accounts delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}/accounts/${argv["member-account-id"] == null ? "" : encodeURIComponent(String(argv["member-account-id"]))}`, - pathParams: { - "address-map-id": String(argv["address-map-id"] ?? ""), - "member-account-id": String(argv["member-account-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - address_map_id: argv["address-map-id"], - member_account_id: argv["member-account-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 addressing address-maps accounts delete \n\nRemove an account as a member of a particular address map.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/accounts/index.ts b/packages/cli/src/commands/_generated/addressing/address-maps/accounts/index.ts index 76096b0378..974f25e45f 100644 --- a/packages/cli/src/commands/_generated/addressing/address-maps/accounts/index.ts +++ b/packages/cli/src/commands/_generated/addressing/address-maps/accounts/index.ts @@ -1,24 +1,19 @@ import $create from "./create.js"; import $delete from "./delete.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * accounts command group * @generated from apis/overlays/addressing.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "accounts", describe: "Operations for address-maps.accounts", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/create.handler.ts b/packages/cli/src/commands/_generated/addressing/address-maps/create.handler.ts new file mode 100644 index 0000000000..2318c74c71 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/address-maps/create.handler.ts @@ -0,0 +1,86 @@ +import operation from "../../_operations/addressing/address-maps/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing address-maps create", + classification: { + safeFlags: ["enabled", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing address-maps create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + enabled: argv["enabled"], + ips: argv["ips"], + memberships: parseObjectArray( + argv["memberships"], + "memberships" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + enabled: argv["enabled"], + ips: argv["ips"], + memberships: parseObjectArray(argv["memberships"], "memberships"), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/create.ts b/packages/cli/src/commands/_generated/addressing/address-maps/create.ts index eaa7528113..975928fa65 100644 --- a/packages/cli/src/commands/_generated/addressing/address-maps/create.ts +++ b/packages/cli/src/commands/_generated/addressing/address-maps/create.ts @@ -1,136 +1,64 @@ -import operation from "../../_operations/addressing/address-maps/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing address-maps create\n\nCreate a new address map under the account." - ) - .option("description", { - type: "string", - description: +const parameters = { + flags: { + description: { + kind: "parsed", + brief: "An optional description field which may be used to describe the types of IPs or zones on the map.", - }) - .option("enabled", { - type: "boolean", - description: + optional: true, + parse: String, + }, + enabled: { + kind: "boolean", + brief: "Whether the Address Map is enabled or not. Cloudflare's DNS will not respond with IP addresses on an Address Map until the map is enabled.", default: false, - }) - .option("ips", { - type: "string", - array: true, - description: "The ips field", - }) - .option("memberships", { - type: "string", - description: + }, + ips: { + kind: "parsed", + brief: "The ips field", + variadic: true, + optional: true, + parse: String, + }, + memberships: { + kind: "parsed", + brief: 'Zones and Accounts which will be assigned IPs on this Address Map. A zone membership will take priority over an account membership. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"identifier"?: string, "kind"?: "zone" | "account"}]. ? marks optional keys.', - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Create Address Map", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing address-maps create", - classification: { - safeFlags: ["enabled", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing address-maps create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - enabled: argv["enabled"], - ips: argv["ips"], - memberships: parseObjectArray( - argv["memberships"], - "memberships" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - enabled: argv["enabled"], - ips: argv["ips"], - memberships: parseObjectArray(argv["memberships"], "memberships"), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 addressing address-maps create\n\nCreate a new address map under the account.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/delete.handler.ts b/packages/cli/src/commands/_generated/addressing/address-maps/delete.handler.ts new file mode 100644 index 0000000000..96faae9c20 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/address-maps/delete.handler.ts @@ -0,0 +1,57 @@ +import operation from "../../_operations/addressing/address-maps/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing address-maps delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing address-maps delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}`, + pathParams: { + "address-map-id": String(argv["address-map-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + address_map_id: argv["address-map-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/delete.ts b/packages/cli/src/commands/_generated/addressing/address-maps/delete.ts index 4f56d9d60b..3ab49b6735 100644 --- a/packages/cli/src/commands/_generated/addressing/address-maps/delete.ts +++ b/packages/cli/src/commands/_generated/addressing/address-maps/delete.ts @@ -1,93 +1,43 @@ -import operation from "../../_operations/addressing/address-maps/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing address-maps delete \n\nDelete a particular address map owned by the account. An Address Map must be disabled before it can be deleted." - ) - .positional("address-map-id", { - type: "string", - description: "Identifier of an Address Map.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "address-map-id", + brief: "Identifier of an Address Map.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete Address Map", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing address-maps delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing address-maps delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}`, - pathParams: { - "address-map-id": String(argv["address-map-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - address_map_id: argv["address-map-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 addressing address-maps delete \n\nDelete a particular address map owned by the account. An Address Map must be disabled before it can be deleted.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/edit.handler.ts b/packages/cli/src/commands/_generated/addressing/address-maps/edit.handler.ts new file mode 100644 index 0000000000..ce032d664c --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/address-maps/edit.handler.ts @@ -0,0 +1,99 @@ +import operation from "../../_operations/addressing/address-maps/edit.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./edit.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing address-maps edit", + classification: { + safeFlags: ["enabled", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing address-maps edit", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}`, + pathParams: { + "address-map-id": String(argv["address-map-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + default_sni: resolveFileToken( + argv["default-sni"] as string | undefined, + "default-sni", + "text" + ), + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + enabled: argv["enabled"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + address_map_id: argv["address-map-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + default_sni: resolveFileToken( + argv["default-sni"] as string | undefined, + "default-sni", + "text" + ), + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + enabled: argv["enabled"], + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + address_map_id: argv["address-map-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/edit.ts b/packages/cli/src/commands/_generated/addressing/address-maps/edit.ts index fc52828d9b..7878697df8 100644 --- a/packages/cli/src/commands/_generated/addressing/address-maps/edit.ts +++ b/packages/cli/src/commands/_generated/addressing/address-maps/edit.ts @@ -1,148 +1,63 @@ -import operation from "../../_operations/addressing/address-maps/edit.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * edit command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing address-maps edit \n\nModify properties of an address map owned by the account." - ) - .positional("address-map-id", { - type: "string", - description: "Identifier of an Address Map.", - demandOption: true, - }) - .option("default-sni", { - type: "string", - description: +const parameters = { + flags: { + "default-sni": { + kind: "parsed", + brief: "If you have legacy TLS clients which do not send the TLS server name indicator, then you can specify one default SNI on the map. If Cloudflare receives a TLS handshake from a client without an SNI, it will respond with the default SNI on those IPs. The default SNI can be any valid zone or subdomain owned by the account.", - }) - .option("description", { - type: "string", - description: + optional: true, + parse: String, + }, + description: { + kind: "parsed", + brief: "An optional description field which may be used to describe the types of IPs or zones on the map.", - }) - .option("enabled", { - type: "boolean", - description: + optional: true, + parse: String, + }, + enabled: { + kind: "boolean", + brief: "Whether the Address Map is enabled or not. Cloudflare's DNS will not respond with IP addresses on an Address Map until the map is enabled.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "address-map-id", + brief: "Identifier of an Address Map.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "edit ", describe: "Update Address Map", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing address-maps edit", - classification: { - safeFlags: ["enabled", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing address-maps edit", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}`, - pathParams: { - "address-map-id": String(argv["address-map-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - default_sni: resolveFileToken( - argv["default-sni"] as string | undefined, - "default-sni", - "text" - ), - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - enabled: argv["enabled"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - address_map_id: argv["address-map-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - default_sni: resolveFileToken( - argv["default-sni"] as string | undefined, - "default-sni", - "text" - ), - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - enabled: argv["enabled"], - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - address_map_id: argv["address-map-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 addressing address-maps edit \n\nModify properties of an address map owned by the account.", + ...parameters, + loader: () => import("./edit.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/get.handler.ts b/packages/cli/src/commands/_generated/addressing/address-maps/get.handler.ts new file mode 100644 index 0000000000..ad52d26290 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/address-maps/get.handler.ts @@ -0,0 +1,51 @@ +import operation from "../../_operations/addressing/address-maps/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing address-maps get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing address-maps get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}`, + pathParams: { + "address-map-id": String(argv["address-map-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + address_map_id: argv["address-map-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/get.ts b/packages/cli/src/commands/_generated/addressing/address-maps/get.ts index dda3be7873..6ccf758d7a 100644 --- a/packages/cli/src/commands/_generated/addressing/address-maps/get.ts +++ b/packages/cli/src/commands/_generated/addressing/address-maps/get.ts @@ -1,81 +1,37 @@ -import operation from "../../_operations/addressing/address-maps/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing address-maps get \n\nShow a particular address map owned by the account." - ) - .positional("address-map-id", { - type: "string", - description: "Identifier of an Address Map.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "address-map-id", + brief: "Identifier of an Address Map.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Address Map Details", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing address-maps get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing address-maps get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}`, - pathParams: { - "address-map-id": String(argv["address-map-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - address_map_id: argv["address-map-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 addressing address-maps get \n\nShow a particular address map owned by the account.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/index.ts b/packages/cli/src/commands/_generated/addressing/address-maps/index.ts index f0b9930c38..9a31195b38 100644 --- a/packages/cli/src/commands/_generated/addressing/address-maps/index.ts +++ b/packages/cli/src/commands/_generated/addressing/address-maps/index.ts @@ -6,31 +6,26 @@ import $get from "./get.js"; import $ips from "./ips/index.js"; import $list from "./list.js"; import $zones from "./zones/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * address-maps command group * @generated from apis/overlays/addressing.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "address-maps", describe: "Operations for address-maps", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($edit) - .command($get) - .command($list) - .command($accounts) - .command($ips) - .command($zones) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + edit: $edit, + get: $get, + list: $list, + accounts: $accounts, + ips: $ips, + zones: $zones, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/ips/bulk-create.handler.ts b/packages/cli/src/commands/_generated/addressing/address-maps/ips/bulk-create.handler.ts new file mode 100644 index 0000000000..12d2c7aa68 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/address-maps/ips/bulk-create.handler.ts @@ -0,0 +1,89 @@ +import operation from "../../../_operations/addressing/address-maps/ips/bulk-create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./bulk-create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing address-maps ips bulk-create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["ips"] === undefined) { + throw new Error( + "--ips is required (or pass --body with this field set)." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing address-maps ips bulk-create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}/ips`, + pathParams: { + "address-map-id": String(argv["address-map-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + ips: argv["ips"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + address_map_id: argv["address-map-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + ips: argv["ips"], + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + address_map_id: argv["address-map-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/ips/bulk-create.ts b/packages/cli/src/commands/_generated/addressing/address-maps/ips/bulk-create.ts index ddcaa10491..f853829514 100644 --- a/packages/cli/src/commands/_generated/addressing/address-maps/ips/bulk-create.ts +++ b/packages/cli/src/commands/_generated/addressing/address-maps/ips/bulk-create.ts @@ -1,128 +1,49 @@ -import operation from "../../../_operations/addressing/address-maps/ips/bulk-create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * bulk-create command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing address-maps ips bulk-create\n\nAdd multiple IPs to a particular address map." - ) - .option("address-map-id", { - type: "string", - description: "Identifier of an Address Map.", - demandOption: true, - }) - .option("ips", { - type: "string", - array: true, - description: "The ips field", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "address-map-id": { + kind: "parsed", + brief: "Identifier of an Address Map.", + parse: String, + }, + ips: { + kind: "parsed", + brief: "The ips field", + variadic: true, + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "bulk-create", describe: "Add Multiple IPs to an Address Map", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing address-maps ips bulk-create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["ips"] === undefined) { - throw new Error( - "--ips is required (or pass --body with this field set)." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing address-maps ips bulk-create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}/ips`, - pathParams: { - "address-map-id": String(argv["address-map-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - ips: argv["ips"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - address_map_id: argv["address-map-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - ips: argv["ips"], - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - address_map_id: argv["address-map-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 addressing address-maps ips bulk-create\n\nAdd multiple IPs to a particular address map.", + ...parameters, + loader: () => import("./bulk-create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/ips/bulk-delete.handler.ts b/packages/cli/src/commands/_generated/addressing/address-maps/ips/bulk-delete.handler.ts new file mode 100644 index 0000000000..a39a80cb56 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/address-maps/ips/bulk-delete.handler.ts @@ -0,0 +1,95 @@ +import operation from "../../../_operations/addressing/address-maps/ips/bulk-delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./bulk-delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing address-maps ips bulk-delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["ips"] === undefined) { + throw new Error( + "--ips is required (or pass --body with this field set)." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing address-maps ips bulk-delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}/ips`, + pathParams: { + "address-map-id": String(argv["address-map-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + ips: argv["ips"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + address_map_id: argv["address-map-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + ips: argv["ips"], + }); + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + address_map_id: argv["address-map-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/ips/bulk-delete.ts b/packages/cli/src/commands/_generated/addressing/address-maps/ips/bulk-delete.ts index 1020cfd49e..608bb0e503 100644 --- a/packages/cli/src/commands/_generated/addressing/address-maps/ips/bulk-delete.ts +++ b/packages/cli/src/commands/_generated/addressing/address-maps/ips/bulk-delete.ts @@ -1,140 +1,55 @@ -import operation from "../../../_operations/addressing/address-maps/ips/bulk-delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * bulk-delete command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing address-maps ips bulk-delete\n\nRemove multiple IPs from a particular address map." - ) - .option("address-map-id", { - type: "string", - description: "Identifier of an Address Map.", - demandOption: true, - }) - .option("ips", { - type: "string", - array: true, - description: "The ips field", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "address-map-id": { + kind: "parsed", + brief: "Identifier of an Address Map.", + parse: String, + }, + ips: { + kind: "parsed", + brief: "The ips field", + variadic: true, + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "bulk-delete", describe: "Remove Multiple IPs from an Address Map", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing address-maps ips bulk-delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["ips"] === undefined) { - throw new Error( - "--ips is required (or pass --body with this field set)." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing address-maps ips bulk-delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}/ips`, - pathParams: { - "address-map-id": String(argv["address-map-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - ips: argv["ips"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - address_map_id: argv["address-map-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - ips: argv["ips"], - }); - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - address_map_id: argv["address-map-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 addressing address-maps ips bulk-delete\n\nRemove multiple IPs from a particular address map.", + ...parameters, + loader: () => import("./bulk-delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/ips/create.handler.ts b/packages/cli/src/commands/_generated/addressing/address-maps/ips/create.handler.ts new file mode 100644 index 0000000000..accf239c22 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/address-maps/ips/create.handler.ts @@ -0,0 +1,53 @@ +import operation from "../../../_operations/addressing/address-maps/ips/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing address-maps ips create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing address-maps ips create", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}/ips/${argv["ip-address"] == null ? "" : encodeURIComponent(String(argv["ip-address"]))}`, + pathParams: { + "address-map-id": String(argv["address-map-id"] ?? ""), + "ip-address": String(argv["ip-address"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Updating`, async () => + client.send(operation, { + account_id: accountId, + address_map_id: argv["address-map-id"], + ip_address: argv["ip-address"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/ips/create.ts b/packages/cli/src/commands/_generated/addressing/address-maps/ips/create.ts index cd6d110455..b69a105f4e 100644 --- a/packages/cli/src/commands/_generated/addressing/address-maps/ips/create.ts +++ b/packages/cli/src/commands/_generated/addressing/address-maps/ips/create.ts @@ -1,88 +1,42 @@ -import operation from "../../../_operations/addressing/address-maps/ips/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing address-maps ips create \n\nAdd an IP from a prefix owned by the account to a particular address map." - ) - .positional("ip-address", { - type: "string", - description: "An IPv4 or IPv6 address.", - demandOption: true, - }) - .option("address-map-id", { - type: "string", - description: "Identifier of an Address Map.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "address-map-id": { + kind: "parsed", + brief: "Identifier of an Address Map.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "ip-address", + brief: "An IPv4 or IPv6 address.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Add an IP to an Address Map", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing address-maps ips create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing address-maps ips create", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}/ips/${argv["ip-address"] == null ? "" : encodeURIComponent(String(argv["ip-address"]))}`, - pathParams: { - "address-map-id": String(argv["address-map-id"] ?? ""), - "ip-address": String(argv["ip-address"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Updating`, async () => - client.send(operation, { - account_id: accountId, - address_map_id: argv["address-map-id"], - ip_address: argv["ip-address"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 addressing address-maps ips create \n\nAdd an IP from a prefix owned by the account to a particular address map.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/ips/delete.handler.ts b/packages/cli/src/commands/_generated/addressing/address-maps/ips/delete.handler.ts new file mode 100644 index 0000000000..06d8b870c7 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/address-maps/ips/delete.handler.ts @@ -0,0 +1,59 @@ +import operation from "../../../_operations/addressing/address-maps/ips/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing address-maps ips delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing address-maps ips delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}/ips/${argv["ip-address"] == null ? "" : encodeURIComponent(String(argv["ip-address"]))}`, + pathParams: { + "address-map-id": String(argv["address-map-id"] ?? ""), + "ip-address": String(argv["ip-address"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + address_map_id: argv["address-map-id"], + ip_address: argv["ip-address"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/ips/delete.ts b/packages/cli/src/commands/_generated/addressing/address-maps/ips/delete.ts index 7fea83c550..6ac8f9f04b 100644 --- a/packages/cli/src/commands/_generated/addressing/address-maps/ips/delete.ts +++ b/packages/cli/src/commands/_generated/addressing/address-maps/ips/delete.ts @@ -1,100 +1,48 @@ -import operation from "../../../_operations/addressing/address-maps/ips/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing address-maps ips delete \n\nRemove an IP from a particular address map." - ) - .positional("ip-address", { - type: "string", - description: "An IPv4 or IPv6 address.", - demandOption: true, - }) - .option("address-map-id", { - type: "string", - description: "Identifier of an Address Map.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "address-map-id": { + kind: "parsed", + brief: "Identifier of an Address Map.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "ip-address", + brief: "An IPv4 or IPv6 address.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Remove an IP from an Address Map", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing address-maps ips delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing address-maps ips delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}/ips/${argv["ip-address"] == null ? "" : encodeURIComponent(String(argv["ip-address"]))}`, - pathParams: { - "address-map-id": String(argv["address-map-id"] ?? ""), - "ip-address": String(argv["ip-address"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - address_map_id: argv["address-map-id"], - ip_address: argv["ip-address"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 addressing address-maps ips delete \n\nRemove an IP from a particular address map.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/ips/index.ts b/packages/cli/src/commands/_generated/addressing/address-maps/ips/index.ts index e00d660272..0c0ec84a5f 100644 --- a/packages/cli/src/commands/_generated/addressing/address-maps/ips/index.ts +++ b/packages/cli/src/commands/_generated/addressing/address-maps/ips/index.ts @@ -2,27 +2,22 @@ import $bulkcreate from "./bulk-create.js"; import $bulkdelete from "./bulk-delete.js"; import $create from "./create.js"; import $delete from "./delete.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * ips command group * @generated from apis/overlays/addressing.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "ips", describe: "Operations for address-maps.ips", - builder: (yargs) => { - return yargs - .command($bulkcreate) - .command($bulkdelete) - .command($create) - .command($delete) - .demandCommand(1, "Please specify a subcommand"); + routes: { + "bulk-create": $bulkcreate, + "bulk-delete": $bulkdelete, + create: $create, + delete: $delete, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/list.handler.ts b/packages/cli/src/commands/_generated/addressing/address-maps/list.handler.ts new file mode 100644 index 0000000000..8d6b906ab4 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/address-maps/list.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/addressing/address-maps/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing address-maps list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing address-maps list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/list.ts b/packages/cli/src/commands/_generated/addressing/address-maps/list.ts index ee9ea6010d..ab4f7f8d22 100644 --- a/packages/cli/src/commands/_generated/addressing/address-maps/list.ts +++ b/packages/cli/src/commands/_generated/addressing/address-maps/list.ts @@ -1,71 +1,31 @@ -import operation from "../../_operations/addressing/address-maps/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing address-maps list\n\nList all address maps owned by the account." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Address Maps", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing address-maps list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing address-maps list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 addressing address-maps list\n\nList all address maps owned by the account.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/zones/bulk-create.handler.ts b/packages/cli/src/commands/_generated/addressing/address-maps/zones/bulk-create.handler.ts new file mode 100644 index 0000000000..028beaee33 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/address-maps/zones/bulk-create.handler.ts @@ -0,0 +1,89 @@ +import operation from "../../../_operations/addressing/address-maps/zones/bulk-create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./bulk-create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing address-maps zones bulk-create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["zones"] === undefined) { + throw new Error( + "--zones is required (or pass --body with this field set)." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing address-maps zones bulk-create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}/zones`, + pathParams: { + "address-map-id": String(argv["address-map-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + zones: argv["zones"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + address_map_id: argv["address-map-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + zones: argv["zones"], + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + address_map_id: argv["address-map-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/zones/bulk-create.ts b/packages/cli/src/commands/_generated/addressing/address-maps/zones/bulk-create.ts index 23a40d4432..620adcd70a 100644 --- a/packages/cli/src/commands/_generated/addressing/address-maps/zones/bulk-create.ts +++ b/packages/cli/src/commands/_generated/addressing/address-maps/zones/bulk-create.ts @@ -1,128 +1,49 @@ -import operation from "../../../_operations/addressing/address-maps/zones/bulk-create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * bulk-create command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing address-maps zones bulk-create\n\nAdd multiple zones as members of a particular address map." - ) - .option("address-map-id", { - type: "string", - description: "Identifier of an Address Map.", - demandOption: true, - }) - .option("zones", { - type: "string", - array: true, - description: "The zones field", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "address-map-id": { + kind: "parsed", + brief: "Identifier of an Address Map.", + parse: String, + }, + zones: { + kind: "parsed", + brief: "The zones field", + variadic: true, + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "bulk-create", describe: "Add Multiple Zones to an Address Map", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing address-maps zones bulk-create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["zones"] === undefined) { - throw new Error( - "--zones is required (or pass --body with this field set)." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing address-maps zones bulk-create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}/zones`, - pathParams: { - "address-map-id": String(argv["address-map-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - zones: argv["zones"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - address_map_id: argv["address-map-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - zones: argv["zones"], - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - address_map_id: argv["address-map-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 addressing address-maps zones bulk-create\n\nAdd multiple zones as members of a particular address map.", + ...parameters, + loader: () => import("./bulk-create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/zones/bulk-delete.handler.ts b/packages/cli/src/commands/_generated/addressing/address-maps/zones/bulk-delete.handler.ts new file mode 100644 index 0000000000..26b43402ea --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/address-maps/zones/bulk-delete.handler.ts @@ -0,0 +1,95 @@ +import operation from "../../../_operations/addressing/address-maps/zones/bulk-delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./bulk-delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing address-maps zones bulk-delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["zones"] === undefined) { + throw new Error( + "--zones is required (or pass --body with this field set)." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing address-maps zones bulk-delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}/zones`, + pathParams: { + "address-map-id": String(argv["address-map-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + zones: argv["zones"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + address_map_id: argv["address-map-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + zones: argv["zones"], + }); + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + address_map_id: argv["address-map-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/zones/bulk-delete.ts b/packages/cli/src/commands/_generated/addressing/address-maps/zones/bulk-delete.ts index 8e1d8303f1..b7985c3888 100644 --- a/packages/cli/src/commands/_generated/addressing/address-maps/zones/bulk-delete.ts +++ b/packages/cli/src/commands/_generated/addressing/address-maps/zones/bulk-delete.ts @@ -1,140 +1,55 @@ -import operation from "../../../_operations/addressing/address-maps/zones/bulk-delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * bulk-delete command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing address-maps zones bulk-delete\n\nRemove multiple zones as members of a particular address map." - ) - .option("address-map-id", { - type: "string", - description: "Identifier of an Address Map.", - demandOption: true, - }) - .option("zones", { - type: "string", - array: true, - description: "The zones field", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "address-map-id": { + kind: "parsed", + brief: "Identifier of an Address Map.", + parse: String, + }, + zones: { + kind: "parsed", + brief: "The zones field", + variadic: true, + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "bulk-delete", describe: "Remove Multiple Zones from an Address Map", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing address-maps zones bulk-delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["zones"] === undefined) { - throw new Error( - "--zones is required (or pass --body with this field set)." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing address-maps zones bulk-delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}/zones`, - pathParams: { - "address-map-id": String(argv["address-map-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - zones: argv["zones"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - address_map_id: argv["address-map-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - zones: argv["zones"], - }); - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - address_map_id: argv["address-map-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 addressing address-maps zones bulk-delete\n\nRemove multiple zones as members of a particular address map.", + ...parameters, + loader: () => import("./bulk-delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/zones/create.handler.ts b/packages/cli/src/commands/_generated/addressing/address-maps/zones/create.handler.ts new file mode 100644 index 0000000000..84a511a731 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/address-maps/zones/create.handler.ts @@ -0,0 +1,53 @@ +import operation from "../../../_operations/addressing/address-maps/zones/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing address-maps zones create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing address-maps zones create", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}/zones/${argv["member-zone-id"] == null ? "" : encodeURIComponent(String(argv["member-zone-id"]))}`, + pathParams: { + "address-map-id": String(argv["address-map-id"] ?? ""), + "member-zone-id": String(argv["member-zone-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Updating`, async () => + client.send(operation, { + account_id: accountId, + address_map_id: argv["address-map-id"], + member_zone_id: argv["member-zone-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/zones/create.ts b/packages/cli/src/commands/_generated/addressing/address-maps/zones/create.ts index 83150b733d..693fc270d8 100644 --- a/packages/cli/src/commands/_generated/addressing/address-maps/zones/create.ts +++ b/packages/cli/src/commands/_generated/addressing/address-maps/zones/create.ts @@ -1,88 +1,42 @@ -import operation from "../../../_operations/addressing/address-maps/zones/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing address-maps zones create \n\nAdd a zone as a member of a particular address map." - ) - .positional("member-zone-id", { - type: "string", - description: "Identifier of a zone.", - demandOption: true, - }) - .option("address-map-id", { - type: "string", - description: "Identifier of an Address Map.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "address-map-id": { + kind: "parsed", + brief: "Identifier of an Address Map.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "member-zone-id", + brief: "Identifier of a zone.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Add a zone membership to an Address Map", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing address-maps zones create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing address-maps zones create", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}/zones/${argv["member-zone-id"] == null ? "" : encodeURIComponent(String(argv["member-zone-id"]))}`, - pathParams: { - "address-map-id": String(argv["address-map-id"] ?? ""), - "member-zone-id": String(argv["member-zone-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Updating`, async () => - client.send(operation, { - account_id: accountId, - address_map_id: argv["address-map-id"], - member_zone_id: argv["member-zone-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 addressing address-maps zones create \n\nAdd a zone as a member of a particular address map.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/zones/delete.handler.ts b/packages/cli/src/commands/_generated/addressing/address-maps/zones/delete.handler.ts new file mode 100644 index 0000000000..a277323b28 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/address-maps/zones/delete.handler.ts @@ -0,0 +1,59 @@ +import operation from "../../../_operations/addressing/address-maps/zones/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing address-maps zones delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing address-maps zones delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}/zones/${argv["member-zone-id"] == null ? "" : encodeURIComponent(String(argv["member-zone-id"]))}`, + pathParams: { + "address-map-id": String(argv["address-map-id"] ?? ""), + "member-zone-id": String(argv["member-zone-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + address_map_id: argv["address-map-id"], + member_zone_id: argv["member-zone-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/zones/delete.ts b/packages/cli/src/commands/_generated/addressing/address-maps/zones/delete.ts index 13913aa65e..aa2aa2c9a6 100644 --- a/packages/cli/src/commands/_generated/addressing/address-maps/zones/delete.ts +++ b/packages/cli/src/commands/_generated/addressing/address-maps/zones/delete.ts @@ -1,100 +1,48 @@ -import operation from "../../../_operations/addressing/address-maps/zones/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing address-maps zones delete \n\nRemove a zone as a member of a particular address map." - ) - .positional("member-zone-id", { - type: "string", - description: "Identifier of a zone.", - demandOption: true, - }) - .option("address-map-id", { - type: "string", - description: "Identifier of an Address Map.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "address-map-id": { + kind: "parsed", + brief: "Identifier of an Address Map.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "member-zone-id", + brief: "Identifier of a zone.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Remove a zone membership from an Address Map", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing address-maps zones delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing address-maps zones delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/address_maps/${argv["address-map-id"] == null ? "" : encodeURIComponent(String(argv["address-map-id"]))}/zones/${argv["member-zone-id"] == null ? "" : encodeURIComponent(String(argv["member-zone-id"]))}`, - pathParams: { - "address-map-id": String(argv["address-map-id"] ?? ""), - "member-zone-id": String(argv["member-zone-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - address_map_id: argv["address-map-id"], - member_zone_id: argv["member-zone-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 addressing address-maps zones delete \n\nRemove a zone as a member of a particular address map.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/address-maps/zones/index.ts b/packages/cli/src/commands/_generated/addressing/address-maps/zones/index.ts index f2ce46612d..12d73e8e4b 100644 --- a/packages/cli/src/commands/_generated/addressing/address-maps/zones/index.ts +++ b/packages/cli/src/commands/_generated/addressing/address-maps/zones/index.ts @@ -2,27 +2,22 @@ import $bulkcreate from "./bulk-create.js"; import $bulkdelete from "./bulk-delete.js"; import $create from "./create.js"; import $delete from "./delete.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * zones command group * @generated from apis/overlays/addressing.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "zones", describe: "Operations for address-maps.zones", - builder: (yargs) => { - return yargs - .command($bulkcreate) - .command($bulkdelete) - .command($create) - .command($delete) - .demandCommand(1, "Please specify a subcommand"); + routes: { + "bulk-create": $bulkcreate, + "bulk-delete": $bulkdelete, + create: $create, + delete: $delete, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/index.ts b/packages/cli/src/commands/_generated/addressing/index.ts index 7a92b50dcc..99c664fc0a 100644 --- a/packages/cli/src/commands/_generated/addressing/index.ts +++ b/packages/cli/src/commands/_generated/addressing/index.ts @@ -4,29 +4,24 @@ import $loadocuments from "./loa-documents/index.js"; import $prefixes from "./prefixes/index.js"; import $regionalhostnames from "./regional-hostnames/index.js"; import $services from "./services/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * addressing command * @generated from apis/overlays/addressing.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "addressing", describe: "addressing", - builder: (yargs) => { - return yargs - .command($addressmaps) - .command($leases) - .command($loadocuments) - .command($prefixes) - .command($regionalhostnames) - .command($services) - .demandCommand(1, "Please specify a subcommand"); + routes: { + "address-maps": $addressmaps, + leases: $leases, + "loa-documents": $loadocuments, + prefixes: $prefixes, + "regional-hostnames": $regionalhostnames, + services: $services, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/leases/index.ts b/packages/cli/src/commands/_generated/addressing/leases/index.ts index 306f2cecdc..d7c55d7d66 100644 --- a/packages/cli/src/commands/_generated/addressing/leases/index.ts +++ b/packages/cli/src/commands/_generated/addressing/leases/index.ts @@ -1,20 +1,17 @@ import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * leases command group * @generated from apis/overlays/addressing.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "leases", describe: "Operations for leases", - builder: (yargs) => { - return yargs.command($list).demandCommand(1, "Please specify a subcommand"); + routes: { + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/leases/list.handler.ts b/packages/cli/src/commands/_generated/addressing/leases/list.handler.ts new file mode 100644 index 0000000000..bf8968353c --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/leases/list.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/addressing/leases/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing leases list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing leases list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/leases`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/leases/list.ts b/packages/cli/src/commands/_generated/addressing/leases/list.ts index 9312d5beee..3992ea8a33 100644 --- a/packages/cli/src/commands/_generated/addressing/leases/list.ts +++ b/packages/cli/src/commands/_generated/addressing/leases/list.ts @@ -1,69 +1,30 @@ -import operation from "../../_operations/addressing/leases/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage("$0 addressing leases list\n\nList all leases owned by the account.") - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Leases", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing leases list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing leases list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/leases`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: "$0 addressing leases list\n\nList all leases owned by the account.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/loa-documents/create.handler.ts b/packages/cli/src/commands/_generated/addressing/loa-documents/create.handler.ts new file mode 100644 index 0000000000..3b7ee3d626 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/loa-documents/create.handler.ts @@ -0,0 +1,114 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { readFileForFlag, resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing loa-documents create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if ( + argv.body === undefined && + argv.file === undefined && + argv["loa-document"] === undefined + ) { + throw new Error( + "--body or --file is required for this command. Pass --body '' or --file path/to/file." + ); + } + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing loa-documents create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/loa_documents`, + pathParams: {}, + bodyKind: "multipart", + body: { + body: argv["body"], + file: argv["file"], + "loa-document": argv["loa-document"], + }, + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + argv.file !== undefined || + argv.body !== undefined || + argv["loa-document"] !== undefined + ) { + const formData = new FormData(); + if (argv.file !== undefined) { + const fileContent = readFileForFlag(argv.file); + formData.append( + "file", + new Blob([fileContent]), + argv.file.split(/[\\/]/).filter(Boolean).pop() + ); + } else if (argv.body !== undefined) { + formData.append("file", argv.body); + } + if (argv["loa-document"] !== undefined) + formData.append( + "loa_document", + String( + resolveFileToken( + argv["loa-document"] as string | undefined, + "loa-document", + "text" + ) ?? "" + ) + ); + const result = await withProgress(`Creating`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/addressing/loa_documents`, + { body: formData } + ) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + if (argv.body !== undefined) { + // Endpoint does not accept application/json — send --body as raw bytes, + // resolving @file references as binary file contents. + const bodyData = resolveFileToken(argv.body, "body", "binary"); + const result = await withProgress(`Creating`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/addressing/loa_documents`, + { + body: bodyData, + headers: { "Content-Type": "multipart/form-data" }, + } + ) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/loa-documents/create.ts b/packages/cli/src/commands/_generated/addressing/loa-documents/create.ts index f076f53864..5b80749463 100644 --- a/packages/cli/src/commands/_generated/addressing/loa-documents/create.ts +++ b/packages/cli/src/commands/_generated/addressing/loa-documents/create.ts @@ -1,151 +1,49 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { readFileForFlag, resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing loa-documents create\n\nSubmit LOA document (pdf format) under the account." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }) - .option("file", { - type: "string", - description: "Path to a file to upload as the request body", - }) - .option("loa-document", { - type: "string", - description: "LOA document to upload.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + file: { + kind: "parsed", + brief: "Path to a file to upload as the request body", + optional: true, + parse: String, + }, + "loa-document": { + kind: "parsed", + brief: "LOA document to upload.", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Upload LOA Document", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing loa-documents create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if ( - argv.body === undefined && - argv.file === undefined && - argv["loa-document"] === undefined - ) { - throw new Error( - "--body or --file is required for this command. Pass --body '' or --file path/to/file." - ); - } - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing loa-documents create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/loa_documents`, - pathParams: {}, - bodyKind: "multipart", - body: { - body: argv["body"], - file: argv["file"], - "loa-document": argv["loa-document"], - }, - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - argv.file !== undefined || - argv.body !== undefined || - argv["loa-document"] !== undefined - ) { - const formData = new FormData(); - if (argv.file !== undefined) { - const fileContent = readFileForFlag(argv.file); - formData.append( - "file", - new Blob([fileContent]), - argv.file.split(/[\\/]/).filter(Boolean).pop() - ); - } else if (argv.body !== undefined) { - formData.append("file", argv.body); - } - if (argv["loa-document"] !== undefined) - formData.append( - "loa_document", - String( - resolveFileToken( - argv["loa-document"] as string | undefined, - "loa-document", - "text" - ) ?? "" - ) - ); - const result = await withProgress(`Creating`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/addressing/loa_documents`, - { body: formData } - ) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - if (argv.body !== undefined) { - // Endpoint does not accept application/json — send --body as raw bytes, - // resolving @file references as binary file contents. - const bodyData = resolveFileToken(argv.body, "body", "binary"); - const result = await withProgress(`Creating`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/addressing/loa_documents`, - { - body: bodyData, - headers: { "Content-Type": "multipart/form-data" }, - } - ) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - } - ), -}; + usage: + "$0 addressing loa-documents create\n\nSubmit LOA document (pdf format) under the account.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/loa-documents/get.handler.ts b/packages/cli/src/commands/_generated/addressing/loa-documents/get.handler.ts new file mode 100644 index 0000000000..82a29d3715 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/loa-documents/get.handler.ts @@ -0,0 +1,58 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { fetchRawBytes, writeRawOutput } from "#lib/raw-fetch.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing loa-documents get", + classification: { + safeFlags: ["dry-run", "text"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing loa-documents get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/loa_documents/${argv["loa-document-id"] == null ? "" : encodeURIComponent(String(argv["loa-document-id"]))}/download`, + pathParams: { + "loa-document-id": String(argv["loa-document-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const __cfRawBytes = await withProgress(`Loading`, async () => + fetchRawBytes( + `/accounts/${accountId}/addressing/loa_documents/${encodeURIComponent(String(argv["loa-document-id"]))}/download`, + { + method: "GET", + local: argv.local === true, + persistTo: argv.persistTo as string | undefined, + } + ) + ); + writeRawOutput( + argv.text === true ? __cfRawBytes.toString("utf-8") : __cfRawBytes + ); + return; + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/loa-documents/get.ts b/packages/cli/src/commands/_generated/addressing/loa-documents/get.ts index 37844ecd6b..1caff49ce2 100644 --- a/packages/cli/src/commands/_generated/addressing/loa-documents/get.ts +++ b/packages/cli/src/commands/_generated/addressing/loa-documents/get.ts @@ -1,94 +1,43 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { fetchRawBytes, writeRawOutput } from "#lib/raw-fetch.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing loa-documents get \n\nDownload specified LOA document under the account." - ) - .positional("loa-document-id", { - type: "string", - description: "Identifier for the uploaded LOA document.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("text", { - type: "boolean", - description: + }, + text: { + kind: "boolean", + brief: "Decode the response body as UTF-8 text instead of writing raw bytes", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "loa-document-id", + brief: "Identifier for the uploaded LOA document.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Download LOA Document", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing loa-documents get", - classification: { - safeFlags: ["dry-run", "text"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing loa-documents get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/loa_documents/${argv["loa-document-id"] == null ? "" : encodeURIComponent(String(argv["loa-document-id"]))}/download`, - pathParams: { - "loa-document-id": String(argv["loa-document-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const __cfRawBytes = await withProgress(`Loading`, async () => - fetchRawBytes( - `/accounts/${accountId}/addressing/loa_documents/${encodeURIComponent(String(argv["loa-document-id"]))}/download`, - { - method: "GET", - local: argv.local === true, - persistTo: argv.persistTo as string | undefined, - } - ) - ); - writeRawOutput( - argv.text === true ? __cfRawBytes.toString("utf-8") : __cfRawBytes - ); - return; - } - ), -}; + usage: + "$0 addressing loa-documents get \n\nDownload specified LOA document under the account.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/loa-documents/index.ts b/packages/cli/src/commands/_generated/addressing/loa-documents/index.ts index c55ae9052c..124eb60c88 100644 --- a/packages/cli/src/commands/_generated/addressing/loa-documents/index.ts +++ b/packages/cli/src/commands/_generated/addressing/loa-documents/index.ts @@ -1,26 +1,21 @@ import $create from "./create.js"; import $get from "./get.js"; import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * loa-documents command group * @generated from apis/overlays/addressing.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "loa-documents", describe: "Operations for loa-documents", - builder: (yargs) => { - return yargs - .command($create) - .command($get) - .command($list) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + get: $get, + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/loa-documents/list.handler.ts b/packages/cli/src/commands/_generated/addressing/loa-documents/list.handler.ts new file mode 100644 index 0000000000..4aef483a4d --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/loa-documents/list.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/addressing/loa-documents/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing loa-documents list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing loa-documents list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/loa_documents`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/loa-documents/list.ts b/packages/cli/src/commands/_generated/addressing/loa-documents/list.ts index 4aa7541da2..3c2e2a2062 100644 --- a/packages/cli/src/commands/_generated/addressing/loa-documents/list.ts +++ b/packages/cli/src/commands/_generated/addressing/loa-documents/list.ts @@ -1,71 +1,31 @@ -import operation from "../../_operations/addressing/loa-documents/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing loa-documents list\n\nList all LOA documents uploaded under the account." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List LOA Documents", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing loa-documents list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing loa-documents list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/loa_documents`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 addressing loa-documents list\n\nList all LOA documents uploaded under the account.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/advertisement-status/edit.handler.ts b/packages/cli/src/commands/_generated/addressing/prefixes/advertisement-status/edit.handler.ts new file mode 100644 index 0000000000..e101201ad2 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/prefixes/advertisement-status/edit.handler.ts @@ -0,0 +1,87 @@ +import operation from "../../../_operations/addressing/prefixes/advertisement-status/edit.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./edit.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing prefixes advertisement-status edit", + classification: { + safeFlags: ["advertised", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["advertised"] === undefined) { + throw new Error( + "--advertised is required (or pass --body with this field set)." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing prefixes advertisement-status edit", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/bgp/status`, + pathParams: { "prefix-id": String(argv["prefix-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + advertised: argv["advertised"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + prefix_id: argv["prefix-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + advertised: argv["advertised"], + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + prefix_id: argv["prefix-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/advertisement-status/edit.ts b/packages/cli/src/commands/_generated/addressing/prefixes/advertisement-status/edit.ts index a5441283bf..e4ff3b6d39 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/advertisement-status/edit.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/advertisement-status/edit.ts @@ -1,126 +1,49 @@ -import operation from "../../../_operations/addressing/prefixes/advertisement-status/edit.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * edit command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing prefixes advertisement-status edit \n\nAdvertise or withdraw the BGP route for a prefix. **Deprecated:** Prefer the BGP Prefixes endpoints, which additionally allow for advertising and withdrawing subnets of an IP prefix." - ) - .positional("prefix-id", { - type: "string", - description: "Identifier of an IP Prefix.", - demandOption: true, - }) - .option("advertised", { - type: "boolean", - description: +const parameters = { + flags: { + advertised: { + kind: "boolean", + brief: "Advertisement status of the prefix. If `true`, the BGP route for the prefix is advertised to the Internet. If \n`false`, the BGP route is withdrawn.\n", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "prefix-id", + brief: "Identifier of an IP Prefix.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "edit ", describe: "Update Prefix Dynamic Advertisement Status", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing prefixes advertisement-status edit", - classification: { - safeFlags: ["advertised", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["advertised"] === undefined) { - throw new Error( - "--advertised is required (or pass --body with this field set)." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing prefixes advertisement-status edit", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/bgp/status`, - pathParams: { "prefix-id": String(argv["prefix-id"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - advertised: argv["advertised"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - prefix_id: argv["prefix-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - advertised: argv["advertised"], - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - prefix_id: argv["prefix-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 addressing prefixes advertisement-status edit \n\nAdvertise or withdraw the BGP route for a prefix. **Deprecated:** Prefer the BGP Prefixes endpoints, which additionally allow for advertising and withdrawing subnets of an IP prefix.", + ...parameters, + loader: () => import("./edit.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/advertisement-status/get.handler.ts b/packages/cli/src/commands/_generated/addressing/prefixes/advertisement-status/get.handler.ts new file mode 100644 index 0000000000..dce7c629a9 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/prefixes/advertisement-status/get.handler.ts @@ -0,0 +1,49 @@ +import operation from "../../../_operations/addressing/prefixes/advertisement-status/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing prefixes advertisement-status get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing prefixes advertisement-status get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/bgp/status`, + pathParams: { "prefix-id": String(argv["prefix-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + prefix_id: argv["prefix-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/advertisement-status/get.ts b/packages/cli/src/commands/_generated/addressing/prefixes/advertisement-status/get.ts index e5d59aaed0..b7b1f16d2c 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/advertisement-status/get.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/advertisement-status/get.ts @@ -1,79 +1,37 @@ -import operation from "../../../_operations/addressing/prefixes/advertisement-status/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing prefixes advertisement-status get \n\nView the current advertisement state for a prefix. **Deprecated:** Prefer the BGP Prefixes endpoints, which additionally allow for advertising and withdrawing subnets of an IP prefix." - ) - .positional("prefix-id", { - type: "string", - description: "Identifier of an IP Prefix.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "prefix-id", + brief: "Identifier of an IP Prefix.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get Advertisement Status", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing prefixes advertisement-status get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing prefixes advertisement-status get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/bgp/status`, - pathParams: { "prefix-id": String(argv["prefix-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - prefix_id: argv["prefix-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 addressing prefixes advertisement-status get \n\nView the current advertisement state for a prefix. **Deprecated:** Prefer the BGP Prefixes endpoints, which additionally allow for advertising and withdrawing subnets of an IP prefix.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/advertisement-status/index.ts b/packages/cli/src/commands/_generated/addressing/prefixes/advertisement-status/index.ts index a8c3870d93..a139624251 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/advertisement-status/index.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/advertisement-status/index.ts @@ -1,24 +1,19 @@ import $edit from "./edit.js"; import $get from "./get.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * advertisement-status command group * @generated from apis/overlays/addressing.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "advertisement-status", describe: "Operations for prefixes.advertisement-status", - builder: (yargs) => { - return yargs - .command($edit) - .command($get) - .demandCommand(1, "Please specify a subcommand"); + routes: { + edit: $edit, + get: $get, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/create.handler.ts b/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/create.handler.ts new file mode 100644 index 0000000000..8a664d468c --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/create.handler.ts @@ -0,0 +1,98 @@ +import operation from "../../../_operations/addressing/prefixes/bgp-prefixes/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing prefixes bgp-prefixes create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["cidr"] === undefined) { + argv["cidr"] = await promptForRequiredField( + "cidr", + "IP Prefix in Classless Inter-Domain Routing format." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing prefixes bgp-prefixes create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/bgp/prefixes`, + pathParams: { "prefix-id": String(argv["prefix-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + cidr: resolveFileToken( + argv["cidr"] as string | undefined, + "cidr", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + prefix_id: argv["prefix-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + cidr: resolveFileToken( + argv["cidr"] as string | undefined, + "cidr", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + prefix_id: argv["prefix-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/create.ts b/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/create.ts index 0f245bf2aa..18cb59b43d 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/create.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/create.ts @@ -1,136 +1,49 @@ -import operation from "../../../_operations/addressing/prefixes/bgp-prefixes/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing prefixes bgp-prefixes create \n\nCreate a BGP prefix, controlling the BGP advertisement status of a specific subnet. When created, BGP prefixes are initially withdrawn, and can be advertised with the Update BGP Prefix API." - ) - .positional("prefix-id", { - type: "string", - description: "Identifier of an IP Prefix.", - demandOption: true, - }) - .option("cidr", { - type: "string", - description: "IP Prefix in Classless Inter-Domain Routing format.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + cidr: { + kind: "parsed", + brief: "IP Prefix in Classless Inter-Domain Routing format.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "prefix-id", + brief: "Identifier of an IP Prefix.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Create BGP Prefix", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing prefixes bgp-prefixes create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["cidr"] === undefined) { - argv["cidr"] = await promptForRequiredField( - "cidr", - "IP Prefix in Classless Inter-Domain Routing format." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing prefixes bgp-prefixes create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/bgp/prefixes`, - pathParams: { "prefix-id": String(argv["prefix-id"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - cidr: resolveFileToken( - argv["cidr"] as string | undefined, - "cidr", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - prefix_id: argv["prefix-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - cidr: resolveFileToken( - argv["cidr"] as string | undefined, - "cidr", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - prefix_id: argv["prefix-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 addressing prefixes bgp-prefixes create \n\nCreate a BGP prefix, controlling the BGP advertisement status of a specific subnet. When created, BGP prefixes are initially withdrawn, and can be advertised with the Update BGP Prefix API.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/delete.handler.ts b/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/delete.handler.ts new file mode 100644 index 0000000000..144f7263ba --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/delete.handler.ts @@ -0,0 +1,59 @@ +import operation from "../../../_operations/addressing/prefixes/bgp-prefixes/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing prefixes bgp-prefixes delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing prefixes bgp-prefixes delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/bgp/prefixes/${argv["bgp-prefix-id"] == null ? "" : encodeURIComponent(String(argv["bgp-prefix-id"]))}`, + pathParams: { + "prefix-id": String(argv["prefix-id"] ?? ""), + "bgp-prefix-id": String(argv["bgp-prefix-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + prefix_id: argv["prefix-id"], + bgp_prefix_id: argv["bgp-prefix-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/delete.ts b/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/delete.ts index 11cb19fbf2..595143557a 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/delete.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/delete.ts @@ -1,100 +1,48 @@ -import operation from "../../../_operations/addressing/prefixes/bgp-prefixes/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing prefixes bgp-prefixes delete \n\nDelete a BGP Prefix associated with the specified IP Prefix. A BGP Prefix must be withdrawn before it can be deleted." - ) - .positional("bgp-prefix-id", { - type: "string", - description: "Identifier of BGP Prefix.", - demandOption: true, - }) - .option("prefix-id", { - type: "string", - description: "Identifier of an IP Prefix.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "prefix-id": { + kind: "parsed", + brief: "Identifier of an IP Prefix.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "bgp-prefix-id", + brief: "Identifier of BGP Prefix.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete BGP Prefix", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing prefixes bgp-prefixes delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing prefixes bgp-prefixes delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/bgp/prefixes/${argv["bgp-prefix-id"] == null ? "" : encodeURIComponent(String(argv["bgp-prefix-id"]))}`, - pathParams: { - "prefix-id": String(argv["prefix-id"] ?? ""), - "bgp-prefix-id": String(argv["bgp-prefix-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - prefix_id: argv["prefix-id"], - bgp_prefix_id: argv["bgp-prefix-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 addressing prefixes bgp-prefixes delete \n\nDelete a BGP Prefix associated with the specified IP Prefix. A BGP Prefix must be withdrawn before it can be deleted.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/edit.handler.ts b/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/edit.handler.ts new file mode 100644 index 0000000000..d8b10d4117 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/edit.handler.ts @@ -0,0 +1,93 @@ +import operation from "../../../_operations/addressing/prefixes/bgp-prefixes/edit.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./edit.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing prefixes bgp-prefixes edit", + classification: { + safeFlags: [ + "auto-advertise-withdraw", + "on-demand-advertised", + "dry-run", + ], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing prefixes bgp-prefixes edit", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/bgp/prefixes/${argv["bgp-prefix-id"] == null ? "" : encodeURIComponent(String(argv["bgp-prefix-id"]))}`, + pathParams: { + "prefix-id": String(argv["prefix-id"] ?? ""), + "bgp-prefix-id": String(argv["bgp-prefix-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + asn_prepend_count: argv["asn-prepend-count"], + auto_advertise_withdraw: argv["auto-advertise-withdraw"], + on_demand: { + advertised: argv["on-demand-advertised"], + }, + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + prefix_id: argv["prefix-id"], + bgp_prefix_id: argv["bgp-prefix-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + asn_prepend_count: argv["asn-prepend-count"], + auto_advertise_withdraw: argv["auto-advertise-withdraw"], + on_demand: { + advertised: argv["on-demand-advertised"], + }, + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + prefix_id: argv["prefix-id"], + bgp_prefix_id: argv["bgp-prefix-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/edit.ts b/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/edit.ts index a3d9182324..554a211f6b 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/edit.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/edit.ts @@ -1,146 +1,66 @@ -import operation from "../../../_operations/addressing/prefixes/bgp-prefixes/edit.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * edit command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing prefixes bgp-prefixes edit \n\nUpdate the properties of a BGP Prefix, such as the on demand advertisement status (advertised or withdrawn)." - ) - .positional("bgp-prefix-id", { - type: "string", - description: "Identifier of BGP Prefix.", - demandOption: true, - }) - .option("prefix-id", { - type: "string", - description: "Identifier of an IP Prefix.", - demandOption: true, - }) - .option("asn-prepend-count", { - type: "number", - description: +const parameters = { + flags: { + "prefix-id": { + kind: "parsed", + brief: "Identifier of an IP Prefix.", + parse: String, + }, + "asn-prepend-count": { + kind: "parsed", + brief: "Number of times to prepend the Cloudflare ASN to the BGP AS-Path attribute", - }) - .option("auto-advertise-withdraw", { - type: "boolean", - description: + optional: true, + parse: Number, + }, + "auto-advertise-withdraw": { + kind: "boolean", + brief: "Determines if Cloudflare advertises a BYOIP BGP prefix even when there is no matching BGP prefix in the Magic routing table. When true, Cloudflare will automatically withdraw the BGP prefix when there are no matching BGP routes, and will resume advertising when there is at least one matching BGP route.", - }) - .option("on-demand-advertised", { - type: "boolean", - description: "The on_demand.advertised field", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + }, + "on-demand-advertised": { + kind: "boolean", + brief: "The on_demand.advertised field", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "bgp-prefix-id", + brief: "Identifier of BGP Prefix.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "edit ", describe: "Update BGP Prefix", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing prefixes bgp-prefixes edit", - classification: { - safeFlags: [ - "auto-advertise-withdraw", - "on-demand-advertised", - "dry-run", - ], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing prefixes bgp-prefixes edit", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/bgp/prefixes/${argv["bgp-prefix-id"] == null ? "" : encodeURIComponent(String(argv["bgp-prefix-id"]))}`, - pathParams: { - "prefix-id": String(argv["prefix-id"] ?? ""), - "bgp-prefix-id": String(argv["bgp-prefix-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - asn_prepend_count: argv["asn-prepend-count"], - auto_advertise_withdraw: argv["auto-advertise-withdraw"], - on_demand: { - advertised: argv["on-demand-advertised"], - }, - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - prefix_id: argv["prefix-id"], - bgp_prefix_id: argv["bgp-prefix-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - asn_prepend_count: argv["asn-prepend-count"], - auto_advertise_withdraw: argv["auto-advertise-withdraw"], - on_demand: { - advertised: argv["on-demand-advertised"], - }, - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - prefix_id: argv["prefix-id"], - bgp_prefix_id: argv["bgp-prefix-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 addressing prefixes bgp-prefixes edit \n\nUpdate the properties of a BGP Prefix, such as the on demand advertisement status (advertised or withdrawn).", + ...parameters, + loader: () => import("./edit.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/get.handler.ts b/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/get.handler.ts new file mode 100644 index 0000000000..79ffe2d3d9 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/get.handler.ts @@ -0,0 +1,53 @@ +import operation from "../../../_operations/addressing/prefixes/bgp-prefixes/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing prefixes bgp-prefixes get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing prefixes bgp-prefixes get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/bgp/prefixes/${argv["bgp-prefix-id"] == null ? "" : encodeURIComponent(String(argv["bgp-prefix-id"]))}`, + pathParams: { + "prefix-id": String(argv["prefix-id"] ?? ""), + "bgp-prefix-id": String(argv["bgp-prefix-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + prefix_id: argv["prefix-id"], + bgp_prefix_id: argv["bgp-prefix-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/get.ts b/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/get.ts index a6c0b6cf2a..d1d6e239e1 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/get.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/get.ts @@ -1,88 +1,42 @@ -import operation from "../../../_operations/addressing/prefixes/bgp-prefixes/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing prefixes bgp-prefixes get \n\nRetrieve a single BGP Prefix according to its identifier" - ) - .positional("bgp-prefix-id", { - type: "string", - description: "Identifier of BGP Prefix.", - demandOption: true, - }) - .option("prefix-id", { - type: "string", - description: "Identifier of an IP Prefix.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "prefix-id": { + kind: "parsed", + brief: "Identifier of an IP Prefix.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "bgp-prefix-id", + brief: "Identifier of BGP Prefix.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Fetch BGP Prefix", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing prefixes bgp-prefixes get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing prefixes bgp-prefixes get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/bgp/prefixes/${argv["bgp-prefix-id"] == null ? "" : encodeURIComponent(String(argv["bgp-prefix-id"]))}`, - pathParams: { - "prefix-id": String(argv["prefix-id"] ?? ""), - "bgp-prefix-id": String(argv["bgp-prefix-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - prefix_id: argv["prefix-id"], - bgp_prefix_id: argv["bgp-prefix-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 addressing prefixes bgp-prefixes get \n\nRetrieve a single BGP Prefix according to its identifier", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/index.ts b/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/index.ts index fed42a814e..40034df705 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/index.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/index.ts @@ -3,28 +3,23 @@ import $delete from "./delete.js"; import $edit from "./edit.js"; import $get from "./get.js"; import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * bgp-prefixes command group * @generated from apis/overlays/addressing.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "bgp-prefixes", describe: "Operations for prefixes.bgp-prefixes", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($edit) - .command($get) - .command($list) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + edit: $edit, + get: $get, + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/list.handler.ts b/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/list.handler.ts new file mode 100644 index 0000000000..1c88ad3945 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/list.handler.ts @@ -0,0 +1,49 @@ +import operation from "../../../_operations/addressing/prefixes/bgp-prefixes/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing prefixes bgp-prefixes list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing prefixes bgp-prefixes list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/bgp/prefixes`, + pathParams: { "prefix-id": String(argv["prefix-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + prefix_id: argv["prefix-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/list.ts b/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/list.ts index dd4c211d2b..dbe3559f7b 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/list.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/bgp-prefixes/list.ts @@ -1,79 +1,36 @@ -import operation from "../../../_operations/addressing/prefixes/bgp-prefixes/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing prefixes bgp-prefixes list\n\nList all BGP Prefixes within the specified IP Prefix. BGP Prefixes are used to control which specific subnets are advertised to the Internet. It is possible to advertise subnets more specific than an IP Prefix by creating more specific BGP Prefixes." - ) - .option("prefix-id", { - type: "string", - description: "Identifier of an IP Prefix.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "prefix-id": { + kind: "parsed", + brief: "Identifier of an IP Prefix.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List BGP Prefixes", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing prefixes bgp-prefixes list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing prefixes bgp-prefixes list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/bgp/prefixes`, - pathParams: { "prefix-id": String(argv["prefix-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - prefix_id: argv["prefix-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 addressing prefixes bgp-prefixes list\n\nList all BGP Prefixes within the specified IP Prefix. BGP Prefixes are used to control which specific subnets are advertised to the Internet. It is possible to advertise subnets more specific than an IP Prefix by creating more specific BGP Prefixes.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/create.handler.ts b/packages/cli/src/commands/_generated/addressing/prefixes/create.handler.ts new file mode 100644 index 0000000000..8eb0acde0d --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/prefixes/create.handler.ts @@ -0,0 +1,119 @@ +import operation from "../../_operations/addressing/prefixes/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing prefixes create", + classification: { + safeFlags: ["delegate-loa-creation", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["asn"] === undefined) { + throw new Error( + "--asn is required (or pass --body with this field set)." + ); + } + if (argv["cidr"] === undefined) { + argv["cidr"] = await promptForRequiredField( + "cidr", + "IP Prefix in Classless Inter-Domain Routing format." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing prefixes create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + asn: argv["asn"], + cidr: resolveFileToken( + argv["cidr"] as string | undefined, + "cidr", + "text" + ), + delegate_loa_creation: argv["delegate-loa-creation"], + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + loa_document_id: resolveFileToken( + argv["loa-document-id"] as string | undefined, + "loa-document-id", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + asn: argv["asn"], + cidr: resolveFileToken( + argv["cidr"] as string | undefined, + "cidr", + "text" + ), + delegate_loa_creation: argv["delegate-loa-creation"], + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + loa_document_id: resolveFileToken( + argv["loa-document-id"] as string | undefined, + "loa-document-id", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/create.ts b/packages/cli/src/commands/_generated/addressing/prefixes/create.ts index f5d19dc59a..88c4e73d6c 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/create.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/create.ts @@ -1,171 +1,67 @@ -import operation from "../../_operations/addressing/prefixes/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing prefixes create\n\nAdd a new prefix under the account." - ) - .option("asn", { - type: "number", - description: +const parameters = { + flags: { + asn: { + kind: "parsed", + brief: "Autonomous System Number (ASN) the prefix will be advertised under. Use 13335 for Cloudflare's ASN, or your own ASN as an integer without the AS prefix. The IRR route and RPKI ROA must authorize this ASN.", - }) - .option("cidr", { - type: "string", - description: "IP Prefix in Classless Inter-Domain Routing format.", - }) - .option("delegate-loa-creation", { - type: "boolean", - description: + optional: true, + parse: Number, + }, + cidr: { + kind: "parsed", + brief: "IP Prefix in Classless Inter-Domain Routing format.", + optional: true, + parse: String, + }, + "delegate-loa-creation": { + kind: "boolean", + brief: "Whether Cloudflare is allowed to generate the LOA document on behalf of the prefix owner.", default: false, - }) - .option("description", { - type: "string", - description: "Description of the prefix.", - }) - .option("loa-document-id", { - type: "string", - description: "Identifier for the uploaded LOA document.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + }, + description: { + kind: "parsed", + brief: "Description of the prefix.", + optional: true, + parse: String, + }, + "loa-document-id": { + kind: "parsed", + brief: "Identifier for the uploaded LOA document.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Add Prefix", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing prefixes create", - classification: { - safeFlags: ["delegate-loa-creation", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["asn"] === undefined) { - throw new Error( - "--asn is required (or pass --body with this field set)." - ); - } - if (argv["cidr"] === undefined) { - argv["cidr"] = await promptForRequiredField( - "cidr", - "IP Prefix in Classless Inter-Domain Routing format." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing prefixes create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - asn: argv["asn"], - cidr: resolveFileToken( - argv["cidr"] as string | undefined, - "cidr", - "text" - ), - delegate_loa_creation: argv["delegate-loa-creation"], - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - loa_document_id: resolveFileToken( - argv["loa-document-id"] as string | undefined, - "loa-document-id", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - asn: argv["asn"], - cidr: resolveFileToken( - argv["cidr"] as string | undefined, - "cidr", - "text" - ), - delegate_loa_creation: argv["delegate-loa-creation"], - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - loa_document_id: resolveFileToken( - argv["loa-document-id"] as string | undefined, - "loa-document-id", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: "$0 addressing prefixes create\n\nAdd a new prefix under the account.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/delegations/create.handler.ts b/packages/cli/src/commands/_generated/addressing/prefixes/delegations/create.handler.ts new file mode 100644 index 0000000000..f3abb0bdec --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/prefixes/delegations/create.handler.ts @@ -0,0 +1,114 @@ +import operation from "../../../_operations/addressing/prefixes/delegations/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing prefixes delegations create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["cidr"] === undefined) { + argv["cidr"] = await promptForRequiredField( + "cidr", + "IP Prefix in Classless Inter-Domain Routing format." + ); + } + if (argv["delegated-account-id"] === undefined) { + argv["delegated-account-id"] = await promptForRequiredField( + "delegated-account-id", + "Account identifier for the account to which prefix is being delegated." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing prefixes delegations create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/delegations`, + pathParams: { "prefix-id": String(argv["prefix-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + cidr: resolveFileToken( + argv["cidr"] as string | undefined, + "cidr", + "text" + ), + delegated_account_id: resolveFileToken( + argv["delegated-account-id"] as string | undefined, + "delegated-account-id", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + prefix_id: argv["prefix-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + cidr: resolveFileToken( + argv["cidr"] as string | undefined, + "cidr", + "text" + ), + delegated_account_id: resolveFileToken( + argv["delegated-account-id"] as string | undefined, + "delegated-account-id", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + prefix_id: argv["prefix-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/delegations/create.ts b/packages/cli/src/commands/_generated/addressing/prefixes/delegations/create.ts index 0afe1c393d..9a1c9bc060 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/delegations/create.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/delegations/create.ts @@ -1,157 +1,56 @@ -import operation from "../../../_operations/addressing/prefixes/delegations/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing prefixes delegations create \n\nCreate a new account delegation for a given IP prefix." - ) - .positional("prefix-id", { - type: "string", - description: "Identifier of an IP Prefix.", - demandOption: true, - }) - .option("cidr", { - type: "string", - description: "IP Prefix in Classless Inter-Domain Routing format.", - }) - .option("delegated-account-id", { - type: "string", - description: +const parameters = { + flags: { + cidr: { + kind: "parsed", + brief: "IP Prefix in Classless Inter-Domain Routing format.", + optional: true, + parse: String, + }, + "delegated-account-id": { + kind: "parsed", + brief: "Account identifier for the account to which prefix is being delegated.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "prefix-id", + brief: "Identifier of an IP Prefix.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Create Prefix Delegation", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing prefixes delegations create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["cidr"] === undefined) { - argv["cidr"] = await promptForRequiredField( - "cidr", - "IP Prefix in Classless Inter-Domain Routing format." - ); - } - if (argv["delegated-account-id"] === undefined) { - argv["delegated-account-id"] = await promptForRequiredField( - "delegated-account-id", - "Account identifier for the account to which prefix is being delegated." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing prefixes delegations create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/delegations`, - pathParams: { "prefix-id": String(argv["prefix-id"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - cidr: resolveFileToken( - argv["cidr"] as string | undefined, - "cidr", - "text" - ), - delegated_account_id: resolveFileToken( - argv["delegated-account-id"] as string | undefined, - "delegated-account-id", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - prefix_id: argv["prefix-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - cidr: resolveFileToken( - argv["cidr"] as string | undefined, - "cidr", - "text" - ), - delegated_account_id: resolveFileToken( - argv["delegated-account-id"] as string | undefined, - "delegated-account-id", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - prefix_id: argv["prefix-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 addressing prefixes delegations create \n\nCreate a new account delegation for a given IP prefix.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/delegations/delete.handler.ts b/packages/cli/src/commands/_generated/addressing/prefixes/delegations/delete.handler.ts new file mode 100644 index 0000000000..eec638c033 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/prefixes/delegations/delete.handler.ts @@ -0,0 +1,59 @@ +import operation from "../../../_operations/addressing/prefixes/delegations/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing prefixes delegations delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing prefixes delegations delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/delegations/${argv["delegation-id"] == null ? "" : encodeURIComponent(String(argv["delegation-id"]))}`, + pathParams: { + "prefix-id": String(argv["prefix-id"] ?? ""), + "delegation-id": String(argv["delegation-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + prefix_id: argv["prefix-id"], + delegation_id: argv["delegation-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/delegations/delete.ts b/packages/cli/src/commands/_generated/addressing/prefixes/delegations/delete.ts index bc96bc81e4..e8a36847e5 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/delegations/delete.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/delegations/delete.ts @@ -1,100 +1,48 @@ -import operation from "../../../_operations/addressing/prefixes/delegations/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing prefixes delegations delete \n\nDelete an account delegation for a given IP prefix." - ) - .positional("delegation-id", { - type: "string", - description: "Identifier of a Delegation.", - demandOption: true, - }) - .option("prefix-id", { - type: "string", - description: "Identifier of an IP Prefix.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "prefix-id": { + kind: "parsed", + brief: "Identifier of an IP Prefix.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "delegation-id", + brief: "Identifier of a Delegation.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete Prefix Delegation", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing prefixes delegations delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing prefixes delegations delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/delegations/${argv["delegation-id"] == null ? "" : encodeURIComponent(String(argv["delegation-id"]))}`, - pathParams: { - "prefix-id": String(argv["prefix-id"] ?? ""), - "delegation-id": String(argv["delegation-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - prefix_id: argv["prefix-id"], - delegation_id: argv["delegation-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 addressing prefixes delegations delete \n\nDelete an account delegation for a given IP prefix.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/delegations/index.ts b/packages/cli/src/commands/_generated/addressing/prefixes/delegations/index.ts index 45771a2495..edce1f8468 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/delegations/index.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/delegations/index.ts @@ -1,26 +1,21 @@ import $create from "./create.js"; import $delete from "./delete.js"; import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * delegations command group * @generated from apis/overlays/addressing.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "delegations", describe: "Operations for prefixes.delegations", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($list) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/delegations/list.handler.ts b/packages/cli/src/commands/_generated/addressing/prefixes/delegations/list.handler.ts new file mode 100644 index 0000000000..6208c74ae0 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/prefixes/delegations/list.handler.ts @@ -0,0 +1,49 @@ +import operation from "../../../_operations/addressing/prefixes/delegations/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing prefixes delegations list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing prefixes delegations list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/delegations`, + pathParams: { "prefix-id": String(argv["prefix-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + prefix_id: argv["prefix-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/delegations/list.ts b/packages/cli/src/commands/_generated/addressing/prefixes/delegations/list.ts index e479d8af1b..b003019c22 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/delegations/list.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/delegations/list.ts @@ -1,79 +1,36 @@ -import operation from "../../../_operations/addressing/prefixes/delegations/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing prefixes delegations list\n\nList all delegations for a given account IP prefix." - ) - .option("prefix-id", { - type: "string", - description: "Identifier of an IP Prefix.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "prefix-id": { + kind: "parsed", + brief: "Identifier of an IP Prefix.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Prefix Delegations", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing prefixes delegations list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing prefixes delegations list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/delegations`, - pathParams: { "prefix-id": String(argv["prefix-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - prefix_id: argv["prefix-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 addressing prefixes delegations list\n\nList all delegations for a given account IP prefix.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/delete.handler.ts b/packages/cli/src/commands/_generated/addressing/prefixes/delete.handler.ts new file mode 100644 index 0000000000..937f39258d --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/prefixes/delete.handler.ts @@ -0,0 +1,55 @@ +import operation from "../../_operations/addressing/prefixes/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing prefixes delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing prefixes delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}`, + pathParams: { "prefix-id": String(argv["prefix-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + prefix_id: argv["prefix-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/delete.ts b/packages/cli/src/commands/_generated/addressing/prefixes/delete.ts index 77b6000cf9..df2b12e84d 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/delete.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/delete.ts @@ -1,91 +1,43 @@ -import operation from "../../_operations/addressing/prefixes/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing prefixes delete \n\nDelete an unapproved prefix owned by the account." - ) - .positional("prefix-id", { - type: "string", - description: "Identifier of an IP Prefix.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "prefix-id", + brief: "Identifier of an IP Prefix.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete Prefix", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing prefixes delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing prefixes delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}`, - pathParams: { "prefix-id": String(argv["prefix-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - prefix_id: argv["prefix-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 addressing prefixes delete \n\nDelete an unapproved prefix owned by the account.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/edit.handler.ts b/packages/cli/src/commands/_generated/addressing/prefixes/edit.handler.ts new file mode 100644 index 0000000000..60ec60fe04 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/prefixes/edit.handler.ts @@ -0,0 +1,98 @@ +import operation from "../../_operations/addressing/prefixes/edit.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./edit.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing prefixes edit", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["description"] === undefined) { + argv["description"] = await promptForRequiredField( + "description", + "Description of the prefix." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing prefixes edit", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}`, + pathParams: { "prefix-id": String(argv["prefix-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + prefix_id: argv["prefix-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + prefix_id: argv["prefix-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/edit.ts b/packages/cli/src/commands/_generated/addressing/prefixes/edit.ts index 5b6762c753..9dd4815a75 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/edit.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/edit.ts @@ -1,136 +1,49 @@ -import operation from "../../_operations/addressing/prefixes/edit.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * edit command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing prefixes edit \n\nModify the description for a prefix owned by the account." - ) - .positional("prefix-id", { - type: "string", - description: "Identifier of an IP Prefix.", - demandOption: true, - }) - .option("description", { - type: "string", - description: "Description of the prefix.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + description: { + kind: "parsed", + brief: "Description of the prefix.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "prefix-id", + brief: "Identifier of an IP Prefix.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "edit ", describe: "Update Prefix Description", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing prefixes edit", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["description"] === undefined) { - argv["description"] = await promptForRequiredField( - "description", - "Description of the prefix." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing prefixes edit", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}`, - pathParams: { "prefix-id": String(argv["prefix-id"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - prefix_id: argv["prefix-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - prefix_id: argv["prefix-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 addressing prefixes edit \n\nModify the description for a prefix owned by the account.", + ...parameters, + loader: () => import("./edit.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/get.handler.ts b/packages/cli/src/commands/_generated/addressing/prefixes/get.handler.ts new file mode 100644 index 0000000000..6e18ad7096 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/prefixes/get.handler.ts @@ -0,0 +1,49 @@ +import operation from "../../_operations/addressing/prefixes/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing prefixes get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing prefixes get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}`, + pathParams: { "prefix-id": String(argv["prefix-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + prefix_id: argv["prefix-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/get.ts b/packages/cli/src/commands/_generated/addressing/prefixes/get.ts index 9da2d34076..7daa5a2ddf 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/get.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/get.ts @@ -1,79 +1,37 @@ -import operation from "../../_operations/addressing/prefixes/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing prefixes get \n\nList a particular prefix owned by the account." - ) - .positional("prefix-id", { - type: "string", - description: "Identifier of an IP Prefix.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "prefix-id", + brief: "Identifier of an IP Prefix.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Prefix Details", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing prefixes get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing prefixes get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}`, - pathParams: { "prefix-id": String(argv["prefix-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - prefix_id: argv["prefix-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 addressing prefixes get \n\nList a particular prefix owned by the account.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/index.ts b/packages/cli/src/commands/_generated/addressing/prefixes/index.ts index 3a2faf947d..f27a94d3d0 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/index.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/index.ts @@ -8,33 +8,28 @@ import $get from "./get.js"; import $list from "./list.js"; import $servicebindings from "./service-bindings/index.js"; import $validate from "./validate/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * prefixes command group * @generated from apis/overlays/addressing.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "prefixes", describe: "Operations for prefixes", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($edit) - .command($get) - .command($list) - .command($advertisementstatus) - .command($bgpprefixes) - .command($delegations) - .command($servicebindings) - .command($validate) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + edit: $edit, + get: $get, + list: $list, + "advertisement-status": $advertisementstatus, + "bgp-prefixes": $bgpprefixes, + delegations: $delegations, + "service-bindings": $servicebindings, + validate: $validate, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/list.handler.ts b/packages/cli/src/commands/_generated/addressing/prefixes/list.handler.ts new file mode 100644 index 0000000000..ae0d2041d5 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/prefixes/list.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/addressing/prefixes/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing prefixes list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing prefixes list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/list.ts b/packages/cli/src/commands/_generated/addressing/prefixes/list.ts index 2f80e5a572..7dfec2894f 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/list.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/list.ts @@ -1,71 +1,31 @@ -import operation from "../../_operations/addressing/prefixes/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing prefixes list\n\nList all prefixes owned by the account." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Prefixes", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing prefixes list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing prefixes list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 addressing prefixes list\n\nList all prefixes owned by the account.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/create.handler.ts b/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/create.handler.ts new file mode 100644 index 0000000000..bf479afc85 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/create.handler.ts @@ -0,0 +1,114 @@ +import operation from "../../../_operations/addressing/prefixes/service-bindings/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing prefixes service-bindings create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["cidr"] === undefined) { + argv["cidr"] = await promptForRequiredField( + "cidr", + "IP Prefix in Classless Inter-Domain Routing format." + ); + } + if (argv["service-id"] === undefined) { + argv["service-id"] = await promptForRequiredField( + "service-id", + "Identifier of a Service on the Cloudflare network. Available services and their IDs may be found in the **List Services** endpoint. " + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing prefixes service-bindings create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/bindings`, + pathParams: { "prefix-id": String(argv["prefix-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + cidr: resolveFileToken( + argv["cidr"] as string | undefined, + "cidr", + "text" + ), + service_id: resolveFileToken( + argv["service-id"] as string | undefined, + "service-id", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + prefix_id: argv["prefix-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + cidr: resolveFileToken( + argv["cidr"] as string | undefined, + "cidr", + "text" + ), + service_id: resolveFileToken( + argv["service-id"] as string | undefined, + "service-id", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + prefix_id: argv["prefix-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/create.ts b/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/create.ts index 016a5f2fa4..9de30bb6f0 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/create.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/create.ts @@ -1,157 +1,56 @@ -import operation from "../../../_operations/addressing/prefixes/service-bindings/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing prefixes service-bindings create \n\nCreates a new Service Binding, routing traffic to IPs within the given CIDR to a service running on Cloudflare's network. **NOTE:** The first Service Binding created for an IP Prefix must exactly match the IP Prefix's CIDR. Subsequent Service Bindings may be created with a more-specific CIDR. Refer to the [Service Bindings Documentation](https://developers.cloudflare.com/byoip/service-bindings/) for compatibility details." - ) - .positional("prefix-id", { - type: "string", - description: "Identifier of an IP Prefix.", - demandOption: true, - }) - .option("cidr", { - type: "string", - description: "IP Prefix in Classless Inter-Domain Routing format.", - }) - .option("service-id", { - type: "string", - description: +const parameters = { + flags: { + cidr: { + kind: "parsed", + brief: "IP Prefix in Classless Inter-Domain Routing format.", + optional: true, + parse: String, + }, + "service-id": { + kind: "parsed", + brief: "Identifier of a Service on the Cloudflare network. Available services and their IDs may be found in the\n**List Services** endpoint.\n", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "prefix-id", + brief: "Identifier of an IP Prefix.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Create Service Binding", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing prefixes service-bindings create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["cidr"] === undefined) { - argv["cidr"] = await promptForRequiredField( - "cidr", - "IP Prefix in Classless Inter-Domain Routing format." - ); - } - if (argv["service-id"] === undefined) { - argv["service-id"] = await promptForRequiredField( - "service-id", - "Identifier of a Service on the Cloudflare network. Available services and their IDs may be found in the **List Services** endpoint. " - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing prefixes service-bindings create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/bindings`, - pathParams: { "prefix-id": String(argv["prefix-id"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - cidr: resolveFileToken( - argv["cidr"] as string | undefined, - "cidr", - "text" - ), - service_id: resolveFileToken( - argv["service-id"] as string | undefined, - "service-id", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - prefix_id: argv["prefix-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - cidr: resolveFileToken( - argv["cidr"] as string | undefined, - "cidr", - "text" - ), - service_id: resolveFileToken( - argv["service-id"] as string | undefined, - "service-id", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - prefix_id: argv["prefix-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 addressing prefixes service-bindings create \n\nCreates a new Service Binding, routing traffic to IPs within the given CIDR to a service running on Cloudflare's network. **NOTE:** The first Service Binding created for an IP Prefix must exactly match the IP Prefix's CIDR. Subsequent Service Bindings may be created with a more-specific CIDR. Refer to the [Service Bindings Documentation](https://developers.cloudflare.com/byoip/service-bindings/) for compatibility details.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/delete.handler.ts b/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/delete.handler.ts new file mode 100644 index 0000000000..e632338739 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/delete.handler.ts @@ -0,0 +1,59 @@ +import operation from "../../../_operations/addressing/prefixes/service-bindings/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing prefixes service-bindings delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing prefixes service-bindings delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/bindings/${argv["binding-id"] == null ? "" : encodeURIComponent(String(argv["binding-id"]))}`, + pathParams: { + "prefix-id": String(argv["prefix-id"] ?? ""), + "binding-id": String(argv["binding-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + prefix_id: argv["prefix-id"], + binding_id: argv["binding-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/delete.ts b/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/delete.ts index bda77dfa80..09934ded97 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/delete.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/delete.ts @@ -1,100 +1,48 @@ -import operation from "../../../_operations/addressing/prefixes/service-bindings/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing prefixes service-bindings delete \n\nDelete a Service Binding" - ) - .positional("binding-id", { - type: "string", - description: "Identifier of a Service Binding.", - demandOption: true, - }) - .option("prefix-id", { - type: "string", - description: "Identifier of an IP Prefix.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "prefix-id": { + kind: "parsed", + brief: "Identifier of an IP Prefix.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "binding-id", + brief: "Identifier of a Service Binding.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete Service Binding", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing prefixes service-bindings delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing prefixes service-bindings delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/bindings/${argv["binding-id"] == null ? "" : encodeURIComponent(String(argv["binding-id"]))}`, - pathParams: { - "prefix-id": String(argv["prefix-id"] ?? ""), - "binding-id": String(argv["binding-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - prefix_id: argv["prefix-id"], - binding_id: argv["binding-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 addressing prefixes service-bindings delete \n\nDelete a Service Binding", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/get.handler.ts b/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/get.handler.ts new file mode 100644 index 0000000000..e0ae59b105 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/get.handler.ts @@ -0,0 +1,53 @@ +import operation from "../../../_operations/addressing/prefixes/service-bindings/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing prefixes service-bindings get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing prefixes service-bindings get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/bindings/${argv["binding-id"] == null ? "" : encodeURIComponent(String(argv["binding-id"]))}`, + pathParams: { + "prefix-id": String(argv["prefix-id"] ?? ""), + "binding-id": String(argv["binding-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + prefix_id: argv["prefix-id"], + binding_id: argv["binding-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/get.ts b/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/get.ts index 34b7ae169e..a0ede1ff8b 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/get.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/get.ts @@ -1,88 +1,42 @@ -import operation from "../../../_operations/addressing/prefixes/service-bindings/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing prefixes service-bindings get \n\nFetch a single Service Binding" - ) - .positional("binding-id", { - type: "string", - description: "Identifier of a Service Binding.", - demandOption: true, - }) - .option("prefix-id", { - type: "string", - description: "Identifier of an IP Prefix.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "prefix-id": { + kind: "parsed", + brief: "Identifier of an IP Prefix.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "binding-id", + brief: "Identifier of a Service Binding.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get Service Binding", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing prefixes service-bindings get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing prefixes service-bindings get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/bindings/${argv["binding-id"] == null ? "" : encodeURIComponent(String(argv["binding-id"]))}`, - pathParams: { - "prefix-id": String(argv["prefix-id"] ?? ""), - "binding-id": String(argv["binding-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - prefix_id: argv["prefix-id"], - binding_id: argv["binding-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 addressing prefixes service-bindings get \n\nFetch a single Service Binding", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/index.ts b/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/index.ts index 49a6e5a1bf..bd029dad03 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/index.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/index.ts @@ -2,27 +2,22 @@ import $create from "./create.js"; import $delete from "./delete.js"; import $get from "./get.js"; import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * service-bindings command group * @generated from apis/overlays/addressing.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "service-bindings", describe: "Operations for prefixes.service-bindings", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .command($list) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/list.handler.ts b/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/list.handler.ts new file mode 100644 index 0000000000..e7cb68effe --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/list.handler.ts @@ -0,0 +1,49 @@ +import operation from "../../../_operations/addressing/prefixes/service-bindings/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing prefixes service-bindings list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing prefixes service-bindings list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/bindings`, + pathParams: { "prefix-id": String(argv["prefix-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + prefix_id: argv["prefix-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/list.ts b/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/list.ts index 483fddae06..95f85ab884 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/list.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/service-bindings/list.ts @@ -1,79 +1,36 @@ -import operation from "../../../_operations/addressing/prefixes/service-bindings/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing prefixes service-bindings list\n\nList the Cloudflare services this prefix is currently bound to. Traffic sent to an address within an IP prefix will be routed to the Cloudflare service of the most-specific Service Binding matching the address. **Example:** binding `192.0.2.0/24` to Cloudflare Magic Transit and `192.0.2.1/32` to the Cloudflare CDN would route traffic for `192.0.2.1` to the CDN, and traffic for all other IPs in the prefix to Cloudflare Magic Transit." - ) - .option("prefix-id", { - type: "string", - description: "Identifier of an IP Prefix.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "prefix-id": { + kind: "parsed", + brief: "Identifier of an IP Prefix.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Service Bindings", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing prefixes service-bindings list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing prefixes service-bindings list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/bindings`, - pathParams: { "prefix-id": String(argv["prefix-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - prefix_id: argv["prefix-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 addressing prefixes service-bindings list\n\nList the Cloudflare services this prefix is currently bound to. Traffic sent to an address within an IP prefix will be routed to the Cloudflare service of the most-specific Service Binding matching the address. **Example:** binding `192.0.2.0/24` to Cloudflare Magic Transit and `192.0.2.1/32` to the Cloudflare CDN would route traffic for `192.0.2.1` to the CDN, and traffic for all other IPs in the prefix to Cloudflare Magic Transit.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/validate/create.handler.ts b/packages/cli/src/commands/_generated/addressing/prefixes/validate/create.handler.ts new file mode 100644 index 0000000000..fc0b53bff8 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/prefixes/validate/create.handler.ts @@ -0,0 +1,49 @@ +import operation from "../../../_operations/addressing/prefixes/validate/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing prefixes validate create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing prefixes validate create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/validate`, + pathParams: { "prefix-id": String(argv["prefix-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Creating`, async () => + client.send(operation, { + account_id: accountId, + prefix_id: argv["prefix-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/validate/create.ts b/packages/cli/src/commands/_generated/addressing/prefixes/validate/create.ts index 397860e262..b1e251bf59 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/validate/create.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/validate/create.ts @@ -1,79 +1,37 @@ -import operation from "../../../_operations/addressing/prefixes/validate/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing prefixes validate create \n\nTriggers a new prefix validation. The checks run asynchronously and include IRR, RPKI, prefix ownership, and, when applicable, ASN ownership and Autonomous System Provider Authorization (ASPA). Use Prefix Details to monitor the results. Approval does not advertise the prefix or activate traffic." - ) - .positional("prefix-id", { - type: "string", - description: "Identifier of an IP Prefix.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "prefix-id", + brief: "Identifier of an IP Prefix.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Validate Prefix", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing prefixes validate create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing prefixes validate create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/prefixes/${argv["prefix-id"] == null ? "" : encodeURIComponent(String(argv["prefix-id"]))}/validate`, - pathParams: { "prefix-id": String(argv["prefix-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Creating`, async () => - client.send(operation, { - account_id: accountId, - prefix_id: argv["prefix-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 addressing prefixes validate create \n\nTriggers a new prefix validation. The checks run asynchronously and include IRR, RPKI, prefix ownership, and, when applicable, ASN ownership and Autonomous System Provider Authorization (ASPA). Use Prefix Details to monitor the results. Approval does not advertise the prefix or activate traffic.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/prefixes/validate/index.ts b/packages/cli/src/commands/_generated/addressing/prefixes/validate/index.ts index be501cbd79..784742f068 100644 --- a/packages/cli/src/commands/_generated/addressing/prefixes/validate/index.ts +++ b/packages/cli/src/commands/_generated/addressing/prefixes/validate/index.ts @@ -1,22 +1,17 @@ import $create from "./create.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * validate command group * @generated from apis/overlays/addressing.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "validate", describe: "Operations for prefixes.validate", - builder: (yargs) => { - return yargs - .command($create) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/regional-hostnames/create.handler.ts b/packages/cli/src/commands/_generated/addressing/regional-hostnames/create.handler.ts new file mode 100644 index 0000000000..92d23af755 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/regional-hostnames/create.handler.ts @@ -0,0 +1,112 @@ +import operation from "../../_operations/addressing/regional-hostnames/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing regional-hostnames create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["hostname"] === undefined) { + argv["hostname"] = await promptForRequiredField( + "hostname", + "DNS hostname to be regionalized, must be a subdomain of the zone. Wildcards are supported for one level, e.g \`*.example.com\`" + ); + } + if (argv["region-key"] === undefined) { + argv["region-key"] = await promptForRequiredField( + "region-key", + "Identifying key for the region" + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + formatDryRun({ + command: "cf addressing regional-hostnames create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/addressing/regional_hostnames`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + hostname: resolveFileToken( + argv["hostname"] as string | undefined, + "hostname", + "text" + ), + region_key: resolveFileToken( + argv["region-key"] as string | undefined, + "region-key", + "text" + ), + routing: resolveFileToken( + argv["routing"] as string | undefined, + "routing", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + hostname: resolveFileToken( + argv["hostname"] as string | undefined, + "hostname", + "text" + ), + region_key: resolveFileToken( + argv["region-key"] as string | undefined, + "region-key", + "text" + ), + routing: resolveFileToken( + argv["routing"] as string | undefined, + "routing", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/regional-hostnames/create.ts b/packages/cli/src/commands/_generated/addressing/regional-hostnames/create.ts index 75caa581a5..cdd6bed0ac 100644 --- a/packages/cli/src/commands/_generated/addressing/regional-hostnames/create.ts +++ b/packages/cli/src/commands/_generated/addressing/regional-hostnames/create.ts @@ -1,158 +1,56 @@ -import operation from "../../_operations/addressing/regional-hostnames/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing regional-hostnames create\n\nCreate a new Regional Hostname entry. Cloudflare will only use data centers that are physically located within the chosen region to decrypt and service HTTPS traffic. Learn more about [Regional Services](https://developers.cloudflare.com/data-localization/regional-services/get-started/)." - ) - .option("hostname", { - type: "string", - description: +const parameters = { + flags: { + hostname: { + kind: "parsed", + brief: "DNS hostname to be regionalized, must be a subdomain of the zone. Wildcards are supported for one level, e.g `*.example.com`", - }) - .option("region-key", { - type: "string", - description: "Identifying key for the region", - }) - .option("routing", { - type: "string", - description: - "Configure which routing method to use for the regional hostname", + optional: true, + parse: String, + }, + "region-key": { + kind: "parsed", + brief: "Identifying key for the region", + optional: true, + parse: String, + }, + routing: { + kind: "parsed", + brief: "Configure which routing method to use for the regional hostname", default: "dns", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Create Regional Hostname", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing regional-hostnames create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["hostname"] === undefined) { - argv["hostname"] = await promptForRequiredField( - "hostname", - "DNS hostname to be regionalized, must be a subdomain of the zone. Wildcards are supported for one level, e.g \`*.example.com\`" - ); - } - if (argv["region-key"] === undefined) { - argv["region-key"] = await promptForRequiredField( - "region-key", - "Identifying key for the region" - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - formatDryRun({ - command: "cf addressing regional-hostnames create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/addressing/regional_hostnames`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - hostname: resolveFileToken( - argv["hostname"] as string | undefined, - "hostname", - "text" - ), - region_key: resolveFileToken( - argv["region-key"] as string | undefined, - "region-key", - "text" - ), - routing: resolveFileToken( - argv["routing"] as string | undefined, - "routing", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - hostname: resolveFileToken( - argv["hostname"] as string | undefined, - "hostname", - "text" - ), - region_key: resolveFileToken( - argv["region-key"] as string | undefined, - "region-key", - "text" - ), - routing: resolveFileToken( - argv["routing"] as string | undefined, - "routing", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 addressing regional-hostnames create\n\nCreate a new Regional Hostname entry. Cloudflare will only use data centers that are physically located within the chosen region to decrypt and service HTTPS traffic. Learn more about [Regional Services](https://developers.cloudflare.com/data-localization/regional-services/get-started/).", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/regional-hostnames/delete.handler.ts b/packages/cli/src/commands/_generated/addressing/regional-hostnames/delete.handler.ts new file mode 100644 index 0000000000..b9af04e8e1 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/regional-hostnames/delete.handler.ts @@ -0,0 +1,51 @@ +import operation from "../../_operations/addressing/regional-hostnames/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing regional-hostnames delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf addressing regional-hostnames delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/addressing/regional_hostnames/${argv["hostname"] == null ? "" : encodeURIComponent(String(argv["hostname"]))}`, + pathParams: { + "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), + hostname: String(argv["hostname"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { zone_id: zoneId, hostname: argv["hostname"] }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/regional-hostnames/delete.ts b/packages/cli/src/commands/_generated/addressing/regional-hostnames/delete.ts index 1eaa5175de..b4031ea279 100644 --- a/packages/cli/src/commands/_generated/addressing/regional-hostnames/delete.ts +++ b/packages/cli/src/commands/_generated/addressing/regional-hostnames/delete.ts @@ -1,91 +1,44 @@ -import operation from "../../_operations/addressing/regional-hostnames/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing regional-hostnames delete \n\nDelete the region configuration for a specific Regional Hostname." - ) - .positional("hostname", { - type: "string", - description: - "DNS hostname to be regionalized, must be a subdomain of the zone. Wildcards are supported for one level, e.g \`*.example.com\`", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "hostname", + brief: + "DNS hostname to be regionalized, must be a subdomain of the zone. Wildcards are supported for one level, e.g \`*.example.com\`", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete Regional Hostname", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing regional-hostnames delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf addressing regional-hostnames delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/addressing/regional_hostnames/${argv["hostname"] == null ? "" : encodeURIComponent(String(argv["hostname"]))}`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - hostname: String(argv["hostname"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - zone_id: zoneId, - hostname: argv["hostname"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 addressing regional-hostnames delete \n\nDelete the region configuration for a specific Regional Hostname.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/regional-hostnames/edit.handler.ts b/packages/cli/src/commands/_generated/addressing/regional-hostnames/edit.handler.ts new file mode 100644 index 0000000000..f06679cefd --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/regional-hostnames/edit.handler.ts @@ -0,0 +1,97 @@ +import operation from "../../_operations/addressing/regional-hostnames/edit.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./edit.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing regional-hostnames edit", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["region-key"] === undefined) { + argv["region-key"] = await promptForRequiredField( + "region-key", + "Identifying key for the region" + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + formatDryRun({ + command: "cf addressing regional-hostnames edit", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/addressing/regional_hostnames/${argv["hostname"] == null ? "" : encodeURIComponent(String(argv["hostname"]))}`, + pathParams: { + "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), + hostname: String(argv["hostname"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + region_key: resolveFileToken( + argv["region-key"] as string | undefined, + "region-key", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + zone_id: zoneId, + hostname: argv["hostname"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + region_key: resolveFileToken( + argv["region-key"] as string | undefined, + "region-key", + "text" + ), + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + zone_id: zoneId, + hostname: argv["hostname"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/regional-hostnames/edit.ts b/packages/cli/src/commands/_generated/addressing/regional-hostnames/edit.ts index 737c1c55fa..aa51901667 100644 --- a/packages/cli/src/commands/_generated/addressing/regional-hostnames/edit.ts +++ b/packages/cli/src/commands/_generated/addressing/regional-hostnames/edit.ts @@ -1,136 +1,50 @@ -import operation from "../../_operations/addressing/regional-hostnames/edit.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * edit command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing regional-hostnames edit \n\nUpdate the configuration for a specific Regional Hostname. Only the region_key of a hostname is mutable." - ) - .positional("hostname", { - type: "string", - description: - "DNS hostname to be regionalized, must be a subdomain of the zone. Wildcards are supported for one level, e.g \`*.example.com\`", - demandOption: true, - }) - .option("region-key", { - type: "string", - description: "Identifying key for the region", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "region-key": { + kind: "parsed", + brief: "Identifying key for the region", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "hostname", + brief: + "DNS hostname to be regionalized, must be a subdomain of the zone. Wildcards are supported for one level, e.g \`*.example.com\`", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "edit ", describe: "Update Regional Hostname", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing regional-hostnames edit", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["region-key"] === undefined) { - argv["region-key"] = await promptForRequiredField( - "region-key", - "Identifying key for the region" - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - formatDryRun({ - command: "cf addressing regional-hostnames edit", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/addressing/regional_hostnames/${argv["hostname"] == null ? "" : encodeURIComponent(String(argv["hostname"]))}`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - hostname: String(argv["hostname"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - region_key: resolveFileToken( - argv["region-key"] as string | undefined, - "region-key", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - zone_id: zoneId, - hostname: argv["hostname"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - region_key: resolveFileToken( - argv["region-key"] as string | undefined, - "region-key", - "text" - ), - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - zone_id: zoneId, - hostname: argv["hostname"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 addressing regional-hostnames edit \n\nUpdate the configuration for a specific Regional Hostname. Only the region_key of a hostname is mutable.", + ...parameters, + loader: () => import("./edit.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/regional-hostnames/get.handler.ts b/packages/cli/src/commands/_generated/addressing/regional-hostnames/get.handler.ts new file mode 100644 index 0000000000..085ac6c3eb --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/regional-hostnames/get.handler.ts @@ -0,0 +1,45 @@ +import operation from "../../_operations/addressing/regional-hostnames/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing regional-hostnames get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf addressing regional-hostnames get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/addressing/regional_hostnames/${argv["hostname"] == null ? "" : encodeURIComponent(String(argv["hostname"]))}`, + pathParams: { + "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), + hostname: String(argv["hostname"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { zone_id: zoneId, hostname: argv["hostname"] }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/regional-hostnames/get.ts b/packages/cli/src/commands/_generated/addressing/regional-hostnames/get.ts index 1b71125547..2f0a39a94a 100644 --- a/packages/cli/src/commands/_generated/addressing/regional-hostnames/get.ts +++ b/packages/cli/src/commands/_generated/addressing/regional-hostnames/get.ts @@ -1,79 +1,38 @@ -import operation from "../../_operations/addressing/regional-hostnames/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing regional-hostnames get \n\nFetch the configuration for a specific Regional Hostname, within a zone." - ) - .positional("hostname", { - type: "string", - description: - "DNS hostname to be regionalized, must be a subdomain of the zone. Wildcards are supported for one level, e.g \`*.example.com\`", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "hostname", + brief: + "DNS hostname to be regionalized, must be a subdomain of the zone. Wildcards are supported for one level, e.g \`*.example.com\`", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Fetch Regional Hostname", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing regional-hostnames get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf addressing regional-hostnames get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/addressing/regional_hostnames/${argv["hostname"] == null ? "" : encodeURIComponent(String(argv["hostname"]))}`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - hostname: String(argv["hostname"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - zone_id: zoneId, - hostname: argv["hostname"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 addressing regional-hostnames get \n\nFetch the configuration for a specific Regional Hostname, within a zone.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/regional-hostnames/index.ts b/packages/cli/src/commands/_generated/addressing/regional-hostnames/index.ts index 2574e769c3..a86eb0a96e 100644 --- a/packages/cli/src/commands/_generated/addressing/regional-hostnames/index.ts +++ b/packages/cli/src/commands/_generated/addressing/regional-hostnames/index.ts @@ -4,29 +4,24 @@ import $edit from "./edit.js"; import $get from "./get.js"; import $list from "./list.js"; import $regions from "./regions/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * regional-hostnames command group * @generated from apis/overlays/addressing.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "regional-hostnames", describe: "Operations for regional-hostnames", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($edit) - .command($get) - .command($list) - .command($regions) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + edit: $edit, + get: $get, + list: $list, + regions: $regions, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/regional-hostnames/list.handler.ts b/packages/cli/src/commands/_generated/addressing/regional-hostnames/list.handler.ts new file mode 100644 index 0000000000..6a7ac19807 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/regional-hostnames/list.handler.ts @@ -0,0 +1,42 @@ +import operation from "../../_operations/addressing/regional-hostnames/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing regional-hostnames list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf addressing regional-hostnames list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/addressing/regional_hostnames`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/regional-hostnames/list.ts b/packages/cli/src/commands/_generated/addressing/regional-hostnames/list.ts index 066ca72c3a..7b60b98d02 100644 --- a/packages/cli/src/commands/_generated/addressing/regional-hostnames/list.ts +++ b/packages/cli/src/commands/_generated/addressing/regional-hostnames/list.ts @@ -1,69 +1,31 @@ -import operation from "../../_operations/addressing/regional-hostnames/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing regional-hostnames list\n\nList all Regional Hostnames within a zone." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Regional Hostnames", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing regional-hostnames list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf addressing regional-hostnames list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/addressing/regional_hostnames`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 addressing regional-hostnames list\n\nList all Regional Hostnames within a zone.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/regional-hostnames/regions/index.ts b/packages/cli/src/commands/_generated/addressing/regional-hostnames/regions/index.ts index b4968f1944..23905475cf 100644 --- a/packages/cli/src/commands/_generated/addressing/regional-hostnames/regions/index.ts +++ b/packages/cli/src/commands/_generated/addressing/regional-hostnames/regions/index.ts @@ -1,20 +1,17 @@ import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * regions command group * @generated from apis/overlays/addressing.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "regions", describe: "Operations for regional-hostnames.regions", - builder: (yargs) => { - return yargs.command($list).demandCommand(1, "Please specify a subcommand"); + routes: { + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/regional-hostnames/regions/list.handler.ts b/packages/cli/src/commands/_generated/addressing/regional-hostnames/regions/list.handler.ts new file mode 100644 index 0000000000..f5068b1134 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/regional-hostnames/regions/list.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../../_operations/addressing/regional-hostnames/regions/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing regional-hostnames regions list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing regional-hostnames regions list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/regional_hostnames/regions`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/regional-hostnames/regions/list.ts b/packages/cli/src/commands/_generated/addressing/regional-hostnames/regions/list.ts index 12eb02f812..ecccb3cd5d 100644 --- a/packages/cli/src/commands/_generated/addressing/regional-hostnames/regions/list.ts +++ b/packages/cli/src/commands/_generated/addressing/regional-hostnames/regions/list.ts @@ -1,71 +1,31 @@ -import operation from "../../../_operations/addressing/regional-hostnames/regions/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing regional-hostnames regions list\n\nList all Regional Services regions available for use by this account." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Regions", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing regional-hostnames regions list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing regional-hostnames regions list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/regional_hostnames/regions`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 addressing regional-hostnames regions list\n\nList all Regional Services regions available for use by this account.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/services/index.ts b/packages/cli/src/commands/_generated/addressing/services/index.ts index a34df479c2..031849f62e 100644 --- a/packages/cli/src/commands/_generated/addressing/services/index.ts +++ b/packages/cli/src/commands/_generated/addressing/services/index.ts @@ -1,20 +1,17 @@ import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * services command group * @generated from apis/overlays/addressing.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "services", describe: "Operations for services", - builder: (yargs) => { - return yargs.command($list).demandCommand(1, "Please specify a subcommand"); + routes: { + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/addressing/services/list.handler.ts b/packages/cli/src/commands/_generated/addressing/services/list.handler.ts new file mode 100644 index 0000000000..40e0e1a953 --- /dev/null +++ b/packages/cli/src/commands/_generated/addressing/services/list.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/addressing/services/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "addressing services list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf addressing services list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/services`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/addressing/services/list.ts b/packages/cli/src/commands/_generated/addressing/services/list.ts index 805251173c..76540f165a 100644 --- a/packages/cli/src/commands/_generated/addressing/services/list.ts +++ b/packages/cli/src/commands/_generated/addressing/services/list.ts @@ -1,71 +1,31 @@ -import operation from "../../_operations/addressing/services/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/addressing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 addressing services list\n\nBring-Your-Own IP (BYOIP) prefixes onboarded to Cloudflare must be bound to a service running on the Cloudflare network to enable a Cloudflare product on the IP addresses. This endpoint can be used as a reference of available services on the Cloudflare network, and their service IDs." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Services", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "addressing services list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf addressing services list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/addressing/services`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 addressing services list\n\nBring-Your-Own IP (BYOIP) prefixes onboarded to Cloudflare must be bound to a service running on the Cloudflare network to enable a Cloudflare product on the IP addresses. This endpoint can be used as a reference of available services on the Cloudflare network, and their service IDs.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/agent-memory/create-namespace.handler.ts b/packages/cli/src/commands/_generated/agent-memory/create-namespace.handler.ts new file mode 100644 index 0000000000..e6e4b63abd --- /dev/null +++ b/packages/cli/src/commands/_generated/agent-memory/create-namespace.handler.ts @@ -0,0 +1,90 @@ +import operation from "../_operations/agent-memory/create-namespace.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create-namespace.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "agent-memory create-namespace", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField( + "name", + "Namespace name." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf agent-memory create-namespace", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/agent-memory/create-namespace.ts b/packages/cli/src/commands/_generated/agent-memory/create-namespace.ts index c5ea3ae258..1d51a087fe 100644 --- a/packages/cli/src/commands/_generated/agent-memory/create-namespace.ts +++ b/packages/cli/src/commands/_generated/agent-memory/create-namespace.ts @@ -1,120 +1,43 @@ -import operation from "../_operations/agent-memory/create-namespace.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create-namespace command * @generated from apis/overlays/agent-memory.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 agent-memory create-namespace\n\nCreates a new memory namespace owned by the account." - ) - .option("name", { type: "string", description: "Namespace name." }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + name: { + kind: "parsed", + brief: "Namespace name.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create-namespace", describe: "Create a namespace", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "agent-memory create-namespace", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "Namespace name." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf agent-memory create-namespace", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 agent-memory create-namespace\n\nCreates a new memory namespace owned by the account.", + ...parameters, + loader: () => import("./create-namespace.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/agent-memory/delete-memory.handler.ts b/packages/cli/src/commands/_generated/agent-memory/delete-memory.handler.ts new file mode 100644 index 0000000000..3cfd7492bf --- /dev/null +++ b/packages/cli/src/commands/_generated/agent-memory/delete-memory.handler.ts @@ -0,0 +1,66 @@ +import operation from "../_operations/agent-memory/delete-memory.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete-memory.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "agent-memory delete-memory", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf agent-memory delete-memory", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces/${argv["namespace-name"] == null ? "" : encodeURIComponent(String(argv["namespace-name"]))}/profiles/${argv["profile-name"] == null ? "" : encodeURIComponent(String(argv["profile-name"]))}/memories/${argv["memory-id"] == null ? "" : encodeURIComponent(String(argv["memory-id"]))}`, + pathParams: { + "namespace-name": String(argv["namespace-name"] ?? ""), + "profile-name": String(argv["profile-name"] ?? ""), + "memory-id": String(argv["memory-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This operation deletes the memory and any source messages linked to it.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + namespace_name: argv["namespace-name"], + profile_name: argv["profile-name"], + memory_id: argv["memory-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/agent-memory/delete-memory.ts b/packages/cli/src/commands/_generated/agent-memory/delete-memory.ts index 55b55d1c43..88a529b36b 100644 --- a/packages/cli/src/commands/_generated/agent-memory/delete-memory.ts +++ b/packages/cli/src/commands/_generated/agent-memory/delete-memory.ts @@ -1,112 +1,45 @@ -import operation from "../_operations/agent-memory/delete-memory.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete-memory command * @generated from apis/overlays/agent-memory.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 agent-memory delete-memory \n\nDeletes a memory by ID. Removes the memory and any source messages linked to it. Returns the deleted memory." - ) - .positional("memory-id", { - type: "string", - description: "Memory Identifier.", - demandOption: true, - }) - .option("namespace-name", { - type: "string", - description: "Namespace name.", - demandOption: true, - }) - .option("profile-name", { - type: "string", - description: "Profile name.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "namespace-name": { + kind: "parsed", + brief: "Namespace name.", + parse: String, + }, + "profile-name": { kind: "parsed", brief: "Profile name.", parse: String }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "memory-id", brief: "Memory Identifier.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete-memory ", describe: "Delete a memory", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "agent-memory delete-memory", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf agent-memory delete-memory", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces/${argv["namespace-name"] == null ? "" : encodeURIComponent(String(argv["namespace-name"]))}/profiles/${argv["profile-name"] == null ? "" : encodeURIComponent(String(argv["profile-name"]))}/memories/${argv["memory-id"] == null ? "" : encodeURIComponent(String(argv["memory-id"]))}`, - pathParams: { - "namespace-name": String(argv["namespace-name"] ?? ""), - "profile-name": String(argv["profile-name"] ?? ""), - "memory-id": String(argv["memory-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This operation deletes the memory and any source messages linked to it.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - namespace_name: argv["namespace-name"], - profile_name: argv["profile-name"], - memory_id: argv["memory-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 agent-memory delete-memory \n\nDeletes a memory by ID. Removes the memory and any source messages linked to it. Returns the deleted memory.", + ...parameters, + loader: () => import("./delete-memory.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/agent-memory/delete-namespace.handler.ts b/packages/cli/src/commands/_generated/agent-memory/delete-namespace.handler.ts new file mode 100644 index 0000000000..eb0b29c765 --- /dev/null +++ b/packages/cli/src/commands/_generated/agent-memory/delete-namespace.handler.ts @@ -0,0 +1,62 @@ +import operation from "../_operations/agent-memory/delete-namespace.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete-namespace.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "agent-memory delete-namespace", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf agent-memory delete-namespace", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces/${argv["namespace-name"] == null ? "" : encodeURIComponent(String(argv["namespace-name"]))}`, + pathParams: { + "namespace-name": String(argv["namespace-name"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This operation deletes the namespace along with all memory profiles, memories, and sessions it contains.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + namespace_name: argv["namespace-name"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/agent-memory/delete-namespace.ts b/packages/cli/src/commands/_generated/agent-memory/delete-namespace.ts index 414cf9906e..dbc60e2db8 100644 --- a/packages/cli/src/commands/_generated/agent-memory/delete-namespace.ts +++ b/packages/cli/src/commands/_generated/agent-memory/delete-namespace.ts @@ -1,98 +1,39 @@ -import operation from "../_operations/agent-memory/delete-namespace.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete-namespace command * @generated from apis/overlays/agent-memory.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 agent-memory delete-namespace \n\nDeletes a namespace." - ) - .positional("namespace-name", { - type: "string", - description: "Namespace name.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "namespace-name", brief: "Namespace name.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete-namespace ", describe: "Delete a namespace", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "agent-memory delete-namespace", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf agent-memory delete-namespace", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces/${argv["namespace-name"] == null ? "" : encodeURIComponent(String(argv["namespace-name"]))}`, - pathParams: { - "namespace-name": String(argv["namespace-name"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This operation deletes the namespace along with all memory profiles, memories, and sessions it contains.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - namespace_name: argv["namespace-name"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 agent-memory delete-namespace \n\nDeletes a namespace.", + ...parameters, + loader: () => import("./delete-namespace.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/agent-memory/delete-profile.handler.ts b/packages/cli/src/commands/_generated/agent-memory/delete-profile.handler.ts new file mode 100644 index 0000000000..aff1bae929 --- /dev/null +++ b/packages/cli/src/commands/_generated/agent-memory/delete-profile.handler.ts @@ -0,0 +1,64 @@ +import operation from "../_operations/agent-memory/delete-profile.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete-profile.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "agent-memory delete-profile", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf agent-memory delete-profile", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces/${argv["namespace-name"] == null ? "" : encodeURIComponent(String(argv["namespace-name"]))}/profiles/${argv["profile-name"] == null ? "" : encodeURIComponent(String(argv["profile-name"]))}`, + pathParams: { + "namespace-name": String(argv["namespace-name"] ?? ""), + "profile-name": String(argv["profile-name"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This operation deletes the profile along with all of its memories and messages.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + namespace_name: argv["namespace-name"], + profile_name: argv["profile-name"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/agent-memory/delete-profile.ts b/packages/cli/src/commands/_generated/agent-memory/delete-profile.ts index e6fc58644f..ffbf773cf4 100644 --- a/packages/cli/src/commands/_generated/agent-memory/delete-profile.ts +++ b/packages/cli/src/commands/_generated/agent-memory/delete-profile.ts @@ -1,105 +1,44 @@ -import operation from "../_operations/agent-memory/delete-profile.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete-profile command * @generated from apis/overlays/agent-memory.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 agent-memory delete-profile \n\nMarks a profile for deletion." - ) - .positional("profile-name", { - type: "string", - description: "Profile name.", - demandOption: true, - }) - .option("namespace-name", { - type: "string", - description: "Namespace name.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "namespace-name": { + kind: "parsed", + brief: "Namespace name.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "profile-name", brief: "Profile name.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete-profile ", describe: "Delete a profile", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "agent-memory delete-profile", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf agent-memory delete-profile", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces/${argv["namespace-name"] == null ? "" : encodeURIComponent(String(argv["namespace-name"]))}/profiles/${argv["profile-name"] == null ? "" : encodeURIComponent(String(argv["profile-name"]))}`, - pathParams: { - "namespace-name": String(argv["namespace-name"] ?? ""), - "profile-name": String(argv["profile-name"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This operation deletes the profile along with all of its memories and messages.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - namespace_name: argv["namespace-name"], - profile_name: argv["profile-name"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 agent-memory delete-profile \n\nMarks a profile for deletion.", + ...parameters, + loader: () => import("./delete-profile.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/agent-memory/delete-session.handler.ts b/packages/cli/src/commands/_generated/agent-memory/delete-session.handler.ts new file mode 100644 index 0000000000..0bc2ef304c --- /dev/null +++ b/packages/cli/src/commands/_generated/agent-memory/delete-session.handler.ts @@ -0,0 +1,66 @@ +import operation from "../_operations/agent-memory/delete-session.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete-session.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "agent-memory delete-session", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf agent-memory delete-session", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces/${argv["namespace-name"] == null ? "" : encodeURIComponent(String(argv["namespace-name"]))}/profiles/${argv["profile-name"] == null ? "" : encodeURIComponent(String(argv["profile-name"]))}/sessions/${argv["session-id"] == null ? "" : encodeURIComponent(String(argv["session-id"]))}`, + pathParams: { + "namespace-name": String(argv["namespace-name"] ?? ""), + "profile-name": String(argv["profile-name"] ?? ""), + "session-id": String(argv["session-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This operation deletes all memories and messages tagged with this session ID.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + namespace_name: argv["namespace-name"], + profile_name: argv["profile-name"], + session_id: argv["session-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/agent-memory/delete-session.ts b/packages/cli/src/commands/_generated/agent-memory/delete-session.ts index 08e7538995..c7073aedf8 100644 --- a/packages/cli/src/commands/_generated/agent-memory/delete-session.ts +++ b/packages/cli/src/commands/_generated/agent-memory/delete-session.ts @@ -1,112 +1,45 @@ -import operation from "../_operations/agent-memory/delete-session.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete-session command * @generated from apis/overlays/agent-memory.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 agent-memory delete-session \n\nMarks all memories and messages in a profile that are tagged with the given session ID for deletion." - ) - .positional("session-id", { - type: "string", - description: "Session identifier.", - demandOption: true, - }) - .option("namespace-name", { - type: "string", - description: "Namespace name.", - demandOption: true, - }) - .option("profile-name", { - type: "string", - description: "Profile name.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "namespace-name": { + kind: "parsed", + brief: "Namespace name.", + parse: String, + }, + "profile-name": { kind: "parsed", brief: "Profile name.", parse: String }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "session-id", brief: "Session identifier.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete-session ", describe: "Delete a session", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "agent-memory delete-session", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf agent-memory delete-session", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces/${argv["namespace-name"] == null ? "" : encodeURIComponent(String(argv["namespace-name"]))}/profiles/${argv["profile-name"] == null ? "" : encodeURIComponent(String(argv["profile-name"]))}/sessions/${argv["session-id"] == null ? "" : encodeURIComponent(String(argv["session-id"]))}`, - pathParams: { - "namespace-name": String(argv["namespace-name"] ?? ""), - "profile-name": String(argv["profile-name"] ?? ""), - "session-id": String(argv["session-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This operation deletes all memories and messages tagged with this session ID.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - namespace_name: argv["namespace-name"], - profile_name: argv["profile-name"], - session_id: argv["session-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 agent-memory delete-session \n\nMarks all memories and messages in a profile that are tagged with the given session ID for deletion.", + ...parameters, + loader: () => import("./delete-session.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/agent-memory/get-memory.handler.ts b/packages/cli/src/commands/_generated/agent-memory/get-memory.handler.ts new file mode 100644 index 0000000000..6411bf4d08 --- /dev/null +++ b/packages/cli/src/commands/_generated/agent-memory/get-memory.handler.ts @@ -0,0 +1,55 @@ +import operation from "../_operations/agent-memory/get-memory.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get-memory.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "agent-memory get-memory", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf agent-memory get-memory", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces/${argv["namespace-name"] == null ? "" : encodeURIComponent(String(argv["namespace-name"]))}/profiles/${argv["profile-name"] == null ? "" : encodeURIComponent(String(argv["profile-name"]))}/memories/${argv["memory-id"] == null ? "" : encodeURIComponent(String(argv["memory-id"]))}`, + pathParams: { + "namespace-name": String(argv["namespace-name"] ?? ""), + "profile-name": String(argv["profile-name"] ?? ""), + "memory-id": String(argv["memory-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + namespace_name: argv["namespace-name"], + profile_name: argv["profile-name"], + memory_id: argv["memory-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/agent-memory/get-memory.ts b/packages/cli/src/commands/_generated/agent-memory/get-memory.ts index cfdb475b9f..a98f94c17e 100644 --- a/packages/cli/src/commands/_generated/agent-memory/get-memory.ts +++ b/packages/cli/src/commands/_generated/agent-memory/get-memory.ts @@ -1,95 +1,38 @@ -import operation from "../_operations/agent-memory/get-memory.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get-memory command * @generated from apis/overlays/agent-memory.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 agent-memory get-memory \n\nRetrieves a memory by ID." - ) - .positional("memory-id", { - type: "string", - description: "Memory Identifier.", - demandOption: true, - }) - .option("namespace-name", { - type: "string", - description: "Namespace name.", - demandOption: true, - }) - .option("profile-name", { - type: "string", - description: "Profile name.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "namespace-name": { + kind: "parsed", + brief: "Namespace name.", + parse: String, + }, + "profile-name": { kind: "parsed", brief: "Profile name.", parse: String }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "memory-id", brief: "Memory Identifier.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get-memory ", describe: "Get a memory", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "agent-memory get-memory", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf agent-memory get-memory", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces/${argv["namespace-name"] == null ? "" : encodeURIComponent(String(argv["namespace-name"]))}/profiles/${argv["profile-name"] == null ? "" : encodeURIComponent(String(argv["profile-name"]))}/memories/${argv["memory-id"] == null ? "" : encodeURIComponent(String(argv["memory-id"]))}`, - pathParams: { - "namespace-name": String(argv["namespace-name"] ?? ""), - "profile-name": String(argv["profile-name"] ?? ""), - "memory-id": String(argv["memory-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - namespace_name: argv["namespace-name"], - profile_name: argv["profile-name"], - memory_id: argv["memory-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: "$0 agent-memory get-memory \n\nRetrieves a memory by ID.", + ...parameters, + loader: () => import("./get-memory.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/agent-memory/get-namespace.handler.ts b/packages/cli/src/commands/_generated/agent-memory/get-namespace.handler.ts new file mode 100644 index 0000000000..1db90dfb78 --- /dev/null +++ b/packages/cli/src/commands/_generated/agent-memory/get-namespace.handler.ts @@ -0,0 +1,51 @@ +import operation from "../_operations/agent-memory/get-namespace.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get-namespace.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "agent-memory get-namespace", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf agent-memory get-namespace", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces/${argv["namespace-name"] == null ? "" : encodeURIComponent(String(argv["namespace-name"]))}`, + pathParams: { + "namespace-name": String(argv["namespace-name"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + namespace_name: argv["namespace-name"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/agent-memory/get-namespace.ts b/packages/cli/src/commands/_generated/agent-memory/get-namespace.ts index 96d62880ea..67bd3b1f49 100644 --- a/packages/cli/src/commands/_generated/agent-memory/get-namespace.ts +++ b/packages/cli/src/commands/_generated/agent-memory/get-namespace.ts @@ -1,81 +1,33 @@ -import operation from "../_operations/agent-memory/get-namespace.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get-namespace command * @generated from apis/overlays/agent-memory.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 agent-memory get-namespace \n\nGets a namespace by name." - ) - .positional("namespace-name", { - type: "string", - description: "Namespace name.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "namespace-name", brief: "Namespace name.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get-namespace ", describe: "Get a namespace", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "agent-memory get-namespace", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf agent-memory get-namespace", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces/${argv["namespace-name"] == null ? "" : encodeURIComponent(String(argv["namespace-name"]))}`, - pathParams: { - "namespace-name": String(argv["namespace-name"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - namespace_name: argv["namespace-name"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 agent-memory get-namespace \n\nGets a namespace by name.", + ...parameters, + loader: () => import("./get-namespace.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/agent-memory/index.ts b/packages/cli/src/commands/_generated/agent-memory/index.ts index 3e11e5948d..3c3e02bba2 100644 --- a/packages/cli/src/commands/_generated/agent-memory/index.ts +++ b/packages/cli/src/commands/_generated/agent-memory/index.ts @@ -12,37 +12,32 @@ import $listprofiles from "./list-profiles.js"; import $recall from "./recall.js"; import $remember from "./remember.js"; import $summary from "./summary.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * agent-memory command * @generated from apis/overlays/agent-memory.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "agent-memory", describe: "agent-memory", - builder: (yargs) => { - return yargs - .command($createnamespace) - .command($deletememory) - .command($deletenamespace) - .command($deleteprofile) - .command($deletesession) - .command($getmemory) - .command($getnamespace) - .command($ingest) - .command($listmemories) - .command($listnamespaces) - .command($listprofiles) - .command($recall) - .command($remember) - .command($summary) - .demandCommand(1, "Please specify a subcommand"); + routes: { + "create-namespace": $createnamespace, + "delete-memory": $deletememory, + "delete-namespace": $deletenamespace, + "delete-profile": $deleteprofile, + "delete-session": $deletesession, + "get-memory": $getmemory, + "get-namespace": $getnamespace, + ingest: $ingest, + "list-memories": $listmemories, + "list-namespaces": $listnamespaces, + "list-profiles": $listprofiles, + recall: $recall, + remember: $remember, + summary: $summary, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/agent-memory/ingest.handler.ts b/packages/cli/src/commands/_generated/agent-memory/ingest.handler.ts new file mode 100644 index 0000000000..db7f44aded --- /dev/null +++ b/packages/cli/src/commands/_generated/agent-memory/ingest.handler.ts @@ -0,0 +1,103 @@ +import operation from "../_operations/agent-memory/ingest.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./ingest.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "agent-memory ingest", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["messages"] === undefined) { + throw new Error( + "--messages is required (or pass --body with this field set)." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf agent-memory ingest", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces/${argv["namespace-name"] == null ? "" : encodeURIComponent(String(argv["namespace-name"]))}/profiles/${argv["profile-name"] == null ? "" : encodeURIComponent(String(argv["profile-name"]))}/ingest`, + pathParams: { + "namespace-name": String(argv["namespace-name"] ?? ""), + "profile-name": String(argv["profile-name"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + messages: parseObjectArray(argv["messages"], "messages"), + sessionId: resolveFileToken( + argv["session-id"] as string | undefined, + "session-id", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + namespace_name: argv["namespace-name"], + profile_name: argv["profile-name"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + messages: parseObjectArray(argv["messages"], "messages"), + sessionId: resolveFileToken( + argv["session-id"] as string | undefined, + "session-id", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + namespace_name: argv["namespace-name"], + profile_name: argv["profile-name"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/agent-memory/ingest.ts b/packages/cli/src/commands/_generated/agent-memory/ingest.ts index 833887eac9..c893d93367 100644 --- a/packages/cli/src/commands/_generated/agent-memory/ingest.ts +++ b/packages/cli/src/commands/_generated/agent-memory/ingest.ts @@ -1,151 +1,57 @@ -import operation from "../_operations/agent-memory/ingest.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * ingest command * @generated from apis/overlays/agent-memory.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 agent-memory ingest \n\nProcesses a conversation and extracts structured memories from it. Agent Memory identifies facts, events, instructions, and tasks automatically." - ) - .positional("profile-name", { - type: "string", - description: "Profile name.", - demandOption: true, - }) - .option("namespace-name", { - type: "string", - description: "Namespace name.", - demandOption: true, - }) - .option("messages", { - type: "string", - description: +const parameters = { + flags: { + "namespace-name": { + kind: "parsed", + brief: "Namespace name.", + parse: String, + }, + messages: { + kind: "parsed", + brief: 'Conversation messages to extract memories from. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"content": string, "role": "system" | "user" | "assistant", "timestamp"?: string}]. ? marks optional keys.', - }) - .option("session-id", { - type: "string", - description: "Session identifier.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "session-id": { + kind: "parsed", + brief: "Session identifier.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { placeholder: "profile-name", brief: "Profile name.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "ingest ", describe: "Ingest messages", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "agent-memory ingest", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["messages"] === undefined) { - throw new Error( - "--messages is required (or pass --body with this field set)." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf agent-memory ingest", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces/${argv["namespace-name"] == null ? "" : encodeURIComponent(String(argv["namespace-name"]))}/profiles/${argv["profile-name"] == null ? "" : encodeURIComponent(String(argv["profile-name"]))}/ingest`, - pathParams: { - "namespace-name": String(argv["namespace-name"] ?? ""), - "profile-name": String(argv["profile-name"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - messages: parseObjectArray(argv["messages"], "messages"), - sessionId: resolveFileToken( - argv["session-id"] as string | undefined, - "session-id", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - namespace_name: argv["namespace-name"], - profile_name: argv["profile-name"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - messages: parseObjectArray(argv["messages"], "messages"), - sessionId: resolveFileToken( - argv["session-id"] as string | undefined, - "session-id", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - namespace_name: argv["namespace-name"], - profile_name: argv["profile-name"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 agent-memory ingest \n\nProcesses a conversation and extracts structured memories from it. Agent Memory identifies facts, events, instructions, and tasks automatically.", + ...parameters, + loader: () => import("./ingest.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/agent-memory/list-memories.handler.ts b/packages/cli/src/commands/_generated/agent-memory/list-memories.handler.ts new file mode 100644 index 0000000000..eb65f76de4 --- /dev/null +++ b/packages/cli/src/commands/_generated/agent-memory/list-memories.handler.ts @@ -0,0 +1,61 @@ +import operation from "../_operations/agent-memory/list-memories.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list-memories.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "agent-memory list-memories", + classification: { + safeFlags: ["type", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + per_page: argv["per-page"], + cursor: argv["cursor"], + session_id: argv["session-id"], + type: argv["type"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf agent-memory list-memories", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces/${argv["namespace-name"] == null ? "" : encodeURIComponent(String(argv["namespace-name"]))}/profiles/${argv["profile-name"] == null ? "" : encodeURIComponent(String(argv["profile-name"]))}/memories`, + pathParams: { + "namespace-name": String(argv["namespace-name"] ?? ""), + "profile-name": String(argv["profile-name"] ?? ""), + }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + namespace_name: argv["namespace-name"], + profile_name: argv["profile-name"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/agent-memory/list-memories.ts b/packages/cli/src/commands/_generated/agent-memory/list-memories.ts index f35e0fa896..7f064d7737 100644 --- a/packages/cli/src/commands/_generated/agent-memory/list-memories.ts +++ b/packages/cli/src/commands/_generated/agent-memory/list-memories.ts @@ -1,113 +1,62 @@ -import operation from "../_operations/agent-memory/list-memories.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list-memories command * @generated from apis/overlays/agent-memory.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 agent-memory list-memories \n\nList memories stored in a profile." - ) - .positional("profile-name", { - type: "string", - description: "Profile name.", - demandOption: true, - }) - .option("namespace-name", { - type: "string", - description: "Namespace name.", - demandOption: true, - }) - .option("per-page", { - type: "number", - description: "Number of results per page.", - }) - .option("cursor", { - type: "string", - description: "Continuation cursor for paginated results.", - }) - .option("session-id", { - type: "string", - description: "Session identifier for filtering.", - }) - .option("type", { - type: "string", - description: "Memory type for filtering.", - choices: ["fact", "event", "instruction", "task"], - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "namespace-name": { + kind: "parsed", + brief: "Namespace name.", + parse: String, + }, + "per-page": { + kind: "parsed", + brief: "Number of results per page.", + optional: true, + parse: Number, + }, + cursor: { + kind: "parsed", + brief: "Continuation cursor for paginated results.", + optional: true, + parse: String, + }, + "session-id": { + kind: "parsed", + brief: "Session identifier for filtering.", + optional: true, + parse: String, + }, + type: { + kind: "enum", + brief: "Memory type for filtering.", + values: ["fact", "event", "instruction", "task"], + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "profile-name", brief: "Profile name.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list-memories ", describe: "List memories", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "agent-memory list-memories", - classification: { - safeFlags: ["type", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - per_page: argv["per-page"], - cursor: argv["cursor"], - session_id: argv["session-id"], - type: argv["type"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf agent-memory list-memories", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces/${argv["namespace-name"] == null ? "" : encodeURIComponent(String(argv["namespace-name"]))}/profiles/${argv["profile-name"] == null ? "" : encodeURIComponent(String(argv["profile-name"]))}/memories`, - pathParams: { - "namespace-name": String(argv["namespace-name"] ?? ""), - "profile-name": String(argv["profile-name"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - namespace_name: argv["namespace-name"], - profile_name: argv["profile-name"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 agent-memory list-memories \n\nList memories stored in a profile.", + ...parameters, + loader: () => import("./list-memories.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/agent-memory/list-namespaces.handler.ts b/packages/cli/src/commands/_generated/agent-memory/list-namespaces.handler.ts new file mode 100644 index 0000000000..1fb1e8f673 --- /dev/null +++ b/packages/cli/src/commands/_generated/agent-memory/list-namespaces.handler.ts @@ -0,0 +1,53 @@ +import operation from "../_operations/agent-memory/list-namespaces.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list-namespaces.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "agent-memory list-namespaces", + classification: { + safeFlags: ["order", "direction", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + per_page: argv["per-page"], + order: argv["order"], + direction: argv["direction"], + cursor: argv["cursor"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf agent-memory list-namespaces", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/agent-memory/list-namespaces.ts b/packages/cli/src/commands/_generated/agent-memory/list-namespaces.ts index 0e0382ec51..f953a1f29e 100644 --- a/packages/cli/src/commands/_generated/agent-memory/list-namespaces.ts +++ b/packages/cli/src/commands/_generated/agent-memory/list-namespaces.ts @@ -1,96 +1,55 @@ -import operation from "../_operations/agent-memory/list-namespaces.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list-namespaces command * @generated from apis/overlays/agent-memory.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 agent-memory list-namespaces\n\nLists all namespaces for the given account. Results are paginated." - ) - .option("per-page", { - type: "number", - description: "Number of results per page.", - }) - .option("order", { - type: "string", - description: "Field to order the results by.", - choices: ["id", "name"], - }) - .option("direction", { - type: "string", - description: "Direction to sort the results in.", - choices: ["asc", "desc"], - }) - .option("cursor", { - type: "string", - description: "Pagination cursor returned by a previous list response.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "per-page": { + kind: "parsed", + brief: "Number of results per page.", + optional: true, + parse: Number, + }, + order: { + kind: "enum", + brief: "Field to order the results by.", + values: ["id", "name"], + optional: true, + }, + direction: { + kind: "enum", + brief: "Direction to sort the results in.", + values: ["asc", "desc"], + optional: true, + }, + cursor: { + kind: "parsed", + brief: "Pagination cursor returned by a previous list response.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list-namespaces", describe: "List namespaces", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "agent-memory list-namespaces", - classification: { - safeFlags: ["order", "direction", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - per_page: argv["per-page"], - order: argv["order"], - direction: argv["direction"], - cursor: argv["cursor"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf agent-memory list-namespaces", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 agent-memory list-namespaces\n\nLists all namespaces for the given account. Results are paginated.", + ...parameters, + loader: () => import("./list-namespaces.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/agent-memory/list-profiles.handler.ts b/packages/cli/src/commands/_generated/agent-memory/list-profiles.handler.ts new file mode 100644 index 0000000000..4f4ba58068 --- /dev/null +++ b/packages/cli/src/commands/_generated/agent-memory/list-profiles.handler.ts @@ -0,0 +1,57 @@ +import operation from "../_operations/agent-memory/list-profiles.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list-profiles.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "agent-memory list-profiles", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + per_page: argv["per-page"], + cursor: argv["cursor"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf agent-memory list-profiles", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces/${argv["namespace-name"] == null ? "" : encodeURIComponent(String(argv["namespace-name"]))}/profiles`, + pathParams: { + "namespace-name": String(argv["namespace-name"] ?? ""), + }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + namespace_name: argv["namespace-name"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/agent-memory/list-profiles.ts b/packages/cli/src/commands/_generated/agent-memory/list-profiles.ts index f3e7b406bb..a50a3ddb51 100644 --- a/packages/cli/src/commands/_generated/agent-memory/list-profiles.ts +++ b/packages/cli/src/commands/_generated/agent-memory/list-profiles.ts @@ -1,96 +1,45 @@ -import operation from "../_operations/agent-memory/list-profiles.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list-profiles command * @generated from apis/overlays/agent-memory.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 agent-memory list-profiles \n\nLists the profiles of a namespace, ordered by name. A profile appears once it has been used." - ) - .positional("namespace-name", { - type: "string", - description: "Namespace name.", - demandOption: true, - }) - .option("per-page", { - type: "number", - description: "Number of results per page.", - }) - .option("cursor", { - type: "string", - description: - "Opaque continuation cursor returned by a previous list response.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "per-page": { + kind: "parsed", + brief: "Number of results per page.", + optional: true, + parse: Number, + }, + cursor: { + kind: "parsed", + brief: "Opaque continuation cursor returned by a previous list response.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "namespace-name", brief: "Namespace name.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list-profiles ", describe: "List profiles", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "agent-memory list-profiles", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - per_page: argv["per-page"], - cursor: argv["cursor"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf agent-memory list-profiles", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces/${argv["namespace-name"] == null ? "" : encodeURIComponent(String(argv["namespace-name"]))}/profiles`, - pathParams: { - "namespace-name": String(argv["namespace-name"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - namespace_name: argv["namespace-name"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 agent-memory list-profiles \n\nLists the profiles of a namespace, ordered by name. A profile appears once it has been used.", + ...parameters, + loader: () => import("./list-profiles.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/agent-memory/recall.handler.ts b/packages/cli/src/commands/_generated/agent-memory/recall.handler.ts new file mode 100644 index 0000000000..b2ad7b9eb2 --- /dev/null +++ b/packages/cli/src/commands/_generated/agent-memory/recall.handler.ts @@ -0,0 +1,117 @@ +import operation from "../_operations/agent-memory/recall.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./recall.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "agent-memory recall", + classification: { + safeFlags: ["response-length", "thinking-level", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["query"] === undefined) { + argv["query"] = await promptForRequiredField( + "query", + "Natural-language query to match against stored memories." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf agent-memory recall", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces/${argv["namespace-name"] == null ? "" : encodeURIComponent(String(argv["namespace-name"]))}/profiles/${argv["profile-name"] == null ? "" : encodeURIComponent(String(argv["profile-name"]))}/recall`, + pathParams: { + "namespace-name": String(argv["namespace-name"] ?? ""), + "profile-name": String(argv["profile-name"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + query: resolveFileToken( + argv["query"] as string | undefined, + "query", + "text" + ), + referenceDate: resolveFileToken( + argv["reference-date"] as string | undefined, + "reference-date", + "text" + ), + responseLength: argv["response-length"], + thinkingLevel: argv["thinking-level"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + namespace_name: argv["namespace-name"], + profile_name: argv["profile-name"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + query: resolveFileToken( + argv["query"] as string | undefined, + "query", + "text" + ), + referenceDate: resolveFileToken( + argv["reference-date"] as string | undefined, + "reference-date", + "text" + ), + responseLength: argv["response-length"], + thinkingLevel: argv["thinking-level"], + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + namespace_name: argv["namespace-name"], + profile_name: argv["profile-name"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/agent-memory/recall.ts b/packages/cli/src/commands/_generated/agent-memory/recall.ts index 37e58a8d38..fbfd660d88 100644 --- a/packages/cli/src/commands/_generated/agent-memory/recall.ts +++ b/packages/cli/src/commands/_generated/agent-memory/recall.ts @@ -1,180 +1,75 @@ -import operation from "../_operations/agent-memory/recall.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * recall command * @generated from apis/overlays/agent-memory.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 agent-memory recall \n\nRetrieves memories relevant to the query and returns a synthesized answer." - ) - .positional("profile-name", { - type: "string", - description: "Profile name.", - demandOption: true, - }) - .option("namespace-name", { - type: "string", - description: "Namespace name.", - demandOption: true, - }) - .option("query", { - type: "string", - description: "Natural-language query to match against stored memories.", - }) - .option("reference-date", { - type: "string", - description: "Temporal anchor for relative date references in the query.", - }) - .option("response-length", { - type: "string", - description: "Verbosity of the synthesized answer. Defaults to 'medium'.", +const parameters = { + flags: { + "namespace-name": { + kind: "parsed", + brief: "Namespace name.", + parse: String, + }, + query: { + kind: "parsed", + brief: "Natural-language query to match against stored memories.", + optional: true, + parse: String, + }, + "reference-date": { + kind: "parsed", + brief: "Temporal anchor for relative date references in the query.", + optional: true, + parse: String, + }, + "response-length": { + kind: "parsed", + brief: "Verbosity of the synthesized answer. Defaults to 'medium'.", + optional: true, choices: ["short", "medium", "long"], - }) - .coerce("response-length", (value) => - resolveFileToken(value, "response-length", "text") - ) - .option("thinking-level", { - type: "string", - description: "Recall intensity / search depth. Defaults to 'low'.", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "response-length", "text"), + }, + "thinking-level": { + kind: "parsed", + brief: "Recall intensity / search depth. Defaults to 'low'.", + optional: true, choices: ["low", "medium", "high"], - }) - .coerce("thinking-level", (value) => - resolveFileToken(value, "thinking-level", "text") - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "thinking-level", "text"), + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { placeholder: "profile-name", brief: "Profile name.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "recall ", describe: "Recall memories", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "agent-memory recall", - classification: { - safeFlags: ["response-length", "thinking-level", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["query"] === undefined) { - argv["query"] = await promptForRequiredField( - "query", - "Natural-language query to match against stored memories." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf agent-memory recall", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces/${argv["namespace-name"] == null ? "" : encodeURIComponent(String(argv["namespace-name"]))}/profiles/${argv["profile-name"] == null ? "" : encodeURIComponent(String(argv["profile-name"]))}/recall`, - pathParams: { - "namespace-name": String(argv["namespace-name"] ?? ""), - "profile-name": String(argv["profile-name"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - query: resolveFileToken( - argv["query"] as string | undefined, - "query", - "text" - ), - referenceDate: resolveFileToken( - argv["reference-date"] as string | undefined, - "reference-date", - "text" - ), - responseLength: argv["response-length"], - thinkingLevel: argv["thinking-level"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - namespace_name: argv["namespace-name"], - profile_name: argv["profile-name"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - query: resolveFileToken( - argv["query"] as string | undefined, - "query", - "text" - ), - referenceDate: resolveFileToken( - argv["reference-date"] as string | undefined, - "reference-date", - "text" - ), - responseLength: argv["response-length"], - thinkingLevel: argv["thinking-level"], - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - namespace_name: argv["namespace-name"], - profile_name: argv["profile-name"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 agent-memory recall \n\nRetrieves memories relevant to the query and returns a synthesized answer.", + ...parameters, + loader: () => import("./recall.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/agent-memory/remember.handler.ts b/packages/cli/src/commands/_generated/agent-memory/remember.handler.ts new file mode 100644 index 0000000000..84a1263787 --- /dev/null +++ b/packages/cli/src/commands/_generated/agent-memory/remember.handler.ts @@ -0,0 +1,113 @@ +import operation from "../_operations/agent-memory/remember.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./remember.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "agent-memory remember", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["content"] === undefined) { + argv["content"] = await promptForRequiredField( + "content", + "Raw memory content to store." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf agent-memory remember", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces/${argv["namespace-name"] == null ? "" : encodeURIComponent(String(argv["namespace-name"]))}/profiles/${argv["profile-name"] == null ? "" : encodeURIComponent(String(argv["profile-name"]))}/remember`, + pathParams: { + "namespace-name": String(argv["namespace-name"] ?? ""), + "profile-name": String(argv["profile-name"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + content: resolveFileToken( + argv["content"] as string | undefined, + "content", + "text" + ), + sessionId: resolveFileToken( + argv["session-id"] as string | undefined, + "session-id", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + namespace_name: argv["namespace-name"], + profile_name: argv["profile-name"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + content: resolveFileToken( + argv["content"] as string | undefined, + "content", + "text" + ), + sessionId: resolveFileToken( + argv["session-id"] as string | undefined, + "session-id", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + namespace_name: argv["namespace-name"], + profile_name: argv["profile-name"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/agent-memory/remember.ts b/packages/cli/src/commands/_generated/agent-memory/remember.ts index 2aef57992c..a8acf73905 100644 --- a/packages/cli/src/commands/_generated/agent-memory/remember.ts +++ b/packages/cli/src/commands/_generated/agent-memory/remember.ts @@ -1,160 +1,56 @@ -import operation from "../_operations/agent-memory/remember.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * remember command * @generated from apis/overlays/agent-memory.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 agent-memory remember \n\nStores a single memory explicitly." - ) - .positional("profile-name", { - type: "string", - description: "Profile name.", - demandOption: true, - }) - .option("namespace-name", { - type: "string", - description: "Namespace name.", - demandOption: true, - }) - .option("content", { - type: "string", - description: "Raw memory content to store.", - }) - .option("session-id", { - type: "string", - description: "Session identifier.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "namespace-name": { + kind: "parsed", + brief: "Namespace name.", + parse: String, + }, + content: { + kind: "parsed", + brief: "Raw memory content to store.", + optional: true, + parse: String, + }, + "session-id": { + kind: "parsed", + brief: "Session identifier.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { placeholder: "profile-name", brief: "Profile name.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "remember ", describe: "Remember a memory", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "agent-memory remember", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["content"] === undefined) { - argv["content"] = await promptForRequiredField( - "content", - "Raw memory content to store." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf agent-memory remember", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces/${argv["namespace-name"] == null ? "" : encodeURIComponent(String(argv["namespace-name"]))}/profiles/${argv["profile-name"] == null ? "" : encodeURIComponent(String(argv["profile-name"]))}/remember`, - pathParams: { - "namespace-name": String(argv["namespace-name"] ?? ""), - "profile-name": String(argv["profile-name"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - content: resolveFileToken( - argv["content"] as string | undefined, - "content", - "text" - ), - sessionId: resolveFileToken( - argv["session-id"] as string | undefined, - "session-id", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - namespace_name: argv["namespace-name"], - profile_name: argv["profile-name"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - content: resolveFileToken( - argv["content"] as string | undefined, - "content", - "text" - ), - sessionId: resolveFileToken( - argv["session-id"] as string | undefined, - "session-id", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - namespace_name: argv["namespace-name"], - profile_name: argv["profile-name"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 agent-memory remember \n\nStores a single memory explicitly.", + ...parameters, + loader: () => import("./remember.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/agent-memory/summary.handler.ts b/packages/cli/src/commands/_generated/agent-memory/summary.handler.ts new file mode 100644 index 0000000000..e89801fd58 --- /dev/null +++ b/packages/cli/src/commands/_generated/agent-memory/summary.handler.ts @@ -0,0 +1,90 @@ +import operation from "../_operations/agent-memory/summary.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./summary.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "agent-memory summary", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf agent-memory summary", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces/${argv["namespace-name"] == null ? "" : encodeURIComponent(String(argv["namespace-name"]))}/profiles/${argv["profile-name"] == null ? "" : encodeURIComponent(String(argv["profile-name"]))}/summary`, + pathParams: { + "namespace-name": String(argv["namespace-name"] ?? ""), + "profile-name": String(argv["profile-name"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + sessionId: resolveFileToken( + argv["session-id"] as string | undefined, + "session-id", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + namespace_name: argv["namespace-name"], + profile_name: argv["profile-name"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + sessionId: resolveFileToken( + argv["session-id"] as string | undefined, + "session-id", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + namespace_name: argv["namespace-name"], + profile_name: argv["profile-name"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/agent-memory/summary.ts b/packages/cli/src/commands/_generated/agent-memory/summary.ts index dfc768f37f..56385e2f06 100644 --- a/packages/cli/src/commands/_generated/agent-memory/summary.ts +++ b/packages/cli/src/commands/_generated/agent-memory/summary.ts @@ -1,133 +1,50 @@ -import operation from "../_operations/agent-memory/summary.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * summary command * @generated from apis/overlays/agent-memory.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 agent-memory summary \n\nGenerates a paste-ready prompt block summarizing everything stored in a memory profile." - ) - .positional("profile-name", { - type: "string", - description: "Profile name.", - demandOption: true, - }) - .option("namespace-name", { - type: "string", - description: "Namespace name.", - demandOption: true, - }) - .option("session-id", { - type: "string", - description: "Session identifier.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "namespace-name": { + kind: "parsed", + brief: "Namespace name.", + parse: String, + }, + "session-id": { + kind: "parsed", + brief: "Session identifier.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { placeholder: "profile-name", brief: "Profile name.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "summary ", describe: "Get a profile summary", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "agent-memory summary", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf agent-memory summary", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/agent-memory/namespaces/${argv["namespace-name"] == null ? "" : encodeURIComponent(String(argv["namespace-name"]))}/profiles/${argv["profile-name"] == null ? "" : encodeURIComponent(String(argv["profile-name"]))}/summary`, - pathParams: { - "namespace-name": String(argv["namespace-name"] ?? ""), - "profile-name": String(argv["profile-name"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - sessionId: resolveFileToken( - argv["session-id"] as string | undefined, - "session-id", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - namespace_name: argv["namespace-name"], - profile_name: argv["profile-name"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - sessionId: resolveFileToken( - argv["session-id"] as string | undefined, - "session-id", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - namespace_name: argv["namespace-name"], - profile_name: argv["profile-name"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 agent-memory summary \n\nGenerates a paste-ready prompt block summarizing everything stored in a memory profile.", + ...parameters, + loader: () => import("./summary.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-audit/index.ts b/packages/cli/src/commands/_generated/ai-audit/index.ts index 1eb221eb32..dbf977b318 100644 --- a/packages/cli/src/commands/_generated/ai-audit/index.ts +++ b/packages/cli/src/commands/_generated/ai-audit/index.ts @@ -1,22 +1,17 @@ import $robots from "./robots/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * ai-audit command * @generated from apis/overlays/ai-audit.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "ai-audit", describe: "ai-audit", - builder: (yargs) => { - return yargs - .command($robots) - .demandCommand(1, "Please specify a subcommand"); + routes: { + robots: $robots, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-audit/robots/bulk-get.handler.ts b/packages/cli/src/commands/_generated/ai-audit/robots/bulk-get.handler.ts new file mode 100644 index 0000000000..926ae7da1f --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-audit/robots/bulk-get.handler.ts @@ -0,0 +1,56 @@ +import operation from "../../_operations/ai-audit/robots/bulk-get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./bulk-get.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-audit robots bulk-get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.body === undefined) { + throw new Error( + "--body is required for this command. Pass --body '' or --body @path/to/file.json." + ); + } + if (argv.dryRun) { + formatDryRun({ + command: "cf ai-audit robots bulk-get", + method: "POST", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/ai-audit/robots/bulk`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined ? parseBody(argv.body, [], 25) : undefined, + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body, [], 25) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Loading`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + return; + } + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-audit/robots/bulk-get.ts b/packages/cli/src/commands/_generated/ai-audit/robots/bulk-get.ts index 80c6079827..05bcf49342 100644 --- a/packages/cli/src/commands/_generated/ai-audit/robots/bulk-get.ts +++ b/packages/cli/src/commands/_generated/ai-audit/robots/bulk-get.ts @@ -1,90 +1,38 @@ -import operation from "../../_operations/ai-audit/robots/bulk-get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * bulk-get command * @generated from apis/overlays/ai-audit.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-audit robots bulk-get\n\nFetches and parses robots.txt files for multiple domains within a zone in a single request. Each domain must belong to the specified zone. Results are keyed by hostname." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: + }, + body: { + kind: "parsed", + brief: "Array of domain hostnames to fetch robots.txt for. Each domain must end with the zone name. Maximum 25 domains per request.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "bulk-get", describe: "Bulk get robots.txt rules", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-audit robots bulk-get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.body === undefined) { - throw new Error( - "--body is required for this command. Pass --body '' or --body @path/to/file.json." - ); - } - if (argv.dryRun) { - formatDryRun({ - command: "cf ai-audit robots bulk-get", - method: "POST", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/ai-audit/robots/bulk`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body, [], 25) - : undefined, - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body, [], 25) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Loading`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - return; - } - } - ), -}; + usage: + "$0 ai-audit robots bulk-get\n\nFetches and parses robots.txt files for multiple domains within a zone in a single request. Each domain must belong to the specified zone. Results are keyed by hostname.", + ...parameters, + loader: () => import("./bulk-get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-audit/robots/get.handler.ts b/packages/cli/src/commands/_generated/ai-audit/robots/get.handler.ts new file mode 100644 index 0000000000..ae9cb2ebe1 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-audit/robots/get.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/ai-audit/robots/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-audit robots get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + subdomain: argv["subdomain"], + }; + if (argv.dryRun) { + formatDryRun({ + command: "cf ai-audit robots get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/ai-audit/robots`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { zone_id: zoneId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-audit/robots/get.ts b/packages/cli/src/commands/_generated/ai-audit/robots/get.ts index e305b0f6b3..4ffd857c75 100644 --- a/packages/cli/src/commands/_generated/ai-audit/robots/get.ts +++ b/packages/cli/src/commands/_generated/ai-audit/robots/get.ts @@ -1,78 +1,38 @@ -import operation from "../../_operations/ai-audit/robots/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/ai-audit.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-audit robots get\n\nFetches and parses the robots.txt file for a zone or a specific subdomain within the zone. Returns parsed user-agent rules, content signals, and sitemaps." - ) - .option("subdomain", { - type: "string", - description: +const parameters = { + flags: { + subdomain: { + kind: "parsed", + brief: "Optional subdomain to fetch robots.txt for. If omitted, fetches robots.txt for the zone apex domain.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "Get robots.txt rules", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-audit robots get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - subdomain: argv["subdomain"], - }; - if (argv.dryRun) { - formatDryRun({ - command: "cf ai-audit robots get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/ai-audit/robots`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { zone_id: zoneId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-audit robots get\n\nFetches and parses the robots.txt file for a zone or a specific subdomain within the zone. Returns parsed user-agent rules, content signals, and sitemaps.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-audit/robots/index.ts b/packages/cli/src/commands/_generated/ai-audit/robots/index.ts index a3169b3eda..e60226fe98 100644 --- a/packages/cli/src/commands/_generated/ai-audit/robots/index.ts +++ b/packages/cli/src/commands/_generated/ai-audit/robots/index.ts @@ -1,24 +1,19 @@ import $bulkget from "./bulk-get.js"; import $get from "./get.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * robots command group * @generated from apis/overlays/ai-audit.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "robots", describe: "Operations for robots", - builder: (yargs) => { - return yargs - .command($bulkget) - .command($get) - .demandCommand(1, "Please specify a subcommand"); + routes: { + "bulk-get": $bulkget, + get: $get, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/custom-domains/create.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/custom-domains/create.handler.ts new file mode 100644 index 0000000000..49117db643 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/custom-domains/create.handler.ts @@ -0,0 +1,116 @@ +import operation from "../../_operations/ai-gateway/custom-domains/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway custom-domains create", + classification: { + safeFlags: ["min-tls", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["domain"] === undefined) { + argv["domain"] = await promptForRequiredField( + "domain", + "Custom hostname that you own, such as \`ai.example.com\`." + ); + } + if (argv["zone-id"] === undefined) { + argv["zone-id"] = await promptForRequiredField( + "zone-id", + "ID of the Cloudflare zone that contains the custom hostname." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway custom-domains create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/custom-domains`, + pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + domain: resolveFileToken( + argv["domain"] as string | undefined, + "domain", + "text" + ), + minTLS: argv["min-tls"], + zone_id: resolveFileToken( + argv["zone-id"] as string | undefined, + "zone-id", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + gateway_id: argv["gateway-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + domain: resolveFileToken( + argv["domain"] as string | undefined, + "domain", + "text" + ), + minTLS: argv["min-tls"], + zone_id: resolveFileToken( + argv["zone-id"] as string | undefined, + "zone-id", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + gateway_id: argv["gateway-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/custom-domains/create.ts b/packages/cli/src/commands/_generated/ai-gateway/custom-domains/create.ts index 5fc32fd7e4..686d97b3f4 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/custom-domains/create.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/custom-domains/create.ts @@ -1,165 +1,64 @@ -import operation from "../../_operations/ai-gateway/custom-domains/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway custom-domains create \n\nProvisions a Cloudflare-for-SaaS custom hostname and returns the CNAME target to point DNS at." - ) - .positional("gateway-id", { - type: "string", - description: "Unique identifier of the AI Gateway within the account.", - demandOption: true, - }) - .option("domain", { - type: "string", - description: "Custom hostname that you own, such as `ai.example.com`.", - }) - .option("min-tls", { - type: "string", - description: "The minTLS field", +const parameters = { + flags: { + domain: { + kind: "parsed", + brief: "Custom hostname that you own, such as `ai.example.com`.", + optional: true, + parse: String, + }, + "min-tls": { + kind: "parsed", + brief: "The minTLS field", + optional: true, choices: ["1.0", "1.1", "1.2", "1.3"], - }) - .coerce("min-tls", (value) => resolveFileToken(value, "min-tls", "text")) - .option("zone-id", { - type: "string", - description: - "ID of the Cloudflare zone that contains the custom hostname.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => resolveFileToken(value, "min-tls", "text"), + }, + "zone-id": { + kind: "parsed", + brief: "ID of the Cloudflare zone that contains the custom hostname.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "gateway-id", + brief: "Unique identifier of the AI Gateway within the account.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Create a custom domain for a gateway", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway custom-domains create", - classification: { - safeFlags: ["min-tls", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["domain"] === undefined) { - argv["domain"] = await promptForRequiredField( - "domain", - "Custom hostname that you own, such as \`ai.example.com\`." - ); - } - if (argv["zone-id"] === undefined) { - argv["zone-id"] = await promptForRequiredField( - "zone-id", - "ID of the Cloudflare zone that contains the custom hostname." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway custom-domains create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/custom-domains`, - pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - domain: resolveFileToken( - argv["domain"] as string | undefined, - "domain", - "text" - ), - minTLS: argv["min-tls"], - zone_id: resolveFileToken( - argv["zone-id"] as string | undefined, - "zone-id", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - gateway_id: argv["gateway-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - domain: resolveFileToken( - argv["domain"] as string | undefined, - "domain", - "text" - ), - minTLS: argv["min-tls"], - zone_id: resolveFileToken( - argv["zone-id"] as string | undefined, - "zone-id", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - gateway_id: argv["gateway-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 ai-gateway custom-domains create \n\nProvisions a Cloudflare-for-SaaS custom hostname and returns the CNAME target to point DNS at.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/custom-domains/delete.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/custom-domains/delete.handler.ts new file mode 100644 index 0000000000..ce914c0a37 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/custom-domains/delete.handler.ts @@ -0,0 +1,64 @@ +import operation from "../../_operations/ai-gateway/custom-domains/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway custom-domains delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway custom-domains delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/custom-domains/${argv["hostname"] == null ? "" : encodeURIComponent(String(argv["hostname"]))}`, + pathParams: { + "gateway-id": String(argv["gateway-id"] ?? ""), + hostname: String(argv["hostname"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This deletes the custom domain and its custom hostname. Requests to this hostname will stop reaching the gateway.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + gateway_id: argv["gateway-id"], + hostname: argv["hostname"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/custom-domains/delete.ts b/packages/cli/src/commands/_generated/ai-gateway/custom-domains/delete.ts index 9a672306f1..98a3a2f351 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/custom-domains/delete.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/custom-domains/delete.ts @@ -1,105 +1,48 @@ -import operation from "../../_operations/ai-gateway/custom-domains/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway custom-domains delete \n\nDeletes a custom domain from an AI Gateway and removes its Cloudflare for SaaS custom hostname." - ) - .positional("hostname", { - type: "string", - description: "Custom hostname that you own, such as \`ai.example.com\`.", - demandOption: true, - }) - .option("gateway-id", { - type: "string", - description: "Unique identifier of the AI Gateway within the account.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "gateway-id": { + kind: "parsed", + brief: "Unique identifier of the AI Gateway within the account.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "hostname", + brief: "Custom hostname that you own, such as \`ai.example.com\`.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete a custom domain", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway custom-domains delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway custom-domains delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/custom-domains/${argv["hostname"] == null ? "" : encodeURIComponent(String(argv["hostname"]))}`, - pathParams: { - "gateway-id": String(argv["gateway-id"] ?? ""), - hostname: String(argv["hostname"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This deletes the custom domain and its custom hostname. Requests to this hostname will stop reaching the gateway.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - gateway_id: argv["gateway-id"], - hostname: argv["hostname"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 ai-gateway custom-domains delete \n\nDeletes a custom domain from an AI Gateway and removes its Cloudflare for SaaS custom hostname.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/custom-domains/get.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/custom-domains/get.handler.ts new file mode 100644 index 0000000000..5cef1e05a1 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/custom-domains/get.handler.ts @@ -0,0 +1,53 @@ +import operation from "../../_operations/ai-gateway/custom-domains/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway custom-domains get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway custom-domains get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/custom-domains/${argv["hostname"] == null ? "" : encodeURIComponent(String(argv["hostname"]))}`, + pathParams: { + "gateway-id": String(argv["gateway-id"] ?? ""), + hostname: String(argv["hostname"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + gateway_id: argv["gateway-id"], + hostname: argv["hostname"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/custom-domains/get.ts b/packages/cli/src/commands/_generated/ai-gateway/custom-domains/get.ts index 847cf40ca8..e6ea23ce33 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/custom-domains/get.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/custom-domains/get.ts @@ -1,88 +1,42 @@ -import operation from "../../_operations/ai-gateway/custom-domains/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway custom-domains get \n\nRetrieves a custom domain attached to an AI Gateway, including its status and CNAME target." - ) - .positional("hostname", { - type: "string", - description: "Custom hostname that you own, such as \`ai.example.com\`.", - demandOption: true, - }) - .option("gateway-id", { - type: "string", - description: "Unique identifier of the AI Gateway within the account.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "gateway-id": { + kind: "parsed", + brief: "Unique identifier of the AI Gateway within the account.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "hostname", + brief: "Custom hostname that you own, such as \`ai.example.com\`.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get a custom domain", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway custom-domains get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway custom-domains get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/custom-domains/${argv["hostname"] == null ? "" : encodeURIComponent(String(argv["hostname"]))}`, - pathParams: { - "gateway-id": String(argv["gateway-id"] ?? ""), - hostname: String(argv["hostname"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - gateway_id: argv["gateway-id"], - hostname: argv["hostname"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-gateway custom-domains get \n\nRetrieves a custom domain attached to an AI Gateway, including its status and CNAME target.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/custom-domains/index.ts b/packages/cli/src/commands/_generated/ai-gateway/custom-domains/index.ts index 4dc3cb4e60..13afe8d0a0 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/custom-domains/index.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/custom-domains/index.ts @@ -2,27 +2,22 @@ import $create from "./create.js"; import $delete from "./delete.js"; import $get from "./get.js"; import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * custom-domains command group * @generated from apis/overlays/ai-gateway.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "custom-domains", describe: "Manage custom hostnames that route requests through an AI Gateway", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .command($list) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/custom-domains/list.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/custom-domains/list.handler.ts new file mode 100644 index 0000000000..86b95379df --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/custom-domains/list.handler.ts @@ -0,0 +1,57 @@ +import operation from "../../_operations/ai-gateway/custom-domains/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway custom-domains list", + classification: { + safeFlags: ["status", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + status: argv["status"], + search: argv["search"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway custom-domains list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/custom-domains`, + pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + gateway_id: argv["gateway-id"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/custom-domains/list.ts b/packages/cli/src/commands/_generated/ai-gateway/custom-domains/list.ts index acf026a3fa..c853e68213 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/custom-domains/list.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/custom-domains/list.ts @@ -1,95 +1,55 @@ -import operation from "../../_operations/ai-gateway/custom-domains/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway custom-domains list\n\nLists the custom domains attached to an AI Gateway, including the certificate and validation status of each domain." - ) - .option("gateway-id", { - type: "string", - description: "Unique identifier of the AI Gateway within the account.", - demandOption: true, - }) - .option("page", { type: "number", description: "Page" }) - .option("per-page", { type: "number", description: "Per page" }) - .option("status", { - type: "string", - description: "Status", - choices: ["initializing", "pending_dcv", "active", "blocked", "error"], - }) - .option("search", { type: "string", description: "Search by hostname" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "gateway-id": { + kind: "parsed", + brief: "Unique identifier of the AI Gateway within the account.", + parse: String, + }, + page: { kind: "parsed", brief: "Page", optional: true, parse: Number }, + "per-page": { + kind: "parsed", + brief: "Per page", + optional: true, + parse: Number, + }, + status: { + kind: "enum", + brief: "Status", + values: ["initializing", "pending_dcv", "active", "blocked", "error"], + optional: true, + }, + search: { + kind: "parsed", + brief: "Search by hostname", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List custom domains", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway custom-domains list", - classification: { - safeFlags: ["status", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - status: argv["status"], - search: argv["search"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway custom-domains list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/custom-domains`, - pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - gateway_id: argv["gateway-id"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-gateway custom-domains list\n\nLists the custom domains attached to an AI Gateway, including the certificate and validation status of each domain.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/custom-providers/create.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/custom-providers/create.handler.ts new file mode 100644 index 0000000000..f454dfe826 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/custom-providers/create.handler.ts @@ -0,0 +1,173 @@ +import operation from "../../_operations/ai-gateway/custom-providers/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway custom-providers create", + classification: { + safeFlags: ["beta", "enable", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["base-url"] === undefined) { + argv["base-url"] = await promptForRequiredField( + "base-url", + "The base_url field" + ); + } + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField("name", "The name field"); + } + if (argv["slug"] === undefined) { + argv["slug"] = await promptForRequiredField("slug", "The slug field"); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway custom-providers create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/custom-providers`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + base_url: resolveFileToken( + argv["base-url"] as string | undefined, + "base-url", + "text" + ), + beta: argv["beta"], + curl_example: resolveFileToken( + argv["curl-example"] as string | undefined, + "curl-example", + "text" + ), + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + enable: argv["enable"], + headers: resolveFileToken( + argv["headers"] as string | undefined, + "headers", + "text" + ), + js_example: resolveFileToken( + argv["js-example"] as string | undefined, + "js-example", + "text" + ), + link: resolveFileToken( + argv["link"] as string | undefined, + "link", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + position: argv["position"], + slug: resolveFileToken( + argv["slug"] as string | undefined, + "slug", + "text" + ), + }), + sensitiveBodyPaths: [["headers"]], + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + base_url: resolveFileToken( + argv["base-url"] as string | undefined, + "base-url", + "text" + ), + beta: argv["beta"], + curl_example: resolveFileToken( + argv["curl-example"] as string | undefined, + "curl-example", + "text" + ), + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + enable: argv["enable"], + headers: resolveFileToken( + argv["headers"] as string | undefined, + "headers", + "text" + ), + js_example: resolveFileToken( + argv["js-example"] as string | undefined, + "js-example", + "text" + ), + link: resolveFileToken( + argv["link"] as string | undefined, + "link", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + position: argv["position"], + slug: resolveFileToken( + argv["slug"] as string | undefined, + "slug", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/custom-providers/create.ts b/packages/cli/src/commands/_generated/ai-gateway/custom-providers/create.ts index 290998409a..61435ebd62 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/custom-providers/create.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/custom-providers/create.ts @@ -1,232 +1,94 @@ -import operation from "../../_operations/ai-gateway/custom-providers/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway custom-providers create\n\nCreates an account-level custom provider that forwards AI Gateway requests to the HTTPS base URL you supply. Requests reference the provider as `custom-{slug}`, so the slug must be unique within the account." - ) - .option("base-url", { type: "string", description: "The base_url field" }) - .option("beta", { type: "boolean", description: "The beta field" }) - .option("curl-example", { - type: "string", - description: "The curl_example field", - }) - .option("description", { - type: "string", - description: "The description field", - }) - .option("enable", { type: "boolean", description: "The enable field" }) - .option("headers", { - type: "string", - description: +const parameters = { + flags: { + "base-url": { + kind: "parsed", + brief: "The base_url field", + optional: true, + parse: String, + }, + beta: { kind: "boolean", brief: "The beta field", optional: true }, + "curl-example": { + kind: "parsed", + brief: "The curl_example field", + optional: true, + parse: String, + }, + description: { + kind: "parsed", + brief: "The description field", + optional: true, + parse: String, + }, + enable: { kind: "boolean", brief: "The enable field", optional: true }, + headers: { + kind: "parsed", + brief: "JSON object of extra HTTP headers that AI Gateway sends to the provider. Values can contain credentials.", - }) - .option("js-example", { - type: "string", - description: "The js_example field", - }) - .option("link", { type: "string", description: "The link field" }) - .option("name", { type: "string", description: "The name field" }) - .option("position", { type: "number", description: "The position field" }) - .option("slug", { type: "string", description: "The slug field" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "js-example": { + kind: "parsed", + brief: "The js_example field", + optional: true, + parse: String, + }, + link: { + kind: "parsed", + brief: "The link field", + optional: true, + parse: String, + }, + name: { + kind: "parsed", + brief: "The name field", + optional: true, + parse: String, + }, + position: { + kind: "parsed", + brief: "The position field", + optional: true, + parse: Number, + }, + slug: { + kind: "parsed", + brief: "The slug field", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Create a custom provider", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway custom-providers create", - classification: { - safeFlags: ["beta", "enable", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["base-url"] === undefined) { - argv["base-url"] = await promptForRequiredField( - "base-url", - "The base_url field" - ); - } - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "The name field" - ); - } - if (argv["slug"] === undefined) { - argv["slug"] = await promptForRequiredField( - "slug", - "The slug field" - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway custom-providers create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/custom-providers`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - base_url: resolveFileToken( - argv["base-url"] as string | undefined, - "base-url", - "text" - ), - beta: argv["beta"], - curl_example: resolveFileToken( - argv["curl-example"] as string | undefined, - "curl-example", - "text" - ), - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - enable: argv["enable"], - headers: resolveFileToken( - argv["headers"] as string | undefined, - "headers", - "text" - ), - js_example: resolveFileToken( - argv["js-example"] as string | undefined, - "js-example", - "text" - ), - link: resolveFileToken( - argv["link"] as string | undefined, - "link", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - position: argv["position"], - slug: resolveFileToken( - argv["slug"] as string | undefined, - "slug", - "text" - ), - }), - sensitiveBodyPaths: [["headers"]], - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - base_url: resolveFileToken( - argv["base-url"] as string | undefined, - "base-url", - "text" - ), - beta: argv["beta"], - curl_example: resolveFileToken( - argv["curl-example"] as string | undefined, - "curl-example", - "text" - ), - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - enable: argv["enable"], - headers: resolveFileToken( - argv["headers"] as string | undefined, - "headers", - "text" - ), - js_example: resolveFileToken( - argv["js-example"] as string | undefined, - "js-example", - "text" - ), - link: resolveFileToken( - argv["link"] as string | undefined, - "link", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - position: argv["position"], - slug: resolveFileToken( - argv["slug"] as string | undefined, - "slug", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 ai-gateway custom-providers create\n\nCreates an account-level custom provider that forwards AI Gateway requests to the HTTPS base URL you supply. Requests reference the provider as `custom-{slug}`, so the slug must be unique within the account.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/custom-providers/delete.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/custom-providers/delete.handler.ts new file mode 100644 index 0000000000..5d24a174e6 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/custom-providers/delete.handler.ts @@ -0,0 +1,57 @@ +import operation from "../../_operations/ai-gateway/custom-providers/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway custom-providers delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway custom-providers delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/custom-providers/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, + pathParams: { id: String(argv["id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This permanently deletes the custom provider and all of its pricing rules. Gateway requests that use \`custom-{slug}\` for this provider will stop routing.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { account_id: accountId, id: argv["id"] }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/custom-providers/delete.ts b/packages/cli/src/commands/_generated/ai-gateway/custom-providers/delete.ts index 92b3bb76a6..8187fb2026 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/custom-providers/delete.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/custom-providers/delete.ts @@ -1,93 +1,37 @@ -import operation from "../../_operations/ai-gateway/custom-providers/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway custom-providers delete \n\nDeletes a custom provider and every pricing rule that belongs to it." - ) - .positional("id", { - type: "string", - description: "ID", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "id", brief: "ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete a custom provider", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway custom-providers delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway custom-providers delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/custom-providers/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, - pathParams: { id: String(argv["id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This permanently deletes the custom provider and all of its pricing rules. Gateway requests that use \`custom-{slug}\` for this provider will stop routing.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { account_id: accountId, id: argv["id"] }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 ai-gateway custom-providers delete \n\nDeletes a custom provider and every pricing rule that belongs to it.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/custom-providers/get.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/custom-providers/get.handler.ts new file mode 100644 index 0000000000..734f9dae66 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/custom-providers/get.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/ai-gateway/custom-providers/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway custom-providers get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway custom-providers get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/custom-providers/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, + pathParams: { id: String(argv["id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, id: argv["id"] }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/custom-providers/get.ts b/packages/cli/src/commands/_generated/ai-gateway/custom-providers/get.ts index 50b257accc..bd1c62a9ac 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/custom-providers/get.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/custom-providers/get.ts @@ -1,76 +1,31 @@ -import operation from "../../_operations/ai-gateway/custom-providers/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway custom-providers get \n\nRetrieves a custom provider, including its slug, base URL, and custom headers." - ) - .positional("id", { - type: "string", - description: "ID", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "id", brief: "ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get a custom provider", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway custom-providers get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway custom-providers get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/custom-providers/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, - pathParams: { id: String(argv["id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, id: argv["id"] }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-gateway custom-providers get \n\nRetrieves a custom provider, including its slug, base URL, and custom headers.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/custom-providers/index.ts b/packages/cli/src/commands/_generated/ai-gateway/custom-providers/index.ts index 1e6320b19c..b63a377eb2 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/custom-providers/index.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/custom-providers/index.ts @@ -3,29 +3,24 @@ import $delete from "./delete.js"; import $get from "./get.js"; import $list from "./list.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * custom-providers command group * @generated from apis/overlays/ai-gateway.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "custom-providers", describe: "Manage account-level custom AI providers and their endpoint settings", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .command($list) - .command($update) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, + list: $list, + update: $update, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/custom-providers/list.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/custom-providers/list.handler.ts new file mode 100644 index 0000000000..722ffbda72 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/custom-providers/list.handler.ts @@ -0,0 +1,54 @@ +import operation from "../../_operations/ai-gateway/custom-providers/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway custom-providers list", + classification: { + safeFlags: ["beta", "enable", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + beta: argv["beta"], + enable: argv["enable"], + search: argv["search"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway custom-providers list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/custom-providers`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/custom-providers/list.ts b/packages/cli/src/commands/_generated/ai-gateway/custom-providers/list.ts index e692a5da9b..cf207b866e 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/custom-providers/list.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/custom-providers/list.ts @@ -1,87 +1,46 @@ -import operation from "../../_operations/ai-gateway/custom-providers/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway custom-providers list\n\nLists the custom providers configured for the account, ordered by position and then name." - ) - .option("page", { type: "number", description: "Page" }) - .option("per-page", { type: "number", description: "Per page" }) - .option("beta", { type: "boolean", description: "Beta" }) - .option("enable", { type: "boolean", description: "Enable" }) - .option("search", { - type: "string", - description: "Search by id, name, slug", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + page: { kind: "parsed", brief: "Page", optional: true, parse: Number }, + "per-page": { + kind: "parsed", + brief: "Per page", + optional: true, + parse: Number, + }, + beta: { kind: "boolean", brief: "Beta", optional: true }, + enable: { kind: "boolean", brief: "Enable", optional: true }, + search: { + kind: "parsed", + brief: "Search by id, name, slug", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List custom providers", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway custom-providers list", - classification: { - safeFlags: ["beta", "enable", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - beta: argv["beta"], - enable: argv["enable"], - search: argv["search"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway custom-providers list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/custom-providers`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-gateway custom-providers list\n\nLists the custom providers configured for the account, ordered by position and then name.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/custom-providers/update.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/custom-providers/update.handler.ts new file mode 100644 index 0000000000..b1472ca706 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/custom-providers/update.handler.ts @@ -0,0 +1,172 @@ +import operation from "../../_operations/ai-gateway/custom-providers/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway custom-providers update", + classification: { + safeFlags: ["beta", "enable", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway custom-providers update", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/custom-providers/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, + pathParams: { id: String(argv["id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + base_url: resolveFileToken( + argv["base-url"] as string | undefined, + "base-url", + "text" + ), + beta: argv["beta"], + curl_example: resolveFileToken( + argv["curl-example"] as string | undefined, + "curl-example", + "text" + ), + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + enable: argv["enable"], + headers: resolveFileToken( + argv["headers"] as string | undefined, + "headers", + "text" + ), + js_example: resolveFileToken( + argv["js-example"] as string | undefined, + "js-example", + "text" + ), + link: resolveFileToken( + argv["link"] as string | undefined, + "link", + "text" + ), + logo: resolveFileToken( + argv["logo"] as string | undefined, + "logo", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + position: argv["position"], + slug: resolveFileToken( + argv["slug"] as string | undefined, + "slug", + "text" + ), + }), + sensitiveBodyPaths: [["headers"]], + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + base_url: resolveFileToken( + argv["base-url"] as string | undefined, + "base-url", + "text" + ), + beta: argv["beta"], + curl_example: resolveFileToken( + argv["curl-example"] as string | undefined, + "curl-example", + "text" + ), + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + enable: argv["enable"], + headers: resolveFileToken( + argv["headers"] as string | undefined, + "headers", + "text" + ), + js_example: resolveFileToken( + argv["js-example"] as string | undefined, + "js-example", + "text" + ), + link: resolveFileToken( + argv["link"] as string | undefined, + "link", + "text" + ), + logo: resolveFileToken( + argv["logo"] as string | undefined, + "logo", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + position: argv["position"], + slug: resolveFileToken( + argv["slug"] as string | undefined, + "slug", + "text" + ), + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/custom-providers/update.ts b/packages/cli/src/commands/_generated/ai-gateway/custom-providers/update.ts index 67b6c3343e..093f095f3b 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/custom-providers/update.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/custom-providers/update.ts @@ -1,231 +1,100 @@ -import operation from "../../_operations/ai-gateway/custom-providers/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway custom-providers update \n\nUpdates the specified fields of a custom provider. Changes clear cached entries for the provider." - ) - .positional("id", { - type: "string", - description: "ID", - demandOption: true, - }) - .option("base-url", { type: "string", description: "The base_url field" }) - .option("beta", { type: "boolean", description: "The beta field" }) - .option("curl-example", { - type: "string", - description: "The curl_example field", - }) - .option("description", { - type: "string", - description: "The description field", - }) - .option("enable", { type: "boolean", description: "The enable field" }) - .option("headers", { - type: "string", - description: +const parameters = { + flags: { + "base-url": { + kind: "parsed", + brief: "The base_url field", + optional: true, + parse: String, + }, + beta: { kind: "boolean", brief: "The beta field", optional: true }, + "curl-example": { + kind: "parsed", + brief: "The curl_example field", + optional: true, + parse: String, + }, + description: { + kind: "parsed", + brief: "The description field", + optional: true, + parse: String, + }, + enable: { kind: "boolean", brief: "The enable field", optional: true }, + headers: { + kind: "parsed", + brief: "JSON object of extra HTTP headers that AI Gateway sends to the provider. Values can contain credentials.", - }) - .option("js-example", { - type: "string", - description: "The js_example field", - }) - .option("link", { type: "string", description: "The link field" }) - .option("logo", { type: "string", description: "The logo field" }) - .option("name", { type: "string", description: "The name field" }) - .option("position", { type: "number", description: "The position field" }) - .option("slug", { type: "string", description: "The slug field" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "js-example": { + kind: "parsed", + brief: "The js_example field", + optional: true, + parse: String, + }, + link: { + kind: "parsed", + brief: "The link field", + optional: true, + parse: String, + }, + logo: { + kind: "parsed", + brief: "The logo field", + optional: true, + parse: String, + }, + name: { + kind: "parsed", + brief: "The name field", + optional: true, + parse: String, + }, + position: { + kind: "parsed", + brief: "The position field", + optional: true, + parse: Number, + }, + slug: { + kind: "parsed", + brief: "The slug field", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [{ placeholder: "id", brief: "ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update ", describe: "Update a custom provider", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway custom-providers update", - classification: { - safeFlags: ["beta", "enable", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway custom-providers update", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/custom-providers/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, - pathParams: { id: String(argv["id"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - base_url: resolveFileToken( - argv["base-url"] as string | undefined, - "base-url", - "text" - ), - beta: argv["beta"], - curl_example: resolveFileToken( - argv["curl-example"] as string | undefined, - "curl-example", - "text" - ), - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - enable: argv["enable"], - headers: resolveFileToken( - argv["headers"] as string | undefined, - "headers", - "text" - ), - js_example: resolveFileToken( - argv["js-example"] as string | undefined, - "js-example", - "text" - ), - link: resolveFileToken( - argv["link"] as string | undefined, - "link", - "text" - ), - logo: resolveFileToken( - argv["logo"] as string | undefined, - "logo", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - position: argv["position"], - slug: resolveFileToken( - argv["slug"] as string | undefined, - "slug", - "text" - ), - }), - sensitiveBodyPaths: [["headers"]], - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - base_url: resolveFileToken( - argv["base-url"] as string | undefined, - "base-url", - "text" - ), - beta: argv["beta"], - curl_example: resolveFileToken( - argv["curl-example"] as string | undefined, - "curl-example", - "text" - ), - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - enable: argv["enable"], - headers: resolveFileToken( - argv["headers"] as string | undefined, - "headers", - "text" - ), - js_example: resolveFileToken( - argv["js-example"] as string | undefined, - "js-example", - "text" - ), - link: resolveFileToken( - argv["link"] as string | undefined, - "link", - "text" - ), - logo: resolveFileToken( - argv["logo"] as string | undefined, - "logo", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - position: argv["position"], - slug: resolveFileToken( - argv["slug"] as string | undefined, - "slug", - "text" - ), - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 ai-gateway custom-providers update \n\nUpdates the specified fields of a custom provider. Changes clear cached entries for the provider.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/create.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/create.handler.ts new file mode 100644 index 0000000000..498242b974 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/create.handler.ts @@ -0,0 +1,102 @@ +import operation from "../../_operations/ai-gateway/dynamic-routing/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway dynamic-routing create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["elements"] === undefined) { + throw new Error( + "--elements is required (or pass --body with this field set)." + ); + } + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField("name", "The name field"); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway dynamic-routing create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/routes`, + pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + elements: parseObjectArray(argv["elements"], "elements"), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + gateway_id: argv["gateway-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + elements: parseObjectArray(argv["elements"], "elements"), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + gateway_id: argv["gateway-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/create.ts b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/create.ts index c67e8b667b..d4b46b9bbf 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/create.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/create.ts @@ -1,145 +1,50 @@ -import operation from "../../_operations/ai-gateway/dynamic-routing/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway dynamic-routing create \n\nCreates a dynamic route on an AI Gateway from the specified routing elements. Clients call the route by using `dynamic/{name}` as the model name." - ) - .positional("gateway-id", { - type: "string", - description: "Gateway ID", - demandOption: true, - }) - .option("elements", { - type: "string", - description: +const parameters = { + flags: { + elements: { + kind: "parsed", + brief: 'The elements field. Provide as a JSON array of objects or @path/to/file.json. Shape: [({"id": string, "outputs": {...}, "type": "start"} | {"id": string, "outputs": {...}, "properties": {...}, "type": "conditional"} | {"id": string, "outputs": {...}, "type": "percentage"} | ...more)].', - }) - .option("name", { type: "string", description: "The name field" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + name: { + kind: "parsed", + brief: "The name field", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [{ placeholder: "gateway-id", brief: "Gateway ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Create a dynamic route", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway dynamic-routing create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["elements"] === undefined) { - throw new Error( - "--elements is required (or pass --body with this field set)." - ); - } - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "The name field" - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway dynamic-routing create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/routes`, - pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - elements: parseObjectArray(argv["elements"], "elements"), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - gateway_id: argv["gateway-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - elements: parseObjectArray(argv["elements"], "elements"), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - gateway_id: argv["gateway-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 ai-gateway dynamic-routing create \n\nCreates a dynamic route on an AI Gateway from the specified routing elements. Clients call the route by using `dynamic/{name}` as the model name.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/delete.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/delete.handler.ts new file mode 100644 index 0000000000..4adc95b078 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/delete.handler.ts @@ -0,0 +1,59 @@ +import operation from "../../_operations/ai-gateway/dynamic-routing/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway dynamic-routing delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway dynamic-routing delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/routes/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, + pathParams: { + "gateway-id": String(argv["gateway-id"] ?? ""), + id: String(argv["id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/delete.ts b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/delete.ts index eacae83eeb..bf494dab0c 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/delete.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/delete.ts @@ -1,100 +1,38 @@ -import operation from "../../_operations/ai-gateway/dynamic-routing/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway dynamic-routing delete \n\nDeletes a dynamic route from an AI Gateway." - ) - .positional("id", { - type: "string", - description: "ID", - demandOption: true, - }) - .option("gateway-id", { - type: "string", - description: "Gateway ID", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "gateway-id": { kind: "parsed", brief: "Gateway ID", parse: String }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "id", brief: "ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete a dynamic route", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway dynamic-routing delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway dynamic-routing delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/routes/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, - pathParams: { - "gateway-id": String(argv["gateway-id"] ?? ""), - id: String(argv["id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 ai-gateway dynamic-routing delete \n\nDeletes a dynamic route from an AI Gateway.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/deployments/create.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/deployments/create.handler.ts new file mode 100644 index 0000000000..b54fefc5d7 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/deployments/create.handler.ts @@ -0,0 +1,103 @@ +import operation from "../../../_operations/ai-gateway/dynamic-routing/deployments/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway dynamic-routing deployments create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["version-id"] === undefined) { + argv["version-id"] = await promptForRequiredField( + "version-id", + "The version_id field" + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway dynamic-routing deployments create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/routes/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}/deployments`, + pathParams: { + "gateway-id": String(argv["gateway-id"] ?? ""), + id: String(argv["id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + version_id: resolveFileToken( + argv["version-id"] as string | undefined, + "version-id", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + version_id: resolveFileToken( + argv["version-id"] as string | undefined, + "version-id", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/deployments/create.ts b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/deployments/create.ts index d8201b1d71..c2c0d8527b 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/deployments/create.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/deployments/create.ts @@ -1,146 +1,44 @@ -import operation from "../../../_operations/ai-gateway/dynamic-routing/deployments/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway dynamic-routing deployments create \n\nDeploys the specified version of a dynamic route so that it serves traffic. Deploy an earlier version to roll back." - ) - .positional("id", { - type: "string", - description: "ID", - demandOption: true, - }) - .option("gateway-id", { - type: "string", - description: "Gateway ID", - demandOption: true, - }) - .option("version-id", { - type: "string", - description: "The version_id field", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "gateway-id": { kind: "parsed", brief: "Gateway ID", parse: String }, + "version-id": { + kind: "parsed", + brief: "The version_id field", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [{ placeholder: "id", brief: "ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Deploy a dynamic route version", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway dynamic-routing deployments create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["version-id"] === undefined) { - argv["version-id"] = await promptForRequiredField( - "version-id", - "The version_id field" - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway dynamic-routing deployments create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/routes/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}/deployments`, - pathParams: { - "gateway-id": String(argv["gateway-id"] ?? ""), - id: String(argv["id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - version_id: resolveFileToken( - argv["version-id"] as string | undefined, - "version-id", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - version_id: resolveFileToken( - argv["version-id"] as string | undefined, - "version-id", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 ai-gateway dynamic-routing deployments create \n\nDeploys the specified version of a dynamic route so that it serves traffic. Deploy an earlier version to roll back.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/deployments/index.ts b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/deployments/index.ts index 2eb8b23ff4..4cd9ac95b9 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/deployments/index.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/deployments/index.ts @@ -1,24 +1,19 @@ import $create from "./create.js"; import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * deployments command group * @generated from apis/overlays/ai-gateway.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "deployments", describe: "Deploy dynamic route versions and view deployment history", - builder: (yargs) => { - return yargs - .command($create) - .command($list) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/deployments/list.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/deployments/list.handler.ts new file mode 100644 index 0000000000..e934a11995 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/deployments/list.handler.ts @@ -0,0 +1,59 @@ +import operation from "../../../_operations/ai-gateway/dynamic-routing/deployments/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway dynamic-routing deployments list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway dynamic-routing deployments list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/routes/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}/deployments`, + pathParams: { + "gateway-id": String(argv["gateway-id"] ?? ""), + id: String(argv["id"] ?? ""), + }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/deployments/list.ts b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/deployments/list.ts index 6153ac6b26..bb73595d3a 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/deployments/list.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/deployments/list.ts @@ -1,95 +1,45 @@ -import operation from "../../../_operations/ai-gateway/dynamic-routing/deployments/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway dynamic-routing deployments list\n\nLists the deployment history of a dynamic route." - ) - .option("gateway-id", { - type: "string", - description: "Gateway ID", - demandOption: true, - }) - .option("id", { type: "string", description: "ID", demandOption: true }) - .option("page", { type: "number", description: "Page number" }) - .option("per-page", { - type: "number", - description: "Number of deployments per page", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "gateway-id": { kind: "parsed", brief: "Gateway ID", parse: String }, + id: { kind: "parsed", brief: "ID", parse: String }, + page: { + kind: "parsed", + brief: "Page number", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Number of deployments per page", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List dynamic route deployments", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway dynamic-routing deployments list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway dynamic-routing deployments list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/routes/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}/deployments`, - pathParams: { - "gateway-id": String(argv["gateway-id"] ?? ""), - id: String(argv["id"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-gateway dynamic-routing deployments list\n\nLists the deployment history of a dynamic route.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/get.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/get.handler.ts new file mode 100644 index 0000000000..19aade91bf --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/get.handler.ts @@ -0,0 +1,53 @@ +import operation from "../../_operations/ai-gateway/dynamic-routing/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway dynamic-routing get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway dynamic-routing get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/routes/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, + pathParams: { + "gateway-id": String(argv["gateway-id"] ?? ""), + id: String(argv["id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/get.ts b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/get.ts index a3584ad8a2..48c07e5076 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/get.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/get.ts @@ -1,88 +1,32 @@ -import operation from "../../_operations/ai-gateway/dynamic-routing/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway dynamic-routing get \n\nRetrieves a dynamic route with its routing elements, active version, and current deployment." - ) - .positional("id", { - type: "string", - description: "ID", - demandOption: true, - }) - .option("gateway-id", { - type: "string", - description: "Gateway ID", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "gateway-id": { kind: "parsed", brief: "Gateway ID", parse: String }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "id", brief: "ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get a dynamic route", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway dynamic-routing get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway dynamic-routing get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/routes/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, - pathParams: { - "gateway-id": String(argv["gateway-id"] ?? ""), - id: String(argv["id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-gateway dynamic-routing get \n\nRetrieves a dynamic route with its routing elements, active version, and current deployment.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/index.ts b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/index.ts index 323da423da..d3649525ad 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/index.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/index.ts @@ -5,31 +5,26 @@ import $get from "./get.js"; import $list from "./list.js"; import $update from "./update.js"; import $versions from "./versions/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * dynamic-routing command group * @generated from apis/overlays/ai-gateway.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "dynamic-routing", describe: "Route requests across multiple AI providers with fallback, load-balancing, and versioned deployments", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .command($list) - .command($update) - .command($deployments) - .command($versions) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, + list: $list, + update: $update, + deployments: $deployments, + versions: $versions, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/list.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/list.handler.ts new file mode 100644 index 0000000000..99fd6c4f57 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/list.handler.ts @@ -0,0 +1,55 @@ +import operation from "../../_operations/ai-gateway/dynamic-routing/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway dynamic-routing list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway dynamic-routing list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/routes`, + pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + gateway_id: argv["gateway-id"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/list.ts b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/list.ts index bc209bfc51..827cf54467 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/list.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/list.ts @@ -1,90 +1,44 @@ -import operation from "../../_operations/ai-gateway/dynamic-routing/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway dynamic-routing list\n\nLists the dynamic routes configured on an AI Gateway." - ) - .option("gateway-id", { - type: "string", - description: "Gateway ID", - demandOption: true, - }) - .option("page", { type: "number", description: "Page number" }) - .option("per-page", { - type: "number", - description: "Number of routes per page", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "gateway-id": { kind: "parsed", brief: "Gateway ID", parse: String }, + page: { + kind: "parsed", + brief: "Page number", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Number of routes per page", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List dynamic routes", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway dynamic-routing list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway dynamic-routing list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/routes`, - pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - gateway_id: argv["gateway-id"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-gateway dynamic-routing list\n\nLists the dynamic routes configured on an AI Gateway.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/update.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/update.handler.ts new file mode 100644 index 0000000000..8f6607cbe0 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/update.handler.ts @@ -0,0 +1,100 @@ +import operation from "../../_operations/ai-gateway/dynamic-routing/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway dynamic-routing update", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField("name", "The name field"); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway dynamic-routing update", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/routes/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, + pathParams: { + "gateway-id": String(argv["gateway-id"] ?? ""), + id: String(argv["id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/update.ts b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/update.ts index a16b592f3d..eedb0a20eb 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/update.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/update.ts @@ -1,143 +1,44 @@ -import operation from "../../_operations/ai-gateway/dynamic-routing/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway dynamic-routing update \n\nUpdates the name of a dynamic route. To change routing behaviour, create and deploy a new version." - ) - .positional("id", { - type: "string", - description: "ID", - demandOption: true, - }) - .option("gateway-id", { - type: "string", - description: "Gateway ID", - demandOption: true, - }) - .option("name", { type: "string", description: "The name field" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "gateway-id": { kind: "parsed", brief: "Gateway ID", parse: String }, + name: { + kind: "parsed", + brief: "The name field", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [{ placeholder: "id", brief: "ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update ", describe: "Rename a dynamic route", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway dynamic-routing update", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "The name field" - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway dynamic-routing update", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/routes/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, - pathParams: { - "gateway-id": String(argv["gateway-id"] ?? ""), - id: String(argv["id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 ai-gateway dynamic-routing update \n\nUpdates the name of a dynamic route. To change routing behaviour, create and deploy a new version.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/create.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/create.handler.ts new file mode 100644 index 0000000000..bd442d7b28 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/create.handler.ts @@ -0,0 +1,92 @@ +import operation from "../../../_operations/ai-gateway/dynamic-routing/versions/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway dynamic-routing versions create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["elements"] === undefined) { + throw new Error( + "--elements is required (or pass --body with this field set)." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway dynamic-routing versions create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/routes/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}/versions`, + pathParams: { + "gateway-id": String(argv["gateway-id"] ?? ""), + id: String(argv["id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + elements: parseObjectArray(argv["elements"], "elements"), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + elements: parseObjectArray(argv["elements"], "elements"), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/create.ts b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/create.ts index c05db32fe1..3538754512 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/create.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/create.ts @@ -1,136 +1,45 @@ -import operation from "../../../_operations/ai-gateway/dynamic-routing/versions/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway dynamic-routing versions create \n\nCreates a new version of a dynamic route from the specified routing elements. The version does not serve traffic until you deploy it." - ) - .positional("id", { - type: "string", - description: "ID", - demandOption: true, - }) - .option("gateway-id", { - type: "string", - description: "Gateway ID", - demandOption: true, - }) - .option("elements", { - type: "string", - description: +const parameters = { + flags: { + "gateway-id": { kind: "parsed", brief: "Gateway ID", parse: String }, + elements: { + kind: "parsed", + brief: 'The elements field. Provide as a JSON array of objects or @path/to/file.json. Shape: [({"id": string, "outputs": {...}, "type": "start"} | {"id": string, "outputs": {...}, "properties": {...}, "type": "conditional"} | {"id": string, "outputs": {...}, "type": "percentage"} | ...more)].', - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [{ placeholder: "id", brief: "ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Create a dynamic route version", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway dynamic-routing versions create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["elements"] === undefined) { - throw new Error( - "--elements is required (or pass --body with this field set)." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway dynamic-routing versions create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/routes/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}/versions`, - pathParams: { - "gateway-id": String(argv["gateway-id"] ?? ""), - id: String(argv["id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - elements: parseObjectArray(argv["elements"], "elements"), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - elements: parseObjectArray(argv["elements"], "elements"), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 ai-gateway dynamic-routing versions create \n\nCreates a new version of a dynamic route from the specified routing elements. The version does not serve traffic until you deploy it.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/get.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/get.handler.ts new file mode 100644 index 0000000000..3c9926375a --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/get.handler.ts @@ -0,0 +1,55 @@ +import operation from "../../../_operations/ai-gateway/dynamic-routing/versions/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway dynamic-routing versions get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway dynamic-routing versions get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/routes/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}/versions/${argv["version-id"] == null ? "" : encodeURIComponent(String(argv["version-id"]))}`, + pathParams: { + "gateway-id": String(argv["gateway-id"] ?? ""), + id: String(argv["id"] ?? ""), + "version-id": String(argv["version-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + version_id: argv["version-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/get.ts b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/get.ts index c93ee407c6..7b694a02da 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/get.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/get.ts @@ -1,91 +1,33 @@ -import operation from "../../../_operations/ai-gateway/dynamic-routing/versions/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway dynamic-routing versions get \n\nRetrieves a saved version of a dynamic route, including its routing elements." - ) - .positional("version-id", { - type: "string", - description: "Version ID", - demandOption: true, - }) - .option("gateway-id", { - type: "string", - description: "Gateway ID", - demandOption: true, - }) - .option("id", { type: "string", description: "ID", demandOption: true }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "gateway-id": { kind: "parsed", brief: "Gateway ID", parse: String }, + id: { kind: "parsed", brief: "ID", parse: String }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "version-id", brief: "Version ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get a dynamic route version", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway dynamic-routing versions get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway dynamic-routing versions get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/routes/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}/versions/${argv["version-id"] == null ? "" : encodeURIComponent(String(argv["version-id"]))}`, - pathParams: { - "gateway-id": String(argv["gateway-id"] ?? ""), - id: String(argv["id"] ?? ""), - "version-id": String(argv["version-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - version_id: argv["version-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-gateway dynamic-routing versions get \n\nRetrieves a saved version of a dynamic route, including its routing elements.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/index.ts b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/index.ts index 9d657751b9..c86f9ae704 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/index.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/index.ts @@ -1,26 +1,21 @@ import $create from "./create.js"; import $get from "./get.js"; import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * versions command group * @generated from apis/overlays/ai-gateway.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "versions", describe: "Create and inspect saved versions of a dynamic route", - builder: (yargs) => { - return yargs - .command($create) - .command($get) - .command($list) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + get: $get, + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/list.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/list.handler.ts new file mode 100644 index 0000000000..63f12789d1 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/list.handler.ts @@ -0,0 +1,59 @@ +import operation from "../../../_operations/ai-gateway/dynamic-routing/versions/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway dynamic-routing versions list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway dynamic-routing versions list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/routes/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}/versions`, + pathParams: { + "gateway-id": String(argv["gateway-id"] ?? ""), + id: String(argv["id"] ?? ""), + }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/list.ts b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/list.ts index 382591cce2..a6fd3a08a6 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/list.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/dynamic-routing/versions/list.ts @@ -1,95 +1,45 @@ -import operation from "../../../_operations/ai-gateway/dynamic-routing/versions/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway dynamic-routing versions list\n\nLists the saved versions of a dynamic route." - ) - .option("gateway-id", { - type: "string", - description: "Gateway ID", - demandOption: true, - }) - .option("id", { type: "string", description: "ID", demandOption: true }) - .option("page", { type: "number", description: "Page number" }) - .option("per-page", { - type: "number", - description: "Number of versions per page", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "gateway-id": { kind: "parsed", brief: "Gateway ID", parse: String }, + id: { kind: "parsed", brief: "ID", parse: String }, + page: { + kind: "parsed", + brief: "Page number", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Number of versions per page", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List dynamic route versions", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway dynamic-routing versions list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway dynamic-routing versions list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/routes/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}/versions`, - pathParams: { - "gateway-id": String(argv["gateway-id"] ?? ""), - id: String(argv["id"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-gateway dynamic-routing versions list\n\nLists the saved versions of a dynamic route.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/create.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/create.handler.ts new file mode 100644 index 0000000000..0f604bb9d9 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/create.handler.ts @@ -0,0 +1,323 @@ +import operation from "../../_operations/ai-gateway/gateways/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway gateways create", + classification: { + safeFlags: [ + "authentication", + "byok-only", + "cache-invalidate-on-update", + "collect-logs", + "guardrails-prompt-p1", + "guardrails-prompt-s1", + "guardrails-prompt-s10", + "guardrails-prompt-s11", + "guardrails-prompt-s12", + "guardrails-prompt-s13", + "guardrails-prompt-s14", + "guardrails-prompt-s2", + "guardrails-prompt-s3", + "guardrails-prompt-s4", + "guardrails-prompt-s5", + "guardrails-prompt-s6", + "guardrails-prompt-s7", + "guardrails-prompt-s8", + "guardrails-prompt-s9", + "guardrails-response-p1", + "guardrails-response-s1", + "guardrails-response-s10", + "guardrails-response-s11", + "guardrails-response-s12", + "guardrails-response-s13", + "guardrails-response-s14", + "guardrails-response-s2", + "guardrails-response-s3", + "guardrails-response-s4", + "guardrails-response-s5", + "guardrails-response-s6", + "guardrails-response-s7", + "guardrails-response-s8", + "guardrails-response-s9", + "log-classification", + "log-management-strategy", + "logpush", + "multiprovider-enabled", + "rate-limiting-technique", + "retry-backoff", + "spend-limits-enabled", + "workers-ai-billing-mode", + "zdr", + "dry-run", + ], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["cache-invalidate-on-update"] === undefined) { + throw new Error( + "--cache-invalidate-on-update is required (or pass --body with this field set)." + ); + } + if (argv["cache-ttl"] === undefined) { + throw new Error( + "--cache-ttl is required (or pass --body with this field set)." + ); + } + if (argv["collect-logs"] === undefined) { + throw new Error( + "--collect-logs is required (or pass --body with this field set)." + ); + } + if (argv["id"] === undefined) { + argv["id"] = await promptForRequiredField( + "id", + "Unique identifier of the AI Gateway within the account." + ); + } + if (argv["rate-limiting-interval"] === undefined) { + throw new Error( + "--rate-limiting-interval is required (or pass --body with this field set)." + ); + } + if (argv["rate-limiting-limit"] === undefined) { + throw new Error( + "--rate-limiting-limit is required (or pass --body with this field set)." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway gateways create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + authentication: argv["authentication"], + byok_only: argv["byok-only"], + cache_invalidate_on_update: + argv["cache-invalidate-on-update"], + cache_ttl: argv["cache-ttl"], + collect_logs: argv["collect-logs"], + guardrails: { + prompt: { + P1: argv["guardrails-prompt-p1"], + S1: argv["guardrails-prompt-s1"], + S10: argv["guardrails-prompt-s10"], + S11: argv["guardrails-prompt-s11"], + S12: argv["guardrails-prompt-s12"], + S13: argv["guardrails-prompt-s13"], + S14: argv["guardrails-prompt-s14"], + S2: argv["guardrails-prompt-s2"], + S3: argv["guardrails-prompt-s3"], + S4: argv["guardrails-prompt-s4"], + S5: argv["guardrails-prompt-s5"], + S6: argv["guardrails-prompt-s6"], + S7: argv["guardrails-prompt-s7"], + S8: argv["guardrails-prompt-s8"], + S9: argv["guardrails-prompt-s9"], + }, + response: { + P1: argv["guardrails-response-p1"], + S1: argv["guardrails-response-s1"], + S10: argv["guardrails-response-s10"], + S11: argv["guardrails-response-s11"], + S12: argv["guardrails-response-s12"], + S13: argv["guardrails-response-s13"], + S14: argv["guardrails-response-s14"], + S2: argv["guardrails-response-s2"], + S3: argv["guardrails-response-s3"], + S4: argv["guardrails-response-s4"], + S5: argv["guardrails-response-s5"], + S6: argv["guardrails-response-s6"], + S7: argv["guardrails-response-s7"], + S8: argv["guardrails-response-s8"], + S9: argv["guardrails-response-s9"], + }, + }, + id: resolveFileToken( + argv["id"] as string | undefined, + "id", + "text" + ), + log_classification: argv["log-classification"], + log_management: argv["log-management"], + log_management_strategy: argv["log-management-strategy"], + logpush: argv["logpush"], + logpush_public_key: resolveFileToken( + argv["logpush-public-key"] as string | undefined, + "logpush-public-key", + "text" + ), + multiprovider_enabled: argv["multiprovider-enabled"], + otel: parseObjectArray(argv["otel"], "otel", true), + rate_limiting_interval: argv["rate-limiting-interval"], + rate_limiting_limit: argv["rate-limiting-limit"], + rate_limiting_technique: argv["rate-limiting-technique"], + retry_backoff: argv["retry-backoff"], + retry_delay: argv["retry-delay"], + retry_max_attempts: argv["retry-max-attempts"], + spend_limits: { + enabled: argv["spend-limits-enabled"], + rules: parseObjectArray( + argv["spend-limits-rules"], + "spend-limits-rules" + ), + }, + store_id: resolveFileToken( + argv["store-id"] as string | undefined, + "store-id", + "text" + ), + stripe: { + authorization: resolveFileToken( + argv["stripe-authorization"] as string | undefined, + "stripe-authorization", + "text" + ), + usage_events: parseObjectArray( + argv["stripe-usage-events"], + "stripe-usage-events" + ), + }, + workers_ai_billing_mode: argv["workers-ai-billing-mode"], + zdr: argv["zdr"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + authentication: argv["authentication"], + byok_only: argv["byok-only"], + cache_invalidate_on_update: argv["cache-invalidate-on-update"], + cache_ttl: argv["cache-ttl"], + collect_logs: argv["collect-logs"], + guardrails: { + prompt: { + P1: argv["guardrails-prompt-p1"], + S1: argv["guardrails-prompt-s1"], + S10: argv["guardrails-prompt-s10"], + S11: argv["guardrails-prompt-s11"], + S12: argv["guardrails-prompt-s12"], + S13: argv["guardrails-prompt-s13"], + S14: argv["guardrails-prompt-s14"], + S2: argv["guardrails-prompt-s2"], + S3: argv["guardrails-prompt-s3"], + S4: argv["guardrails-prompt-s4"], + S5: argv["guardrails-prompt-s5"], + S6: argv["guardrails-prompt-s6"], + S7: argv["guardrails-prompt-s7"], + S8: argv["guardrails-prompt-s8"], + S9: argv["guardrails-prompt-s9"], + }, + response: { + P1: argv["guardrails-response-p1"], + S1: argv["guardrails-response-s1"], + S10: argv["guardrails-response-s10"], + S11: argv["guardrails-response-s11"], + S12: argv["guardrails-response-s12"], + S13: argv["guardrails-response-s13"], + S14: argv["guardrails-response-s14"], + S2: argv["guardrails-response-s2"], + S3: argv["guardrails-response-s3"], + S4: argv["guardrails-response-s4"], + S5: argv["guardrails-response-s5"], + S6: argv["guardrails-response-s6"], + S7: argv["guardrails-response-s7"], + S8: argv["guardrails-response-s8"], + S9: argv["guardrails-response-s9"], + }, + }, + id: resolveFileToken(argv["id"] as string | undefined, "id", "text"), + log_classification: argv["log-classification"], + log_management: argv["log-management"], + log_management_strategy: argv["log-management-strategy"], + logpush: argv["logpush"], + logpush_public_key: resolveFileToken( + argv["logpush-public-key"] as string | undefined, + "logpush-public-key", + "text" + ), + multiprovider_enabled: argv["multiprovider-enabled"], + otel: parseObjectArray(argv["otel"], "otel", true), + rate_limiting_interval: argv["rate-limiting-interval"], + rate_limiting_limit: argv["rate-limiting-limit"], + rate_limiting_technique: argv["rate-limiting-technique"], + retry_backoff: argv["retry-backoff"], + retry_delay: argv["retry-delay"], + retry_max_attempts: argv["retry-max-attempts"], + spend_limits: { + enabled: argv["spend-limits-enabled"], + rules: parseObjectArray( + argv["spend-limits-rules"], + "spend-limits-rules" + ), + }, + store_id: resolveFileToken( + argv["store-id"] as string | undefined, + "store-id", + "text" + ), + stripe: { + authorization: resolveFileToken( + argv["stripe-authorization"] as string | undefined, + "stripe-authorization", + "text" + ), + usage_events: parseObjectArray( + argv["stripe-usage-events"], + "stripe-usage-events" + ), + }, + workers_ai_billing_mode: argv["workers-ai-billing-mode"], + zdr: argv["zdr"], + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/create.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/create.ts index 184faa8533..ed961db771 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/gateways/create.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/create.ts @@ -1,400 +1,460 @@ -import operation from "../../_operations/ai-gateway/gateways/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway gateways create\n\nCreates an AI Gateway in the account with the specified caching, rate limiting, logging, and authentication settings. The gateway ID appears in request URLs and must be unique within the account." - ) - .option("authentication", { - type: "boolean", - description: +const parameters = { + flags: { + authentication: { + kind: "boolean", + brief: "Require authentication for gateway access. New gateways must have authentication enabled. Once enabled, authentication cannot be disabled.", - }) - .option("byok-only", { - type: "boolean", - description: + optional: true, + }, + "byok-only": { + kind: "boolean", + brief: "Requires customer-provided provider credentials and prevents fallback to Unified Billing.", - }) - .option("cache-invalidate-on-update", { - type: "boolean", - description: "The cache_invalidate_on_update field", - }) - .option("cache-ttl", { type: "number", description: "The cache_ttl field" }) - .option("collect-logs", { - type: "boolean", - description: "The collect_logs field", - }) - .option("guardrails-prompt-p1", { - type: "string", - description: "The guardrails.prompt.P1 field", + optional: true, + }, + "cache-invalidate-on-update": { + kind: "boolean", + brief: "The cache_invalidate_on_update field", + optional: true, + }, + "cache-ttl": { + kind: "parsed", + brief: "The cache_ttl field", + optional: true, + parse: Number, + }, + "collect-logs": { + kind: "boolean", + brief: "The collect_logs field", + optional: true, + }, + "guardrails-prompt-p1": { + kind: "parsed", + brief: "The guardrails.prompt.P1 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-p1", (value) => - resolveFileToken(value, "guardrails-prompt-p1", "text") - ) - .option("guardrails-prompt-s1", { - type: "string", - description: "The guardrails.prompt.S1 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-p1", "text"), + }, + "guardrails-prompt-s1": { + kind: "parsed", + brief: "The guardrails.prompt.S1 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s1", (value) => - resolveFileToken(value, "guardrails-prompt-s1", "text") - ) - .option("guardrails-prompt-s10", { - type: "string", - description: "The guardrails.prompt.S10 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s1", "text"), + }, + "guardrails-prompt-s10": { + kind: "parsed", + brief: "The guardrails.prompt.S10 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s10", (value) => - resolveFileToken(value, "guardrails-prompt-s10", "text") - ) - .option("guardrails-prompt-s11", { - type: "string", - description: "The guardrails.prompt.S11 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s10", "text"), + }, + "guardrails-prompt-s11": { + kind: "parsed", + brief: "The guardrails.prompt.S11 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s11", (value) => - resolveFileToken(value, "guardrails-prompt-s11", "text") - ) - .option("guardrails-prompt-s12", { - type: "string", - description: "The guardrails.prompt.S12 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s11", "text"), + }, + "guardrails-prompt-s12": { + kind: "parsed", + brief: "The guardrails.prompt.S12 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s12", (value) => - resolveFileToken(value, "guardrails-prompt-s12", "text") - ) - .option("guardrails-prompt-s13", { - type: "string", - description: "The guardrails.prompt.S13 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s12", "text"), + }, + "guardrails-prompt-s13": { + kind: "parsed", + brief: "The guardrails.prompt.S13 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s13", (value) => - resolveFileToken(value, "guardrails-prompt-s13", "text") - ) - .option("guardrails-prompt-s14", { - type: "string", - description: "The guardrails.prompt.S14 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s13", "text"), + }, + "guardrails-prompt-s14": { + kind: "parsed", + brief: "The guardrails.prompt.S14 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s14", (value) => - resolveFileToken(value, "guardrails-prompt-s14", "text") - ) - .option("guardrails-prompt-s2", { - type: "string", - description: "The guardrails.prompt.S2 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s14", "text"), + }, + "guardrails-prompt-s2": { + kind: "parsed", + brief: "The guardrails.prompt.S2 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s2", (value) => - resolveFileToken(value, "guardrails-prompt-s2", "text") - ) - .option("guardrails-prompt-s3", { - type: "string", - description: "The guardrails.prompt.S3 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s2", "text"), + }, + "guardrails-prompt-s3": { + kind: "parsed", + brief: "The guardrails.prompt.S3 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s3", (value) => - resolveFileToken(value, "guardrails-prompt-s3", "text") - ) - .option("guardrails-prompt-s4", { - type: "string", - description: "The guardrails.prompt.S4 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s3", "text"), + }, + "guardrails-prompt-s4": { + kind: "parsed", + brief: "The guardrails.prompt.S4 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s4", (value) => - resolveFileToken(value, "guardrails-prompt-s4", "text") - ) - .option("guardrails-prompt-s5", { - type: "string", - description: "The guardrails.prompt.S5 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s4", "text"), + }, + "guardrails-prompt-s5": { + kind: "parsed", + brief: "The guardrails.prompt.S5 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s5", (value) => - resolveFileToken(value, "guardrails-prompt-s5", "text") - ) - .option("guardrails-prompt-s6", { - type: "string", - description: "The guardrails.prompt.S6 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s5", "text"), + }, + "guardrails-prompt-s6": { + kind: "parsed", + brief: "The guardrails.prompt.S6 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s6", (value) => - resolveFileToken(value, "guardrails-prompt-s6", "text") - ) - .option("guardrails-prompt-s7", { - type: "string", - description: "The guardrails.prompt.S7 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s6", "text"), + }, + "guardrails-prompt-s7": { + kind: "parsed", + brief: "The guardrails.prompt.S7 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s7", (value) => - resolveFileToken(value, "guardrails-prompt-s7", "text") - ) - .option("guardrails-prompt-s8", { - type: "string", - description: "The guardrails.prompt.S8 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s7", "text"), + }, + "guardrails-prompt-s8": { + kind: "parsed", + brief: "The guardrails.prompt.S8 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s8", (value) => - resolveFileToken(value, "guardrails-prompt-s8", "text") - ) - .option("guardrails-prompt-s9", { - type: "string", - description: "The guardrails.prompt.S9 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s8", "text"), + }, + "guardrails-prompt-s9": { + kind: "parsed", + brief: "The guardrails.prompt.S9 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s9", (value) => - resolveFileToken(value, "guardrails-prompt-s9", "text") - ) - .option("guardrails-response-p1", { - type: "string", - description: "The guardrails.response.P1 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s9", "text"), + }, + "guardrails-response-p1": { + kind: "parsed", + brief: "The guardrails.response.P1 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-p1", (value) => - resolveFileToken(value, "guardrails-response-p1", "text") - ) - .option("guardrails-response-s1", { - type: "string", - description: "The guardrails.response.S1 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-p1", "text"), + }, + "guardrails-response-s1": { + kind: "parsed", + brief: "The guardrails.response.S1 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s1", (value) => - resolveFileToken(value, "guardrails-response-s1", "text") - ) - .option("guardrails-response-s10", { - type: "string", - description: "The guardrails.response.S10 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s1", "text"), + }, + "guardrails-response-s10": { + kind: "parsed", + brief: "The guardrails.response.S10 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s10", (value) => - resolveFileToken(value, "guardrails-response-s10", "text") - ) - .option("guardrails-response-s11", { - type: "string", - description: "The guardrails.response.S11 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s10", "text"), + }, + "guardrails-response-s11": { + kind: "parsed", + brief: "The guardrails.response.S11 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s11", (value) => - resolveFileToken(value, "guardrails-response-s11", "text") - ) - .option("guardrails-response-s12", { - type: "string", - description: "The guardrails.response.S12 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s11", "text"), + }, + "guardrails-response-s12": { + kind: "parsed", + brief: "The guardrails.response.S12 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s12", (value) => - resolveFileToken(value, "guardrails-response-s12", "text") - ) - .option("guardrails-response-s13", { - type: "string", - description: "The guardrails.response.S13 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s12", "text"), + }, + "guardrails-response-s13": { + kind: "parsed", + brief: "The guardrails.response.S13 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s13", (value) => - resolveFileToken(value, "guardrails-response-s13", "text") - ) - .option("guardrails-response-s14", { - type: "string", - description: "The guardrails.response.S14 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s13", "text"), + }, + "guardrails-response-s14": { + kind: "parsed", + brief: "The guardrails.response.S14 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s14", (value) => - resolveFileToken(value, "guardrails-response-s14", "text") - ) - .option("guardrails-response-s2", { - type: "string", - description: "The guardrails.response.S2 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s14", "text"), + }, + "guardrails-response-s2": { + kind: "parsed", + brief: "The guardrails.response.S2 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s2", (value) => - resolveFileToken(value, "guardrails-response-s2", "text") - ) - .option("guardrails-response-s3", { - type: "string", - description: "The guardrails.response.S3 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s2", "text"), + }, + "guardrails-response-s3": { + kind: "parsed", + brief: "The guardrails.response.S3 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s3", (value) => - resolveFileToken(value, "guardrails-response-s3", "text") - ) - .option("guardrails-response-s4", { - type: "string", - description: "The guardrails.response.S4 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s3", "text"), + }, + "guardrails-response-s4": { + kind: "parsed", + brief: "The guardrails.response.S4 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s4", (value) => - resolveFileToken(value, "guardrails-response-s4", "text") - ) - .option("guardrails-response-s5", { - type: "string", - description: "The guardrails.response.S5 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s4", "text"), + }, + "guardrails-response-s5": { + kind: "parsed", + brief: "The guardrails.response.S5 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s5", (value) => - resolveFileToken(value, "guardrails-response-s5", "text") - ) - .option("guardrails-response-s6", { - type: "string", - description: "The guardrails.response.S6 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s5", "text"), + }, + "guardrails-response-s6": { + kind: "parsed", + brief: "The guardrails.response.S6 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s6", (value) => - resolveFileToken(value, "guardrails-response-s6", "text") - ) - .option("guardrails-response-s7", { - type: "string", - description: "The guardrails.response.S7 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s6", "text"), + }, + "guardrails-response-s7": { + kind: "parsed", + brief: "The guardrails.response.S7 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s7", (value) => - resolveFileToken(value, "guardrails-response-s7", "text") - ) - .option("guardrails-response-s8", { - type: "string", - description: "The guardrails.response.S8 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s7", "text"), + }, + "guardrails-response-s8": { + kind: "parsed", + brief: "The guardrails.response.S8 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s8", (value) => - resolveFileToken(value, "guardrails-response-s8", "text") - ) - .option("guardrails-response-s9", { - type: "string", - description: "The guardrails.response.S9 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s8", "text"), + }, + "guardrails-response-s9": { + kind: "parsed", + brief: "The guardrails.response.S9 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s9", (value) => - resolveFileToken(value, "guardrails-response-s9", "text") - ) - .option("id", { - type: "string", - description: "Unique identifier of the AI Gateway within the account.", - }) - .option("log-classification", { - type: "boolean", - description: "The log_classification field", - }) - .option("log-management", { - type: "number", - description: "The log_management field", - }) - .option("log-management-strategy", { - type: "string", - description: "The log_management_strategy field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s9", "text"), + }, + id: { + kind: "parsed", + brief: "Unique identifier of the AI Gateway within the account.", + optional: true, + parse: String, + }, + "log-classification": { + kind: "boolean", + brief: "The log_classification field", + optional: true, + }, + "log-management": { + kind: "parsed", + brief: "The log_management field", + optional: true, + parse: Number, + }, + "log-management-strategy": { + kind: "parsed", + brief: "The log_management_strategy field", + optional: true, choices: ["STOP_INSERTING", "DELETE_OLDEST"], - }) - .coerce("log-management-strategy", (value) => - resolveFileToken(value, "log-management-strategy", "text") - ) - .option("logpush", { type: "boolean", description: "The logpush field" }) - .option("logpush-public-key", { - type: "string", - description: "The logpush_public_key field", - }) - .option("multiprovider-enabled", { - type: "boolean", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "log-management-strategy", "text"), + }, + logpush: { kind: "boolean", brief: "The logpush field", optional: true }, + "logpush-public-key": { + kind: "parsed", + brief: "The logpush_public_key field", + optional: true, + parse: String, + }, + "multiprovider-enabled": { + kind: "boolean", + brief: "Lets requests to a model use every provider that serves it. When off, a model uses only the providers it launched with, so a provider added later receives none of its traffic. A request that names providers (the cf-aig-allowed-providers header or routing.allowedProviders) can still use any of them. Model aliases (custom/) are not restricted.", - }) - .option("otel", { - type: "string", - description: + optional: true, + }, + otel: { + kind: "parsed", + brief: 'The otel field. Provide as a JSON array of objects, null, or @path/to/file.json. Shape: [{"headers": {...}, "url": string, "authorization"?: string, "content_type"?: "json" | "protobuf"}]. ? marks optional keys.', - }) - .option("rate-limiting-interval", { - type: "number", - description: "The rate_limiting_interval field", - }) - .option("rate-limiting-limit", { - type: "number", - description: "The rate_limiting_limit field", - }) - .option("rate-limiting-technique", { - type: "string", - description: "The rate_limiting_technique field", + optional: true, + parse: String, + }, + "rate-limiting-interval": { + kind: "parsed", + brief: "The rate_limiting_interval field", + optional: true, + parse: Number, + }, + "rate-limiting-limit": { + kind: "parsed", + brief: "The rate_limiting_limit field", + optional: true, + parse: Number, + }, + "rate-limiting-technique": { + kind: "parsed", + brief: "The rate_limiting_technique field", + optional: true, choices: ["fixed", "sliding"], - }) - .coerce("rate-limiting-technique", (value) => - resolveFileToken(value, "rate-limiting-technique", "text") - ) - .option("retry-backoff", { - type: "string", - description: "Backoff strategy for retry delays", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "rate-limiting-technique", "text"), + }, + "retry-backoff": { + kind: "parsed", + brief: "Backoff strategy for retry delays", + optional: true, choices: ["constant", "linear", "exponential"], - }) - .coerce("retry-backoff", (value) => - resolveFileToken(value, "retry-backoff", "text") - ) - .option("retry-delay", { - type: "number", - description: "Delay between retry attempts in milliseconds (0-60000)", - }) - .option("retry-max-attempts", { - type: "number", - description: "Maximum number of retry attempts for failed requests (1-5)", - }) - .option("spend-limits-enabled", { - type: "boolean", - description: "The spend_limits.enabled field", - }) - .option("spend-limits-rules", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "retry-backoff", "text"), + }, + "retry-delay": { + kind: "parsed", + brief: "Delay between retry attempts in milliseconds (0-60000)", + optional: true, + parse: Number, + }, + "retry-max-attempts": { + kind: "parsed", + brief: "Maximum number of retry attempts for failed requests (1-5)", + optional: true, + parse: Number, + }, + "spend-limits-enabled": { + kind: "boolean", + brief: "The spend_limits.enabled field", + optional: true, + }, + "spend-limits-rules": { + kind: "parsed", + brief: 'The spend_limits.rules field. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"limit": number, "limitType": "cost", "window": number, "enabled"?: boolean, "id"?: string, ...more}]. ? marks optional keys.', - }) - .option("store-id", { - type: "string", - description: + optional: true, + parse: String, + }, + "store-id": { + kind: "parsed", + brief: "Secrets Store used by this gateway. Omit on update to keep the current store. Cannot be cleared while stored keys or secret references depend on it.", - }) - .option("stripe-authorization", { - type: "string", - description: "The stripe.authorization field", - }) - .option("stripe-usage-events", { - type: "string", - description: + optional: true, + parse: String, + }, + "stripe-authorization": { + kind: "parsed", + brief: "The stripe.authorization field", + optional: true, + parse: String, + }, + "stripe-usage-events": { + kind: "parsed", + brief: 'The stripe.usage_events field. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"payload": string}].', - }) - .option("workers-ai-billing-mode", { - type: "string", - description: + optional: true, + parse: String, + }, + "workers-ai-billing-mode": { + kind: "parsed", + brief: "Controls how Workers AI inference calls routed through this gateway are billed. 'postpaid' bills the account directly through Workers AI; 'unified' deducts credits via AI Gateway using neuron-based pricing and delegates billing to AI Gateway.", - choices: ["postpaid", "unified"], default: "postpaid", - }) - .coerce("workers-ai-billing-mode", (value) => - resolveFileToken(value, "workers-ai-billing-mode", "text") - ) - .option("zdr", { type: "boolean", description: "The zdr field" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + choices: ["postpaid", "unified"], + parse: String, + coerce: (value: string) => + resolveFileToken(value, "workers-ai-billing-mode", "text"), + }, + zdr: { kind: "boolean", brief: "The zdr field", optional: true }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }) - .check((argv) => { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], + rules(rules) { + rules.check((argv) => { const groupSet = ["stripe-authorization", "stripe-usage-events"].some( (k) => argv[k] !== undefined ); @@ -410,319 +470,16 @@ function builder(yargs: Argv) { } return true; }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Create a gateway", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway gateways create", - classification: { - safeFlags: [ - "authentication", - "byok-only", - "cache-invalidate-on-update", - "collect-logs", - "guardrails-prompt-p1", - "guardrails-prompt-s1", - "guardrails-prompt-s10", - "guardrails-prompt-s11", - "guardrails-prompt-s12", - "guardrails-prompt-s13", - "guardrails-prompt-s14", - "guardrails-prompt-s2", - "guardrails-prompt-s3", - "guardrails-prompt-s4", - "guardrails-prompt-s5", - "guardrails-prompt-s6", - "guardrails-prompt-s7", - "guardrails-prompt-s8", - "guardrails-prompt-s9", - "guardrails-response-p1", - "guardrails-response-s1", - "guardrails-response-s10", - "guardrails-response-s11", - "guardrails-response-s12", - "guardrails-response-s13", - "guardrails-response-s14", - "guardrails-response-s2", - "guardrails-response-s3", - "guardrails-response-s4", - "guardrails-response-s5", - "guardrails-response-s6", - "guardrails-response-s7", - "guardrails-response-s8", - "guardrails-response-s9", - "log-classification", - "log-management-strategy", - "logpush", - "multiprovider-enabled", - "rate-limiting-technique", - "retry-backoff", - "spend-limits-enabled", - "workers-ai-billing-mode", - "zdr", - "dry-run", - ], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["cache-invalidate-on-update"] === undefined) { - throw new Error( - "--cache-invalidate-on-update is required (or pass --body with this field set)." - ); - } - if (argv["cache-ttl"] === undefined) { - throw new Error( - "--cache-ttl is required (or pass --body with this field set)." - ); - } - if (argv["collect-logs"] === undefined) { - throw new Error( - "--collect-logs is required (or pass --body with this field set)." - ); - } - if (argv["id"] === undefined) { - argv["id"] = await promptForRequiredField( - "id", - "Unique identifier of the AI Gateway within the account." - ); - } - if (argv["rate-limiting-interval"] === undefined) { - throw new Error( - "--rate-limiting-interval is required (or pass --body with this field set)." - ); - } - if (argv["rate-limiting-limit"] === undefined) { - throw new Error( - "--rate-limiting-limit is required (or pass --body with this field set)." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway gateways create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - authentication: argv["authentication"], - byok_only: argv["byok-only"], - cache_invalidate_on_update: - argv["cache-invalidate-on-update"], - cache_ttl: argv["cache-ttl"], - collect_logs: argv["collect-logs"], - guardrails: { - prompt: { - P1: argv["guardrails-prompt-p1"], - S1: argv["guardrails-prompt-s1"], - S10: argv["guardrails-prompt-s10"], - S11: argv["guardrails-prompt-s11"], - S12: argv["guardrails-prompt-s12"], - S13: argv["guardrails-prompt-s13"], - S14: argv["guardrails-prompt-s14"], - S2: argv["guardrails-prompt-s2"], - S3: argv["guardrails-prompt-s3"], - S4: argv["guardrails-prompt-s4"], - S5: argv["guardrails-prompt-s5"], - S6: argv["guardrails-prompt-s6"], - S7: argv["guardrails-prompt-s7"], - S8: argv["guardrails-prompt-s8"], - S9: argv["guardrails-prompt-s9"], - }, - response: { - P1: argv["guardrails-response-p1"], - S1: argv["guardrails-response-s1"], - S10: argv["guardrails-response-s10"], - S11: argv["guardrails-response-s11"], - S12: argv["guardrails-response-s12"], - S13: argv["guardrails-response-s13"], - S14: argv["guardrails-response-s14"], - S2: argv["guardrails-response-s2"], - S3: argv["guardrails-response-s3"], - S4: argv["guardrails-response-s4"], - S5: argv["guardrails-response-s5"], - S6: argv["guardrails-response-s6"], - S7: argv["guardrails-response-s7"], - S8: argv["guardrails-response-s8"], - S9: argv["guardrails-response-s9"], - }, - }, - id: resolveFileToken( - argv["id"] as string | undefined, - "id", - "text" - ), - log_classification: argv["log-classification"], - log_management: argv["log-management"], - log_management_strategy: argv["log-management-strategy"], - logpush: argv["logpush"], - logpush_public_key: resolveFileToken( - argv["logpush-public-key"] as string | undefined, - "logpush-public-key", - "text" - ), - multiprovider_enabled: argv["multiprovider-enabled"], - otel: parseObjectArray(argv["otel"], "otel", true), - rate_limiting_interval: argv["rate-limiting-interval"], - rate_limiting_limit: argv["rate-limiting-limit"], - rate_limiting_technique: argv["rate-limiting-technique"], - retry_backoff: argv["retry-backoff"], - retry_delay: argv["retry-delay"], - retry_max_attempts: argv["retry-max-attempts"], - spend_limits: { - enabled: argv["spend-limits-enabled"], - rules: parseObjectArray( - argv["spend-limits-rules"], - "spend-limits-rules" - ), - }, - store_id: resolveFileToken( - argv["store-id"] as string | undefined, - "store-id", - "text" - ), - stripe: { - authorization: resolveFileToken( - argv["stripe-authorization"] as string | undefined, - "stripe-authorization", - "text" - ), - usage_events: parseObjectArray( - argv["stripe-usage-events"], - "stripe-usage-events" - ), - }, - workers_ai_billing_mode: argv["workers-ai-billing-mode"], - zdr: argv["zdr"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - authentication: argv["authentication"], - byok_only: argv["byok-only"], - cache_invalidate_on_update: argv["cache-invalidate-on-update"], - cache_ttl: argv["cache-ttl"], - collect_logs: argv["collect-logs"], - guardrails: { - prompt: { - P1: argv["guardrails-prompt-p1"], - S1: argv["guardrails-prompt-s1"], - S10: argv["guardrails-prompt-s10"], - S11: argv["guardrails-prompt-s11"], - S12: argv["guardrails-prompt-s12"], - S13: argv["guardrails-prompt-s13"], - S14: argv["guardrails-prompt-s14"], - S2: argv["guardrails-prompt-s2"], - S3: argv["guardrails-prompt-s3"], - S4: argv["guardrails-prompt-s4"], - S5: argv["guardrails-prompt-s5"], - S6: argv["guardrails-prompt-s6"], - S7: argv["guardrails-prompt-s7"], - S8: argv["guardrails-prompt-s8"], - S9: argv["guardrails-prompt-s9"], - }, - response: { - P1: argv["guardrails-response-p1"], - S1: argv["guardrails-response-s1"], - S10: argv["guardrails-response-s10"], - S11: argv["guardrails-response-s11"], - S12: argv["guardrails-response-s12"], - S13: argv["guardrails-response-s13"], - S14: argv["guardrails-response-s14"], - S2: argv["guardrails-response-s2"], - S3: argv["guardrails-response-s3"], - S4: argv["guardrails-response-s4"], - S5: argv["guardrails-response-s5"], - S6: argv["guardrails-response-s6"], - S7: argv["guardrails-response-s7"], - S8: argv["guardrails-response-s8"], - S9: argv["guardrails-response-s9"], - }, - }, - id: resolveFileToken(argv["id"] as string | undefined, "id", "text"), - log_classification: argv["log-classification"], - log_management: argv["log-management"], - log_management_strategy: argv["log-management-strategy"], - logpush: argv["logpush"], - logpush_public_key: resolveFileToken( - argv["logpush-public-key"] as string | undefined, - "logpush-public-key", - "text" - ), - multiprovider_enabled: argv["multiprovider-enabled"], - otel: parseObjectArray(argv["otel"], "otel", true), - rate_limiting_interval: argv["rate-limiting-interval"], - rate_limiting_limit: argv["rate-limiting-limit"], - rate_limiting_technique: argv["rate-limiting-technique"], - retry_backoff: argv["retry-backoff"], - retry_delay: argv["retry-delay"], - retry_max_attempts: argv["retry-max-attempts"], - spend_limits: { - enabled: argv["spend-limits-enabled"], - rules: parseObjectArray( - argv["spend-limits-rules"], - "spend-limits-rules" - ), - }, - store_id: resolveFileToken( - argv["store-id"] as string | undefined, - "store-id", - "text" - ), - stripe: { - authorization: resolveFileToken( - argv["stripe-authorization"] as string | undefined, - "stripe-authorization", - "text" - ), - usage_events: parseObjectArray( - argv["stripe-usage-events"], - "stripe-usage-events" - ), - }, - workers_ai_billing_mode: argv["workers-ai-billing-mode"], - zdr: argv["zdr"], - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 ai-gateway gateways create\n\nCreates an AI Gateway in the account with the specified caching, rate limiting, logging, and authentication settings. The gateway ID appears in request URLs and must be unique within the account.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/delete.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/delete.handler.ts new file mode 100644 index 0000000000..db0606b50d --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/delete.handler.ts @@ -0,0 +1,61 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway gateways delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway gateways delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}`, + pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This permanently deletes the gateway, its configuration, and its stored logs. Requests sent to this gateway will fail. This action cannot be undone.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + requestApi( + client, + "DELETE", + `/accounts/${accountId}/ai-gateway/gateways/${encodeURIComponent(String(argv["gateway-id"]))}` + ) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/delete.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/delete.ts index dce68fae09..9333e50fe0 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/gateways/delete.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/delete.ts @@ -1,97 +1,43 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway gateways delete \n\nPermanently deletes an AI Gateway, its configuration, and its stored logs." - ) - .positional("gateway-id", { - type: "string", - description: "Unique identifier of the AI Gateway within the account.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "gateway-id", + brief: "Unique identifier of the AI Gateway within the account.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete a gateway", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway gateways delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway gateways delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}`, - pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This permanently deletes the gateway, its configuration, and its stored logs. Requests sent to this gateway will fail. This action cannot be undone.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - requestApi( - client, - "DELETE", - `/accounts/${accountId}/ai-gateway/gateways/${encodeURIComponent(String(argv["gateway-id"]))}` - ) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 ai-gateway gateways delete \n\nPermanently deletes an AI Gateway, its configuration, and its stored logs.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/get-url.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/get-url.handler.ts new file mode 100644 index 0000000000..79dd209b75 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/get-url.handler.ts @@ -0,0 +1,53 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get-url.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway gateways get-url", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway gateways get-url", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/url/${argv["ai-gateway-provider"] == null ? "" : encodeURIComponent(String(argv["ai-gateway-provider"]))}`, + pathParams: { + "gateway-id": String(argv["gateway-id"] ?? ""), + "ai-gateway-provider": String(argv["ai-gateway-provider"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + requestApi( + client, + "GET", + `/accounts/${accountId}/ai-gateway/gateways/${encodeURIComponent(String(argv["gateway-id"]))}/url/${encodeURIComponent(String(argv["ai-gateway-provider"]))}` + ) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/get-url.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/get-url.ts index f9b173bcbf..04b71ae3d5 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/gateways/get-url.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/get-url.ts @@ -1,88 +1,38 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get-url command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway gateways get-url \n\nRetrieves the endpoint URL for an AI Gateway." - ) - .positional("ai-gateway-provider", { - type: "string", - description: "Provider", - demandOption: true, - }) - .option("gateway-id", { - type: "string", - description: "Unique identifier of the AI Gateway within the account.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "gateway-id": { + kind: "parsed", + brief: "Unique identifier of the AI Gateway within the account.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "ai-gateway-provider", brief: "Provider", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get-url ", describe: "Get Gateway URL", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway gateways get-url", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway gateways get-url", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/url/${argv["ai-gateway-provider"] == null ? "" : encodeURIComponent(String(argv["ai-gateway-provider"]))}`, - pathParams: { - "gateway-id": String(argv["gateway-id"] ?? ""), - "ai-gateway-provider": String(argv["ai-gateway-provider"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - requestApi( - client, - "GET", - `/accounts/${accountId}/ai-gateway/gateways/${encodeURIComponent(String(argv["gateway-id"]))}/url/${encodeURIComponent(String(argv["ai-gateway-provider"]))}` - ) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-gateway gateways get-url \n\nRetrieves the endpoint URL for an AI Gateway.", + ...parameters, + loader: () => import("./get-url.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/get.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/get.handler.ts new file mode 100644 index 0000000000..7928ae365a --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/get.handler.ts @@ -0,0 +1,50 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway gateways get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway gateways get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}`, + pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + requestApi( + client, + "GET", + `/accounts/${accountId}/ai-gateway/gateways/${encodeURIComponent(String(argv["gateway-id"]))}` + ) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/get.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/get.ts index 8c8bcfcc1c..081e487966 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/gateways/get.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/get.ts @@ -1,80 +1,37 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway gateways get \n\nRetrieves the configuration of an AI Gateway." - ) - .positional("gateway-id", { - type: "string", - description: "Unique identifier of the AI Gateway within the account.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "gateway-id", + brief: "Unique identifier of the AI Gateway within the account.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get a gateway", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway gateways get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway gateways get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}`, - pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - requestApi( - client, - "GET", - `/accounts/${accountId}/ai-gateway/gateways/${encodeURIComponent(String(argv["gateway-id"]))}` - ) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-gateway gateways get \n\nRetrieves the configuration of an AI Gateway.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/index.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/index.ts index cdb4c0e799..97a994dd58 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/gateways/index.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/index.ts @@ -5,30 +5,25 @@ import $get from "./get.js"; import $list from "./list.js"; import $providers from "./providers/index.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * gateways command group * @generated from apis/overlays/ai-gateway.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "gateways", describe: "Create and configure AI Gateways for an account", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .command($geturl) - .command($list) - .command($update) - .command($providers) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, + "get-url": $geturl, + list: $list, + update: $update, + providers: $providers, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/list.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/list.handler.ts new file mode 100644 index 0000000000..58713323d3 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/list.handler.ts @@ -0,0 +1,52 @@ +import operation from "../../_operations/ai-gateway/gateways/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway gateways list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + search: argv["search"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway gateways list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/list.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/list.ts index 2f6f976308..48edc4d882 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/gateways/list.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/list.ts @@ -1,80 +1,44 @@ -import operation from "../../_operations/ai-gateway/gateways/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway gateways list\n\nLists the AI Gateways in the account. Use `search` to filter by gateway ID." - ) - .option("page", { type: "number", description: "Page" }) - .option("per-page", { type: "number", description: "Per page" }) - .option("search", { type: "string", description: "Search by id" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + page: { kind: "parsed", brief: "Page", optional: true, parse: Number }, + "per-page": { + kind: "parsed", + brief: "Per page", + optional: true, + parse: Number, + }, + search: { + kind: "parsed", + brief: "Search by id", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List gateways", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway gateways list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - search: argv["search"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway gateways list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-gateway gateways list\n\nLists the AI Gateways in the account. Use `search` to filter by gateway ID.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/create.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/create.handler.ts new file mode 100644 index 0000000000..7bf1be85c3 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/create.handler.ts @@ -0,0 +1,146 @@ +import operation from "../../../_operations/ai-gateway/gateways/providers/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway gateways providers create", + classification: { + safeFlags: ["default-config", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["alias"] === undefined) { + argv["alias"] = await promptForRequiredField( + "alias", + "The alias field" + ); + } + if (argv["default-config"] === undefined) { + throw new Error( + "--default-config is required (or pass --body with this field set)." + ); + } + if (argv["provider-slug"] === undefined) { + argv["provider-slug"] = await promptForRequiredField( + "provider-slug", + "The provider_slug field" + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway gateways providers create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/provider_configs`, + pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + alias: resolveFileToken( + argv["alias"] as string | undefined, + "alias", + "text" + ), + default_config: argv["default-config"], + provider_slug: resolveFileToken( + argv["provider-slug"] as string | undefined, + "provider-slug", + "text" + ), + rate_limit: argv["rate-limit"], + rate_limit_period: argv["rate-limit-period"], + secret: resolveFileToken( + argv["secret"] as string | undefined, + "secret", + "text" + ), + secret_id: resolveFileToken( + argv["secret-id"] as string | undefined, + "secret-id", + "text" + ), + }), + sensitiveBodyPaths: [["secret"]], + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + gateway_id: argv["gateway-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + alias: resolveFileToken( + argv["alias"] as string | undefined, + "alias", + "text" + ), + default_config: argv["default-config"], + provider_slug: resolveFileToken( + argv["provider-slug"] as string | undefined, + "provider-slug", + "text" + ), + rate_limit: argv["rate-limit"], + rate_limit_period: argv["rate-limit-period"], + secret: resolveFileToken( + argv["secret"] as string | undefined, + "secret", + "text" + ), + secret_id: resolveFileToken( + argv["secret-id"] as string | undefined, + "secret-id", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + gateway_id: argv["gateway-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/create.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/create.ts index efb85e3ae4..ff1b984c46 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/create.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/create.ts @@ -1,204 +1,85 @@ -import operation from "../../../_operations/ai-gateway/gateways/providers/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway gateways providers create \n\nStores an upstream AI provider API key for an AI Gateway in the Secrets Store configured on the gateway, with an optional rate limit. Pass `secret` to store a new key, or omit it to use an existing Secrets Store secret." - ) - .positional("gateway-id", { - type: "string", - description: "Unique identifier of the AI Gateway within the account.", - demandOption: true, - }) - .option("alias", { type: "string", description: "The alias field" }) - .option("default-config", { - type: "boolean", - description: "The default_config field", - }) - .option("provider-slug", { - type: "string", - description: "The provider_slug field", - }) - .option("rate-limit", { - type: "number", - description: "The rate_limit field", - }) - .option("rate-limit-period", { - type: "number", - description: "The rate_limit_period field", - default: 60, - }) - .option("secret", { - type: "string", - description: +const parameters = { + flags: { + alias: { + kind: "parsed", + brief: "The alias field", + optional: true, + parse: String, + }, + "default-config": { + kind: "boolean", + brief: "The default_config field", + optional: true, + }, + "provider-slug": { + kind: "parsed", + brief: "The provider_slug field", + optional: true, + parse: String, + }, + "rate-limit": { + kind: "parsed", + brief: "The rate_limit field", + optional: true, + parse: Number, + }, + "rate-limit-period": { + kind: "parsed", + brief: "The rate_limit_period field", + default: "60", + parse: Number, + }, + secret: { + kind: "parsed", + brief: "Provider API key to store in the Secrets Store configured on the gateway.", - }) - .option("secret-id", { type: "string", description: "The secret_id field" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "secret-id": { + kind: "parsed", + brief: "The secret_id field", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "gateway-id", + brief: "Unique identifier of the AI Gateway within the account.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Store a provider key", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway gateways providers create", - classification: { - safeFlags: ["default-config", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["alias"] === undefined) { - argv["alias"] = await promptForRequiredField( - "alias", - "The alias field" - ); - } - if (argv["default-config"] === undefined) { - throw new Error( - "--default-config is required (or pass --body with this field set)." - ); - } - if (argv["provider-slug"] === undefined) { - argv["provider-slug"] = await promptForRequiredField( - "provider-slug", - "The provider_slug field" - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway gateways providers create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/provider_configs`, - pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - alias: resolveFileToken( - argv["alias"] as string | undefined, - "alias", - "text" - ), - default_config: argv["default-config"], - provider_slug: resolveFileToken( - argv["provider-slug"] as string | undefined, - "provider-slug", - "text" - ), - rate_limit: argv["rate-limit"], - rate_limit_period: argv["rate-limit-period"], - secret: resolveFileToken( - argv["secret"] as string | undefined, - "secret", - "text" - ), - secret_id: resolveFileToken( - argv["secret-id"] as string | undefined, - "secret-id", - "text" - ), - }), - sensitiveBodyPaths: [["secret"]], - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - gateway_id: argv["gateway-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - alias: resolveFileToken( - argv["alias"] as string | undefined, - "alias", - "text" - ), - default_config: argv["default-config"], - provider_slug: resolveFileToken( - argv["provider-slug"] as string | undefined, - "provider-slug", - "text" - ), - rate_limit: argv["rate-limit"], - rate_limit_period: argv["rate-limit-period"], - secret: resolveFileToken( - argv["secret"] as string | undefined, - "secret", - "text" - ), - secret_id: resolveFileToken( - argv["secret-id"] as string | undefined, - "secret-id", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - gateway_id: argv["gateway-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 ai-gateway gateways providers create \n\nStores an upstream AI provider API key for an AI Gateway in the Secrets Store configured on the gateway, with an optional rate limit. Pass `secret` to store a new key, or omit it to use an existing Secrets Store secret.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/delete.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/delete.handler.ts new file mode 100644 index 0000000000..8ad0c3178a --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/delete.handler.ts @@ -0,0 +1,64 @@ +import operation from "../../../_operations/ai-gateway/gateways/providers/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway gateways providers delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway gateways providers delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/provider_configs/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, + pathParams: { + "gateway-id": String(argv["gateway-id"] ?? ""), + id: String(argv["id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This deletes the stored provider key and its Secrets Store secret. Requests that rely on this key will stop authenticating with it.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/delete.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/delete.ts index 6cb871ec7a..2db61dffac 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/delete.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/delete.ts @@ -1,105 +1,42 @@ -import operation from "../../../_operations/ai-gateway/gateways/providers/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway gateways providers delete \n\nDeletes a provider key configuration from an AI Gateway and deletes its secret from the Secrets Store." - ) - .positional("id", { - type: "string", - description: "ID", - demandOption: true, - }) - .option("gateway-id", { - type: "string", - description: "Unique identifier of the AI Gateway within the account.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "gateway-id": { + kind: "parsed", + brief: "Unique identifier of the AI Gateway within the account.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "id", brief: "ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete a provider key", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway gateways providers delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway gateways providers delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/provider_configs/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, - pathParams: { - "gateway-id": String(argv["gateway-id"] ?? ""), - id: String(argv["id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This deletes the stored provider key and its Secrets Store secret. Requests that rely on this key will stop authenticating with it.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 ai-gateway gateways providers delete \n\nDeletes a provider key configuration from an AI Gateway and deletes its secret from the Secrets Store.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/get.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/get.handler.ts new file mode 100644 index 0000000000..1b1296378e --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/get.handler.ts @@ -0,0 +1,53 @@ +import operation from "../../../_operations/ai-gateway/gateways/providers/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway gateways providers get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway gateways providers get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/provider_configs/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, + pathParams: { + "gateway-id": String(argv["gateway-id"] ?? ""), + id: String(argv["id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/get.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/get.ts index 83102ad921..fabb0f7bf0 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/get.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/get.ts @@ -1,88 +1,36 @@ -import operation from "../../../_operations/ai-gateway/gateways/providers/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway gateways providers get \n\nRetrieves a provider key configuration for an AI Gateway. The response shows a masked preview of the key, never the key itself." - ) - .positional("id", { - type: "string", - description: "ID", - demandOption: true, - }) - .option("gateway-id", { - type: "string", - description: "Unique identifier of the AI Gateway within the account.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "gateway-id": { + kind: "parsed", + brief: "Unique identifier of the AI Gateway within the account.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "id", brief: "ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get a provider key", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway gateways providers get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway gateways providers get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/provider_configs/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, - pathParams: { - "gateway-id": String(argv["gateway-id"] ?? ""), - id: String(argv["id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-gateway gateways providers get \n\nRetrieves a provider key configuration for an AI Gateway. The response shows a masked preview of the key, never the key itself.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/index.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/index.ts index 2c936470db..e0826d82dc 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/index.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/index.ts @@ -4,29 +4,24 @@ import $get from "./get.js"; import $list from "./list.js"; import $test from "./test.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * providers command group * @generated from apis/overlays/ai-gateway.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "providers", describe: "Store and rotate upstream AI provider keys for a gateway", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .command($list) - .command($test) - .command($update) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, + list: $list, + test: $test, + update: $update, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/list.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/list.handler.ts new file mode 100644 index 0000000000..81a77aca47 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/list.handler.ts @@ -0,0 +1,55 @@ +import operation from "../../../_operations/ai-gateway/gateways/providers/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway gateways providers list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway gateways providers list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/provider_configs`, + pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + gateway_id: argv["gateway-id"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/list.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/list.ts index 3a3dce14fe..2185c4e0d7 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/list.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/list.ts @@ -1,87 +1,43 @@ -import operation from "../../../_operations/ai-gateway/gateways/providers/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway gateways providers list\n\nLists the provider keys stored for an AI Gateway. Responses show a masked preview of each key, never the key itself." - ) - .option("gateway-id", { - type: "string", - description: "Unique identifier of the AI Gateway within the account.", - demandOption: true, - }) - .option("page", { type: "number", description: "Page" }) - .option("per-page", { type: "number", description: "Per page" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "gateway-id": { + kind: "parsed", + brief: "Unique identifier of the AI Gateway within the account.", + parse: String, + }, + page: { kind: "parsed", brief: "Page", optional: true, parse: Number }, + "per-page": { + kind: "parsed", + brief: "Per page", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List provider keys", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway gateways providers list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway gateways providers list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/provider_configs`, - pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - gateway_id: argv["gateway-id"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-gateway gateways providers list\n\nLists the provider keys stored for an AI Gateway. Responses show a masked preview of each key, never the key itself.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/test.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/test.handler.ts new file mode 100644 index 0000000000..70d04bf5ec --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/test.handler.ts @@ -0,0 +1,72 @@ +import operation from "../../../_operations/ai-gateway/gateways/providers/test.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./test.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway gateways providers test", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway gateways providers test", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/provider_configs/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}/test`, + pathParams: { + "gateway-id": String(argv["gateway-id"] ?? ""), + id: String(argv["id"] ?? ""), + }, + bodyKind: "json", + body: argv.body !== undefined ? parseBody(argv.body) : undefined, + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + const result = await withProgress(`Creating`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/ai-gateway/gateways/${encodeURIComponent(String(argv["gateway-id"]))}/provider_configs/${encodeURIComponent(String(argv["id"]))}/test` + ) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/test.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/test.ts index 8988081a10..36d4feca6c 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/test.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/test.ts @@ -1,111 +1,42 @@ -import operation from "../../../_operations/ai-gateway/gateways/providers/test.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * test command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway gateways providers test \n\nChecks whether stored credentials can list models through the provider implementation in AI Gateway. Requires AI Gateway content update permission. Does not run inference, check credits or inference permissions, or return provider response bodies. HTTP 401 from the model-list request is classified as invalid, as is AWS Bedrock HTTP 403 with an UnrecognizedClientException error type. Other failures are inconclusive, including other HTTP 400 or 403 responses; a 403 alone does not distinguish rejected credentials from insufficient permissions. Unsupported providers or credential formats also return an inconclusive result." - ) - .positional("id", { - type: "string", - description: "ID", - demandOption: true, - }) - .option("gateway-id", { - type: "string", - description: "Unique identifier of the AI Gateway within the account.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "gateway-id": { + kind: "parsed", + brief: "Unique identifier of the AI Gateway within the account.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [{ placeholder: "id", brief: "ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "test ", describe: "Check stored provider credentials", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway gateways providers test", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway gateways providers test", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/provider_configs/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}/test`, - pathParams: { - "gateway-id": String(argv["gateway-id"] ?? ""), - id: String(argv["id"] ?? ""), - }, - bodyKind: "json", - body: argv.body !== undefined ? parseBody(argv.body) : undefined, - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - const result = await withProgress(`Creating`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/ai-gateway/gateways/${encodeURIComponent(String(argv["gateway-id"]))}/provider_configs/${encodeURIComponent(String(argv["id"]))}/test` - ) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 ai-gateway gateways providers test \n\nChecks whether stored credentials can list models through the provider implementation in AI Gateway. Requires AI Gateway content update permission. Does not run inference, check credits or inference permissions, or return provider response bodies. HTTP 401 from the model-list request is classified as invalid, as is AWS Bedrock HTTP 403 with an UnrecognizedClientException error type. Other failures are inconclusive, including other HTTP 400 or 403 responses; a 403 alone does not distinguish rejected credentials from insufficient permissions. Unsupported providers or credential formats also return an inconclusive result.", + ...parameters, + loader: () => import("./test.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/update.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/update.handler.ts new file mode 100644 index 0000000000..9205e1b919 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/update.handler.ts @@ -0,0 +1,105 @@ +import operation from "../../../_operations/ai-gateway/gateways/providers/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway gateways providers update", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["secret"] === undefined) { + argv["secret"] = await promptForRequiredField( + "secret", + "Provider API key to store in the Secrets Store configured on the gateway.", + { kind: "secret" } + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway gateways providers update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/provider_configs/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, + pathParams: { + "gateway-id": String(argv["gateway-id"] ?? ""), + id: String(argv["id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + secret: resolveFileToken( + argv["secret"] as string | undefined, + "secret", + "text" + ), + }), + sensitiveBodyPaths: [["secret"]], + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + secret: resolveFileToken( + argv["secret"] as string | undefined, + "secret", + "text" + ), + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/update.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/update.ts index b8d4db0a38..eafaf91d2e 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/update.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/providers/update.ts @@ -1,149 +1,49 @@ -import operation from "../../../_operations/ai-gateway/gateways/providers/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway gateways providers update \n\nReplaces the stored API key of a provider key configuration. Only the key can change." - ) - .positional("id", { - type: "string", - description: "ID", - demandOption: true, - }) - .option("gateway-id", { - type: "string", - description: "Unique identifier of the AI Gateway within the account.", - demandOption: true, - }) - .option("secret", { - type: "string", - description: +const parameters = { + flags: { + "gateway-id": { + kind: "parsed", + brief: "Unique identifier of the AI Gateway within the account.", + parse: String, + }, + secret: { + kind: "parsed", + brief: "Provider API key to store in the Secrets Store configured on the gateway.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [{ placeholder: "id", brief: "ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update ", describe: "Rotate a provider key", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway gateways providers update", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["secret"] === undefined) { - argv["secret"] = await promptForRequiredField( - "secret", - "Provider API key to store in the Secrets Store configured on the gateway.", - { kind: "secret" } - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway gateways providers update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/provider_configs/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, - pathParams: { - "gateway-id": String(argv["gateway-id"] ?? ""), - id: String(argv["id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - secret: resolveFileToken( - argv["secret"] as string | undefined, - "secret", - "text" - ), - }), - sensitiveBodyPaths: [["secret"]], - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - secret: resolveFileToken( - argv["secret"] as string | undefined, - "secret", - "text" - ), - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 ai-gateway gateways providers update \n\nReplaces the stored API key of a provider key configuration. Only the key can change.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/update.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/update.handler.ts new file mode 100644 index 0000000000..1e25b7dda4 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/update.handler.ts @@ -0,0 +1,547 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { + compactBody, + parseBody, + parseObjectArray, + setNestedValue, +} from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway gateways update", + classification: { + safeFlags: [ + "authentication", + "byok-only", + "cache-invalidate-on-update", + "collect-logs", + "guardrails-prompt-p1", + "guardrails-prompt-s1", + "guardrails-prompt-s10", + "guardrails-prompt-s11", + "guardrails-prompt-s12", + "guardrails-prompt-s13", + "guardrails-prompt-s14", + "guardrails-prompt-s2", + "guardrails-prompt-s3", + "guardrails-prompt-s4", + "guardrails-prompt-s5", + "guardrails-prompt-s6", + "guardrails-prompt-s7", + "guardrails-prompt-s8", + "guardrails-prompt-s9", + "guardrails-response-p1", + "guardrails-response-s1", + "guardrails-response-s10", + "guardrails-response-s11", + "guardrails-response-s12", + "guardrails-response-s13", + "guardrails-response-s14", + "guardrails-response-s2", + "guardrails-response-s3", + "guardrails-response-s4", + "guardrails-response-s5", + "guardrails-response-s6", + "guardrails-response-s7", + "guardrails-response-s8", + "guardrails-response-s9", + "log-classification", + "log-management-strategy", + "logpush", + "multiprovider-enabled", + "rate-limiting-technique", + "retry-backoff", + "spend-limits-enabled", + "workers-ai-billing-mode", + "zdr", + "dry-run", + ], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["cache-invalidate-on-update"] === undefined) { + throw new Error( + "--cache-invalidate-on-update is required (or pass --body with this field set)." + ); + } + if (argv["cache-ttl"] === undefined) { + throw new Error( + "--cache-ttl is required (or pass --body with this field set)." + ); + } + if (argv["collect-logs"] === undefined) { + throw new Error( + "--collect-logs is required (or pass --body with this field set)." + ); + } + if (argv["rate-limiting-interval"] === undefined) { + throw new Error( + "--rate-limiting-interval is required (or pass --body with this field set)." + ); + } + if (argv["rate-limiting-limit"] === undefined) { + throw new Error( + "--rate-limiting-limit is required (or pass --body with this field set)." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway gateways update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}`, + pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + authentication: argv["authentication"], + byok_only: argv["byok-only"], + cache_invalidate_on_update: + argv["cache-invalidate-on-update"], + cache_ttl: argv["cache-ttl"], + collect_logs: argv["collect-logs"], + guardrails: { + prompt: { + P1: argv["guardrails-prompt-p1"], + S1: argv["guardrails-prompt-s1"], + S10: argv["guardrails-prompt-s10"], + S11: argv["guardrails-prompt-s11"], + S12: argv["guardrails-prompt-s12"], + S13: argv["guardrails-prompt-s13"], + S14: argv["guardrails-prompt-s14"], + S2: argv["guardrails-prompt-s2"], + S3: argv["guardrails-prompt-s3"], + S4: argv["guardrails-prompt-s4"], + S5: argv["guardrails-prompt-s5"], + S6: argv["guardrails-prompt-s6"], + S7: argv["guardrails-prompt-s7"], + S8: argv["guardrails-prompt-s8"], + S9: argv["guardrails-prompt-s9"], + }, + response: { + P1: argv["guardrails-response-p1"], + S1: argv["guardrails-response-s1"], + S10: argv["guardrails-response-s10"], + S11: argv["guardrails-response-s11"], + S12: argv["guardrails-response-s12"], + S13: argv["guardrails-response-s13"], + S14: argv["guardrails-response-s14"], + S2: argv["guardrails-response-s2"], + S3: argv["guardrails-response-s3"], + S4: argv["guardrails-response-s4"], + S5: argv["guardrails-response-s5"], + S6: argv["guardrails-response-s6"], + S7: argv["guardrails-response-s7"], + S8: argv["guardrails-response-s8"], + S9: argv["guardrails-response-s9"], + }, + }, + log_classification: argv["log-classification"], + log_management: argv["log-management"], + log_management_strategy: argv["log-management-strategy"], + logpush: argv["logpush"], + logpush_public_key: resolveFileToken( + argv["logpush-public-key"] as string | undefined, + "logpush-public-key", + "text" + ), + multiprovider_enabled: argv["multiprovider-enabled"], + otel: parseObjectArray(argv["otel"], "otel", true), + rate_limiting_interval: argv["rate-limiting-interval"], + rate_limiting_limit: argv["rate-limiting-limit"], + rate_limiting_technique: argv["rate-limiting-technique"], + retry_backoff: argv["retry-backoff"], + retry_delay: argv["retry-delay"], + retry_max_attempts: argv["retry-max-attempts"], + spend_limits: { + enabled: argv["spend-limits-enabled"], + rules: parseObjectArray( + argv["spend-limits-rules"], + "spend-limits-rules" + ), + }, + store_id: resolveFileToken( + argv["store-id"] as string | undefined, + "store-id", + "text" + ), + stripe: { + authorization: resolveFileToken( + argv["stripe-authorization"] as string | undefined, + "stripe-authorization", + "text" + ), + usage_events: parseObjectArray( + argv["stripe-usage-events"], + "stripe-usage-events" + ), + }, + workers_ai_billing_mode: argv["workers-ai-billing-mode"], + zdr: argv["zdr"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + requestApi( + client, + "PUT", + `/accounts/${accountId}/ai-gateway/gateways/${encodeURIComponent(String(argv["gateway-id"]))}`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData: Record = {}; + if (argv["authentication"] !== undefined) + setNestedValue(bodyData, ["authentication"], argv["authentication"]); + if (argv["byok-only"] !== undefined) + setNestedValue(bodyData, ["byok_only"], argv["byok-only"]); + if (argv["cache-invalidate-on-update"] !== undefined) + setNestedValue( + bodyData, + ["cache_invalidate_on_update"], + argv["cache-invalidate-on-update"] + ); + if (argv["cache-ttl"] !== undefined) + setNestedValue(bodyData, ["cache_ttl"], argv["cache-ttl"]); + if (argv["collect-logs"] !== undefined) + setNestedValue(bodyData, ["collect_logs"], argv["collect-logs"]); + if (argv["guardrails-prompt-p1"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "prompt", "P1"], + argv["guardrails-prompt-p1"] + ); + if (argv["guardrails-prompt-s1"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "prompt", "S1"], + argv["guardrails-prompt-s1"] + ); + if (argv["guardrails-prompt-s10"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "prompt", "S10"], + argv["guardrails-prompt-s10"] + ); + if (argv["guardrails-prompt-s11"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "prompt", "S11"], + argv["guardrails-prompt-s11"] + ); + if (argv["guardrails-prompt-s12"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "prompt", "S12"], + argv["guardrails-prompt-s12"] + ); + if (argv["guardrails-prompt-s13"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "prompt", "S13"], + argv["guardrails-prompt-s13"] + ); + if (argv["guardrails-prompt-s14"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "prompt", "S14"], + argv["guardrails-prompt-s14"] + ); + if (argv["guardrails-prompt-s2"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "prompt", "S2"], + argv["guardrails-prompt-s2"] + ); + if (argv["guardrails-prompt-s3"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "prompt", "S3"], + argv["guardrails-prompt-s3"] + ); + if (argv["guardrails-prompt-s4"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "prompt", "S4"], + argv["guardrails-prompt-s4"] + ); + if (argv["guardrails-prompt-s5"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "prompt", "S5"], + argv["guardrails-prompt-s5"] + ); + if (argv["guardrails-prompt-s6"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "prompt", "S6"], + argv["guardrails-prompt-s6"] + ); + if (argv["guardrails-prompt-s7"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "prompt", "S7"], + argv["guardrails-prompt-s7"] + ); + if (argv["guardrails-prompt-s8"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "prompt", "S8"], + argv["guardrails-prompt-s8"] + ); + if (argv["guardrails-prompt-s9"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "prompt", "S9"], + argv["guardrails-prompt-s9"] + ); + if (argv["guardrails-response-p1"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "response", "P1"], + argv["guardrails-response-p1"] + ); + if (argv["guardrails-response-s1"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "response", "S1"], + argv["guardrails-response-s1"] + ); + if (argv["guardrails-response-s10"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "response", "S10"], + argv["guardrails-response-s10"] + ); + if (argv["guardrails-response-s11"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "response", "S11"], + argv["guardrails-response-s11"] + ); + if (argv["guardrails-response-s12"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "response", "S12"], + argv["guardrails-response-s12"] + ); + if (argv["guardrails-response-s13"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "response", "S13"], + argv["guardrails-response-s13"] + ); + if (argv["guardrails-response-s14"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "response", "S14"], + argv["guardrails-response-s14"] + ); + if (argv["guardrails-response-s2"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "response", "S2"], + argv["guardrails-response-s2"] + ); + if (argv["guardrails-response-s3"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "response", "S3"], + argv["guardrails-response-s3"] + ); + if (argv["guardrails-response-s4"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "response", "S4"], + argv["guardrails-response-s4"] + ); + if (argv["guardrails-response-s5"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "response", "S5"], + argv["guardrails-response-s5"] + ); + if (argv["guardrails-response-s6"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "response", "S6"], + argv["guardrails-response-s6"] + ); + if (argv["guardrails-response-s7"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "response", "S7"], + argv["guardrails-response-s7"] + ); + if (argv["guardrails-response-s8"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "response", "S8"], + argv["guardrails-response-s8"] + ); + if (argv["guardrails-response-s9"] !== undefined) + setNestedValue( + bodyData, + ["guardrails", "response", "S9"], + argv["guardrails-response-s9"] + ); + if (argv["log-classification"] !== undefined) + setNestedValue( + bodyData, + ["log_classification"], + argv["log-classification"] + ); + if (argv["log-management"] !== undefined) + setNestedValue(bodyData, ["log_management"], argv["log-management"]); + if (argv["log-management-strategy"] !== undefined) + setNestedValue( + bodyData, + ["log_management_strategy"], + argv["log-management-strategy"] + ); + if (argv["logpush"] !== undefined) + setNestedValue(bodyData, ["logpush"], argv["logpush"]); + if (argv["logpush-public-key"] !== undefined) + setNestedValue( + bodyData, + ["logpush_public_key"], + resolveFileToken( + argv["logpush-public-key"] as string | undefined, + "logpush-public-key", + "text" + ) + ); + if (argv["multiprovider-enabled"] !== undefined) + setNestedValue( + bodyData, + ["multiprovider_enabled"], + argv["multiprovider-enabled"] + ); + if (argv["otel"] !== undefined) + setNestedValue( + bodyData, + ["otel"], + parseObjectArray(argv["otel"], "otel", true) + ); + if (argv["rate-limiting-interval"] !== undefined) + setNestedValue( + bodyData, + ["rate_limiting_interval"], + argv["rate-limiting-interval"] + ); + if (argv["rate-limiting-limit"] !== undefined) + setNestedValue( + bodyData, + ["rate_limiting_limit"], + argv["rate-limiting-limit"] + ); + if (argv["rate-limiting-technique"] !== undefined) + setNestedValue( + bodyData, + ["rate_limiting_technique"], + argv["rate-limiting-technique"] + ); + if (argv["retry-backoff"] !== undefined) + setNestedValue(bodyData, ["retry_backoff"], argv["retry-backoff"]); + if (argv["retry-delay"] !== undefined) + setNestedValue(bodyData, ["retry_delay"], argv["retry-delay"]); + if (argv["retry-max-attempts"] !== undefined) + setNestedValue( + bodyData, + ["retry_max_attempts"], + argv["retry-max-attempts"] + ); + if (argv["spend-limits-enabled"] !== undefined) + setNestedValue( + bodyData, + ["spend_limits", "enabled"], + argv["spend-limits-enabled"] + ); + if (argv["spend-limits-rules"] !== undefined) + setNestedValue( + bodyData, + ["spend_limits", "rules"], + parseObjectArray(argv["spend-limits-rules"], "spend-limits-rules") + ); + if (argv["store-id"] !== undefined) + setNestedValue( + bodyData, + ["store_id"], + resolveFileToken( + argv["store-id"] as string | undefined, + "store-id", + "text" + ) + ); + if (argv["stripe-authorization"] !== undefined) + setNestedValue( + bodyData, + ["stripe", "authorization"], + resolveFileToken( + argv["stripe-authorization"] as string | undefined, + "stripe-authorization", + "text" + ) + ); + if (argv["stripe-usage-events"] !== undefined) + setNestedValue( + bodyData, + ["stripe", "usage_events"], + parseObjectArray(argv["stripe-usage-events"], "stripe-usage-events") + ); + if (argv["workers-ai-billing-mode"] !== undefined) + setNestedValue( + bodyData, + ["workers_ai_billing_mode"], + argv["workers-ai-billing-mode"] + ); + if (argv["zdr"] !== undefined) + setNestedValue(bodyData, ["zdr"], argv["zdr"]); + const result = await withProgress(`Updating`, async () => + requestApi( + client, + "PUT", + `/accounts/${accountId}/ai-gateway/gateways/${encodeURIComponent(String(argv["gateway-id"]))}`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/gateways/update.ts b/packages/cli/src/commands/_generated/ai-gateway/gateways/update.ts index adbeddb462..31d7ce792b 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/gateways/update.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/gateways/update.ts @@ -1,404 +1,460 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { - compactBody, - parseBody, - parseObjectArray, - setNestedValue, -} from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway gateways update \n\nUpdates the configuration of an AI Gateway, such as its caching, rate limiting, spend limits, logging, and authentication settings." - ) - .positional("gateway-id", { - type: "string", - description: "Unique identifier of the AI Gateway within the account.", - demandOption: true, - }) - .option("authentication", { - type: "boolean", - description: +const parameters = { + flags: { + authentication: { + kind: "boolean", + brief: "Require authentication for gateway access. New gateways must have authentication enabled. Once enabled, authentication cannot be disabled.", - }) - .option("byok-only", { - type: "boolean", - description: + optional: true, + }, + "byok-only": { + kind: "boolean", + brief: "Requires customer-provided provider credentials and prevents fallback to Unified Billing.", - }) - .option("cache-invalidate-on-update", { - type: "boolean", - description: "The cache_invalidate_on_update field", - }) - .option("cache-ttl", { type: "number", description: "The cache_ttl field" }) - .option("collect-logs", { - type: "boolean", - description: "The collect_logs field", - }) - .option("guardrails-prompt-p1", { - type: "string", - description: "The guardrails.prompt.P1 field", + optional: true, + }, + "cache-invalidate-on-update": { + kind: "boolean", + brief: "The cache_invalidate_on_update field", + optional: true, + }, + "cache-ttl": { + kind: "parsed", + brief: "The cache_ttl field", + optional: true, + parse: Number, + }, + "collect-logs": { + kind: "boolean", + brief: "The collect_logs field", + optional: true, + }, + "guardrails-prompt-p1": { + kind: "parsed", + brief: "The guardrails.prompt.P1 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-p1", (value) => - resolveFileToken(value, "guardrails-prompt-p1", "text") - ) - .option("guardrails-prompt-s1", { - type: "string", - description: "The guardrails.prompt.S1 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-p1", "text"), + }, + "guardrails-prompt-s1": { + kind: "parsed", + brief: "The guardrails.prompt.S1 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s1", (value) => - resolveFileToken(value, "guardrails-prompt-s1", "text") - ) - .option("guardrails-prompt-s10", { - type: "string", - description: "The guardrails.prompt.S10 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s1", "text"), + }, + "guardrails-prompt-s10": { + kind: "parsed", + brief: "The guardrails.prompt.S10 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s10", (value) => - resolveFileToken(value, "guardrails-prompt-s10", "text") - ) - .option("guardrails-prompt-s11", { - type: "string", - description: "The guardrails.prompt.S11 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s10", "text"), + }, + "guardrails-prompt-s11": { + kind: "parsed", + brief: "The guardrails.prompt.S11 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s11", (value) => - resolveFileToken(value, "guardrails-prompt-s11", "text") - ) - .option("guardrails-prompt-s12", { - type: "string", - description: "The guardrails.prompt.S12 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s11", "text"), + }, + "guardrails-prompt-s12": { + kind: "parsed", + brief: "The guardrails.prompt.S12 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s12", (value) => - resolveFileToken(value, "guardrails-prompt-s12", "text") - ) - .option("guardrails-prompt-s13", { - type: "string", - description: "The guardrails.prompt.S13 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s12", "text"), + }, + "guardrails-prompt-s13": { + kind: "parsed", + brief: "The guardrails.prompt.S13 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s13", (value) => - resolveFileToken(value, "guardrails-prompt-s13", "text") - ) - .option("guardrails-prompt-s14", { - type: "string", - description: "The guardrails.prompt.S14 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s13", "text"), + }, + "guardrails-prompt-s14": { + kind: "parsed", + brief: "The guardrails.prompt.S14 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s14", (value) => - resolveFileToken(value, "guardrails-prompt-s14", "text") - ) - .option("guardrails-prompt-s2", { - type: "string", - description: "The guardrails.prompt.S2 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s14", "text"), + }, + "guardrails-prompt-s2": { + kind: "parsed", + brief: "The guardrails.prompt.S2 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s2", (value) => - resolveFileToken(value, "guardrails-prompt-s2", "text") - ) - .option("guardrails-prompt-s3", { - type: "string", - description: "The guardrails.prompt.S3 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s2", "text"), + }, + "guardrails-prompt-s3": { + kind: "parsed", + brief: "The guardrails.prompt.S3 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s3", (value) => - resolveFileToken(value, "guardrails-prompt-s3", "text") - ) - .option("guardrails-prompt-s4", { - type: "string", - description: "The guardrails.prompt.S4 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s3", "text"), + }, + "guardrails-prompt-s4": { + kind: "parsed", + brief: "The guardrails.prompt.S4 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s4", (value) => - resolveFileToken(value, "guardrails-prompt-s4", "text") - ) - .option("guardrails-prompt-s5", { - type: "string", - description: "The guardrails.prompt.S5 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s4", "text"), + }, + "guardrails-prompt-s5": { + kind: "parsed", + brief: "The guardrails.prompt.S5 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s5", (value) => - resolveFileToken(value, "guardrails-prompt-s5", "text") - ) - .option("guardrails-prompt-s6", { - type: "string", - description: "The guardrails.prompt.S6 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s5", "text"), + }, + "guardrails-prompt-s6": { + kind: "parsed", + brief: "The guardrails.prompt.S6 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s6", (value) => - resolveFileToken(value, "guardrails-prompt-s6", "text") - ) - .option("guardrails-prompt-s7", { - type: "string", - description: "The guardrails.prompt.S7 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s6", "text"), + }, + "guardrails-prompt-s7": { + kind: "parsed", + brief: "The guardrails.prompt.S7 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s7", (value) => - resolveFileToken(value, "guardrails-prompt-s7", "text") - ) - .option("guardrails-prompt-s8", { - type: "string", - description: "The guardrails.prompt.S8 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s7", "text"), + }, + "guardrails-prompt-s8": { + kind: "parsed", + brief: "The guardrails.prompt.S8 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s8", (value) => - resolveFileToken(value, "guardrails-prompt-s8", "text") - ) - .option("guardrails-prompt-s9", { - type: "string", - description: "The guardrails.prompt.S9 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s8", "text"), + }, + "guardrails-prompt-s9": { + kind: "parsed", + brief: "The guardrails.prompt.S9 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-prompt-s9", (value) => - resolveFileToken(value, "guardrails-prompt-s9", "text") - ) - .option("guardrails-response-p1", { - type: "string", - description: "The guardrails.response.P1 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-prompt-s9", "text"), + }, + "guardrails-response-p1": { + kind: "parsed", + brief: "The guardrails.response.P1 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-p1", (value) => - resolveFileToken(value, "guardrails-response-p1", "text") - ) - .option("guardrails-response-s1", { - type: "string", - description: "The guardrails.response.S1 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-p1", "text"), + }, + "guardrails-response-s1": { + kind: "parsed", + brief: "The guardrails.response.S1 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s1", (value) => - resolveFileToken(value, "guardrails-response-s1", "text") - ) - .option("guardrails-response-s10", { - type: "string", - description: "The guardrails.response.S10 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s1", "text"), + }, + "guardrails-response-s10": { + kind: "parsed", + brief: "The guardrails.response.S10 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s10", (value) => - resolveFileToken(value, "guardrails-response-s10", "text") - ) - .option("guardrails-response-s11", { - type: "string", - description: "The guardrails.response.S11 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s10", "text"), + }, + "guardrails-response-s11": { + kind: "parsed", + brief: "The guardrails.response.S11 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s11", (value) => - resolveFileToken(value, "guardrails-response-s11", "text") - ) - .option("guardrails-response-s12", { - type: "string", - description: "The guardrails.response.S12 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s11", "text"), + }, + "guardrails-response-s12": { + kind: "parsed", + brief: "The guardrails.response.S12 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s12", (value) => - resolveFileToken(value, "guardrails-response-s12", "text") - ) - .option("guardrails-response-s13", { - type: "string", - description: "The guardrails.response.S13 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s12", "text"), + }, + "guardrails-response-s13": { + kind: "parsed", + brief: "The guardrails.response.S13 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s13", (value) => - resolveFileToken(value, "guardrails-response-s13", "text") - ) - .option("guardrails-response-s14", { - type: "string", - description: "The guardrails.response.S14 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s13", "text"), + }, + "guardrails-response-s14": { + kind: "parsed", + brief: "The guardrails.response.S14 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s14", (value) => - resolveFileToken(value, "guardrails-response-s14", "text") - ) - .option("guardrails-response-s2", { - type: "string", - description: "The guardrails.response.S2 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s14", "text"), + }, + "guardrails-response-s2": { + kind: "parsed", + brief: "The guardrails.response.S2 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s2", (value) => - resolveFileToken(value, "guardrails-response-s2", "text") - ) - .option("guardrails-response-s3", { - type: "string", - description: "The guardrails.response.S3 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s2", "text"), + }, + "guardrails-response-s3": { + kind: "parsed", + brief: "The guardrails.response.S3 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s3", (value) => - resolveFileToken(value, "guardrails-response-s3", "text") - ) - .option("guardrails-response-s4", { - type: "string", - description: "The guardrails.response.S4 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s3", "text"), + }, + "guardrails-response-s4": { + kind: "parsed", + brief: "The guardrails.response.S4 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s4", (value) => - resolveFileToken(value, "guardrails-response-s4", "text") - ) - .option("guardrails-response-s5", { - type: "string", - description: "The guardrails.response.S5 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s4", "text"), + }, + "guardrails-response-s5": { + kind: "parsed", + brief: "The guardrails.response.S5 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s5", (value) => - resolveFileToken(value, "guardrails-response-s5", "text") - ) - .option("guardrails-response-s6", { - type: "string", - description: "The guardrails.response.S6 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s5", "text"), + }, + "guardrails-response-s6": { + kind: "parsed", + brief: "The guardrails.response.S6 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s6", (value) => - resolveFileToken(value, "guardrails-response-s6", "text") - ) - .option("guardrails-response-s7", { - type: "string", - description: "The guardrails.response.S7 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s6", "text"), + }, + "guardrails-response-s7": { + kind: "parsed", + brief: "The guardrails.response.S7 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s7", (value) => - resolveFileToken(value, "guardrails-response-s7", "text") - ) - .option("guardrails-response-s8", { - type: "string", - description: "The guardrails.response.S8 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s7", "text"), + }, + "guardrails-response-s8": { + kind: "parsed", + brief: "The guardrails.response.S8 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s8", (value) => - resolveFileToken(value, "guardrails-response-s8", "text") - ) - .option("guardrails-response-s9", { - type: "string", - description: "The guardrails.response.S9 field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s8", "text"), + }, + "guardrails-response-s9": { + kind: "parsed", + brief: "The guardrails.response.S9 field", + optional: true, choices: ["FLAG", "BLOCK"], - }) - .coerce("guardrails-response-s9", (value) => - resolveFileToken(value, "guardrails-response-s9", "text") - ) - .option("log-classification", { - type: "boolean", - description: "The log_classification field", - }) - .option("log-management", { - type: "number", - description: "The log_management field", - }) - .option("log-management-strategy", { - type: "string", - description: "The log_management_strategy field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-response-s9", "text"), + }, + "log-classification": { + kind: "boolean", + brief: "The log_classification field", + optional: true, + }, + "log-management": { + kind: "parsed", + brief: "The log_management field", + optional: true, + parse: Number, + }, + "log-management-strategy": { + kind: "parsed", + brief: "The log_management_strategy field", + optional: true, choices: ["STOP_INSERTING", "DELETE_OLDEST"], - }) - .coerce("log-management-strategy", (value) => - resolveFileToken(value, "log-management-strategy", "text") - ) - .option("logpush", { type: "boolean", description: "The logpush field" }) - .option("logpush-public-key", { - type: "string", - description: "The logpush_public_key field", - }) - .option("multiprovider-enabled", { - type: "boolean", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "log-management-strategy", "text"), + }, + logpush: { kind: "boolean", brief: "The logpush field", optional: true }, + "logpush-public-key": { + kind: "parsed", + brief: "The logpush_public_key field", + optional: true, + parse: String, + }, + "multiprovider-enabled": { + kind: "boolean", + brief: "Lets requests to a model use every provider that serves it. When off, a model uses only the providers it launched with, so a provider added later receives none of its traffic. A request that names providers (the cf-aig-allowed-providers header or routing.allowedProviders) can still use any of them. Model aliases (custom/) are not restricted.", - }) - .option("otel", { - type: "string", - description: + optional: true, + }, + otel: { + kind: "parsed", + brief: 'The otel field. Provide as a JSON array of objects, null, or @path/to/file.json. Shape: [{"headers": {...}, "url": string, "authorization"?: string, "content_type"?: "json" | "protobuf"}]. ? marks optional keys.', - }) - .option("rate-limiting-interval", { - type: "number", - description: "The rate_limiting_interval field", - }) - .option("rate-limiting-limit", { - type: "number", - description: "The rate_limiting_limit field", - }) - .option("rate-limiting-technique", { - type: "string", - description: "The rate_limiting_technique field", + optional: true, + parse: String, + }, + "rate-limiting-interval": { + kind: "parsed", + brief: "The rate_limiting_interval field", + optional: true, + parse: Number, + }, + "rate-limiting-limit": { + kind: "parsed", + brief: "The rate_limiting_limit field", + optional: true, + parse: Number, + }, + "rate-limiting-technique": { + kind: "parsed", + brief: "The rate_limiting_technique field", + optional: true, choices: ["fixed", "sliding"], - }) - .coerce("rate-limiting-technique", (value) => - resolveFileToken(value, "rate-limiting-technique", "text") - ) - .option("retry-backoff", { - type: "string", - description: "Backoff strategy for retry delays", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "rate-limiting-technique", "text"), + }, + "retry-backoff": { + kind: "parsed", + brief: "Backoff strategy for retry delays", + optional: true, choices: ["constant", "linear", "exponential"], - }) - .coerce("retry-backoff", (value) => - resolveFileToken(value, "retry-backoff", "text") - ) - .option("retry-delay", { - type: "number", - description: "Delay between retry attempts in milliseconds (0-60000)", - }) - .option("retry-max-attempts", { - type: "number", - description: "Maximum number of retry attempts for failed requests (1-5)", - }) - .option("spend-limits-enabled", { - type: "boolean", - description: "The spend_limits.enabled field", - }) - .option("spend-limits-rules", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "retry-backoff", "text"), + }, + "retry-delay": { + kind: "parsed", + brief: "Delay between retry attempts in milliseconds (0-60000)", + optional: true, + parse: Number, + }, + "retry-max-attempts": { + kind: "parsed", + brief: "Maximum number of retry attempts for failed requests (1-5)", + optional: true, + parse: Number, + }, + "spend-limits-enabled": { + kind: "boolean", + brief: "The spend_limits.enabled field", + optional: true, + }, + "spend-limits-rules": { + kind: "parsed", + brief: 'The spend_limits.rules field. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"limit": number, "limitType": "cost", "window": number, "enabled"?: boolean, "id"?: string, ...more}]. ? marks optional keys.', - }) - .option("store-id", { - type: "string", - description: + optional: true, + parse: String, + }, + "store-id": { + kind: "parsed", + brief: "Secrets Store used by this gateway. Omit on update to keep the current store. Cannot be cleared while stored keys or secret references depend on it.", - }) - .option("stripe-authorization", { - type: "string", - description: "The stripe.authorization field", - }) - .option("stripe-usage-events", { - type: "string", - description: + optional: true, + parse: String, + }, + "stripe-authorization": { + kind: "parsed", + brief: "The stripe.authorization field", + optional: true, + parse: String, + }, + "stripe-usage-events": { + kind: "parsed", + brief: 'The stripe.usage_events field. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"payload": string}].', - }) - .option("workers-ai-billing-mode", { - type: "string", - description: + optional: true, + parse: String, + }, + "workers-ai-billing-mode": { + kind: "parsed", + brief: "Controls how Workers AI inference calls routed through this gateway are billed. 'postpaid' bills the account directly through Workers AI; 'unified' deducts credits via AI Gateway using neuron-based pricing and delegates billing to AI Gateway.", + optional: true, choices: ["postpaid", "unified"], - }) - .coerce("workers-ai-billing-mode", (value) => - resolveFileToken(value, "workers-ai-billing-mode", "text") - ) - .option("zdr", { type: "boolean", description: "The zdr field" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "workers-ai-billing-mode", "text"), + }, + zdr: { kind: "boolean", brief: "The zdr field", optional: true }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }) - .check((argv) => { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "gateway-id", + brief: "Unique identifier of the AI Gateway within the account.", + parse: String, + }, + ], + rules(rules) { + rules.check((argv) => { const groupSet = ["stripe-authorization", "stripe-usage-events"].some( (k) => argv[k] !== undefined ); @@ -414,539 +470,16 @@ function builder(yargs: Argv) { } return true; }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update ", describe: "Update a gateway", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway gateways update", - classification: { - safeFlags: [ - "authentication", - "byok-only", - "cache-invalidate-on-update", - "collect-logs", - "guardrails-prompt-p1", - "guardrails-prompt-s1", - "guardrails-prompt-s10", - "guardrails-prompt-s11", - "guardrails-prompt-s12", - "guardrails-prompt-s13", - "guardrails-prompt-s14", - "guardrails-prompt-s2", - "guardrails-prompt-s3", - "guardrails-prompt-s4", - "guardrails-prompt-s5", - "guardrails-prompt-s6", - "guardrails-prompt-s7", - "guardrails-prompt-s8", - "guardrails-prompt-s9", - "guardrails-response-p1", - "guardrails-response-s1", - "guardrails-response-s10", - "guardrails-response-s11", - "guardrails-response-s12", - "guardrails-response-s13", - "guardrails-response-s14", - "guardrails-response-s2", - "guardrails-response-s3", - "guardrails-response-s4", - "guardrails-response-s5", - "guardrails-response-s6", - "guardrails-response-s7", - "guardrails-response-s8", - "guardrails-response-s9", - "log-classification", - "log-management-strategy", - "logpush", - "multiprovider-enabled", - "rate-limiting-technique", - "retry-backoff", - "spend-limits-enabled", - "workers-ai-billing-mode", - "zdr", - "dry-run", - ], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["cache-invalidate-on-update"] === undefined) { - throw new Error( - "--cache-invalidate-on-update is required (or pass --body with this field set)." - ); - } - if (argv["cache-ttl"] === undefined) { - throw new Error( - "--cache-ttl is required (or pass --body with this field set)." - ); - } - if (argv["collect-logs"] === undefined) { - throw new Error( - "--collect-logs is required (or pass --body with this field set)." - ); - } - if (argv["rate-limiting-interval"] === undefined) { - throw new Error( - "--rate-limiting-interval is required (or pass --body with this field set)." - ); - } - if (argv["rate-limiting-limit"] === undefined) { - throw new Error( - "--rate-limiting-limit is required (or pass --body with this field set)." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway gateways update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}`, - pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - authentication: argv["authentication"], - byok_only: argv["byok-only"], - cache_invalidate_on_update: - argv["cache-invalidate-on-update"], - cache_ttl: argv["cache-ttl"], - collect_logs: argv["collect-logs"], - guardrails: { - prompt: { - P1: argv["guardrails-prompt-p1"], - S1: argv["guardrails-prompt-s1"], - S10: argv["guardrails-prompt-s10"], - S11: argv["guardrails-prompt-s11"], - S12: argv["guardrails-prompt-s12"], - S13: argv["guardrails-prompt-s13"], - S14: argv["guardrails-prompt-s14"], - S2: argv["guardrails-prompt-s2"], - S3: argv["guardrails-prompt-s3"], - S4: argv["guardrails-prompt-s4"], - S5: argv["guardrails-prompt-s5"], - S6: argv["guardrails-prompt-s6"], - S7: argv["guardrails-prompt-s7"], - S8: argv["guardrails-prompt-s8"], - S9: argv["guardrails-prompt-s9"], - }, - response: { - P1: argv["guardrails-response-p1"], - S1: argv["guardrails-response-s1"], - S10: argv["guardrails-response-s10"], - S11: argv["guardrails-response-s11"], - S12: argv["guardrails-response-s12"], - S13: argv["guardrails-response-s13"], - S14: argv["guardrails-response-s14"], - S2: argv["guardrails-response-s2"], - S3: argv["guardrails-response-s3"], - S4: argv["guardrails-response-s4"], - S5: argv["guardrails-response-s5"], - S6: argv["guardrails-response-s6"], - S7: argv["guardrails-response-s7"], - S8: argv["guardrails-response-s8"], - S9: argv["guardrails-response-s9"], - }, - }, - log_classification: argv["log-classification"], - log_management: argv["log-management"], - log_management_strategy: argv["log-management-strategy"], - logpush: argv["logpush"], - logpush_public_key: resolveFileToken( - argv["logpush-public-key"] as string | undefined, - "logpush-public-key", - "text" - ), - multiprovider_enabled: argv["multiprovider-enabled"], - otel: parseObjectArray(argv["otel"], "otel", true), - rate_limiting_interval: argv["rate-limiting-interval"], - rate_limiting_limit: argv["rate-limiting-limit"], - rate_limiting_technique: argv["rate-limiting-technique"], - retry_backoff: argv["retry-backoff"], - retry_delay: argv["retry-delay"], - retry_max_attempts: argv["retry-max-attempts"], - spend_limits: { - enabled: argv["spend-limits-enabled"], - rules: parseObjectArray( - argv["spend-limits-rules"], - "spend-limits-rules" - ), - }, - store_id: resolveFileToken( - argv["store-id"] as string | undefined, - "store-id", - "text" - ), - stripe: { - authorization: resolveFileToken( - argv["stripe-authorization"] as string | undefined, - "stripe-authorization", - "text" - ), - usage_events: parseObjectArray( - argv["stripe-usage-events"], - "stripe-usage-events" - ), - }, - workers_ai_billing_mode: argv["workers-ai-billing-mode"], - zdr: argv["zdr"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - requestApi( - client, - "PUT", - `/accounts/${accountId}/ai-gateway/gateways/${encodeURIComponent(String(argv["gateway-id"]))}`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData: Record = {}; - if (argv["authentication"] !== undefined) - setNestedValue(bodyData, ["authentication"], argv["authentication"]); - if (argv["byok-only"] !== undefined) - setNestedValue(bodyData, ["byok_only"], argv["byok-only"]); - if (argv["cache-invalidate-on-update"] !== undefined) - setNestedValue( - bodyData, - ["cache_invalidate_on_update"], - argv["cache-invalidate-on-update"] - ); - if (argv["cache-ttl"] !== undefined) - setNestedValue(bodyData, ["cache_ttl"], argv["cache-ttl"]); - if (argv["collect-logs"] !== undefined) - setNestedValue(bodyData, ["collect_logs"], argv["collect-logs"]); - if (argv["guardrails-prompt-p1"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "prompt", "P1"], - argv["guardrails-prompt-p1"] - ); - if (argv["guardrails-prompt-s1"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "prompt", "S1"], - argv["guardrails-prompt-s1"] - ); - if (argv["guardrails-prompt-s10"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "prompt", "S10"], - argv["guardrails-prompt-s10"] - ); - if (argv["guardrails-prompt-s11"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "prompt", "S11"], - argv["guardrails-prompt-s11"] - ); - if (argv["guardrails-prompt-s12"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "prompt", "S12"], - argv["guardrails-prompt-s12"] - ); - if (argv["guardrails-prompt-s13"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "prompt", "S13"], - argv["guardrails-prompt-s13"] - ); - if (argv["guardrails-prompt-s14"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "prompt", "S14"], - argv["guardrails-prompt-s14"] - ); - if (argv["guardrails-prompt-s2"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "prompt", "S2"], - argv["guardrails-prompt-s2"] - ); - if (argv["guardrails-prompt-s3"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "prompt", "S3"], - argv["guardrails-prompt-s3"] - ); - if (argv["guardrails-prompt-s4"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "prompt", "S4"], - argv["guardrails-prompt-s4"] - ); - if (argv["guardrails-prompt-s5"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "prompt", "S5"], - argv["guardrails-prompt-s5"] - ); - if (argv["guardrails-prompt-s6"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "prompt", "S6"], - argv["guardrails-prompt-s6"] - ); - if (argv["guardrails-prompt-s7"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "prompt", "S7"], - argv["guardrails-prompt-s7"] - ); - if (argv["guardrails-prompt-s8"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "prompt", "S8"], - argv["guardrails-prompt-s8"] - ); - if (argv["guardrails-prompt-s9"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "prompt", "S9"], - argv["guardrails-prompt-s9"] - ); - if (argv["guardrails-response-p1"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "response", "P1"], - argv["guardrails-response-p1"] - ); - if (argv["guardrails-response-s1"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "response", "S1"], - argv["guardrails-response-s1"] - ); - if (argv["guardrails-response-s10"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "response", "S10"], - argv["guardrails-response-s10"] - ); - if (argv["guardrails-response-s11"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "response", "S11"], - argv["guardrails-response-s11"] - ); - if (argv["guardrails-response-s12"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "response", "S12"], - argv["guardrails-response-s12"] - ); - if (argv["guardrails-response-s13"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "response", "S13"], - argv["guardrails-response-s13"] - ); - if (argv["guardrails-response-s14"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "response", "S14"], - argv["guardrails-response-s14"] - ); - if (argv["guardrails-response-s2"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "response", "S2"], - argv["guardrails-response-s2"] - ); - if (argv["guardrails-response-s3"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "response", "S3"], - argv["guardrails-response-s3"] - ); - if (argv["guardrails-response-s4"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "response", "S4"], - argv["guardrails-response-s4"] - ); - if (argv["guardrails-response-s5"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "response", "S5"], - argv["guardrails-response-s5"] - ); - if (argv["guardrails-response-s6"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "response", "S6"], - argv["guardrails-response-s6"] - ); - if (argv["guardrails-response-s7"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "response", "S7"], - argv["guardrails-response-s7"] - ); - if (argv["guardrails-response-s8"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "response", "S8"], - argv["guardrails-response-s8"] - ); - if (argv["guardrails-response-s9"] !== undefined) - setNestedValue( - bodyData, - ["guardrails", "response", "S9"], - argv["guardrails-response-s9"] - ); - if (argv["log-classification"] !== undefined) - setNestedValue( - bodyData, - ["log_classification"], - argv["log-classification"] - ); - if (argv["log-management"] !== undefined) - setNestedValue(bodyData, ["log_management"], argv["log-management"]); - if (argv["log-management-strategy"] !== undefined) - setNestedValue( - bodyData, - ["log_management_strategy"], - argv["log-management-strategy"] - ); - if (argv["logpush"] !== undefined) - setNestedValue(bodyData, ["logpush"], argv["logpush"]); - if (argv["logpush-public-key"] !== undefined) - setNestedValue( - bodyData, - ["logpush_public_key"], - resolveFileToken( - argv["logpush-public-key"] as string | undefined, - "logpush-public-key", - "text" - ) - ); - if (argv["multiprovider-enabled"] !== undefined) - setNestedValue( - bodyData, - ["multiprovider_enabled"], - argv["multiprovider-enabled"] - ); - if (argv["otel"] !== undefined) - setNestedValue( - bodyData, - ["otel"], - parseObjectArray(argv["otel"], "otel", true) - ); - if (argv["rate-limiting-interval"] !== undefined) - setNestedValue( - bodyData, - ["rate_limiting_interval"], - argv["rate-limiting-interval"] - ); - if (argv["rate-limiting-limit"] !== undefined) - setNestedValue( - bodyData, - ["rate_limiting_limit"], - argv["rate-limiting-limit"] - ); - if (argv["rate-limiting-technique"] !== undefined) - setNestedValue( - bodyData, - ["rate_limiting_technique"], - argv["rate-limiting-technique"] - ); - if (argv["retry-backoff"] !== undefined) - setNestedValue(bodyData, ["retry_backoff"], argv["retry-backoff"]); - if (argv["retry-delay"] !== undefined) - setNestedValue(bodyData, ["retry_delay"], argv["retry-delay"]); - if (argv["retry-max-attempts"] !== undefined) - setNestedValue( - bodyData, - ["retry_max_attempts"], - argv["retry-max-attempts"] - ); - if (argv["spend-limits-enabled"] !== undefined) - setNestedValue( - bodyData, - ["spend_limits", "enabled"], - argv["spend-limits-enabled"] - ); - if (argv["spend-limits-rules"] !== undefined) - setNestedValue( - bodyData, - ["spend_limits", "rules"], - parseObjectArray(argv["spend-limits-rules"], "spend-limits-rules") - ); - if (argv["store-id"] !== undefined) - setNestedValue( - bodyData, - ["store_id"], - resolveFileToken( - argv["store-id"] as string | undefined, - "store-id", - "text" - ) - ); - if (argv["stripe-authorization"] !== undefined) - setNestedValue( - bodyData, - ["stripe", "authorization"], - resolveFileToken( - argv["stripe-authorization"] as string | undefined, - "stripe-authorization", - "text" - ) - ); - if (argv["stripe-usage-events"] !== undefined) - setNestedValue( - bodyData, - ["stripe", "usage_events"], - parseObjectArray(argv["stripe-usage-events"], "stripe-usage-events") - ); - if (argv["workers-ai-billing-mode"] !== undefined) - setNestedValue( - bodyData, - ["workers_ai_billing_mode"], - argv["workers-ai-billing-mode"] - ); - if (argv["zdr"] !== undefined) - setNestedValue(bodyData, ["zdr"], argv["zdr"]); - const result = await withProgress(`Updating`, async () => - requestApi( - client, - "PUT", - `/accounts/${accountId}/ai-gateway/gateways/${encodeURIComponent(String(argv["gateway-id"]))}`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 ai-gateway gateways update \n\nUpdates the configuration of an AI Gateway, such as its caching, rate limiting, spend limits, logging, and authentication settings.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/index.ts b/packages/cli/src/commands/_generated/ai-gateway/index.ts index 2613e67834..b48f87e382 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/index.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/index.ts @@ -4,30 +4,25 @@ import $dynamicrouting from "./dynamic-routing/index.js"; import $gateways from "./gateways/index.js"; import $logs from "./logs/index.js"; import $modelaliases from "./model-aliases/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * ai-gateway command * @generated from apis/overlays/ai-gateway.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "ai-gateway", describe: "Proxy, cache, rate-limit, and observe requests to AI providers — OpenAI, Anthropic, Workers AI, and more", - builder: (yargs) => { - return yargs - .command($customdomains) - .command($customproviders) - .command($dynamicrouting) - .command($gateways) - .command($logs) - .command($modelaliases) - .demandCommand(1, "Please specify a subcommand"); + routes: { + "custom-domains": $customdomains, + "custom-providers": $customproviders, + "dynamic-routing": $dynamicrouting, + gateways: $gateways, + logs: $logs, + "model-aliases": $modelaliases, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/logs/delete.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/logs/delete.handler.ts new file mode 100644 index 0000000000..66b08737e4 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/logs/delete.handler.ts @@ -0,0 +1,68 @@ +import operation from "../../_operations/ai-gateway/logs/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway logs delete", + classification: { + safeFlags: ["order-by", "order-by-direction", "dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + order_by: argv["order-by"], + order_by_direction: argv["order-by-direction"], + filters: argv["filters"], + limit: argv["limit"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway logs delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/logs`, + pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This permanently deletes every stored log entry on the gateway that matches the filters. Deleted logs cannot be recovered.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + gateway_id: argv["gateway-id"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/logs/delete.ts b/packages/cli/src/commands/_generated/ai-gateway/logs/delete.ts index 9756a240e3..4498765f96 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/logs/delete.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/logs/delete.ts @@ -1,37 +1,19 @@ -import operation from "../../_operations/ai-gateway/logs/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway logs delete \n\nDeletes gateway log entries matching the specified criteria." - ) - .positional("gateway-id", { - type: "string", - description: "Unique identifier of the AI Gateway within the account.", - demandOption: true, - }) - .option("order-by", { - type: "string", - description: "Order by", - choices: [ +const parameters = { + flags: { + "order-by": { + kind: "enum", + brief: "Order by", + values: [ "created_at", "provider", "model", @@ -44,85 +26,50 @@ function builder(yargs: Argv) { "duration", "feedback", ], - }) - .option("order-by-direction", { - type: "string", - description: "Order by direction", - choices: ["asc", "desc"], - }) - .option("filters", { type: "string", array: true, description: "Filters" }) - .option("limit", { type: "number", description: "Limit" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + }, + "order-by-direction": { + kind: "enum", + brief: "Order by direction", + values: ["asc", "desc"], + optional: true, + }, + filters: { + kind: "parsed", + brief: "Filters", + variadic: true, + optional: true, + parse: String, + }, + limit: { kind: "parsed", brief: "Limit", optional: true, parse: Number }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "gateway-id", + brief: "Unique identifier of the AI Gateway within the account.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete Gateway Logs", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway logs delete", - classification: { - safeFlags: ["order-by", "order-by-direction", "dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - order_by: argv["order-by"], - order_by_direction: argv["order-by-direction"], - filters: argv["filters"], - limit: argv["limit"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway logs delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/logs`, - pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This permanently deletes every stored log entry on the gateway that matches the filters. Deleted logs cannot be recovered.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - gateway_id: argv["gateway-id"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 ai-gateway logs delete \n\nDeletes gateway log entries matching the specified criteria.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/logs/get-request.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/logs/get-request.handler.ts new file mode 100644 index 0000000000..4ed2699064 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/logs/get-request.handler.ts @@ -0,0 +1,53 @@ +import operation from "../../_operations/ai-gateway/logs/get-request.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get-request.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway logs get-request", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway logs get-request", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/logs/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}/request`, + pathParams: { + "gateway-id": String(argv["gateway-id"] ?? ""), + id: String(argv["id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/logs/get-request.ts b/packages/cli/src/commands/_generated/ai-gateway/logs/get-request.ts index 5f55287367..a55ee3fd43 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/logs/get-request.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/logs/get-request.ts @@ -1,88 +1,36 @@ -import operation from "../../_operations/ai-gateway/logs/get-request.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get-request command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway logs get-request \n\nRetrieves the original request payload for an AI Gateway log entry." - ) - .positional("id", { - type: "string", - description: "ID", - demandOption: true, - }) - .option("gateway-id", { - type: "string", - description: "Unique identifier of the AI Gateway within the account.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "gateway-id": { + kind: "parsed", + brief: "Unique identifier of the AI Gateway within the account.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "id", brief: "ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get-request ", describe: "Get Gateway Log Request", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway logs get-request", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway logs get-request", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/logs/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}/request`, - pathParams: { - "gateway-id": String(argv["gateway-id"] ?? ""), - id: String(argv["id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-gateway logs get-request \n\nRetrieves the original request payload for an AI Gateway log entry.", + ...parameters, + loader: () => import("./get-request.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/logs/get-response.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/logs/get-response.handler.ts new file mode 100644 index 0000000000..f4231a47ab --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/logs/get-response.handler.ts @@ -0,0 +1,53 @@ +import operation from "../../_operations/ai-gateway/logs/get-response.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get-response.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway logs get-response", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway logs get-response", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/logs/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}/response`, + pathParams: { + "gateway-id": String(argv["gateway-id"] ?? ""), + id: String(argv["id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/logs/get-response.ts b/packages/cli/src/commands/_generated/ai-gateway/logs/get-response.ts index 57a92997b9..f24423f1b3 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/logs/get-response.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/logs/get-response.ts @@ -1,88 +1,36 @@ -import operation from "../../_operations/ai-gateway/logs/get-response.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get-response command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway logs get-response \n\nRetrieves the response payload for an AI Gateway log entry." - ) - .positional("id", { - type: "string", - description: "ID", - demandOption: true, - }) - .option("gateway-id", { - type: "string", - description: "Unique identifier of the AI Gateway within the account.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "gateway-id": { + kind: "parsed", + brief: "Unique identifier of the AI Gateway within the account.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "id", brief: "ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get-response ", describe: "Get Gateway Log Response", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway logs get-response", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway logs get-response", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/logs/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}/response`, - pathParams: { - "gateway-id": String(argv["gateway-id"] ?? ""), - id: String(argv["id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-gateway logs get-response \n\nRetrieves the response payload for an AI Gateway log entry.", + ...parameters, + loader: () => import("./get-response.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/logs/get.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/logs/get.handler.ts new file mode 100644 index 0000000000..045cbf6525 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/logs/get.handler.ts @@ -0,0 +1,53 @@ +import operation from "../../_operations/ai-gateway/logs/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway logs get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway logs get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/logs/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, + pathParams: { + "gateway-id": String(argv["gateway-id"] ?? ""), + id: String(argv["id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/logs/get.ts b/packages/cli/src/commands/_generated/ai-gateway/logs/get.ts index 5d13205173..537349098c 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/logs/get.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/logs/get.ts @@ -1,88 +1,36 @@ -import operation from "../../_operations/ai-gateway/logs/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway logs get \n\nRetrieves detailed information for a specific AI Gateway log entry." - ) - .positional("id", { - type: "string", - description: "ID", - demandOption: true, - }) - .option("gateway-id", { - type: "string", - description: "Unique identifier of the AI Gateway within the account.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "gateway-id": { + kind: "parsed", + brief: "Unique identifier of the AI Gateway within the account.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "id", brief: "ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get Gateway Log Detail", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway logs get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway logs get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/logs/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, - pathParams: { - "gateway-id": String(argv["gateway-id"] ?? ""), - id: String(argv["id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-gateway logs get \n\nRetrieves detailed information for a specific AI Gateway log entry.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/logs/index.ts b/packages/cli/src/commands/_generated/ai-gateway/logs/index.ts index 622fcbd279..b98ac917b0 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/logs/index.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/logs/index.ts @@ -4,30 +4,25 @@ import $getresponse from "./get-response.js"; import $get from "./get.js"; import $list from "./list.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * logs command group * @generated from apis/overlays/ai-gateway.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "logs", describe: "Inspect, annotate, and delete gateway request logs stored by Legacy Logs", - builder: (yargs) => { - return yargs - .command($delete) - .command($get) - .command($getrequest) - .command($getresponse) - .command($list) - .command($update) - .demandCommand(1, "Please specify a subcommand"); + routes: { + delete: $delete, + get: $get, + "get-request": $getrequest, + "get-response": $getresponse, + list: $list, + update: $update, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/logs/list.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/logs/list.handler.ts new file mode 100644 index 0000000000..cf33cb769c --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/logs/list.handler.ts @@ -0,0 +1,90 @@ +import operation from "../../_operations/ai-gateway/logs/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway logs list", + classification: { + safeFlags: [ + "order-by", + "order-by-direction", + "meta-info", + "direction", + "feedback", + "success", + "cached", + "dry-run", + ], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + search: argv["search"], + page: argv["page"], + per_page: argv["per-page"], + order_by: argv["order-by"], + order_by_direction: argv["order-by-direction"], + filters: argv["filters"], + meta_info: argv["meta-info"], + direction: argv["direction"], + start_date: argv["start-date"], + end_date: argv["end-date"], + min_cost: argv["min-cost"], + max_cost: argv["max-cost"], + min_tokens_in: argv["min-tokens-in"], + max_tokens_in: argv["max-tokens-in"], + min_tokens_out: argv["min-tokens-out"], + max_tokens_out: argv["max-tokens-out"], + min_total_tokens: argv["min-total-tokens"], + max_total_tokens: argv["max-total-tokens"], + min_duration: argv["min-duration"], + max_duration: argv["max-duration"], + feedback: argv["feedback"], + success: argv["success"], + cached: argv["cached"], + model: argv["model"], + model_type: argv["model-type"], + provider: argv["ai-gateway-provider"], + request_content_type: argv["request-content-type"], + response_content_type: argv["response-content-type"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway logs list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/logs`, + pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + gateway_id: argv["gateway-id"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/logs/list.ts b/packages/cli/src/commands/_generated/ai-gateway/logs/list.ts index 3ec26e19e9..afcd31e3d1 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/logs/list.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/logs/list.ts @@ -1,46 +1,43 @@ -import operation from "../../_operations/ai-gateway/logs/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway logs list\n\nLists request/response log entries for the AI gateway with filtering and pagination." - ) - .option("gateway-id", { - type: "string", - description: "Unique identifier of the AI Gateway within the account.", - demandOption: true, - }) - .option("search", { - type: "string", - description: "Free-text search over log metadata.", - }) - .option("page", { - type: "number", - description: +const parameters = { + flags: { + "gateway-id": { + kind: "parsed", + brief: "Unique identifier of the AI Gateway within the account.", + parse: String, + }, + search: { + kind: "parsed", + brief: "Free-text search over log metadata.", + optional: true, + parse: String, + }, + page: { + kind: "parsed", + brief: "Page number, from 1. A high page reads every page before it again. To read further back in a listing sorted by created_at, ask for page 1 again with a created_at lt filter set to the created_at of the last log returned. Logs in the same millisecond as that log can be left out: to include them, set the filter 1 ms later and drop the logs already returned.", - }) - .option("per-page", { type: "number", description: "Per page" }) - .option("order-by", { - type: "string", - description: "Order by", - choices: [ + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Per page", + optional: true, + parse: Number, + }, + "order-by": { + kind: "enum", + brief: "Order by", + values: [ "created_at", "provider", "model", @@ -48,143 +45,154 @@ function builder(yargs: Argv) { "success", "cached", ], - }) - .option("order-by-direction", { - type: "string", - description: "Order by direction", - choices: ["asc", "desc"], - }) - .option("filters", { type: "string", array: true, description: "Filters" }) - .option("meta-info", { type: "boolean", description: "Meta info" }) - .option("direction", { - type: "string", - description: "Direction", - choices: ["asc", "desc"], - }) - .option("start-date", { type: "string", description: "Start date" }) - .option("end-date", { type: "string", description: "End date" }) - .option("min-cost", { type: "number", description: "Min cost" }) - .option("max-cost", { type: "number", description: "Max cost" }) - .option("min-tokens-in", { type: "number", description: "Min tokens in" }) - .option("max-tokens-in", { type: "number", description: "Max tokens in" }) - .option("min-tokens-out", { type: "number", description: "Min tokens out" }) - .option("max-tokens-out", { type: "number", description: "Max tokens out" }) - .option("min-total-tokens", { - type: "number", - description: "Min total tokens", - }) - .option("max-total-tokens", { - type: "number", - description: "Max total tokens", - }) - .option("min-duration", { type: "number", description: "Min duration" }) - .option("max-duration", { type: "number", description: "Max duration" }) - .option("feedback", { - type: "string", - description: "Feedback", - choices: ["-1", "0", "1"], - }) - .option("success", { type: "boolean", description: "Success" }) - .option("cached", { type: "boolean", description: "Cached" }) - .option("model", { type: "string", description: "Model filter." }) - .option("model-type", { type: "string", description: "Model type" }) - .option("ai-gateway-provider", { type: "string", description: "Provider" }) - .option("request-content-type", { - type: "string", - description: "Request content type", - }) - .option("response-content-type", { - type: "string", - description: "Response content type", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + }, + "order-by-direction": { + kind: "enum", + brief: "Order by direction", + values: ["asc", "desc"], + optional: true, + }, + filters: { + kind: "parsed", + brief: "Filters", + variadic: true, + optional: true, + parse: String, + }, + "meta-info": { kind: "boolean", brief: "Meta info", optional: true }, + direction: { + kind: "enum", + brief: "Direction", + values: ["asc", "desc"], + optional: true, + }, + "start-date": { + kind: "parsed", + brief: "Start date", + optional: true, + parse: String, + }, + "end-date": { + kind: "parsed", + brief: "End date", + optional: true, + parse: String, + }, + "min-cost": { + kind: "parsed", + brief: "Min cost", + optional: true, + parse: Number, + }, + "max-cost": { + kind: "parsed", + brief: "Max cost", + optional: true, + parse: Number, + }, + "min-tokens-in": { + kind: "parsed", + brief: "Min tokens in", + optional: true, + parse: Number, + }, + "max-tokens-in": { + kind: "parsed", + brief: "Max tokens in", + optional: true, + parse: Number, + }, + "min-tokens-out": { + kind: "parsed", + brief: "Min tokens out", + optional: true, + parse: Number, + }, + "max-tokens-out": { + kind: "parsed", + brief: "Max tokens out", + optional: true, + parse: Number, + }, + "min-total-tokens": { + kind: "parsed", + brief: "Min total tokens", + optional: true, + parse: Number, + }, + "max-total-tokens": { + kind: "parsed", + brief: "Max total tokens", + optional: true, + parse: Number, + }, + "min-duration": { + kind: "parsed", + brief: "Min duration", + optional: true, + parse: Number, + }, + "max-duration": { + kind: "parsed", + brief: "Max duration", + optional: true, + parse: Number, + }, + feedback: { + kind: "enum", + brief: "Feedback", + values: ["-1", "0", "1"], + optional: true, + }, + success: { kind: "boolean", brief: "Success", optional: true }, + cached: { kind: "boolean", brief: "Cached", optional: true }, + model: { + kind: "parsed", + brief: "Model filter.", + optional: true, + parse: String, + }, + "model-type": { + kind: "parsed", + brief: "Model type", + optional: true, + parse: String, + }, + "ai-gateway-provider": { + kind: "parsed", + brief: "Provider", + optional: true, + parse: String, + }, + "request-content-type": { + kind: "parsed", + brief: "Request content type", + optional: true, + parse: String, + }, + "response-content-type": { + kind: "parsed", + brief: "Response content type", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Gateway Logs", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway logs list", - classification: { - safeFlags: [ - "order-by", - "order-by-direction", - "meta-info", - "direction", - "feedback", - "success", - "cached", - "dry-run", - ], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - search: argv["search"], - page: argv["page"], - per_page: argv["per-page"], - order_by: argv["order-by"], - order_by_direction: argv["order-by-direction"], - filters: argv["filters"], - meta_info: argv["meta-info"], - direction: argv["direction"], - start_date: argv["start-date"], - end_date: argv["end-date"], - min_cost: argv["min-cost"], - max_cost: argv["max-cost"], - min_tokens_in: argv["min-tokens-in"], - max_tokens_in: argv["max-tokens-in"], - min_tokens_out: argv["min-tokens-out"], - max_tokens_out: argv["max-tokens-out"], - min_total_tokens: argv["min-total-tokens"], - max_total_tokens: argv["max-total-tokens"], - min_duration: argv["min-duration"], - max_duration: argv["max-duration"], - feedback: argv["feedback"], - success: argv["success"], - cached: argv["cached"], - model: argv["model"], - model_type: argv["model-type"], - provider: argv["ai-gateway-provider"], - request_content_type: argv["request-content-type"], - response_content_type: argv["response-content-type"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway logs list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/logs`, - pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - gateway_id: argv["gateway-id"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-gateway logs list\n\nLists request/response log entries for the AI gateway with filtering and pagination.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/logs/update.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/logs/update.handler.ts new file mode 100644 index 0000000000..5dea656a70 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/logs/update.handler.ts @@ -0,0 +1,91 @@ +import operation from "../../_operations/ai-gateway/logs/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseJsonMap } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway logs update", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway logs update", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/logs/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, + pathParams: { + "gateway-id": String(argv["gateway-id"] ?? ""), + id: String(argv["id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody( + { + feedback: argv["feedback"], + metadata: parseJsonMap(argv["metadata"], "metadata"), + score: argv["score"], + }, + [["metadata"]] + ), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody( + { + feedback: argv["feedback"], + metadata: parseJsonMap(argv["metadata"], "metadata"), + score: argv["score"], + }, + [["metadata"]] + ); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/logs/update.ts b/packages/cli/src/commands/_generated/ai-gateway/logs/update.ts index ca387a41f9..caa4eb6e39 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/logs/update.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/logs/update.ts @@ -1,137 +1,61 @@ -import operation from "../../_operations/ai-gateway/logs/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseJsonMap } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway logs update \n\nUpdates metadata for an AI Gateway log entry." - ) - .positional("id", { - type: "string", - description: "ID", - demandOption: true, - }) - .option("gateway-id", { - type: "string", - description: "Unique identifier of the AI Gateway within the account.", - demandOption: true, - }) - .option("feedback", { type: "number", description: "The feedback field" }) - .option("metadata", { - type: "string", - description: +const parameters = { + flags: { + "gateway-id": { + kind: "parsed", + brief: "Unique identifier of the AI Gateway within the account.", + parse: String, + }, + feedback: { + kind: "parsed", + brief: "The feedback field", + optional: true, + parse: Number, + }, + metadata: { + kind: "parsed", + brief: 'The metadata field. Provide as a JSON object or @path/to/file.json. Shape: {"": (string | number | boolean)}.', - }) - .option("score", { type: "number", description: "The score field" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + score: { + kind: "parsed", + brief: "The score field", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [{ placeholder: "id", brief: "ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update ", describe: "Patch Gateway Log", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway logs update", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway logs update", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/logs/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, - pathParams: { - "gateway-id": String(argv["gateway-id"] ?? ""), - id: String(argv["id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody( - { - feedback: argv["feedback"], - metadata: parseJsonMap(argv["metadata"], "metadata"), - score: argv["score"], - }, - [["metadata"]] - ), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody( - { - feedback: argv["feedback"], - metadata: parseJsonMap(argv["metadata"], "metadata"), - score: argv["score"], - }, - [["metadata"]] - ); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 ai-gateway logs update \n\nUpdates metadata for an AI Gateway log entry.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/model-aliases/create.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/model-aliases/create.handler.ts new file mode 100644 index 0000000000..ae9ab2e57f --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/model-aliases/create.handler.ts @@ -0,0 +1,110 @@ +import operation from "../../_operations/ai-gateway/model-aliases/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway model-aliases create", + classification: { + safeFlags: ["routing-algorithm", "routing-mode", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["models"] === undefined) { + throw new Error( + "--models is required (or pass --body with this field set)." + ); + } + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField("name", "The name field"); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway model-aliases create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/model_aliases`, + pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + models: parseObjectArray(argv["models"], "models"), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + routing: { + algorithm: argv["routing-algorithm"], + mode: argv["routing-mode"], + }, + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + gateway_id: argv["gateway-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + models: parseObjectArray(argv["models"], "models"), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + routing: { + algorithm: argv["routing-algorithm"], + mode: argv["routing-mode"], + }, + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + gateway_id: argv["gateway-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/model-aliases/create.ts b/packages/cli/src/commands/_generated/ai-gateway/model-aliases/create.ts index 457c6307fd..4066e4acb7 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/model-aliases/create.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/model-aliases/create.ts @@ -1,169 +1,69 @@ -import operation from "../../_operations/ai-gateway/model-aliases/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway model-aliases create \n\nCreates a model alias on a gateway: a named, ordered list of catalog models, each optionally restricted to providers. Requests address it as `custom/`." - ) - .positional("gateway-id", { - type: "string", - description: "Gateway ID", - demandOption: true, - }) - .option("models", { - type: "string", - description: +const parameters = { + flags: { + models: { + kind: "parsed", + brief: 'The models field. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"model": string, "providers"?: [string]}]. ? marks optional keys.', - }) - .option("name", { type: "string", description: "The name field" }) - .option("routing-algorithm", { - type: "string", - description: "The routing.algorithm field", + optional: true, + parse: String, + }, + name: { + kind: "parsed", + brief: "The name field", + optional: true, + parse: String, + }, + "routing-algorithm": { + kind: "parsed", + brief: "The routing.algorithm field", + optional: true, choices: ["preferred", "smart"], - }) - .coerce("routing-algorithm", (value) => - resolveFileToken(value, "routing-algorithm", "text") - ) - .option("routing-mode", { - type: "string", - description: "The routing.mode field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "routing-algorithm", "text"), + }, + "routing-mode": { + kind: "parsed", + brief: "The routing.mode field", + optional: true, choices: ["cost", "best"], - }) - .coerce("routing-mode", (value) => - resolveFileToken(value, "routing-mode", "text") - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "routing-mode", "text"), + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [{ placeholder: "gateway-id", brief: "Gateway ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Create a model alias", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway model-aliases create", - classification: { - safeFlags: ["routing-algorithm", "routing-mode", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["models"] === undefined) { - throw new Error( - "--models is required (or pass --body with this field set)." - ); - } - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "The name field" - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway model-aliases create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/model_aliases`, - pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - models: parseObjectArray(argv["models"], "models"), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - routing: { - algorithm: argv["routing-algorithm"], - mode: argv["routing-mode"], - }, - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - gateway_id: argv["gateway-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - models: parseObjectArray(argv["models"], "models"), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - routing: { - algorithm: argv["routing-algorithm"], - mode: argv["routing-mode"], - }, - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - gateway_id: argv["gateway-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 ai-gateway model-aliases create \n\nCreates a model alias on a gateway: a named, ordered list of catalog models, each optionally restricted to providers. Requests address it as `custom/`.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/model-aliases/delete.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/model-aliases/delete.handler.ts new file mode 100644 index 0000000000..fb33f7a586 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/model-aliases/delete.handler.ts @@ -0,0 +1,59 @@ +import operation from "../../_operations/ai-gateway/model-aliases/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway model-aliases delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway model-aliases delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/model_aliases/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, + pathParams: { + "gateway-id": String(argv["gateway-id"] ?? ""), + id: String(argv["id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/model-aliases/delete.ts b/packages/cli/src/commands/_generated/ai-gateway/model-aliases/delete.ts index 79703c9ea1..5118746936 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/model-aliases/delete.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/model-aliases/delete.ts @@ -1,100 +1,38 @@ -import operation from "../../_operations/ai-gateway/model-aliases/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway model-aliases delete \n\nDeletes a model alias from a gateway." - ) - .positional("id", { - type: "string", - description: "ID", - demandOption: true, - }) - .option("gateway-id", { - type: "string", - description: "Gateway ID", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "gateway-id": { kind: "parsed", brief: "Gateway ID", parse: String }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "id", brief: "ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete a model alias", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway model-aliases delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway model-aliases delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/model_aliases/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, - pathParams: { - "gateway-id": String(argv["gateway-id"] ?? ""), - id: String(argv["id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 ai-gateway model-aliases delete \n\nDeletes a model alias from a gateway.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/model-aliases/get.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/model-aliases/get.handler.ts new file mode 100644 index 0000000000..ebd7acd002 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/model-aliases/get.handler.ts @@ -0,0 +1,53 @@ +import operation from "../../_operations/ai-gateway/model-aliases/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway model-aliases get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway model-aliases get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/model_aliases/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, + pathParams: { + "gateway-id": String(argv["gateway-id"] ?? ""), + id: String(argv["id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/model-aliases/get.ts b/packages/cli/src/commands/_generated/ai-gateway/model-aliases/get.ts index 2bf1f3f33a..2c12dec4ec 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/model-aliases/get.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/model-aliases/get.ts @@ -1,88 +1,32 @@ -import operation from "../../_operations/ai-gateway/model-aliases/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway model-aliases get \n\nRetrieves a model alias configured on a gateway." - ) - .positional("id", { - type: "string", - description: "ID", - demandOption: true, - }) - .option("gateway-id", { - type: "string", - description: "Gateway ID", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "gateway-id": { kind: "parsed", brief: "Gateway ID", parse: String }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "id", brief: "ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get a model alias", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway model-aliases get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway model-aliases get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/model_aliases/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, - pathParams: { - "gateway-id": String(argv["gateway-id"] ?? ""), - id: String(argv["id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-gateway model-aliases get \n\nRetrieves a model alias configured on a gateway.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/model-aliases/index.ts b/packages/cli/src/commands/_generated/ai-gateway/model-aliases/index.ts index 2bf9151443..61ff9261d2 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/model-aliases/index.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/model-aliases/index.ts @@ -3,29 +3,24 @@ import $delete from "./delete.js"; import $get from "./get.js"; import $list from "./list.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * model-aliases command group * @generated from apis/overlays/ai-gateway.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "model-aliases", describe: "Map a custom model name to one or more provider models on a gateway", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .command($list) - .command($update) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, + list: $list, + update: $update, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/model-aliases/list.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/model-aliases/list.handler.ts new file mode 100644 index 0000000000..d37602c8ed --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/model-aliases/list.handler.ts @@ -0,0 +1,55 @@ +import operation from "../../_operations/ai-gateway/model-aliases/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway model-aliases list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway model-aliases list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/model_aliases`, + pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + gateway_id: argv["gateway-id"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/model-aliases/list.ts b/packages/cli/src/commands/_generated/ai-gateway/model-aliases/list.ts index db721f6725..c9cd1dd823 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/model-aliases/list.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/model-aliases/list.ts @@ -1,87 +1,39 @@ -import operation from "../../_operations/ai-gateway/model-aliases/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway model-aliases list\n\nLists the model aliases configured on a gateway, sorted by name." - ) - .option("gateway-id", { - type: "string", - description: "Gateway ID", - demandOption: true, - }) - .option("page", { type: "number", description: "Page" }) - .option("per-page", { type: "number", description: "Per page" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "gateway-id": { kind: "parsed", brief: "Gateway ID", parse: String }, + page: { kind: "parsed", brief: "Page", optional: true, parse: Number }, + "per-page": { + kind: "parsed", + brief: "Per page", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List model aliases", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway model-aliases list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway model-aliases list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/model_aliases`, - pathParams: { "gateway-id": String(argv["gateway-id"] ?? "") }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - gateway_id: argv["gateway-id"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-gateway model-aliases list\n\nLists the model aliases configured on a gateway, sorted by name.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-gateway/model-aliases/update.handler.ts b/packages/cli/src/commands/_generated/ai-gateway/model-aliases/update.handler.ts new file mode 100644 index 0000000000..be9e07f2fc --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-gateway/model-aliases/update.handler.ts @@ -0,0 +1,115 @@ +import operation from "../../_operations/ai-gateway/model-aliases/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-gateway model-aliases update", + classification: { + safeFlags: ["routing-algorithm", "routing-mode", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["models"] === undefined) { + throw new Error( + "--models is required (or pass --body with this field set)." + ); + } + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField("name", "The name field"); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-gateway model-aliases update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/model_aliases/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, + pathParams: { + "gateway-id": String(argv["gateway-id"] ?? ""), + id: String(argv["id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + models: parseObjectArray(argv["models"], "models"), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + routing: { + algorithm: argv["routing-algorithm"], + mode: argv["routing-mode"], + }, + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + models: parseObjectArray(argv["models"], "models"), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + routing: { + algorithm: argv["routing-algorithm"], + mode: argv["routing-mode"], + }, + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + gateway_id: argv["gateway-id"], + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-gateway/model-aliases/update.ts b/packages/cli/src/commands/_generated/ai-gateway/model-aliases/update.ts index 0d0021543e..91160f82ca 100644 --- a/packages/cli/src/commands/_generated/ai-gateway/model-aliases/update.ts +++ b/packages/cli/src/commands/_generated/ai-gateway/model-aliases/update.ts @@ -1,179 +1,70 @@ -import operation from "../../_operations/ai-gateway/model-aliases/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/ai-gateway.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-gateway model-aliases update \n\nReplaces a model alias. Omitting `routing` clears any previously stored routing options." - ) - .positional("id", { - type: "string", - description: "ID", - demandOption: true, - }) - .option("gateway-id", { - type: "string", - description: "Gateway ID", - demandOption: true, - }) - .option("models", { - type: "string", - description: +const parameters = { + flags: { + "gateway-id": { kind: "parsed", brief: "Gateway ID", parse: String }, + models: { + kind: "parsed", + brief: 'The models field. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"model": string, "providers"?: [string]}]. ? marks optional keys.', - }) - .option("name", { type: "string", description: "The name field" }) - .option("routing-algorithm", { - type: "string", - description: "The routing.algorithm field", + optional: true, + parse: String, + }, + name: { + kind: "parsed", + brief: "The name field", + optional: true, + parse: String, + }, + "routing-algorithm": { + kind: "parsed", + brief: "The routing.algorithm field", + optional: true, choices: ["preferred", "smart"], - }) - .coerce("routing-algorithm", (value) => - resolveFileToken(value, "routing-algorithm", "text") - ) - .option("routing-mode", { - type: "string", - description: "The routing.mode field", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "routing-algorithm", "text"), + }, + "routing-mode": { + kind: "parsed", + brief: "The routing.mode field", + optional: true, choices: ["cost", "best"], - }) - .coerce("routing-mode", (value) => - resolveFileToken(value, "routing-mode", "text") - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "routing-mode", "text"), + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [{ placeholder: "id", brief: "ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update ", describe: "Update a model alias", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-gateway model-aliases update", - classification: { - safeFlags: ["routing-algorithm", "routing-mode", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["models"] === undefined) { - throw new Error( - "--models is required (or pass --body with this field set)." - ); - } - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "The name field" - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-gateway model-aliases update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-gateway/gateways/${argv["gateway-id"] == null ? "" : encodeURIComponent(String(argv["gateway-id"]))}/model_aliases/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, - pathParams: { - "gateway-id": String(argv["gateway-id"] ?? ""), - id: String(argv["id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - models: parseObjectArray(argv["models"], "models"), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - routing: { - algorithm: argv["routing-algorithm"], - mode: argv["routing-mode"], - }, - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - models: parseObjectArray(argv["models"], "models"), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - routing: { - algorithm: argv["routing-algorithm"], - mode: argv["routing-mode"], - }, - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - gateway_id: argv["gateway-id"], - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 ai-gateway model-aliases update \n\nReplaces a model alias. Omitting `routing` clears any previously stored routing options.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/chat-completions.handler.ts b/packages/cli/src/commands/_generated/ai-search/chat-completions.handler.ts new file mode 100644 index 0000000000..4ad12ba856 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/chat-completions.handler.ts @@ -0,0 +1,332 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./chat-completions.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { + compactBody, + parseBody, + parseJsonMap, + parseObjectArray, + setNestedValue, +} from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search chat-completions", + classification: { + safeFlags: [ + "ai-search-options-cache-cache-threshold", + "ai-search-options-cache-enabled", + "ai-search-options-query-rewrite-enabled", + "ai-search-options-reranking-enabled", + "ai-search-options-retrieval-fusion-method", + "ai-search-options-retrieval-keyword-match-mode", + "ai-search-options-retrieval-retrieval-type", + "ai-search-options-retrieval-return-on-failure", + "stream", + "dry-run", + ], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["messages"] === undefined) { + throw new Error( + "--messages is required (or pass --body with this field set)." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search chat-completions", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/chat/completions`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + "instance-id": String(argv["instance-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody( + { + ai_search_options: { + cache: { + cache_threshold: + argv["ai-search-options-cache-cache-threshold"], + enabled: argv["ai-search-options-cache-enabled"], + }, + custom_metadata: parseJsonMap( + argv["ai-search-options-custom-metadata"], + "ai-search-options-custom-metadata" + ), + query_rewrite: { + enabled: + argv["ai-search-options-query-rewrite-enabled"], + model: resolveFileToken( + argv["ai-search-options-query-rewrite-model"] as + | string + | undefined, + "ai-search-options-query-rewrite-model", + "text" + ), + rewrite_prompt: resolveFileToken( + argv[ + "ai-search-options-query-rewrite-rewrite-prompt" + ] as string | undefined, + "ai-search-options-query-rewrite-rewrite-prompt", + "text" + ), + }, + reranking: { + enabled: argv["ai-search-options-reranking-enabled"], + match_threshold: + argv["ai-search-options-reranking-match-threshold"], + model: resolveFileToken( + argv["ai-search-options-reranking-model"] as + | string + | undefined, + "ai-search-options-reranking-model", + "text" + ), + }, + retrieval: { + boost_by: parseObjectArray( + argv["ai-search-options-retrieval-boost-by"], + "ai-search-options-retrieval-boost-by" + ), + context_expansion: + argv["ai-search-options-retrieval-context-expansion"], + filters: parseJsonMap( + argv["ai-search-options-retrieval-filters"], + "ai-search-options-retrieval-filters" + ), + fusion_method: + argv["ai-search-options-retrieval-fusion-method"], + keyword_match_mode: + argv[ + "ai-search-options-retrieval-keyword-match-mode" + ], + match_threshold: + argv["ai-search-options-retrieval-match-threshold"], + max_num_results: + argv["ai-search-options-retrieval-max-num-results"], + retrieval_type: + argv["ai-search-options-retrieval-retrieval-type"], + return_on_failure: + argv["ai-search-options-retrieval-return-on-failure"], + }, + }, + messages: parseObjectArray(argv["messages"], "messages"), + model: resolveFileToken( + argv["model"] as string | undefined, + "model", + "text" + ), + stream: argv["stream"], + }, + [ + ["ai_search_options", "custom_metadata"], + ["ai_search_options", "retrieval", "filters"], + ] + ), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/chat/completions`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData: Record = {}; + if (argv["ai-search-options-cache-cache-threshold"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "cache", "cache_threshold"], + argv["ai-search-options-cache-cache-threshold"] + ); + if (argv["ai-search-options-cache-enabled"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "cache", "enabled"], + argv["ai-search-options-cache-enabled"] + ); + if (argv["ai-search-options-custom-metadata"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "custom_metadata"], + parseJsonMap( + argv["ai-search-options-custom-metadata"], + "ai-search-options-custom-metadata" + ) + ); + if (argv["ai-search-options-query-rewrite-enabled"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "query_rewrite", "enabled"], + argv["ai-search-options-query-rewrite-enabled"] + ); + if (argv["ai-search-options-query-rewrite-model"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "query_rewrite", "model"], + resolveFileToken( + argv["ai-search-options-query-rewrite-model"] as string | undefined, + "ai-search-options-query-rewrite-model", + "text" + ) + ); + if (argv["ai-search-options-query-rewrite-rewrite-prompt"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "query_rewrite", "rewrite_prompt"], + resolveFileToken( + argv["ai-search-options-query-rewrite-rewrite-prompt"] as + | string + | undefined, + "ai-search-options-query-rewrite-rewrite-prompt", + "text" + ) + ); + if (argv["ai-search-options-reranking-enabled"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "reranking", "enabled"], + argv["ai-search-options-reranking-enabled"] + ); + if (argv["ai-search-options-reranking-match-threshold"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "reranking", "match_threshold"], + argv["ai-search-options-reranking-match-threshold"] + ); + if (argv["ai-search-options-reranking-model"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "reranking", "model"], + resolveFileToken( + argv["ai-search-options-reranking-model"] as string | undefined, + "ai-search-options-reranking-model", + "text" + ) + ); + if (argv["ai-search-options-retrieval-boost-by"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "boost_by"], + parseObjectArray( + argv["ai-search-options-retrieval-boost-by"], + "ai-search-options-retrieval-boost-by" + ) + ); + if (argv["ai-search-options-retrieval-context-expansion"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "context_expansion"], + argv["ai-search-options-retrieval-context-expansion"] + ); + if (argv["ai-search-options-retrieval-filters"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "filters"], + parseJsonMap( + argv["ai-search-options-retrieval-filters"], + "ai-search-options-retrieval-filters" + ) + ); + if (argv["ai-search-options-retrieval-fusion-method"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "fusion_method"], + argv["ai-search-options-retrieval-fusion-method"] + ); + if (argv["ai-search-options-retrieval-keyword-match-mode"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "keyword_match_mode"], + argv["ai-search-options-retrieval-keyword-match-mode"] + ); + if (argv["ai-search-options-retrieval-match-threshold"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "match_threshold"], + argv["ai-search-options-retrieval-match-threshold"] + ); + if (argv["ai-search-options-retrieval-max-num-results"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "max_num_results"], + argv["ai-search-options-retrieval-max-num-results"] + ); + if (argv["ai-search-options-retrieval-retrieval-type"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "retrieval_type"], + argv["ai-search-options-retrieval-retrieval-type"] + ); + if (argv["ai-search-options-retrieval-return-on-failure"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "return_on_failure"], + argv["ai-search-options-retrieval-return-on-failure"] + ); + if (argv["messages"] !== undefined) + setNestedValue( + bodyData, + ["messages"], + parseObjectArray(argv["messages"], "messages") + ); + if (argv["model"] !== undefined) + setNestedValue( + bodyData, + ["model"], + resolveFileToken(argv["model"] as string | undefined, "model", "text") + ); + if (argv["stream"] !== undefined) + setNestedValue(bodyData, ["stream"], argv["stream"]); + const result = await withProgress(`Creating`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/chat/completions`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/chat-completions.ts b/packages/cli/src/commands/_generated/ai-search/chat-completions.ts index 10c3255b26..9022bc51e3 100644 --- a/packages/cli/src/commands/_generated/ai-search/chat-completions.ts +++ b/packages/cli/src/commands/_generated/ai-search/chat-completions.ts @@ -1,509 +1,210 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * chat-completions command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { - compactBody, - parseBody, - parseJsonMap, - parseObjectArray, - setNestedValue, -} from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search chat-completions \n\nPerforms a chat completion request against an AI Search instance, using indexed content as context for generating responses." - ) - .positional("instance-id", { - type: "string", - description: "AI Search instance ID.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("ai-search-options-cache-cache-threshold", { - type: "string", - description: "The ai_search_options.cache.cache_threshold field", + parse: String, + }, + "ai-search-options-cache-cache-threshold": { + kind: "parsed", + brief: "The ai_search_options.cache.cache_threshold field", + optional: true, choices: [ "super_strict_match", "close_enough", "flexible_friend", "anything_goes", ], - }) - .coerce("ai-search-options-cache-cache-threshold", (value) => - resolveFileToken(value, "ai-search-options-cache-cache-threshold", "text") - ) - .option("ai-search-options-cache-enabled", { - type: "boolean", - description: "The ai_search_options.cache.enabled field", - }) - .option("ai-search-options-custom-metadata", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "ai-search-options-cache-cache-threshold", + "text" + ), + }, + "ai-search-options-cache-enabled": { + kind: "boolean", + brief: "The ai_search_options.cache.enabled field", + optional: true, + }, + "ai-search-options-custom-metadata": { + kind: "parsed", + brief: "Metadata added to AI Gateway logs for requests this operation triggers. Accepts up to 2 string, number, or boolean entries. Reserved keys: 'ai-search', 'task', 'origin', and any key beginning with 'cf.'. Provide as a JSON object or @path/to/file.json. Shape: {\"\": (string | number | boolean)}.", - }) - .option("ai-search-options-query-rewrite-enabled", { - type: "boolean", - description: "The ai_search_options.query_rewrite.enabled field", - }) - .option("ai-search-options-query-rewrite-model", { - type: "string", - description: + optional: true, + parse: String, + }, + "ai-search-options-query-rewrite-enabled": { + kind: "boolean", + brief: "The ai_search_options.query_rewrite.enabled field", + optional: true, + }, + "ai-search-options-query-rewrite-model": { + kind: "parsed", + brief: "A Workers AI model ID or an AI Gateway model ID compatible with the OpenAI Chat Completions API. An empty string uses the configured or default model.", - }) - .option("ai-search-options-query-rewrite-rewrite-prompt", { - type: "string", - description: "The ai_search_options.query_rewrite.rewrite_prompt field", - }) - .option("ai-search-options-reranking-enabled", { - type: "boolean", - description: "The ai_search_options.reranking.enabled field", - }) - .option("ai-search-options-reranking-match-threshold", { - type: "number", - description: + optional: true, + parse: String, + }, + "ai-search-options-query-rewrite-rewrite-prompt": { + kind: "parsed", + brief: "The ai_search_options.query_rewrite.rewrite_prompt field", + optional: true, + parse: String, + }, + "ai-search-options-reranking-enabled": { + kind: "boolean", + brief: "The ai_search_options.reranking.enabled field", + optional: true, + }, + "ai-search-options-reranking-match-threshold": { + kind: "parsed", + brief: "Minimum reranker relevance score a chunk must reach to be returned. When omitted, falls back to the instance-level score_threshold, then to 0.4.", - }) - .option("ai-search-options-reranking-model", { - type: "string", - description: "The ai_search_options.reranking.model field", - }) - .option("ai-search-options-retrieval-boost-by", { - type: "string", - description: + optional: true, + parse: Number, + }, + "ai-search-options-reranking-model": { + kind: "parsed", + brief: "The ai_search_options.reranking.model field", + optional: true, + parse: String, + }, + "ai-search-options-retrieval-boost-by": { + kind: "parsed", + brief: 'Metadata fields to boost search results by. Overrides the instance-level boost_by config. Direction defaults to \'asc\' for numeric/datetime fields, \'exists\' for text/boolean fields. Fields must match \'timestamp\' or a defined custom_metadata field. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"field": string, "direction"?: "asc" | "desc" | "exists" | ...more}]. ? marks optional keys.', - }) - .option("ai-search-options-retrieval-context-expansion", { - type: "number", - description: "The ai_search_options.retrieval.context_expansion field", - }) - .option("ai-search-options-retrieval-filters", { - type: "string", - description: + optional: true, + parse: String, + }, + "ai-search-options-retrieval-context-expansion": { + kind: "parsed", + brief: "The ai_search_options.retrieval.context_expansion field", + optional: true, + parse: Number, + }, + "ai-search-options-retrieval-filters": { + kind: "parsed", + brief: 'The ai_search_options.retrieval.filters field. Provide as a JSON object or @path/to/file.json. Shape: {"": unknown}.', - }) - .option("ai-search-options-retrieval-fusion-method", { - type: "string", - description: "The ai_search_options.retrieval.fusion_method field", + optional: true, + parse: String, + }, + "ai-search-options-retrieval-fusion-method": { + kind: "parsed", + brief: "The ai_search_options.retrieval.fusion_method field", + optional: true, choices: ["max", "rrf"], - }) - .coerce("ai-search-options-retrieval-fusion-method", (value) => - resolveFileToken( - value, - "ai-search-options-retrieval-fusion-method", - "text" - ) - ) - .option("ai-search-options-retrieval-keyword-match-mode", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "ai-search-options-retrieval-fusion-method", + "text" + ), + }, + "ai-search-options-retrieval-keyword-match-mode": { + kind: "parsed", + brief: "Controls which documents become candidates for BM25 scoring. 'and' restricts candidates to documents containing all query terms; 'or' includes any document containing at least one term and ranks results according to BM25 relevance. When omitted, falls back to the instance-level retrieval_options.keyword_match_mode, then to 'and'.", + optional: true, choices: ["and", "or"], - }) - .coerce("ai-search-options-retrieval-keyword-match-mode", (value) => - resolveFileToken( - value, - "ai-search-options-retrieval-keyword-match-mode", - "text" - ) - ) - .option("ai-search-options-retrieval-match-threshold", { - type: "number", - description: + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "ai-search-options-retrieval-keyword-match-mode", + "text" + ), + }, + "ai-search-options-retrieval-match-threshold": { + kind: "parsed", + brief: "Minimum similarity score a chunk must reach to be returned. When omitted, falls back to the instance-level score_threshold, then to 0.4.", - }) - .option("ai-search-options-retrieval-max-num-results", { - type: "number", - description: + optional: true, + parse: Number, + }, + "ai-search-options-retrieval-max-num-results": { + kind: "parsed", + brief: "Maximum number of results to return. When omitted, falls back to the instance-level max_num_results, then to 10.", - }) - .option("ai-search-options-retrieval-retrieval-type", { - type: "string", - description: "The ai_search_options.retrieval.retrieval_type field", + optional: true, + parse: Number, + }, + "ai-search-options-retrieval-retrieval-type": { + kind: "parsed", + brief: "The ai_search_options.retrieval.retrieval_type field", + optional: true, choices: ["vector", "keyword", "hybrid"], - }) - .coerce("ai-search-options-retrieval-retrieval-type", (value) => - resolveFileToken( - value, - "ai-search-options-retrieval-retrieval-type", - "text" - ) - ) - .option("ai-search-options-retrieval-return-on-failure", { - type: "boolean", - description: "The ai_search_options.retrieval.return_on_failure field", - }) - .option("messages", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "ai-search-options-retrieval-retrieval-type", + "text" + ), + }, + "ai-search-options-retrieval-return-on-failure": { + kind: "boolean", + brief: "The ai_search_options.retrieval.return_on_failure field", + optional: true, + }, + messages: { + kind: "parsed", + brief: 'The messages field. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"content": (string | [{...}] | null), "role": "system" | "developer" | "user" | ...more, "": unknown}].', - }) - .option("model", { - type: "string", - description: + optional: true, + parse: String, + }, + model: { + kind: "parsed", + brief: "A Workers AI model ID or an AI Gateway model ID compatible with the OpenAI Chat Completions API. An empty string uses the configured or default model.", - }) - .option("stream", { type: "boolean", description: "The stream field" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + stream: { kind: "boolean", brief: "The stream field", optional: true }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "instance-id", + brief: "AI Search instance ID.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "chat-completions ", describe: "Chat Completions", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search chat-completions", - classification: { - safeFlags: [ - "ai-search-options-cache-cache-threshold", - "ai-search-options-cache-enabled", - "ai-search-options-query-rewrite-enabled", - "ai-search-options-reranking-enabled", - "ai-search-options-retrieval-fusion-method", - "ai-search-options-retrieval-keyword-match-mode", - "ai-search-options-retrieval-retrieval-type", - "ai-search-options-retrieval-return-on-failure", - "stream", - "dry-run", - ], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["messages"] === undefined) { - throw new Error( - "--messages is required (or pass --body with this field set)." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search chat-completions", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/chat/completions`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - "instance-id": String(argv["instance-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody( - { - ai_search_options: { - cache: { - cache_threshold: - argv["ai-search-options-cache-cache-threshold"], - enabled: argv["ai-search-options-cache-enabled"], - }, - custom_metadata: parseJsonMap( - argv["ai-search-options-custom-metadata"], - "ai-search-options-custom-metadata" - ), - query_rewrite: { - enabled: - argv["ai-search-options-query-rewrite-enabled"], - model: resolveFileToken( - argv["ai-search-options-query-rewrite-model"] as - | string - | undefined, - "ai-search-options-query-rewrite-model", - "text" - ), - rewrite_prompt: resolveFileToken( - argv[ - "ai-search-options-query-rewrite-rewrite-prompt" - ] as string | undefined, - "ai-search-options-query-rewrite-rewrite-prompt", - "text" - ), - }, - reranking: { - enabled: argv["ai-search-options-reranking-enabled"], - match_threshold: - argv["ai-search-options-reranking-match-threshold"], - model: resolveFileToken( - argv["ai-search-options-reranking-model"] as - | string - | undefined, - "ai-search-options-reranking-model", - "text" - ), - }, - retrieval: { - boost_by: parseObjectArray( - argv["ai-search-options-retrieval-boost-by"], - "ai-search-options-retrieval-boost-by" - ), - context_expansion: - argv[ - "ai-search-options-retrieval-context-expansion" - ], - filters: parseJsonMap( - argv["ai-search-options-retrieval-filters"], - "ai-search-options-retrieval-filters" - ), - fusion_method: - argv["ai-search-options-retrieval-fusion-method"], - keyword_match_mode: - argv[ - "ai-search-options-retrieval-keyword-match-mode" - ], - match_threshold: - argv["ai-search-options-retrieval-match-threshold"], - max_num_results: - argv["ai-search-options-retrieval-max-num-results"], - retrieval_type: - argv["ai-search-options-retrieval-retrieval-type"], - return_on_failure: - argv[ - "ai-search-options-retrieval-return-on-failure" - ], - }, - }, - messages: parseObjectArray(argv["messages"], "messages"), - model: resolveFileToken( - argv["model"] as string | undefined, - "model", - "text" - ), - stream: argv["stream"], - }, - [ - ["ai_search_options", "custom_metadata"], - ["ai_search_options", "retrieval", "filters"], - ] - ), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/chat/completions`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData: Record = {}; - if (argv["ai-search-options-cache-cache-threshold"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "cache", "cache_threshold"], - argv["ai-search-options-cache-cache-threshold"] - ); - if (argv["ai-search-options-cache-enabled"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "cache", "enabled"], - argv["ai-search-options-cache-enabled"] - ); - if (argv["ai-search-options-custom-metadata"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "custom_metadata"], - parseJsonMap( - argv["ai-search-options-custom-metadata"], - "ai-search-options-custom-metadata" - ) - ); - if (argv["ai-search-options-query-rewrite-enabled"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "query_rewrite", "enabled"], - argv["ai-search-options-query-rewrite-enabled"] - ); - if (argv["ai-search-options-query-rewrite-model"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "query_rewrite", "model"], - resolveFileToken( - argv["ai-search-options-query-rewrite-model"] as - | string - | undefined, - "ai-search-options-query-rewrite-model", - "text" - ) - ); - if ( - argv["ai-search-options-query-rewrite-rewrite-prompt"] !== undefined - ) - setNestedValue( - bodyData, - ["ai_search_options", "query_rewrite", "rewrite_prompt"], - resolveFileToken( - argv["ai-search-options-query-rewrite-rewrite-prompt"] as - | string - | undefined, - "ai-search-options-query-rewrite-rewrite-prompt", - "text" - ) - ); - if (argv["ai-search-options-reranking-enabled"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "reranking", "enabled"], - argv["ai-search-options-reranking-enabled"] - ); - if (argv["ai-search-options-reranking-match-threshold"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "reranking", "match_threshold"], - argv["ai-search-options-reranking-match-threshold"] - ); - if (argv["ai-search-options-reranking-model"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "reranking", "model"], - resolveFileToken( - argv["ai-search-options-reranking-model"] as string | undefined, - "ai-search-options-reranking-model", - "text" - ) - ); - if (argv["ai-search-options-retrieval-boost-by"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "boost_by"], - parseObjectArray( - argv["ai-search-options-retrieval-boost-by"], - "ai-search-options-retrieval-boost-by" - ) - ); - if (argv["ai-search-options-retrieval-context-expansion"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "context_expansion"], - argv["ai-search-options-retrieval-context-expansion"] - ); - if (argv["ai-search-options-retrieval-filters"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "filters"], - parseJsonMap( - argv["ai-search-options-retrieval-filters"], - "ai-search-options-retrieval-filters" - ) - ); - if (argv["ai-search-options-retrieval-fusion-method"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "fusion_method"], - argv["ai-search-options-retrieval-fusion-method"] - ); - if ( - argv["ai-search-options-retrieval-keyword-match-mode"] !== undefined - ) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "keyword_match_mode"], - argv["ai-search-options-retrieval-keyword-match-mode"] - ); - if (argv["ai-search-options-retrieval-match-threshold"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "match_threshold"], - argv["ai-search-options-retrieval-match-threshold"] - ); - if (argv["ai-search-options-retrieval-max-num-results"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "max_num_results"], - argv["ai-search-options-retrieval-max-num-results"] - ); - if (argv["ai-search-options-retrieval-retrieval-type"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "retrieval_type"], - argv["ai-search-options-retrieval-retrieval-type"] - ); - if (argv["ai-search-options-retrieval-return-on-failure"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "return_on_failure"], - argv["ai-search-options-retrieval-return-on-failure"] - ); - if (argv["messages"] !== undefined) - setNestedValue( - bodyData, - ["messages"], - parseObjectArray(argv["messages"], "messages") - ); - if (argv["model"] !== undefined) - setNestedValue( - bodyData, - ["model"], - resolveFileToken( - argv["model"] as string | undefined, - "model", - "text" - ) - ); - if (argv["stream"] !== undefined) - setNestedValue(bodyData, ["stream"], argv["stream"]); - const result = await withProgress(`Creating`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/chat/completions`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 ai-search chat-completions \n\nPerforms a chat completion request against an AI Search instance, using indexed content as context for generating responses.", + ...parameters, + loader: () => import("./chat-completions.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/create.handler.ts b/packages/cli/src/commands/_generated/ai-search/create.handler.ts new file mode 100644 index 0000000000..32732adbc0 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/create.handler.ts @@ -0,0 +1,528 @@ +import operation from "../_operations/ai-search/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { + compactBody, + mergeBodyPositionals, + parseBody, + parseJsonMap, + parseObjectArray, +} from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search create", + classification: { + safeFlags: [ + "cache", + "cache-threshold", + "chunk", + "fusion-method", + "hybrid-search-enabled", + "index-method-keyword", + "index-method-vector", + "indexing-options-file-summary", + "indexing-options-keyword-tokenizer", + "indexing-options-use-ocr", + "metadata-created-from-aisearch-wizard", + "metadata-created-from-emdash-plugin-type", + "public-endpoint-params-chat-completions-endpoint-disabled", + "public-endpoint-params-default-domain-enabled", + "public-endpoint-params-enabled", + "public-endpoint-params-mcp-disabled", + "public-endpoint-params-rate-limit-technique", + "public-endpoint-params-search-endpoint-disabled", + "reranking", + "retrieval-options-keyword-match-mode", + "rewrite-query", + "source-params-d1-template", + "source-params-web-crawler-discover-options-include-external-links", + "source-params-web-crawler-discover-options-include-subdomains", + "source-params-web-crawler-discover-options-source", + "source-params-web-crawler-parse-options-include-images", + "source-params-web-crawler-parse-options-use-browser-rendering", + "source-params-web-crawler-parse-type", + "type", + "dry-run", + ], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances`, + pathParams: { namespace: String(argv["namespace"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? mergeBodyPositionals(parseBody(argv.body), [ + { name: "id", field: "id", value: argv["id"] }, + ]) + : compactBody( + { + ai_gateway_id: resolveFileToken( + argv["ai-gateway-id"] as string | undefined, + "ai-gateway-id", + "text" + ), + ai_search_model: resolveFileToken( + argv["ai-search-model"] as string | undefined, + "ai-search-model", + "text" + ), + cache: argv["cache"], + cache_threshold: argv["cache-threshold"], + cache_ttl: argv["cache-ttl"], + chunk: argv["chunk"], + chunk_overlap: argv["chunk-overlap"], + chunk_size: argv["chunk-size"], + custom_metadata: parseObjectArray( + argv["custom-metadata"], + "custom-metadata" + ), + embedding_model: resolveFileToken( + argv["embedding-model"] as string | undefined, + "embedding-model", + "text" + ), + fusion_method: argv["fusion-method"], + hybrid_search_enabled: argv["hybrid-search-enabled"], + index_method: { + keyword: argv["index-method-keyword"], + vector: argv["index-method-vector"], + }, + indexing_options: { + file_summary: argv["indexing-options-file-summary"], + keyword_tokenizer: + argv["indexing-options-keyword-tokenizer"], + use_ocr: argv["indexing-options-use-ocr"], + }, + max_num_results: argv["max-num-results"], + metadata: { + created_from_aisearch_wizard: + argv["metadata-created-from-aisearch-wizard"], + created_from_emdash_plugin: { + type: argv["metadata-created-from-emdash-plugin-type"], + version: resolveFileToken( + argv[ + "metadata-created-from-emdash-plugin-version" + ] as string | undefined, + "metadata-created-from-emdash-plugin-version", + "text" + ), + }, + worker_domain: resolveFileToken( + argv["metadata-worker-domain"] as string | undefined, + "metadata-worker-domain", + "text" + ), + }, + public_endpoint_params: { + authorized_hosts: + argv["public-endpoint-params-authorized-hosts"], + chat_completions_endpoint: { + disabled: + argv[ + "public-endpoint-params-chat-completions-endpoint-disabled" + ], + }, + custom_domains: + argv["public-endpoint-params-custom-domains"], + default_domain_enabled: + argv["public-endpoint-params-default-domain-enabled"], + enabled: argv["public-endpoint-params-enabled"], + mcp: { + description: resolveFileToken( + argv["public-endpoint-params-mcp-description"] as + | string + | undefined, + "public-endpoint-params-mcp-description", + "text" + ), + disabled: argv["public-endpoint-params-mcp-disabled"], + }, + rate_limit: { + period_ms: + argv["public-endpoint-params-rate-limit-period-ms"], + requests: + argv["public-endpoint-params-rate-limit-requests"], + technique: + argv["public-endpoint-params-rate-limit-technique"], + }, + search_endpoint: { + disabled: + argv[ + "public-endpoint-params-search-endpoint-disabled" + ], + }, + }, + reranking: argv["reranking"], + reranking_model: resolveFileToken( + argv["reranking-model"] as string | undefined, + "reranking-model", + "text" + ), + retrieval_options: { + boost_by: parseObjectArray( + argv["retrieval-options-boost-by"], + "retrieval-options-boost-by" + ), + keyword_match_mode: + argv["retrieval-options-keyword-match-mode"], + }, + rewrite_model: resolveFileToken( + argv["rewrite-model"] as string | undefined, + "rewrite-model", + "text" + ), + rewrite_query: argv["rewrite-query"], + score_threshold: argv["score-threshold"], + source: resolveFileToken( + argv["source"] as string | undefined, + "source", + "text" + ), + source_params: { + d1: { + query: resolveFileToken( + argv["source-params-d1-query"] as string | undefined, + "source-params-d1-query", + "text" + ), + template: argv["source-params-d1-template"], + }, + exclude_items: argv["source-params-exclude-items"], + include_items: argv["source-params-include-items"], + prefix: resolveFileToken( + argv["source-params-prefix"] as string | undefined, + "source-params-prefix", + "text" + ), + r2_jurisdiction: resolveFileToken( + argv["source-params-r2-jurisdiction"] as + | string + | undefined, + "source-params-r2-jurisdiction", + "text" + ), + web_crawler: { + discover_options: { + depth: + argv[ + "source-params-web-crawler-discover-options-depth" + ], + include_external_links: + argv[ + "source-params-web-crawler-discover-options-include-external-links" + ], + include_subdomains: + argv[ + "source-params-web-crawler-discover-options-include-subdomains" + ], + limit: + argv[ + "source-params-web-crawler-discover-options-limit" + ], + max_age: + argv[ + "source-params-web-crawler-discover-options-max-age" + ], + source: + argv[ + "source-params-web-crawler-discover-options-source" + ], + }, + parse_options: { + content_selector: parseObjectArray( + argv[ + "source-params-web-crawler-parse-options-content-selector" + ], + "source-params-web-crawler-parse-options-content-selector" + ), + include_headers: parseJsonMap( + argv[ + "source-params-web-crawler-parse-options-include-headers" + ], + "source-params-web-crawler-parse-options-include-headers" + ), + include_images: + argv[ + "source-params-web-crawler-parse-options-include-images" + ], + specific_sitemaps: + argv[ + "source-params-web-crawler-parse-options-specific-sitemaps" + ], + use_browser_rendering: + argv[ + "source-params-web-crawler-parse-options-use-browser-rendering" + ], + }, + parse_type: + argv["source-params-web-crawler-parse-type"], + }, + }, + sync_interval: argv["sync-interval"], + token_id: resolveFileToken( + argv["token-id"] as string | undefined, + "token-id", + "text" + ), + type: argv["type"], + id: argv["id"], + }, + [ + [ + "source_params", + "web_crawler", + "parse_options", + "include_headers", + ], + ] + ), + }); + return; + } + const parsedBody = + argv.body !== undefined + ? mergeBodyPositionals(parseBody(argv.body), [ + { name: "id", field: "id", value: argv["id"] }, + ]) + : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + namespace: argv["namespace"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody( + { + ai_gateway_id: resolveFileToken( + argv["ai-gateway-id"] as string | undefined, + "ai-gateway-id", + "text" + ), + ai_search_model: resolveFileToken( + argv["ai-search-model"] as string | undefined, + "ai-search-model", + "text" + ), + cache: argv["cache"], + cache_threshold: argv["cache-threshold"], + cache_ttl: argv["cache-ttl"], + chunk: argv["chunk"], + chunk_overlap: argv["chunk-overlap"], + chunk_size: argv["chunk-size"], + custom_metadata: parseObjectArray( + argv["custom-metadata"], + "custom-metadata" + ), + embedding_model: resolveFileToken( + argv["embedding-model"] as string | undefined, + "embedding-model", + "text" + ), + fusion_method: argv["fusion-method"], + hybrid_search_enabled: argv["hybrid-search-enabled"], + index_method: { + keyword: argv["index-method-keyword"], + vector: argv["index-method-vector"], + }, + indexing_options: { + file_summary: argv["indexing-options-file-summary"], + keyword_tokenizer: argv["indexing-options-keyword-tokenizer"], + use_ocr: argv["indexing-options-use-ocr"], + }, + max_num_results: argv["max-num-results"], + metadata: { + created_from_aisearch_wizard: + argv["metadata-created-from-aisearch-wizard"], + created_from_emdash_plugin: { + type: argv["metadata-created-from-emdash-plugin-type"], + version: resolveFileToken( + argv["metadata-created-from-emdash-plugin-version"] as + | string + | undefined, + "metadata-created-from-emdash-plugin-version", + "text" + ), + }, + worker_domain: resolveFileToken( + argv["metadata-worker-domain"] as string | undefined, + "metadata-worker-domain", + "text" + ), + }, + public_endpoint_params: { + authorized_hosts: argv["public-endpoint-params-authorized-hosts"], + chat_completions_endpoint: { + disabled: + argv[ + "public-endpoint-params-chat-completions-endpoint-disabled" + ], + }, + custom_domains: argv["public-endpoint-params-custom-domains"], + default_domain_enabled: + argv["public-endpoint-params-default-domain-enabled"], + enabled: argv["public-endpoint-params-enabled"], + mcp: { + description: resolveFileToken( + argv["public-endpoint-params-mcp-description"] as + | string + | undefined, + "public-endpoint-params-mcp-description", + "text" + ), + disabled: argv["public-endpoint-params-mcp-disabled"], + }, + rate_limit: { + period_ms: argv["public-endpoint-params-rate-limit-period-ms"], + requests: argv["public-endpoint-params-rate-limit-requests"], + technique: argv["public-endpoint-params-rate-limit-technique"], + }, + search_endpoint: { + disabled: argv["public-endpoint-params-search-endpoint-disabled"], + }, + }, + reranking: argv["reranking"], + reranking_model: resolveFileToken( + argv["reranking-model"] as string | undefined, + "reranking-model", + "text" + ), + retrieval_options: { + boost_by: parseObjectArray( + argv["retrieval-options-boost-by"], + "retrieval-options-boost-by" + ), + keyword_match_mode: argv["retrieval-options-keyword-match-mode"], + }, + rewrite_model: resolveFileToken( + argv["rewrite-model"] as string | undefined, + "rewrite-model", + "text" + ), + rewrite_query: argv["rewrite-query"], + score_threshold: argv["score-threshold"], + source: resolveFileToken( + argv["source"] as string | undefined, + "source", + "text" + ), + source_params: { + d1: { + query: resolveFileToken( + argv["source-params-d1-query"] as string | undefined, + "source-params-d1-query", + "text" + ), + template: argv["source-params-d1-template"], + }, + exclude_items: argv["source-params-exclude-items"], + include_items: argv["source-params-include-items"], + prefix: resolveFileToken( + argv["source-params-prefix"] as string | undefined, + "source-params-prefix", + "text" + ), + r2_jurisdiction: resolveFileToken( + argv["source-params-r2-jurisdiction"] as string | undefined, + "source-params-r2-jurisdiction", + "text" + ), + web_crawler: { + discover_options: { + depth: argv["source-params-web-crawler-discover-options-depth"], + include_external_links: + argv[ + "source-params-web-crawler-discover-options-include-external-links" + ], + include_subdomains: + argv[ + "source-params-web-crawler-discover-options-include-subdomains" + ], + limit: argv["source-params-web-crawler-discover-options-limit"], + max_age: + argv["source-params-web-crawler-discover-options-max-age"], + source: + argv["source-params-web-crawler-discover-options-source"], + }, + parse_options: { + content_selector: parseObjectArray( + argv[ + "source-params-web-crawler-parse-options-content-selector" + ], + "source-params-web-crawler-parse-options-content-selector" + ), + include_headers: parseJsonMap( + argv[ + "source-params-web-crawler-parse-options-include-headers" + ], + "source-params-web-crawler-parse-options-include-headers" + ), + include_images: + argv[ + "source-params-web-crawler-parse-options-include-images" + ], + specific_sitemaps: + argv[ + "source-params-web-crawler-parse-options-specific-sitemaps" + ], + use_browser_rendering: + argv[ + "source-params-web-crawler-parse-options-use-browser-rendering" + ], + }, + parse_type: argv["source-params-web-crawler-parse-type"], + }, + }, + sync_interval: argv["sync-interval"], + token_id: resolveFileToken( + argv["token-id"] as string | undefined, + "token-id", + "text" + ), + type: argv["type"], + id: argv["id"], + }, + [["source_params", "web_crawler", "parse_options", "include_headers"]] + ); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + namespace: argv["namespace"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/create.ts b/packages/cli/src/commands/_generated/ai-search/create.ts index e53e46caa6..c459174c76 100644 --- a/packages/cli/src/commands/_generated/ai-search/create.ts +++ b/packages/cli/src/commands/_generated/ai-search/create.ts @@ -1,400 +1,465 @@ -import operation from "../_operations/ai-search/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { - compactBody, - mergeBodyPositionals, - parseBody, - parseJsonMap, - parseObjectArray, -} from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search create \n\nCreate a new AI Search instance with the given configuration. If type is omitted or null, a non-blank HTTP(S) source infers web-crawler and any other source infers r2; r2 sources must name an existing bucket. A missing or blank source without a type creates a managed upload-only instance." - ) - .positional("id", { - type: "string", - description: "Unique ID for the new AI Search instance.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("ai-gateway-id", { - type: "string", - description: "The ai_gateway_id field", - }) - .option("ai-search-model", { - type: "string", - description: + parse: String, + }, + "ai-gateway-id": { + kind: "parsed", + brief: "The ai_gateway_id field", + optional: true, + parse: String, + }, + "ai-search-model": { + kind: "parsed", + brief: "A Workers AI model ID or an AI Gateway model ID compatible with the OpenAI Chat Completions API. An empty string uses the configured or default model.", - }) - .option("cache", { - type: "boolean", - description: "The cache field", - default: true, - }) - .option("cache-threshold", { - type: "string", - description: "The cache_threshold field", + optional: true, + parse: String, + }, + cache: { kind: "boolean", brief: "The cache field", default: true }, + "cache-threshold": { + kind: "parsed", + brief: "The cache_threshold field", + default: "close_enough", choices: [ "super_strict_match", "close_enough", "flexible_friend", "anything_goes", ], - default: "close_enough", - }) - .coerce("cache-threshold", (value) => - resolveFileToken(value, "cache-threshold", "text") - ) - .option("cache-ttl", { - type: "number", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "cache-threshold", "text"), + }, + "cache-ttl": { + kind: "parsed", + brief: "Cache entry TTL in seconds. Allowed values: 600 (10min), 1800 (30min), 3600 (1h), 7200 (2h), 21600 (6h), 43200 (12h), 86400 (24h), 172800 (48h), 259200 (72h), 518400 (6d).", - default: 172800, - }) - .option("chunk", { - type: "boolean", - description: "The chunk field", - default: true, - }) - .option("chunk-overlap", { - type: "number", - description: "The chunk_overlap field", - default: 10, - }) - .option("chunk-size", { - type: "number", - description: "The chunk_size field", - }) - .option("custom-metadata", { - type: "string", - description: + default: "172800", + parse: Number, + }, + chunk: { kind: "boolean", brief: "The chunk field", default: true }, + "chunk-overlap": { + kind: "parsed", + brief: "The chunk_overlap field", + default: "10", + parse: Number, + }, + "chunk-size": { + kind: "parsed", + brief: "The chunk_size field", + optional: true, + parse: Number, + }, + "custom-metadata": { + kind: "parsed", + brief: 'The custom_metadata field. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"data_type": "text" | "number" | "boolean" | ...more, "field_name": string}].', - }) - .option("embedding-model", { - type: "string", - description: "The embedding_model field", - }) - .option("fusion-method", { - type: "string", - description: "The fusion_method field", - choices: ["max", "rrf"], + optional: true, + parse: String, + }, + "embedding-model": { + kind: "parsed", + brief: "The embedding_model field", + optional: true, + parse: String, + }, + "fusion-method": { + kind: "parsed", + brief: "The fusion_method field", default: "rrf", - }) - .coerce("fusion-method", (value) => - resolveFileToken(value, "fusion-method", "text") - ) - .option("hybrid-search-enabled", { - type: "boolean", - description: + choices: ["max", "rrf"], + parse: String, + coerce: (value: string) => + resolveFileToken(value, "fusion-method", "text"), + }, + "hybrid-search-enabled": { + kind: "boolean", + brief: "Deprecated — use index_method instead. Defaults to true for new instances; set false to create a vector-only instance.", - }) - .option("index-method-keyword", { - type: "boolean", - description: "Enable keyword (BM25) storage backend.", - }) - .option("index-method-vector", { - type: "boolean", - description: "Enable vector (embedding) storage backend.", - }) - .option("indexing-options-file-summary", { - type: "boolean", - description: + optional: true, + }, + "index-method-keyword": { + kind: "boolean", + brief: "Enable keyword (BM25) storage backend.", + optional: true, + }, + "index-method-vector": { + kind: "boolean", + brief: "Enable vector (embedding) storage backend.", + optional: true, + }, + "indexing-options-file-summary": { + kind: "boolean", + brief: "Generates a per-file summary, topics, and keywords during indexing for text files and media transcripts of at least three chunks. The summary and keywords are stored as the item's context metadata (a context you set is kept), and the topics are added to chunk context headers where they fit. Best effort: a file whose summary fails is indexed without one. The model calls are billed to your account through the instance's AI Gateway. Changing this triggers a full re-index. Defaults to false.", - }) - .option("indexing-options-keyword-tokenizer", { - type: "string", - description: + optional: true, + }, + "indexing-options-keyword-tokenizer": { + kind: "parsed", + brief: "Tokenizer used for keyword search indexing. porter provides word-level tokenization with Porter stemming (good for natural language queries). trigram enables character-level substring matching (good for partial matches, code, identifiers). Changing this triggers a full re-index. Defaults to porter.", + optional: true, choices: ["porter", "trigram"], - }) - .coerce("indexing-options-keyword-tokenizer", (value) => - resolveFileToken(value, "indexing-options-keyword-tokenizer", "text") - ) - .option("indexing-options-use-ocr", { - type: "boolean", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "indexing-options-keyword-tokenizer", "text"), + }, + "indexing-options-use-ocr": { + kind: "boolean", + brief: "Enables OCR ingestion for PDFs and images. Changing this triggers a full re-index. Defaults to false.", - }) - .option("max-num-results", { - type: "number", - description: "The max_num_results field", - default: 10, - }) - .option("metadata-created-from-aisearch-wizard", { - type: "boolean", - description: "The metadata.created_from_aisearch_wizard field", - }) - .option("metadata-created-from-emdash-plugin-type", { - type: "string", - description: "The metadata.created_from_emdash_plugin.type field", + optional: true, + }, + "max-num-results": { + kind: "parsed", + brief: "The max_num_results field", + default: "10", + parse: Number, + }, + "metadata-created-from-aisearch-wizard": { + kind: "boolean", + brief: "The metadata.created_from_aisearch_wizard field", + optional: true, + }, + "metadata-created-from-emdash-plugin-type": { + kind: "parsed", + brief: "The metadata.created_from_emdash_plugin.type field", + optional: true, choices: ["native", "rest"], - }) - .coerce("metadata-created-from-emdash-plugin-type", (value) => - resolveFileToken( - value, - "metadata-created-from-emdash-plugin-type", - "text" - ) - ) - .option("metadata-created-from-emdash-plugin-version", { - type: "string", - description: "The metadata.created_from_emdash_plugin.version field", - }) - .option("metadata-worker-domain", { - type: "string", - description: "The metadata.worker_domain field", - }) - .option("public-endpoint-params-authorized-hosts", { - type: "string", - array: true, - description: "The public_endpoint_params.authorized_hosts field", - }) - .option("public-endpoint-params-chat-completions-endpoint-disabled", { - type: "boolean", - description: - "Disable chat completions endpoint for this public endpoint.", - }) - .option("public-endpoint-params-custom-domains", { - type: "string", - array: true, - description: + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "metadata-created-from-emdash-plugin-type", + "text" + ), + }, + "metadata-created-from-emdash-plugin-version": { + kind: "parsed", + brief: "The metadata.created_from_emdash_plugin.version field", + optional: true, + parse: String, + }, + "metadata-worker-domain": { + kind: "parsed", + brief: "The metadata.worker_domain field", + optional: true, + parse: String, + }, + "public-endpoint-params-authorized-hosts": { + kind: "parsed", + brief: "The public_endpoint_params.authorized_hosts field", + variadic: true, + optional: true, + parse: String, + }, + "public-endpoint-params-chat-completions-endpoint-disabled": { + kind: "boolean", + brief: "Disable chat completions endpoint for this public endpoint.", + optional: true, + }, + "public-endpoint-params-custom-domains": { + kind: "parsed", + brief: "Custom domain hostnames that alias this public endpoint. GET and create responses return the current set; on update (PUT) this field is only echoed back when supplied in the request body, otherwise it is null (omit it to leave domains unchanged).", - }) - .option("public-endpoint-params-default-domain-enabled", { - type: "boolean", - description: + variadic: true, + optional: true, + parse: String, + }, + "public-endpoint-params-default-domain-enabled": { + kind: "boolean", + brief: "When false, the instance is reachable only via a registered custom domain and the default .search.ai.cloudflare.com host returns 404. Requires at least one custom domain. Defaults to true. public_endpoint_params is replaced wholesale on update, so resend default_domain_enabled on every update to keep the default host off — omitting it resets to true.", - }) - .option("public-endpoint-params-enabled", { - type: "boolean", - description: "The public_endpoint_params.enabled field", - }) - .option("public-endpoint-params-mcp-description", { - type: "string", - description: "The public_endpoint_params.mcp.description field", - }) - .option("public-endpoint-params-mcp-disabled", { - type: "boolean", - description: "Disable MCP endpoint for this public endpoint.", - }) - .option("public-endpoint-params-rate-limit-period-ms", { - type: "number", - description: "The public_endpoint_params.rate_limit.period_ms field", - }) - .option("public-endpoint-params-rate-limit-requests", { - type: "number", - description: "The public_endpoint_params.rate_limit.requests field", - }) - .option("public-endpoint-params-rate-limit-technique", { - type: "string", - description: "The public_endpoint_params.rate_limit.technique field", + optional: true, + }, + "public-endpoint-params-enabled": { + kind: "boolean", + brief: "The public_endpoint_params.enabled field", + optional: true, + }, + "public-endpoint-params-mcp-description": { + kind: "parsed", + brief: "The public_endpoint_params.mcp.description field", + optional: true, + parse: String, + }, + "public-endpoint-params-mcp-disabled": { + kind: "boolean", + brief: "Disable MCP endpoint for this public endpoint.", + optional: true, + }, + "public-endpoint-params-rate-limit-period-ms": { + kind: "parsed", + brief: "The public_endpoint_params.rate_limit.period_ms field", + optional: true, + parse: Number, + }, + "public-endpoint-params-rate-limit-requests": { + kind: "parsed", + brief: "The public_endpoint_params.rate_limit.requests field", + optional: true, + parse: Number, + }, + "public-endpoint-params-rate-limit-technique": { + kind: "parsed", + brief: "The public_endpoint_params.rate_limit.technique field", + optional: true, choices: ["fixed", "sliding"], - }) - .coerce("public-endpoint-params-rate-limit-technique", (value) => - resolveFileToken( - value, - "public-endpoint-params-rate-limit-technique", - "text" - ) - ) - .option("public-endpoint-params-search-endpoint-disabled", { - type: "boolean", - description: "Disable search endpoint for this public endpoint.", - }) - .option("reranking", { - type: "boolean", - description: "The reranking field", + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "public-endpoint-params-rate-limit-technique", + "text" + ), + }, + "public-endpoint-params-search-endpoint-disabled": { + kind: "boolean", + brief: "Disable search endpoint for this public endpoint.", + optional: true, + }, + reranking: { + kind: "boolean", + brief: "The reranking field", default: false, - }) - .option("reranking-model", { - type: "string", - description: "The reranking_model field", - }) - .option("retrieval-options-boost-by", { - type: "string", - description: + }, + "reranking-model": { + kind: "parsed", + brief: "The reranking_model field", + optional: true, + parse: String, + }, + "retrieval-options-boost-by": { + kind: "parsed", + brief: 'Metadata fields to boost search results by. Each entry specifies a metadata field and an optional direction. Direction defaults to \'asc\' for numeric/datetime fields and \'exists\' for text/boolean fields. Fields must match \'timestamp\' or a defined custom_metadata field. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"field": string, "direction"?: "asc" | "desc" | "exists" | ...more}]. ? marks optional keys.', - }) - .option("retrieval-options-keyword-match-mode", { - type: "string", - description: + optional: true, + parse: String, + }, + "retrieval-options-keyword-match-mode": { + kind: "parsed", + brief: "Controls which documents become candidates for BM25 scoring. 'and' restricts candidates to documents containing all query terms; 'or' includes any document containing at least one term and ranks results according to BM25 relevance. When omitted on an update, the existing stored value stays unchanged; when never set, search falls back to 'and'.", + optional: true, choices: ["and", "or"], - }) - .coerce("retrieval-options-keyword-match-mode", (value) => - resolveFileToken(value, "retrieval-options-keyword-match-mode", "text") - ) - .option("rewrite-model", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "retrieval-options-keyword-match-mode", "text"), + }, + "rewrite-model": { + kind: "parsed", + brief: "A Workers AI model ID or an AI Gateway model ID compatible with the OpenAI Chat Completions API. An empty string uses the configured or default model.", - }) - .option("rewrite-query", { - type: "boolean", - description: "The rewrite_query field", + optional: true, + parse: String, + }, + "rewrite-query": { + kind: "boolean", + brief: "The rewrite_query field", default: false, - }) - .option("score-threshold", { - type: "number", - description: + }, + "score-threshold": { + kind: "parsed", + brief: "Minimum similarity score a chunk must reach to be returned. Defaults to 0.4.", - }) - .option("source", { - type: "string", - description: + optional: true, + parse: Number, + }, + source: { + kind: "parsed", + brief: "R2 bucket name or HTTP(S) root website URL to index. When type is omitted, the source determines it.", - }) - .option("source-params-d1-query", { - type: "string", - description: + optional: true, + parse: String, + }, + "source-params-d1-query": { + kind: "parsed", + brief: "Read-only SELECT query run against the D1 database. It must return an `id` column that uniquely identifies each row. Columns named `title` and `content` set the document title and body, and up to 5 `meta_*` columns become filterable custom metadata; any other column is indexed as a labelled field. Every sync reads the full result, up to 100,000 rows, with the instance's token, and those reads count against your D1 usage. Leading and trailing whitespace is trimmed before the query is stored.", - }) - .option("source-params-d1-template", { - type: "string", - description: + optional: true, + parse: String, + }, + "source-params-d1-template": { + kind: "parsed", + brief: "How each row is rendered into the indexed document: labelled renders the title, the labelled fields, then the content; content_only renders the title and content (labelled fields only when there is no content); key_value renders every column as name: value; json renders every column as a JSON object.", + optional: true, choices: ["labelled", "content_only", "key_value", "json"], - }) - .coerce("source-params-d1-template", (value) => - resolveFileToken(value, "source-params-d1-template", "text") - ) - .option("source-params-exclude-items", { - type: "string", - array: true, - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "source-params-d1-template", "text"), + }, + "source-params-exclude-items": { + kind: "parsed", + brief: "List of path patterns to exclude. Uses micromatch glob syntax: * matches within a path segment, ** matches across path segments (e.g., /admin/** matches /admin/users and /admin/settings/advanced). Most accounts have a limit of 10 rules; contact support to raise it.", - }) - .option("source-params-include-items", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + "source-params-include-items": { + kind: "parsed", + brief: "List of path patterns to include. Uses micromatch glob syntax: * matches within a path segment, ** matches across path segments (e.g., /blog/** matches /blog/post and /blog/2024/post). Most accounts have a limit of 10 rules; contact support to raise it.", - }) - .option("source-params-prefix", { - type: "string", - description: "The source_params.prefix field", - }) - .option("source-params-r2-jurisdiction", { - type: "string", - description: "The source_params.r2_jurisdiction field", - }) - .option("source-params-web-crawler-discover-options-depth", { - type: "number", - description: "Maximum link-follow depth from the seed URL.", - }) - .option( - "source-params-web-crawler-discover-options-include-external-links", - { - type: "boolean", - description: - "Follow links that point outside the source domain. Must stay `false` because discover crawls only cover the zone you own.", - } - ) - .option("source-params-web-crawler-discover-options-include-subdomains", { - type: "boolean", - description: "Follow links to subdomains of the source host.", - }) - .option("source-params-web-crawler-discover-options-limit", { - type: "number", - description: "Maximum number of pages to crawl (1-100000).", - }) - .option("source-params-web-crawler-discover-options-max-age", { - type: "number", - description: "Maximum content age in seconds to accept (0–604800).", - }) - .option("source-params-web-crawler-discover-options-source", { - type: "string", - description: + variadic: true, + optional: true, + parse: String, + }, + "source-params-prefix": { + kind: "parsed", + brief: "The source_params.prefix field", + optional: true, + parse: String, + }, + "source-params-r2-jurisdiction": { + kind: "parsed", + brief: "The source_params.r2_jurisdiction field", + optional: true, + parse: String, + }, + "source-params-web-crawler-discover-options-depth": { + kind: "parsed", + brief: "Maximum link-follow depth from the seed URL.", + optional: true, + parse: Number, + }, + "source-params-web-crawler-discover-options-include-external-links": { + kind: "boolean", + brief: + "Follow links that point outside the source domain. Must stay `false` because discover crawls only cover the zone you own.", + optional: true, + }, + "source-params-web-crawler-discover-options-include-subdomains": { + kind: "boolean", + brief: "Follow links to subdomains of the source host.", + optional: true, + }, + "source-params-web-crawler-discover-options-limit": { + kind: "parsed", + brief: "Maximum number of pages to crawl (1-100000).", + optional: true, + parse: Number, + }, + "source-params-web-crawler-discover-options-max-age": { + kind: "parsed", + brief: "Maximum content age in seconds to accept (0–604800).", + optional: true, + parse: Number, + }, + "source-params-web-crawler-discover-options-source": { + kind: "parsed", + brief: "Where the crawler looks for URLs: 'sitemaps' reads sitemap XML only, 'links' follows page links only, 'all' does both.", + optional: true, choices: ["all", "sitemaps", "links"], - }) - .coerce("source-params-web-crawler-discover-options-source", (value) => - resolveFileToken( - value, - "source-params-web-crawler-discover-options-source", - "text" - ) - ) - .option("source-params-web-crawler-parse-options-content-selector", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "source-params-web-crawler-discover-options-source", + "text" + ), + }, + "source-params-web-crawler-parse-options-content-selector": { + kind: "parsed", + brief: 'List of path-to-selector mappings for extracting specific content from crawled pages. Each entry pairs a URL glob pattern with a CSS selector. The first matching path wins. The crawler stores and indexes only the matched HTML fragment. Omit the field to disable content selection; the API rejects empty arrays. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"path": string, "selector": string}].', - }) - .option("source-params-web-crawler-parse-options-include-headers", { - type: "string", - description: + optional: true, + parse: String, + }, + "source-params-web-crawler-parse-options-include-headers": { + kind: "parsed", + brief: 'Up to 5 custom HTTP headers sent with each crawl request. Names must use RFC-7230 token characters, excluding spaces, colons, and control characters. Values must use HTAB and printable ASCII only, excluding CR and LF. Provide as a JSON object or @path/to/file.json. Shape: {"": string}.', - }) - .option("source-params-web-crawler-parse-options-include-images", { - type: "boolean", - description: - "The source_params.web_crawler.parse_options.include_images field", - }) - .option("source-params-web-crawler-parse-options-specific-sitemaps", { - type: "string", - array: true, - description: + optional: true, + parse: String, + }, + "source-params-web-crawler-parse-options-include-images": { + kind: "boolean", + brief: "The source_params.web_crawler.parse_options.include_images field", + optional: true, + }, + "source-params-web-crawler-parse-options-specific-sitemaps": { + kind: "parsed", + brief: "List of specific sitemap URLs to use for crawling. Only valid when parse_type is 'sitemap'.", - }) - .option("source-params-web-crawler-parse-options-use-browser-rendering", { - type: "boolean", - description: + variadic: true, + optional: true, + parse: String, + }, + "source-params-web-crawler-parse-options-use-browser-rendering": { + kind: "boolean", + brief: "The source_params.web_crawler.parse_options.use_browser_rendering field", - }) - .option("source-params-web-crawler-parse-type", { - type: "string", - description: + optional: true, + }, + "source-params-web-crawler-parse-type": { + kind: "parsed", + brief: "How the crawler finds URLs. 'sitemap' reads XML sitemaps; 'discover' follows links recursively and requires the source to belong to a Verified zone on this account.", + optional: true, choices: ["sitemap", "discover"], - }) - .coerce("source-params-web-crawler-parse-type", (value) => - resolveFileToken(value, "source-params-web-crawler-parse-type", "text") - ) - .option("sync-interval", { - type: "number", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "source-params-web-crawler-parse-type", "text"), + }, + "sync-interval": { + kind: "parsed", + brief: "Interval between automatic syncs, in seconds. Allowed values: 900 (15min), 1800 (30min), 3600 (1h), 7200 (2h), 14400 (4h), 21600 (6h), 43200 (12h), 86400 (24h). Defaults to 86400 (24h).", - }) - .option("token-id", { type: "string", description: "The token_id field" }) - .option("type", { - type: "string", - description: "Data source type: r2 or web-crawler.", + optional: true, + parse: Number, + }, + "token-id": { + kind: "parsed", + brief: "The token_id field", + optional: true, + parse: String, + }, + type: { + kind: "parsed", + brief: "Data source type: r2 or web-crawler.", + optional: true, choices: ["r2", "web-crawler", "d1"], - }) - .coerce("type", (value) => resolveFileToken(value, "type", "text")) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => resolveFileToken(value, "type", "text"), + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }) - .check((argv) => { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "id", + brief: "Unique ID for the new AI Search instance.", + parse: String, + }, + ], + rules(rules) { + rules.check((argv) => { const groupSet = ["index-method-keyword", "index-method-vector"].some( (k) => argv[k] !== undefined ); @@ -409,8 +474,8 @@ function builder(yargs: Argv) { } } return true; - }) - .check((argv) => { + }); + rules.check((argv) => { const groupSet = [ "metadata-created-from-emdash-plugin-type", "metadata-created-from-emdash-plugin-version", @@ -427,8 +492,8 @@ function builder(yargs: Argv) { } } return true; - }) - .check((argv) => { + }); + rules.check((argv) => { const groupSet = [ "source-params-d1-query", "source-params-d1-template", @@ -445,526 +510,16 @@ function builder(yargs: Argv) { } return true; }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Create an AI Search instance.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search create", - classification: { - safeFlags: [ - "cache", - "cache-threshold", - "chunk", - "fusion-method", - "hybrid-search-enabled", - "index-method-keyword", - "index-method-vector", - "indexing-options-file-summary", - "indexing-options-keyword-tokenizer", - "indexing-options-use-ocr", - "metadata-created-from-aisearch-wizard", - "metadata-created-from-emdash-plugin-type", - "public-endpoint-params-chat-completions-endpoint-disabled", - "public-endpoint-params-default-domain-enabled", - "public-endpoint-params-enabled", - "public-endpoint-params-mcp-disabled", - "public-endpoint-params-rate-limit-technique", - "public-endpoint-params-search-endpoint-disabled", - "reranking", - "retrieval-options-keyword-match-mode", - "rewrite-query", - "source-params-d1-template", - "source-params-web-crawler-discover-options-include-external-links", - "source-params-web-crawler-discover-options-include-subdomains", - "source-params-web-crawler-discover-options-source", - "source-params-web-crawler-parse-options-include-images", - "source-params-web-crawler-parse-options-use-browser-rendering", - "source-params-web-crawler-parse-type", - "type", - "dry-run", - ], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances`, - pathParams: { namespace: String(argv["namespace"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? mergeBodyPositionals(parseBody(argv.body), [ - { name: "id", field: "id", value: argv["id"] }, - ]) - : compactBody( - { - ai_gateway_id: resolveFileToken( - argv["ai-gateway-id"] as string | undefined, - "ai-gateway-id", - "text" - ), - ai_search_model: resolveFileToken( - argv["ai-search-model"] as string | undefined, - "ai-search-model", - "text" - ), - cache: argv["cache"], - cache_threshold: argv["cache-threshold"], - cache_ttl: argv["cache-ttl"], - chunk: argv["chunk"], - chunk_overlap: argv["chunk-overlap"], - chunk_size: argv["chunk-size"], - custom_metadata: parseObjectArray( - argv["custom-metadata"], - "custom-metadata" - ), - embedding_model: resolveFileToken( - argv["embedding-model"] as string | undefined, - "embedding-model", - "text" - ), - fusion_method: argv["fusion-method"], - hybrid_search_enabled: argv["hybrid-search-enabled"], - index_method: { - keyword: argv["index-method-keyword"], - vector: argv["index-method-vector"], - }, - indexing_options: { - file_summary: argv["indexing-options-file-summary"], - keyword_tokenizer: - argv["indexing-options-keyword-tokenizer"], - use_ocr: argv["indexing-options-use-ocr"], - }, - max_num_results: argv["max-num-results"], - metadata: { - created_from_aisearch_wizard: - argv["metadata-created-from-aisearch-wizard"], - created_from_emdash_plugin: { - type: argv[ - "metadata-created-from-emdash-plugin-type" - ], - version: resolveFileToken( - argv[ - "metadata-created-from-emdash-plugin-version" - ] as string | undefined, - "metadata-created-from-emdash-plugin-version", - "text" - ), - }, - worker_domain: resolveFileToken( - argv["metadata-worker-domain"] as string | undefined, - "metadata-worker-domain", - "text" - ), - }, - public_endpoint_params: { - authorized_hosts: - argv["public-endpoint-params-authorized-hosts"], - chat_completions_endpoint: { - disabled: - argv[ - "public-endpoint-params-chat-completions-endpoint-disabled" - ], - }, - custom_domains: - argv["public-endpoint-params-custom-domains"], - default_domain_enabled: - argv["public-endpoint-params-default-domain-enabled"], - enabled: argv["public-endpoint-params-enabled"], - mcp: { - description: resolveFileToken( - argv["public-endpoint-params-mcp-description"] as - | string - | undefined, - "public-endpoint-params-mcp-description", - "text" - ), - disabled: argv["public-endpoint-params-mcp-disabled"], - }, - rate_limit: { - period_ms: - argv["public-endpoint-params-rate-limit-period-ms"], - requests: - argv["public-endpoint-params-rate-limit-requests"], - technique: - argv["public-endpoint-params-rate-limit-technique"], - }, - search_endpoint: { - disabled: - argv[ - "public-endpoint-params-search-endpoint-disabled" - ], - }, - }, - reranking: argv["reranking"], - reranking_model: resolveFileToken( - argv["reranking-model"] as string | undefined, - "reranking-model", - "text" - ), - retrieval_options: { - boost_by: parseObjectArray( - argv["retrieval-options-boost-by"], - "retrieval-options-boost-by" - ), - keyword_match_mode: - argv["retrieval-options-keyword-match-mode"], - }, - rewrite_model: resolveFileToken( - argv["rewrite-model"] as string | undefined, - "rewrite-model", - "text" - ), - rewrite_query: argv["rewrite-query"], - score_threshold: argv["score-threshold"], - source: resolveFileToken( - argv["source"] as string | undefined, - "source", - "text" - ), - source_params: { - d1: { - query: resolveFileToken( - argv["source-params-d1-query"] as - | string - | undefined, - "source-params-d1-query", - "text" - ), - template: argv["source-params-d1-template"], - }, - exclude_items: argv["source-params-exclude-items"], - include_items: argv["source-params-include-items"], - prefix: resolveFileToken( - argv["source-params-prefix"] as string | undefined, - "source-params-prefix", - "text" - ), - r2_jurisdiction: resolveFileToken( - argv["source-params-r2-jurisdiction"] as - | string - | undefined, - "source-params-r2-jurisdiction", - "text" - ), - web_crawler: { - discover_options: { - depth: - argv[ - "source-params-web-crawler-discover-options-depth" - ], - include_external_links: - argv[ - "source-params-web-crawler-discover-options-include-external-links" - ], - include_subdomains: - argv[ - "source-params-web-crawler-discover-options-include-subdomains" - ], - limit: - argv[ - "source-params-web-crawler-discover-options-limit" - ], - max_age: - argv[ - "source-params-web-crawler-discover-options-max-age" - ], - source: - argv[ - "source-params-web-crawler-discover-options-source" - ], - }, - parse_options: { - content_selector: parseObjectArray( - argv[ - "source-params-web-crawler-parse-options-content-selector" - ], - "source-params-web-crawler-parse-options-content-selector" - ), - include_headers: parseJsonMap( - argv[ - "source-params-web-crawler-parse-options-include-headers" - ], - "source-params-web-crawler-parse-options-include-headers" - ), - include_images: - argv[ - "source-params-web-crawler-parse-options-include-images" - ], - specific_sitemaps: - argv[ - "source-params-web-crawler-parse-options-specific-sitemaps" - ], - use_browser_rendering: - argv[ - "source-params-web-crawler-parse-options-use-browser-rendering" - ], - }, - parse_type: - argv["source-params-web-crawler-parse-type"], - }, - }, - sync_interval: argv["sync-interval"], - token_id: resolveFileToken( - argv["token-id"] as string | undefined, - "token-id", - "text" - ), - type: argv["type"], - id: argv["id"], - }, - [ - [ - "source_params", - "web_crawler", - "parse_options", - "include_headers", - ], - ] - ), - }); - return; - } - const parsedBody = - argv.body !== undefined - ? mergeBodyPositionals(parseBody(argv.body), [ - { name: "id", field: "id", value: argv["id"] }, - ]) - : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - namespace: argv["namespace"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody( - { - ai_gateway_id: resolveFileToken( - argv["ai-gateway-id"] as string | undefined, - "ai-gateway-id", - "text" - ), - ai_search_model: resolveFileToken( - argv["ai-search-model"] as string | undefined, - "ai-search-model", - "text" - ), - cache: argv["cache"], - cache_threshold: argv["cache-threshold"], - cache_ttl: argv["cache-ttl"], - chunk: argv["chunk"], - chunk_overlap: argv["chunk-overlap"], - chunk_size: argv["chunk-size"], - custom_metadata: parseObjectArray( - argv["custom-metadata"], - "custom-metadata" - ), - embedding_model: resolveFileToken( - argv["embedding-model"] as string | undefined, - "embedding-model", - "text" - ), - fusion_method: argv["fusion-method"], - hybrid_search_enabled: argv["hybrid-search-enabled"], - index_method: { - keyword: argv["index-method-keyword"], - vector: argv["index-method-vector"], - }, - indexing_options: { - file_summary: argv["indexing-options-file-summary"], - keyword_tokenizer: argv["indexing-options-keyword-tokenizer"], - use_ocr: argv["indexing-options-use-ocr"], - }, - max_num_results: argv["max-num-results"], - metadata: { - created_from_aisearch_wizard: - argv["metadata-created-from-aisearch-wizard"], - created_from_emdash_plugin: { - type: argv["metadata-created-from-emdash-plugin-type"], - version: resolveFileToken( - argv["metadata-created-from-emdash-plugin-version"] as - | string - | undefined, - "metadata-created-from-emdash-plugin-version", - "text" - ), - }, - worker_domain: resolveFileToken( - argv["metadata-worker-domain"] as string | undefined, - "metadata-worker-domain", - "text" - ), - }, - public_endpoint_params: { - authorized_hosts: argv["public-endpoint-params-authorized-hosts"], - chat_completions_endpoint: { - disabled: - argv[ - "public-endpoint-params-chat-completions-endpoint-disabled" - ], - }, - custom_domains: argv["public-endpoint-params-custom-domains"], - default_domain_enabled: - argv["public-endpoint-params-default-domain-enabled"], - enabled: argv["public-endpoint-params-enabled"], - mcp: { - description: resolveFileToken( - argv["public-endpoint-params-mcp-description"] as - | string - | undefined, - "public-endpoint-params-mcp-description", - "text" - ), - disabled: argv["public-endpoint-params-mcp-disabled"], - }, - rate_limit: { - period_ms: argv["public-endpoint-params-rate-limit-period-ms"], - requests: argv["public-endpoint-params-rate-limit-requests"], - technique: argv["public-endpoint-params-rate-limit-technique"], - }, - search_endpoint: { - disabled: - argv["public-endpoint-params-search-endpoint-disabled"], - }, - }, - reranking: argv["reranking"], - reranking_model: resolveFileToken( - argv["reranking-model"] as string | undefined, - "reranking-model", - "text" - ), - retrieval_options: { - boost_by: parseObjectArray( - argv["retrieval-options-boost-by"], - "retrieval-options-boost-by" - ), - keyword_match_mode: argv["retrieval-options-keyword-match-mode"], - }, - rewrite_model: resolveFileToken( - argv["rewrite-model"] as string | undefined, - "rewrite-model", - "text" - ), - rewrite_query: argv["rewrite-query"], - score_threshold: argv["score-threshold"], - source: resolveFileToken( - argv["source"] as string | undefined, - "source", - "text" - ), - source_params: { - d1: { - query: resolveFileToken( - argv["source-params-d1-query"] as string | undefined, - "source-params-d1-query", - "text" - ), - template: argv["source-params-d1-template"], - }, - exclude_items: argv["source-params-exclude-items"], - include_items: argv["source-params-include-items"], - prefix: resolveFileToken( - argv["source-params-prefix"] as string | undefined, - "source-params-prefix", - "text" - ), - r2_jurisdiction: resolveFileToken( - argv["source-params-r2-jurisdiction"] as string | undefined, - "source-params-r2-jurisdiction", - "text" - ), - web_crawler: { - discover_options: { - depth: - argv["source-params-web-crawler-discover-options-depth"], - include_external_links: - argv[ - "source-params-web-crawler-discover-options-include-external-links" - ], - include_subdomains: - argv[ - "source-params-web-crawler-discover-options-include-subdomains" - ], - limit: - argv["source-params-web-crawler-discover-options-limit"], - max_age: - argv["source-params-web-crawler-discover-options-max-age"], - source: - argv["source-params-web-crawler-discover-options-source"], - }, - parse_options: { - content_selector: parseObjectArray( - argv[ - "source-params-web-crawler-parse-options-content-selector" - ], - "source-params-web-crawler-parse-options-content-selector" - ), - include_headers: parseJsonMap( - argv[ - "source-params-web-crawler-parse-options-include-headers" - ], - "source-params-web-crawler-parse-options-include-headers" - ), - include_images: - argv[ - "source-params-web-crawler-parse-options-include-images" - ], - specific_sitemaps: - argv[ - "source-params-web-crawler-parse-options-specific-sitemaps" - ], - use_browser_rendering: - argv[ - "source-params-web-crawler-parse-options-use-browser-rendering" - ], - }, - parse_type: argv["source-params-web-crawler-parse-type"], - }, - }, - sync_interval: argv["sync-interval"], - token_id: resolveFileToken( - argv["token-id"] as string | undefined, - "token-id", - "text" - ), - type: argv["type"], - id: argv["id"], - }, - [["source_params", "web_crawler", "parse_options", "include_headers"]] - ); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - namespace: argv["namespace"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 ai-search create \n\nCreate a new AI Search instance with the given configuration. If type is omitted or null, a non-blank HTTP(S) source infers web-crawler and any other source infers r2; r2 sources must name an existing bucket. A missing or blank source without a type creates a managed upload-only instance.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/delete.handler.ts b/packages/cli/src/commands/_generated/ai-search/delete.handler.ts new file mode 100644 index 0000000000..ca474290ce --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/delete.handler.ts @@ -0,0 +1,64 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + "instance-id": String(argv["instance-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This operation permanently deletes the AI Search instance and all its indexed data.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + requestApi( + client, + "DELETE", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}` + ) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/delete.ts b/packages/cli/src/commands/_generated/ai-search/delete.ts index fca78819cb..5d5ad63a4a 100644 --- a/packages/cli/src/commands/_generated/ai-search/delete.ts +++ b/packages/cli/src/commands/_generated/ai-search/delete.ts @@ -1,105 +1,49 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search delete \n\nDeletes an AI Search instance and all its indexed data permanently." - ) - .positional("instance-id", { - type: "string", - description: "AI Search instance ID.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "instance-id", + brief: "AI Search instance ID.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete an AI Search instance.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - "instance-id": String(argv["instance-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This operation permanently deletes the AI Search instance and all its indexed data.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - requestApi( - client, - "DELETE", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}` - ) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 ai-search delete \n\nDeletes an AI Search instance and all its indexed data permanently.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/get.handler.ts b/packages/cli/src/commands/_generated/ai-search/get.handler.ts new file mode 100644 index 0000000000..22d35f63f8 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/get.handler.ts @@ -0,0 +1,53 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + "instance-id": String(argv["instance-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + requestApi( + client, + "GET", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}` + ) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/get.ts b/packages/cli/src/commands/_generated/ai-search/get.ts index 4272016920..4b4ecd0fcc 100644 --- a/packages/cli/src/commands/_generated/ai-search/get.ts +++ b/packages/cli/src/commands/_generated/ai-search/get.ts @@ -1,88 +1,43 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search get \n\nRetrieve the configuration and status of an AI Search instance." - ) - .positional("instance-id", { - type: "string", - description: "AI Search instance ID.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "instance-id", + brief: "AI Search instance ID.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get an AI Search instance.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - "instance-id": String(argv["instance-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - requestApi( - client, - "GET", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}` - ) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-search get \n\nRetrieve the configuration and status of an AI Search instance.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/index.ts b/packages/cli/src/commands/_generated/ai-search/index.ts index 3ad6770026..e31318e4c1 100644 --- a/packages/cli/src/commands/_generated/ai-search/index.ts +++ b/packages/cli/src/commands/_generated/ai-search/index.ts @@ -14,40 +14,35 @@ import $search from "./search.js"; import $stats from "./stats.js"; import $tokens from "./tokens/index.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * ai-search command * @generated from apis/overlays/ai-search.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "ai-search", describe: "Managed search-as-a-service: crawl, index, and query content with AI-powered relevance and chat completions", - builder: (yargs) => { - return yargs - .command($chatcompletions) - .command($create) - .command($delete) - .command($get) - .command($list) - .command($move) - .command($multichatcompletions) - .command($multisearch) - .command($purgecache) - .command($search) - .command($stats) - .command($update) - .command($items) - .command($jobs) - .command($namespace) - .command($tokens) - .demandCommand(1, "Please specify a subcommand"); + routes: { + "chat-completions": $chatcompletions, + create: $create, + delete: $delete, + get: $get, + list: $list, + move: $move, + "multi-chat-completions": $multichatcompletions, + "multi-search": $multisearch, + "purge-cache": $purgecache, + search: $search, + stats: $stats, + update: $update, + items: $items, + jobs: $jobs, + namespace: $namespace, + tokens: $tokens, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/items/chunks.handler.ts b/packages/cli/src/commands/_generated/ai-search/items/chunks.handler.ts new file mode 100644 index 0000000000..6cdf5bda96 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/items/chunks.handler.ts @@ -0,0 +1,60 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./chunks.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search items chunks", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + limit: argv["limit"], + offset: argv["offset"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search items chunks", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/items/${argv["item-id"] == null ? "" : encodeURIComponent(String(argv["item-id"]))}/chunks`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + "instance-id": String(argv["instance-id"] ?? ""), + "item-id": String(argv["item-id"] ?? ""), + }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + requestApi( + client, + "GET", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/items/${encodeURIComponent(String(argv["item-id"]))}/chunks`, + { query: queryParams } + ) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/items/chunks.ts b/packages/cli/src/commands/_generated/ai-search/items/chunks.ts index a2c54bcead..c56d8446a8 100644 --- a/packages/cli/src/commands/_generated/ai-search/items/chunks.ts +++ b/packages/cli/src/commands/_generated/ai-search/items/chunks.ts @@ -1,102 +1,46 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * chunks command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search items chunks \n\nLists chunks for a specific item in an AI Search instance, including their text content." - ) - .positional("item-id", { - type: "string", - description: "Indexed item ID.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("instance-id", { - type: "string", - description: "AI Search instance ID.", - demandOption: true, - }) - .option("limit", { type: "number", description: "Limit" }) - .option("offset", { type: "number", description: "Offset" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + }, + "instance-id": { + kind: "parsed", + brief: "AI Search instance ID.", + parse: String, + }, + limit: { kind: "parsed", brief: "Limit", optional: true, parse: Number }, + offset: { kind: "parsed", brief: "Offset", optional: true, parse: Number }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "item-id", brief: "Indexed item ID.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "chunks ", describe: "List Item Chunks.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search items chunks", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - limit: argv["limit"], - offset: argv["offset"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search items chunks", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/items/${argv["item-id"] == null ? "" : encodeURIComponent(String(argv["item-id"]))}/chunks`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - "instance-id": String(argv["instance-id"] ?? ""), - "item-id": String(argv["item-id"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - requestApi( - client, - "GET", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/items/${encodeURIComponent(String(argv["item-id"]))}/chunks`, - { query: queryParams } - ) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-search items chunks \n\nLists chunks for a specific item in an AI Search instance, including their text content.", + ...parameters, + loader: () => import("./chunks.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/items/delete.handler.ts b/packages/cli/src/commands/_generated/ai-search/items/delete.handler.ts new file mode 100644 index 0000000000..88ef057ec3 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/items/delete.handler.ts @@ -0,0 +1,60 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search items delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search items delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/items/${argv["item-id"] == null ? "" : encodeURIComponent(String(argv["item-id"]))}`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + "instance-id": String(argv["instance-id"] ?? ""), + "item-id": String(argv["item-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + requestApi( + client, + "DELETE", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/items/${encodeURIComponent(String(argv["item-id"]))}` + ) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/items/delete.ts b/packages/cli/src/commands/_generated/ai-search/items/delete.ts index 408287f04c..9270bffa5d 100644 --- a/packages/cli/src/commands/_generated/ai-search/items/delete.ts +++ b/packages/cli/src/commands/_generated/ai-search/items/delete.ts @@ -1,106 +1,50 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search items delete \n\nDeletes a file from a managed AI Search instance and removes its indexed data." - ) - .positional("item-id", { - type: "string", - description: "Indexed item ID.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("instance-id", { - type: "string", - description: "AI Search instance ID.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + }, + "instance-id": { + kind: "parsed", + brief: "AI Search instance ID.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "item-id", brief: "Indexed item ID.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete Item.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search items delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search items delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/items/${argv["item-id"] == null ? "" : encodeURIComponent(String(argv["item-id"]))}`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - "instance-id": String(argv["instance-id"] ?? ""), - "item-id": String(argv["item-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - requestApi( - client, - "DELETE", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/items/${encodeURIComponent(String(argv["item-id"]))}` - ) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 ai-search items delete \n\nDeletes a file from a managed AI Search instance and removes its indexed data.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/items/download.handler.ts b/packages/cli/src/commands/_generated/ai-search/items/download.handler.ts new file mode 100644 index 0000000000..d9714c9861 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/items/download.handler.ts @@ -0,0 +1,60 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./download.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { fetchRawBytes, writeRawOutput } from "#lib/raw-fetch.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search items download", + classification: { + safeFlags: ["dry-run", "text"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search items download", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/items/${argv["item-id"] == null ? "" : encodeURIComponent(String(argv["item-id"]))}/download`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + "instance-id": String(argv["instance-id"] ?? ""), + "item-id": String(argv["item-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const __cfRawBytes = await withProgress(`Loading`, async () => + fetchRawBytes( + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/items/${encodeURIComponent(String(argv["item-id"]))}/download`, + { + method: "GET", + local: argv.local === true, + persistTo: argv.persistTo as string | undefined, + } + ) + ); + writeRawOutput( + argv.text === true ? __cfRawBytes.toString("utf-8") : __cfRawBytes + ); + return; + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/items/download.ts b/packages/cli/src/commands/_generated/ai-search/items/download.ts index 61cf146d24..ce2f63777d 100644 --- a/packages/cli/src/commands/_generated/ai-search/items/download.ts +++ b/packages/cli/src/commands/_generated/ai-search/items/download.ts @@ -1,106 +1,50 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * download command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { fetchRawBytes, writeRawOutput } from "#lib/raw-fetch.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search items download \n\nDownloads the raw file content for a specific item from the managed AI Search instance storage." - ) - .positional("item-id", { - type: "string", - description: "Indexed item ID.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("instance-id", { - type: "string", - description: "AI Search instance ID.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + }, + "instance-id": { + kind: "parsed", + brief: "AI Search instance ID.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("text", { - type: "boolean", - description: + }, + text: { + kind: "boolean", + brief: "Decode the response body as UTF-8 text instead of writing raw bytes", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "item-id", brief: "Indexed item ID.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "download ", describe: "Download Item Content.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search items download", - classification: { - safeFlags: ["dry-run", "text"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search items download", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/items/${argv["item-id"] == null ? "" : encodeURIComponent(String(argv["item-id"]))}/download`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - "instance-id": String(argv["instance-id"] ?? ""), - "item-id": String(argv["item-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const __cfRawBytes = await withProgress(`Loading`, async () => - fetchRawBytes( - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/items/${encodeURIComponent(String(argv["item-id"]))}/download`, - { - method: "GET", - local: argv.local === true, - persistTo: argv.persistTo as string | undefined, - } - ) - ); - writeRawOutput( - argv.text === true ? __cfRawBytes.toString("utf-8") : __cfRawBytes - ); - return; - } - ), -}; + usage: + "$0 ai-search items download \n\nDownloads the raw file content for a specific item from the managed AI Search instance storage.", + ...parameters, + loader: () => import("./download.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/items/get.handler.ts b/packages/cli/src/commands/_generated/ai-search/items/get.handler.ts new file mode 100644 index 0000000000..3a6cc11a92 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/items/get.handler.ts @@ -0,0 +1,54 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search items get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search items get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/items/${argv["item-id"] == null ? "" : encodeURIComponent(String(argv["item-id"]))}`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + "instance-id": String(argv["instance-id"] ?? ""), + "item-id": String(argv["item-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + requestApi( + client, + "GET", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/items/${encodeURIComponent(String(argv["item-id"]))}` + ) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/items/get.ts b/packages/cli/src/commands/_generated/ai-search/items/get.ts index 3415d0bc4d..f367a7db59 100644 --- a/packages/cli/src/commands/_generated/ai-search/items/get.ts +++ b/packages/cli/src/commands/_generated/ai-search/items/get.ts @@ -1,94 +1,44 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search items get \n\nRetrieves a specific indexed item from an AI Search instance." - ) - .positional("item-id", { - type: "string", - description: "Indexed item ID.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("instance-id", { - type: "string", - description: "AI Search instance ID.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + }, + "instance-id": { + kind: "parsed", + brief: "AI Search instance ID.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "item-id", brief: "Indexed item ID.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get Item.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search items get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search items get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/items/${argv["item-id"] == null ? "" : encodeURIComponent(String(argv["item-id"]))}`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - "instance-id": String(argv["instance-id"] ?? ""), - "item-id": String(argv["item-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - requestApi( - client, - "GET", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/items/${encodeURIComponent(String(argv["item-id"]))}` - ) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-search items get \n\nRetrieves a specific indexed item from an AI Search instance.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/items/index.ts b/packages/cli/src/commands/_generated/ai-search/items/index.ts index 1f78164bba..3425f3f929 100644 --- a/packages/cli/src/commands/_generated/ai-search/items/index.ts +++ b/packages/cli/src/commands/_generated/ai-search/items/index.ts @@ -7,32 +7,27 @@ import $logs from "./logs.js"; import $sync from "./sync.js"; import $upload from "./upload.js"; import $upsert from "./upsert.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * items command group * @generated from apis/overlays/ai-search.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "items", describe: "Content indexed by AI Search instances", - builder: (yargs) => { - return yargs - .command($chunks) - .command($delete) - .command($download) - .command($get) - .command($list) - .command($logs) - .command($sync) - .command($upload) - .command($upsert) - .demandCommand(1, "Please specify a subcommand"); + routes: { + chunks: $chunks, + delete: $delete, + download: $download, + get: $get, + list: $list, + logs: $logs, + sync: $sync, + upload: $upload, + upsert: $upsert, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/items/list.handler.ts b/packages/cli/src/commands/_generated/ai-search/items/list.handler.ts new file mode 100644 index 0000000000..6a0edbffe7 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/items/list.handler.ts @@ -0,0 +1,66 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search items list", + classification: { + safeFlags: ["sort-by", "status", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + search: argv["search"], + sort_by: argv["sort-by"], + status: argv["status"], + source: argv["source"], + metadata_filter: argv["metadata-filter"], + item_id: argv["item-id"], + key: argv["key"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search items list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/items`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + "instance-id": String(argv["instance-id"] ?? ""), + }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + requestApi( + client, + "GET", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/items`, + { query: queryParams } + ) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/items/list.ts b/packages/cli/src/commands/_generated/ai-search/items/list.ts index 75db14ddff..8aab1e6335 100644 --- a/packages/cli/src/commands/_generated/ai-search/items/list.ts +++ b/packages/cli/src/commands/_generated/ai-search/items/list.ts @@ -1,50 +1,45 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search items list\n\nLists indexed items in an AI Search instance." - ) - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("instance-id", { - type: "string", - description: "AI Search instance ID.", - demandOption: true, - }) - .option("page", { type: "number", description: "Page" }) - .option("per-page", { type: "number", description: "Per page" }) - .option("search", { type: "string", description: "Search" }) - .option("sort-by", { - type: "string", - description: + parse: String, + }, + "instance-id": { + kind: "parsed", + brief: "AI Search instance ID.", + parse: String, + }, + page: { kind: "parsed", brief: "Page", optional: true, parse: Number }, + "per-page": { + kind: "parsed", + brief: "Per page", + optional: true, + parse: Number, + }, + search: { kind: "parsed", brief: "Search", optional: true, parse: String }, + "sort-by": { + kind: "enum", + brief: 'Sort order for items. "status" (default) sorts items according to status priority, then last_seen_at. "modified_at" sorts items according to file modification time (most recent first), falling back to created_at.', - choices: ["status", "modified_at"], - }) - .option("status", { - type: "string", - description: "Status", - choices: [ + values: ["status", "modified_at"], + optional: true, + }, + status: { + kind: "enum", + brief: "Status", + values: [ "queued", "running", "completed", @@ -52,91 +47,52 @@ function builder(yargs: Argv) { "skipped", "outdated", ], - }) - .option("source", { - type: "string", - description: + optional: true, + }, + source: { + kind: "parsed", + brief: 'Return only items with this source_id. Use "builtin" for uploaded files, or a source identifier like "web-crawler:https://example.com".', - }) - .option("metadata-filter", { - type: "string", - description: + optional: true, + parse: String, + }, + "metadata-filter": { + kind: "parsed", + brief: 'JSON-encoded metadata filter using Vectorize filter syntax. Examples: {"folder":"reports/"}, {"timestamp":{"$gte":1700000000000}}, {"folder":{"$in":["docs/","reports/"]}}.', - }) - .option("item-id", { - type: "string", - description: + optional: true, + parse: String, + }, + "item-id": { + kind: "parsed", + brief: "Return only the item with this unique ID. Returns at most one item.", - }) - .option("key", { - type: "string", - description: + optional: true, + parse: String, + }, + key: { + kind: "parsed", + brief: "Return only items with this exact key (object key / filename). Each key is unique within a source, so combine with `source` to disambiguate across data sources.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "Items List.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search items list", - classification: { - safeFlags: ["sort-by", "status", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - search: argv["search"], - sort_by: argv["sort-by"], - status: argv["status"], - source: argv["source"], - metadata_filter: argv["metadata-filter"], - item_id: argv["item-id"], - key: argv["key"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search items list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/items`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - "instance-id": String(argv["instance-id"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - requestApi( - client, - "GET", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/items`, - { query: queryParams } - ) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-search items list\n\nLists indexed items in an AI Search instance.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/items/logs.handler.ts b/packages/cli/src/commands/_generated/ai-search/items/logs.handler.ts new file mode 100644 index 0000000000..13b537b2bc --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/items/logs.handler.ts @@ -0,0 +1,60 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./logs.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search items logs", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + limit: argv["limit"], + cursor: argv["cursor"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search items logs", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/items/${argv["item-id"] == null ? "" : encodeURIComponent(String(argv["item-id"]))}/logs`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + "instance-id": String(argv["instance-id"] ?? ""), + "item-id": String(argv["item-id"] ?? ""), + }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + requestApi( + client, + "GET", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/items/${encodeURIComponent(String(argv["item-id"]))}/logs`, + { query: queryParams } + ) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/items/logs.ts b/packages/cli/src/commands/_generated/ai-search/items/logs.ts index b9720c7b95..80121d48f8 100644 --- a/packages/cli/src/commands/_generated/ai-search/items/logs.ts +++ b/packages/cli/src/commands/_generated/ai-search/items/logs.ts @@ -1,102 +1,46 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * logs command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search items logs \n\nLists processing logs for a specific item in an AI Search instance." - ) - .positional("item-id", { - type: "string", - description: "Indexed item ID.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("instance-id", { - type: "string", - description: "AI Search instance ID.", - demandOption: true, - }) - .option("limit", { type: "number", description: "Limit" }) - .option("cursor", { type: "string", description: "Cursor" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + }, + "instance-id": { + kind: "parsed", + brief: "AI Search instance ID.", + parse: String, + }, + limit: { kind: "parsed", brief: "Limit", optional: true, parse: Number }, + cursor: { kind: "parsed", brief: "Cursor", optional: true, parse: String }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "item-id", brief: "Indexed item ID.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "logs ", describe: "Item Logs.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search items logs", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - limit: argv["limit"], - cursor: argv["cursor"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search items logs", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/items/${argv["item-id"] == null ? "" : encodeURIComponent(String(argv["item-id"]))}/logs`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - "instance-id": String(argv["instance-id"] ?? ""), - "item-id": String(argv["item-id"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - requestApi( - client, - "GET", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/items/${encodeURIComponent(String(argv["item-id"]))}/logs`, - { query: queryParams } - ) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-search items logs \n\nLists processing logs for a specific item in an AI Search instance.", + ...parameters, + loader: () => import("./logs.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/items/sync.handler.ts b/packages/cli/src/commands/_generated/ai-search/items/sync.handler.ts new file mode 100644 index 0000000000..c853ee2c7e --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/items/sync.handler.ts @@ -0,0 +1,103 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./sync.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, setNestedValue } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredEnumField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search items sync", + classification: { + safeFlags: ["next-action", "wait-for-completion", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["next-action"] === undefined) { + argv["next-action"] = await promptForRequiredEnumField( + "next-action", + "The next_action field", + ["INDEX"] as const + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search items sync", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/items/${argv["item-id"] == null ? "" : encodeURIComponent(String(argv["item-id"]))}`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + "instance-id": String(argv["instance-id"] ?? ""), + "item-id": String(argv["item-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + next_action: argv["next-action"], + wait_for_completion: argv["wait-for-completion"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + requestApi( + client, + "PATCH", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/items/${encodeURIComponent(String(argv["item-id"]))}`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData: Record = {}; + if (argv["next-action"] !== undefined) + setNestedValue(bodyData, ["next_action"], argv["next-action"]); + if (argv["wait-for-completion"] !== undefined) + setNestedValue( + bodyData, + ["wait_for_completion"], + argv["wait-for-completion"] + ); + const result = await withProgress(`Updating`, async () => + requestApi( + client, + "PATCH", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/items/${encodeURIComponent(String(argv["item-id"]))}`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/items/sync.ts b/packages/cli/src/commands/_generated/ai-search/items/sync.ts index 27aa13f285..862299a933 100644 --- a/packages/cli/src/commands/_generated/ai-search/items/sync.ts +++ b/packages/cli/src/commands/_generated/ai-search/items/sync.ts @@ -1,161 +1,65 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * sync command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, setNestedValue } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredEnumField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search items sync \n\nSynchronizes an item to an AI Search instance index." - ) - .positional("item-id", { - type: "string", - description: "Indexed item ID.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("instance-id", { - type: "string", - description: "AI Search instance ID.", - demandOption: true, - }) - .option("next-action", { - type: "string", - description: "The next_action field", + parse: String, + }, + "instance-id": { + kind: "parsed", + brief: "AI Search instance ID.", + parse: String, + }, + "next-action": { + kind: "parsed", + brief: "The next_action field", + optional: true, choices: ["INDEX"], - }) - .coerce("next-action", (value) => - resolveFileToken(value, "next-action", "text") - ) - .option("wait-for-completion", { - type: "boolean", - description: + parse: String, + coerce: (value: string) => resolveFileToken(value, "next-action", "text"), + }, + "wait-for-completion": { + kind: "boolean", + brief: "Wait for indexing before responding. After processing, vector-indexed instances use any time remaining in a 25s wait budget to confirm Vectorize ingestion. Processing itself continues uninterrupted and can exceed that budget. If confirmation times out, the response returns the current item state and background indexing continues. Defaults to false.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { placeholder: "item-id", brief: "Indexed item ID.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "sync ", describe: "Sync Item.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search items sync", - classification: { - safeFlags: ["next-action", "wait-for-completion", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["next-action"] === undefined) { - argv["next-action"] = await promptForRequiredEnumField( - "next-action", - "The next_action field", - ["INDEX"] as const - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search items sync", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/items/${argv["item-id"] == null ? "" : encodeURIComponent(String(argv["item-id"]))}`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - "instance-id": String(argv["instance-id"] ?? ""), - "item-id": String(argv["item-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - next_action: argv["next-action"], - wait_for_completion: argv["wait-for-completion"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - requestApi( - client, - "PATCH", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/items/${encodeURIComponent(String(argv["item-id"]))}`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData: Record = {}; - if (argv["next-action"] !== undefined) - setNestedValue(bodyData, ["next_action"], argv["next-action"]); - if (argv["wait-for-completion"] !== undefined) - setNestedValue( - bodyData, - ["wait_for_completion"], - argv["wait-for-completion"] - ); - const result = await withProgress(`Updating`, async () => - requestApi( - client, - "PATCH", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/items/${encodeURIComponent(String(argv["item-id"]))}`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 ai-search items sync \n\nSynchronizes an item to an AI Search instance index.", + ...parameters, + loader: () => import("./sync.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/items/upload.handler.ts b/packages/cli/src/commands/_generated/ai-search/items/upload.handler.ts new file mode 100644 index 0000000000..255f6ecc04 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/items/upload.handler.ts @@ -0,0 +1,125 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./upload.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { readFileForFlag, resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search items upload", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if ( + argv.body === undefined && + argv.file === undefined && + argv["metadata"] === undefined && + argv["wait-for-completion"] === undefined + ) { + throw new Error( + "--body or --file is required for this command. Pass --body '' or --file path/to/file." + ); + } + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search items upload", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/items`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + "instance-id": String(argv["instance-id"] ?? ""), + }, + bodyKind: "multipart", + body: { + body: argv["body"], + file: argv["file"], + metadata: argv["metadata"], + "wait-for-completion": argv["wait-for-completion"], + }, + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + argv.file !== undefined || + argv.body !== undefined || + argv["metadata"] !== undefined || + argv["wait-for-completion"] !== undefined + ) { + const formData = new FormData(); + if (argv.file !== undefined) { + const fileContent = readFileForFlag(argv.file); + formData.append( + "file", + new Blob([fileContent]), + argv.file.split(/[\\/]/).filter(Boolean).pop() + ); + } else if (argv.body !== undefined) { + formData.append("file", argv.body); + } + if (argv["metadata"] !== undefined) + formData.append( + "metadata", + String( + resolveFileToken( + argv["metadata"] as string | undefined, + "metadata", + "text" + ) ?? "" + ) + ); + if (argv["wait-for-completion"] !== undefined) + formData.append( + "wait_for_completion", + String(argv["wait-for-completion"]) + ); + const result = await withProgress(`Creating`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/items`, + { body: formData } + ) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + if (argv.body !== undefined) { + // Endpoint does not accept application/json — send --body as raw bytes, + // resolving @file references as binary file contents. + const bodyData = resolveFileToken(argv.body, "body", "binary"); + const result = await withProgress(`Creating`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/items`, + { + body: bodyData, + headers: { "Content-Type": "multipart/form-data" }, + } + ) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/items/upload.ts b/packages/cli/src/commands/_generated/ai-search/items/upload.ts index 9bd7b05134..14c359fff8 100644 --- a/packages/cli/src/commands/_generated/ai-search/items/upload.ts +++ b/packages/cli/src/commands/_generated/ai-search/items/upload.ts @@ -1,177 +1,67 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * upload command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { readFileForFlag, resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search items upload \n\nUploads a file to a managed AI Search instance via multipart/form-data." - ) - .positional("instance-id", { - type: "string", - description: "AI Search instance ID.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }) - .option("file", { - type: "string", - description: "Path to a file to upload as the request body", - }) - .option("metadata", { - type: "string", - description: "JSON string of custom metadata key-value pairs.", - }) - .option("wait-for-completion", { - type: "boolean", - description: + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + file: { + kind: "parsed", + brief: "Path to a file to upload as the request body", + optional: true, + parse: String, + }, + metadata: { + kind: "parsed", + brief: "JSON string of custom metadata key-value pairs.", + optional: true, + parse: String, + }, + "wait-for-completion": { + kind: "boolean", + brief: "Wait for indexing before responding. After processing, vector-indexed instances use any time remaining in a 25s wait budget to confirm Vectorize ingestion. Processing itself continues uninterrupted and can exceed that budget. If confirmation times out, the response returns the current item state and background indexing continues. Defaults to false.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + optional: true, + }, + }, + operands: [ + { + placeholder: "instance-id", + brief: "AI Search instance ID.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "upload ", describe: "Upload Item.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search items upload", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if ( - argv.body === undefined && - argv.file === undefined && - argv["metadata"] === undefined && - argv["wait-for-completion"] === undefined - ) { - throw new Error( - "--body or --file is required for this command. Pass --body '' or --file path/to/file." - ); - } - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search items upload", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/items`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - "instance-id": String(argv["instance-id"] ?? ""), - }, - bodyKind: "multipart", - body: { - body: argv["body"], - file: argv["file"], - metadata: argv["metadata"], - "wait-for-completion": argv["wait-for-completion"], - }, - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - argv.file !== undefined || - argv.body !== undefined || - argv["metadata"] !== undefined || - argv["wait-for-completion"] !== undefined - ) { - const formData = new FormData(); - if (argv.file !== undefined) { - const fileContent = readFileForFlag(argv.file); - formData.append( - "file", - new Blob([fileContent]), - argv.file.split(/[\\/]/).filter(Boolean).pop() - ); - } else if (argv.body !== undefined) { - formData.append("file", argv.body); - } - if (argv["metadata"] !== undefined) - formData.append( - "metadata", - String( - resolveFileToken( - argv["metadata"] as string | undefined, - "metadata", - "text" - ) ?? "" - ) - ); - if (argv["wait-for-completion"] !== undefined) - formData.append( - "wait_for_completion", - String(argv["wait-for-completion"]) - ); - const result = await withProgress(`Creating`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/items`, - { body: formData } - ) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - if (argv.body !== undefined) { - // Endpoint does not accept application/json — send --body as raw bytes, - // resolving @file references as binary file contents. - const bodyData = resolveFileToken(argv.body, "body", "binary"); - const result = await withProgress(`Creating`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/items`, - { - body: bodyData, - headers: { "Content-Type": "multipart/form-data" }, - } - ) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - } - ), -}; + usage: + "$0 ai-search items upload \n\nUploads a file to a managed AI Search instance via multipart/form-data.", + ...parameters, + loader: () => import("./upload.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/items/upsert.handler.ts b/packages/cli/src/commands/_generated/ai-search/items/upsert.handler.ts new file mode 100644 index 0000000000..d4383b8e27 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/items/upsert.handler.ts @@ -0,0 +1,123 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./upsert.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, setNestedValue } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { + promptForRequiredEnumField, + promptForRequiredField, +} from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search items upsert", + classification: { + safeFlags: ["next-action", "wait-for-completion", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["key"] === undefined) { + argv["key"] = await promptForRequiredField( + "key", + "Item key / filename. Must not exceed 128 characters." + ); + } + if (argv["next-action"] === undefined) { + argv["next-action"] = await promptForRequiredEnumField( + "next-action", + "The next_action field", + ["INDEX"] as const + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search items upsert", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/items`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + "instance-id": String(argv["instance-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + key: resolveFileToken( + argv["key"] as string | undefined, + "key", + "text" + ), + next_action: argv["next-action"], + wait_for_completion: argv["wait-for-completion"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + requestApi( + client, + "PUT", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/items`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData: Record = {}; + if (argv["key"] !== undefined) + setNestedValue( + bodyData, + ["key"], + resolveFileToken(argv["key"] as string | undefined, "key", "text") + ); + if (argv["next-action"] !== undefined) + setNestedValue(bodyData, ["next_action"], argv["next-action"]); + if (argv["wait-for-completion"] !== undefined) + setNestedValue( + bodyData, + ["wait_for_completion"], + argv["wait-for-completion"] + ); + const result = await withProgress(`Updating`, async () => + requestApi( + client, + "PUT", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/items`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/items/upsert.ts b/packages/cli/src/commands/_generated/ai-search/items/upsert.ts index 4080438152..8fcf2e639e 100644 --- a/packages/cli/src/commands/_generated/ai-search/items/upsert.ts +++ b/packages/cli/src/commands/_generated/ai-search/items/upsert.ts @@ -1,179 +1,70 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * upsert command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, setNestedValue } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { - promptForRequiredEnumField, - promptForRequiredField, -} from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search items upsert \n\nCreates or updates an indexed item in an AI Search instance." - ) - .positional("instance-id", { - type: "string", - description: "AI Search instance ID.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("key", { - type: "string", - description: "Item key / filename. Must not exceed 128 characters.", - }) - .option("next-action", { - type: "string", - description: "The next_action field", + parse: String, + }, + key: { + kind: "parsed", + brief: "Item key / filename. Must not exceed 128 characters.", + optional: true, + parse: String, + }, + "next-action": { + kind: "parsed", + brief: "The next_action field", + optional: true, choices: ["INDEX"], - }) - .coerce("next-action", (value) => - resolveFileToken(value, "next-action", "text") - ) - .option("wait-for-completion", { - type: "boolean", - description: + parse: String, + coerce: (value: string) => resolveFileToken(value, "next-action", "text"), + }, + "wait-for-completion": { + kind: "boolean", + brief: "Wait for indexing before responding. After processing, vector-indexed instances use any time remaining in a 25s wait budget to confirm Vectorize ingestion. Processing itself continues uninterrupted and can exceed that budget. If confirmation times out, the response returns the current item state and background indexing continues. Defaults to false.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "instance-id", + brief: "AI Search instance ID.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "upsert ", describe: "Create or Update Item.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search items upsert", - classification: { - safeFlags: ["next-action", "wait-for-completion", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["key"] === undefined) { - argv["key"] = await promptForRequiredField( - "key", - "Item key / filename. Must not exceed 128 characters." - ); - } - if (argv["next-action"] === undefined) { - argv["next-action"] = await promptForRequiredEnumField( - "next-action", - "The next_action field", - ["INDEX"] as const - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search items upsert", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/items`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - "instance-id": String(argv["instance-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - key: resolveFileToken( - argv["key"] as string | undefined, - "key", - "text" - ), - next_action: argv["next-action"], - wait_for_completion: argv["wait-for-completion"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - requestApi( - client, - "PUT", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/items`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData: Record = {}; - if (argv["key"] !== undefined) - setNestedValue( - bodyData, - ["key"], - resolveFileToken(argv["key"] as string | undefined, "key", "text") - ); - if (argv["next-action"] !== undefined) - setNestedValue(bodyData, ["next_action"], argv["next-action"]); - if (argv["wait-for-completion"] !== undefined) - setNestedValue( - bodyData, - ["wait_for_completion"], - argv["wait-for-completion"] - ); - const result = await withProgress(`Updating`, async () => - requestApi( - client, - "PUT", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/items`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 ai-search items upsert \n\nCreates or updates an indexed item in an AI Search instance.", + ...parameters, + loader: () => import("./upsert.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/jobs/cancel.handler.ts b/packages/cli/src/commands/_generated/ai-search/jobs/cancel.handler.ts new file mode 100644 index 0000000000..4f6772cd20 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/jobs/cancel.handler.ts @@ -0,0 +1,106 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./cancel.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, setNestedValue } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete, promptForRequiredEnumField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search jobs cancel", + classification: { + safeFlags: ["action", "dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["action"] === undefined) { + argv["action"] = await promptForRequiredEnumField( + "action", + "The action field", + ["cancel"] as const + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search jobs cancel", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/jobs/${argv["job-id"] == null ? "" : encodeURIComponent(String(argv["job-id"]))}`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + "instance-id": String(argv["instance-id"] ?? ""), + "job-id": String(argv["job-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + action: argv["action"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This operation cancels the running indexing job.`, + })) + ) { + return; + } + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + requestApi( + client, + "PATCH", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/jobs/${encodeURIComponent(String(argv["job-id"]))}`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData: Record = {}; + if (argv["action"] !== undefined) + setNestedValue(bodyData, ["action"], argv["action"]); + const result = await withProgress(`Updating`, async () => + requestApi( + client, + "PATCH", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/jobs/${encodeURIComponent(String(argv["job-id"]))}`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/jobs/cancel.ts b/packages/cli/src/commands/_generated/ai-search/jobs/cancel.ts index 4e7989f281..467117a387 100644 --- a/packages/cli/src/commands/_generated/ai-search/jobs/cancel.ts +++ b/packages/cli/src/commands/_generated/ai-search/jobs/cancel.ts @@ -1,163 +1,65 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * cancel command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, setNestedValue } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete, promptForRequiredEnumField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search jobs cancel \n\nCancels an in-progress indexing job for an AI Search instance." - ) - .positional("job-id", { - type: "string", - description: "Indexing job ID.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("instance-id", { - type: "string", - description: "AI Search instance ID.", - demandOption: true, - }) - .option("action", { - type: "string", - description: "The action field", + parse: String, + }, + "instance-id": { + kind: "parsed", + brief: "AI Search instance ID.", + parse: String, + }, + action: { + kind: "parsed", + brief: "The action field", + optional: true, choices: ["cancel"], - }) - .coerce("action", (value) => resolveFileToken(value, "action", "text")) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => resolveFileToken(value, "action", "text"), + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { placeholder: "job-id", brief: "Indexing job ID.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "cancel ", describe: "Cancel an indexing job.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search jobs cancel", - classification: { - safeFlags: ["action", "dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["action"] === undefined) { - argv["action"] = await promptForRequiredEnumField( - "action", - "The action field", - ["cancel"] as const - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search jobs cancel", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/jobs/${argv["job-id"] == null ? "" : encodeURIComponent(String(argv["job-id"]))}`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - "instance-id": String(argv["instance-id"] ?? ""), - "job-id": String(argv["job-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - action: argv["action"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This operation cancels the running indexing job.`, - })) - ) { - return; - } - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - requestApi( - client, - "PATCH", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/jobs/${encodeURIComponent(String(argv["job-id"]))}`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData: Record = {}; - if (argv["action"] !== undefined) - setNestedValue(bodyData, ["action"], argv["action"]); - const result = await withProgress(`Updating`, async () => - requestApi( - client, - "PATCH", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/jobs/${encodeURIComponent(String(argv["job-id"]))}`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 ai-search jobs cancel \n\nCancels an in-progress indexing job for an AI Search instance.", + ...parameters, + loader: () => import("./cancel.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/jobs/create.handler.ts b/packages/cli/src/commands/_generated/ai-search/jobs/create.handler.ts new file mode 100644 index 0000000000..f366136c31 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/jobs/create.handler.ts @@ -0,0 +1,94 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, setNestedValue } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search jobs create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search jobs create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/jobs`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + "instance-id": String(argv["instance-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/jobs`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + // Assemble request body from individual flags + const bodyData: Record = {}; + if (argv["description"] !== undefined) + setNestedValue( + bodyData, + ["description"], + resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ) + ); + const result = await withProgress(`Creating`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/jobs`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/jobs/create.ts b/packages/cli/src/commands/_generated/ai-search/jobs/create.ts index f184b16464..1d7dc99b26 100644 --- a/packages/cli/src/commands/_generated/ai-search/jobs/create.ts +++ b/packages/cli/src/commands/_generated/ai-search/jobs/create.ts @@ -1,137 +1,55 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, setNestedValue } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search jobs create \n\nCreates a new indexing job for an AI Search instance." - ) - .positional("instance-id", { - type: "string", - description: "AI Search instance ID.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("description", { - type: "string", - description: "Optional description for the indexing job.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + }, + description: { + kind: "parsed", + brief: "Optional description for the indexing job.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "instance-id", + brief: "AI Search instance ID.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Create new job", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search jobs create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search jobs create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/jobs`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - "instance-id": String(argv["instance-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/jobs`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - // Assemble request body from individual flags - const bodyData: Record = {}; - if (argv["description"] !== undefined) - setNestedValue( - bodyData, - ["description"], - resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ) - ); - const result = await withProgress(`Creating`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/jobs`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 ai-search jobs create \n\nCreates a new indexing job for an AI Search instance.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/jobs/get.handler.ts b/packages/cli/src/commands/_generated/ai-search/jobs/get.handler.ts new file mode 100644 index 0000000000..17940da3d4 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/jobs/get.handler.ts @@ -0,0 +1,54 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search jobs get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search jobs get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/jobs/${argv["job-id"] == null ? "" : encodeURIComponent(String(argv["job-id"]))}`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + "instance-id": String(argv["instance-id"] ?? ""), + "job-id": String(argv["job-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + requestApi( + client, + "GET", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/jobs/${encodeURIComponent(String(argv["job-id"]))}` + ) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/jobs/get.ts b/packages/cli/src/commands/_generated/ai-search/jobs/get.ts index 85ce386124..39929074ac 100644 --- a/packages/cli/src/commands/_generated/ai-search/jobs/get.ts +++ b/packages/cli/src/commands/_generated/ai-search/jobs/get.ts @@ -1,94 +1,44 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search jobs get \n\nRetrieves details for a specific AI Search indexing job." - ) - .positional("job-id", { - type: "string", - description: "Indexing job ID.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("instance-id", { - type: "string", - description: "AI Search instance ID.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + }, + "instance-id": { + kind: "parsed", + brief: "AI Search instance ID.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "job-id", brief: "Indexing job ID.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get a Job Details", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search jobs get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search jobs get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/jobs/${argv["job-id"] == null ? "" : encodeURIComponent(String(argv["job-id"]))}`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - "instance-id": String(argv["instance-id"] ?? ""), - "job-id": String(argv["job-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - requestApi( - client, - "GET", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/jobs/${encodeURIComponent(String(argv["job-id"]))}` - ) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-search jobs get \n\nRetrieves details for a specific AI Search indexing job.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/jobs/index.ts b/packages/cli/src/commands/_generated/ai-search/jobs/index.ts index 9ac1b90caf..71899a1d14 100644 --- a/packages/cli/src/commands/_generated/ai-search/jobs/index.ts +++ b/packages/cli/src/commands/_generated/ai-search/jobs/index.ts @@ -3,28 +3,23 @@ import $create from "./create.js"; import $get from "./get.js"; import $list from "./list.js"; import $logs from "./logs.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * jobs command group * @generated from apis/overlays/ai-search.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "jobs", describe: "Indexing job lifecycle for AI Search instances", - builder: (yargs) => { - return yargs - .command($cancel) - .command($create) - .command($get) - .command($list) - .command($logs) - .demandCommand(1, "Please specify a subcommand"); + routes: { + cancel: $cancel, + create: $create, + get: $get, + list: $list, + logs: $logs, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/jobs/list.handler.ts b/packages/cli/src/commands/_generated/ai-search/jobs/list.handler.ts new file mode 100644 index 0000000000..e0c1b4506f --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/jobs/list.handler.ts @@ -0,0 +1,59 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search jobs list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search jobs list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/jobs`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + "instance-id": String(argv["instance-id"] ?? ""), + }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + requestApi( + client, + "GET", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/jobs`, + { query: queryParams } + ) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/jobs/list.ts b/packages/cli/src/commands/_generated/ai-search/jobs/list.ts index b039dfdb0f..a6a9dec51e 100644 --- a/packages/cli/src/commands/_generated/ai-search/jobs/list.ts +++ b/packages/cli/src/commands/_generated/ai-search/jobs/list.ts @@ -1,96 +1,49 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search jobs list\n\nLists indexing jobs for an AI Search instance." - ) - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("instance-id", { - type: "string", - description: "AI Search instance ID.", - demandOption: true, - }) - .option("page", { type: "number", description: "Page" }) - .option("per-page", { type: "number", description: "Per page" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + }, + "instance-id": { + kind: "parsed", + brief: "AI Search instance ID.", + parse: String, + }, + page: { kind: "parsed", brief: "Page", optional: true, parse: Number }, + "per-page": { + kind: "parsed", + brief: "Per page", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Jobs", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search jobs list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search jobs list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/jobs`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - "instance-id": String(argv["instance-id"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - requestApi( - client, - "GET", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/jobs`, - { query: queryParams } - ) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-search jobs list\n\nLists indexing jobs for an AI Search instance.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/jobs/logs.handler.ts b/packages/cli/src/commands/_generated/ai-search/jobs/logs.handler.ts new file mode 100644 index 0000000000..1509fc178a --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/jobs/logs.handler.ts @@ -0,0 +1,60 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./logs.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search jobs logs", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search jobs logs", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/jobs/${argv["job-id"] == null ? "" : encodeURIComponent(String(argv["job-id"]))}/logs`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + "instance-id": String(argv["instance-id"] ?? ""), + "job-id": String(argv["job-id"] ?? ""), + }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + requestApi( + client, + "GET", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/jobs/${encodeURIComponent(String(argv["job-id"]))}/logs`, + { query: queryParams } + ) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/jobs/logs.ts b/packages/cli/src/commands/_generated/ai-search/jobs/logs.ts index fa3b6b6a15..89f3e89674 100644 --- a/packages/cli/src/commands/_generated/ai-search/jobs/logs.ts +++ b/packages/cli/src/commands/_generated/ai-search/jobs/logs.ts @@ -1,102 +1,51 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * logs command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search jobs logs \n\nLists log entries for an AI Search indexing job." - ) - .positional("job-id", { - type: "string", - description: "Indexing job ID.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("instance-id", { - type: "string", - description: "AI Search instance ID.", - demandOption: true, - }) - .option("page", { type: "number", description: "Page" }) - .option("per-page", { type: "number", description: "Per page" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + }, + "instance-id": { + kind: "parsed", + brief: "AI Search instance ID.", + parse: String, + }, + page: { kind: "parsed", brief: "Page", optional: true, parse: Number }, + "per-page": { + kind: "parsed", + brief: "Per page", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "job-id", brief: "Indexing job ID.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "logs ", describe: "List Job Logs", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search jobs logs", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search jobs logs", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/jobs/${argv["job-id"] == null ? "" : encodeURIComponent(String(argv["job-id"]))}/logs`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - "instance-id": String(argv["instance-id"] ?? ""), - "job-id": String(argv["job-id"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - requestApi( - client, - "GET", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/jobs/${encodeURIComponent(String(argv["job-id"]))}/logs`, - { query: queryParams } - ) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-search jobs logs \n\nLists log entries for an AI Search indexing job.", + ...parameters, + loader: () => import("./logs.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/list.handler.ts b/packages/cli/src/commands/_generated/ai-search/list.handler.ts new file mode 100644 index 0000000000..dc15530822 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/list.handler.ts @@ -0,0 +1,59 @@ +import operation from "../_operations/ai-search/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search list", + classification: { + safeFlags: ["order-by", "order-by-direction", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + search: argv["search"], + hostname: argv["hostname"], + order_by: argv["order-by"], + order_by_direction: argv["order-by-direction"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances`, + pathParams: { namespace: String(argv["namespace"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + namespace: argv["namespace"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/list.ts b/packages/cli/src/commands/_generated/ai-search/list.ts index ccc7e29e00..4d2a1d2660 100644 --- a/packages/cli/src/commands/_generated/ai-search/list.ts +++ b/packages/cli/src/commands/_generated/ai-search/list.ts @@ -1,112 +1,74 @@ -import operation from "../_operations/ai-search/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage("$0 ai-search list\n\nLists all AI Search instances in the account.") - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("page", { type: "number", description: "Page number (1-indexed)." }) - .option("per-page", { - type: "number", - description: "Number of results per page.", - }) - .option("search", { - type: "string", - description: + parse: String, + }, + page: { + kind: "parsed", + brief: "Page number (1-indexed).", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Number of results per page.", + optional: true, + parse: Number, + }, + search: { + kind: "parsed", + brief: "Filter instances whose id contains this string (case-insensitive).", - }) - .option("hostname", { - type: "string", - description: + optional: true, + parse: String, + }, + hostname: { + kind: "parsed", + brief: "Return only instances with this exact Search for Agents hostname (case-insensitive).", - }) - .option("order-by", { - type: "string", - description: "Field to order results by.", - choices: ["created_at"], - }) - .option("order-by-direction", { - type: "string", - description: "Order direction.", - choices: ["asc", "desc"], - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "order-by": { + kind: "enum", + brief: "Field to order results by.", + values: ["created_at"], + optional: true, + }, + "order-by-direction": { + kind: "enum", + brief: "Order direction.", + values: ["asc", "desc"], + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List AI Search instances.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search list", - classification: { - safeFlags: ["order-by", "order-by-direction", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - search: argv["search"], - hostname: argv["hostname"], - order_by: argv["order-by"], - order_by_direction: argv["order-by-direction"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances`, - pathParams: { namespace: String(argv["namespace"] ?? "") }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - namespace: argv["namespace"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: "$0 ai-search list\n\nLists all AI Search instances in the account.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/move.handler.ts b/packages/cli/src/commands/_generated/ai-search/move.handler.ts new file mode 100644 index 0000000000..0603b65dda --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/move.handler.ts @@ -0,0 +1,107 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./move.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, setNestedValue } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search move", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["destination-namespace"] === undefined) { + argv["destination-namespace"] = await promptForRequiredField( + "destination-namespace", + "Namespace to move the instance into." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search move", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["source-namespace"] == null ? "" : encodeURIComponent(String(argv["source-namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}`, + pathParams: { + "source-namespace": String(argv["source-namespace"] ?? ""), + "instance-id": String(argv["instance-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + new_namespace: resolveFileToken( + argv["destination-namespace"] as string | undefined, + "destination-namespace", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + requestApi( + client, + "PATCH", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["source-namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData: Record = {}; + if (argv["destination-namespace"] !== undefined) + setNestedValue( + bodyData, + ["new_namespace"], + resolveFileToken( + argv["destination-namespace"] as string | undefined, + "destination-namespace", + "text" + ) + ); + const result = await withProgress(`Updating`, async () => + requestApi( + client, + "PATCH", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["source-namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/move.ts b/packages/cli/src/commands/_generated/ai-search/move.ts index bf9c9cb177..aae587307f 100644 --- a/packages/cli/src/commands/_generated/ai-search/move.ts +++ b/packages/cli/src/commands/_generated/ai-search/move.ts @@ -1,150 +1,55 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * move command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, setNestedValue } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search move \n\nMoves an instance from its current namespace to the specified target namespace. Use 'default' with --destination-namespace to move the instance back to the default namespace. Fails with 400 if the target namespace already has an instance with the same id (ids must be unique within a namespace — the same id can exist in different namespaces)." - ) - .positional("instance-id", { - type: "string", - description: "AI Search instance ID.", - demandOption: true, - }) - .option("source-namespace", { - type: "string", - description: "Namespace currently containing the instance.", +const parameters = { + flags: { + "source-namespace": { + kind: "parsed", + brief: "Namespace currently containing the instance.", default: "default", - }) - .option("destination-namespace", { - type: "string", - description: "Namespace to move the instance into.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + }, + "destination-namespace": { + kind: "parsed", + brief: "Namespace to move the instance into.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "instance-id", + brief: "AI Search instance ID.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "move ", describe: "Move an instance to a different namespace.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search move", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["destination-namespace"] === undefined) { - argv["destination-namespace"] = await promptForRequiredField( - "destination-namespace", - "Namespace to move the instance into." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search move", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["source-namespace"] == null ? "" : encodeURIComponent(String(argv["source-namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}`, - pathParams: { - "source-namespace": String(argv["source-namespace"] ?? ""), - "instance-id": String(argv["instance-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - new_namespace: resolveFileToken( - argv["destination-namespace"] as string | undefined, - "destination-namespace", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - requestApi( - client, - "PATCH", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["source-namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData: Record = {}; - if (argv["destination-namespace"] !== undefined) - setNestedValue( - bodyData, - ["new_namespace"], - resolveFileToken( - argv["destination-namespace"] as string | undefined, - "destination-namespace", - "text" - ) - ); - const result = await withProgress(`Updating`, async () => - requestApi( - client, - "PATCH", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["source-namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 ai-search move \n\nMoves an instance from its current namespace to the specified target namespace. Use 'default' with --destination-namespace to move the instance back to the default namespace. Fails with 400 if the target namespace already has an instance with the same id (ids must be unique within a namespace — the same id can exist in different namespaces).", + ...parameters, + loader: () => import("./move.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/multi-chat-completions.handler.ts b/packages/cli/src/commands/_generated/ai-search/multi-chat-completions.handler.ts new file mode 100644 index 0000000000..7fd44bb448 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/multi-chat-completions.handler.ts @@ -0,0 +1,341 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./multi-chat-completions.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { + compactBody, + parseBody, + parseJsonMap, + parseObjectArray, + setNestedValue, +} from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search multi-chat-completions", + classification: { + safeFlags: [ + "ai-search-options-cache-cache-threshold", + "ai-search-options-cache-enabled", + "ai-search-options-query-rewrite-enabled", + "ai-search-options-reranking-enabled", + "ai-search-options-retrieval-fusion-method", + "ai-search-options-retrieval-keyword-match-mode", + "ai-search-options-retrieval-retrieval-type", + "ai-search-options-retrieval-return-on-failure", + "stream", + "dry-run", + ], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["ai-search-options-instance-ids"] === undefined) { + throw new Error( + "--ai-search-options-instance-ids is required (or pass --body with this field set)." + ); + } + if (argv["messages"] === undefined) { + throw new Error( + "--messages is required (or pass --body with this field set)." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search multi-chat-completions", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/chat/completions`, + pathParams: { namespace: String(argv["namespace"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody( + { + ai_search_options: { + cache: { + cache_threshold: + argv["ai-search-options-cache-cache-threshold"], + enabled: argv["ai-search-options-cache-enabled"], + }, + custom_metadata: parseJsonMap( + argv["ai-search-options-custom-metadata"], + "ai-search-options-custom-metadata" + ), + instance_ids: argv["ai-search-options-instance-ids"], + query_rewrite: { + enabled: + argv["ai-search-options-query-rewrite-enabled"], + model: resolveFileToken( + argv["ai-search-options-query-rewrite-model"] as + | string + | undefined, + "ai-search-options-query-rewrite-model", + "text" + ), + rewrite_prompt: resolveFileToken( + argv[ + "ai-search-options-query-rewrite-rewrite-prompt" + ] as string | undefined, + "ai-search-options-query-rewrite-rewrite-prompt", + "text" + ), + }, + reranking: { + enabled: argv["ai-search-options-reranking-enabled"], + match_threshold: + argv["ai-search-options-reranking-match-threshold"], + model: resolveFileToken( + argv["ai-search-options-reranking-model"] as + | string + | undefined, + "ai-search-options-reranking-model", + "text" + ), + }, + retrieval: { + boost_by: parseObjectArray( + argv["ai-search-options-retrieval-boost-by"], + "ai-search-options-retrieval-boost-by" + ), + context_expansion: + argv["ai-search-options-retrieval-context-expansion"], + filters: parseJsonMap( + argv["ai-search-options-retrieval-filters"], + "ai-search-options-retrieval-filters" + ), + fusion_method: + argv["ai-search-options-retrieval-fusion-method"], + keyword_match_mode: + argv[ + "ai-search-options-retrieval-keyword-match-mode" + ], + match_threshold: + argv["ai-search-options-retrieval-match-threshold"], + max_num_results: + argv["ai-search-options-retrieval-max-num-results"], + retrieval_type: + argv["ai-search-options-retrieval-retrieval-type"], + return_on_failure: + argv["ai-search-options-retrieval-return-on-failure"], + }, + }, + messages: parseObjectArray(argv["messages"], "messages"), + model: resolveFileToken( + argv["model"] as string | undefined, + "model", + "text" + ), + stream: argv["stream"], + }, + [ + ["ai_search_options", "custom_metadata"], + ["ai_search_options", "retrieval", "filters"], + ] + ), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/chat/completions`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData: Record = {}; + if (argv["ai-search-options-cache-cache-threshold"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "cache", "cache_threshold"], + argv["ai-search-options-cache-cache-threshold"] + ); + if (argv["ai-search-options-cache-enabled"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "cache", "enabled"], + argv["ai-search-options-cache-enabled"] + ); + if (argv["ai-search-options-custom-metadata"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "custom_metadata"], + parseJsonMap( + argv["ai-search-options-custom-metadata"], + "ai-search-options-custom-metadata" + ) + ); + if (argv["ai-search-options-instance-ids"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "instance_ids"], + argv["ai-search-options-instance-ids"] + ); + if (argv["ai-search-options-query-rewrite-enabled"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "query_rewrite", "enabled"], + argv["ai-search-options-query-rewrite-enabled"] + ); + if (argv["ai-search-options-query-rewrite-model"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "query_rewrite", "model"], + resolveFileToken( + argv["ai-search-options-query-rewrite-model"] as string | undefined, + "ai-search-options-query-rewrite-model", + "text" + ) + ); + if (argv["ai-search-options-query-rewrite-rewrite-prompt"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "query_rewrite", "rewrite_prompt"], + resolveFileToken( + argv["ai-search-options-query-rewrite-rewrite-prompt"] as + | string + | undefined, + "ai-search-options-query-rewrite-rewrite-prompt", + "text" + ) + ); + if (argv["ai-search-options-reranking-enabled"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "reranking", "enabled"], + argv["ai-search-options-reranking-enabled"] + ); + if (argv["ai-search-options-reranking-match-threshold"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "reranking", "match_threshold"], + argv["ai-search-options-reranking-match-threshold"] + ); + if (argv["ai-search-options-reranking-model"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "reranking", "model"], + resolveFileToken( + argv["ai-search-options-reranking-model"] as string | undefined, + "ai-search-options-reranking-model", + "text" + ) + ); + if (argv["ai-search-options-retrieval-boost-by"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "boost_by"], + parseObjectArray( + argv["ai-search-options-retrieval-boost-by"], + "ai-search-options-retrieval-boost-by" + ) + ); + if (argv["ai-search-options-retrieval-context-expansion"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "context_expansion"], + argv["ai-search-options-retrieval-context-expansion"] + ); + if (argv["ai-search-options-retrieval-filters"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "filters"], + parseJsonMap( + argv["ai-search-options-retrieval-filters"], + "ai-search-options-retrieval-filters" + ) + ); + if (argv["ai-search-options-retrieval-fusion-method"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "fusion_method"], + argv["ai-search-options-retrieval-fusion-method"] + ); + if (argv["ai-search-options-retrieval-keyword-match-mode"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "keyword_match_mode"], + argv["ai-search-options-retrieval-keyword-match-mode"] + ); + if (argv["ai-search-options-retrieval-match-threshold"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "match_threshold"], + argv["ai-search-options-retrieval-match-threshold"] + ); + if (argv["ai-search-options-retrieval-max-num-results"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "max_num_results"], + argv["ai-search-options-retrieval-max-num-results"] + ); + if (argv["ai-search-options-retrieval-retrieval-type"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "retrieval_type"], + argv["ai-search-options-retrieval-retrieval-type"] + ); + if (argv["ai-search-options-retrieval-return-on-failure"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "return_on_failure"], + argv["ai-search-options-retrieval-return-on-failure"] + ); + if (argv["messages"] !== undefined) + setNestedValue( + bodyData, + ["messages"], + parseObjectArray(argv["messages"], "messages") + ); + if (argv["model"] !== undefined) + setNestedValue( + bodyData, + ["model"], + resolveFileToken(argv["model"] as string | undefined, "model", "text") + ); + if (argv["stream"] !== undefined) + setNestedValue(bodyData, ["stream"], argv["stream"]); + const result = await withProgress(`Creating`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/chat/completions`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/multi-chat-completions.ts b/packages/cli/src/commands/_generated/ai-search/multi-chat-completions.ts index 4c43e02ad3..8340728858 100644 --- a/packages/cli/src/commands/_generated/ai-search/multi-chat-completions.ts +++ b/packages/cli/src/commands/_generated/ai-search/multi-chat-completions.ts @@ -1,518 +1,211 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * multi-chat-completions command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { - compactBody, - parseBody, - parseJsonMap, - parseObjectArray, - setNestedValue, -} from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search multi-chat-completions\n\nPerforms a chat completion request against multiple AI Search instances in parallel, merging retrieved content as context for generating a response." - ) - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("ai-search-options-cache-cache-threshold", { - type: "string", - description: "The ai_search_options.cache.cache_threshold field", + parse: String, + }, + "ai-search-options-cache-cache-threshold": { + kind: "parsed", + brief: "The ai_search_options.cache.cache_threshold field", + optional: true, choices: [ "super_strict_match", "close_enough", "flexible_friend", "anything_goes", ], - }) - .coerce("ai-search-options-cache-cache-threshold", (value) => - resolveFileToken(value, "ai-search-options-cache-cache-threshold", "text") - ) - .option("ai-search-options-cache-enabled", { - type: "boolean", - description: "The ai_search_options.cache.enabled field", - }) - .option("ai-search-options-custom-metadata", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "ai-search-options-cache-cache-threshold", + "text" + ), + }, + "ai-search-options-cache-enabled": { + kind: "boolean", + brief: "The ai_search_options.cache.enabled field", + optional: true, + }, + "ai-search-options-custom-metadata": { + kind: "parsed", + brief: "Metadata added to AI Gateway logs for requests this operation triggers. Accepts up to 2 string, number, or boolean entries. Reserved keys: 'ai-search', 'task', 'origin', and any key beginning with 'cf.'. Provide as a JSON object or @path/to/file.json. Shape: {\"\": (string | number | boolean)}.", - }) - .option("ai-search-options-instance-ids", { - type: "string", - array: true, - description: "The ai_search_options.instance_ids field", - }) - .option("ai-search-options-query-rewrite-enabled", { - type: "boolean", - description: "The ai_search_options.query_rewrite.enabled field", - }) - .option("ai-search-options-query-rewrite-model", { - type: "string", - description: + optional: true, + parse: String, + }, + "ai-search-options-instance-ids": { + kind: "parsed", + brief: "The ai_search_options.instance_ids field", + variadic: true, + optional: true, + parse: String, + }, + "ai-search-options-query-rewrite-enabled": { + kind: "boolean", + brief: "The ai_search_options.query_rewrite.enabled field", + optional: true, + }, + "ai-search-options-query-rewrite-model": { + kind: "parsed", + brief: "A Workers AI model ID or an AI Gateway model ID compatible with the OpenAI Chat Completions API. An empty string uses the configured or default model.", - }) - .option("ai-search-options-query-rewrite-rewrite-prompt", { - type: "string", - description: "The ai_search_options.query_rewrite.rewrite_prompt field", - }) - .option("ai-search-options-reranking-enabled", { - type: "boolean", - description: "The ai_search_options.reranking.enabled field", - }) - .option("ai-search-options-reranking-match-threshold", { - type: "number", - description: + optional: true, + parse: String, + }, + "ai-search-options-query-rewrite-rewrite-prompt": { + kind: "parsed", + brief: "The ai_search_options.query_rewrite.rewrite_prompt field", + optional: true, + parse: String, + }, + "ai-search-options-reranking-enabled": { + kind: "boolean", + brief: "The ai_search_options.reranking.enabled field", + optional: true, + }, + "ai-search-options-reranking-match-threshold": { + kind: "parsed", + brief: "Minimum reranker relevance score a chunk must reach to be returned. When omitted, falls back to the instance-level score_threshold, then to 0.4.", - }) - .option("ai-search-options-reranking-model", { - type: "string", - description: "The ai_search_options.reranking.model field", - }) - .option("ai-search-options-retrieval-boost-by", { - type: "string", - description: + optional: true, + parse: Number, + }, + "ai-search-options-reranking-model": { + kind: "parsed", + brief: "The ai_search_options.reranking.model field", + optional: true, + parse: String, + }, + "ai-search-options-retrieval-boost-by": { + kind: "parsed", + brief: 'Metadata fields to boost search results by. Overrides the instance-level boost_by config. Direction defaults to \'asc\' for numeric/datetime fields, \'exists\' for text/boolean fields. Fields must match \'timestamp\' or a defined custom_metadata field. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"field": string, "direction"?: "asc" | "desc" | "exists" | ...more}]. ? marks optional keys.', - }) - .option("ai-search-options-retrieval-context-expansion", { - type: "number", - description: "The ai_search_options.retrieval.context_expansion field", - }) - .option("ai-search-options-retrieval-filters", { - type: "string", - description: + optional: true, + parse: String, + }, + "ai-search-options-retrieval-context-expansion": { + kind: "parsed", + brief: "The ai_search_options.retrieval.context_expansion field", + optional: true, + parse: Number, + }, + "ai-search-options-retrieval-filters": { + kind: "parsed", + brief: 'The ai_search_options.retrieval.filters field. Provide as a JSON object or @path/to/file.json. Shape: {"": unknown}.', - }) - .option("ai-search-options-retrieval-fusion-method", { - type: "string", - description: "The ai_search_options.retrieval.fusion_method field", + optional: true, + parse: String, + }, + "ai-search-options-retrieval-fusion-method": { + kind: "parsed", + brief: "The ai_search_options.retrieval.fusion_method field", + optional: true, choices: ["max", "rrf"], - }) - .coerce("ai-search-options-retrieval-fusion-method", (value) => - resolveFileToken( - value, - "ai-search-options-retrieval-fusion-method", - "text" - ) - ) - .option("ai-search-options-retrieval-keyword-match-mode", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "ai-search-options-retrieval-fusion-method", + "text" + ), + }, + "ai-search-options-retrieval-keyword-match-mode": { + kind: "parsed", + brief: "Controls which documents become candidates for BM25 scoring. 'and' restricts candidates to documents containing all query terms; 'or' includes any document containing at least one term and ranks results according to BM25 relevance. When omitted, falls back to the instance-level retrieval_options.keyword_match_mode, then to 'and'.", + optional: true, choices: ["and", "or"], - }) - .coerce("ai-search-options-retrieval-keyword-match-mode", (value) => - resolveFileToken( - value, - "ai-search-options-retrieval-keyword-match-mode", - "text" - ) - ) - .option("ai-search-options-retrieval-match-threshold", { - type: "number", - description: + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "ai-search-options-retrieval-keyword-match-mode", + "text" + ), + }, + "ai-search-options-retrieval-match-threshold": { + kind: "parsed", + brief: "Minimum score a chunk must reach to be returned. When omitted, each instance's chunks are filtered by that instance's score_threshold, capped at the lower of the first instance's score_threshold and 0.4.", - }) - .option("ai-search-options-retrieval-max-num-results", { - type: "number", - description: + optional: true, + parse: Number, + }, + "ai-search-options-retrieval-max-num-results": { + kind: "parsed", + brief: "Maximum number of merged results to return. When omitted, defaults to the first instance's max_num_results, then 10.", - }) - .option("ai-search-options-retrieval-retrieval-type", { - type: "string", - description: "The ai_search_options.retrieval.retrieval_type field", + optional: true, + parse: Number, + }, + "ai-search-options-retrieval-retrieval-type": { + kind: "parsed", + brief: "The ai_search_options.retrieval.retrieval_type field", + optional: true, choices: ["vector", "keyword", "hybrid"], - }) - .coerce("ai-search-options-retrieval-retrieval-type", (value) => - resolveFileToken( - value, - "ai-search-options-retrieval-retrieval-type", - "text" - ) - ) - .option("ai-search-options-retrieval-return-on-failure", { - type: "boolean", - description: "The ai_search_options.retrieval.return_on_failure field", - }) - .option("messages", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "ai-search-options-retrieval-retrieval-type", + "text" + ), + }, + "ai-search-options-retrieval-return-on-failure": { + kind: "boolean", + brief: "The ai_search_options.retrieval.return_on_failure field", + optional: true, + }, + messages: { + kind: "parsed", + brief: 'The messages field. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"content": (string | [{...}] | null), "role": "system" | "developer" | "user" | ...more, "": unknown}].', - }) - .option("model", { - type: "string", - description: + optional: true, + parse: String, + }, + model: { + kind: "parsed", + brief: "A Workers AI model ID or an AI Gateway model ID compatible with the OpenAI Chat Completions API. An empty string uses the configured or default model.", - }) - .option("stream", { type: "boolean", description: "The stream field" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + stream: { kind: "boolean", brief: "The stream field", optional: true }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "multi-chat-completions", describe: "Multi-Instance Chat Completions", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search multi-chat-completions", - classification: { - safeFlags: [ - "ai-search-options-cache-cache-threshold", - "ai-search-options-cache-enabled", - "ai-search-options-query-rewrite-enabled", - "ai-search-options-reranking-enabled", - "ai-search-options-retrieval-fusion-method", - "ai-search-options-retrieval-keyword-match-mode", - "ai-search-options-retrieval-retrieval-type", - "ai-search-options-retrieval-return-on-failure", - "stream", - "dry-run", - ], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["ai-search-options-instance-ids"] === undefined) { - throw new Error( - "--ai-search-options-instance-ids is required (or pass --body with this field set)." - ); - } - if (argv["messages"] === undefined) { - throw new Error( - "--messages is required (or pass --body with this field set)." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search multi-chat-completions", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/chat/completions`, - pathParams: { namespace: String(argv["namespace"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody( - { - ai_search_options: { - cache: { - cache_threshold: - argv["ai-search-options-cache-cache-threshold"], - enabled: argv["ai-search-options-cache-enabled"], - }, - custom_metadata: parseJsonMap( - argv["ai-search-options-custom-metadata"], - "ai-search-options-custom-metadata" - ), - instance_ids: argv["ai-search-options-instance-ids"], - query_rewrite: { - enabled: - argv["ai-search-options-query-rewrite-enabled"], - model: resolveFileToken( - argv["ai-search-options-query-rewrite-model"] as - | string - | undefined, - "ai-search-options-query-rewrite-model", - "text" - ), - rewrite_prompt: resolveFileToken( - argv[ - "ai-search-options-query-rewrite-rewrite-prompt" - ] as string | undefined, - "ai-search-options-query-rewrite-rewrite-prompt", - "text" - ), - }, - reranking: { - enabled: argv["ai-search-options-reranking-enabled"], - match_threshold: - argv["ai-search-options-reranking-match-threshold"], - model: resolveFileToken( - argv["ai-search-options-reranking-model"] as - | string - | undefined, - "ai-search-options-reranking-model", - "text" - ), - }, - retrieval: { - boost_by: parseObjectArray( - argv["ai-search-options-retrieval-boost-by"], - "ai-search-options-retrieval-boost-by" - ), - context_expansion: - argv[ - "ai-search-options-retrieval-context-expansion" - ], - filters: parseJsonMap( - argv["ai-search-options-retrieval-filters"], - "ai-search-options-retrieval-filters" - ), - fusion_method: - argv["ai-search-options-retrieval-fusion-method"], - keyword_match_mode: - argv[ - "ai-search-options-retrieval-keyword-match-mode" - ], - match_threshold: - argv["ai-search-options-retrieval-match-threshold"], - max_num_results: - argv["ai-search-options-retrieval-max-num-results"], - retrieval_type: - argv["ai-search-options-retrieval-retrieval-type"], - return_on_failure: - argv[ - "ai-search-options-retrieval-return-on-failure" - ], - }, - }, - messages: parseObjectArray(argv["messages"], "messages"), - model: resolveFileToken( - argv["model"] as string | undefined, - "model", - "text" - ), - stream: argv["stream"], - }, - [ - ["ai_search_options", "custom_metadata"], - ["ai_search_options", "retrieval", "filters"], - ] - ), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/chat/completions`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData: Record = {}; - if (argv["ai-search-options-cache-cache-threshold"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "cache", "cache_threshold"], - argv["ai-search-options-cache-cache-threshold"] - ); - if (argv["ai-search-options-cache-enabled"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "cache", "enabled"], - argv["ai-search-options-cache-enabled"] - ); - if (argv["ai-search-options-custom-metadata"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "custom_metadata"], - parseJsonMap( - argv["ai-search-options-custom-metadata"], - "ai-search-options-custom-metadata" - ) - ); - if (argv["ai-search-options-instance-ids"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "instance_ids"], - argv["ai-search-options-instance-ids"] - ); - if (argv["ai-search-options-query-rewrite-enabled"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "query_rewrite", "enabled"], - argv["ai-search-options-query-rewrite-enabled"] - ); - if (argv["ai-search-options-query-rewrite-model"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "query_rewrite", "model"], - resolveFileToken( - argv["ai-search-options-query-rewrite-model"] as - | string - | undefined, - "ai-search-options-query-rewrite-model", - "text" - ) - ); - if ( - argv["ai-search-options-query-rewrite-rewrite-prompt"] !== undefined - ) - setNestedValue( - bodyData, - ["ai_search_options", "query_rewrite", "rewrite_prompt"], - resolveFileToken( - argv["ai-search-options-query-rewrite-rewrite-prompt"] as - | string - | undefined, - "ai-search-options-query-rewrite-rewrite-prompt", - "text" - ) - ); - if (argv["ai-search-options-reranking-enabled"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "reranking", "enabled"], - argv["ai-search-options-reranking-enabled"] - ); - if (argv["ai-search-options-reranking-match-threshold"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "reranking", "match_threshold"], - argv["ai-search-options-reranking-match-threshold"] - ); - if (argv["ai-search-options-reranking-model"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "reranking", "model"], - resolveFileToken( - argv["ai-search-options-reranking-model"] as string | undefined, - "ai-search-options-reranking-model", - "text" - ) - ); - if (argv["ai-search-options-retrieval-boost-by"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "boost_by"], - parseObjectArray( - argv["ai-search-options-retrieval-boost-by"], - "ai-search-options-retrieval-boost-by" - ) - ); - if (argv["ai-search-options-retrieval-context-expansion"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "context_expansion"], - argv["ai-search-options-retrieval-context-expansion"] - ); - if (argv["ai-search-options-retrieval-filters"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "filters"], - parseJsonMap( - argv["ai-search-options-retrieval-filters"], - "ai-search-options-retrieval-filters" - ) - ); - if (argv["ai-search-options-retrieval-fusion-method"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "fusion_method"], - argv["ai-search-options-retrieval-fusion-method"] - ); - if ( - argv["ai-search-options-retrieval-keyword-match-mode"] !== undefined - ) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "keyword_match_mode"], - argv["ai-search-options-retrieval-keyword-match-mode"] - ); - if (argv["ai-search-options-retrieval-match-threshold"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "match_threshold"], - argv["ai-search-options-retrieval-match-threshold"] - ); - if (argv["ai-search-options-retrieval-max-num-results"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "max_num_results"], - argv["ai-search-options-retrieval-max-num-results"] - ); - if (argv["ai-search-options-retrieval-retrieval-type"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "retrieval_type"], - argv["ai-search-options-retrieval-retrieval-type"] - ); - if (argv["ai-search-options-retrieval-return-on-failure"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "return_on_failure"], - argv["ai-search-options-retrieval-return-on-failure"] - ); - if (argv["messages"] !== undefined) - setNestedValue( - bodyData, - ["messages"], - parseObjectArray(argv["messages"], "messages") - ); - if (argv["model"] !== undefined) - setNestedValue( - bodyData, - ["model"], - resolveFileToken( - argv["model"] as string | undefined, - "model", - "text" - ) - ); - if (argv["stream"] !== undefined) - setNestedValue(bodyData, ["stream"], argv["stream"]); - const result = await withProgress(`Creating`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/chat/completions`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 ai-search multi-chat-completions\n\nPerforms a chat completion request against multiple AI Search instances in parallel, merging retrieved content as context for generating a response.", + ...parameters, + loader: () => import("./multi-chat-completions.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/multi-search.handler.ts b/packages/cli/src/commands/_generated/ai-search/multi-search.handler.ts new file mode 100644 index 0000000000..8ff0c93088 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/multi-search.handler.ts @@ -0,0 +1,330 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./multi-search.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { + compactBody, + mergeBodyPositionals, + parseBody, + parseJsonMap, + parseObjectArray, + setNestedValue, +} from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search multi-search", + classification: { + safeFlags: [ + "ai-search-options-cache-cache-threshold", + "ai-search-options-cache-enabled", + "ai-search-options-query-rewrite-enabled", + "ai-search-options-reranking-enabled", + "ai-search-options-retrieval-fusion-method", + "ai-search-options-retrieval-keyword-match-mode", + "ai-search-options-retrieval-retrieval-type", + "ai-search-options-retrieval-return-on-failure", + "dry-run", + ], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["ai-search-options-instance-ids"] === undefined) { + throw new Error( + "--ai-search-options-instance-ids is required (or pass --body with this field set)." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search multi-search", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/search`, + pathParams: { namespace: String(argv["namespace"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? mergeBodyPositionals(parseBody(argv.body), [ + { name: "query", field: "query", value: argv["query"] }, + ]) + : compactBody( + { + ai_search_options: { + cache: { + cache_threshold: + argv["ai-search-options-cache-cache-threshold"], + enabled: argv["ai-search-options-cache-enabled"], + }, + custom_metadata: parseJsonMap( + argv["ai-search-options-custom-metadata"], + "ai-search-options-custom-metadata" + ), + instance_ids: argv["ai-search-options-instance-ids"], + query_rewrite: { + enabled: + argv["ai-search-options-query-rewrite-enabled"], + model: resolveFileToken( + argv["ai-search-options-query-rewrite-model"] as + | string + | undefined, + "ai-search-options-query-rewrite-model", + "text" + ), + rewrite_prompt: resolveFileToken( + argv[ + "ai-search-options-query-rewrite-rewrite-prompt" + ] as string | undefined, + "ai-search-options-query-rewrite-rewrite-prompt", + "text" + ), + }, + reranking: { + enabled: argv["ai-search-options-reranking-enabled"], + match_threshold: + argv["ai-search-options-reranking-match-threshold"], + model: resolveFileToken( + argv["ai-search-options-reranking-model"] as + | string + | undefined, + "ai-search-options-reranking-model", + "text" + ), + }, + retrieval: { + boost_by: parseObjectArray( + argv["ai-search-options-retrieval-boost-by"], + "ai-search-options-retrieval-boost-by" + ), + context_expansion: + argv["ai-search-options-retrieval-context-expansion"], + filters: parseJsonMap( + argv["ai-search-options-retrieval-filters"], + "ai-search-options-retrieval-filters" + ), + fusion_method: + argv["ai-search-options-retrieval-fusion-method"], + keyword_match_mode: + argv[ + "ai-search-options-retrieval-keyword-match-mode" + ], + match_threshold: + argv["ai-search-options-retrieval-match-threshold"], + max_num_results: + argv["ai-search-options-retrieval-max-num-results"], + retrieval_type: + argv["ai-search-options-retrieval-retrieval-type"], + return_on_failure: + argv["ai-search-options-retrieval-return-on-failure"], + }, + }, + messages: parseObjectArray(argv["messages"], "messages"), + query: argv["query"], + }, + [ + ["ai_search_options", "custom_metadata"], + ["ai_search_options", "retrieval", "filters"], + ] + ), + }); + return; + } + const parsedBody = + argv.body !== undefined + ? mergeBodyPositionals(parseBody(argv.body), [ + { name: "query", field: "query", value: argv["query"] }, + ]) + : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/search`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData: Record = {}; + if (argv["ai-search-options-cache-cache-threshold"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "cache", "cache_threshold"], + argv["ai-search-options-cache-cache-threshold"] + ); + if (argv["ai-search-options-cache-enabled"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "cache", "enabled"], + argv["ai-search-options-cache-enabled"] + ); + if (argv["ai-search-options-custom-metadata"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "custom_metadata"], + parseJsonMap( + argv["ai-search-options-custom-metadata"], + "ai-search-options-custom-metadata" + ) + ); + if (argv["ai-search-options-instance-ids"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "instance_ids"], + argv["ai-search-options-instance-ids"] + ); + if (argv["ai-search-options-query-rewrite-enabled"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "query_rewrite", "enabled"], + argv["ai-search-options-query-rewrite-enabled"] + ); + if (argv["ai-search-options-query-rewrite-model"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "query_rewrite", "model"], + resolveFileToken( + argv["ai-search-options-query-rewrite-model"] as string | undefined, + "ai-search-options-query-rewrite-model", + "text" + ) + ); + if (argv["ai-search-options-query-rewrite-rewrite-prompt"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "query_rewrite", "rewrite_prompt"], + resolveFileToken( + argv["ai-search-options-query-rewrite-rewrite-prompt"] as + | string + | undefined, + "ai-search-options-query-rewrite-rewrite-prompt", + "text" + ) + ); + if (argv["ai-search-options-reranking-enabled"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "reranking", "enabled"], + argv["ai-search-options-reranking-enabled"] + ); + if (argv["ai-search-options-reranking-match-threshold"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "reranking", "match_threshold"], + argv["ai-search-options-reranking-match-threshold"] + ); + if (argv["ai-search-options-reranking-model"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "reranking", "model"], + resolveFileToken( + argv["ai-search-options-reranking-model"] as string | undefined, + "ai-search-options-reranking-model", + "text" + ) + ); + if (argv["ai-search-options-retrieval-boost-by"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "boost_by"], + parseObjectArray( + argv["ai-search-options-retrieval-boost-by"], + "ai-search-options-retrieval-boost-by" + ) + ); + if (argv["ai-search-options-retrieval-context-expansion"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "context_expansion"], + argv["ai-search-options-retrieval-context-expansion"] + ); + if (argv["ai-search-options-retrieval-filters"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "filters"], + parseJsonMap( + argv["ai-search-options-retrieval-filters"], + "ai-search-options-retrieval-filters" + ) + ); + if (argv["ai-search-options-retrieval-fusion-method"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "fusion_method"], + argv["ai-search-options-retrieval-fusion-method"] + ); + if (argv["ai-search-options-retrieval-keyword-match-mode"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "keyword_match_mode"], + argv["ai-search-options-retrieval-keyword-match-mode"] + ); + if (argv["ai-search-options-retrieval-match-threshold"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "match_threshold"], + argv["ai-search-options-retrieval-match-threshold"] + ); + if (argv["ai-search-options-retrieval-max-num-results"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "max_num_results"], + argv["ai-search-options-retrieval-max-num-results"] + ); + if (argv["ai-search-options-retrieval-retrieval-type"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "retrieval_type"], + argv["ai-search-options-retrieval-retrieval-type"] + ); + if (argv["ai-search-options-retrieval-return-on-failure"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "return_on_failure"], + argv["ai-search-options-retrieval-return-on-failure"] + ); + if (argv["messages"] !== undefined) + setNestedValue( + bodyData, + ["messages"], + parseObjectArray(argv["messages"], "messages") + ); + if (argv["query"] !== undefined) bodyData["query"] = argv["query"]; + const result = await withProgress(`Creating`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/search`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/multi-search.ts b/packages/cli/src/commands/_generated/ai-search/multi-search.ts index e18e651bce..c316a320cf 100644 --- a/packages/cli/src/commands/_generated/ai-search/multi-search.ts +++ b/packages/cli/src/commands/_generated/ai-search/multi-search.ts @@ -1,501 +1,210 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * multi-search command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { - compactBody, - mergeBodyPositionals, - parseBody, - parseJsonMap, - parseObjectArray, - setNestedValue, -} from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search multi-search [query]\n\nPerforms a semantic search query against multiple AI Search instances in parallel, merging the retrieved results into a single ranked response." - ) - .positional("query", { - type: "string", - description: "Text to search for.", - }) - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("ai-search-options-cache-cache-threshold", { - type: "string", - description: "The ai_search_options.cache.cache_threshold field", + parse: String, + }, + "ai-search-options-cache-cache-threshold": { + kind: "parsed", + brief: "The ai_search_options.cache.cache_threshold field", + optional: true, choices: [ "super_strict_match", "close_enough", "flexible_friend", "anything_goes", ], - }) - .coerce("ai-search-options-cache-cache-threshold", (value) => - resolveFileToken(value, "ai-search-options-cache-cache-threshold", "text") - ) - .option("ai-search-options-cache-enabled", { - type: "boolean", - description: "The ai_search_options.cache.enabled field", - }) - .option("ai-search-options-custom-metadata", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "ai-search-options-cache-cache-threshold", + "text" + ), + }, + "ai-search-options-cache-enabled": { + kind: "boolean", + brief: "The ai_search_options.cache.enabled field", + optional: true, + }, + "ai-search-options-custom-metadata": { + kind: "parsed", + brief: "Metadata added to AI Gateway logs for requests this operation triggers. Accepts up to 2 string, number, or boolean entries. Reserved keys: 'ai-search', 'task', 'origin', and any key beginning with 'cf.'. Provide as a JSON object or @path/to/file.json. Shape: {\"\": (string | number | boolean)}.", - }) - .option("ai-search-options-instance-ids", { - type: "string", - array: true, - description: "The ai_search_options.instance_ids field", - }) - .option("ai-search-options-query-rewrite-enabled", { - type: "boolean", - description: "The ai_search_options.query_rewrite.enabled field", - }) - .option("ai-search-options-query-rewrite-model", { - type: "string", - description: + optional: true, + parse: String, + }, + "ai-search-options-instance-ids": { + kind: "parsed", + brief: "The ai_search_options.instance_ids field", + variadic: true, + optional: true, + parse: String, + }, + "ai-search-options-query-rewrite-enabled": { + kind: "boolean", + brief: "The ai_search_options.query_rewrite.enabled field", + optional: true, + }, + "ai-search-options-query-rewrite-model": { + kind: "parsed", + brief: "A Workers AI model ID or an AI Gateway model ID compatible with the OpenAI Chat Completions API. An empty string uses the configured or default model.", - }) - .option("ai-search-options-query-rewrite-rewrite-prompt", { - type: "string", - description: "The ai_search_options.query_rewrite.rewrite_prompt field", - }) - .option("ai-search-options-reranking-enabled", { - type: "boolean", - description: "The ai_search_options.reranking.enabled field", - }) - .option("ai-search-options-reranking-match-threshold", { - type: "number", - description: + optional: true, + parse: String, + }, + "ai-search-options-query-rewrite-rewrite-prompt": { + kind: "parsed", + brief: "The ai_search_options.query_rewrite.rewrite_prompt field", + optional: true, + parse: String, + }, + "ai-search-options-reranking-enabled": { + kind: "boolean", + brief: "The ai_search_options.reranking.enabled field", + optional: true, + }, + "ai-search-options-reranking-match-threshold": { + kind: "parsed", + brief: "Minimum reranker relevance score a chunk must reach to be returned. When omitted, falls back to the instance-level score_threshold, then to 0.4.", - }) - .option("ai-search-options-reranking-model", { - type: "string", - description: "The ai_search_options.reranking.model field", - }) - .option("ai-search-options-retrieval-boost-by", { - type: "string", - description: + optional: true, + parse: Number, + }, + "ai-search-options-reranking-model": { + kind: "parsed", + brief: "The ai_search_options.reranking.model field", + optional: true, + parse: String, + }, + "ai-search-options-retrieval-boost-by": { + kind: "parsed", + brief: 'Metadata fields to boost search results by. Overrides the instance-level boost_by config. Direction defaults to \'asc\' for numeric/datetime fields, \'exists\' for text/boolean fields. Fields must match \'timestamp\' or a defined custom_metadata field. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"field": string, "direction"?: "asc" | "desc" | "exists" | ...more}]. ? marks optional keys.', - }) - .option("ai-search-options-retrieval-context-expansion", { - type: "number", - description: "The ai_search_options.retrieval.context_expansion field", - }) - .option("ai-search-options-retrieval-filters", { - type: "string", - description: + optional: true, + parse: String, + }, + "ai-search-options-retrieval-context-expansion": { + kind: "parsed", + brief: "The ai_search_options.retrieval.context_expansion field", + optional: true, + parse: Number, + }, + "ai-search-options-retrieval-filters": { + kind: "parsed", + brief: 'The ai_search_options.retrieval.filters field. Provide as a JSON object or @path/to/file.json. Shape: {"": unknown}.', - }) - .option("ai-search-options-retrieval-fusion-method", { - type: "string", - description: "The ai_search_options.retrieval.fusion_method field", + optional: true, + parse: String, + }, + "ai-search-options-retrieval-fusion-method": { + kind: "parsed", + brief: "The ai_search_options.retrieval.fusion_method field", + optional: true, choices: ["max", "rrf"], - }) - .coerce("ai-search-options-retrieval-fusion-method", (value) => - resolveFileToken( - value, - "ai-search-options-retrieval-fusion-method", - "text" - ) - ) - .option("ai-search-options-retrieval-keyword-match-mode", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "ai-search-options-retrieval-fusion-method", + "text" + ), + }, + "ai-search-options-retrieval-keyword-match-mode": { + kind: "parsed", + brief: "Controls which documents become candidates for BM25 scoring. 'and' restricts candidates to documents containing all query terms; 'or' includes any document containing at least one term and ranks results according to BM25 relevance. When omitted, falls back to the instance-level retrieval_options.keyword_match_mode, then to 'and'.", + optional: true, choices: ["and", "or"], - }) - .coerce("ai-search-options-retrieval-keyword-match-mode", (value) => - resolveFileToken( - value, - "ai-search-options-retrieval-keyword-match-mode", - "text" - ) - ) - .option("ai-search-options-retrieval-match-threshold", { - type: "number", - description: + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "ai-search-options-retrieval-keyword-match-mode", + "text" + ), + }, + "ai-search-options-retrieval-match-threshold": { + kind: "parsed", + brief: "Minimum score a chunk must reach to be returned. When omitted, each instance's chunks are filtered by that instance's score_threshold, capped at 0.4.", - }) - .option("ai-search-options-retrieval-max-num-results", { - type: "number", - description: + optional: true, + parse: Number, + }, + "ai-search-options-retrieval-max-num-results": { + kind: "parsed", + brief: "Maximum number of merged results to return. When omitted, defaults to the sum of the searched instances' max_num_results (each falling back to 10), up to 50.", - }) - .option("ai-search-options-retrieval-retrieval-type", { - type: "string", - description: "The ai_search_options.retrieval.retrieval_type field", + optional: true, + parse: Number, + }, + "ai-search-options-retrieval-retrieval-type": { + kind: "parsed", + brief: "The ai_search_options.retrieval.retrieval_type field", + optional: true, choices: ["vector", "keyword", "hybrid"], - }) - .coerce("ai-search-options-retrieval-retrieval-type", (value) => - resolveFileToken( - value, - "ai-search-options-retrieval-retrieval-type", - "text" - ) - ) - .option("ai-search-options-retrieval-return-on-failure", { - type: "boolean", - description: "The ai_search_options.retrieval.return_on_failure field", - }) - .option("messages", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "ai-search-options-retrieval-retrieval-type", + "text" + ), + }, + "ai-search-options-retrieval-return-on-failure": { + kind: "boolean", + brief: "The ai_search_options.retrieval.return_on_failure field", + optional: true, + }, + messages: { + kind: "parsed", + brief: "OpenAI-compatible message array. For multimodal queries, set the last user message's `content` to an array of typed parts: `[{type:'text', text:'…'}, {type:'image_url', image_url:{url:'…'}}]`. Image inputs require the RAG's embedding_model to declare 'image' in supported_modalities. Provide as a JSON array of objects or @path/to/file.json. Shape: [{\"content\": (string | [{...}] | null), \"role\": \"system\" | \"developer\" | \"user\" | ...more, \"\": unknown}].", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "query", + brief: "Text to search for.", + parse: String, + optional: true, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "multi-search [query]", describe: "Multi-Instance Search", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search multi-search", - classification: { - safeFlags: [ - "ai-search-options-cache-cache-threshold", - "ai-search-options-cache-enabled", - "ai-search-options-query-rewrite-enabled", - "ai-search-options-reranking-enabled", - "ai-search-options-retrieval-fusion-method", - "ai-search-options-retrieval-keyword-match-mode", - "ai-search-options-retrieval-retrieval-type", - "ai-search-options-retrieval-return-on-failure", - "dry-run", - ], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["ai-search-options-instance-ids"] === undefined) { - throw new Error( - "--ai-search-options-instance-ids is required (or pass --body with this field set)." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search multi-search", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/search`, - pathParams: { namespace: String(argv["namespace"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? mergeBodyPositionals(parseBody(argv.body), [ - { name: "query", field: "query", value: argv["query"] }, - ]) - : compactBody( - { - ai_search_options: { - cache: { - cache_threshold: - argv["ai-search-options-cache-cache-threshold"], - enabled: argv["ai-search-options-cache-enabled"], - }, - custom_metadata: parseJsonMap( - argv["ai-search-options-custom-metadata"], - "ai-search-options-custom-metadata" - ), - instance_ids: argv["ai-search-options-instance-ids"], - query_rewrite: { - enabled: - argv["ai-search-options-query-rewrite-enabled"], - model: resolveFileToken( - argv["ai-search-options-query-rewrite-model"] as - | string - | undefined, - "ai-search-options-query-rewrite-model", - "text" - ), - rewrite_prompt: resolveFileToken( - argv[ - "ai-search-options-query-rewrite-rewrite-prompt" - ] as string | undefined, - "ai-search-options-query-rewrite-rewrite-prompt", - "text" - ), - }, - reranking: { - enabled: argv["ai-search-options-reranking-enabled"], - match_threshold: - argv["ai-search-options-reranking-match-threshold"], - model: resolveFileToken( - argv["ai-search-options-reranking-model"] as - | string - | undefined, - "ai-search-options-reranking-model", - "text" - ), - }, - retrieval: { - boost_by: parseObjectArray( - argv["ai-search-options-retrieval-boost-by"], - "ai-search-options-retrieval-boost-by" - ), - context_expansion: - argv[ - "ai-search-options-retrieval-context-expansion" - ], - filters: parseJsonMap( - argv["ai-search-options-retrieval-filters"], - "ai-search-options-retrieval-filters" - ), - fusion_method: - argv["ai-search-options-retrieval-fusion-method"], - keyword_match_mode: - argv[ - "ai-search-options-retrieval-keyword-match-mode" - ], - match_threshold: - argv["ai-search-options-retrieval-match-threshold"], - max_num_results: - argv["ai-search-options-retrieval-max-num-results"], - retrieval_type: - argv["ai-search-options-retrieval-retrieval-type"], - return_on_failure: - argv[ - "ai-search-options-retrieval-return-on-failure" - ], - }, - }, - messages: parseObjectArray(argv["messages"], "messages"), - query: argv["query"], - }, - [ - ["ai_search_options", "custom_metadata"], - ["ai_search_options", "retrieval", "filters"], - ] - ), - }); - return; - } - const parsedBody = - argv.body !== undefined - ? mergeBodyPositionals(parseBody(argv.body), [ - { name: "query", field: "query", value: argv["query"] }, - ]) - : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/search`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData: Record = {}; - if (argv["ai-search-options-cache-cache-threshold"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "cache", "cache_threshold"], - argv["ai-search-options-cache-cache-threshold"] - ); - if (argv["ai-search-options-cache-enabled"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "cache", "enabled"], - argv["ai-search-options-cache-enabled"] - ); - if (argv["ai-search-options-custom-metadata"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "custom_metadata"], - parseJsonMap( - argv["ai-search-options-custom-metadata"], - "ai-search-options-custom-metadata" - ) - ); - if (argv["ai-search-options-instance-ids"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "instance_ids"], - argv["ai-search-options-instance-ids"] - ); - if (argv["ai-search-options-query-rewrite-enabled"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "query_rewrite", "enabled"], - argv["ai-search-options-query-rewrite-enabled"] - ); - if (argv["ai-search-options-query-rewrite-model"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "query_rewrite", "model"], - resolveFileToken( - argv["ai-search-options-query-rewrite-model"] as - | string - | undefined, - "ai-search-options-query-rewrite-model", - "text" - ) - ); - if ( - argv["ai-search-options-query-rewrite-rewrite-prompt"] !== undefined - ) - setNestedValue( - bodyData, - ["ai_search_options", "query_rewrite", "rewrite_prompt"], - resolveFileToken( - argv["ai-search-options-query-rewrite-rewrite-prompt"] as - | string - | undefined, - "ai-search-options-query-rewrite-rewrite-prompt", - "text" - ) - ); - if (argv["ai-search-options-reranking-enabled"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "reranking", "enabled"], - argv["ai-search-options-reranking-enabled"] - ); - if (argv["ai-search-options-reranking-match-threshold"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "reranking", "match_threshold"], - argv["ai-search-options-reranking-match-threshold"] - ); - if (argv["ai-search-options-reranking-model"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "reranking", "model"], - resolveFileToken( - argv["ai-search-options-reranking-model"] as string | undefined, - "ai-search-options-reranking-model", - "text" - ) - ); - if (argv["ai-search-options-retrieval-boost-by"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "boost_by"], - parseObjectArray( - argv["ai-search-options-retrieval-boost-by"], - "ai-search-options-retrieval-boost-by" - ) - ); - if (argv["ai-search-options-retrieval-context-expansion"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "context_expansion"], - argv["ai-search-options-retrieval-context-expansion"] - ); - if (argv["ai-search-options-retrieval-filters"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "filters"], - parseJsonMap( - argv["ai-search-options-retrieval-filters"], - "ai-search-options-retrieval-filters" - ) - ); - if (argv["ai-search-options-retrieval-fusion-method"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "fusion_method"], - argv["ai-search-options-retrieval-fusion-method"] - ); - if ( - argv["ai-search-options-retrieval-keyword-match-mode"] !== undefined - ) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "keyword_match_mode"], - argv["ai-search-options-retrieval-keyword-match-mode"] - ); - if (argv["ai-search-options-retrieval-match-threshold"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "match_threshold"], - argv["ai-search-options-retrieval-match-threshold"] - ); - if (argv["ai-search-options-retrieval-max-num-results"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "max_num_results"], - argv["ai-search-options-retrieval-max-num-results"] - ); - if (argv["ai-search-options-retrieval-retrieval-type"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "retrieval_type"], - argv["ai-search-options-retrieval-retrieval-type"] - ); - if (argv["ai-search-options-retrieval-return-on-failure"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "return_on_failure"], - argv["ai-search-options-retrieval-return-on-failure"] - ); - if (argv["messages"] !== undefined) - setNestedValue( - bodyData, - ["messages"], - parseObjectArray(argv["messages"], "messages") - ); - if (argv["query"] !== undefined) bodyData["query"] = argv["query"]; - const result = await withProgress(`Creating`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/search`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 ai-search multi-search [query]\n\nPerforms a semantic search query against multiple AI Search instances in parallel, merging the retrieved results into a single ranked response.", + ...parameters, + loader: () => import("./multi-search.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/namespace/create.handler.ts b/packages/cli/src/commands/_generated/ai-search/namespace/create.handler.ts new file mode 100644 index 0000000000..afaf9e882c --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/namespace/create.handler.ts @@ -0,0 +1,170 @@ +import operation from "../../_operations/ai-search/namespace/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { + compactBody, + mergeBodyPositionals, + parseBody, +} from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search namespace create", + classification: { + safeFlags: [ + "public-endpoint-params-chat-completions-endpoint-disabled", + "public-endpoint-params-default-domain-enabled", + "public-endpoint-params-enabled", + "public-endpoint-params-mcp-disabled", + "public-endpoint-params-rate-limit-technique", + "public-endpoint-params-search-endpoint-disabled", + "dry-run", + ], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search namespace create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? mergeBodyPositionals(parseBody(argv.body), [ + { + name: "namespace", + field: "name", + value: argv["namespace"], + }, + ]) + : compactBody({ + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + public_endpoint_params: { + authorized_hosts: + argv["public-endpoint-params-authorized-hosts"], + chat_completions_endpoint: { + disabled: + argv[ + "public-endpoint-params-chat-completions-endpoint-disabled" + ], + }, + custom_domains: + argv["public-endpoint-params-custom-domains"], + default_domain_enabled: + argv["public-endpoint-params-default-domain-enabled"], + enabled: argv["public-endpoint-params-enabled"], + instances_allowed: + argv["public-endpoint-params-instances-allowed"], + mcp: { + description: resolveFileToken( + argv["public-endpoint-params-mcp-description"] as + | string + | undefined, + "public-endpoint-params-mcp-description", + "text" + ), + disabled: argv["public-endpoint-params-mcp-disabled"], + }, + rate_limit: { + period_ms: + argv["public-endpoint-params-rate-limit-period-ms"], + requests: + argv["public-endpoint-params-rate-limit-requests"], + technique: + argv["public-endpoint-params-rate-limit-technique"], + }, + search_endpoint: { + disabled: + argv["public-endpoint-params-search-endpoint-disabled"], + }, + }, + name: argv["namespace"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined + ? mergeBodyPositionals(parseBody(argv.body), [ + { name: "namespace", field: "name", value: argv["namespace"] }, + ]) + : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + public_endpoint_params: { + authorized_hosts: argv["public-endpoint-params-authorized-hosts"], + chat_completions_endpoint: { + disabled: + argv["public-endpoint-params-chat-completions-endpoint-disabled"], + }, + custom_domains: argv["public-endpoint-params-custom-domains"], + default_domain_enabled: + argv["public-endpoint-params-default-domain-enabled"], + enabled: argv["public-endpoint-params-enabled"], + instances_allowed: argv["public-endpoint-params-instances-allowed"], + mcp: { + description: resolveFileToken( + argv["public-endpoint-params-mcp-description"] as + | string + | undefined, + "public-endpoint-params-mcp-description", + "text" + ), + disabled: argv["public-endpoint-params-mcp-disabled"], + }, + rate_limit: { + period_ms: argv["public-endpoint-params-rate-limit-period-ms"], + requests: argv["public-endpoint-params-rate-limit-requests"], + technique: argv["public-endpoint-params-rate-limit-technique"], + }, + search_endpoint: { + disabled: argv["public-endpoint-params-search-endpoint-disabled"], + }, + }, + name: argv["namespace"], + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/namespace/create.ts b/packages/cli/src/commands/_generated/ai-search/namespace/create.ts index 1239760e6e..97fd8e1009 100644 --- a/packages/cli/src/commands/_generated/ai-search/namespace/create.ts +++ b/packages/cli/src/commands/_generated/ai-search/namespace/create.ts @@ -1,276 +1,130 @@ -import operation from "../../_operations/ai-search/namespace/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { - compactBody, - mergeBodyPositionals, - parseBody, -} from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search namespace create \n\nCreate a namespace for organizing AI Search instances." - ) - .positional("namespace", { - type: "string", - description: "Name for the new namespace.", - demandOption: true, - }) - .option("description", { - type: "string", - description: - "Optional description for the namespace. Max 256 characters.", - }) - .option("public-endpoint-params-authorized-hosts", { - type: "string", - array: true, - description: "The public_endpoint_params.authorized_hosts field", - }) - .option("public-endpoint-params-chat-completions-endpoint-disabled", { - type: "boolean", - description: - "Disable chat completions endpoint for this public endpoint.", - }) - .option("public-endpoint-params-custom-domains", { - type: "string", - array: true, - description: +const parameters = { + flags: { + description: { + kind: "parsed", + brief: "Optional description for the namespace. Max 256 characters.", + optional: true, + parse: String, + }, + "public-endpoint-params-authorized-hosts": { + kind: "parsed", + brief: "The public_endpoint_params.authorized_hosts field", + variadic: true, + optional: true, + parse: String, + }, + "public-endpoint-params-chat-completions-endpoint-disabled": { + kind: "boolean", + brief: "Disable chat completions endpoint for this public endpoint.", + optional: true, + }, + "public-endpoint-params-custom-domains": { + kind: "parsed", + brief: "Custom domain hostnames that alias this public endpoint. GET and create responses return the current set; on update (PUT) this field is only echoed back when supplied in the request body, otherwise it is null (omit it to leave domains unchanged).", - }) - .option("public-endpoint-params-default-domain-enabled", { - type: "boolean", - description: + variadic: true, + optional: true, + parse: String, + }, + "public-endpoint-params-default-domain-enabled": { + kind: "boolean", + brief: "When false, the instance is reachable only via a registered custom domain and the default .search.ai.cloudflare.com host returns 404. Requires at least one custom domain. Defaults to true. public_endpoint_params is replaced wholesale on update, so resend default_domain_enabled on every update to keep the default host off — omitting it resets to true.", - }) - .option("public-endpoint-params-enabled", { - type: "boolean", - description: "The public_endpoint_params.enabled field", - }) - .option("public-endpoint-params-instances-allowed", { - type: "string", - array: true, - description: + optional: true, + }, + "public-endpoint-params-enabled": { + kind: "boolean", + brief: "The public_endpoint_params.enabled field", + optional: true, + }, + "public-endpoint-params-instances-allowed": { + kind: "parsed", + brief: "Instance IDs exposed through the namespace public endpoint. Empty means nothing is searchable. Every ID must reference an existing instance in this namespace, and the list must stay within the account's multi-instance search limit.", - }) - .option("public-endpoint-params-mcp-description", { - type: "string", - description: "The public_endpoint_params.mcp.description field", - }) - .option("public-endpoint-params-mcp-disabled", { - type: "boolean", - description: "Disable MCP endpoint for this public endpoint.", - }) - .option("public-endpoint-params-rate-limit-period-ms", { - type: "number", - description: "The public_endpoint_params.rate_limit.period_ms field", - }) - .option("public-endpoint-params-rate-limit-requests", { - type: "number", - description: "The public_endpoint_params.rate_limit.requests field", - }) - .option("public-endpoint-params-rate-limit-technique", { - type: "string", - description: "The public_endpoint_params.rate_limit.technique field", + variadic: true, + optional: true, + parse: String, + }, + "public-endpoint-params-mcp-description": { + kind: "parsed", + brief: "The public_endpoint_params.mcp.description field", + optional: true, + parse: String, + }, + "public-endpoint-params-mcp-disabled": { + kind: "boolean", + brief: "Disable MCP endpoint for this public endpoint.", + optional: true, + }, + "public-endpoint-params-rate-limit-period-ms": { + kind: "parsed", + brief: "The public_endpoint_params.rate_limit.period_ms field", + optional: true, + parse: Number, + }, + "public-endpoint-params-rate-limit-requests": { + kind: "parsed", + brief: "The public_endpoint_params.rate_limit.requests field", + optional: true, + parse: Number, + }, + "public-endpoint-params-rate-limit-technique": { + kind: "parsed", + brief: "The public_endpoint_params.rate_limit.technique field", + optional: true, choices: ["fixed", "sliding"], - }) - .coerce("public-endpoint-params-rate-limit-technique", (value) => - resolveFileToken( - value, - "public-endpoint-params-rate-limit-technique", - "text" - ) - ) - .option("public-endpoint-params-search-endpoint-disabled", { - type: "boolean", - description: "Disable search endpoint for this public endpoint.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "public-endpoint-params-rate-limit-technique", + "text" + ), + }, + "public-endpoint-params-search-endpoint-disabled": { + kind: "boolean", + brief: "Disable search endpoint for this public endpoint.", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "namespace", + brief: "Name for the new namespace.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Create a namespace", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search namespace create", - classification: { - safeFlags: [ - "public-endpoint-params-chat-completions-endpoint-disabled", - "public-endpoint-params-default-domain-enabled", - "public-endpoint-params-enabled", - "public-endpoint-params-mcp-disabled", - "public-endpoint-params-rate-limit-technique", - "public-endpoint-params-search-endpoint-disabled", - "dry-run", - ], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search namespace create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? mergeBodyPositionals(parseBody(argv.body), [ - { - name: "namespace", - field: "name", - value: argv["namespace"], - }, - ]) - : compactBody({ - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - public_endpoint_params: { - authorized_hosts: - argv["public-endpoint-params-authorized-hosts"], - chat_completions_endpoint: { - disabled: - argv[ - "public-endpoint-params-chat-completions-endpoint-disabled" - ], - }, - custom_domains: - argv["public-endpoint-params-custom-domains"], - default_domain_enabled: - argv["public-endpoint-params-default-domain-enabled"], - enabled: argv["public-endpoint-params-enabled"], - instances_allowed: - argv["public-endpoint-params-instances-allowed"], - mcp: { - description: resolveFileToken( - argv["public-endpoint-params-mcp-description"] as - | string - | undefined, - "public-endpoint-params-mcp-description", - "text" - ), - disabled: argv["public-endpoint-params-mcp-disabled"], - }, - rate_limit: { - period_ms: - argv["public-endpoint-params-rate-limit-period-ms"], - requests: - argv["public-endpoint-params-rate-limit-requests"], - technique: - argv["public-endpoint-params-rate-limit-technique"], - }, - search_endpoint: { - disabled: - argv[ - "public-endpoint-params-search-endpoint-disabled" - ], - }, - }, - name: argv["namespace"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined - ? mergeBodyPositionals(parseBody(argv.body), [ - { name: "namespace", field: "name", value: argv["namespace"] }, - ]) - : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - public_endpoint_params: { - authorized_hosts: argv["public-endpoint-params-authorized-hosts"], - chat_completions_endpoint: { - disabled: - argv[ - "public-endpoint-params-chat-completions-endpoint-disabled" - ], - }, - custom_domains: argv["public-endpoint-params-custom-domains"], - default_domain_enabled: - argv["public-endpoint-params-default-domain-enabled"], - enabled: argv["public-endpoint-params-enabled"], - instances_allowed: argv["public-endpoint-params-instances-allowed"], - mcp: { - description: resolveFileToken( - argv["public-endpoint-params-mcp-description"] as - | string - | undefined, - "public-endpoint-params-mcp-description", - "text" - ), - disabled: argv["public-endpoint-params-mcp-disabled"], - }, - rate_limit: { - period_ms: argv["public-endpoint-params-rate-limit-period-ms"], - requests: argv["public-endpoint-params-rate-limit-requests"], - technique: argv["public-endpoint-params-rate-limit-technique"], - }, - search_endpoint: { - disabled: argv["public-endpoint-params-search-endpoint-disabled"], - }, - }, - name: argv["namespace"], - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 ai-search namespace create \n\nCreate a namespace for organizing AI Search instances.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/namespace/delete.handler.ts b/packages/cli/src/commands/_generated/ai-search/namespace/delete.handler.ts new file mode 100644 index 0000000000..30e75b6295 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/namespace/delete.handler.ts @@ -0,0 +1,61 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search namespace delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search namespace delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}`, + pathParams: { namespace: String(argv["namespace"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This operation permanently deletes the namespace.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + requestApi( + client, + "DELETE", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}` + ) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/namespace/delete.ts b/packages/cli/src/commands/_generated/ai-search/namespace/delete.ts index f24d5b0bed..158554c27e 100644 --- a/packages/cli/src/commands/_generated/ai-search/namespace/delete.ts +++ b/packages/cli/src/commands/_generated/ai-search/namespace/delete.ts @@ -1,97 +1,39 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search namespace delete \n\nDeletes a namespace permanently. The namespace must not contain any instances (instances whose deletion is still in progress do not count), and the default namespace cannot be deleted." - ) - .positional("namespace", { - type: "string", - description: "Namespace to delete.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "namespace", brief: "Namespace to delete.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete a namespace", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search namespace delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search namespace delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}`, - pathParams: { namespace: String(argv["namespace"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This operation permanently deletes the namespace.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - requestApi( - client, - "DELETE", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}` - ) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 ai-search namespace delete \n\nDeletes a namespace permanently. The namespace must not contain any instances (instances whose deletion is still in progress do not count), and the default namespace cannot be deleted.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/namespace/get.handler.ts b/packages/cli/src/commands/_generated/ai-search/namespace/get.handler.ts new file mode 100644 index 0000000000..2c82ad617e --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/namespace/get.handler.ts @@ -0,0 +1,50 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search namespace get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search namespace get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}`, + pathParams: { namespace: String(argv["namespace"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + requestApi( + client, + "GET", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}` + ) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/namespace/get.ts b/packages/cli/src/commands/_generated/ai-search/namespace/get.ts index 89f35d4044..25839c3762 100644 --- a/packages/cli/src/commands/_generated/ai-search/namespace/get.ts +++ b/packages/cli/src/commands/_generated/ai-search/namespace/get.ts @@ -1,80 +1,37 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search namespace get \n\nRetrieve a namespace and its description." - ) - .positional("namespace", { - type: "string", - description: "Namespace to retrieve.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "namespace", + brief: "Namespace to retrieve.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get a namespace", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search namespace get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search namespace get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}`, - pathParams: { namespace: String(argv["namespace"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - requestApi( - client, - "GET", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}` - ) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-search namespace get \n\nRetrieve a namespace and its description.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/namespace/index.ts b/packages/cli/src/commands/_generated/ai-search/namespace/index.ts index 48d029ed88..5c6f867261 100644 --- a/packages/cli/src/commands/_generated/ai-search/namespace/index.ts +++ b/packages/cli/src/commands/_generated/ai-search/namespace/index.ts @@ -3,28 +3,23 @@ import $delete from "./delete.js"; import $get from "./get.js"; import $list from "./list.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * namespace command group * @generated from apis/overlays/ai-search.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "namespace", describe: "Logical groupings for organizing AI Search instances", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .command($list) - .command($update) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, + list: $list, + update: $update, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/namespace/list.handler.ts b/packages/cli/src/commands/_generated/ai-search/namespace/list.handler.ts new file mode 100644 index 0000000000..0c4f968ae8 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/namespace/list.handler.ts @@ -0,0 +1,52 @@ +import operation from "../../_operations/ai-search/namespace/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search namespace list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + search: argv["search"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search namespace list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/namespace/list.ts b/packages/cli/src/commands/_generated/ai-search/namespace/list.ts index a5eec70757..fa3b0bbf05 100644 --- a/packages/cli/src/commands/_generated/ai-search/namespace/list.ts +++ b/packages/cli/src/commands/_generated/ai-search/namespace/list.ts @@ -1,87 +1,50 @@ -import operation from "../../_operations/ai-search/namespace/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search namespace list\n\nLists namespaces in the account, including their descriptions and creation times." - ) - .option("page", { type: "number", description: "Page number (1-indexed)." }) - .option("per-page", { - type: "number", - description: "Number of results per page.", - }) - .option("search", { - type: "string", - description: +const parameters = { + flags: { + page: { + kind: "parsed", + brief: "Page number (1-indexed).", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Number of results per page.", + optional: true, + parse: Number, + }, + search: { + kind: "parsed", + brief: "Filter namespaces whose name or description contains this string (case-insensitive).", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List namespaces", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search namespace list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - search: argv["search"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search namespace list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-search namespace list\n\nLists namespaces in the account, including their descriptions and creation times.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/namespace/update.handler.ts b/packages/cli/src/commands/_generated/ai-search/namespace/update.handler.ts new file mode 100644 index 0000000000..81fbbc9698 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/namespace/update.handler.ts @@ -0,0 +1,219 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, setNestedValue } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search namespace update", + classification: { + safeFlags: [ + "public-endpoint-params-chat-completions-endpoint-disabled", + "public-endpoint-params-default-domain-enabled", + "public-endpoint-params-enabled", + "public-endpoint-params-mcp-disabled", + "public-endpoint-params-rate-limit-technique", + "public-endpoint-params-search-endpoint-disabled", + "dry-run", + ], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search namespace update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}`, + pathParams: { namespace: String(argv["namespace"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + public_endpoint_params: { + authorized_hosts: + argv["public-endpoint-params-authorized-hosts"], + chat_completions_endpoint: { + disabled: + argv[ + "public-endpoint-params-chat-completions-endpoint-disabled" + ], + }, + custom_domains: + argv["public-endpoint-params-custom-domains"], + default_domain_enabled: + argv["public-endpoint-params-default-domain-enabled"], + enabled: argv["public-endpoint-params-enabled"], + instances_allowed: + argv["public-endpoint-params-instances-allowed"], + mcp: { + description: resolveFileToken( + argv["public-endpoint-params-mcp-description"] as + | string + | undefined, + "public-endpoint-params-mcp-description", + "text" + ), + disabled: argv["public-endpoint-params-mcp-disabled"], + }, + rate_limit: { + period_ms: + argv["public-endpoint-params-rate-limit-period-ms"], + requests: + argv["public-endpoint-params-rate-limit-requests"], + technique: + argv["public-endpoint-params-rate-limit-technique"], + }, + search_endpoint: { + disabled: + argv["public-endpoint-params-search-endpoint-disabled"], + }, + }, + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + requestApi( + client, + "PUT", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData: Record = {}; + if (argv["description"] !== undefined) + setNestedValue( + bodyData, + ["description"], + resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ) + ); + if (argv["public-endpoint-params-authorized-hosts"] !== undefined) + setNestedValue( + bodyData, + ["public_endpoint_params", "authorized_hosts"], + argv["public-endpoint-params-authorized-hosts"] + ); + if ( + argv["public-endpoint-params-chat-completions-endpoint-disabled"] !== + undefined + ) + setNestedValue( + bodyData, + ["public_endpoint_params", "chat_completions_endpoint", "disabled"], + argv["public-endpoint-params-chat-completions-endpoint-disabled"] + ); + if (argv["public-endpoint-params-custom-domains"] !== undefined) + setNestedValue( + bodyData, + ["public_endpoint_params", "custom_domains"], + argv["public-endpoint-params-custom-domains"] + ); + if (argv["public-endpoint-params-default-domain-enabled"] !== undefined) + setNestedValue( + bodyData, + ["public_endpoint_params", "default_domain_enabled"], + argv["public-endpoint-params-default-domain-enabled"] + ); + if (argv["public-endpoint-params-enabled"] !== undefined) + setNestedValue( + bodyData, + ["public_endpoint_params", "enabled"], + argv["public-endpoint-params-enabled"] + ); + if (argv["public-endpoint-params-instances-allowed"] !== undefined) + setNestedValue( + bodyData, + ["public_endpoint_params", "instances_allowed"], + argv["public-endpoint-params-instances-allowed"] + ); + if (argv["public-endpoint-params-mcp-description"] !== undefined) + setNestedValue( + bodyData, + ["public_endpoint_params", "mcp", "description"], + resolveFileToken( + argv["public-endpoint-params-mcp-description"] as + | string + | undefined, + "public-endpoint-params-mcp-description", + "text" + ) + ); + if (argv["public-endpoint-params-mcp-disabled"] !== undefined) + setNestedValue( + bodyData, + ["public_endpoint_params", "mcp", "disabled"], + argv["public-endpoint-params-mcp-disabled"] + ); + if (argv["public-endpoint-params-rate-limit-period-ms"] !== undefined) + setNestedValue( + bodyData, + ["public_endpoint_params", "rate_limit", "period_ms"], + argv["public-endpoint-params-rate-limit-period-ms"] + ); + if (argv["public-endpoint-params-rate-limit-requests"] !== undefined) + setNestedValue( + bodyData, + ["public_endpoint_params", "rate_limit", "requests"], + argv["public-endpoint-params-rate-limit-requests"] + ); + if (argv["public-endpoint-params-rate-limit-technique"] !== undefined) + setNestedValue( + bodyData, + ["public_endpoint_params", "rate_limit", "technique"], + argv["public-endpoint-params-rate-limit-technique"] + ); + if (argv["public-endpoint-params-search-endpoint-disabled"] !== undefined) + setNestedValue( + bodyData, + ["public_endpoint_params", "search_endpoint", "disabled"], + argv["public-endpoint-params-search-endpoint-disabled"] + ); + const result = await withProgress(`Updating`, async () => + requestApi( + client, + "PUT", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/namespace/update.ts b/packages/cli/src/commands/_generated/ai-search/namespace/update.ts index 221ce4da83..6f5d53acaa 100644 --- a/packages/cli/src/commands/_generated/ai-search/namespace/update.ts +++ b/packages/cli/src/commands/_generated/ai-search/namespace/update.ts @@ -1,325 +1,126 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, setNestedValue } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search namespace update \n\nUpdates the description and/or the public endpoint configuration of an existing namespace. The default namespace's description cannot be modified, but its public endpoint can." - ) - .positional("namespace", { - type: "string", - description: "Namespace to update.", - demandOption: true, - }) - .option("description", { - type: "string", - description: - "Optional description for the namespace. Max 256 characters.", - }) - .option("public-endpoint-params-authorized-hosts", { - type: "string", - array: true, - description: "The public_endpoint_params.authorized_hosts field", - }) - .option("public-endpoint-params-chat-completions-endpoint-disabled", { - type: "boolean", - description: - "Disable chat completions endpoint for this public endpoint.", - }) - .option("public-endpoint-params-custom-domains", { - type: "string", - array: true, - description: +const parameters = { + flags: { + description: { + kind: "parsed", + brief: "Optional description for the namespace. Max 256 characters.", + optional: true, + parse: String, + }, + "public-endpoint-params-authorized-hosts": { + kind: "parsed", + brief: "The public_endpoint_params.authorized_hosts field", + variadic: true, + optional: true, + parse: String, + }, + "public-endpoint-params-chat-completions-endpoint-disabled": { + kind: "boolean", + brief: "Disable chat completions endpoint for this public endpoint.", + optional: true, + }, + "public-endpoint-params-custom-domains": { + kind: "parsed", + brief: "Custom domain hostnames that alias this public endpoint. GET and create responses return the current set; on update (PUT) this field is only echoed back when supplied in the request body, otherwise it is null (omit it to leave domains unchanged).", - }) - .option("public-endpoint-params-default-domain-enabled", { - type: "boolean", - description: + variadic: true, + optional: true, + parse: String, + }, + "public-endpoint-params-default-domain-enabled": { + kind: "boolean", + brief: "When false, the instance is reachable only via a registered custom domain and the default .search.ai.cloudflare.com host returns 404. Requires at least one custom domain. Defaults to true. public_endpoint_params is replaced wholesale on update, so resend default_domain_enabled on every update to keep the default host off — omitting it resets to true.", - }) - .option("public-endpoint-params-enabled", { - type: "boolean", - description: "The public_endpoint_params.enabled field", - }) - .option("public-endpoint-params-instances-allowed", { - type: "string", - array: true, - description: + optional: true, + }, + "public-endpoint-params-enabled": { + kind: "boolean", + brief: "The public_endpoint_params.enabled field", + optional: true, + }, + "public-endpoint-params-instances-allowed": { + kind: "parsed", + brief: "Instance IDs exposed through the namespace public endpoint. Empty means nothing is searchable. Every ID must reference an existing instance in this namespace, and the list must stay within the account's multi-instance search limit.", - }) - .option("public-endpoint-params-mcp-description", { - type: "string", - description: "The public_endpoint_params.mcp.description field", - }) - .option("public-endpoint-params-mcp-disabled", { - type: "boolean", - description: "Disable MCP endpoint for this public endpoint.", - }) - .option("public-endpoint-params-rate-limit-period-ms", { - type: "number", - description: "The public_endpoint_params.rate_limit.period_ms field", - }) - .option("public-endpoint-params-rate-limit-requests", { - type: "number", - description: "The public_endpoint_params.rate_limit.requests field", - }) - .option("public-endpoint-params-rate-limit-technique", { - type: "string", - description: "The public_endpoint_params.rate_limit.technique field", + variadic: true, + optional: true, + parse: String, + }, + "public-endpoint-params-mcp-description": { + kind: "parsed", + brief: "The public_endpoint_params.mcp.description field", + optional: true, + parse: String, + }, + "public-endpoint-params-mcp-disabled": { + kind: "boolean", + brief: "Disable MCP endpoint for this public endpoint.", + optional: true, + }, + "public-endpoint-params-rate-limit-period-ms": { + kind: "parsed", + brief: "The public_endpoint_params.rate_limit.period_ms field", + optional: true, + parse: Number, + }, + "public-endpoint-params-rate-limit-requests": { + kind: "parsed", + brief: "The public_endpoint_params.rate_limit.requests field", + optional: true, + parse: Number, + }, + "public-endpoint-params-rate-limit-technique": { + kind: "parsed", + brief: "The public_endpoint_params.rate_limit.technique field", + optional: true, choices: ["fixed", "sliding"], - }) - .coerce("public-endpoint-params-rate-limit-technique", (value) => - resolveFileToken( - value, - "public-endpoint-params-rate-limit-technique", - "text" - ) - ) - .option("public-endpoint-params-search-endpoint-disabled", { - type: "boolean", - description: "Disable search endpoint for this public endpoint.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "public-endpoint-params-rate-limit-technique", + "text" + ), + }, + "public-endpoint-params-search-endpoint-disabled": { + kind: "boolean", + brief: "Disable search endpoint for this public endpoint.", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { placeholder: "namespace", brief: "Namespace to update.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update ", describe: "Update a namespace", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search namespace update", - classification: { - safeFlags: [ - "public-endpoint-params-chat-completions-endpoint-disabled", - "public-endpoint-params-default-domain-enabled", - "public-endpoint-params-enabled", - "public-endpoint-params-mcp-disabled", - "public-endpoint-params-rate-limit-technique", - "public-endpoint-params-search-endpoint-disabled", - "dry-run", - ], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search namespace update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}`, - pathParams: { namespace: String(argv["namespace"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - public_endpoint_params: { - authorized_hosts: - argv["public-endpoint-params-authorized-hosts"], - chat_completions_endpoint: { - disabled: - argv[ - "public-endpoint-params-chat-completions-endpoint-disabled" - ], - }, - custom_domains: - argv["public-endpoint-params-custom-domains"], - default_domain_enabled: - argv["public-endpoint-params-default-domain-enabled"], - enabled: argv["public-endpoint-params-enabled"], - instances_allowed: - argv["public-endpoint-params-instances-allowed"], - mcp: { - description: resolveFileToken( - argv["public-endpoint-params-mcp-description"] as - | string - | undefined, - "public-endpoint-params-mcp-description", - "text" - ), - disabled: argv["public-endpoint-params-mcp-disabled"], - }, - rate_limit: { - period_ms: - argv["public-endpoint-params-rate-limit-period-ms"], - requests: - argv["public-endpoint-params-rate-limit-requests"], - technique: - argv["public-endpoint-params-rate-limit-technique"], - }, - search_endpoint: { - disabled: - argv[ - "public-endpoint-params-search-endpoint-disabled" - ], - }, - }, - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - requestApi( - client, - "PUT", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData: Record = {}; - if (argv["description"] !== undefined) - setNestedValue( - bodyData, - ["description"], - resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ) - ); - if (argv["public-endpoint-params-authorized-hosts"] !== undefined) - setNestedValue( - bodyData, - ["public_endpoint_params", "authorized_hosts"], - argv["public-endpoint-params-authorized-hosts"] - ); - if ( - argv["public-endpoint-params-chat-completions-endpoint-disabled"] !== - undefined - ) - setNestedValue( - bodyData, - ["public_endpoint_params", "chat_completions_endpoint", "disabled"], - argv["public-endpoint-params-chat-completions-endpoint-disabled"] - ); - if (argv["public-endpoint-params-custom-domains"] !== undefined) - setNestedValue( - bodyData, - ["public_endpoint_params", "custom_domains"], - argv["public-endpoint-params-custom-domains"] - ); - if (argv["public-endpoint-params-default-domain-enabled"] !== undefined) - setNestedValue( - bodyData, - ["public_endpoint_params", "default_domain_enabled"], - argv["public-endpoint-params-default-domain-enabled"] - ); - if (argv["public-endpoint-params-enabled"] !== undefined) - setNestedValue( - bodyData, - ["public_endpoint_params", "enabled"], - argv["public-endpoint-params-enabled"] - ); - if (argv["public-endpoint-params-instances-allowed"] !== undefined) - setNestedValue( - bodyData, - ["public_endpoint_params", "instances_allowed"], - argv["public-endpoint-params-instances-allowed"] - ); - if (argv["public-endpoint-params-mcp-description"] !== undefined) - setNestedValue( - bodyData, - ["public_endpoint_params", "mcp", "description"], - resolveFileToken( - argv["public-endpoint-params-mcp-description"] as - | string - | undefined, - "public-endpoint-params-mcp-description", - "text" - ) - ); - if (argv["public-endpoint-params-mcp-disabled"] !== undefined) - setNestedValue( - bodyData, - ["public_endpoint_params", "mcp", "disabled"], - argv["public-endpoint-params-mcp-disabled"] - ); - if (argv["public-endpoint-params-rate-limit-period-ms"] !== undefined) - setNestedValue( - bodyData, - ["public_endpoint_params", "rate_limit", "period_ms"], - argv["public-endpoint-params-rate-limit-period-ms"] - ); - if (argv["public-endpoint-params-rate-limit-requests"] !== undefined) - setNestedValue( - bodyData, - ["public_endpoint_params", "rate_limit", "requests"], - argv["public-endpoint-params-rate-limit-requests"] - ); - if (argv["public-endpoint-params-rate-limit-technique"] !== undefined) - setNestedValue( - bodyData, - ["public_endpoint_params", "rate_limit", "technique"], - argv["public-endpoint-params-rate-limit-technique"] - ); - if ( - argv["public-endpoint-params-search-endpoint-disabled"] !== undefined - ) - setNestedValue( - bodyData, - ["public_endpoint_params", "search_endpoint", "disabled"], - argv["public-endpoint-params-search-endpoint-disabled"] - ); - const result = await withProgress(`Updating`, async () => - requestApi( - client, - "PUT", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 ai-search namespace update \n\nUpdates the description and/or the public endpoint configuration of an existing namespace. The default namespace's description cannot be modified, but its public endpoint can.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/purge-cache.handler.ts b/packages/cli/src/commands/_generated/ai-search/purge-cache.handler.ts new file mode 100644 index 0000000000..033be9602c --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/purge-cache.handler.ts @@ -0,0 +1,53 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./purge-cache.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search purge-cache", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search purge-cache", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/purge_cache`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + "instance-id": String(argv["instance-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Creating`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/purge_cache` + ) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/purge-cache.ts b/packages/cli/src/commands/_generated/ai-search/purge-cache.ts index 9d53eceacc..c0cda87253 100644 --- a/packages/cli/src/commands/_generated/ai-search/purge-cache.ts +++ b/packages/cli/src/commands/_generated/ai-search/purge-cache.ts @@ -1,88 +1,43 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * purge-cache command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search purge-cache \n\nPurges all cached search results for an AI Search instance. A new internal cache key is generated, immediately orphaning all prior cached entries." - ) - .positional("instance-id", { - type: "string", - description: "AI Search instance ID.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "instance-id", + brief: "AI Search instance ID.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "purge-cache ", describe: "Purge search cache.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search purge-cache", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search purge-cache", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/purge_cache`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - "instance-id": String(argv["instance-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Creating`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/purge_cache` - ) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 ai-search purge-cache \n\nPurges all cached search results for an AI Search instance. A new internal cache key is generated, immediately orphaning all prior cached entries.", + ...parameters, + loader: () => import("./purge-cache.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/search.handler.ts b/packages/cli/src/commands/_generated/ai-search/search.handler.ts new file mode 100644 index 0000000000..785b96184d --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/search.handler.ts @@ -0,0 +1,315 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./search.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { + compactBody, + mergeBodyPositionals, + parseBody, + parseJsonMap, + parseObjectArray, + setNestedValue, +} from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search search", + classification: { + safeFlags: [ + "ai-search-options-cache-cache-threshold", + "ai-search-options-cache-enabled", + "ai-search-options-query-rewrite-enabled", + "ai-search-options-reranking-enabled", + "ai-search-options-retrieval-fusion-method", + "ai-search-options-retrieval-keyword-match-mode", + "ai-search-options-retrieval-retrieval-type", + "ai-search-options-retrieval-return-on-failure", + "dry-run", + ], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search search", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/search`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + "instance-id": String(argv["instance-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? mergeBodyPositionals(parseBody(argv.body), [ + { name: "query", field: "query", value: argv["query"] }, + ]) + : compactBody( + { + ai_search_options: { + cache: { + cache_threshold: + argv["ai-search-options-cache-cache-threshold"], + enabled: argv["ai-search-options-cache-enabled"], + }, + custom_metadata: parseJsonMap( + argv["ai-search-options-custom-metadata"], + "ai-search-options-custom-metadata" + ), + query_rewrite: { + enabled: + argv["ai-search-options-query-rewrite-enabled"], + model: resolveFileToken( + argv["ai-search-options-query-rewrite-model"] as + | string + | undefined, + "ai-search-options-query-rewrite-model", + "text" + ), + rewrite_prompt: resolveFileToken( + argv[ + "ai-search-options-query-rewrite-rewrite-prompt" + ] as string | undefined, + "ai-search-options-query-rewrite-rewrite-prompt", + "text" + ), + }, + reranking: { + enabled: argv["ai-search-options-reranking-enabled"], + match_threshold: + argv["ai-search-options-reranking-match-threshold"], + model: resolveFileToken( + argv["ai-search-options-reranking-model"] as + | string + | undefined, + "ai-search-options-reranking-model", + "text" + ), + }, + retrieval: { + boost_by: parseObjectArray( + argv["ai-search-options-retrieval-boost-by"], + "ai-search-options-retrieval-boost-by" + ), + context_expansion: + argv["ai-search-options-retrieval-context-expansion"], + filters: parseJsonMap( + argv["ai-search-options-retrieval-filters"], + "ai-search-options-retrieval-filters" + ), + fusion_method: + argv["ai-search-options-retrieval-fusion-method"], + keyword_match_mode: + argv[ + "ai-search-options-retrieval-keyword-match-mode" + ], + match_threshold: + argv["ai-search-options-retrieval-match-threshold"], + max_num_results: + argv["ai-search-options-retrieval-max-num-results"], + retrieval_type: + argv["ai-search-options-retrieval-retrieval-type"], + return_on_failure: + argv["ai-search-options-retrieval-return-on-failure"], + }, + }, + messages: parseObjectArray(argv["messages"], "messages"), + query: argv["query"], + }, + [ + ["ai_search_options", "custom_metadata"], + ["ai_search_options", "retrieval", "filters"], + ] + ), + }); + return; + } + const parsedBody = + argv.body !== undefined + ? mergeBodyPositionals(parseBody(argv.body), [ + { name: "query", field: "query", value: argv["query"] }, + ]) + : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Loading`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/search`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Loaded` }); + return; + } + + // Assemble request body from individual flags + const bodyData: Record = {}; + if (argv["ai-search-options-cache-cache-threshold"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "cache", "cache_threshold"], + argv["ai-search-options-cache-cache-threshold"] + ); + if (argv["ai-search-options-cache-enabled"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "cache", "enabled"], + argv["ai-search-options-cache-enabled"] + ); + if (argv["ai-search-options-custom-metadata"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "custom_metadata"], + parseJsonMap( + argv["ai-search-options-custom-metadata"], + "ai-search-options-custom-metadata" + ) + ); + if (argv["ai-search-options-query-rewrite-enabled"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "query_rewrite", "enabled"], + argv["ai-search-options-query-rewrite-enabled"] + ); + if (argv["ai-search-options-query-rewrite-model"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "query_rewrite", "model"], + resolveFileToken( + argv["ai-search-options-query-rewrite-model"] as string | undefined, + "ai-search-options-query-rewrite-model", + "text" + ) + ); + if (argv["ai-search-options-query-rewrite-rewrite-prompt"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "query_rewrite", "rewrite_prompt"], + resolveFileToken( + argv["ai-search-options-query-rewrite-rewrite-prompt"] as + | string + | undefined, + "ai-search-options-query-rewrite-rewrite-prompt", + "text" + ) + ); + if (argv["ai-search-options-reranking-enabled"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "reranking", "enabled"], + argv["ai-search-options-reranking-enabled"] + ); + if (argv["ai-search-options-reranking-match-threshold"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "reranking", "match_threshold"], + argv["ai-search-options-reranking-match-threshold"] + ); + if (argv["ai-search-options-reranking-model"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "reranking", "model"], + resolveFileToken( + argv["ai-search-options-reranking-model"] as string | undefined, + "ai-search-options-reranking-model", + "text" + ) + ); + if (argv["ai-search-options-retrieval-boost-by"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "boost_by"], + parseObjectArray( + argv["ai-search-options-retrieval-boost-by"], + "ai-search-options-retrieval-boost-by" + ) + ); + if (argv["ai-search-options-retrieval-context-expansion"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "context_expansion"], + argv["ai-search-options-retrieval-context-expansion"] + ); + if (argv["ai-search-options-retrieval-filters"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "filters"], + parseJsonMap( + argv["ai-search-options-retrieval-filters"], + "ai-search-options-retrieval-filters" + ) + ); + if (argv["ai-search-options-retrieval-fusion-method"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "fusion_method"], + argv["ai-search-options-retrieval-fusion-method"] + ); + if (argv["ai-search-options-retrieval-keyword-match-mode"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "keyword_match_mode"], + argv["ai-search-options-retrieval-keyword-match-mode"] + ); + if (argv["ai-search-options-retrieval-match-threshold"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "match_threshold"], + argv["ai-search-options-retrieval-match-threshold"] + ); + if (argv["ai-search-options-retrieval-max-num-results"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "max_num_results"], + argv["ai-search-options-retrieval-max-num-results"] + ); + if (argv["ai-search-options-retrieval-retrieval-type"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "retrieval_type"], + argv["ai-search-options-retrieval-retrieval-type"] + ); + if (argv["ai-search-options-retrieval-return-on-failure"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_options", "retrieval", "return_on_failure"], + argv["ai-search-options-retrieval-return-on-failure"] + ); + if (argv["messages"] !== undefined) + setNestedValue( + bodyData, + ["messages"], + parseObjectArray(argv["messages"], "messages") + ); + if (argv["query"] !== undefined) bodyData["query"] = argv["query"]; + const result = await withProgress(`Loading`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/search`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/search.ts b/packages/cli/src/commands/_generated/ai-search/search.ts index 0634807cf1..ec74641541 100644 --- a/packages/cli/src/commands/_generated/ai-search/search.ts +++ b/packages/cli/src/commands/_generated/ai-search/search.ts @@ -1,486 +1,208 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * search command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { - compactBody, - mergeBodyPositionals, - parseBody, - parseJsonMap, - parseObjectArray, - setNestedValue, -} from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search search [query]\n\nExecutes a semantic search query against an AI Search instance to find relevant indexed content." - ) - .positional("instance-id", { - type: "string", - description: "AI Search instance ID.", - demandOption: true, - }) - .positional("query", { - type: "string", - description: "Text to search for.", - }) - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("ai-search-options-cache-cache-threshold", { - type: "string", - description: "The ai_search_options.cache.cache_threshold field", + parse: String, + }, + "ai-search-options-cache-cache-threshold": { + kind: "parsed", + brief: "The ai_search_options.cache.cache_threshold field", + optional: true, choices: [ "super_strict_match", "close_enough", "flexible_friend", "anything_goes", ], - }) - .coerce("ai-search-options-cache-cache-threshold", (value) => - resolveFileToken(value, "ai-search-options-cache-cache-threshold", "text") - ) - .option("ai-search-options-cache-enabled", { - type: "boolean", - description: "The ai_search_options.cache.enabled field", - }) - .option("ai-search-options-custom-metadata", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "ai-search-options-cache-cache-threshold", + "text" + ), + }, + "ai-search-options-cache-enabled": { + kind: "boolean", + brief: "The ai_search_options.cache.enabled field", + optional: true, + }, + "ai-search-options-custom-metadata": { + kind: "parsed", + brief: "Metadata added to AI Gateway logs for requests this operation triggers. Accepts up to 2 string, number, or boolean entries. Reserved keys: 'ai-search', 'task', 'origin', and any key beginning with 'cf.'. Provide as a JSON object or @path/to/file.json. Shape: {\"\": (string | number | boolean)}.", - }) - .option("ai-search-options-query-rewrite-enabled", { - type: "boolean", - description: "The ai_search_options.query_rewrite.enabled field", - }) - .option("ai-search-options-query-rewrite-model", { - type: "string", - description: + optional: true, + parse: String, + }, + "ai-search-options-query-rewrite-enabled": { + kind: "boolean", + brief: "The ai_search_options.query_rewrite.enabled field", + optional: true, + }, + "ai-search-options-query-rewrite-model": { + kind: "parsed", + brief: "A Workers AI model ID or an AI Gateway model ID compatible with the OpenAI Chat Completions API. An empty string uses the configured or default model.", - }) - .option("ai-search-options-query-rewrite-rewrite-prompt", { - type: "string", - description: "The ai_search_options.query_rewrite.rewrite_prompt field", - }) - .option("ai-search-options-reranking-enabled", { - type: "boolean", - description: "The ai_search_options.reranking.enabled field", - }) - .option("ai-search-options-reranking-match-threshold", { - type: "number", - description: + optional: true, + parse: String, + }, + "ai-search-options-query-rewrite-rewrite-prompt": { + kind: "parsed", + brief: "The ai_search_options.query_rewrite.rewrite_prompt field", + optional: true, + parse: String, + }, + "ai-search-options-reranking-enabled": { + kind: "boolean", + brief: "The ai_search_options.reranking.enabled field", + optional: true, + }, + "ai-search-options-reranking-match-threshold": { + kind: "parsed", + brief: "Minimum reranker relevance score a chunk must reach to be returned. When omitted, falls back to the instance-level score_threshold, then to 0.4.", - }) - .option("ai-search-options-reranking-model", { - type: "string", - description: "The ai_search_options.reranking.model field", - }) - .option("ai-search-options-retrieval-boost-by", { - type: "string", - description: + optional: true, + parse: Number, + }, + "ai-search-options-reranking-model": { + kind: "parsed", + brief: "The ai_search_options.reranking.model field", + optional: true, + parse: String, + }, + "ai-search-options-retrieval-boost-by": { + kind: "parsed", + brief: 'Metadata fields to boost search results by. Overrides the instance-level boost_by config. Direction defaults to \'asc\' for numeric/datetime fields, \'exists\' for text/boolean fields. Fields must match \'timestamp\' or a defined custom_metadata field. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"field": string, "direction"?: "asc" | "desc" | "exists" | ...more}]. ? marks optional keys.', - }) - .option("ai-search-options-retrieval-context-expansion", { - type: "number", - description: "The ai_search_options.retrieval.context_expansion field", - }) - .option("ai-search-options-retrieval-filters", { - type: "string", - description: + optional: true, + parse: String, + }, + "ai-search-options-retrieval-context-expansion": { + kind: "parsed", + brief: "The ai_search_options.retrieval.context_expansion field", + optional: true, + parse: Number, + }, + "ai-search-options-retrieval-filters": { + kind: "parsed", + brief: 'The ai_search_options.retrieval.filters field. Provide as a JSON object or @path/to/file.json. Shape: {"": unknown}.', - }) - .option("ai-search-options-retrieval-fusion-method", { - type: "string", - description: "The ai_search_options.retrieval.fusion_method field", + optional: true, + parse: String, + }, + "ai-search-options-retrieval-fusion-method": { + kind: "parsed", + brief: "The ai_search_options.retrieval.fusion_method field", + optional: true, choices: ["max", "rrf"], - }) - .coerce("ai-search-options-retrieval-fusion-method", (value) => - resolveFileToken( - value, - "ai-search-options-retrieval-fusion-method", - "text" - ) - ) - .option("ai-search-options-retrieval-keyword-match-mode", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "ai-search-options-retrieval-fusion-method", + "text" + ), + }, + "ai-search-options-retrieval-keyword-match-mode": { + kind: "parsed", + brief: "Controls which documents become candidates for BM25 scoring. 'and' restricts candidates to documents containing all query terms; 'or' includes any document containing at least one term and ranks results according to BM25 relevance. When omitted, falls back to the instance-level retrieval_options.keyword_match_mode, then to 'and'.", + optional: true, choices: ["and", "or"], - }) - .coerce("ai-search-options-retrieval-keyword-match-mode", (value) => - resolveFileToken( - value, - "ai-search-options-retrieval-keyword-match-mode", - "text" - ) - ) - .option("ai-search-options-retrieval-match-threshold", { - type: "number", - description: + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "ai-search-options-retrieval-keyword-match-mode", + "text" + ), + }, + "ai-search-options-retrieval-match-threshold": { + kind: "parsed", + brief: "Minimum similarity score a chunk must reach to be returned. When omitted, falls back to the instance-level score_threshold, then to 0.4.", - }) - .option("ai-search-options-retrieval-max-num-results", { - type: "number", - description: + optional: true, + parse: Number, + }, + "ai-search-options-retrieval-max-num-results": { + kind: "parsed", + brief: "Maximum number of results to return. When omitted, falls back to the instance-level max_num_results, then to 10.", - }) - .option("ai-search-options-retrieval-retrieval-type", { - type: "string", - description: "The ai_search_options.retrieval.retrieval_type field", + optional: true, + parse: Number, + }, + "ai-search-options-retrieval-retrieval-type": { + kind: "parsed", + brief: "The ai_search_options.retrieval.retrieval_type field", + optional: true, choices: ["vector", "keyword", "hybrid"], - }) - .coerce("ai-search-options-retrieval-retrieval-type", (value) => - resolveFileToken( - value, - "ai-search-options-retrieval-retrieval-type", - "text" - ) - ) - .option("ai-search-options-retrieval-return-on-failure", { - type: "boolean", - description: "The ai_search_options.retrieval.return_on_failure field", - }) - .option("messages", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "ai-search-options-retrieval-retrieval-type", + "text" + ), + }, + "ai-search-options-retrieval-return-on-failure": { + kind: "boolean", + brief: "The ai_search_options.retrieval.return_on_failure field", + optional: true, + }, + messages: { + kind: "parsed", + brief: "OpenAI-compatible message array. For multimodal queries, set the last user message's `content` to an array of typed parts: `[{type:'text', text:'…'}, {type:'image_url', image_url:{url:'…'}}]`. Image inputs require the RAG's embedding_model to declare 'image' in supported_modalities. Provide as a JSON array of objects or @path/to/file.json. Shape: [{\"content\": (string | [{...}] | null), \"role\": \"system\" | \"developer\" | \"user\" | ...more, \"\": unknown}].", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "instance-id", + brief: "AI Search instance ID.", + parse: String, + }, + { + placeholder: "query", + brief: "Text to search for.", + parse: String, + optional: true, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "search [query]", describe: "Search", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search search", - classification: { - safeFlags: [ - "ai-search-options-cache-cache-threshold", - "ai-search-options-cache-enabled", - "ai-search-options-query-rewrite-enabled", - "ai-search-options-reranking-enabled", - "ai-search-options-retrieval-fusion-method", - "ai-search-options-retrieval-keyword-match-mode", - "ai-search-options-retrieval-retrieval-type", - "ai-search-options-retrieval-return-on-failure", - "dry-run", - ], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search search", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/search`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - "instance-id": String(argv["instance-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? mergeBodyPositionals(parseBody(argv.body), [ - { name: "query", field: "query", value: argv["query"] }, - ]) - : compactBody( - { - ai_search_options: { - cache: { - cache_threshold: - argv["ai-search-options-cache-cache-threshold"], - enabled: argv["ai-search-options-cache-enabled"], - }, - custom_metadata: parseJsonMap( - argv["ai-search-options-custom-metadata"], - "ai-search-options-custom-metadata" - ), - query_rewrite: { - enabled: - argv["ai-search-options-query-rewrite-enabled"], - model: resolveFileToken( - argv["ai-search-options-query-rewrite-model"] as - | string - | undefined, - "ai-search-options-query-rewrite-model", - "text" - ), - rewrite_prompt: resolveFileToken( - argv[ - "ai-search-options-query-rewrite-rewrite-prompt" - ] as string | undefined, - "ai-search-options-query-rewrite-rewrite-prompt", - "text" - ), - }, - reranking: { - enabled: argv["ai-search-options-reranking-enabled"], - match_threshold: - argv["ai-search-options-reranking-match-threshold"], - model: resolveFileToken( - argv["ai-search-options-reranking-model"] as - | string - | undefined, - "ai-search-options-reranking-model", - "text" - ), - }, - retrieval: { - boost_by: parseObjectArray( - argv["ai-search-options-retrieval-boost-by"], - "ai-search-options-retrieval-boost-by" - ), - context_expansion: - argv[ - "ai-search-options-retrieval-context-expansion" - ], - filters: parseJsonMap( - argv["ai-search-options-retrieval-filters"], - "ai-search-options-retrieval-filters" - ), - fusion_method: - argv["ai-search-options-retrieval-fusion-method"], - keyword_match_mode: - argv[ - "ai-search-options-retrieval-keyword-match-mode" - ], - match_threshold: - argv["ai-search-options-retrieval-match-threshold"], - max_num_results: - argv["ai-search-options-retrieval-max-num-results"], - retrieval_type: - argv["ai-search-options-retrieval-retrieval-type"], - return_on_failure: - argv[ - "ai-search-options-retrieval-return-on-failure" - ], - }, - }, - messages: parseObjectArray(argv["messages"], "messages"), - query: argv["query"], - }, - [ - ["ai_search_options", "custom_metadata"], - ["ai_search_options", "retrieval", "filters"], - ] - ), - }); - return; - } - const parsedBody = - argv.body !== undefined - ? mergeBodyPositionals(parseBody(argv.body), [ - { name: "query", field: "query", value: argv["query"] }, - ]) - : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Loading`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/search`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Loaded` }); - return; - } - - // Assemble request body from individual flags - const bodyData: Record = {}; - if (argv["ai-search-options-cache-cache-threshold"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "cache", "cache_threshold"], - argv["ai-search-options-cache-cache-threshold"] - ); - if (argv["ai-search-options-cache-enabled"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "cache", "enabled"], - argv["ai-search-options-cache-enabled"] - ); - if (argv["ai-search-options-custom-metadata"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "custom_metadata"], - parseJsonMap( - argv["ai-search-options-custom-metadata"], - "ai-search-options-custom-metadata" - ) - ); - if (argv["ai-search-options-query-rewrite-enabled"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "query_rewrite", "enabled"], - argv["ai-search-options-query-rewrite-enabled"] - ); - if (argv["ai-search-options-query-rewrite-model"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "query_rewrite", "model"], - resolveFileToken( - argv["ai-search-options-query-rewrite-model"] as - | string - | undefined, - "ai-search-options-query-rewrite-model", - "text" - ) - ); - if ( - argv["ai-search-options-query-rewrite-rewrite-prompt"] !== undefined - ) - setNestedValue( - bodyData, - ["ai_search_options", "query_rewrite", "rewrite_prompt"], - resolveFileToken( - argv["ai-search-options-query-rewrite-rewrite-prompt"] as - | string - | undefined, - "ai-search-options-query-rewrite-rewrite-prompt", - "text" - ) - ); - if (argv["ai-search-options-reranking-enabled"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "reranking", "enabled"], - argv["ai-search-options-reranking-enabled"] - ); - if (argv["ai-search-options-reranking-match-threshold"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "reranking", "match_threshold"], - argv["ai-search-options-reranking-match-threshold"] - ); - if (argv["ai-search-options-reranking-model"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "reranking", "model"], - resolveFileToken( - argv["ai-search-options-reranking-model"] as string | undefined, - "ai-search-options-reranking-model", - "text" - ) - ); - if (argv["ai-search-options-retrieval-boost-by"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "boost_by"], - parseObjectArray( - argv["ai-search-options-retrieval-boost-by"], - "ai-search-options-retrieval-boost-by" - ) - ); - if (argv["ai-search-options-retrieval-context-expansion"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "context_expansion"], - argv["ai-search-options-retrieval-context-expansion"] - ); - if (argv["ai-search-options-retrieval-filters"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "filters"], - parseJsonMap( - argv["ai-search-options-retrieval-filters"], - "ai-search-options-retrieval-filters" - ) - ); - if (argv["ai-search-options-retrieval-fusion-method"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "fusion_method"], - argv["ai-search-options-retrieval-fusion-method"] - ); - if ( - argv["ai-search-options-retrieval-keyword-match-mode"] !== undefined - ) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "keyword_match_mode"], - argv["ai-search-options-retrieval-keyword-match-mode"] - ); - if (argv["ai-search-options-retrieval-match-threshold"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "match_threshold"], - argv["ai-search-options-retrieval-match-threshold"] - ); - if (argv["ai-search-options-retrieval-max-num-results"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "max_num_results"], - argv["ai-search-options-retrieval-max-num-results"] - ); - if (argv["ai-search-options-retrieval-retrieval-type"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "retrieval_type"], - argv["ai-search-options-retrieval-retrieval-type"] - ); - if (argv["ai-search-options-retrieval-return-on-failure"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_options", "retrieval", "return_on_failure"], - argv["ai-search-options-retrieval-return-on-failure"] - ); - if (argv["messages"] !== undefined) - setNestedValue( - bodyData, - ["messages"], - parseObjectArray(argv["messages"], "messages") - ); - if (argv["query"] !== undefined) bodyData["query"] = argv["query"]; - const result = await withProgress(`Loading`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/search`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-search search [query]\n\nExecutes a semantic search query against an AI Search instance to find relevant indexed content.", + ...parameters, + loader: () => import("./search.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/stats.handler.ts b/packages/cli/src/commands/_generated/ai-search/stats.handler.ts new file mode 100644 index 0000000000..f8aca7eefb --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/stats.handler.ts @@ -0,0 +1,53 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./stats.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search stats", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search stats", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/stats`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + "instance-id": String(argv["instance-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + requestApi( + client, + "GET", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/stats` + ) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/stats.ts b/packages/cli/src/commands/_generated/ai-search/stats.ts index 1b51a1064a..26615a9279 100644 --- a/packages/cli/src/commands/_generated/ai-search/stats.ts +++ b/packages/cli/src/commands/_generated/ai-search/stats.ts @@ -1,88 +1,43 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * stats command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search stats \n\nRetrieve usage and indexing statistics for an AI Search instance." - ) - .positional("instance-id", { - type: "string", - description: "AI Search instance ID.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "instance-id", + brief: "AI Search instance ID.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "stats ", describe: "Get instance statistics.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search stats", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search stats", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}/stats`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - "instance-id": String(argv["instance-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - requestApi( - client, - "GET", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}/stats` - ) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-search stats \n\nRetrieve usage and indexing statistics for an AI Search instance.", + ...parameters, + loader: () => import("./stats.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/tokens/create.handler.ts b/packages/cli/src/commands/_generated/ai-search/tokens/create.handler.ts new file mode 100644 index 0000000000..789f76da22 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/tokens/create.handler.ts @@ -0,0 +1,122 @@ +import operation from "../../_operations/ai-search/tokens/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { + compactBody, + mergeBodyPositionals, + parseBody, +} from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search tokens create", + classification: { + safeFlags: ["legacy", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["api-token-id"] === undefined) { + argv["api-token-id"] = await promptForRequiredField( + "api-token-id", + "Cloudflare API token ID." + ); + } + if (argv["api-token"] === undefined) { + argv["api-token"] = await promptForRequiredField( + "api-token", + "Cloudflare API token value.", + { kind: "secret" } + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search tokens create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/tokens`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? mergeBodyPositionals(parseBody(argv.body), [ + { name: "name", field: "name", value: argv["name"] }, + ]) + : compactBody({ + cf_api_id: resolveFileToken( + argv["api-token-id"] as string | undefined, + "api-token-id", + "text" + ), + cf_api_key: resolveFileToken( + argv["api-token"] as string | undefined, + "api-token", + "text" + ), + legacy: argv["legacy"], + name: argv["name"], + }), + sensitiveBodyPaths: [["cf_api_key"]], + }); + return; + } + const parsedBody = + argv.body !== undefined + ? mergeBodyPositionals(parseBody(argv.body), [ + { name: "name", field: "name", value: argv["name"] }, + ]) + : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + cf_api_id: resolveFileToken( + argv["api-token-id"] as string | undefined, + "api-token-id", + "text" + ), + cf_api_key: resolveFileToken( + argv["api-token"] as string | undefined, + "api-token", + "text" + ), + legacy: argv["legacy"], + name: argv["name"], + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/tokens/create.ts b/packages/cli/src/commands/_generated/ai-search/tokens/create.ts index 0cda884edd..273ad8c6b0 100644 --- a/packages/cli/src/commands/_generated/ai-search/tokens/create.ts +++ b/packages/cli/src/commands/_generated/ai-search/tokens/create.ts @@ -1,169 +1,60 @@ -import operation from "../../_operations/ai-search/tokens/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { - compactBody, - mergeBodyPositionals, - parseBody, -} from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search tokens create \n\nCreate a stored Cloudflare credential for an AI Search instance to access its data source." - ) - .positional("name", { - type: "string", - description: "Human-readable name for the credential.", - demandOption: true, - }) - .option("api-token-id", { - type: "string", - description: "Cloudflare API token ID.", - }) - .option("api-token", { - type: "string", - description: "Cloudflare API token value.", - }) - .option("legacy", { - type: "boolean", - description: "Whether the credential uses the legacy API key format.", +const parameters = { + flags: { + "api-token-id": { + kind: "parsed", + brief: "Cloudflare API token ID.", + optional: true, + parse: String, + }, + "api-token": { + kind: "parsed", + brief: "Cloudflare API token value.", + optional: true, + parse: String, + }, + legacy: { + kind: "boolean", + brief: "Whether the credential uses the legacy API key format.", default: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "name", + brief: "Human-readable name for the credential.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Create a token", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search tokens create", - classification: { - safeFlags: ["legacy", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["api-token-id"] === undefined) { - argv["api-token-id"] = await promptForRequiredField( - "api-token-id", - "Cloudflare API token ID." - ); - } - if (argv["api-token"] === undefined) { - argv["api-token"] = await promptForRequiredField( - "api-token", - "Cloudflare API token value.", - { kind: "secret" } - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search tokens create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/tokens`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? mergeBodyPositionals(parseBody(argv.body), [ - { name: "name", field: "name", value: argv["name"] }, - ]) - : compactBody({ - cf_api_id: resolveFileToken( - argv["api-token-id"] as string | undefined, - "api-token-id", - "text" - ), - cf_api_key: resolveFileToken( - argv["api-token"] as string | undefined, - "api-token", - "text" - ), - legacy: argv["legacy"], - name: argv["name"], - }), - sensitiveBodyPaths: [["cf_api_key"]], - }); - return; - } - const parsedBody = - argv.body !== undefined - ? mergeBodyPositionals(parseBody(argv.body), [ - { name: "name", field: "name", value: argv["name"] }, - ]) - : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - cf_api_id: resolveFileToken( - argv["api-token-id"] as string | undefined, - "api-token-id", - "text" - ), - cf_api_key: resolveFileToken( - argv["api-token"] as string | undefined, - "api-token", - "text" - ), - legacy: argv["legacy"], - name: argv["name"], - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 ai-search tokens create \n\nCreate a stored Cloudflare credential for an AI Search instance to access its data source.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/tokens/delete.handler.ts b/packages/cli/src/commands/_generated/ai-search/tokens/delete.handler.ts new file mode 100644 index 0000000000..cf5f828269 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/tokens/delete.handler.ts @@ -0,0 +1,61 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search tokens delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search tokens delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/tokens/${argv["token-id"] == null ? "" : encodeURIComponent(String(argv["token-id"]))}`, + pathParams: { "token-id": String(argv["token-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This operation permanently deletes the stored credential.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + requestApi( + client, + "DELETE", + `/accounts/${accountId}/ai-search/tokens/${encodeURIComponent(String(argv["token-id"]))}` + ) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/tokens/delete.ts b/packages/cli/src/commands/_generated/ai-search/tokens/delete.ts index 25f270988b..2704163334 100644 --- a/packages/cli/src/commands/_generated/ai-search/tokens/delete.ts +++ b/packages/cli/src/commands/_generated/ai-search/tokens/delete.ts @@ -1,97 +1,43 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search tokens delete \n\nDeletes a stored AI Search credential permanently. Credentials in use by an instance cannot be deleted." - ) - .positional("token-id", { - type: "string", - description: "Stored credential record ID.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "token-id", + brief: "Stored credential record ID.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete a token", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search tokens delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search tokens delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/tokens/${argv["token-id"] == null ? "" : encodeURIComponent(String(argv["token-id"]))}`, - pathParams: { "token-id": String(argv["token-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This operation permanently deletes the stored credential.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - requestApi( - client, - "DELETE", - `/accounts/${accountId}/ai-search/tokens/${encodeURIComponent(String(argv["token-id"]))}` - ) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 ai-search tokens delete \n\nDeletes a stored AI Search credential permanently. Credentials in use by an instance cannot be deleted.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/tokens/get.handler.ts b/packages/cli/src/commands/_generated/ai-search/tokens/get.handler.ts new file mode 100644 index 0000000000..19238bdace --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/tokens/get.handler.ts @@ -0,0 +1,50 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search tokens get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search tokens get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/tokens/${argv["token-id"] == null ? "" : encodeURIComponent(String(argv["token-id"]))}`, + pathParams: { "token-id": String(argv["token-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + requestApi( + client, + "GET", + `/accounts/${accountId}/ai-search/tokens/${encodeURIComponent(String(argv["token-id"]))}` + ) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/tokens/get.ts b/packages/cli/src/commands/_generated/ai-search/tokens/get.ts index 6ab7a2a4d9..43e0674b2e 100644 --- a/packages/cli/src/commands/_generated/ai-search/tokens/get.ts +++ b/packages/cli/src/commands/_generated/ai-search/tokens/get.ts @@ -1,80 +1,37 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search tokens get \n\nRetrieve a stored AI Search credential without exposing its secret." - ) - .positional("token-id", { - type: "string", - description: "Stored credential record ID.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "token-id", + brief: "Stored credential record ID.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get a token", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search tokens get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search tokens get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/tokens/${argv["token-id"] == null ? "" : encodeURIComponent(String(argv["token-id"]))}`, - pathParams: { "token-id": String(argv["token-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - requestApi( - client, - "GET", - `/accounts/${accountId}/ai-search/tokens/${encodeURIComponent(String(argv["token-id"]))}` - ) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-search tokens get \n\nRetrieve a stored AI Search credential without exposing its secret.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/tokens/index.ts b/packages/cli/src/commands/_generated/ai-search/tokens/index.ts index 70b659e5e8..cb5dc12b4c 100644 --- a/packages/cli/src/commands/_generated/ai-search/tokens/index.ts +++ b/packages/cli/src/commands/_generated/ai-search/tokens/index.ts @@ -3,28 +3,23 @@ import $delete from "./delete.js"; import $get from "./get.js"; import $list from "./list.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * tokens command group * @generated from apis/overlays/ai-search.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "tokens", describe: "Credentials used by AI Search instances", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .command($list) - .command($update) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, + list: $list, + update: $update, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/tokens/list.handler.ts b/packages/cli/src/commands/_generated/ai-search/tokens/list.handler.ts new file mode 100644 index 0000000000..857f17abb8 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/tokens/list.handler.ts @@ -0,0 +1,52 @@ +import operation from "../../_operations/ai-search/tokens/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search tokens list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + search: argv["search"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search tokens list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/tokens`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/tokens/list.ts b/packages/cli/src/commands/_generated/ai-search/tokens/list.ts index 1c4907c783..36a75fd460 100644 --- a/packages/cli/src/commands/_generated/ai-search/tokens/list.ts +++ b/packages/cli/src/commands/_generated/ai-search/tokens/list.ts @@ -1,87 +1,50 @@ -import operation from "../../_operations/ai-search/tokens/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search tokens list\n\nLists stored AI Search credentials in the account without exposing their secrets." - ) - .option("page", { type: "number", description: "Page number (1-indexed)." }) - .option("per-page", { - type: "number", - description: "Number of results per page.", - }) - .option("search", { - type: "string", - description: +const parameters = { + flags: { + page: { + kind: "parsed", + brief: "Page number (1-indexed).", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Number of results per page.", + optional: true, + parse: Number, + }, + search: { + kind: "parsed", + brief: "Filter tokens whose name contains this string (case-insensitive).", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List tokens", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search tokens list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - search: argv["search"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search tokens list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/tokens`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-search tokens list\n\nLists stored AI Search credentials in the account without exposing their secrets.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/tokens/update.handler.ts b/packages/cli/src/commands/_generated/ai-search/tokens/update.handler.ts new file mode 100644 index 0000000000..875fafcb01 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/tokens/update.handler.ts @@ -0,0 +1,147 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, setNestedValue } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search tokens update", + classification: { + safeFlags: ["legacy", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["api-token-id"] === undefined) { + argv["api-token-id"] = await promptForRequiredField( + "api-token-id", + "Cloudflare API token ID." + ); + } + if (argv["api-token"] === undefined) { + argv["api-token"] = await promptForRequiredField( + "api-token", + "Cloudflare API token value.", + { kind: "secret" } + ); + } + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField( + "name", + "Human-readable name for the credential." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search tokens update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/tokens/${argv["token-id"] == null ? "" : encodeURIComponent(String(argv["token-id"]))}`, + pathParams: { "token-id": String(argv["token-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + cf_api_id: resolveFileToken( + argv["api-token-id"] as string | undefined, + "api-token-id", + "text" + ), + cf_api_key: resolveFileToken( + argv["api-token"] as string | undefined, + "api-token", + "text" + ), + legacy: argv["legacy"], + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + }), + sensitiveBodyPaths: [["cf_api_key"]], + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + requestApi( + client, + "PUT", + `/accounts/${accountId}/ai-search/tokens/${encodeURIComponent(String(argv["token-id"]))}`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData: Record = {}; + if (argv["api-token-id"] !== undefined) + setNestedValue( + bodyData, + ["cf_api_id"], + resolveFileToken( + argv["api-token-id"] as string | undefined, + "api-token-id", + "text" + ) + ); + if (argv["api-token"] !== undefined) + setNestedValue( + bodyData, + ["cf_api_key"], + resolveFileToken( + argv["api-token"] as string | undefined, + "api-token", + "text" + ) + ); + if (argv["legacy"] !== undefined) + setNestedValue(bodyData, ["legacy"], argv["legacy"]); + if (argv["name"] !== undefined) + setNestedValue( + bodyData, + ["name"], + resolveFileToken(argv["name"] as string | undefined, "name", "text") + ); + const result = await withProgress(`Updating`, async () => + requestApi( + client, + "PUT", + `/accounts/${accountId}/ai-search/tokens/${encodeURIComponent(String(argv["token-id"]))}`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/tokens/update.ts b/packages/cli/src/commands/_generated/ai-search/tokens/update.ts index f0fd4d83ab..d90769f256 100644 --- a/packages/cli/src/commands/_generated/ai-search/tokens/update.ts +++ b/packages/cli/src/commands/_generated/ai-search/tokens/update.ts @@ -1,197 +1,66 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, setNestedValue } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search tokens update \n\nReplace a stored AI Search credential and invalidate cached credentials for instances that use it." - ) - .positional("token-id", { - type: "string", - description: "Stored credential record ID.", - demandOption: true, - }) - .option("api-token-id", { - type: "string", - description: "Cloudflare API token ID.", - }) - .option("api-token", { - type: "string", - description: "Cloudflare API token value.", - }) - .option("legacy", { - type: "boolean", - description: "Whether the credential uses the legacy API key format.", - }) - .option("name", { - type: "string", - description: "Human-readable name for the credential.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "api-token-id": { + kind: "parsed", + brief: "Cloudflare API token ID.", + optional: true, + parse: String, + }, + "api-token": { + kind: "parsed", + brief: "Cloudflare API token value.", + optional: true, + parse: String, + }, + legacy: { + kind: "boolean", + brief: "Whether the credential uses the legacy API key format.", + optional: true, + }, + name: { + kind: "parsed", + brief: "Human-readable name for the credential.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "token-id", + brief: "Stored credential record ID.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update ", describe: "Update a token", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search tokens update", - classification: { - safeFlags: ["legacy", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["api-token-id"] === undefined) { - argv["api-token-id"] = await promptForRequiredField( - "api-token-id", - "Cloudflare API token ID." - ); - } - if (argv["api-token"] === undefined) { - argv["api-token"] = await promptForRequiredField( - "api-token", - "Cloudflare API token value.", - { kind: "secret" } - ); - } - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "Human-readable name for the credential." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search tokens update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/tokens/${argv["token-id"] == null ? "" : encodeURIComponent(String(argv["token-id"]))}`, - pathParams: { "token-id": String(argv["token-id"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - cf_api_id: resolveFileToken( - argv["api-token-id"] as string | undefined, - "api-token-id", - "text" - ), - cf_api_key: resolveFileToken( - argv["api-token"] as string | undefined, - "api-token", - "text" - ), - legacy: argv["legacy"], - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - }), - sensitiveBodyPaths: [["cf_api_key"]], - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - requestApi( - client, - "PUT", - `/accounts/${accountId}/ai-search/tokens/${encodeURIComponent(String(argv["token-id"]))}`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData: Record = {}; - if (argv["api-token-id"] !== undefined) - setNestedValue( - bodyData, - ["cf_api_id"], - resolveFileToken( - argv["api-token-id"] as string | undefined, - "api-token-id", - "text" - ) - ); - if (argv["api-token"] !== undefined) - setNestedValue( - bodyData, - ["cf_api_key"], - resolveFileToken( - argv["api-token"] as string | undefined, - "api-token", - "text" - ) - ); - if (argv["legacy"] !== undefined) - setNestedValue(bodyData, ["legacy"], argv["legacy"]); - if (argv["name"] !== undefined) - setNestedValue( - bodyData, - ["name"], - resolveFileToken(argv["name"] as string | undefined, "name", "text") - ); - const result = await withProgress(`Updating`, async () => - requestApi( - client, - "PUT", - `/accounts/${accountId}/ai-search/tokens/${encodeURIComponent(String(argv["token-id"]))}`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 ai-search tokens update \n\nReplace a stored AI Search credential and invalidate cached credentials for instances that use it.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-search/update.handler.ts b/packages/cli/src/commands/_generated/ai-search/update.handler.ts new file mode 100644 index 0000000000..f70dbeb46e --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-search/update.handler.ts @@ -0,0 +1,835 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { + compactBody, + parseBody, + parseJsonMap, + parseObjectArray, + setNestedValue, +} from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-search update", + classification: { + safeFlags: [ + "cache", + "cache-threshold", + "chunk", + "fusion-method", + "index-method-keyword", + "index-method-vector", + "indexing-options-file-summary", + "indexing-options-keyword-tokenizer", + "indexing-options-use-ocr", + "metadata-created-from-aisearch-wizard", + "metadata-created-from-emdash-plugin-type", + "paused", + "public-endpoint-params-chat-completions-endpoint-disabled", + "public-endpoint-params-default-domain-enabled", + "public-endpoint-params-enabled", + "public-endpoint-params-mcp-disabled", + "public-endpoint-params-rate-limit-technique", + "public-endpoint-params-search-endpoint-disabled", + "reranking", + "retrieval-options-keyword-match-mode", + "rewrite-query", + "source-params-d1-template", + "source-params-web-crawler-discover-options-include-external-links", + "source-params-web-crawler-discover-options-include-subdomains", + "source-params-web-crawler-discover-options-source", + "source-params-web-crawler-parse-options-include-images", + "source-params-web-crawler-parse-options-use-browser-rendering", + "source-params-web-crawler-parse-type", + "summarization", + "dry-run", + ], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai-search update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + "instance-id": String(argv["instance-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody( + { + ai_gateway_id: resolveFileToken( + argv["ai-gateway-id"] as string | undefined, + "ai-gateway-id", + "text" + ), + ai_search_model: resolveFileToken( + argv["ai-search-model"] as string | undefined, + "ai-search-model", + "text" + ), + cache: argv["cache"], + cache_threshold: argv["cache-threshold"], + cache_ttl: argv["cache-ttl"], + chunk: argv["chunk"], + chunk_overlap: argv["chunk-overlap"], + chunk_size: argv["chunk-size"], + custom_metadata: parseObjectArray( + argv["custom-metadata"], + "custom-metadata" + ), + embedding_model: resolveFileToken( + argv["embedding-model"] as string | undefined, + "embedding-model", + "text" + ), + fusion_method: argv["fusion-method"], + index_method: { + keyword: argv["index-method-keyword"], + vector: argv["index-method-vector"], + }, + indexing_options: { + file_summary: argv["indexing-options-file-summary"], + keyword_tokenizer: + argv["indexing-options-keyword-tokenizer"], + use_ocr: argv["indexing-options-use-ocr"], + }, + max_num_results: argv["max-num-results"], + metadata: { + created_from_aisearch_wizard: + argv["metadata-created-from-aisearch-wizard"], + created_from_emdash_plugin: { + type: argv["metadata-created-from-emdash-plugin-type"], + version: resolveFileToken( + argv[ + "metadata-created-from-emdash-plugin-version" + ] as string | undefined, + "metadata-created-from-emdash-plugin-version", + "text" + ), + }, + worker_domain: resolveFileToken( + argv["metadata-worker-domain"] as string | undefined, + "metadata-worker-domain", + "text" + ), + }, + paused: argv["paused"], + public_endpoint_params: { + authorized_hosts: + argv["public-endpoint-params-authorized-hosts"], + chat_completions_endpoint: { + disabled: + argv[ + "public-endpoint-params-chat-completions-endpoint-disabled" + ], + }, + custom_domains: + argv["public-endpoint-params-custom-domains"], + default_domain_enabled: + argv["public-endpoint-params-default-domain-enabled"], + enabled: argv["public-endpoint-params-enabled"], + mcp: { + description: resolveFileToken( + argv["public-endpoint-params-mcp-description"] as + | string + | undefined, + "public-endpoint-params-mcp-description", + "text" + ), + disabled: argv["public-endpoint-params-mcp-disabled"], + }, + rate_limit: { + period_ms: + argv["public-endpoint-params-rate-limit-period-ms"], + requests: + argv["public-endpoint-params-rate-limit-requests"], + technique: + argv["public-endpoint-params-rate-limit-technique"], + }, + search_endpoint: { + disabled: + argv[ + "public-endpoint-params-search-endpoint-disabled" + ], + }, + }, + reranking: argv["reranking"], + reranking_model: resolveFileToken( + argv["reranking-model"] as string | undefined, + "reranking-model", + "text" + ), + retrieval_options: { + boost_by: parseObjectArray( + argv["retrieval-options-boost-by"], + "retrieval-options-boost-by" + ), + keyword_match_mode: + argv["retrieval-options-keyword-match-mode"], + }, + rewrite_model: resolveFileToken( + argv["rewrite-model"] as string | undefined, + "rewrite-model", + "text" + ), + rewrite_query: argv["rewrite-query"], + score_threshold: argv["score-threshold"], + source: resolveFileToken( + argv["source"] as string | undefined, + "source", + "text" + ), + source_params: { + d1: { + query: resolveFileToken( + argv["source-params-d1-query"] as string | undefined, + "source-params-d1-query", + "text" + ), + template: argv["source-params-d1-template"], + }, + exclude_items: argv["source-params-exclude-items"], + include_items: argv["source-params-include-items"], + prefix: resolveFileToken( + argv["source-params-prefix"] as string | undefined, + "source-params-prefix", + "text" + ), + r2_jurisdiction: resolveFileToken( + argv["source-params-r2-jurisdiction"] as + | string + | undefined, + "source-params-r2-jurisdiction", + "text" + ), + web_crawler: { + discover_options: { + depth: + argv[ + "source-params-web-crawler-discover-options-depth" + ], + include_external_links: + argv[ + "source-params-web-crawler-discover-options-include-external-links" + ], + include_subdomains: + argv[ + "source-params-web-crawler-discover-options-include-subdomains" + ], + limit: + argv[ + "source-params-web-crawler-discover-options-limit" + ], + max_age: + argv[ + "source-params-web-crawler-discover-options-max-age" + ], + source: + argv[ + "source-params-web-crawler-discover-options-source" + ], + }, + parse_options: { + content_selector: parseObjectArray( + argv[ + "source-params-web-crawler-parse-options-content-selector" + ], + "source-params-web-crawler-parse-options-content-selector" + ), + include_headers: parseJsonMap( + argv[ + "source-params-web-crawler-parse-options-include-headers" + ], + "source-params-web-crawler-parse-options-include-headers" + ), + include_images: + argv[ + "source-params-web-crawler-parse-options-include-images" + ], + specific_sitemaps: + argv[ + "source-params-web-crawler-parse-options-specific-sitemaps" + ], + use_browser_rendering: + argv[ + "source-params-web-crawler-parse-options-use-browser-rendering" + ], + }, + parse_type: + argv["source-params-web-crawler-parse-type"], + }, + }, + summarization: argv["summarization"], + summarization_model: resolveFileToken( + argv["summarization-model"] as string | undefined, + "summarization-model", + "text" + ), + sync_interval: argv["sync-interval"], + system_prompt_ai_search: resolveFileToken( + argv["system-prompt-ai-search"] as string | undefined, + "system-prompt-ai-search", + "text" + ), + system_prompt_index_summarization: resolveFileToken( + argv["system-prompt-index-summarization"] as + | string + | undefined, + "system-prompt-index-summarization", + "text" + ), + system_prompt_rewrite_query: resolveFileToken( + argv["system-prompt-rewrite-query"] as string | undefined, + "system-prompt-rewrite-query", + "text" + ), + token_id: resolveFileToken( + argv["token-id"] as string | undefined, + "token-id", + "text" + ), + }, + [ + [ + "source_params", + "web_crawler", + "parse_options", + "include_headers", + ], + ] + ), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + requestApi( + client, + "PUT", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData: Record = {}; + if (argv["ai-gateway-id"] !== undefined) + setNestedValue( + bodyData, + ["ai_gateway_id"], + resolveFileToken( + argv["ai-gateway-id"] as string | undefined, + "ai-gateway-id", + "text" + ) + ); + if (argv["ai-search-model"] !== undefined) + setNestedValue( + bodyData, + ["ai_search_model"], + resolveFileToken( + argv["ai-search-model"] as string | undefined, + "ai-search-model", + "text" + ) + ); + if (argv["cache"] !== undefined) + setNestedValue(bodyData, ["cache"], argv["cache"]); + if (argv["cache-threshold"] !== undefined) + setNestedValue(bodyData, ["cache_threshold"], argv["cache-threshold"]); + if (argv["cache-ttl"] !== undefined) + setNestedValue(bodyData, ["cache_ttl"], argv["cache-ttl"]); + if (argv["chunk"] !== undefined) + setNestedValue(bodyData, ["chunk"], argv["chunk"]); + if (argv["chunk-overlap"] !== undefined) + setNestedValue(bodyData, ["chunk_overlap"], argv["chunk-overlap"]); + if (argv["chunk-size"] !== undefined) + setNestedValue(bodyData, ["chunk_size"], argv["chunk-size"]); + if (argv["custom-metadata"] !== undefined) + setNestedValue( + bodyData, + ["custom_metadata"], + parseObjectArray(argv["custom-metadata"], "custom-metadata") + ); + if (argv["embedding-model"] !== undefined) + setNestedValue( + bodyData, + ["embedding_model"], + resolveFileToken( + argv["embedding-model"] as string | undefined, + "embedding-model", + "text" + ) + ); + if (argv["fusion-method"] !== undefined) + setNestedValue(bodyData, ["fusion_method"], argv["fusion-method"]); + if (argv["index-method-keyword"] !== undefined) + setNestedValue( + bodyData, + ["index_method", "keyword"], + argv["index-method-keyword"] + ); + if (argv["index-method-vector"] !== undefined) + setNestedValue( + bodyData, + ["index_method", "vector"], + argv["index-method-vector"] + ); + if (argv["indexing-options-file-summary"] !== undefined) + setNestedValue( + bodyData, + ["indexing_options", "file_summary"], + argv["indexing-options-file-summary"] + ); + if (argv["indexing-options-keyword-tokenizer"] !== undefined) + setNestedValue( + bodyData, + ["indexing_options", "keyword_tokenizer"], + argv["indexing-options-keyword-tokenizer"] + ); + if (argv["indexing-options-use-ocr"] !== undefined) + setNestedValue( + bodyData, + ["indexing_options", "use_ocr"], + argv["indexing-options-use-ocr"] + ); + if (argv["max-num-results"] !== undefined) + setNestedValue(bodyData, ["max_num_results"], argv["max-num-results"]); + if (argv["metadata-created-from-aisearch-wizard"] !== undefined) + setNestedValue( + bodyData, + ["metadata", "created_from_aisearch_wizard"], + argv["metadata-created-from-aisearch-wizard"] + ); + if (argv["metadata-created-from-emdash-plugin-type"] !== undefined) + setNestedValue( + bodyData, + ["metadata", "created_from_emdash_plugin", "type"], + argv["metadata-created-from-emdash-plugin-type"] + ); + if (argv["metadata-created-from-emdash-plugin-version"] !== undefined) + setNestedValue( + bodyData, + ["metadata", "created_from_emdash_plugin", "version"], + resolveFileToken( + argv["metadata-created-from-emdash-plugin-version"] as + | string + | undefined, + "metadata-created-from-emdash-plugin-version", + "text" + ) + ); + if (argv["metadata-worker-domain"] !== undefined) + setNestedValue( + bodyData, + ["metadata", "worker_domain"], + resolveFileToken( + argv["metadata-worker-domain"] as string | undefined, + "metadata-worker-domain", + "text" + ) + ); + if (argv["paused"] !== undefined) + setNestedValue(bodyData, ["paused"], argv["paused"]); + if (argv["public-endpoint-params-authorized-hosts"] !== undefined) + setNestedValue( + bodyData, + ["public_endpoint_params", "authorized_hosts"], + argv["public-endpoint-params-authorized-hosts"] + ); + if ( + argv["public-endpoint-params-chat-completions-endpoint-disabled"] !== + undefined + ) + setNestedValue( + bodyData, + ["public_endpoint_params", "chat_completions_endpoint", "disabled"], + argv["public-endpoint-params-chat-completions-endpoint-disabled"] + ); + if (argv["public-endpoint-params-custom-domains"] !== undefined) + setNestedValue( + bodyData, + ["public_endpoint_params", "custom_domains"], + argv["public-endpoint-params-custom-domains"] + ); + if (argv["public-endpoint-params-default-domain-enabled"] !== undefined) + setNestedValue( + bodyData, + ["public_endpoint_params", "default_domain_enabled"], + argv["public-endpoint-params-default-domain-enabled"] + ); + if (argv["public-endpoint-params-enabled"] !== undefined) + setNestedValue( + bodyData, + ["public_endpoint_params", "enabled"], + argv["public-endpoint-params-enabled"] + ); + if (argv["public-endpoint-params-mcp-description"] !== undefined) + setNestedValue( + bodyData, + ["public_endpoint_params", "mcp", "description"], + resolveFileToken( + argv["public-endpoint-params-mcp-description"] as + | string + | undefined, + "public-endpoint-params-mcp-description", + "text" + ) + ); + if (argv["public-endpoint-params-mcp-disabled"] !== undefined) + setNestedValue( + bodyData, + ["public_endpoint_params", "mcp", "disabled"], + argv["public-endpoint-params-mcp-disabled"] + ); + if (argv["public-endpoint-params-rate-limit-period-ms"] !== undefined) + setNestedValue( + bodyData, + ["public_endpoint_params", "rate_limit", "period_ms"], + argv["public-endpoint-params-rate-limit-period-ms"] + ); + if (argv["public-endpoint-params-rate-limit-requests"] !== undefined) + setNestedValue( + bodyData, + ["public_endpoint_params", "rate_limit", "requests"], + argv["public-endpoint-params-rate-limit-requests"] + ); + if (argv["public-endpoint-params-rate-limit-technique"] !== undefined) + setNestedValue( + bodyData, + ["public_endpoint_params", "rate_limit", "technique"], + argv["public-endpoint-params-rate-limit-technique"] + ); + if (argv["public-endpoint-params-search-endpoint-disabled"] !== undefined) + setNestedValue( + bodyData, + ["public_endpoint_params", "search_endpoint", "disabled"], + argv["public-endpoint-params-search-endpoint-disabled"] + ); + if (argv["reranking"] !== undefined) + setNestedValue(bodyData, ["reranking"], argv["reranking"]); + if (argv["reranking-model"] !== undefined) + setNestedValue( + bodyData, + ["reranking_model"], + resolveFileToken( + argv["reranking-model"] as string | undefined, + "reranking-model", + "text" + ) + ); + if (argv["retrieval-options-boost-by"] !== undefined) + setNestedValue( + bodyData, + ["retrieval_options", "boost_by"], + parseObjectArray( + argv["retrieval-options-boost-by"], + "retrieval-options-boost-by" + ) + ); + if (argv["retrieval-options-keyword-match-mode"] !== undefined) + setNestedValue( + bodyData, + ["retrieval_options", "keyword_match_mode"], + argv["retrieval-options-keyword-match-mode"] + ); + if (argv["rewrite-model"] !== undefined) + setNestedValue( + bodyData, + ["rewrite_model"], + resolveFileToken( + argv["rewrite-model"] as string | undefined, + "rewrite-model", + "text" + ) + ); + if (argv["rewrite-query"] !== undefined) + setNestedValue(bodyData, ["rewrite_query"], argv["rewrite-query"]); + if (argv["score-threshold"] !== undefined) + setNestedValue(bodyData, ["score_threshold"], argv["score-threshold"]); + if (argv["source"] !== undefined) + setNestedValue( + bodyData, + ["source"], + resolveFileToken( + argv["source"] as string | undefined, + "source", + "text" + ) + ); + if (argv["source-params-d1-query"] !== undefined) + setNestedValue( + bodyData, + ["source_params", "d1", "query"], + resolveFileToken( + argv["source-params-d1-query"] as string | undefined, + "source-params-d1-query", + "text" + ) + ); + if (argv["source-params-d1-template"] !== undefined) + setNestedValue( + bodyData, + ["source_params", "d1", "template"], + argv["source-params-d1-template"] + ); + if (argv["source-params-exclude-items"] !== undefined) + setNestedValue( + bodyData, + ["source_params", "exclude_items"], + argv["source-params-exclude-items"] + ); + if (argv["source-params-include-items"] !== undefined) + setNestedValue( + bodyData, + ["source_params", "include_items"], + argv["source-params-include-items"] + ); + if (argv["source-params-prefix"] !== undefined) + setNestedValue( + bodyData, + ["source_params", "prefix"], + resolveFileToken( + argv["source-params-prefix"] as string | undefined, + "source-params-prefix", + "text" + ) + ); + if (argv["source-params-r2-jurisdiction"] !== undefined) + setNestedValue( + bodyData, + ["source_params", "r2_jurisdiction"], + resolveFileToken( + argv["source-params-r2-jurisdiction"] as string | undefined, + "source-params-r2-jurisdiction", + "text" + ) + ); + if ( + argv["source-params-web-crawler-discover-options-depth"] !== undefined + ) + setNestedValue( + bodyData, + ["source_params", "web_crawler", "discover_options", "depth"], + argv["source-params-web-crawler-discover-options-depth"] + ); + if ( + argv[ + "source-params-web-crawler-discover-options-include-external-links" + ] !== undefined + ) + setNestedValue( + bodyData, + [ + "source_params", + "web_crawler", + "discover_options", + "include_external_links", + ], + argv[ + "source-params-web-crawler-discover-options-include-external-links" + ] + ); + if ( + argv[ + "source-params-web-crawler-discover-options-include-subdomains" + ] !== undefined + ) + setNestedValue( + bodyData, + [ + "source_params", + "web_crawler", + "discover_options", + "include_subdomains", + ], + argv["source-params-web-crawler-discover-options-include-subdomains"] + ); + if ( + argv["source-params-web-crawler-discover-options-limit"] !== undefined + ) + setNestedValue( + bodyData, + ["source_params", "web_crawler", "discover_options", "limit"], + argv["source-params-web-crawler-discover-options-limit"] + ); + if ( + argv["source-params-web-crawler-discover-options-max-age"] !== undefined + ) + setNestedValue( + bodyData, + ["source_params", "web_crawler", "discover_options", "max_age"], + argv["source-params-web-crawler-discover-options-max-age"] + ); + if ( + argv["source-params-web-crawler-discover-options-source"] !== undefined + ) + setNestedValue( + bodyData, + ["source_params", "web_crawler", "discover_options", "source"], + argv["source-params-web-crawler-discover-options-source"] + ); + if ( + argv["source-params-web-crawler-parse-options-content-selector"] !== + undefined + ) + setNestedValue( + bodyData, + ["source_params", "web_crawler", "parse_options", "content_selector"], + parseObjectArray( + argv["source-params-web-crawler-parse-options-content-selector"], + "source-params-web-crawler-parse-options-content-selector" + ) + ); + if ( + argv["source-params-web-crawler-parse-options-include-headers"] !== + undefined + ) + setNestedValue( + bodyData, + ["source_params", "web_crawler", "parse_options", "include_headers"], + parseJsonMap( + argv["source-params-web-crawler-parse-options-include-headers"], + "source-params-web-crawler-parse-options-include-headers" + ) + ); + if ( + argv["source-params-web-crawler-parse-options-include-images"] !== + undefined + ) + setNestedValue( + bodyData, + ["source_params", "web_crawler", "parse_options", "include_images"], + argv["source-params-web-crawler-parse-options-include-images"] + ); + if ( + argv["source-params-web-crawler-parse-options-specific-sitemaps"] !== + undefined + ) + setNestedValue( + bodyData, + [ + "source_params", + "web_crawler", + "parse_options", + "specific_sitemaps", + ], + argv["source-params-web-crawler-parse-options-specific-sitemaps"] + ); + if ( + argv[ + "source-params-web-crawler-parse-options-use-browser-rendering" + ] !== undefined + ) + setNestedValue( + bodyData, + [ + "source_params", + "web_crawler", + "parse_options", + "use_browser_rendering", + ], + argv["source-params-web-crawler-parse-options-use-browser-rendering"] + ); + if (argv["source-params-web-crawler-parse-type"] !== undefined) + setNestedValue( + bodyData, + ["source_params", "web_crawler", "parse_type"], + argv["source-params-web-crawler-parse-type"] + ); + if (argv["summarization"] !== undefined) + setNestedValue(bodyData, ["summarization"], argv["summarization"]); + if (argv["summarization-model"] !== undefined) + setNestedValue( + bodyData, + ["summarization_model"], + resolveFileToken( + argv["summarization-model"] as string | undefined, + "summarization-model", + "text" + ) + ); + if (argv["sync-interval"] !== undefined) + setNestedValue(bodyData, ["sync_interval"], argv["sync-interval"]); + if (argv["system-prompt-ai-search"] !== undefined) + setNestedValue( + bodyData, + ["system_prompt_ai_search"], + resolveFileToken( + argv["system-prompt-ai-search"] as string | undefined, + "system-prompt-ai-search", + "text" + ) + ); + if (argv["system-prompt-index-summarization"] !== undefined) + setNestedValue( + bodyData, + ["system_prompt_index_summarization"], + resolveFileToken( + argv["system-prompt-index-summarization"] as string | undefined, + "system-prompt-index-summarization", + "text" + ) + ); + if (argv["system-prompt-rewrite-query"] !== undefined) + setNestedValue( + bodyData, + ["system_prompt_rewrite_query"], + resolveFileToken( + argv["system-prompt-rewrite-query"] as string | undefined, + "system-prompt-rewrite-query", + "text" + ) + ); + if (argv["token-id"] !== undefined) + setNestedValue( + bodyData, + ["token_id"], + resolveFileToken( + argv["token-id"] as string | undefined, + "token-id", + "text" + ) + ); + const result = await withProgress(`Updating`, async () => + requestApi( + client, + "PUT", + `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}`, + { body: bodyData } + ) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-search/update.ts b/packages/cli/src/commands/_generated/ai-search/update.ts index f7037adf8e..0895634035 100644 --- a/packages/cli/src/commands/_generated/ai-search/update.ts +++ b/packages/cli/src/commands/_generated/ai-search/update.ts @@ -1,397 +1,483 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/ai-search.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { - compactBody, - parseBody, - parseJsonMap, - parseObjectArray, - setNestedValue, -} from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-search update \n\nUpdates the configuration of an AI Search instance." - ) - .positional("instance-id", { - type: "string", - description: "AI Search instance ID.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Namespace to use for this operation.", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Namespace to use for this operation.", default: "default", - }) - .option("ai-gateway-id", { - type: "string", - description: "The ai_gateway_id field", - }) - .option("ai-search-model", { - type: "string", - description: + parse: String, + }, + "ai-gateway-id": { + kind: "parsed", + brief: "The ai_gateway_id field", + optional: true, + parse: String, + }, + "ai-search-model": { + kind: "parsed", + brief: "A Workers AI model ID or an AI Gateway model ID compatible with the OpenAI Chat Completions API. An empty string uses the configured or default model.", - }) - .option("cache", { type: "boolean", description: "The cache field" }) - .option("cache-threshold", { - type: "string", - description: "The cache_threshold field", + optional: true, + parse: String, + }, + cache: { kind: "boolean", brief: "The cache field", optional: true }, + "cache-threshold": { + kind: "parsed", + brief: "The cache_threshold field", + optional: true, choices: [ "super_strict_match", "close_enough", "flexible_friend", "anything_goes", ], - }) - .coerce("cache-threshold", (value) => - resolveFileToken(value, "cache-threshold", "text") - ) - .option("cache-ttl", { - type: "number", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "cache-threshold", "text"), + }, + "cache-ttl": { + kind: "parsed", + brief: "Cache entry TTL in seconds. Allowed values: 600 (10min), 1800 (30min), 3600 (1h), 7200 (2h), 21600 (6h), 43200 (12h), 86400 (24h), 172800 (48h), 259200 (72h), 518400 (6d).", - }) - .option("chunk", { type: "boolean", description: "The chunk field" }) - .option("chunk-overlap", { - type: "number", - description: "The chunk_overlap field", - }) - .option("chunk-size", { - type: "number", - description: "The chunk_size field", - }) - .option("custom-metadata", { - type: "string", - description: + optional: true, + parse: Number, + }, + chunk: { kind: "boolean", brief: "The chunk field", optional: true }, + "chunk-overlap": { + kind: "parsed", + brief: "The chunk_overlap field", + optional: true, + parse: Number, + }, + "chunk-size": { + kind: "parsed", + brief: "The chunk_size field", + optional: true, + parse: Number, + }, + "custom-metadata": { + kind: "parsed", + brief: 'The custom_metadata field. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"data_type": "text" | "number" | "boolean" | ...more, "field_name": string}].', - }) - .option("embedding-model", { - type: "string", - description: "The embedding_model field", - }) - .option("fusion-method", { - type: "string", - description: "The fusion_method field", + optional: true, + parse: String, + }, + "embedding-model": { + kind: "parsed", + brief: "The embedding_model field", + optional: true, + parse: String, + }, + "fusion-method": { + kind: "parsed", + brief: "The fusion_method field", + optional: true, choices: ["max", "rrf"], - }) - .coerce("fusion-method", (value) => - resolveFileToken(value, "fusion-method", "text") - ) - .option("index-method-keyword", { - type: "boolean", - description: "Enable keyword (BM25) storage backend.", - }) - .option("index-method-vector", { - type: "boolean", - description: "Enable vector (embedding) storage backend.", - }) - .option("indexing-options-file-summary", { - type: "boolean", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "fusion-method", "text"), + }, + "index-method-keyword": { + kind: "boolean", + brief: "Enable keyword (BM25) storage backend.", + optional: true, + }, + "index-method-vector": { + kind: "boolean", + brief: "Enable vector (embedding) storage backend.", + optional: true, + }, + "indexing-options-file-summary": { + kind: "boolean", + brief: "Generates a per-file summary, topics, and keywords during indexing for text files and media transcripts of at least three chunks. The summary and keywords are stored as the item's context metadata (a context you set is kept), and the topics are added to chunk context headers where they fit. Best effort: a file whose summary fails is indexed without one. The model calls are billed to your account through the instance's AI Gateway. Changing this triggers a full re-index. Defaults to false.", - }) - .option("indexing-options-keyword-tokenizer", { - type: "string", - description: + optional: true, + }, + "indexing-options-keyword-tokenizer": { + kind: "parsed", + brief: "Tokenizer used for keyword search indexing. porter provides word-level tokenization with Porter stemming (good for natural language queries). trigram enables character-level substring matching (good for partial matches, code, identifiers). Changing this triggers a full re-index. Defaults to porter.", + optional: true, choices: ["porter", "trigram"], - }) - .coerce("indexing-options-keyword-tokenizer", (value) => - resolveFileToken(value, "indexing-options-keyword-tokenizer", "text") - ) - .option("indexing-options-use-ocr", { - type: "boolean", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "indexing-options-keyword-tokenizer", "text"), + }, + "indexing-options-use-ocr": { + kind: "boolean", + brief: "Enables OCR ingestion for PDFs and images. Changing this triggers a full re-index. Defaults to false.", - }) - .option("max-num-results", { - type: "number", - description: "The max_num_results field", - }) - .option("metadata-created-from-aisearch-wizard", { - type: "boolean", - description: "The metadata.created_from_aisearch_wizard field", - }) - .option("metadata-created-from-emdash-plugin-type", { - type: "string", - description: "The metadata.created_from_emdash_plugin.type field", + optional: true, + }, + "max-num-results": { + kind: "parsed", + brief: "The max_num_results field", + optional: true, + parse: Number, + }, + "metadata-created-from-aisearch-wizard": { + kind: "boolean", + brief: "The metadata.created_from_aisearch_wizard field", + optional: true, + }, + "metadata-created-from-emdash-plugin-type": { + kind: "parsed", + brief: "The metadata.created_from_emdash_plugin.type field", + optional: true, choices: ["native", "rest"], - }) - .coerce("metadata-created-from-emdash-plugin-type", (value) => - resolveFileToken( - value, - "metadata-created-from-emdash-plugin-type", - "text" - ) - ) - .option("metadata-created-from-emdash-plugin-version", { - type: "string", - description: "The metadata.created_from_emdash_plugin.version field", - }) - .option("metadata-worker-domain", { - type: "string", - description: "The metadata.worker_domain field", - }) - .option("paused", { type: "boolean", description: "The paused field" }) - .option("public-endpoint-params-authorized-hosts", { - type: "string", - array: true, - description: "The public_endpoint_params.authorized_hosts field", - }) - .option("public-endpoint-params-chat-completions-endpoint-disabled", { - type: "boolean", - description: - "Disable chat completions endpoint for this public endpoint.", - }) - .option("public-endpoint-params-custom-domains", { - type: "string", - array: true, - description: + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "metadata-created-from-emdash-plugin-type", + "text" + ), + }, + "metadata-created-from-emdash-plugin-version": { + kind: "parsed", + brief: "The metadata.created_from_emdash_plugin.version field", + optional: true, + parse: String, + }, + "metadata-worker-domain": { + kind: "parsed", + brief: "The metadata.worker_domain field", + optional: true, + parse: String, + }, + paused: { kind: "boolean", brief: "The paused field", optional: true }, + "public-endpoint-params-authorized-hosts": { + kind: "parsed", + brief: "The public_endpoint_params.authorized_hosts field", + variadic: true, + optional: true, + parse: String, + }, + "public-endpoint-params-chat-completions-endpoint-disabled": { + kind: "boolean", + brief: "Disable chat completions endpoint for this public endpoint.", + optional: true, + }, + "public-endpoint-params-custom-domains": { + kind: "parsed", + brief: "Custom domain hostnames that alias this public endpoint. GET and create responses return the current set; on update (PUT) this field is only echoed back when supplied in the request body, otherwise it is null (omit it to leave domains unchanged).", - }) - .option("public-endpoint-params-default-domain-enabled", { - type: "boolean", - description: + variadic: true, + optional: true, + parse: String, + }, + "public-endpoint-params-default-domain-enabled": { + kind: "boolean", + brief: "When false, the instance is reachable only via a registered custom domain and the default .search.ai.cloudflare.com host returns 404. Requires at least one custom domain. Defaults to true. public_endpoint_params is replaced wholesale on update, so resend default_domain_enabled on every update to keep the default host off — omitting it resets to true.", - }) - .option("public-endpoint-params-enabled", { - type: "boolean", - description: "The public_endpoint_params.enabled field", - }) - .option("public-endpoint-params-mcp-description", { - type: "string", - description: "The public_endpoint_params.mcp.description field", - }) - .option("public-endpoint-params-mcp-disabled", { - type: "boolean", - description: "Disable MCP endpoint for this public endpoint.", - }) - .option("public-endpoint-params-rate-limit-period-ms", { - type: "number", - description: "The public_endpoint_params.rate_limit.period_ms field", - }) - .option("public-endpoint-params-rate-limit-requests", { - type: "number", - description: "The public_endpoint_params.rate_limit.requests field", - }) - .option("public-endpoint-params-rate-limit-technique", { - type: "string", - description: "The public_endpoint_params.rate_limit.technique field", + optional: true, + }, + "public-endpoint-params-enabled": { + kind: "boolean", + brief: "The public_endpoint_params.enabled field", + optional: true, + }, + "public-endpoint-params-mcp-description": { + kind: "parsed", + brief: "The public_endpoint_params.mcp.description field", + optional: true, + parse: String, + }, + "public-endpoint-params-mcp-disabled": { + kind: "boolean", + brief: "Disable MCP endpoint for this public endpoint.", + optional: true, + }, + "public-endpoint-params-rate-limit-period-ms": { + kind: "parsed", + brief: "The public_endpoint_params.rate_limit.period_ms field", + optional: true, + parse: Number, + }, + "public-endpoint-params-rate-limit-requests": { + kind: "parsed", + brief: "The public_endpoint_params.rate_limit.requests field", + optional: true, + parse: Number, + }, + "public-endpoint-params-rate-limit-technique": { + kind: "parsed", + brief: "The public_endpoint_params.rate_limit.technique field", + optional: true, choices: ["fixed", "sliding"], - }) - .coerce("public-endpoint-params-rate-limit-technique", (value) => - resolveFileToken( - value, - "public-endpoint-params-rate-limit-technique", - "text" - ) - ) - .option("public-endpoint-params-search-endpoint-disabled", { - type: "boolean", - description: "Disable search endpoint for this public endpoint.", - }) - .option("reranking", { - type: "boolean", - description: "The reranking field", - }) - .option("reranking-model", { - type: "string", - description: "The reranking_model field", - }) - .option("retrieval-options-boost-by", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "public-endpoint-params-rate-limit-technique", + "text" + ), + }, + "public-endpoint-params-search-endpoint-disabled": { + kind: "boolean", + brief: "Disable search endpoint for this public endpoint.", + optional: true, + }, + reranking: { + kind: "boolean", + brief: "The reranking field", + optional: true, + }, + "reranking-model": { + kind: "parsed", + brief: "The reranking_model field", + optional: true, + parse: String, + }, + "retrieval-options-boost-by": { + kind: "parsed", + brief: 'Metadata fields to boost search results by. Each entry specifies a metadata field and an optional direction. Direction defaults to \'asc\' for numeric/datetime fields and \'exists\' for text/boolean fields. Fields must match \'timestamp\' or a defined custom_metadata field. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"field": string, "direction"?: "asc" | "desc" | "exists" | ...more}]. ? marks optional keys.', - }) - .option("retrieval-options-keyword-match-mode", { - type: "string", - description: + optional: true, + parse: String, + }, + "retrieval-options-keyword-match-mode": { + kind: "parsed", + brief: "Controls which documents become candidates for BM25 scoring. 'and' restricts candidates to documents containing all query terms; 'or' includes any document containing at least one term and ranks results according to BM25 relevance. When omitted on an update, the existing stored value stays unchanged; when never set, search falls back to 'and'.", + optional: true, choices: ["and", "or"], - }) - .coerce("retrieval-options-keyword-match-mode", (value) => - resolveFileToken(value, "retrieval-options-keyword-match-mode", "text") - ) - .option("rewrite-model", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "retrieval-options-keyword-match-mode", "text"), + }, + "rewrite-model": { + kind: "parsed", + brief: "A Workers AI model ID or an AI Gateway model ID compatible with the OpenAI Chat Completions API. An empty string uses the configured or default model.", - }) - .option("rewrite-query", { - type: "boolean", - description: "The rewrite_query field", - }) - .option("score-threshold", { - type: "number", - description: + optional: true, + parse: String, + }, + "rewrite-query": { + kind: "boolean", + brief: "The rewrite_query field", + optional: true, + }, + "score-threshold": { + kind: "parsed", + brief: "Minimum similarity score a chunk must reach to be returned. Defaults to 0.4.", - }) - .option("source", { - type: "string", - description: "R2 bucket name or HTTP(S) root website URL to index.", - }) - .option("source-params-d1-query", { - type: "string", - description: + optional: true, + parse: Number, + }, + source: { + kind: "parsed", + brief: "R2 bucket name or HTTP(S) root website URL to index.", + optional: true, + parse: String, + }, + "source-params-d1-query": { + kind: "parsed", + brief: "Read-only SELECT query run against the D1 database. It must return an `id` column that uniquely identifies each row. Columns named `title` and `content` set the document title and body, and up to 5 `meta_*` columns become filterable custom metadata; any other column is indexed as a labelled field. Every sync reads the full result, up to 100,000 rows, with the instance's token, and those reads count against your D1 usage. Leading and trailing whitespace is trimmed before the query is stored. Omit to keep the stored query.", - }) - .option("source-params-d1-template", { - type: "string", - description: + optional: true, + parse: String, + }, + "source-params-d1-template": { + kind: "parsed", + brief: "How each row is rendered into the indexed document: labelled renders the title, the labelled fields, then the content; content_only renders the title and content (labelled fields only when there is no content); key_value renders every column as name: value; json renders every column as a JSON object. Omit to keep the stored template.", + optional: true, choices: ["labelled", "content_only", "key_value", "json"], - }) - .coerce("source-params-d1-template", (value) => - resolveFileToken(value, "source-params-d1-template", "text") - ) - .option("source-params-exclude-items", { - type: "string", - array: true, - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "source-params-d1-template", "text"), + }, + "source-params-exclude-items": { + kind: "parsed", + brief: "List of path patterns to exclude. Uses micromatch glob syntax: * matches within a path segment, ** matches across path segments (e.g., /admin/** matches /admin/users and /admin/settings/advanced). Most accounts have a limit of 10 rules; contact support to raise it.", - }) - .option("source-params-include-items", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + "source-params-include-items": { + kind: "parsed", + brief: "List of path patterns to include. Uses micromatch glob syntax: * matches within a path segment, ** matches across path segments (e.g., /blog/** matches /blog/post and /blog/2024/post). Most accounts have a limit of 10 rules; contact support to raise it.", - }) - .option("source-params-prefix", { - type: "string", - description: "The source_params.prefix field", - }) - .option("source-params-r2-jurisdiction", { - type: "string", - description: "The source_params.r2_jurisdiction field", - }) - .option("source-params-web-crawler-discover-options-depth", { - type: "number", - description: "Maximum link-follow depth from the seed URL.", - }) - .option( - "source-params-web-crawler-discover-options-include-external-links", - { - type: "boolean", - description: - "Follow links that point outside the source domain. Must stay `false` because discover crawls only cover the zone you own.", - } - ) - .option("source-params-web-crawler-discover-options-include-subdomains", { - type: "boolean", - description: "Follow links to subdomains of the source host.", - }) - .option("source-params-web-crawler-discover-options-limit", { - type: "number", - description: "Maximum number of pages to crawl (1-100000).", - }) - .option("source-params-web-crawler-discover-options-max-age", { - type: "number", - description: "Maximum content age in seconds to accept (0–604800).", - }) - .option("source-params-web-crawler-discover-options-source", { - type: "string", - description: + variadic: true, + optional: true, + parse: String, + }, + "source-params-prefix": { + kind: "parsed", + brief: "The source_params.prefix field", + optional: true, + parse: String, + }, + "source-params-r2-jurisdiction": { + kind: "parsed", + brief: "The source_params.r2_jurisdiction field", + optional: true, + parse: String, + }, + "source-params-web-crawler-discover-options-depth": { + kind: "parsed", + brief: "Maximum link-follow depth from the seed URL.", + optional: true, + parse: Number, + }, + "source-params-web-crawler-discover-options-include-external-links": { + kind: "boolean", + brief: + "Follow links that point outside the source domain. Must stay `false` because discover crawls only cover the zone you own.", + optional: true, + }, + "source-params-web-crawler-discover-options-include-subdomains": { + kind: "boolean", + brief: "Follow links to subdomains of the source host.", + optional: true, + }, + "source-params-web-crawler-discover-options-limit": { + kind: "parsed", + brief: "Maximum number of pages to crawl (1-100000).", + optional: true, + parse: Number, + }, + "source-params-web-crawler-discover-options-max-age": { + kind: "parsed", + brief: "Maximum content age in seconds to accept (0–604800).", + optional: true, + parse: Number, + }, + "source-params-web-crawler-discover-options-source": { + kind: "parsed", + brief: "Where the crawler looks for URLs: 'sitemaps' reads sitemap XML only, 'links' follows page links only, 'all' does both.", + optional: true, choices: ["all", "sitemaps", "links"], - }) - .coerce("source-params-web-crawler-discover-options-source", (value) => - resolveFileToken( - value, - "source-params-web-crawler-discover-options-source", - "text" - ) - ) - .option("source-params-web-crawler-parse-options-content-selector", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "source-params-web-crawler-discover-options-source", + "text" + ), + }, + "source-params-web-crawler-parse-options-content-selector": { + kind: "parsed", + brief: 'List of path-to-selector mappings for extracting specific content from crawled pages. Each entry pairs a URL glob pattern with a CSS selector. The first matching path wins. The crawler stores and indexes only the matched HTML fragment. Omit the field to disable content selection; the API rejects empty arrays. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"path": string, "selector": string}].', - }) - .option("source-params-web-crawler-parse-options-include-headers", { - type: "string", - description: + optional: true, + parse: String, + }, + "source-params-web-crawler-parse-options-include-headers": { + kind: "parsed", + brief: 'Up to 5 custom HTTP headers sent with each crawl request. Names must use RFC-7230 token characters, excluding spaces, colons, and control characters. Values must use HTAB and printable ASCII only, excluding CR and LF. Provide as a JSON object or @path/to/file.json. Shape: {"": string}.', - }) - .option("source-params-web-crawler-parse-options-include-images", { - type: "boolean", - description: - "The source_params.web_crawler.parse_options.include_images field", - }) - .option("source-params-web-crawler-parse-options-specific-sitemaps", { - type: "string", - array: true, - description: + optional: true, + parse: String, + }, + "source-params-web-crawler-parse-options-include-images": { + kind: "boolean", + brief: "The source_params.web_crawler.parse_options.include_images field", + optional: true, + }, + "source-params-web-crawler-parse-options-specific-sitemaps": { + kind: "parsed", + brief: "List of specific sitemap URLs to use for crawling. Only valid when parse_type is 'sitemap'.", - }) - .option("source-params-web-crawler-parse-options-use-browser-rendering", { - type: "boolean", - description: + variadic: true, + optional: true, + parse: String, + }, + "source-params-web-crawler-parse-options-use-browser-rendering": { + kind: "boolean", + brief: "The source_params.web_crawler.parse_options.use_browser_rendering field", - }) - .option("source-params-web-crawler-parse-type", { - type: "string", - description: + optional: true, + }, + "source-params-web-crawler-parse-type": { + kind: "parsed", + brief: "How the crawler finds URLs. 'sitemap' reads XML sitemaps; 'discover' follows links recursively and requires the source to belong to a Verified zone on this account.", + optional: true, choices: ["sitemap", "discover"], - }) - .coerce("source-params-web-crawler-parse-type", (value) => - resolveFileToken(value, "source-params-web-crawler-parse-type", "text") - ) - .option("summarization", { - type: "boolean", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "source-params-web-crawler-parse-type", "text"), + }, + summarization: { + kind: "boolean", + brief: "Deprecated and ignored during indexing and search; changing it still re-indexes existing files on the next sync. Use indexing_options.file_summary instead.", - }) - .option("summarization-model", { - type: "string", - description: + optional: true, + }, + "summarization-model": { + kind: "parsed", + brief: "Deprecated and ignored during indexing and search; changing it still re-indexes existing files on the next sync. Use indexing_options.file_summary instead.", - }) - .option("sync-interval", { - type: "number", - description: + optional: true, + parse: String, + }, + "sync-interval": { + kind: "parsed", + brief: "Interval between automatic syncs, in seconds. Allowed values: 900 (15min), 1800 (30min), 3600 (1h), 7200 (2h), 14400 (4h), 21600 (6h), 43200 (12h), 86400 (24h). Defaults to 86400 (24h).", - }) - .option("system-prompt-ai-search", { - type: "string", - description: "The system_prompt_ai_search field", - }) - .option("system-prompt-index-summarization", { - type: "string", - description: + optional: true, + parse: Number, + }, + "system-prompt-ai-search": { + kind: "parsed", + brief: "The system_prompt_ai_search field", + optional: true, + parse: String, + }, + "system-prompt-index-summarization": { + kind: "parsed", + brief: "Deprecated and has no effect. Use indexing_options.file_summary instead.", - }) - .option("system-prompt-rewrite-query", { - type: "string", - description: "The system_prompt_rewrite_query field", - }) - .option("token-id", { type: "string", description: "The token_id field" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "system-prompt-rewrite-query": { + kind: "parsed", + brief: "The system_prompt_rewrite_query field", + optional: true, + parse: String, + }, + "token-id": { + kind: "parsed", + brief: "The token_id field", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }) - .check((argv) => { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "instance-id", + brief: "AI Search instance ID.", + parse: String, + }, + ], + rules(rules) { + rules.check((argv) => { const groupSet = ["index-method-keyword", "index-method-vector"].some( (k) => argv[k] !== undefined ); @@ -406,8 +492,8 @@ function builder(yargs: Argv) { } } return true; - }) - .check((argv) => { + }); + rules.check((argv) => { const groupSet = [ "metadata-created-from-emdash-plugin-type", "metadata-created-from-emdash-plugin-version", @@ -425,862 +511,16 @@ function builder(yargs: Argv) { } return true; }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update ", describe: "Update an AI Search instance.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-search update", - classification: { - safeFlags: [ - "cache", - "cache-threshold", - "chunk", - "fusion-method", - "index-method-keyword", - "index-method-vector", - "indexing-options-file-summary", - "indexing-options-keyword-tokenizer", - "indexing-options-use-ocr", - "metadata-created-from-aisearch-wizard", - "metadata-created-from-emdash-plugin-type", - "paused", - "public-endpoint-params-chat-completions-endpoint-disabled", - "public-endpoint-params-default-domain-enabled", - "public-endpoint-params-enabled", - "public-endpoint-params-mcp-disabled", - "public-endpoint-params-rate-limit-technique", - "public-endpoint-params-search-endpoint-disabled", - "reranking", - "retrieval-options-keyword-match-mode", - "rewrite-query", - "source-params-d1-template", - "source-params-web-crawler-discover-options-include-external-links", - "source-params-web-crawler-discover-options-include-subdomains", - "source-params-web-crawler-discover-options-source", - "source-params-web-crawler-parse-options-include-images", - "source-params-web-crawler-parse-options-use-browser-rendering", - "source-params-web-crawler-parse-type", - "summarization", - "dry-run", - ], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai-search update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai-search/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/instances/${argv["instance-id"] == null ? "" : encodeURIComponent(String(argv["instance-id"]))}`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - "instance-id": String(argv["instance-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody( - { - ai_gateway_id: resolveFileToken( - argv["ai-gateway-id"] as string | undefined, - "ai-gateway-id", - "text" - ), - ai_search_model: resolveFileToken( - argv["ai-search-model"] as string | undefined, - "ai-search-model", - "text" - ), - cache: argv["cache"], - cache_threshold: argv["cache-threshold"], - cache_ttl: argv["cache-ttl"], - chunk: argv["chunk"], - chunk_overlap: argv["chunk-overlap"], - chunk_size: argv["chunk-size"], - custom_metadata: parseObjectArray( - argv["custom-metadata"], - "custom-metadata" - ), - embedding_model: resolveFileToken( - argv["embedding-model"] as string | undefined, - "embedding-model", - "text" - ), - fusion_method: argv["fusion-method"], - index_method: { - keyword: argv["index-method-keyword"], - vector: argv["index-method-vector"], - }, - indexing_options: { - file_summary: argv["indexing-options-file-summary"], - keyword_tokenizer: - argv["indexing-options-keyword-tokenizer"], - use_ocr: argv["indexing-options-use-ocr"], - }, - max_num_results: argv["max-num-results"], - metadata: { - created_from_aisearch_wizard: - argv["metadata-created-from-aisearch-wizard"], - created_from_emdash_plugin: { - type: argv[ - "metadata-created-from-emdash-plugin-type" - ], - version: resolveFileToken( - argv[ - "metadata-created-from-emdash-plugin-version" - ] as string | undefined, - "metadata-created-from-emdash-plugin-version", - "text" - ), - }, - worker_domain: resolveFileToken( - argv["metadata-worker-domain"] as string | undefined, - "metadata-worker-domain", - "text" - ), - }, - paused: argv["paused"], - public_endpoint_params: { - authorized_hosts: - argv["public-endpoint-params-authorized-hosts"], - chat_completions_endpoint: { - disabled: - argv[ - "public-endpoint-params-chat-completions-endpoint-disabled" - ], - }, - custom_domains: - argv["public-endpoint-params-custom-domains"], - default_domain_enabled: - argv["public-endpoint-params-default-domain-enabled"], - enabled: argv["public-endpoint-params-enabled"], - mcp: { - description: resolveFileToken( - argv["public-endpoint-params-mcp-description"] as - | string - | undefined, - "public-endpoint-params-mcp-description", - "text" - ), - disabled: argv["public-endpoint-params-mcp-disabled"], - }, - rate_limit: { - period_ms: - argv["public-endpoint-params-rate-limit-period-ms"], - requests: - argv["public-endpoint-params-rate-limit-requests"], - technique: - argv["public-endpoint-params-rate-limit-technique"], - }, - search_endpoint: { - disabled: - argv[ - "public-endpoint-params-search-endpoint-disabled" - ], - }, - }, - reranking: argv["reranking"], - reranking_model: resolveFileToken( - argv["reranking-model"] as string | undefined, - "reranking-model", - "text" - ), - retrieval_options: { - boost_by: parseObjectArray( - argv["retrieval-options-boost-by"], - "retrieval-options-boost-by" - ), - keyword_match_mode: - argv["retrieval-options-keyword-match-mode"], - }, - rewrite_model: resolveFileToken( - argv["rewrite-model"] as string | undefined, - "rewrite-model", - "text" - ), - rewrite_query: argv["rewrite-query"], - score_threshold: argv["score-threshold"], - source: resolveFileToken( - argv["source"] as string | undefined, - "source", - "text" - ), - source_params: { - d1: { - query: resolveFileToken( - argv["source-params-d1-query"] as - | string - | undefined, - "source-params-d1-query", - "text" - ), - template: argv["source-params-d1-template"], - }, - exclude_items: argv["source-params-exclude-items"], - include_items: argv["source-params-include-items"], - prefix: resolveFileToken( - argv["source-params-prefix"] as string | undefined, - "source-params-prefix", - "text" - ), - r2_jurisdiction: resolveFileToken( - argv["source-params-r2-jurisdiction"] as - | string - | undefined, - "source-params-r2-jurisdiction", - "text" - ), - web_crawler: { - discover_options: { - depth: - argv[ - "source-params-web-crawler-discover-options-depth" - ], - include_external_links: - argv[ - "source-params-web-crawler-discover-options-include-external-links" - ], - include_subdomains: - argv[ - "source-params-web-crawler-discover-options-include-subdomains" - ], - limit: - argv[ - "source-params-web-crawler-discover-options-limit" - ], - max_age: - argv[ - "source-params-web-crawler-discover-options-max-age" - ], - source: - argv[ - "source-params-web-crawler-discover-options-source" - ], - }, - parse_options: { - content_selector: parseObjectArray( - argv[ - "source-params-web-crawler-parse-options-content-selector" - ], - "source-params-web-crawler-parse-options-content-selector" - ), - include_headers: parseJsonMap( - argv[ - "source-params-web-crawler-parse-options-include-headers" - ], - "source-params-web-crawler-parse-options-include-headers" - ), - include_images: - argv[ - "source-params-web-crawler-parse-options-include-images" - ], - specific_sitemaps: - argv[ - "source-params-web-crawler-parse-options-specific-sitemaps" - ], - use_browser_rendering: - argv[ - "source-params-web-crawler-parse-options-use-browser-rendering" - ], - }, - parse_type: - argv["source-params-web-crawler-parse-type"], - }, - }, - summarization: argv["summarization"], - summarization_model: resolveFileToken( - argv["summarization-model"] as string | undefined, - "summarization-model", - "text" - ), - sync_interval: argv["sync-interval"], - system_prompt_ai_search: resolveFileToken( - argv["system-prompt-ai-search"] as string | undefined, - "system-prompt-ai-search", - "text" - ), - system_prompt_index_summarization: resolveFileToken( - argv["system-prompt-index-summarization"] as - | string - | undefined, - "system-prompt-index-summarization", - "text" - ), - system_prompt_rewrite_query: resolveFileToken( - argv["system-prompt-rewrite-query"] as - | string - | undefined, - "system-prompt-rewrite-query", - "text" - ), - token_id: resolveFileToken( - argv["token-id"] as string | undefined, - "token-id", - "text" - ), - }, - [ - [ - "source_params", - "web_crawler", - "parse_options", - "include_headers", - ], - ] - ), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - requestApi( - client, - "PUT", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData: Record = {}; - if (argv["ai-gateway-id"] !== undefined) - setNestedValue( - bodyData, - ["ai_gateway_id"], - resolveFileToken( - argv["ai-gateway-id"] as string | undefined, - "ai-gateway-id", - "text" - ) - ); - if (argv["ai-search-model"] !== undefined) - setNestedValue( - bodyData, - ["ai_search_model"], - resolveFileToken( - argv["ai-search-model"] as string | undefined, - "ai-search-model", - "text" - ) - ); - if (argv["cache"] !== undefined) - setNestedValue(bodyData, ["cache"], argv["cache"]); - if (argv["cache-threshold"] !== undefined) - setNestedValue( - bodyData, - ["cache_threshold"], - argv["cache-threshold"] - ); - if (argv["cache-ttl"] !== undefined) - setNestedValue(bodyData, ["cache_ttl"], argv["cache-ttl"]); - if (argv["chunk"] !== undefined) - setNestedValue(bodyData, ["chunk"], argv["chunk"]); - if (argv["chunk-overlap"] !== undefined) - setNestedValue(bodyData, ["chunk_overlap"], argv["chunk-overlap"]); - if (argv["chunk-size"] !== undefined) - setNestedValue(bodyData, ["chunk_size"], argv["chunk-size"]); - if (argv["custom-metadata"] !== undefined) - setNestedValue( - bodyData, - ["custom_metadata"], - parseObjectArray(argv["custom-metadata"], "custom-metadata") - ); - if (argv["embedding-model"] !== undefined) - setNestedValue( - bodyData, - ["embedding_model"], - resolveFileToken( - argv["embedding-model"] as string | undefined, - "embedding-model", - "text" - ) - ); - if (argv["fusion-method"] !== undefined) - setNestedValue(bodyData, ["fusion_method"], argv["fusion-method"]); - if (argv["index-method-keyword"] !== undefined) - setNestedValue( - bodyData, - ["index_method", "keyword"], - argv["index-method-keyword"] - ); - if (argv["index-method-vector"] !== undefined) - setNestedValue( - bodyData, - ["index_method", "vector"], - argv["index-method-vector"] - ); - if (argv["indexing-options-file-summary"] !== undefined) - setNestedValue( - bodyData, - ["indexing_options", "file_summary"], - argv["indexing-options-file-summary"] - ); - if (argv["indexing-options-keyword-tokenizer"] !== undefined) - setNestedValue( - bodyData, - ["indexing_options", "keyword_tokenizer"], - argv["indexing-options-keyword-tokenizer"] - ); - if (argv["indexing-options-use-ocr"] !== undefined) - setNestedValue( - bodyData, - ["indexing_options", "use_ocr"], - argv["indexing-options-use-ocr"] - ); - if (argv["max-num-results"] !== undefined) - setNestedValue( - bodyData, - ["max_num_results"], - argv["max-num-results"] - ); - if (argv["metadata-created-from-aisearch-wizard"] !== undefined) - setNestedValue( - bodyData, - ["metadata", "created_from_aisearch_wizard"], - argv["metadata-created-from-aisearch-wizard"] - ); - if (argv["metadata-created-from-emdash-plugin-type"] !== undefined) - setNestedValue( - bodyData, - ["metadata", "created_from_emdash_plugin", "type"], - argv["metadata-created-from-emdash-plugin-type"] - ); - if (argv["metadata-created-from-emdash-plugin-version"] !== undefined) - setNestedValue( - bodyData, - ["metadata", "created_from_emdash_plugin", "version"], - resolveFileToken( - argv["metadata-created-from-emdash-plugin-version"] as - | string - | undefined, - "metadata-created-from-emdash-plugin-version", - "text" - ) - ); - if (argv["metadata-worker-domain"] !== undefined) - setNestedValue( - bodyData, - ["metadata", "worker_domain"], - resolveFileToken( - argv["metadata-worker-domain"] as string | undefined, - "metadata-worker-domain", - "text" - ) - ); - if (argv["paused"] !== undefined) - setNestedValue(bodyData, ["paused"], argv["paused"]); - if (argv["public-endpoint-params-authorized-hosts"] !== undefined) - setNestedValue( - bodyData, - ["public_endpoint_params", "authorized_hosts"], - argv["public-endpoint-params-authorized-hosts"] - ); - if ( - argv["public-endpoint-params-chat-completions-endpoint-disabled"] !== - undefined - ) - setNestedValue( - bodyData, - ["public_endpoint_params", "chat_completions_endpoint", "disabled"], - argv["public-endpoint-params-chat-completions-endpoint-disabled"] - ); - if (argv["public-endpoint-params-custom-domains"] !== undefined) - setNestedValue( - bodyData, - ["public_endpoint_params", "custom_domains"], - argv["public-endpoint-params-custom-domains"] - ); - if (argv["public-endpoint-params-default-domain-enabled"] !== undefined) - setNestedValue( - bodyData, - ["public_endpoint_params", "default_domain_enabled"], - argv["public-endpoint-params-default-domain-enabled"] - ); - if (argv["public-endpoint-params-enabled"] !== undefined) - setNestedValue( - bodyData, - ["public_endpoint_params", "enabled"], - argv["public-endpoint-params-enabled"] - ); - if (argv["public-endpoint-params-mcp-description"] !== undefined) - setNestedValue( - bodyData, - ["public_endpoint_params", "mcp", "description"], - resolveFileToken( - argv["public-endpoint-params-mcp-description"] as - | string - | undefined, - "public-endpoint-params-mcp-description", - "text" - ) - ); - if (argv["public-endpoint-params-mcp-disabled"] !== undefined) - setNestedValue( - bodyData, - ["public_endpoint_params", "mcp", "disabled"], - argv["public-endpoint-params-mcp-disabled"] - ); - if (argv["public-endpoint-params-rate-limit-period-ms"] !== undefined) - setNestedValue( - bodyData, - ["public_endpoint_params", "rate_limit", "period_ms"], - argv["public-endpoint-params-rate-limit-period-ms"] - ); - if (argv["public-endpoint-params-rate-limit-requests"] !== undefined) - setNestedValue( - bodyData, - ["public_endpoint_params", "rate_limit", "requests"], - argv["public-endpoint-params-rate-limit-requests"] - ); - if (argv["public-endpoint-params-rate-limit-technique"] !== undefined) - setNestedValue( - bodyData, - ["public_endpoint_params", "rate_limit", "technique"], - argv["public-endpoint-params-rate-limit-technique"] - ); - if ( - argv["public-endpoint-params-search-endpoint-disabled"] !== undefined - ) - setNestedValue( - bodyData, - ["public_endpoint_params", "search_endpoint", "disabled"], - argv["public-endpoint-params-search-endpoint-disabled"] - ); - if (argv["reranking"] !== undefined) - setNestedValue(bodyData, ["reranking"], argv["reranking"]); - if (argv["reranking-model"] !== undefined) - setNestedValue( - bodyData, - ["reranking_model"], - resolveFileToken( - argv["reranking-model"] as string | undefined, - "reranking-model", - "text" - ) - ); - if (argv["retrieval-options-boost-by"] !== undefined) - setNestedValue( - bodyData, - ["retrieval_options", "boost_by"], - parseObjectArray( - argv["retrieval-options-boost-by"], - "retrieval-options-boost-by" - ) - ); - if (argv["retrieval-options-keyword-match-mode"] !== undefined) - setNestedValue( - bodyData, - ["retrieval_options", "keyword_match_mode"], - argv["retrieval-options-keyword-match-mode"] - ); - if (argv["rewrite-model"] !== undefined) - setNestedValue( - bodyData, - ["rewrite_model"], - resolveFileToken( - argv["rewrite-model"] as string | undefined, - "rewrite-model", - "text" - ) - ); - if (argv["rewrite-query"] !== undefined) - setNestedValue(bodyData, ["rewrite_query"], argv["rewrite-query"]); - if (argv["score-threshold"] !== undefined) - setNestedValue( - bodyData, - ["score_threshold"], - argv["score-threshold"] - ); - if (argv["source"] !== undefined) - setNestedValue( - bodyData, - ["source"], - resolveFileToken( - argv["source"] as string | undefined, - "source", - "text" - ) - ); - if (argv["source-params-d1-query"] !== undefined) - setNestedValue( - bodyData, - ["source_params", "d1", "query"], - resolveFileToken( - argv["source-params-d1-query"] as string | undefined, - "source-params-d1-query", - "text" - ) - ); - if (argv["source-params-d1-template"] !== undefined) - setNestedValue( - bodyData, - ["source_params", "d1", "template"], - argv["source-params-d1-template"] - ); - if (argv["source-params-exclude-items"] !== undefined) - setNestedValue( - bodyData, - ["source_params", "exclude_items"], - argv["source-params-exclude-items"] - ); - if (argv["source-params-include-items"] !== undefined) - setNestedValue( - bodyData, - ["source_params", "include_items"], - argv["source-params-include-items"] - ); - if (argv["source-params-prefix"] !== undefined) - setNestedValue( - bodyData, - ["source_params", "prefix"], - resolveFileToken( - argv["source-params-prefix"] as string | undefined, - "source-params-prefix", - "text" - ) - ); - if (argv["source-params-r2-jurisdiction"] !== undefined) - setNestedValue( - bodyData, - ["source_params", "r2_jurisdiction"], - resolveFileToken( - argv["source-params-r2-jurisdiction"] as string | undefined, - "source-params-r2-jurisdiction", - "text" - ) - ); - if ( - argv["source-params-web-crawler-discover-options-depth"] !== undefined - ) - setNestedValue( - bodyData, - ["source_params", "web_crawler", "discover_options", "depth"], - argv["source-params-web-crawler-discover-options-depth"] - ); - if ( - argv[ - "source-params-web-crawler-discover-options-include-external-links" - ] !== undefined - ) - setNestedValue( - bodyData, - [ - "source_params", - "web_crawler", - "discover_options", - "include_external_links", - ], - argv[ - "source-params-web-crawler-discover-options-include-external-links" - ] - ); - if ( - argv[ - "source-params-web-crawler-discover-options-include-subdomains" - ] !== undefined - ) - setNestedValue( - bodyData, - [ - "source_params", - "web_crawler", - "discover_options", - "include_subdomains", - ], - argv[ - "source-params-web-crawler-discover-options-include-subdomains" - ] - ); - if ( - argv["source-params-web-crawler-discover-options-limit"] !== undefined - ) - setNestedValue( - bodyData, - ["source_params", "web_crawler", "discover_options", "limit"], - argv["source-params-web-crawler-discover-options-limit"] - ); - if ( - argv["source-params-web-crawler-discover-options-max-age"] !== - undefined - ) - setNestedValue( - bodyData, - ["source_params", "web_crawler", "discover_options", "max_age"], - argv["source-params-web-crawler-discover-options-max-age"] - ); - if ( - argv["source-params-web-crawler-discover-options-source"] !== - undefined - ) - setNestedValue( - bodyData, - ["source_params", "web_crawler", "discover_options", "source"], - argv["source-params-web-crawler-discover-options-source"] - ); - if ( - argv["source-params-web-crawler-parse-options-content-selector"] !== - undefined - ) - setNestedValue( - bodyData, - [ - "source_params", - "web_crawler", - "parse_options", - "content_selector", - ], - parseObjectArray( - argv["source-params-web-crawler-parse-options-content-selector"], - "source-params-web-crawler-parse-options-content-selector" - ) - ); - if ( - argv["source-params-web-crawler-parse-options-include-headers"] !== - undefined - ) - setNestedValue( - bodyData, - [ - "source_params", - "web_crawler", - "parse_options", - "include_headers", - ], - parseJsonMap( - argv["source-params-web-crawler-parse-options-include-headers"], - "source-params-web-crawler-parse-options-include-headers" - ) - ); - if ( - argv["source-params-web-crawler-parse-options-include-images"] !== - undefined - ) - setNestedValue( - bodyData, - ["source_params", "web_crawler", "parse_options", "include_images"], - argv["source-params-web-crawler-parse-options-include-images"] - ); - if ( - argv["source-params-web-crawler-parse-options-specific-sitemaps"] !== - undefined - ) - setNestedValue( - bodyData, - [ - "source_params", - "web_crawler", - "parse_options", - "specific_sitemaps", - ], - argv["source-params-web-crawler-parse-options-specific-sitemaps"] - ); - if ( - argv[ - "source-params-web-crawler-parse-options-use-browser-rendering" - ] !== undefined - ) - setNestedValue( - bodyData, - [ - "source_params", - "web_crawler", - "parse_options", - "use_browser_rendering", - ], - argv[ - "source-params-web-crawler-parse-options-use-browser-rendering" - ] - ); - if (argv["source-params-web-crawler-parse-type"] !== undefined) - setNestedValue( - bodyData, - ["source_params", "web_crawler", "parse_type"], - argv["source-params-web-crawler-parse-type"] - ); - if (argv["summarization"] !== undefined) - setNestedValue(bodyData, ["summarization"], argv["summarization"]); - if (argv["summarization-model"] !== undefined) - setNestedValue( - bodyData, - ["summarization_model"], - resolveFileToken( - argv["summarization-model"] as string | undefined, - "summarization-model", - "text" - ) - ); - if (argv["sync-interval"] !== undefined) - setNestedValue(bodyData, ["sync_interval"], argv["sync-interval"]); - if (argv["system-prompt-ai-search"] !== undefined) - setNestedValue( - bodyData, - ["system_prompt_ai_search"], - resolveFileToken( - argv["system-prompt-ai-search"] as string | undefined, - "system-prompt-ai-search", - "text" - ) - ); - if (argv["system-prompt-index-summarization"] !== undefined) - setNestedValue( - bodyData, - ["system_prompt_index_summarization"], - resolveFileToken( - argv["system-prompt-index-summarization"] as string | undefined, - "system-prompt-index-summarization", - "text" - ) - ); - if (argv["system-prompt-rewrite-query"] !== undefined) - setNestedValue( - bodyData, - ["system_prompt_rewrite_query"], - resolveFileToken( - argv["system-prompt-rewrite-query"] as string | undefined, - "system-prompt-rewrite-query", - "text" - ) - ); - if (argv["token-id"] !== undefined) - setNestedValue( - bodyData, - ["token_id"], - resolveFileToken( - argv["token-id"] as string | undefined, - "token-id", - "text" - ) - ); - const result = await withProgress(`Updating`, async () => - requestApi( - client, - "PUT", - `/accounts/${accountId}/ai-search/namespaces/${encodeURIComponent(String(argv["namespace"]))}/instances/${encodeURIComponent(String(argv["instance-id"]))}`, - { body: bodyData } - ) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 ai-search update \n\nUpdates the configuration of an AI Search instance.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-security/custom-topics/get.handler.ts b/packages/cli/src/commands/_generated/ai-security/custom-topics/get.handler.ts new file mode 100644 index 0000000000..a5beab0481 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-security/custom-topics/get.handler.ts @@ -0,0 +1,42 @@ +import operation from "../../_operations/ai-security/custom-topics/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-security custom-topics get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf ai-security custom-topics get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/ai-security/custom-topics`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-security/custom-topics/get.ts b/packages/cli/src/commands/_generated/ai-security/custom-topics/get.ts index 0eabe2dffa..2168f2b056 100644 --- a/packages/cli/src/commands/_generated/ai-security/custom-topics/get.ts +++ b/packages/cli/src/commands/_generated/ai-security/custom-topics/get.ts @@ -1,69 +1,31 @@ -import operation from "../../_operations/ai-security/custom-topics/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/ai-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-security custom-topics get\n\nGet the custom topic categories defined for the zone. While AI Security for Apps is enabled, it scores every incoming prompt against these topics and writes the scores to the `cf.llm.prompt.custom_topic_categories` field, keyed by topic label. Topics can be configured while the detection is disabled, but no prompt is scored until you enable it." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "Get the AI Security for Apps custom topics of a zone.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-security custom-topics get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf ai-security custom-topics get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/ai-security/custom-topics`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-security custom-topics get\n\nGet the custom topic categories defined for the zone. While AI Security for Apps is enabled, it scores every incoming prompt against these topics and writes the scores to the `cf.llm.prompt.custom_topic_categories` field, keyed by topic label. Topics can be configured while the detection is disabled, but no prompt is scored until you enable it.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-security/custom-topics/index.ts b/packages/cli/src/commands/_generated/ai-security/custom-topics/index.ts index 0810d90ba8..f0a6ea16f0 100644 --- a/packages/cli/src/commands/_generated/ai-security/custom-topics/index.ts +++ b/packages/cli/src/commands/_generated/ai-security/custom-topics/index.ts @@ -1,25 +1,20 @@ import $get from "./get.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * custom-topics command group * @generated from apis/overlays/ai-security.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "custom-topics", describe: "Organization-specific topic categories used by AI Security for Apps content detection", - builder: (yargs) => { - return yargs - .command($get) - .command($update) - .demandCommand(1, "Please specify a subcommand"); + routes: { + get: $get, + update: $update, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-security/custom-topics/update.handler.ts b/packages/cli/src/commands/_generated/ai-security/custom-topics/update.handler.ts new file mode 100644 index 0000000000..721eb39f71 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-security/custom-topics/update.handler.ts @@ -0,0 +1,75 @@ +import operation from "../../_operations/ai-security/custom-topics/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-security custom-topics update", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf ai-security custom-topics update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/ai-security/custom-topics`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + topics: parseObjectArray(argv["topics"], "topics"), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This operation overwrites the AI Security for Apps custom topics for a zone.`, + })) + ) { + return; + } + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + topics: parseObjectArray(argv["topics"], "topics"), + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-security/custom-topics/update.ts b/packages/cli/src/commands/_generated/ai-security/custom-topics/update.ts index 750be60515..e039f99938 100644 --- a/packages/cli/src/commands/_generated/ai-security/custom-topics/update.ts +++ b/packages/cli/src/commands/_generated/ai-security/custom-topics/update.ts @@ -1,117 +1,50 @@ -import operation from "../../_operations/ai-security/custom-topics/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/ai-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-security custom-topics update\n\nUpdate the custom topic list of the zone, overwriting it entirely with the topics in the request, so include every topic you want to keep. Changes can take up to a minute to propagate. Each entry has a `label`, used to reference the topic in rule expressions and analytics, and a `topic` description, which the classifier scores prompts against while AI Security for Apps is enabled. The following rules apply: - A zone can hold at most 20 topics. - `label` must be 2–20 characters, using only lowercase letters (a–z), digits (0–9), and hyphens. - `topic` must be 2–50 UTF-8 bytes. Text in any language is supported, including spaces, numbers, punctuation, and symbols. Tabs, line breaks, invalid text, and invisible formatting characters are not allowed. - Labels must be unique within the zone, and so must topic descriptions." - ) - .option("topics", { - type: "string", - description: +const parameters = { + flags: { + topics: { + kind: "parsed", + brief: 'Custom topic categories for AI Security for Apps content detection. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"label": string, "topic": string}].', - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update", describe: "Update the AI Security for Apps custom topics of a zone.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-security custom-topics update", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf ai-security custom-topics update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/ai-security/custom-topics`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - topics: parseObjectArray(argv["topics"], "topics"), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This operation overwrites the AI Security for Apps custom topics for a zone.`, - })) - ) { - return; - } - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - topics: parseObjectArray(argv["topics"], "topics"), - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 ai-security custom-topics update\n\nUpdate the custom topic list of the zone, overwriting it entirely with the topics in the request, so include every topic you want to keep. Changes can take up to a minute to propagate. Each entry has a `label`, used to reference the topic in rule expressions and analytics, and a `topic` description, which the classifier scores prompts against while AI Security for Apps is enabled. The following rules apply: - A zone can hold at most 20 topics. - `label` must be 2–20 characters, using only lowercase letters (a–z), digits (0–9), and hyphens. - `topic` must be 2–50 UTF-8 bytes. Text in any language is supported, including spaces, numbers, punctuation, and symbols. Tabs, line breaks, invalid text, and invisible formatting characters are not allowed. - Labels must be unique within the zone, and so must topic descriptions.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-security/get.handler.ts b/packages/cli/src/commands/_generated/ai-security/get.handler.ts new file mode 100644 index 0000000000..b861d81e0e --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-security/get.handler.ts @@ -0,0 +1,42 @@ +import operation from "../_operations/ai-security/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-security get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf ai-security get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/ai-security/settings`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-security/get.ts b/packages/cli/src/commands/_generated/ai-security/get.ts index c7374336fe..54d7accdf8 100644 --- a/packages/cli/src/commands/_generated/ai-security/get.ts +++ b/packages/cli/src/commands/_generated/ai-security/get.ts @@ -1,69 +1,31 @@ -import operation from "../_operations/ai-security/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/ai-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-security get\n\nGet the current AI Security for Apps status for the zone. While enabled, Cloudflare scans prompts sent to endpoints labeled `cf-llm` for personally identifiable information, unsafe topics, and prompt injection attempts." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "Get the AI Security for Apps status for a zone.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-security get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf ai-security get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/ai-security/settings`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai-security get\n\nGet the current AI Security for Apps status for the zone. While enabled, Cloudflare scans prompts sent to endpoints labeled `cf-llm` for personally identifiable information, unsafe topics, and prompt injection attempts.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-security/index.ts b/packages/cli/src/commands/_generated/ai-security/index.ts index 4498c16075..5284cc7f4c 100644 --- a/packages/cli/src/commands/_generated/ai-security/index.ts +++ b/packages/cli/src/commands/_generated/ai-security/index.ts @@ -1,27 +1,22 @@ import $customtopics from "./custom-topics/index.js"; import $get from "./get.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * ai-security command * @generated from apis/overlays/ai-security.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "ai-security", describe: "Detect prompt injection, PII, and unsafe topics in traffic to your AI applications", - builder: (yargs) => { - return yargs - .command($get) - .command($update) - .command($customtopics) - .demandCommand(1, "Please specify a subcommand"); + routes: { + get: $get, + update: $update, + "custom-topics": $customtopics, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai-security/update.handler.ts b/packages/cli/src/commands/_generated/ai-security/update.handler.ts new file mode 100644 index 0000000000..d17c6d9241 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai-security/update.handler.ts @@ -0,0 +1,75 @@ +import operation from "../_operations/ai-security/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai-security update", + classification: { + safeFlags: ["enabled", "dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf ai-security update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/ai-security/settings`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + enabled: argv["enabled"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This operation toggles AI Security for Apps for a zone.`, + })) + ) { + return; + } + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + enabled: argv["enabled"], + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai-security/update.ts b/packages/cli/src/commands/_generated/ai-security/update.ts index 3c48a3e9a6..dce53ba5fe 100644 --- a/packages/cli/src/commands/_generated/ai-security/update.ts +++ b/packages/cli/src/commands/_generated/ai-security/update.ts @@ -1,116 +1,48 @@ -import operation from "../_operations/ai-security/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/ai-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai-security update\n\nUpdate the AI Security for Apps status for the zone, enabling or disabling the detection. The detection results are exposed as `cf.llm.prompt.*` fields for use in custom rules and rate limiting rules; changes can take up to a minute to propagate." - ) - .option("enabled", { - type: "boolean", - description: "Whether AI Security for Apps is enabled on the zone.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + enabled: { + kind: "boolean", + brief: "Whether AI Security for Apps is enabled on the zone.", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }) - .option("body", { - type: "string", - description: "AI Security for Apps enablement status for a zone.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "AI Security for Apps enablement status for a zone.", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update", describe: "Update the AI Security for Apps status for a zone.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai-security update", - classification: { - safeFlags: ["enabled", "dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf ai-security update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/ai-security/settings`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - enabled: argv["enabled"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This operation toggles AI Security for Apps for a zone.`, - })) - ) { - return; - } - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - enabled: argv["enabled"], - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 ai-security update\n\nUpdate the AI Security for Apps status for the zone, enabling or disabling the detection. The detection results are exposed as `cf.llm.prompt.*` fields for use in custom rules and rate limiting rules; changes can take up to a minute to propagate.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai/authors/index.ts b/packages/cli/src/commands/_generated/ai/authors/index.ts index 133917d223..18d2163007 100644 --- a/packages/cli/src/commands/_generated/ai/authors/index.ts +++ b/packages/cli/src/commands/_generated/ai/authors/index.ts @@ -1,20 +1,17 @@ import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * authors command group * @generated from apis/overlays/ai.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "authors", describe: "Operations for authors", - builder: (yargs) => { - return yargs.command($list).demandCommand(1, "Please specify a subcommand"); + routes: { + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai/authors/list.handler.ts b/packages/cli/src/commands/_generated/ai/authors/list.handler.ts new file mode 100644 index 0000000000..991f662bf0 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai/authors/list.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/ai/authors/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai authors list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai authors list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/authors/search`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai/authors/list.ts b/packages/cli/src/commands/_generated/ai/authors/list.ts index d17a149a79..42cedc5391 100644 --- a/packages/cli/src/commands/_generated/ai/authors/list.ts +++ b/packages/cli/src/commands/_generated/ai/authors/list.ts @@ -1,71 +1,31 @@ -import operation from "../../_operations/ai/authors/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/ai.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai authors list\n\nSearches Workers AI models by author or organization name." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "Author Search", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai authors list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai authors list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/authors/search`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai authors list\n\nSearches Workers AI models by author or organization name.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai/finetunes/assets/create.handler.ts b/packages/cli/src/commands/_generated/ai/finetunes/assets/create.handler.ts new file mode 100644 index 0000000000..61cdcc7622 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai/finetunes/assets/create.handler.ts @@ -0,0 +1,114 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { readFileForFlag, resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai finetunes assets create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if ( + argv.body === undefined && + argv.file === undefined && + argv["file-name"] === undefined + ) { + throw new Error( + "--body or --file is required for this command. Pass --body '' or --file path/to/file." + ); + } + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai finetunes assets create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/finetunes/${argv["finetune-id"] == null ? "" : encodeURIComponent(String(argv["finetune-id"]))}/finetune-assets`, + pathParams: { "finetune-id": String(argv["finetune-id"] ?? "") }, + bodyKind: "multipart", + body: { + body: argv["body"], + file: argv["file"], + "file-name": argv["file-name"], + }, + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + argv.file !== undefined || + argv.body !== undefined || + argv["file-name"] !== undefined + ) { + const formData = new FormData(); + if (argv.file !== undefined) { + const fileContent = readFileForFlag(argv.file); + formData.append( + "file", + new Blob([fileContent]), + argv.file.split(/[\\/]/).filter(Boolean).pop() + ); + } else if (argv.body !== undefined) { + formData.append("file", argv.body); + } + if (argv["file-name"] !== undefined) + formData.append( + "file_name", + String( + resolveFileToken( + argv["file-name"] as string | undefined, + "file-name", + "text" + ) ?? "" + ) + ); + const result = await withProgress(`Creating`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/ai/finetunes/${encodeURIComponent(String(argv["finetune-id"]))}/finetune-assets`, + { body: formData } + ) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + if (argv.body !== undefined) { + // Endpoint does not accept application/json — send --body as raw bytes, + // resolving @file references as binary file contents. + const bodyData = resolveFileToken(argv.body, "body", "binary"); + const result = await withProgress(`Creating`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/ai/finetunes/${encodeURIComponent(String(argv["finetune-id"]))}/finetune-assets`, + { + body: bodyData, + headers: { "Content-Type": "multipart/form-data" }, + } + ) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai/finetunes/assets/create.ts b/packages/cli/src/commands/_generated/ai/finetunes/assets/create.ts index f9dd5c82db..8fad336670 100644 --- a/packages/cli/src/commands/_generated/ai/finetunes/assets/create.ts +++ b/packages/cli/src/commands/_generated/ai/finetunes/assets/create.ts @@ -1,157 +1,52 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/ai.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { readFileForFlag, resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai finetunes assets create \n\nUploads training data assets for a Workers AI fine-tuning job." - ) - .positional("finetune-id", { - type: "string", - description: "Finetune ID", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Finetune asset file upload.", - }) - .option("file", { - type: "string", - description: "Path to a file to upload as the request body", - }) - .option("file-name", { - type: "string", - description: + }, + body: { + kind: "parsed", + brief: "Finetune asset file upload.", + optional: true, + parse: String, + }, + file: { + kind: "parsed", + brief: "Path to a file to upload as the request body", + optional: true, + parse: String, + }, + "file-name": { + kind: "parsed", + brief: "Name of the file (adapter_config.json or adapter_model.safetensors).", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + optional: true, + parse: String, + }, + }, + operands: [ + { placeholder: "finetune-id", brief: "Finetune ID", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Upload a Finetune Asset", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai finetunes assets create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if ( - argv.body === undefined && - argv.file === undefined && - argv["file-name"] === undefined - ) { - throw new Error( - "--body or --file is required for this command. Pass --body '' or --file path/to/file." - ); - } - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai finetunes assets create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/finetunes/${argv["finetune-id"] == null ? "" : encodeURIComponent(String(argv["finetune-id"]))}/finetune-assets`, - pathParams: { "finetune-id": String(argv["finetune-id"] ?? "") }, - bodyKind: "multipart", - body: { - body: argv["body"], - file: argv["file"], - "file-name": argv["file-name"], - }, - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - argv.file !== undefined || - argv.body !== undefined || - argv["file-name"] !== undefined - ) { - const formData = new FormData(); - if (argv.file !== undefined) { - const fileContent = readFileForFlag(argv.file); - formData.append( - "file", - new Blob([fileContent]), - argv.file.split(/[\\/]/).filter(Boolean).pop() - ); - } else if (argv.body !== undefined) { - formData.append("file", argv.body); - } - if (argv["file-name"] !== undefined) - formData.append( - "file_name", - String( - resolveFileToken( - argv["file-name"] as string | undefined, - "file-name", - "text" - ) ?? "" - ) - ); - const result = await withProgress(`Creating`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/ai/finetunes/${encodeURIComponent(String(argv["finetune-id"]))}/finetune-assets`, - { body: formData } - ) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - if (argv.body !== undefined) { - // Endpoint does not accept application/json — send --body as raw bytes, - // resolving @file references as binary file contents. - const bodyData = resolveFileToken(argv.body, "body", "binary"); - const result = await withProgress(`Creating`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/ai/finetunes/${encodeURIComponent(String(argv["finetune-id"]))}/finetune-assets`, - { - body: bodyData, - headers: { "Content-Type": "multipart/form-data" }, - } - ) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - } - ), -}; + usage: + "$0 ai finetunes assets create \n\nUploads training data assets for a Workers AI fine-tuning job.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai/finetunes/assets/download.handler.ts b/packages/cli/src/commands/_generated/ai/finetunes/assets/download.handler.ts new file mode 100644 index 0000000000..40ac8303b2 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai/finetunes/assets/download.handler.ts @@ -0,0 +1,53 @@ +import operation from "../../../_operations/ai/finetunes/assets/download.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./download.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai finetunes assets download", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai finetunes assets download", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/finetunes/${argv["finetune-id"] == null ? "" : encodeURIComponent(String(argv["finetune-id"]))}/finetune-assets/${argv["file-name"] == null ? "" : encodeURIComponent(String(argv["file-name"]))}`, + pathParams: { + "finetune-id": String(argv["finetune-id"] ?? ""), + "file-name": String(argv["file-name"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + finetune_id: argv["finetune-id"], + file_name: argv["file-name"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai/finetunes/assets/download.ts b/packages/cli/src/commands/_generated/ai/finetunes/assets/download.ts index bcfd36aec0..3512f0ccd3 100644 --- a/packages/cli/src/commands/_generated/ai/finetunes/assets/download.ts +++ b/packages/cli/src/commands/_generated/ai/finetunes/assets/download.ts @@ -1,88 +1,32 @@ -import operation from "../../../_operations/ai/finetunes/assets/download.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * download command * @generated from apis/overlays/ai.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai finetunes assets download \n\nReturns a pre-signed R2 URL for downloading a finetune asset file." - ) - .positional("file-name", { - type: "string", - description: "File name", - demandOption: true, - }) - .option("finetune-id", { - type: "string", - description: "Finetune ID", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "finetune-id": { kind: "parsed", brief: "Finetune ID", parse: String }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "file-name", brief: "File name", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "download ", describe: "Download a Finetune Asset", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai finetunes assets download", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai finetunes assets download", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/finetunes/${argv["finetune-id"] == null ? "" : encodeURIComponent(String(argv["finetune-id"]))}/finetune-assets/${argv["file-name"] == null ? "" : encodeURIComponent(String(argv["file-name"]))}`, - pathParams: { - "finetune-id": String(argv["finetune-id"] ?? ""), - "file-name": String(argv["file-name"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - finetune_id: argv["finetune-id"], - file_name: argv["file-name"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai finetunes assets download \n\nReturns a pre-signed R2 URL for downloading a finetune asset file.", + ...parameters, + loader: () => import("./download.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai/finetunes/assets/index.ts b/packages/cli/src/commands/_generated/ai/finetunes/assets/index.ts index e5720e357a..f09c67062f 100644 --- a/packages/cli/src/commands/_generated/ai/finetunes/assets/index.ts +++ b/packages/cli/src/commands/_generated/ai/finetunes/assets/index.ts @@ -1,24 +1,19 @@ import $create from "./create.js"; import $download from "./download.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * assets command group * @generated from apis/overlays/ai.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "assets", describe: "Operations for finetunes.assets", - builder: (yargs) => { - return yargs - .command($create) - .command($download) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + download: $download, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai/finetunes/create.handler.ts b/packages/cli/src/commands/_generated/ai/finetunes/create.handler.ts new file mode 100644 index 0000000000..37f7dd66ab --- /dev/null +++ b/packages/cli/src/commands/_generated/ai/finetunes/create.handler.ts @@ -0,0 +1,115 @@ +import operation from "../../_operations/ai/finetunes/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai finetunes create", + classification: { + safeFlags: ["public", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["model"] === undefined) { + argv["model"] = await promptForRequiredField( + "model", + "The model field" + ); + } + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField("name", "The name field"); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai finetunes create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/finetunes`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + model: resolveFileToken( + argv["model"] as string | undefined, + "model", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + public: argv["public"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + model: resolveFileToken( + argv["model"] as string | undefined, + "model", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + public: argv["public"], + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai/finetunes/create.ts b/packages/cli/src/commands/_generated/ai/finetunes/create.ts index ed4d4d4aed..1f3f560eff 100644 --- a/packages/cli/src/commands/_generated/ai/finetunes/create.ts +++ b/packages/cli/src/commands/_generated/ai/finetunes/create.ts @@ -1,158 +1,56 @@ -import operation from "../../_operations/ai/finetunes/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/ai.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai finetunes create\n\nCreates a new fine-tuning job for a Workers AI model using custom training data." - ) - .option("description", { - type: "string", - description: "The description field", - }) - .option("model", { type: "string", description: "The model field" }) - .option("name", { type: "string", description: "The name field" }) - .option("public", { - type: "boolean", - description: "The public field", +const parameters = { + flags: { + description: { + kind: "parsed", + brief: "The description field", + optional: true, + parse: String, + }, + model: { + kind: "parsed", + brief: "The model field", + optional: true, + parse: String, + }, + name: { + kind: "parsed", + brief: "The name field", + optional: true, + parse: String, + }, + public: { kind: "boolean", brief: "The public field", default: false }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", - default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Create a new Finetune", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai finetunes create", - classification: { - safeFlags: ["public", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["model"] === undefined) { - argv["model"] = await promptForRequiredField( - "model", - "The model field" - ); - } - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "The name field" - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai finetunes create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/finetunes`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - model: resolveFileToken( - argv["model"] as string | undefined, - "model", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - public: argv["public"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - model: resolveFileToken( - argv["model"] as string | undefined, - "model", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - public: argv["public"], - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 ai finetunes create\n\nCreates a new fine-tuning job for a Workers AI model using custom training data.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai/finetunes/delete.handler.ts b/packages/cli/src/commands/_generated/ai/finetunes/delete.handler.ts new file mode 100644 index 0000000000..39e7e5c52e --- /dev/null +++ b/packages/cli/src/commands/_generated/ai/finetunes/delete.handler.ts @@ -0,0 +1,55 @@ +import operation from "../../_operations/ai/finetunes/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai finetunes delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai finetunes delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/finetunes/${argv["finetune-id"] == null ? "" : encodeURIComponent(String(argv["finetune-id"]))}`, + pathParams: { "finetune-id": String(argv["finetune-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + finetune_id: argv["finetune-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai/finetunes/delete.ts b/packages/cli/src/commands/_generated/ai/finetunes/delete.ts index 0e18f32625..e2ed45c13d 100644 --- a/packages/cli/src/commands/_generated/ai/finetunes/delete.ts +++ b/packages/cli/src/commands/_generated/ai/finetunes/delete.ts @@ -1,91 +1,39 @@ -import operation from "../../_operations/ai/finetunes/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/ai.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai finetunes delete \n\nDelete a finetune. Any in-flight requests referencing the lora will fail after the files are deleted." - ) - .positional("finetune-id", { - type: "string", - description: "Finetune ID", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "finetune-id", brief: "Finetune ID", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete a Finetune", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai finetunes delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai finetunes delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/finetunes/${argv["finetune-id"] == null ? "" : encodeURIComponent(String(argv["finetune-id"]))}`, - pathParams: { "finetune-id": String(argv["finetune-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - finetune_id: argv["finetune-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 ai finetunes delete \n\nDelete a finetune. Any in-flight requests referencing the lora will fail after the files are deleted.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai/finetunes/index.ts b/packages/cli/src/commands/_generated/ai/finetunes/index.ts index fe6bade1bc..50317497bd 100644 --- a/packages/cli/src/commands/_generated/ai/finetunes/index.ts +++ b/packages/cli/src/commands/_generated/ai/finetunes/index.ts @@ -3,28 +3,23 @@ import $create from "./create.js"; import $delete from "./delete.js"; import $list from "./list.js"; import $public from "./public/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * finetunes command group * @generated from apis/overlays/ai.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "finetunes", describe: "Operations for finetunes", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($list) - .command($assets) - .command($public) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + list: $list, + assets: $assets, + public: $public, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai/finetunes/list.handler.ts b/packages/cli/src/commands/_generated/ai/finetunes/list.handler.ts new file mode 100644 index 0000000000..0b2d98001b --- /dev/null +++ b/packages/cli/src/commands/_generated/ai/finetunes/list.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/ai/finetunes/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai finetunes list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai finetunes list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/finetunes`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai/finetunes/list.ts b/packages/cli/src/commands/_generated/ai/finetunes/list.ts index 4ffbe0d182..5c3db7ca2a 100644 --- a/packages/cli/src/commands/_generated/ai/finetunes/list.ts +++ b/packages/cli/src/commands/_generated/ai/finetunes/list.ts @@ -1,71 +1,31 @@ -import operation from "../../_operations/ai/finetunes/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/ai.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai finetunes list\n\nLists all fine-tuning jobs created by the account, including status and metrics." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Finetunes", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai finetunes list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai finetunes list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/finetunes`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai finetunes list\n\nLists all fine-tuning jobs created by the account, including status and metrics.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai/finetunes/public/index.ts b/packages/cli/src/commands/_generated/ai/finetunes/public/index.ts index 0830f8b5c9..ceef2cc948 100644 --- a/packages/cli/src/commands/_generated/ai/finetunes/public/index.ts +++ b/packages/cli/src/commands/_generated/ai/finetunes/public/index.ts @@ -1,20 +1,17 @@ import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * public command group * @generated from apis/overlays/ai.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "public", describe: "Operations for finetunes.public", - builder: (yargs) => { - return yargs.command($list).demandCommand(1, "Please specify a subcommand"); + routes: { + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai/finetunes/public/list.handler.ts b/packages/cli/src/commands/_generated/ai/finetunes/public/list.handler.ts new file mode 100644 index 0000000000..9144105277 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai/finetunes/public/list.handler.ts @@ -0,0 +1,52 @@ +import operation from "../../../_operations/ai/finetunes/public/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai finetunes public list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + limit: argv["limit"], + offset: argv["offset"], + orderBy: argv["order-by"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai finetunes public list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/finetunes/public`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai/finetunes/public/list.ts b/packages/cli/src/commands/_generated/ai/finetunes/public/list.ts index 1c62e466ef..3d001fcde8 100644 --- a/packages/cli/src/commands/_generated/ai/finetunes/public/list.ts +++ b/packages/cli/src/commands/_generated/ai/finetunes/public/list.ts @@ -1,83 +1,49 @@ -import operation from "../../../_operations/ai/finetunes/public/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/ai.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai finetunes public list\n\nLists publicly available fine-tuned models that can be used with Workers AI." - ) - .option("limit", { type: "number", description: "Pagination Limit." }) - .option("offset", { type: "number", description: "Pagination Offset." }) - .option("order-by", { - type: "string", - description: "Order By Column Name.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + limit: { + kind: "parsed", + brief: "Pagination Limit.", + optional: true, + parse: Number, + }, + offset: { + kind: "parsed", + brief: "Pagination Offset.", + optional: true, + parse: Number, + }, + "order-by": { + kind: "parsed", + brief: "Order By Column Name.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Public Finetunes", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai finetunes public list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - limit: argv["limit"], - offset: argv["offset"], - orderBy: argv["order-by"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai finetunes public list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/finetunes/public`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai finetunes public list\n\nLists publicly available fine-tuned models that can be used with Workers AI.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai/get-model-schema.handler.ts b/packages/cli/src/commands/_generated/ai/get-model-schema.handler.ts new file mode 100644 index 0000000000..4ac0f6bac5 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai/get-model-schema.handler.ts @@ -0,0 +1,50 @@ +import operation from "../_operations/ai/get-model-schema.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get-model-schema.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai get-model-schema", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + model: argv["model"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai get-model-schema", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/models/schema`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai/get-model-schema.ts b/packages/cli/src/commands/_generated/ai/get-model-schema.ts index 2175805799..9bf627cf83 100644 --- a/packages/cli/src/commands/_generated/ai/get-model-schema.ts +++ b/packages/cli/src/commands/_generated/ai/get-model-schema.ts @@ -1,81 +1,36 @@ -import operation from "../_operations/ai/get-model-schema.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get-model-schema command * @generated from apis/overlays/ai.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai get-model-schema\n\nRetrieves the input and output JSON Schema definitions for an AI model. Use these definitions to determine the model-specific request fields and response format." - ) - .option("model", { - type: "string", - description: - "AI model identifier, including its namespace and model name.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + model: { + kind: "parsed", + brief: "AI model identifier, including its namespace and model name.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get-model-schema", describe: "Get an AI model's input and output schemas", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai get-model-schema", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - model: argv["model"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai get-model-schema", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/models/schema`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai get-model-schema\n\nRetrieves the input and output JSON Schema definitions for an AI model. Use these definitions to determine the model-specific request fields and response format.", + ...parameters, + loader: () => import("./get-model-schema.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai/index.ts b/packages/cli/src/commands/_generated/ai/index.ts index 794eb3eff0..d22212bd86 100644 --- a/packages/cli/src/commands/_generated/ai/index.ts +++ b/packages/cli/src/commands/_generated/ai/index.ts @@ -6,33 +6,28 @@ import $models from "./models/index.js"; import $tasks from "./tasks/index.js"; import $tomarkdown from "./to-markdown.js"; import $websearch from "./websearch.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; +import $run from "#commands/ai/run/index.js"; /** * ai command * @generated from apis/overlays/ai.ts */ -import type { CommandModule } from "yargs"; -import $run from "#commands/ai/run/index.js"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "ai", describe: "ai", - builder: (yargs) => { - return yargs - .command($getmodelschema) - .command($listmarkdownsupportedformats) - .command($run) - .command($tomarkdown) - .command($websearch) - .command($authors) - .command($finetunes) - .command($models) - .command($tasks) - .demandCommand(1, "Please specify a subcommand"); + routes: { + "get-model-schema": $getmodelschema, + "list-markdown-supported-formats": $listmarkdownsupportedformats, + run: $run, + "to-markdown": $tomarkdown, + websearch: $websearch, + authors: $authors, + finetunes: $finetunes, + models: $models, + tasks: $tasks, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai/list-markdown-supported-formats.handler.ts b/packages/cli/src/commands/_generated/ai/list-markdown-supported-formats.handler.ts new file mode 100644 index 0000000000..6b347f2792 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai/list-markdown-supported-formats.handler.ts @@ -0,0 +1,46 @@ +import operation from "../_operations/ai/list-markdown-supported-formats.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list-markdown-supported-formats.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai list-markdown-supported-formats", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai list-markdown-supported-formats", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/tomarkdown/supported`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai/list-markdown-supported-formats.ts b/packages/cli/src/commands/_generated/ai/list-markdown-supported-formats.ts index d65849ea9d..67ef4f77a8 100644 --- a/packages/cli/src/commands/_generated/ai/list-markdown-supported-formats.ts +++ b/packages/cli/src/commands/_generated/ai/list-markdown-supported-formats.ts @@ -1,71 +1,31 @@ -import operation from "../_operations/ai/list-markdown-supported-formats.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list-markdown-supported-formats command * @generated from apis/overlays/ai.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai list-markdown-supported-formats\n\nLists the file extensions and MIME types accepted by Workers AI's Markdown conversion endpoint. Use this list to check whether a file can be converted before uploading it." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list-markdown-supported-formats", describe: "List supported Markdown conversion formats", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai list-markdown-supported-formats", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai list-markdown-supported-formats", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/tomarkdown/supported`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai list-markdown-supported-formats\n\nLists the file extensions and MIME types accepted by Workers AI's Markdown conversion endpoint. Use this list to check whether a file can be converted before uploading it.", + ...parameters, + loader: () => import("./list-markdown-supported-formats.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai/models/index.ts b/packages/cli/src/commands/_generated/ai/models/index.ts index 5682a68026..9a0d3e49ae 100644 --- a/packages/cli/src/commands/_generated/ai/models/index.ts +++ b/packages/cli/src/commands/_generated/ai/models/index.ts @@ -1,20 +1,17 @@ import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * models command group * @generated from apis/overlays/ai.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "models", describe: "Operations for models", - builder: (yargs) => { - return yargs.command($list).demandCommand(1, "Please specify a subcommand"); + routes: { + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai/models/list.handler.ts b/packages/cli/src/commands/_generated/ai/models/list.handler.ts new file mode 100644 index 0000000000..512c18caa0 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai/models/list.handler.ts @@ -0,0 +1,63 @@ +import operation from "../../_operations/ai/models/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai models list", + classification: { + safeFlags: [ + "hide-experimental", + "include-deprecated", + "format", + "dry-run", + ], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + per_page: argv["per-page"], + page: argv["page"], + task: argv["task"], + author: argv["author"], + source: argv["source"], + hide_experimental: argv["hide-experimental"], + search: argv["search"], + include_deprecated: argv["include-deprecated"], + format: argv["format"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai models list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/models/search`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai/models/list.ts b/packages/cli/src/commands/_generated/ai/models/list.ts index 037516a5ba..92a5465db6 100644 --- a/packages/cli/src/commands/_generated/ai/models/list.ts +++ b/packages/cli/src/commands/_generated/ai/models/list.ts @@ -1,109 +1,75 @@ -import operation from "../../_operations/ai/models/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/ai.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai models list\n\nSearches Workers AI models by name or description." - ) - .option("per-page", { type: "number", description: "Per page" }) - .option("page", { type: "number", description: "Page" }) - .option("task", { type: "string", description: "Filter by Task Name." }) - .option("author", { type: "string", description: "Filter by Author." }) - .option("source", { type: "number", description: "Filter by Source Id." }) - .option("hide-experimental", { - type: "boolean", - description: "Filter to hide experimental models.", - }) - .option("search", { type: "string", description: "Search." }) - .option("include-deprecated", { - type: "boolean", - description: +const parameters = { + flags: { + "per-page": { + kind: "parsed", + brief: "Per page", + optional: true, + parse: Number, + }, + page: { kind: "parsed", brief: "Page", optional: true, parse: Number }, + task: { + kind: "parsed", + brief: "Filter by Task Name.", + optional: true, + parse: String, + }, + author: { + kind: "parsed", + brief: "Filter by Author.", + optional: true, + parse: String, + }, + source: { + kind: "parsed", + brief: "Filter by Source Id.", + optional: true, + parse: Number, + }, + "hide-experimental": { + kind: "boolean", + brief: "Filter to hide experimental models.", + optional: true, + }, + search: { kind: "parsed", brief: "Search.", optional: true, parse: String }, + "include-deprecated": { + kind: "boolean", + brief: "If true, include models for up to three months after their deprecation date. Defaults to false.", - }) - .option("format", { - type: "string", - description: + optional: true, + }, + format: { + kind: "enum", + brief: "If set, return models in the requested marketplace format instead of the default response.", - choices: ["openrouter"], - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + values: ["openrouter"], + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "Model Search", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai models list", - classification: { - safeFlags: [ - "hide-experimental", - "include-deprecated", - "format", - "dry-run", - ], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - per_page: argv["per-page"], - page: argv["page"], - task: argv["task"], - author: argv["author"], - source: argv["source"], - hide_experimental: argv["hide-experimental"], - search: argv["search"], - include_deprecated: argv["include-deprecated"], - format: argv["format"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai models list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/models/search`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai models list\n\nSearches Workers AI models by name or description.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai/tasks/index.ts b/packages/cli/src/commands/_generated/ai/tasks/index.ts index bcc416504a..8728b9f06f 100644 --- a/packages/cli/src/commands/_generated/ai/tasks/index.ts +++ b/packages/cli/src/commands/_generated/ai/tasks/index.ts @@ -1,20 +1,17 @@ import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * tasks command group * @generated from apis/overlays/ai.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "tasks", describe: "Operations for tasks", - builder: (yargs) => { - return yargs.command($list).demandCommand(1, "Please specify a subcommand"); + routes: { + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai/tasks/list.handler.ts b/packages/cli/src/commands/_generated/ai/tasks/list.handler.ts new file mode 100644 index 0000000000..8ce4d16e77 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai/tasks/list.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/ai/tasks/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai tasks list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai tasks list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/tasks/search`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai/tasks/list.ts b/packages/cli/src/commands/_generated/ai/tasks/list.ts index 306e6f94b1..d803621bc8 100644 --- a/packages/cli/src/commands/_generated/ai/tasks/list.ts +++ b/packages/cli/src/commands/_generated/ai/tasks/list.ts @@ -1,71 +1,31 @@ -import operation from "../../_operations/ai/tasks/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/ai.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai tasks list\n\nSearches Workers AI models by task type (e.g., text-generation, embeddings)." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "Task Search", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai tasks list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai tasks list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/tasks/search`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 ai tasks list\n\nSearches Workers AI models by task type (e.g., text-generation, embeddings).", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai/to-markdown.handler.ts b/packages/cli/src/commands/_generated/ai/to-markdown.handler.ts new file mode 100644 index 0000000000..7811a56f92 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai/to-markdown.handler.ts @@ -0,0 +1,122 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./to-markdown.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { readFileForFlag, resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai to-markdown", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if ( + argv.body === undefined && + argv.file === undefined && + argv["files"] === undefined + ) { + throw new Error( + "--body or --file is required for this command. Pass --body '' or --file path/to/file." + ); + } + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai to-markdown", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/tomarkdown`, + pathParams: {}, + bodyKind: "multipart", + body: { + body: argv["body"], + file: argv["file"], + files: argv["files"], + }, + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + argv.file !== undefined || + argv.body !== undefined || + argv["files"] !== undefined + ) { + const formData = new FormData(); + if (argv.file !== undefined) { + const fileContent = readFileForFlag(argv.file); + formData.append( + "files", + new Blob([fileContent]), + argv.file.split(/[\\/]/).filter(Boolean).pop() + ); + } else if (argv.body !== undefined) { + formData.append("files", argv.body); + } + if (argv["files"] !== undefined) { + for (const value of argv["files"]) { + if (value.startsWith("@")) { + const filePath = value.slice(1); + const fileContent = resolveFileToken( + value, + "files", + "binary" + ) as Buffer; + formData.append( + "files", + new Blob([fileContent]), + filePath.split(/[\\/]/).filter(Boolean).pop() + ); + } else { + formData.append("files", new Blob([value]), "files"); + } + } + } + const result = await withProgress(`Creating`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/ai/tomarkdown`, + { body: formData } + ) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + if (argv.body !== undefined) { + // Endpoint does not accept application/json — send --body as raw bytes, + // resolving @file references as binary file contents. + const bodyData = resolveFileToken(argv.body, "body", "binary"); + const result = await withProgress(`Creating`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/ai/tomarkdown`, + { + body: bodyData, + headers: { "Content-Type": "multipart/form-data" }, + } + ) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai/to-markdown.ts b/packages/cli/src/commands/_generated/ai/to-markdown.ts index f23d5b24c0..a08fc51bdd 100644 --- a/packages/cli/src/commands/_generated/ai/to-markdown.ts +++ b/packages/cli/src/commands/_generated/ai/to-markdown.ts @@ -1,162 +1,52 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * to-markdown command * @generated from apis/overlays/ai.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { readFileForFlag, resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai to-markdown\n\nConverts files uploaded as multipart form data into Markdown using Workers AI. Returns a conversion result for each file. Use the supported-formats endpoint to check accepted file types." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }) - .option("file", { - type: "string", - description: "Path to a file to upload as the request body", - }) - .option("files", { - type: "string", - array: true, - requiresArg: true, - description: + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + file: { + kind: "parsed", + brief: "Path to a file to upload as the request body", + optional: true, + parse: String, + }, + files: { + kind: "parsed", + brief: "Literal content or @path/to/file for the `files` form field. Repeat for multiple files. Files to convert, supplied as multipart file uploads.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + variadic: true, + optional: true, + requiresArg: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "to-markdown", describe: "Convert uploaded files to Markdown", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai to-markdown", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if ( - argv.body === undefined && - argv.file === undefined && - argv["files"] === undefined - ) { - throw new Error( - "--body or --file is required for this command. Pass --body '' or --file path/to/file." - ); - } - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai to-markdown", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/tomarkdown`, - pathParams: {}, - bodyKind: "multipart", - body: { - body: argv["body"], - file: argv["file"], - files: argv["files"], - }, - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - argv.file !== undefined || - argv.body !== undefined || - argv["files"] !== undefined - ) { - const formData = new FormData(); - if (argv.file !== undefined) { - const fileContent = readFileForFlag(argv.file); - formData.append( - "files", - new Blob([fileContent]), - argv.file.split(/[\\/]/).filter(Boolean).pop() - ); - } else if (argv.body !== undefined) { - formData.append("files", argv.body); - } - if (argv["files"] !== undefined) { - for (const value of argv["files"]) { - if (value.startsWith("@")) { - const filePath = value.slice(1); - const fileContent = resolveFileToken( - value, - "files", - "binary" - ) as Buffer; - formData.append( - "files", - new Blob([fileContent]), - filePath.split(/[\\/]/).filter(Boolean).pop() - ); - } else { - formData.append("files", new Blob([value]), "files"); - } - } - } - const result = await withProgress(`Creating`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/ai/tomarkdown`, - { body: formData } - ) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - if (argv.body !== undefined) { - // Endpoint does not accept application/json — send --body as raw bytes, - // resolving @file references as binary file contents. - const bodyData = resolveFileToken(argv.body, "body", "binary"); - const result = await withProgress(`Creating`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/ai/tomarkdown`, - { - body: bodyData, - headers: { "Content-Type": "multipart/form-data" }, - } - ) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - } - ), -}; + usage: + "$0 ai to-markdown\n\nConverts files uploaded as multipart form data into Markdown using Workers AI. Returns a conversion result for each file. Use the supported-formats endpoint to check accepted file types.", + ...parameters, + loader: () => import("./to-markdown.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/ai/websearch.handler.ts b/packages/cli/src/commands/_generated/ai/websearch.handler.ts new file mode 100644 index 0000000000..2d2a242178 --- /dev/null +++ b/packages/cli/src/commands/_generated/ai/websearch.handler.ts @@ -0,0 +1,136 @@ +import operation from "../_operations/ai/websearch.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./websearch.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "ai websearch", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["options-gateway-id"] === undefined) { + argv["options-gateway-id"] = await promptForRequiredField( + "options-gateway-id", + "The options.gateway.id field" + ); + } + if (argv["query"] === undefined) { + argv["query"] = await promptForRequiredField( + "query", + "The query field" + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf ai websearch", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/websearch`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + byokAlias: resolveFileToken( + argv["byok-alias"] as string | undefined, + "byok-alias", + "text" + ), + limit: argv["limit"], + options: { + gateway: { + id: resolveFileToken( + argv["options-gateway-id"] as string | undefined, + "options-gateway-id", + "text" + ), + }, + }, + provider: resolveFileToken( + argv["provider"] as string | undefined, + "provider", + "text" + ), + query: resolveFileToken( + argv["query"] as string | undefined, + "query", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + byokAlias: resolveFileToken( + argv["byok-alias"] as string | undefined, + "byok-alias", + "text" + ), + limit: argv["limit"], + options: { + gateway: { + id: resolveFileToken( + argv["options-gateway-id"] as string | undefined, + "options-gateway-id", + "text" + ), + }, + }, + provider: resolveFileToken( + argv["provider"] as string | undefined, + "provider", + "text" + ), + query: resolveFileToken( + argv["query"] as string | undefined, + "query", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/ai/websearch.ts b/packages/cli/src/commands/_generated/ai/websearch.ts index ff6aeecb8f..5a4467d7d0 100644 --- a/packages/cli/src/commands/_generated/ai/websearch.ts +++ b/packages/cli/src/commands/_generated/ai/websearch.ts @@ -1,176 +1,66 @@ -import operation from "../_operations/ai/websearch.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * websearch command * @generated from apis/overlays/ai.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 ai websearch\n\nRun a web search through a configured AI Gateway." - ) - .option("byok-alias", { - type: "string", - description: "The byokAlias field", - }) - .option("limit", { type: "number", description: "The limit field" }) - .option("options-gateway-id", { - type: "string", - description: "The options.gateway.id field", - }) - .option("provider", { type: "string", description: "The provider field" }) - .option("query", { type: "string", description: "The query field" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "byok-alias": { + kind: "parsed", + brief: "The byokAlias field", + optional: true, + parse: String, + }, + limit: { + kind: "parsed", + brief: "The limit field", + optional: true, + parse: Number, + }, + "options-gateway-id": { + kind: "parsed", + brief: "The options.gateway.id field", + optional: true, + parse: String, + }, + provider: { + kind: "parsed", + brief: "The provider field", + optional: true, + parse: String, + }, + query: { + kind: "parsed", + brief: "The query field", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "websearch", describe: "Search the web through AI Gateway", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "ai websearch", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["options-gateway-id"] === undefined) { - argv["options-gateway-id"] = await promptForRequiredField( - "options-gateway-id", - "The options.gateway.id field" - ); - } - if (argv["query"] === undefined) { - argv["query"] = await promptForRequiredField( - "query", - "The query field" - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf ai websearch", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/ai/websearch`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - byokAlias: resolveFileToken( - argv["byok-alias"] as string | undefined, - "byok-alias", - "text" - ), - limit: argv["limit"], - options: { - gateway: { - id: resolveFileToken( - argv["options-gateway-id"] as string | undefined, - "options-gateway-id", - "text" - ), - }, - }, - provider: resolveFileToken( - argv["provider"] as string | undefined, - "provider", - "text" - ), - query: resolveFileToken( - argv["query"] as string | undefined, - "query", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - byokAlias: resolveFileToken( - argv["byok-alias"] as string | undefined, - "byok-alias", - "text" - ), - limit: argv["limit"], - options: { - gateway: { - id: resolveFileToken( - argv["options-gateway-id"] as string | undefined, - "options-gateway-id", - "text" - ), - }, - }, - provider: resolveFileToken( - argv["provider"] as string | undefined, - "provider", - "text" - ), - query: resolveFileToken( - argv["query"] as string | undefined, - "query", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: "$0 ai websearch\n\nRun a web search through a configured AI Gateway.", + ...parameters, + loader: () => import("./websearch.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/available-alerts/index.ts b/packages/cli/src/commands/_generated/alerting/available-alerts/index.ts index f6a64555ab..da6d603ede 100644 --- a/packages/cli/src/commands/_generated/alerting/available-alerts/index.ts +++ b/packages/cli/src/commands/_generated/alerting/available-alerts/index.ts @@ -1,20 +1,17 @@ import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * available-alerts command group * @generated from apis/overlays/alerting.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "available-alerts", describe: "Operations for available-alerts", - builder: (yargs) => { - return yargs.command($list).demandCommand(1, "Please specify a subcommand"); + routes: { + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/available-alerts/list.handler.ts b/packages/cli/src/commands/_generated/alerting/available-alerts/list.handler.ts new file mode 100644 index 0000000000..c4b1324c81 --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/available-alerts/list.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/alerting/available-alerts/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting available-alerts list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting available-alerts list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/available_alerts`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/available-alerts/list.ts b/packages/cli/src/commands/_generated/alerting/available-alerts/list.ts index 64c15a0128..f10df089a4 100644 --- a/packages/cli/src/commands/_generated/alerting/available-alerts/list.ts +++ b/packages/cli/src/commands/_generated/alerting/available-alerts/list.ts @@ -1,71 +1,31 @@ -import operation from "../../_operations/alerting/available-alerts/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 alerting available-alerts list\n\nGets a list of all alert types for which an account is eligible." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "Get Alert Types", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting available-alerts list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting available-alerts list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/available_alerts`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 alerting available-alerts list\n\nGets a list of all alert types for which an account is eligible.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/destinations/eligible/get.handler.ts b/packages/cli/src/commands/_generated/alerting/destinations/eligible/get.handler.ts new file mode 100644 index 0000000000..f472428fa5 --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/destinations/eligible/get.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../../_operations/alerting/destinations/eligible/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting destinations eligible get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting destinations eligible get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/destinations/eligible`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/destinations/eligible/get.ts b/packages/cli/src/commands/_generated/alerting/destinations/eligible/get.ts index 5b678813f1..d4531aa700 100644 --- a/packages/cli/src/commands/_generated/alerting/destinations/eligible/get.ts +++ b/packages/cli/src/commands/_generated/alerting/destinations/eligible/get.ts @@ -1,71 +1,31 @@ -import operation from "../../../_operations/alerting/destinations/eligible/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 alerting destinations eligible get\n\nGet a list of all delivery mechanism types for which an account is eligible." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "Get delivery mechanism eligibility", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting destinations eligible get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting destinations eligible get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/destinations/eligible`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 alerting destinations eligible get\n\nGet a list of all delivery mechanism types for which an account is eligible.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/destinations/eligible/index.ts b/packages/cli/src/commands/_generated/alerting/destinations/eligible/index.ts index 74c3881fba..12b6436b40 100644 --- a/packages/cli/src/commands/_generated/alerting/destinations/eligible/index.ts +++ b/packages/cli/src/commands/_generated/alerting/destinations/eligible/index.ts @@ -1,20 +1,17 @@ import $get from "./get.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * eligible command group * @generated from apis/overlays/alerting.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "eligible", describe: "Operations for destinations.eligible", - builder: (yargs) => { - return yargs.command($get).demandCommand(1, "Please specify a subcommand"); + routes: { + get: $get, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/destinations/index.ts b/packages/cli/src/commands/_generated/alerting/destinations/index.ts index 0bb57b520e..97b3e30809 100644 --- a/packages/cli/src/commands/_generated/alerting/destinations/index.ts +++ b/packages/cli/src/commands/_generated/alerting/destinations/index.ts @@ -1,26 +1,21 @@ import $eligible from "./eligible/index.js"; import $pagerduty from "./pagerduty/index.js"; import $webhooks from "./webhooks/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * destinations command group * @generated from apis/overlays/alerting.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "destinations", describe: "Operations for destinations", - builder: (yargs) => { - return yargs - .command($eligible) - .command($pagerduty) - .command($webhooks) - .demandCommand(1, "Please specify a subcommand"); + routes: { + eligible: $eligible, + pagerduty: $pagerduty, + webhooks: $webhooks, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/create.handler.ts b/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/create.handler.ts new file mode 100644 index 0000000000..edfa300966 --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/create.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../../_operations/alerting/destinations/pagerduty/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting destinations pagerduty create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting destinations pagerduty create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/destinations/pagerduty/connect`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Creating`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/create.ts b/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/create.ts index 66f29af84d..b4ebcf2382 100644 --- a/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/create.ts +++ b/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/create.ts @@ -1,71 +1,31 @@ -import operation from "../../../_operations/alerting/destinations/pagerduty/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 alerting destinations pagerduty create\n\nCreates a new token for integrating with PagerDuty." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Create PagerDuty integration token", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting destinations pagerduty create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting destinations pagerduty create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/destinations/pagerduty/connect`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Creating`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 alerting destinations pagerduty create\n\nCreates a new token for integrating with PagerDuty.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/delete.handler.ts b/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/delete.handler.ts new file mode 100644 index 0000000000..2d76d13d45 --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/delete.handler.ts @@ -0,0 +1,57 @@ +import operation from "../../../_operations/alerting/destinations/pagerduty/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting destinations pagerduty delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting destinations pagerduty delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/destinations/pagerduty`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This operation deletes all PagerDuty services connected to the account.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/delete.ts b/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/delete.ts index e8e3306e6e..1710bc3550 100644 --- a/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/delete.ts +++ b/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/delete.ts @@ -1,88 +1,37 @@ -import operation from "../../../_operations/alerting/destinations/pagerduty/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 alerting destinations pagerduty delete\n\nDeletes all the PagerDuty Services connected to the account." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete", describe: "Delete PagerDuty Services", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting destinations pagerduty delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting destinations pagerduty delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/destinations/pagerduty`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This operation deletes all PagerDuty services connected to the account.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 alerting destinations pagerduty delete\n\nDeletes all the PagerDuty Services connected to the account.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/get.handler.ts b/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/get.handler.ts new file mode 100644 index 0000000000..04748e6067 --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/get.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../../_operations/alerting/destinations/pagerduty/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting destinations pagerduty get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting destinations pagerduty get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/destinations/pagerduty`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/get.ts b/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/get.ts index 5c741161ca..9c24299d52 100644 --- a/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/get.ts +++ b/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/get.ts @@ -1,71 +1,31 @@ -import operation from "../../../_operations/alerting/destinations/pagerduty/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 alerting destinations pagerduty get\n\nGet a list of all configured PagerDuty services." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "List PagerDuty services", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting destinations pagerduty get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting destinations pagerduty get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/destinations/pagerduty`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 alerting destinations pagerduty get\n\nGet a list of all configured PagerDuty services.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/index.ts b/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/index.ts index 0a5f16bde4..2eac8b7344 100644 --- a/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/index.ts +++ b/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/index.ts @@ -2,27 +2,22 @@ import $create from "./create.js"; import $delete from "./delete.js"; import $get from "./get.js"; import $link from "./link.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * pagerduty command group * @generated from apis/overlays/alerting.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "pagerduty", describe: "Operations for destinations.pagerduty", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .command($link) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, + link: $link, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/link.handler.ts b/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/link.handler.ts new file mode 100644 index 0000000000..5e64e309e9 --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/link.handler.ts @@ -0,0 +1,49 @@ +import operation from "../../../_operations/alerting/destinations/pagerduty/link.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./link.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting destinations pagerduty link", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting destinations pagerduty link", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/destinations/pagerduty/connect/${argv["token-id"] == null ? "" : encodeURIComponent(String(argv["token-id"]))}`, + pathParams: { "token-id": String(argv["token-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + token_id: argv["token-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/link.ts b/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/link.ts index 56754f877e..6ef977c166 100644 --- a/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/link.ts +++ b/packages/cli/src/commands/_generated/alerting/destinations/pagerduty/link.ts @@ -1,79 +1,37 @@ -import operation from "../../../_operations/alerting/destinations/pagerduty/link.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * link command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 alerting destinations pagerduty link \n\nLinks PagerDuty with the account using the integration token." - ) - .positional("token-id", { - type: "string", - description: "The token integration key", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "token-id", + brief: "The token integration key", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "link ", describe: "Connect PagerDuty", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting destinations pagerduty link", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting destinations pagerduty link", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/destinations/pagerduty/connect/${argv["token-id"] == null ? "" : encodeURIComponent(String(argv["token-id"]))}`, - pathParams: { "token-id": String(argv["token-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - token_id: argv["token-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 alerting destinations pagerduty link \n\nLinks PagerDuty with the account using the integration token.", + ...parameters, + loader: () => import("./link.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/destinations/webhooks/create.handler.ts b/packages/cli/src/commands/_generated/alerting/destinations/webhooks/create.handler.ts new file mode 100644 index 0000000000..96e57212da --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/destinations/webhooks/create.handler.ts @@ -0,0 +1,113 @@ +import operation from "../../../_operations/alerting/destinations/webhooks/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting destinations webhooks create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField( + "name", + "The name of the webhook destination. This will be included in the request body when you receive a webhook notification." + ); + } + if (argv["url"] === undefined) { + argv["url"] = await promptForRequiredField( + "url", + "The POST endpoint to call when dispatching a notification." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting destinations webhooks create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/destinations/webhooks`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + secret: resolveFileToken( + argv["secret"] as string | undefined, + "secret", + "text" + ), + url: resolveFileToken( + argv["url"] as string | undefined, + "url", + "text" + ), + }), + sensitiveBodyPaths: [["secret"]], + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + secret: resolveFileToken( + argv["secret"] as string | undefined, + "secret", + "text" + ), + url: resolveFileToken(argv["url"] as string | undefined, "url", "text"), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/destinations/webhooks/create.ts b/packages/cli/src/commands/_generated/alerting/destinations/webhooks/create.ts index 5fb8c098cb..de43ef9b15 100644 --- a/packages/cli/src/commands/_generated/alerting/destinations/webhooks/create.ts +++ b/packages/cli/src/commands/_generated/alerting/destinations/webhooks/create.ts @@ -1,160 +1,57 @@ -import operation from "../../../_operations/alerting/destinations/webhooks/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 alerting destinations webhooks create\n\nCreates a new webhook destination." - ) - .option("name", { - type: "string", - description: +const parameters = { + flags: { + name: { + kind: "parsed", + brief: "The name of the webhook destination. This will be included in the request body when you receive a webhook notification.", - }) - .option("secret", { - type: "string", - description: + optional: true, + parse: String, + }, + secret: { + kind: "parsed", + brief: "Optional secret that will be passed in the `cf-webhook-auth` header when dispatching generic webhook notifications or formatted for supported destinations. Secrets are not returned in any API response body.", - }) - .option("url", { - type: "string", - description: "The POST endpoint to call when dispatching a notification.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + url: { + kind: "parsed", + brief: "The POST endpoint to call when dispatching a notification.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Create a webhook", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting destinations webhooks create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "The name of the webhook destination. This will be included in the request body when you receive a webhook notification." - ); - } - if (argv["url"] === undefined) { - argv["url"] = await promptForRequiredField( - "url", - "The POST endpoint to call when dispatching a notification." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting destinations webhooks create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/destinations/webhooks`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - secret: resolveFileToken( - argv["secret"] as string | undefined, - "secret", - "text" - ), - url: resolveFileToken( - argv["url"] as string | undefined, - "url", - "text" - ), - }), - sensitiveBodyPaths: [["secret"]], - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - secret: resolveFileToken( - argv["secret"] as string | undefined, - "secret", - "text" - ), - url: resolveFileToken( - argv["url"] as string | undefined, - "url", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 alerting destinations webhooks create\n\nCreates a new webhook destination.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/destinations/webhooks/delete.handler.ts b/packages/cli/src/commands/_generated/alerting/destinations/webhooks/delete.handler.ts new file mode 100644 index 0000000000..999923a97a --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/destinations/webhooks/delete.handler.ts @@ -0,0 +1,60 @@ +import operation from "../../../_operations/alerting/destinations/webhooks/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting destinations webhooks delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting destinations webhooks delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/destinations/webhooks/${argv["webhook-id"] == null ? "" : encodeURIComponent(String(argv["webhook-id"]))}`, + pathParams: { "webhook-id": String(argv["webhook-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This operation deletes the webhook destination.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + webhook_id: argv["webhook-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/destinations/webhooks/delete.ts b/packages/cli/src/commands/_generated/alerting/destinations/webhooks/delete.ts index a1d8bb0faf..b83d5cf14a 100644 --- a/packages/cli/src/commands/_generated/alerting/destinations/webhooks/delete.ts +++ b/packages/cli/src/commands/_generated/alerting/destinations/webhooks/delete.ts @@ -1,96 +1,43 @@ -import operation from "../../../_operations/alerting/destinations/webhooks/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 alerting destinations webhooks delete \n\nDelete a configured webhook destination." - ) - .positional("webhook-id", { - type: "string", - description: "The unique identifier of a webhook", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "webhook-id", + brief: "The unique identifier of a webhook", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete a webhook", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting destinations webhooks delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting destinations webhooks delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/destinations/webhooks/${argv["webhook-id"] == null ? "" : encodeURIComponent(String(argv["webhook-id"]))}`, - pathParams: { "webhook-id": String(argv["webhook-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This operation deletes the webhook destination.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - webhook_id: argv["webhook-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 alerting destinations webhooks delete \n\nDelete a configured webhook destination.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/destinations/webhooks/get.handler.ts b/packages/cli/src/commands/_generated/alerting/destinations/webhooks/get.handler.ts new file mode 100644 index 0000000000..c2329200f3 --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/destinations/webhooks/get.handler.ts @@ -0,0 +1,49 @@ +import operation from "../../../_operations/alerting/destinations/webhooks/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting destinations webhooks get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting destinations webhooks get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/destinations/webhooks/${argv["webhook-id"] == null ? "" : encodeURIComponent(String(argv["webhook-id"]))}`, + pathParams: { "webhook-id": String(argv["webhook-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + webhook_id: argv["webhook-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/destinations/webhooks/get.ts b/packages/cli/src/commands/_generated/alerting/destinations/webhooks/get.ts index 82871b6afb..e4dd640bf1 100644 --- a/packages/cli/src/commands/_generated/alerting/destinations/webhooks/get.ts +++ b/packages/cli/src/commands/_generated/alerting/destinations/webhooks/get.ts @@ -1,79 +1,37 @@ -import operation from "../../../_operations/alerting/destinations/webhooks/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 alerting destinations webhooks get \n\nGet details for a single webhooks destination." - ) - .positional("webhook-id", { - type: "string", - description: "The unique identifier of a webhook", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "webhook-id", + brief: "The unique identifier of a webhook", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get a webhook", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting destinations webhooks get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting destinations webhooks get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/destinations/webhooks/${argv["webhook-id"] == null ? "" : encodeURIComponent(String(argv["webhook-id"]))}`, - pathParams: { "webhook-id": String(argv["webhook-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - webhook_id: argv["webhook-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 alerting destinations webhooks get \n\nGet details for a single webhooks destination.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/destinations/webhooks/index.ts b/packages/cli/src/commands/_generated/alerting/destinations/webhooks/index.ts index b97c5df929..ed07a9cebe 100644 --- a/packages/cli/src/commands/_generated/alerting/destinations/webhooks/index.ts +++ b/packages/cli/src/commands/_generated/alerting/destinations/webhooks/index.ts @@ -3,28 +3,23 @@ import $delete from "./delete.js"; import $get from "./get.js"; import $list from "./list.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * webhooks command group * @generated from apis/overlays/alerting.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "webhooks", describe: "Operations for destinations.webhooks", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .command($list) - .command($update) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, + list: $list, + update: $update, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/destinations/webhooks/list.handler.ts b/packages/cli/src/commands/_generated/alerting/destinations/webhooks/list.handler.ts new file mode 100644 index 0000000000..6c8753123d --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/destinations/webhooks/list.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../../_operations/alerting/destinations/webhooks/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting destinations webhooks list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting destinations webhooks list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/destinations/webhooks`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/destinations/webhooks/list.ts b/packages/cli/src/commands/_generated/alerting/destinations/webhooks/list.ts index 264cc1907a..5b48ccc7d6 100644 --- a/packages/cli/src/commands/_generated/alerting/destinations/webhooks/list.ts +++ b/packages/cli/src/commands/_generated/alerting/destinations/webhooks/list.ts @@ -1,71 +1,31 @@ -import operation from "../../../_operations/alerting/destinations/webhooks/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 alerting destinations webhooks list\n\nGets a list of all configured webhook destinations." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List webhooks", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting destinations webhooks list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting destinations webhooks list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/destinations/webhooks`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 alerting destinations webhooks list\n\nGets a list of all configured webhook destinations.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/destinations/webhooks/update.handler.ts b/packages/cli/src/commands/_generated/alerting/destinations/webhooks/update.handler.ts new file mode 100644 index 0000000000..19a865e19d --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/destinations/webhooks/update.handler.ts @@ -0,0 +1,98 @@ +import operation from "../../../_operations/alerting/destinations/webhooks/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting destinations webhooks update", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField( + "name", + "The name of the webhook destination. This will be included in the request body when you receive a webhook notification." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting destinations webhooks update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/destinations/webhooks/${argv["webhook-id"] == null ? "" : encodeURIComponent(String(argv["webhook-id"]))}`, + pathParams: { "webhook-id": String(argv["webhook-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + webhook_id: argv["webhook-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + webhook_id: argv["webhook-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/destinations/webhooks/update.ts b/packages/cli/src/commands/_generated/alerting/destinations/webhooks/update.ts index 01b2a63b6c..f51762813d 100644 --- a/packages/cli/src/commands/_generated/alerting/destinations/webhooks/update.ts +++ b/packages/cli/src/commands/_generated/alerting/destinations/webhooks/update.ts @@ -1,137 +1,50 @@ -import operation from "../../../_operations/alerting/destinations/webhooks/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 alerting destinations webhooks update \n\nUpdate a webhook destination. Only `name` can be updated. `url` and `secret` are immutable; to change them, delete the webhook and create a new one." - ) - .positional("webhook-id", { - type: "string", - description: "The unique identifier of a webhook", - demandOption: true, - }) - .option("name", { - type: "string", - description: +const parameters = { + flags: { + name: { + kind: "parsed", + brief: "The name of the webhook destination. This will be included in the request body when you receive a webhook notification.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "webhook-id", + brief: "The unique identifier of a webhook", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update ", describe: "Update a webhook", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting destinations webhooks update", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "The name of the webhook destination. This will be included in the request body when you receive a webhook notification." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting destinations webhooks update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/destinations/webhooks/${argv["webhook-id"] == null ? "" : encodeURIComponent(String(argv["webhook-id"]))}`, - pathParams: { "webhook-id": String(argv["webhook-id"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - webhook_id: argv["webhook-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - webhook_id: argv["webhook-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 alerting destinations webhooks update \n\nUpdate a webhook destination. Only `name` can be updated. `url` and `secret` are immutable; to change them, delete the webhook and create a new one.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/history/index.ts b/packages/cli/src/commands/_generated/alerting/history/index.ts index 6878db0fd7..236694fede 100644 --- a/packages/cli/src/commands/_generated/alerting/history/index.ts +++ b/packages/cli/src/commands/_generated/alerting/history/index.ts @@ -1,20 +1,17 @@ import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * history command group * @generated from apis/overlays/alerting.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "history", describe: "Operations for history", - builder: (yargs) => { - return yargs.command($list).demandCommand(1, "Please specify a subcommand"); + routes: { + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/history/list.handler.ts b/packages/cli/src/commands/_generated/alerting/history/list.handler.ts new file mode 100644 index 0000000000..8980526719 --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/history/list.handler.ts @@ -0,0 +1,53 @@ +import operation from "../../_operations/alerting/history/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting history list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + per_page: argv["per-page"], + before: argv["before"], + page: argv["page"], + since: argv["since"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting history list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/history`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/history/list.ts b/packages/cli/src/commands/_generated/alerting/history/list.ts index 37cab838be..d35f35f435 100644 --- a/packages/cli/src/commands/_generated/alerting/history/list.ts +++ b/packages/cli/src/commands/_generated/alerting/history/list.ts @@ -1,96 +1,57 @@ -import operation from "../../_operations/alerting/history/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 alerting history list\n\nGets a list of history records for notifications sent to an account. The records are displayed for last `x` number of days based on the zone plan (free = 30, pro = 30, biz = 30, ent = 90)." - ) - .option("per-page", { - type: "number", - description: "Number of items per page.", - }) - .option("before", { - type: "string", - description: +const parameters = { + flags: { + "per-page": { + kind: "parsed", + brief: "Number of items per page.", + optional: true, + parse: Number, + }, + before: { + kind: "parsed", + brief: "Limit the returned results to history records older than the specified date. This must be a timestamp that conforms to RFC3339.", - }) - .option("page", { - type: "number", - description: "Page number of paginated results.", - }) - .option("since", { - type: "string", - description: + optional: true, + parse: String, + }, + page: { + kind: "parsed", + brief: "Page number of paginated results.", + optional: true, + parse: Number, + }, + since: { + kind: "parsed", + brief: "Limit the returned results to history records newer than the specified date. This must be a timestamp that conforms to RFC3339.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List History", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting history list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - per_page: argv["per-page"], - before: argv["before"], - page: argv["page"], - since: argv["since"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting history list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/history`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 alerting history list\n\nGets a list of history records for notifications sent to an account. The records are displayed for last `x` number of days based on the zone plan (free = 30, pro = 30, biz = 30, ent = 90).", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/index.ts b/packages/cli/src/commands/_generated/alerting/index.ts index dd2312fbd4..b01aaad3d5 100644 --- a/packages/cli/src/commands/_generated/alerting/index.ts +++ b/packages/cli/src/commands/_generated/alerting/index.ts @@ -3,28 +3,23 @@ import $destinations from "./destinations/index.js"; import $history from "./history/index.js"; import $policies from "./policies/index.js"; import $silences from "./silences/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * alerting command * @generated from apis/overlays/alerting.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "alerting", describe: "alerting", - builder: (yargs) => { - return yargs - .command($availablealerts) - .command($destinations) - .command($history) - .command($policies) - .command($silences) - .demandCommand(1, "Please specify a subcommand"); + routes: { + "available-alerts": $availablealerts, + destinations: $destinations, + history: $history, + policies: $policies, + silences: $silences, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/policies/create.handler.ts b/packages/cli/src/commands/_generated/alerting/policies/create.handler.ts new file mode 100644 index 0000000000..314221a789 --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/policies/create.handler.ts @@ -0,0 +1,347 @@ +import operation from "../../_operations/alerting/policies/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { + promptForRequiredEnumField, + promptForRequiredField, +} from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting policies create", + classification: { + safeFlags: ["alert-type", "enabled", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["alert-type"] === undefined) { + argv["alert-type"] = await promptForRequiredEnumField( + "alert-type", + "Refers to which event will trigger a Notification dispatch. You can use the endpoint to get available alert types which then will give you a list of possible values. This enum lists every alert type, not the ones a given account can create, since some types depend on entitlements or account type. To get the alert types an account can create, call \`GET /accounts/{account_id}/alerting/v3/available_alerts\`.", + [ + "abuse_report_alert", + "access_custom_certificate_expiration_type", + "advanced_ddos_attack_l4_alert", + "advanced_ddos_attack_l7_alert", + "advanced_http_alert_error", + "attack_lifecycle", + "bgp_advertisement_change", + "bgp_hijack_notification", + "billing_budget_alert", + "billing_usage_alert", + "block_notification_block_removed", + "block_notification_new_block", + "block_notification_review_rejected", + "bot_traffic_basic_alert", + "brand_protection_alert", + "brand_protection_digest", + "casb_weekly_digest", + "clickhouse_alert_fw_anomaly", + "clickhouse_alert_fw_ent_anomaly", + "closed_port_scan_alert", + "cloudforce_one_request_notification", + "cmd_managed_defense_notification", + "cni_maintenance_notification", + "containers_security_alert", + "custom_analytics", + "custom_bot_detection_alert", + "custom_ssl_certificate_event_type", + "dedicated_ssl_certificate_event_type", + "device_connectivity_anomaly_alert", + "dex_device_connectivity_alert", + "dex_synthetic_test_availability_alert", + "dex_synthetic_test_latency_alert", + "dos_attack_l4", + "dos_attack_l7", + "executive_communications", + "expiring_service_token_alert", + "failing_logpush_job_disabled_alert", + "fbm_auto_advertisement", + "fbm_dosd_attack", + "fbm_volumetric_attack", + "health_check_status_notification", + "hostname_aop_custom_certificate_expiration_type", + "http_alert_edge_error", + "http_alert_origin_error", + "image_notification", + "image_resizing_notification", + "incident_alert", + "leaked_service_token_alert", + "load_balancing_health_alert", + "load_balancing_pool_enablement_alert", + "log_explorer_ingest_rate_limit", + "log_explorer_scheduled_query_results_alert", + "logo_match_alert", + "magic_endpoint_healthcheck_alert", + "magic_tunnel_health_check_event", + "magic_wan_tunnel_health", + "maintenance_event_notification", + "mtls_certificate_store_certificate_expiration_type", + "open_port_scan_alert", + "pages_event_alert", + "radar_notification", + "real_origin_monitoring", + "scriptmonitor_alert_new_code_change_detections", + "scriptmonitor_alert_new_hosts", + "scriptmonitor_alert_new_malicious_hosts", + "scriptmonitor_alert_new_malicious_scripts", + "scriptmonitor_alert_new_malicious_url", + "scriptmonitor_alert_new_max_length_resource_url", + "scriptmonitor_alert_new_resources", + "secondary_dns_all_primaries_failing", + "secondary_dns_primaries_failing", + "secondary_dns_warning", + "secondary_dns_zone_successfully_updated", + "secondary_dns_zone_validation_warning", + "security_insights_alert", + "sentinel_alert", + "stakeout_credential_leak_alert", + "stakeout_saved_query_daily_digest_alert", + "stakeout_saved_query_immediate_alert", + "stream_live_notifications", + "synthetic_test_latency_alert", + "synthetic_test_low_availability_alert", + "traffic_anomalies_alert", + "tunnel_health_event", + "tunnel_update_event", + "universal_ssl_event_type", + "web_analytics_metrics_update", + "workers_for_platforms_security_alert", + "workers_observability_alert", + "workers_observability_real_time_issue", + "zone_aop_custom_certificate_expiration_type", + ] as const + ); + } + if (argv["enabled"] === undefined) { + throw new Error( + "--enabled is required (or pass --body with this field set)." + ); + } + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField( + "name", + "Name of the policy." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting policies create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/policies`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + alert_interval: resolveFileToken( + argv["alert-interval"] as string | undefined, + "alert-interval", + "text" + ), + alert_type: argv["alert-type"], + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + enabled: argv["enabled"], + filters: { + actions: argv["filters-actions"], + affected_asns: argv["filters-affected-asns"], + affected_components: argv["filters-affected-components"], + affected_locations: argv["filters-affected-locations"], + airport_code: argv["filters-airport-code"], + alert_trigger_preferences: + argv["filters-alert-trigger-preferences"], + alert_trigger_preferences_value: + argv["filters-alert-trigger-preferences-value"], + check_id: argv["filters-check-id"], + enabled: argv["filters-enabled"], + environment: argv["filters-environment"], + event: argv["filters-event"], + event_source: argv["filters-event-source"], + event_type: argv["filters-event-type"], + group_by: argv["filters-group-by"], + health_check_id: argv["filters-health-check-id"], + incident_impact: argv["filters-incident-impact"], + input_id: argv["filters-input-id"], + insight_class: argv["filters-insight-class"], + limit: argv["filters-limit"], + logo_tag: argv["filters-logo-tag"], + megabits_per_second: argv["filters-megabits-per-second"], + new_health: argv["filters-new-health"], + new_status: argv["filters-new-status"], + packets_per_second: argv["filters-packets-per-second"], + pool_id: argv["filters-pool-id"], + pop_names: argv["filters-pop-names"], + product: argv["filters-product"], + project_id: argv["filters-project-id"], + protocol: argv["filters-protocol"], + query_id: argv["filters-query-id"], + query_tag: argv["filters-query-tag"], + requests_per_second: argv["filters-requests-per-second"], + selectors: argv["filters-selectors"], + services: argv["filters-services"], + slo: argv["filters-slo"], + status: argv["filters-status"], + target_hostname: argv["filters-target-hostname"], + target_ip: argv["filters-target-ip"], + target_zone_name: argv["filters-target-zone-name"], + token_id: argv["filters-token-id"], + total_spend_dollars: argv["filters-total-spend-dollars"], + traffic_exclusions: argv["filters-traffic-exclusions"], + tunnel_id: argv["filters-tunnel-id"], + tunnel_name: argv["filters-tunnel-name"], + type: argv["filters-type"], + where: argv["filters-where"], + zones: argv["filters-zones"], + }, + mechanisms: { + email: parseObjectArray( + argv["mechanisms-email"], + "mechanisms-email" + ), + pagerduty: parseObjectArray( + argv["mechanisms-pagerduty"], + "mechanisms-pagerduty" + ), + webhooks: parseObjectArray( + argv["mechanisms-webhooks"], + "mechanisms-webhooks" + ), + }, + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + alert_interval: resolveFileToken( + argv["alert-interval"] as string | undefined, + "alert-interval", + "text" + ), + alert_type: argv["alert-type"], + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + enabled: argv["enabled"], + filters: { + actions: argv["filters-actions"], + affected_asns: argv["filters-affected-asns"], + affected_components: argv["filters-affected-components"], + affected_locations: argv["filters-affected-locations"], + airport_code: argv["filters-airport-code"], + alert_trigger_preferences: argv["filters-alert-trigger-preferences"], + alert_trigger_preferences_value: + argv["filters-alert-trigger-preferences-value"], + check_id: argv["filters-check-id"], + enabled: argv["filters-enabled"], + environment: argv["filters-environment"], + event: argv["filters-event"], + event_source: argv["filters-event-source"], + event_type: argv["filters-event-type"], + group_by: argv["filters-group-by"], + health_check_id: argv["filters-health-check-id"], + incident_impact: argv["filters-incident-impact"], + input_id: argv["filters-input-id"], + insight_class: argv["filters-insight-class"], + limit: argv["filters-limit"], + logo_tag: argv["filters-logo-tag"], + megabits_per_second: argv["filters-megabits-per-second"], + new_health: argv["filters-new-health"], + new_status: argv["filters-new-status"], + packets_per_second: argv["filters-packets-per-second"], + pool_id: argv["filters-pool-id"], + pop_names: argv["filters-pop-names"], + product: argv["filters-product"], + project_id: argv["filters-project-id"], + protocol: argv["filters-protocol"], + query_id: argv["filters-query-id"], + query_tag: argv["filters-query-tag"], + requests_per_second: argv["filters-requests-per-second"], + selectors: argv["filters-selectors"], + services: argv["filters-services"], + slo: argv["filters-slo"], + status: argv["filters-status"], + target_hostname: argv["filters-target-hostname"], + target_ip: argv["filters-target-ip"], + target_zone_name: argv["filters-target-zone-name"], + token_id: argv["filters-token-id"], + total_spend_dollars: argv["filters-total-spend-dollars"], + traffic_exclusions: argv["filters-traffic-exclusions"], + tunnel_id: argv["filters-tunnel-id"], + tunnel_name: argv["filters-tunnel-name"], + type: argv["filters-type"], + where: argv["filters-where"], + zones: argv["filters-zones"], + }, + mechanisms: { + email: parseObjectArray(argv["mechanisms-email"], "mechanisms-email"), + pagerduty: parseObjectArray( + argv["mechanisms-pagerduty"], + "mechanisms-pagerduty" + ), + webhooks: parseObjectArray( + argv["mechanisms-webhooks"], + "mechanisms-webhooks" + ), + }, + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/policies/create.ts b/packages/cli/src/commands/_generated/alerting/policies/create.ts index ef5502d1f9..4267f856f7 100644 --- a/packages/cli/src/commands/_generated/alerting/policies/create.ts +++ b/packages/cli/src/commands/_generated/alerting/policies/create.ts @@ -1,40 +1,28 @@ -import operation from "../../_operations/alerting/policies/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { - promptForRequiredEnumField, - promptForRequiredField, -} from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage("$0 alerting policies create\n\nCreates a new Notification policy.") - .option("alert-interval", { - type: "string", - description: +const parameters = { + flags: { + "alert-interval": { + kind: "parsed", + brief: "Optional specification of how often to re-alert from the same incident, not support on all alert types.", - }) - .option("alert-type", { - type: "string", - description: + optional: true, + parse: String, + }, + "alert-type": { + kind: "parsed", + brief: "Refers to which event will trigger a Notification dispatch. You can use the endpoint to get available alert types which then will give you a list of possible values. This enum lists every alert type, not the ones a given account can create, since some types depend on entitlements or account type. To get the alert types an account can create, call `GET /accounts/{account_id}/alerting/v3/available_alerts`.", + optional: true, choices: [ "abuse_report_alert", "access_custom_certificate_expiration_type", @@ -128,621 +116,401 @@ function builder(yargs: Argv) { "workers_observability_real_time_issue", "zone_aop_custom_certificate_expiration_type", ], - }) - .coerce("alert-type", (value) => - resolveFileToken(value, "alert-type", "text") - ) - .option("description", { - type: "string", - description: "Optional description for the Notification policy.", - }) - .option("enabled", { - type: "boolean", - description: "Whether or not the Notification policy is enabled.", + parse: String, + coerce: (value: string) => resolveFileToken(value, "alert-type", "text"), + }, + description: { + kind: "parsed", + brief: "Optional description for the Notification policy.", + optional: true, + parse: String, + }, + enabled: { + kind: "boolean", + brief: "Whether or not the Notification policy is enabled.", default: true, - }) - .option("filters-actions", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-affected-asns", { - type: "string", - array: true, - description: "Used for configuring radar_notification", - }) - .option("filters-affected-components", { - type: "string", - array: true, - description: "Used for configuring incident_alert", - }) - .option("filters-affected-locations", { - type: "string", - array: true, - description: "Used for configuring radar_notification", - }) - .option("filters-airport-code", { - type: "string", - array: true, - description: "Used for configuring maintenance_event_notification", - }) - .option("filters-alert-trigger-preferences", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-alert-trigger-preferences-value", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-check-id", { - type: "string", - array: true, - description: + }, + "filters-actions": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-affected-asns": { + kind: "parsed", + brief: "Used for configuring radar_notification", + variadic: true, + optional: true, + parse: String, + }, + "filters-affected-components": { + kind: "parsed", + brief: "Used for configuring incident_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-affected-locations": { + kind: "parsed", + brief: "Used for configuring radar_notification", + variadic: true, + optional: true, + parse: String, + }, + "filters-airport-code": { + kind: "parsed", + brief: "Used for configuring maintenance_event_notification", + variadic: true, + optional: true, + parse: String, + }, + "filters-alert-trigger-preferences": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-alert-trigger-preferences-value": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-check-id": { + kind: "parsed", + brief: "Used for configuring magic_endpoint_healthcheck_alert. Takes one or more health check IDs, each a UUID. That alert type requires check_id together with alert_trigger_preferences set to slo, a numeric alert_trigger_preferences_value, and selectors set to failures.", - }) - .option("filters-enabled", { - type: "string", - array: true, - description: "Used for configuring load_balancing_pool_enablement_alert", - }) - .option("filters-environment", { - type: "string", - array: true, - description: "Used for configuring pages_event_alert", - }) - .option("filters-event", { - type: "string", - array: true, - description: "Used for configuring pages_event_alert", - }) - .option("filters-event-source", { - type: "string", - array: true, - description: "Used for configuring load_balancing_health_alert", - }) - .option("filters-event-type", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-group-by", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-health-check-id", { - type: "string", - array: true, - description: "Used for configuring health_check_status_notification", - }) - .option("filters-incident-impact", { - type: "string", - array: true, - description: "Used for configuring incident_alert", - }) - .option("filters-input-id", { - type: "string", - array: true, - description: "Used for configuring stream_live_notifications", - }) - .option("filters-insight-class", { - type: "string", - array: true, - description: "Used for configuring security_insights_alert", - }) - .option("filters-limit", { - type: "string", - array: true, - description: "Used for configuring billing_usage_alert", - }) - .option("filters-logo-tag", { - type: "string", - array: true, - description: "Used for configuring logo_match_alert", - }) - .option("filters-megabits-per-second", { - type: "string", - array: true, - description: "Used for configuring advanced_ddos_attack_l4_alert", - }) - .option("filters-new-health", { - type: "string", - array: true, - description: "Used for configuring load_balancing_health_alert", - }) - .option("filters-new-status", { - type: "string", - array: true, - description: "Used for configuring tunnel_health_event", - }) - .option("filters-packets-per-second", { - type: "string", - array: true, - description: "Used for configuring advanced_ddos_attack_l4_alert", - }) - .option("filters-pool-id", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-pop-names", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-product", { - type: "string", - array: true, - description: "Used for configuring billing_usage_alert", - }) - .option("filters-project-id", { - type: "string", - array: true, - description: "Used for configuring pages_event_alert", - }) - .option("filters-protocol", { - type: "string", - array: true, - description: "Used for configuring advanced_ddos_attack_l4_alert", - }) - .option("filters-query-id", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + "filters-enabled": { + kind: "parsed", + brief: "Used for configuring load_balancing_pool_enablement_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-environment": { + kind: "parsed", + brief: "Used for configuring pages_event_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-event": { + kind: "parsed", + brief: "Used for configuring pages_event_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-event-source": { + kind: "parsed", + brief: "Used for configuring load_balancing_health_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-event-type": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-group-by": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-health-check-id": { + kind: "parsed", + brief: "Used for configuring health_check_status_notification", + variadic: true, + optional: true, + parse: String, + }, + "filters-incident-impact": { + kind: "parsed", + brief: "Used for configuring incident_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-input-id": { + kind: "parsed", + brief: "Used for configuring stream_live_notifications", + variadic: true, + optional: true, + parse: String, + }, + "filters-insight-class": { + kind: "parsed", + brief: "Used for configuring security_insights_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-limit": { + kind: "parsed", + brief: "Used for configuring billing_usage_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-logo-tag": { + kind: "parsed", + brief: "Used for configuring logo_match_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-megabits-per-second": { + kind: "parsed", + brief: "Used for configuring advanced_ddos_attack_l4_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-new-health": { + kind: "parsed", + brief: "Used for configuring load_balancing_health_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-new-status": { + kind: "parsed", + brief: "Used for configuring tunnel_health_event", + variadic: true, + optional: true, + parse: String, + }, + "filters-packets-per-second": { + kind: "parsed", + brief: "Used for configuring advanced_ddos_attack_l4_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-pool-id": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-pop-names": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-product": { + kind: "parsed", + brief: "Used for configuring billing_usage_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-project-id": { + kind: "parsed", + brief: "Used for configuring pages_event_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-protocol": { + kind: "parsed", + brief: "Used for configuring advanced_ddos_attack_l4_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-query-id": { + kind: "parsed", + brief: "Used for configuring stakeout_saved_query_daily_digest_alert and stakeout_saved_query_immediate_alert, which require it. Takes exactly one value, the saved query ID.", - }) - .option("filters-query-tag", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-requests-per-second", { - type: "string", - array: true, - description: "Used for configuring advanced_ddos_attack_l7_alert", - }) - .option("filters-selectors", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-services", { - type: "string", - array: true, - description: "Used for configuring clickhouse_alert_fw_ent_anomaly", - }) - .option("filters-slo", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-status", { - type: "string", - array: true, - description: "Used for configuring health_check_status_notification", - }) - .option("filters-target-hostname", { - type: "string", - array: true, - description: "Used for configuring advanced_ddos_attack_l7_alert", - }) - .option("filters-target-ip", { - type: "string", - array: true, - description: "Used for configuring advanced_ddos_attack_l4_alert", - }) - .option("filters-target-zone-name", { - type: "string", - array: true, - description: "Used for configuring advanced_ddos_attack_l7_alert", - }) - .option("filters-token-id", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + "filters-query-tag": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-requests-per-second": { + kind: "parsed", + brief: "Used for configuring advanced_ddos_attack_l7_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-selectors": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-services": { + kind: "parsed", + brief: "Used for configuring clickhouse_alert_fw_ent_anomaly", + variadic: true, + optional: true, + parse: String, + }, + "filters-slo": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-status": { + kind: "parsed", + brief: "Used for configuring health_check_status_notification", + variadic: true, + optional: true, + parse: String, + }, + "filters-target-hostname": { + kind: "parsed", + brief: "Used for configuring advanced_ddos_attack_l7_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-target-ip": { + kind: "parsed", + brief: "Used for configuring advanced_ddos_attack_l4_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-target-zone-name": { + kind: "parsed", + brief: "Used for configuring advanced_ddos_attack_l7_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-token-id": { + kind: "parsed", + brief: "Access service token IDs to include for expiring_service_token_alert. Omit this property to include all current and future service tokens.", - }) - .option("filters-total-spend-dollars", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + "filters-total-spend-dollars": { + kind: "parsed", + brief: "Used for configuring billing_budget_alert. Takes exactly one value, the budget threshold in US dollars, as a string greater than zero.", - }) - .option("filters-traffic-exclusions", { - type: "string", - array: true, - description: "Used for configuring traffic_anomalies_alert", - }) - .option("filters-tunnel-id", { - type: "string", - array: true, - description: "Used for configuring tunnel_health_event", - }) - .option("filters-tunnel-name", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-type", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-where", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-zones", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("mechanisms-email", { - type: "string", - description: + variadic: true, + optional: true, + parse: String, + }, + "filters-traffic-exclusions": { + kind: "parsed", + brief: "Used for configuring traffic_anomalies_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-tunnel-id": { + kind: "parsed", + brief: "Used for configuring tunnel_health_event", + variadic: true, + optional: true, + parse: String, + }, + "filters-tunnel-name": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-type": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-where": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-zones": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "mechanisms-email": { + kind: "parsed", + brief: 'The mechanisms.email field. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"id"?: string}]. ? marks optional keys.', - }) - .option("mechanisms-pagerduty", { - type: "string", - description: + optional: true, + parse: String, + }, + "mechanisms-pagerduty": { + kind: "parsed", + brief: 'The mechanisms.pagerduty field. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"id"?: string}]. ? marks optional keys.', - }) - .option("mechanisms-webhooks", { - type: "string", - description: + optional: true, + parse: String, + }, + "mechanisms-webhooks": { + kind: "parsed", + brief: 'The mechanisms.webhooks field. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"id"?: string}]. ? marks optional keys.', - }) - .option("name", { type: "string", description: "Name of the policy." }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + name: { + kind: "parsed", + brief: "Name of the policy.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Create a Notification policy", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting policies create", - classification: { - safeFlags: ["alert-type", "enabled", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["alert-type"] === undefined) { - argv["alert-type"] = await promptForRequiredEnumField( - "alert-type", - "Refers to which event will trigger a Notification dispatch. You can use the endpoint to get available alert types which then will give you a list of possible values. This enum lists every alert type, not the ones a given account can create, since some types depend on entitlements or account type. To get the alert types an account can create, call \`GET /accounts/{account_id}/alerting/v3/available_alerts\`.", - [ - "abuse_report_alert", - "access_custom_certificate_expiration_type", - "advanced_ddos_attack_l4_alert", - "advanced_ddos_attack_l7_alert", - "advanced_http_alert_error", - "attack_lifecycle", - "bgp_advertisement_change", - "bgp_hijack_notification", - "billing_budget_alert", - "billing_usage_alert", - "block_notification_block_removed", - "block_notification_new_block", - "block_notification_review_rejected", - "bot_traffic_basic_alert", - "brand_protection_alert", - "brand_protection_digest", - "casb_weekly_digest", - "clickhouse_alert_fw_anomaly", - "clickhouse_alert_fw_ent_anomaly", - "closed_port_scan_alert", - "cloudforce_one_request_notification", - "cmd_managed_defense_notification", - "cni_maintenance_notification", - "containers_security_alert", - "custom_analytics", - "custom_bot_detection_alert", - "custom_ssl_certificate_event_type", - "dedicated_ssl_certificate_event_type", - "device_connectivity_anomaly_alert", - "dex_device_connectivity_alert", - "dex_synthetic_test_availability_alert", - "dex_synthetic_test_latency_alert", - "dos_attack_l4", - "dos_attack_l7", - "executive_communications", - "expiring_service_token_alert", - "failing_logpush_job_disabled_alert", - "fbm_auto_advertisement", - "fbm_dosd_attack", - "fbm_volumetric_attack", - "health_check_status_notification", - "hostname_aop_custom_certificate_expiration_type", - "http_alert_edge_error", - "http_alert_origin_error", - "image_notification", - "image_resizing_notification", - "incident_alert", - "leaked_service_token_alert", - "load_balancing_health_alert", - "load_balancing_pool_enablement_alert", - "log_explorer_ingest_rate_limit", - "log_explorer_scheduled_query_results_alert", - "logo_match_alert", - "magic_endpoint_healthcheck_alert", - "magic_tunnel_health_check_event", - "magic_wan_tunnel_health", - "maintenance_event_notification", - "mtls_certificate_store_certificate_expiration_type", - "open_port_scan_alert", - "pages_event_alert", - "radar_notification", - "real_origin_monitoring", - "scriptmonitor_alert_new_code_change_detections", - "scriptmonitor_alert_new_hosts", - "scriptmonitor_alert_new_malicious_hosts", - "scriptmonitor_alert_new_malicious_scripts", - "scriptmonitor_alert_new_malicious_url", - "scriptmonitor_alert_new_max_length_resource_url", - "scriptmonitor_alert_new_resources", - "secondary_dns_all_primaries_failing", - "secondary_dns_primaries_failing", - "secondary_dns_warning", - "secondary_dns_zone_successfully_updated", - "secondary_dns_zone_validation_warning", - "security_insights_alert", - "sentinel_alert", - "stakeout_credential_leak_alert", - "stakeout_saved_query_daily_digest_alert", - "stakeout_saved_query_immediate_alert", - "stream_live_notifications", - "synthetic_test_latency_alert", - "synthetic_test_low_availability_alert", - "traffic_anomalies_alert", - "tunnel_health_event", - "tunnel_update_event", - "universal_ssl_event_type", - "web_analytics_metrics_update", - "workers_for_platforms_security_alert", - "workers_observability_alert", - "workers_observability_real_time_issue", - "zone_aop_custom_certificate_expiration_type", - ] as const - ); - } - if (argv["enabled"] === undefined) { - throw new Error( - "--enabled is required (or pass --body with this field set)." - ); - } - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "Name of the policy." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting policies create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/policies`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - alert_interval: resolveFileToken( - argv["alert-interval"] as string | undefined, - "alert-interval", - "text" - ), - alert_type: argv["alert-type"], - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - enabled: argv["enabled"], - filters: { - actions: argv["filters-actions"], - affected_asns: argv["filters-affected-asns"], - affected_components: argv["filters-affected-components"], - affected_locations: argv["filters-affected-locations"], - airport_code: argv["filters-airport-code"], - alert_trigger_preferences: - argv["filters-alert-trigger-preferences"], - alert_trigger_preferences_value: - argv["filters-alert-trigger-preferences-value"], - check_id: argv["filters-check-id"], - enabled: argv["filters-enabled"], - environment: argv["filters-environment"], - event: argv["filters-event"], - event_source: argv["filters-event-source"], - event_type: argv["filters-event-type"], - group_by: argv["filters-group-by"], - health_check_id: argv["filters-health-check-id"], - incident_impact: argv["filters-incident-impact"], - input_id: argv["filters-input-id"], - insight_class: argv["filters-insight-class"], - limit: argv["filters-limit"], - logo_tag: argv["filters-logo-tag"], - megabits_per_second: argv["filters-megabits-per-second"], - new_health: argv["filters-new-health"], - new_status: argv["filters-new-status"], - packets_per_second: argv["filters-packets-per-second"], - pool_id: argv["filters-pool-id"], - pop_names: argv["filters-pop-names"], - product: argv["filters-product"], - project_id: argv["filters-project-id"], - protocol: argv["filters-protocol"], - query_id: argv["filters-query-id"], - query_tag: argv["filters-query-tag"], - requests_per_second: argv["filters-requests-per-second"], - selectors: argv["filters-selectors"], - services: argv["filters-services"], - slo: argv["filters-slo"], - status: argv["filters-status"], - target_hostname: argv["filters-target-hostname"], - target_ip: argv["filters-target-ip"], - target_zone_name: argv["filters-target-zone-name"], - token_id: argv["filters-token-id"], - total_spend_dollars: argv["filters-total-spend-dollars"], - traffic_exclusions: argv["filters-traffic-exclusions"], - tunnel_id: argv["filters-tunnel-id"], - tunnel_name: argv["filters-tunnel-name"], - type: argv["filters-type"], - where: argv["filters-where"], - zones: argv["filters-zones"], - }, - mechanisms: { - email: parseObjectArray( - argv["mechanisms-email"], - "mechanisms-email" - ), - pagerduty: parseObjectArray( - argv["mechanisms-pagerduty"], - "mechanisms-pagerduty" - ), - webhooks: parseObjectArray( - argv["mechanisms-webhooks"], - "mechanisms-webhooks" - ), - }, - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - alert_interval: resolveFileToken( - argv["alert-interval"] as string | undefined, - "alert-interval", - "text" - ), - alert_type: argv["alert-type"], - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - enabled: argv["enabled"], - filters: { - actions: argv["filters-actions"], - affected_asns: argv["filters-affected-asns"], - affected_components: argv["filters-affected-components"], - affected_locations: argv["filters-affected-locations"], - airport_code: argv["filters-airport-code"], - alert_trigger_preferences: - argv["filters-alert-trigger-preferences"], - alert_trigger_preferences_value: - argv["filters-alert-trigger-preferences-value"], - check_id: argv["filters-check-id"], - enabled: argv["filters-enabled"], - environment: argv["filters-environment"], - event: argv["filters-event"], - event_source: argv["filters-event-source"], - event_type: argv["filters-event-type"], - group_by: argv["filters-group-by"], - health_check_id: argv["filters-health-check-id"], - incident_impact: argv["filters-incident-impact"], - input_id: argv["filters-input-id"], - insight_class: argv["filters-insight-class"], - limit: argv["filters-limit"], - logo_tag: argv["filters-logo-tag"], - megabits_per_second: argv["filters-megabits-per-second"], - new_health: argv["filters-new-health"], - new_status: argv["filters-new-status"], - packets_per_second: argv["filters-packets-per-second"], - pool_id: argv["filters-pool-id"], - pop_names: argv["filters-pop-names"], - product: argv["filters-product"], - project_id: argv["filters-project-id"], - protocol: argv["filters-protocol"], - query_id: argv["filters-query-id"], - query_tag: argv["filters-query-tag"], - requests_per_second: argv["filters-requests-per-second"], - selectors: argv["filters-selectors"], - services: argv["filters-services"], - slo: argv["filters-slo"], - status: argv["filters-status"], - target_hostname: argv["filters-target-hostname"], - target_ip: argv["filters-target-ip"], - target_zone_name: argv["filters-target-zone-name"], - token_id: argv["filters-token-id"], - total_spend_dollars: argv["filters-total-spend-dollars"], - traffic_exclusions: argv["filters-traffic-exclusions"], - tunnel_id: argv["filters-tunnel-id"], - tunnel_name: argv["filters-tunnel-name"], - type: argv["filters-type"], - where: argv["filters-where"], - zones: argv["filters-zones"], - }, - mechanisms: { - email: parseObjectArray( - argv["mechanisms-email"], - "mechanisms-email" - ), - pagerduty: parseObjectArray( - argv["mechanisms-pagerduty"], - "mechanisms-pagerduty" - ), - webhooks: parseObjectArray( - argv["mechanisms-webhooks"], - "mechanisms-webhooks" - ), - }, - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: "$0 alerting policies create\n\nCreates a new Notification policy.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/policies/delete.handler.ts b/packages/cli/src/commands/_generated/alerting/policies/delete.handler.ts new file mode 100644 index 0000000000..11ae00dc18 --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/policies/delete.handler.ts @@ -0,0 +1,60 @@ +import operation from "../../_operations/alerting/policies/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting policies delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting policies delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/policies/${argv["policy-id"] == null ? "" : encodeURIComponent(String(argv["policy-id"]))}`, + pathParams: { "policy-id": String(argv["policy-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This operation deletes the notification policy.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + policy_id: argv["policy-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/policies/delete.ts b/packages/cli/src/commands/_generated/alerting/policies/delete.ts index b8a9ab7270..557aedcfe1 100644 --- a/packages/cli/src/commands/_generated/alerting/policies/delete.ts +++ b/packages/cli/src/commands/_generated/alerting/policies/delete.ts @@ -1,96 +1,43 @@ -import operation from "../../_operations/alerting/policies/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 alerting policies delete \n\nDelete a Notification policy." - ) - .positional("policy-id", { - type: "string", - description: "The unique identifier of a notification policy", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "policy-id", + brief: "The unique identifier of a notification policy", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete a Notification policy", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting policies delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting policies delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/policies/${argv["policy-id"] == null ? "" : encodeURIComponent(String(argv["policy-id"]))}`, - pathParams: { "policy-id": String(argv["policy-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This operation deletes the notification policy.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - policy_id: argv["policy-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 alerting policies delete \n\nDelete a Notification policy.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/policies/email/details.handler.ts b/packages/cli/src/commands/_generated/alerting/policies/email/details.handler.ts new file mode 100644 index 0000000000..9b91cbfc7d --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/policies/email/details.handler.ts @@ -0,0 +1,64 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./details.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { fetchRawBytes, writeRawOutput } from "#lib/raw-fetch.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting policies email details", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + email: argv["email"], + token: argv["token"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting policies email details", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/policies/${argv["policy-id"] == null ? "" : encodeURIComponent(String(argv["policy-id"]))}/email/unsubscribe`, + pathParams: { "policy-id": String(argv["policy-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const qs = new URLSearchParams( + Object.entries(queryParams) + .filter(([, v]) => v !== undefined) + .map(([k, v]) => [k, String(v)]) + ).toString(); + const __cfRawBytes = await withProgress(`Loading`, async () => + fetchRawBytes( + `/accounts/${accountId}/alerting/v3/policies/${encodeURIComponent(String(argv["policy-id"]))}/email/unsubscribe${qs ? "?" + qs : ""}`, + { + method: "GET", + local: argv.local === true, + persistTo: argv.persistTo as string | undefined, + } + ) + ); + writeRawOutput(__cfRawBytes.toString("utf-8")); + return; + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/policies/email/details.ts b/packages/cli/src/commands/_generated/alerting/policies/email/details.ts index 95ef2e3f7c..1528b62c83 100644 --- a/packages/cli/src/commands/_generated/alerting/policies/email/details.ts +++ b/packages/cli/src/commands/_generated/alerting/policies/email/details.ts @@ -1,104 +1,39 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * details command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { fetchRawBytes, writeRawOutput } from "#lib/raw-fetch.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 alerting policies email details \n\nShows details for unsubscribing an email address from a notification policy." - ) - .positional("policy-id", { - type: "string", - description: "The unique identifier of a notification policy", - demandOption: true, - }) - .option("email", { - type: "string", - description: "Email", - demandOption: true, - }) - .option("token", { - type: "string", - description: "Token", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + email: { kind: "parsed", brief: "Email", parse: String }, + token: { kind: "parsed", brief: "Token", parse: String }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "policy-id", + brief: "The unique identifier of a notification policy", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "details ", describe: "Show email unsubscribe details", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting policies email details", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - email: argv["email"], - token: argv["token"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting policies email details", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/policies/${argv["policy-id"] == null ? "" : encodeURIComponent(String(argv["policy-id"]))}/email/unsubscribe`, - pathParams: { "policy-id": String(argv["policy-id"] ?? "") }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const qs = new URLSearchParams( - Object.entries(queryParams) - .filter(([, v]) => v !== undefined) - .map(([k, v]) => [k, String(v)]) - ).toString(); - const __cfRawBytes = await withProgress(`Loading`, async () => - fetchRawBytes( - `/accounts/${accountId}/alerting/v3/policies/${encodeURIComponent(String(argv["policy-id"]))}/email/unsubscribe${qs ? "?" + qs : ""}`, - { - method: "GET", - local: argv.local === true, - persistTo: argv.persistTo as string | undefined, - } - ) - ); - writeRawOutput(__cfRawBytes.toString("utf-8")); - return; - } - ), -}; + usage: + "$0 alerting policies email details \n\nShows details for unsubscribing an email address from a notification policy.", + ...parameters, + loader: () => import("./details.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/policies/email/index.ts b/packages/cli/src/commands/_generated/alerting/policies/email/index.ts index a87a622f2f..bd36bc0735 100644 --- a/packages/cli/src/commands/_generated/alerting/policies/email/index.ts +++ b/packages/cli/src/commands/_generated/alerting/policies/email/index.ts @@ -1,24 +1,19 @@ import $details from "./details.js"; import $unsubscribe from "./unsubscribe.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * email command group * @generated from apis/overlays/alerting.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "email", describe: "Operations for policies.email", - builder: (yargs) => { - return yargs - .command($details) - .command($unsubscribe) - .demandCommand(1, "Please specify a subcommand"); + routes: { + details: $details, + unsubscribe: $unsubscribe, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/policies/email/unsubscribe.handler.ts b/packages/cli/src/commands/_generated/alerting/policies/email/unsubscribe.handler.ts new file mode 100644 index 0000000000..2d391450cb --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/policies/email/unsubscribe.handler.ts @@ -0,0 +1,64 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./unsubscribe.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { fetchRawBytes, writeRawOutput } from "#lib/raw-fetch.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting policies email unsubscribe", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + email: argv["email"], + token: argv["token"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting policies email unsubscribe", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/policies/${argv["policy-id"] == null ? "" : encodeURIComponent(String(argv["policy-id"]))}/email/unsubscribe`, + pathParams: { "policy-id": String(argv["policy-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const qs = new URLSearchParams( + Object.entries(queryParams) + .filter(([, v]) => v !== undefined) + .map(([k, v]) => [k, String(v)]) + ).toString(); + const __cfRawBytes = await withProgress(`Creating`, async () => + fetchRawBytes( + `/accounts/${accountId}/alerting/v3/policies/${encodeURIComponent(String(argv["policy-id"]))}/email/unsubscribe${qs ? "?" + qs : ""}`, + { + method: "POST", + local: argv.local === true, + persistTo: argv.persistTo as string | undefined, + } + ) + ); + writeRawOutput(__cfRawBytes.toString("utf-8")); + return; + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/policies/email/unsubscribe.ts b/packages/cli/src/commands/_generated/alerting/policies/email/unsubscribe.ts index d8cbb163bd..0322b138fc 100644 --- a/packages/cli/src/commands/_generated/alerting/policies/email/unsubscribe.ts +++ b/packages/cli/src/commands/_generated/alerting/policies/email/unsubscribe.ts @@ -1,104 +1,39 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * unsubscribe command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { fetchRawBytes, writeRawOutput } from "#lib/raw-fetch.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 alerting policies email unsubscribe \n\nUnsubscribes an email address from a notification policy." - ) - .positional("policy-id", { - type: "string", - description: "The unique identifier of a notification policy", - demandOption: true, - }) - .option("email", { - type: "string", - description: "Email", - demandOption: true, - }) - .option("token", { - type: "string", - description: "Token", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + email: { kind: "parsed", brief: "Email", parse: String }, + token: { kind: "parsed", brief: "Token", parse: String }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "policy-id", + brief: "The unique identifier of a notification policy", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "unsubscribe ", describe: "Unsubscribe email from a Notification policy", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting policies email unsubscribe", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - email: argv["email"], - token: argv["token"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting policies email unsubscribe", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/policies/${argv["policy-id"] == null ? "" : encodeURIComponent(String(argv["policy-id"]))}/email/unsubscribe`, - pathParams: { "policy-id": String(argv["policy-id"] ?? "") }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const qs = new URLSearchParams( - Object.entries(queryParams) - .filter(([, v]) => v !== undefined) - .map(([k, v]) => [k, String(v)]) - ).toString(); - const __cfRawBytes = await withProgress(`Creating`, async () => - fetchRawBytes( - `/accounts/${accountId}/alerting/v3/policies/${encodeURIComponent(String(argv["policy-id"]))}/email/unsubscribe${qs ? "?" + qs : ""}`, - { - method: "POST", - local: argv.local === true, - persistTo: argv.persistTo as string | undefined, - } - ) - ); - writeRawOutput(__cfRawBytes.toString("utf-8")); - return; - } - ), -}; + usage: + "$0 alerting policies email unsubscribe \n\nUnsubscribes an email address from a notification policy.", + ...parameters, + loader: () => import("./unsubscribe.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/policies/get.handler.ts b/packages/cli/src/commands/_generated/alerting/policies/get.handler.ts new file mode 100644 index 0000000000..c79a56d8b3 --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/policies/get.handler.ts @@ -0,0 +1,49 @@ +import operation from "../../_operations/alerting/policies/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting policies get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting policies get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/policies/${argv["policy-id"] == null ? "" : encodeURIComponent(String(argv["policy-id"]))}`, + pathParams: { "policy-id": String(argv["policy-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + policy_id: argv["policy-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/policies/get.ts b/packages/cli/src/commands/_generated/alerting/policies/get.ts index fa43db2077..970ce109e6 100644 --- a/packages/cli/src/commands/_generated/alerting/policies/get.ts +++ b/packages/cli/src/commands/_generated/alerting/policies/get.ts @@ -1,79 +1,37 @@ -import operation from "../../_operations/alerting/policies/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 alerting policies get \n\nGet details for a single policy." - ) - .positional("policy-id", { - type: "string", - description: "The unique identifier of a notification policy", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "policy-id", + brief: "The unique identifier of a notification policy", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get a Notification policy", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting policies get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting policies get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/policies/${argv["policy-id"] == null ? "" : encodeURIComponent(String(argv["policy-id"]))}`, - pathParams: { "policy-id": String(argv["policy-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - policy_id: argv["policy-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 alerting policies get \n\nGet details for a single policy.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/policies/index.ts b/packages/cli/src/commands/_generated/alerting/policies/index.ts index 36ef0a527f..7de51d0614 100644 --- a/packages/cli/src/commands/_generated/alerting/policies/index.ts +++ b/packages/cli/src/commands/_generated/alerting/policies/index.ts @@ -5,30 +5,25 @@ import $get from "./get.js"; import $list from "./list.js"; import $test from "./test.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * policies command group * @generated from apis/overlays/alerting.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "policies", describe: "Operations for policies", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .command($list) - .command($test) - .command($update) - .command($email) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, + list: $list, + test: $test, + update: $update, + email: $email, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/policies/list.handler.ts b/packages/cli/src/commands/_generated/alerting/policies/list.handler.ts new file mode 100644 index 0000000000..437e6f3bff --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/policies/list.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/alerting/policies/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting policies list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting policies list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/policies`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/policies/list.ts b/packages/cli/src/commands/_generated/alerting/policies/list.ts index 91310ef965..665b0c63ba 100644 --- a/packages/cli/src/commands/_generated/alerting/policies/list.ts +++ b/packages/cli/src/commands/_generated/alerting/policies/list.ts @@ -1,71 +1,31 @@ -import operation from "../../_operations/alerting/policies/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 alerting policies list\n\nGet a list of all Notification policies." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Notification policies", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting policies list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting policies list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/policies`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 alerting policies list\n\nGet a list of all Notification policies.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/policies/test.handler.ts b/packages/cli/src/commands/_generated/alerting/policies/test.handler.ts new file mode 100644 index 0000000000..0c1ab7a4a7 --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/policies/test.handler.ts @@ -0,0 +1,99 @@ +import operation from "../../_operations/alerting/policies/test.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./test.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting policies test", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting policies test", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/policies/${argv["policy-id"] == null ? "" : encodeURIComponent(String(argv["policy-id"]))}/test`, + pathParams: { "policy-id": String(argv["policy-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + severity: argv["severity"], + source: resolveFileToken( + argv["source"] as string | undefined, + "source", + "text" + ), + state_correlation_id: resolveFileToken( + argv["state-correlation-id"] as string | undefined, + "state-correlation-id", + "text" + ), + state_event: argv["state-event"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + policy_id: argv["policy-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + severity: argv["severity"], + source: resolveFileToken( + argv["source"] as string | undefined, + "source", + "text" + ), + state_correlation_id: resolveFileToken( + argv["state-correlation-id"] as string | undefined, + "state-correlation-id", + "text" + ), + state_event: argv["state-event"], + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + policy_id: argv["policy-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/policies/test.ts b/packages/cli/src/commands/_generated/alerting/policies/test.ts index e8421a9d3c..fd96eb2be9 100644 --- a/packages/cli/src/commands/_generated/alerting/policies/test.ts +++ b/packages/cli/src/commands/_generated/alerting/policies/test.ts @@ -1,153 +1,71 @@ -import operation from "../../_operations/alerting/policies/test.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * test command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 alerting policies test \n\nSend a test notification for a policy to verify delivery mechanisms are working as expected." - ) - .positional("policy-id", { - type: "string", - description: "The unique identifier of a notification policy", - demandOption: true, - }) - .option("severity", { - type: "number", - description: +const parameters = { + flags: { + severity: { + kind: "parsed", + brief: "Severity level for the test alert. Defaults to INFO (1) if omitted.", - }) - .option("source", { - type: "string", - description: "Source identifier for the test alert.", - }) - .option("state-correlation-id", { - type: "string", - description: + optional: true, + parse: Number, + }, + source: { + kind: "parsed", + brief: "Source identifier for the test alert.", + optional: true, + parse: String, + }, + "state-correlation-id": { + kind: "parsed", + brief: "Correlation ID for stateful test alerts. Required when state_event is set.", - }) - .option("state-event", { - type: "number", - description: + optional: true, + parse: String, + }, + "state-event": { + kind: "parsed", + brief: "State event type for stateful test alerts. Use with state_correlation_id.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: + }, + body: { + kind: "parsed", + brief: "Optional configuration for the test notification. When omitted, a default INFO-severity test alert is sent.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "policy-id", + brief: "The unique identifier of a notification policy", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "test ", describe: "Test a Notification policy", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting policies test", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting policies test", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/policies/${argv["policy-id"] == null ? "" : encodeURIComponent(String(argv["policy-id"]))}/test`, - pathParams: { "policy-id": String(argv["policy-id"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - severity: argv["severity"], - source: resolveFileToken( - argv["source"] as string | undefined, - "source", - "text" - ), - state_correlation_id: resolveFileToken( - argv["state-correlation-id"] as string | undefined, - "state-correlation-id", - "text" - ), - state_event: argv["state-event"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - policy_id: argv["policy-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - severity: argv["severity"], - source: resolveFileToken( - argv["source"] as string | undefined, - "source", - "text" - ), - state_correlation_id: resolveFileToken( - argv["state-correlation-id"] as string | undefined, - "state-correlation-id", - "text" - ), - state_event: argv["state-event"], - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - policy_id: argv["policy-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 alerting policies test \n\nSend a test notification for a policy to verify delivery mechanisms are working as expected.", + ...parameters, + loader: () => import("./test.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/policies/update.handler.ts b/packages/cli/src/commands/_generated/alerting/policies/update.handler.ts new file mode 100644 index 0000000000..26e890cc04 --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/policies/update.handler.ts @@ -0,0 +1,235 @@ +import operation from "../../_operations/alerting/policies/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting policies update", + classification: { + safeFlags: ["alert-type", "enabled", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting policies update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/policies/${argv["policy-id"] == null ? "" : encodeURIComponent(String(argv["policy-id"]))}`, + pathParams: { "policy-id": String(argv["policy-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + alert_interval: resolveFileToken( + argv["alert-interval"] as string | undefined, + "alert-interval", + "text" + ), + alert_type: argv["alert-type"], + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + enabled: argv["enabled"], + filters: { + actions: argv["filters-actions"], + affected_asns: argv["filters-affected-asns"], + affected_components: argv["filters-affected-components"], + affected_locations: argv["filters-affected-locations"], + airport_code: argv["filters-airport-code"], + alert_trigger_preferences: + argv["filters-alert-trigger-preferences"], + alert_trigger_preferences_value: + argv["filters-alert-trigger-preferences-value"], + check_id: argv["filters-check-id"], + enabled: argv["filters-enabled"], + environment: argv["filters-environment"], + event: argv["filters-event"], + event_source: argv["filters-event-source"], + event_type: argv["filters-event-type"], + group_by: argv["filters-group-by"], + health_check_id: argv["filters-health-check-id"], + incident_impact: argv["filters-incident-impact"], + input_id: argv["filters-input-id"], + insight_class: argv["filters-insight-class"], + limit: argv["filters-limit"], + logo_tag: argv["filters-logo-tag"], + megabits_per_second: argv["filters-megabits-per-second"], + new_health: argv["filters-new-health"], + new_status: argv["filters-new-status"], + packets_per_second: argv["filters-packets-per-second"], + pool_id: argv["filters-pool-id"], + pop_names: argv["filters-pop-names"], + product: argv["filters-product"], + project_id: argv["filters-project-id"], + protocol: argv["filters-protocol"], + query_id: argv["filters-query-id"], + query_tag: argv["filters-query-tag"], + requests_per_second: argv["filters-requests-per-second"], + selectors: argv["filters-selectors"], + services: argv["filters-services"], + slo: argv["filters-slo"], + status: argv["filters-status"], + target_hostname: argv["filters-target-hostname"], + target_ip: argv["filters-target-ip"], + target_zone_name: argv["filters-target-zone-name"], + token_id: argv["filters-token-id"], + total_spend_dollars: argv["filters-total-spend-dollars"], + traffic_exclusions: argv["filters-traffic-exclusions"], + tunnel_id: argv["filters-tunnel-id"], + tunnel_name: argv["filters-tunnel-name"], + type: argv["filters-type"], + where: argv["filters-where"], + zones: argv["filters-zones"], + }, + mechanisms: { + email: parseObjectArray( + argv["mechanisms-email"], + "mechanisms-email" + ), + pagerduty: parseObjectArray( + argv["mechanisms-pagerduty"], + "mechanisms-pagerduty" + ), + webhooks: parseObjectArray( + argv["mechanisms-webhooks"], + "mechanisms-webhooks" + ), + }, + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + policy_id: argv["policy-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + alert_interval: resolveFileToken( + argv["alert-interval"] as string | undefined, + "alert-interval", + "text" + ), + alert_type: argv["alert-type"], + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + enabled: argv["enabled"], + filters: { + actions: argv["filters-actions"], + affected_asns: argv["filters-affected-asns"], + affected_components: argv["filters-affected-components"], + affected_locations: argv["filters-affected-locations"], + airport_code: argv["filters-airport-code"], + alert_trigger_preferences: argv["filters-alert-trigger-preferences"], + alert_trigger_preferences_value: + argv["filters-alert-trigger-preferences-value"], + check_id: argv["filters-check-id"], + enabled: argv["filters-enabled"], + environment: argv["filters-environment"], + event: argv["filters-event"], + event_source: argv["filters-event-source"], + event_type: argv["filters-event-type"], + group_by: argv["filters-group-by"], + health_check_id: argv["filters-health-check-id"], + incident_impact: argv["filters-incident-impact"], + input_id: argv["filters-input-id"], + insight_class: argv["filters-insight-class"], + limit: argv["filters-limit"], + logo_tag: argv["filters-logo-tag"], + megabits_per_second: argv["filters-megabits-per-second"], + new_health: argv["filters-new-health"], + new_status: argv["filters-new-status"], + packets_per_second: argv["filters-packets-per-second"], + pool_id: argv["filters-pool-id"], + pop_names: argv["filters-pop-names"], + product: argv["filters-product"], + project_id: argv["filters-project-id"], + protocol: argv["filters-protocol"], + query_id: argv["filters-query-id"], + query_tag: argv["filters-query-tag"], + requests_per_second: argv["filters-requests-per-second"], + selectors: argv["filters-selectors"], + services: argv["filters-services"], + slo: argv["filters-slo"], + status: argv["filters-status"], + target_hostname: argv["filters-target-hostname"], + target_ip: argv["filters-target-ip"], + target_zone_name: argv["filters-target-zone-name"], + token_id: argv["filters-token-id"], + total_spend_dollars: argv["filters-total-spend-dollars"], + traffic_exclusions: argv["filters-traffic-exclusions"], + tunnel_id: argv["filters-tunnel-id"], + tunnel_name: argv["filters-tunnel-name"], + type: argv["filters-type"], + where: argv["filters-where"], + zones: argv["filters-zones"], + }, + mechanisms: { + email: parseObjectArray(argv["mechanisms-email"], "mechanisms-email"), + pagerduty: parseObjectArray( + argv["mechanisms-pagerduty"], + "mechanisms-pagerduty" + ), + webhooks: parseObjectArray( + argv["mechanisms-webhooks"], + "mechanisms-webhooks" + ), + }, + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + policy_id: argv["policy-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/policies/update.ts b/packages/cli/src/commands/_generated/alerting/policies/update.ts index eb3bce6357..53b2c7326e 100644 --- a/packages/cli/src/commands/_generated/alerting/policies/update.ts +++ b/packages/cli/src/commands/_generated/alerting/policies/update.ts @@ -1,43 +1,28 @@ -import operation from "../../_operations/alerting/policies/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 alerting policies update \n\nUpdate a Notification policy." - ) - .positional("policy-id", { - type: "string", - description: "The unique identifier of a notification policy", - demandOption: true, - }) - .option("alert-interval", { - type: "string", - description: +const parameters = { + flags: { + "alert-interval": { + kind: "parsed", + brief: "Optional specification of how often to re-alert from the same incident, not support on all alert types.", - }) - .option("alert-type", { - type: "string", - description: + optional: true, + parse: String, + }, + "alert-type": { + kind: "parsed", + brief: "Refers to which event will trigger a Notification dispatch. You can use the endpoint to get available alert types which then will give you a list of possible values. This enum lists every alert type, not the ones a given account can create, since some types depend on entitlements or account type. To get the alert types an account can create, call `GET /accounts/{account_id}/alerting/v3/available_alerts`.", + optional: true, choices: [ "abuse_report_alert", "access_custom_certificate_expiration_type", @@ -131,512 +116,408 @@ function builder(yargs: Argv) { "workers_observability_real_time_issue", "zone_aop_custom_certificate_expiration_type", ], - }) - .coerce("alert-type", (value) => - resolveFileToken(value, "alert-type", "text") - ) - .option("description", { - type: "string", - description: "Optional description for the Notification policy.", - }) - .option("enabled", { - type: "boolean", - description: "Whether or not the Notification policy is enabled.", - }) - .option("filters-actions", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-affected-asns", { - type: "string", - array: true, - description: "Used for configuring radar_notification", - }) - .option("filters-affected-components", { - type: "string", - array: true, - description: "Used for configuring incident_alert", - }) - .option("filters-affected-locations", { - type: "string", - array: true, - description: "Used for configuring radar_notification", - }) - .option("filters-airport-code", { - type: "string", - array: true, - description: "Used for configuring maintenance_event_notification", - }) - .option("filters-alert-trigger-preferences", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-alert-trigger-preferences-value", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-check-id", { - type: "string", - array: true, - description: + parse: String, + coerce: (value: string) => resolveFileToken(value, "alert-type", "text"), + }, + description: { + kind: "parsed", + brief: "Optional description for the Notification policy.", + optional: true, + parse: String, + }, + enabled: { + kind: "boolean", + brief: "Whether or not the Notification policy is enabled.", + optional: true, + }, + "filters-actions": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-affected-asns": { + kind: "parsed", + brief: "Used for configuring radar_notification", + variadic: true, + optional: true, + parse: String, + }, + "filters-affected-components": { + kind: "parsed", + brief: "Used for configuring incident_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-affected-locations": { + kind: "parsed", + brief: "Used for configuring radar_notification", + variadic: true, + optional: true, + parse: String, + }, + "filters-airport-code": { + kind: "parsed", + brief: "Used for configuring maintenance_event_notification", + variadic: true, + optional: true, + parse: String, + }, + "filters-alert-trigger-preferences": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-alert-trigger-preferences-value": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-check-id": { + kind: "parsed", + brief: "Used for configuring magic_endpoint_healthcheck_alert. Takes one or more health check IDs, each a UUID. That alert type requires check_id together with alert_trigger_preferences set to slo, a numeric alert_trigger_preferences_value, and selectors set to failures.", - }) - .option("filters-enabled", { - type: "string", - array: true, - description: "Used for configuring load_balancing_pool_enablement_alert", - }) - .option("filters-environment", { - type: "string", - array: true, - description: "Used for configuring pages_event_alert", - }) - .option("filters-event", { - type: "string", - array: true, - description: "Used for configuring pages_event_alert", - }) - .option("filters-event-source", { - type: "string", - array: true, - description: "Used for configuring load_balancing_health_alert", - }) - .option("filters-event-type", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-group-by", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-health-check-id", { - type: "string", - array: true, - description: "Used for configuring health_check_status_notification", - }) - .option("filters-incident-impact", { - type: "string", - array: true, - description: "Used for configuring incident_alert", - }) - .option("filters-input-id", { - type: "string", - array: true, - description: "Used for configuring stream_live_notifications", - }) - .option("filters-insight-class", { - type: "string", - array: true, - description: "Used for configuring security_insights_alert", - }) - .option("filters-limit", { - type: "string", - array: true, - description: "Used for configuring billing_usage_alert", - }) - .option("filters-logo-tag", { - type: "string", - array: true, - description: "Used for configuring logo_match_alert", - }) - .option("filters-megabits-per-second", { - type: "string", - array: true, - description: "Used for configuring advanced_ddos_attack_l4_alert", - }) - .option("filters-new-health", { - type: "string", - array: true, - description: "Used for configuring load_balancing_health_alert", - }) - .option("filters-new-status", { - type: "string", - array: true, - description: "Used for configuring tunnel_health_event", - }) - .option("filters-packets-per-second", { - type: "string", - array: true, - description: "Used for configuring advanced_ddos_attack_l4_alert", - }) - .option("filters-pool-id", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-pop-names", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-product", { - type: "string", - array: true, - description: "Used for configuring billing_usage_alert", - }) - .option("filters-project-id", { - type: "string", - array: true, - description: "Used for configuring pages_event_alert", - }) - .option("filters-protocol", { - type: "string", - array: true, - description: "Used for configuring advanced_ddos_attack_l4_alert", - }) - .option("filters-query-id", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + "filters-enabled": { + kind: "parsed", + brief: "Used for configuring load_balancing_pool_enablement_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-environment": { + kind: "parsed", + brief: "Used for configuring pages_event_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-event": { + kind: "parsed", + brief: "Used for configuring pages_event_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-event-source": { + kind: "parsed", + brief: "Used for configuring load_balancing_health_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-event-type": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-group-by": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-health-check-id": { + kind: "parsed", + brief: "Used for configuring health_check_status_notification", + variadic: true, + optional: true, + parse: String, + }, + "filters-incident-impact": { + kind: "parsed", + brief: "Used for configuring incident_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-input-id": { + kind: "parsed", + brief: "Used for configuring stream_live_notifications", + variadic: true, + optional: true, + parse: String, + }, + "filters-insight-class": { + kind: "parsed", + brief: "Used for configuring security_insights_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-limit": { + kind: "parsed", + brief: "Used for configuring billing_usage_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-logo-tag": { + kind: "parsed", + brief: "Used for configuring logo_match_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-megabits-per-second": { + kind: "parsed", + brief: "Used for configuring advanced_ddos_attack_l4_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-new-health": { + kind: "parsed", + brief: "Used for configuring load_balancing_health_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-new-status": { + kind: "parsed", + brief: "Used for configuring tunnel_health_event", + variadic: true, + optional: true, + parse: String, + }, + "filters-packets-per-second": { + kind: "parsed", + brief: "Used for configuring advanced_ddos_attack_l4_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-pool-id": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-pop-names": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-product": { + kind: "parsed", + brief: "Used for configuring billing_usage_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-project-id": { + kind: "parsed", + brief: "Used for configuring pages_event_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-protocol": { + kind: "parsed", + brief: "Used for configuring advanced_ddos_attack_l4_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-query-id": { + kind: "parsed", + brief: "Used for configuring stakeout_saved_query_daily_digest_alert and stakeout_saved_query_immediate_alert, which require it. Takes exactly one value, the saved query ID.", - }) - .option("filters-query-tag", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-requests-per-second", { - type: "string", - array: true, - description: "Used for configuring advanced_ddos_attack_l7_alert", - }) - .option("filters-selectors", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-services", { - type: "string", - array: true, - description: "Used for configuring clickhouse_alert_fw_ent_anomaly", - }) - .option("filters-slo", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-status", { - type: "string", - array: true, - description: "Used for configuring health_check_status_notification", - }) - .option("filters-target-hostname", { - type: "string", - array: true, - description: "Used for configuring advanced_ddos_attack_l7_alert", - }) - .option("filters-target-ip", { - type: "string", - array: true, - description: "Used for configuring advanced_ddos_attack_l4_alert", - }) - .option("filters-target-zone-name", { - type: "string", - array: true, - description: "Used for configuring advanced_ddos_attack_l7_alert", - }) - .option("filters-token-id", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + "filters-query-tag": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-requests-per-second": { + kind: "parsed", + brief: "Used for configuring advanced_ddos_attack_l7_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-selectors": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-services": { + kind: "parsed", + brief: "Used for configuring clickhouse_alert_fw_ent_anomaly", + variadic: true, + optional: true, + parse: String, + }, + "filters-slo": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-status": { + kind: "parsed", + brief: "Used for configuring health_check_status_notification", + variadic: true, + optional: true, + parse: String, + }, + "filters-target-hostname": { + kind: "parsed", + brief: "Used for configuring advanced_ddos_attack_l7_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-target-ip": { + kind: "parsed", + brief: "Used for configuring advanced_ddos_attack_l4_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-target-zone-name": { + kind: "parsed", + brief: "Used for configuring advanced_ddos_attack_l7_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-token-id": { + kind: "parsed", + brief: "Access service token IDs to include for expiring_service_token_alert. Omit this property to include all current and future service tokens.", - }) - .option("filters-total-spend-dollars", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + "filters-total-spend-dollars": { + kind: "parsed", + brief: "Used for configuring billing_budget_alert. Takes exactly one value, the budget threshold in US dollars, as a string greater than zero.", - }) - .option("filters-traffic-exclusions", { - type: "string", - array: true, - description: "Used for configuring traffic_anomalies_alert", - }) - .option("filters-tunnel-id", { - type: "string", - array: true, - description: "Used for configuring tunnel_health_event", - }) - .option("filters-tunnel-name", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-type", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-where", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("filters-zones", { - type: "string", - array: true, - description: "Usage depends on specific alert type", - }) - .option("mechanisms-email", { - type: "string", - description: + variadic: true, + optional: true, + parse: String, + }, + "filters-traffic-exclusions": { + kind: "parsed", + brief: "Used for configuring traffic_anomalies_alert", + variadic: true, + optional: true, + parse: String, + }, + "filters-tunnel-id": { + kind: "parsed", + brief: "Used for configuring tunnel_health_event", + variadic: true, + optional: true, + parse: String, + }, + "filters-tunnel-name": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-type": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-where": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "filters-zones": { + kind: "parsed", + brief: "Usage depends on specific alert type", + variadic: true, + optional: true, + parse: String, + }, + "mechanisms-email": { + kind: "parsed", + brief: 'The mechanisms.email field. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"id"?: string}]. ? marks optional keys.', - }) - .option("mechanisms-pagerduty", { - type: "string", - description: + optional: true, + parse: String, + }, + "mechanisms-pagerduty": { + kind: "parsed", + brief: 'The mechanisms.pagerduty field. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"id"?: string}]. ? marks optional keys.', - }) - .option("mechanisms-webhooks", { - type: "string", - description: + optional: true, + parse: String, + }, + "mechanisms-webhooks": { + kind: "parsed", + brief: 'The mechanisms.webhooks field. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"id"?: string}]. ? marks optional keys.', - }) - .option("name", { type: "string", description: "Name of the policy." }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + name: { + kind: "parsed", + brief: "Name of the policy.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "policy-id", + brief: "The unique identifier of a notification policy", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update ", describe: "Update a Notification policy", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting policies update", - classification: { - safeFlags: ["alert-type", "enabled", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting policies update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/policies/${argv["policy-id"] == null ? "" : encodeURIComponent(String(argv["policy-id"]))}`, - pathParams: { "policy-id": String(argv["policy-id"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - alert_interval: resolveFileToken( - argv["alert-interval"] as string | undefined, - "alert-interval", - "text" - ), - alert_type: argv["alert-type"], - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - enabled: argv["enabled"], - filters: { - actions: argv["filters-actions"], - affected_asns: argv["filters-affected-asns"], - affected_components: argv["filters-affected-components"], - affected_locations: argv["filters-affected-locations"], - airport_code: argv["filters-airport-code"], - alert_trigger_preferences: - argv["filters-alert-trigger-preferences"], - alert_trigger_preferences_value: - argv["filters-alert-trigger-preferences-value"], - check_id: argv["filters-check-id"], - enabled: argv["filters-enabled"], - environment: argv["filters-environment"], - event: argv["filters-event"], - event_source: argv["filters-event-source"], - event_type: argv["filters-event-type"], - group_by: argv["filters-group-by"], - health_check_id: argv["filters-health-check-id"], - incident_impact: argv["filters-incident-impact"], - input_id: argv["filters-input-id"], - insight_class: argv["filters-insight-class"], - limit: argv["filters-limit"], - logo_tag: argv["filters-logo-tag"], - megabits_per_second: argv["filters-megabits-per-second"], - new_health: argv["filters-new-health"], - new_status: argv["filters-new-status"], - packets_per_second: argv["filters-packets-per-second"], - pool_id: argv["filters-pool-id"], - pop_names: argv["filters-pop-names"], - product: argv["filters-product"], - project_id: argv["filters-project-id"], - protocol: argv["filters-protocol"], - query_id: argv["filters-query-id"], - query_tag: argv["filters-query-tag"], - requests_per_second: argv["filters-requests-per-second"], - selectors: argv["filters-selectors"], - services: argv["filters-services"], - slo: argv["filters-slo"], - status: argv["filters-status"], - target_hostname: argv["filters-target-hostname"], - target_ip: argv["filters-target-ip"], - target_zone_name: argv["filters-target-zone-name"], - token_id: argv["filters-token-id"], - total_spend_dollars: argv["filters-total-spend-dollars"], - traffic_exclusions: argv["filters-traffic-exclusions"], - tunnel_id: argv["filters-tunnel-id"], - tunnel_name: argv["filters-tunnel-name"], - type: argv["filters-type"], - where: argv["filters-where"], - zones: argv["filters-zones"], - }, - mechanisms: { - email: parseObjectArray( - argv["mechanisms-email"], - "mechanisms-email" - ), - pagerduty: parseObjectArray( - argv["mechanisms-pagerduty"], - "mechanisms-pagerduty" - ), - webhooks: parseObjectArray( - argv["mechanisms-webhooks"], - "mechanisms-webhooks" - ), - }, - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - policy_id: argv["policy-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - alert_interval: resolveFileToken( - argv["alert-interval"] as string | undefined, - "alert-interval", - "text" - ), - alert_type: argv["alert-type"], - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - enabled: argv["enabled"], - filters: { - actions: argv["filters-actions"], - affected_asns: argv["filters-affected-asns"], - affected_components: argv["filters-affected-components"], - affected_locations: argv["filters-affected-locations"], - airport_code: argv["filters-airport-code"], - alert_trigger_preferences: - argv["filters-alert-trigger-preferences"], - alert_trigger_preferences_value: - argv["filters-alert-trigger-preferences-value"], - check_id: argv["filters-check-id"], - enabled: argv["filters-enabled"], - environment: argv["filters-environment"], - event: argv["filters-event"], - event_source: argv["filters-event-source"], - event_type: argv["filters-event-type"], - group_by: argv["filters-group-by"], - health_check_id: argv["filters-health-check-id"], - incident_impact: argv["filters-incident-impact"], - input_id: argv["filters-input-id"], - insight_class: argv["filters-insight-class"], - limit: argv["filters-limit"], - logo_tag: argv["filters-logo-tag"], - megabits_per_second: argv["filters-megabits-per-second"], - new_health: argv["filters-new-health"], - new_status: argv["filters-new-status"], - packets_per_second: argv["filters-packets-per-second"], - pool_id: argv["filters-pool-id"], - pop_names: argv["filters-pop-names"], - product: argv["filters-product"], - project_id: argv["filters-project-id"], - protocol: argv["filters-protocol"], - query_id: argv["filters-query-id"], - query_tag: argv["filters-query-tag"], - requests_per_second: argv["filters-requests-per-second"], - selectors: argv["filters-selectors"], - services: argv["filters-services"], - slo: argv["filters-slo"], - status: argv["filters-status"], - target_hostname: argv["filters-target-hostname"], - target_ip: argv["filters-target-ip"], - target_zone_name: argv["filters-target-zone-name"], - token_id: argv["filters-token-id"], - total_spend_dollars: argv["filters-total-spend-dollars"], - traffic_exclusions: argv["filters-traffic-exclusions"], - tunnel_id: argv["filters-tunnel-id"], - tunnel_name: argv["filters-tunnel-name"], - type: argv["filters-type"], - where: argv["filters-where"], - zones: argv["filters-zones"], - }, - mechanisms: { - email: parseObjectArray( - argv["mechanisms-email"], - "mechanisms-email" - ), - pagerduty: parseObjectArray( - argv["mechanisms-pagerduty"], - "mechanisms-pagerduty" - ), - webhooks: parseObjectArray( - argv["mechanisms-webhooks"], - "mechanisms-webhooks" - ), - }, - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - policy_id: argv["policy-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 alerting policies update \n\nUpdate a Notification policy.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/silences/create.handler.ts b/packages/cli/src/commands/_generated/alerting/silences/create.handler.ts new file mode 100644 index 0000000000..8847cdab50 --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/silences/create.handler.ts @@ -0,0 +1,59 @@ +import operation from "../../_operations/alerting/silences/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting silences create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.body === undefined) { + throw new Error( + "--body is required for this command. Pass --body '' or --body @path/to/file.json." + ); + } + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting silences create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/silences`, + pathParams: {}, + bodyKind: "json", + body: argv.body !== undefined ? parseBody(argv.body) : undefined, + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/silences/create.ts b/packages/cli/src/commands/_generated/alerting/silences/create.ts index 3700ce04b1..81fc44abd4 100644 --- a/packages/cli/src/commands/_generated/alerting/silences/create.ts +++ b/packages/cli/src/commands/_generated/alerting/silences/create.ts @@ -1,88 +1,36 @@ -import operation from "../../_operations/alerting/silences/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 alerting silences create\n\nCreates a new silence for an account." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Create Silences", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting silences create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.body === undefined) { - throw new Error( - "--body is required for this command. Pass --body '' or --body @path/to/file.json." - ); - } - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting silences create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/silences`, - pathParams: {}, - bodyKind: "json", - body: argv.body !== undefined ? parseBody(argv.body) : undefined, - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - } - ), -}; + usage: "$0 alerting silences create\n\nCreates a new silence for an account.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/silences/delete.handler.ts b/packages/cli/src/commands/_generated/alerting/silences/delete.handler.ts new file mode 100644 index 0000000000..26d44d0c03 --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/silences/delete.handler.ts @@ -0,0 +1,60 @@ +import operation from "../../_operations/alerting/silences/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting silences delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting silences delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/silences/${argv["silence-id"] == null ? "" : encodeURIComponent(String(argv["silence-id"]))}`, + pathParams: { "silence-id": String(argv["silence-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This operation deletes the notification silence.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + silence_id: argv["silence-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/silences/delete.ts b/packages/cli/src/commands/_generated/alerting/silences/delete.ts index 25df67f3cc..644fb2b946 100644 --- a/packages/cli/src/commands/_generated/alerting/silences/delete.ts +++ b/packages/cli/src/commands/_generated/alerting/silences/delete.ts @@ -1,96 +1,37 @@ -import operation from "../../_operations/alerting/silences/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 alerting silences delete \n\nDeletes an existing silence for an account." - ) - .positional("silence-id", { - type: "string", - description: "Silence ID", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "silence-id", brief: "Silence ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete Silence", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting silences delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting silences delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/silences/${argv["silence-id"] == null ? "" : encodeURIComponent(String(argv["silence-id"]))}`, - pathParams: { "silence-id": String(argv["silence-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This operation deletes the notification silence.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - silence_id: argv["silence-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 alerting silences delete \n\nDeletes an existing silence for an account.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/silences/get.handler.ts b/packages/cli/src/commands/_generated/alerting/silences/get.handler.ts new file mode 100644 index 0000000000..7361d230c2 --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/silences/get.handler.ts @@ -0,0 +1,49 @@ +import operation from "../../_operations/alerting/silences/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting silences get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting silences get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/silences/${argv["silence-id"] == null ? "" : encodeURIComponent(String(argv["silence-id"]))}`, + pathParams: { "silence-id": String(argv["silence-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + silence_id: argv["silence-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/silences/get.ts b/packages/cli/src/commands/_generated/alerting/silences/get.ts index c5cd1ecfef..30ceffa3a6 100644 --- a/packages/cli/src/commands/_generated/alerting/silences/get.ts +++ b/packages/cli/src/commands/_generated/alerting/silences/get.ts @@ -1,79 +1,31 @@ -import operation from "../../_operations/alerting/silences/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 alerting silences get \n\nGets a specific silence for an account." - ) - .positional("silence-id", { - type: "string", - description: "Silence ID", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "silence-id", brief: "Silence ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get Silence", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting silences get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting silences get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/silences/${argv["silence-id"] == null ? "" : encodeURIComponent(String(argv["silence-id"]))}`, - pathParams: { "silence-id": String(argv["silence-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - silence_id: argv["silence-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 alerting silences get \n\nGets a specific silence for an account.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/silences/index.ts b/packages/cli/src/commands/_generated/alerting/silences/index.ts index 9d1be5e117..8099856057 100644 --- a/packages/cli/src/commands/_generated/alerting/silences/index.ts +++ b/packages/cli/src/commands/_generated/alerting/silences/index.ts @@ -3,28 +3,23 @@ import $delete from "./delete.js"; import $get from "./get.js"; import $list from "./list.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * silences command group * @generated from apis/overlays/alerting.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "silences", describe: "Operations for silences", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .command($list) - .command($update) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, + list: $list, + update: $update, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/silences/list.handler.ts b/packages/cli/src/commands/_generated/alerting/silences/list.handler.ts new file mode 100644 index 0000000000..793386d2a9 --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/silences/list.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/alerting/silences/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting silences list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting silences list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/silences`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/silences/list.ts b/packages/cli/src/commands/_generated/alerting/silences/list.ts index 35332e1a17..d2d075ee14 100644 --- a/packages/cli/src/commands/_generated/alerting/silences/list.ts +++ b/packages/cli/src/commands/_generated/alerting/silences/list.ts @@ -1,71 +1,30 @@ -import operation from "../../_operations/alerting/silences/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 alerting silences list\n\nGets a list of silences for an account." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Silences", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting silences list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting silences list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/silences`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: "$0 alerting silences list\n\nGets a list of silences for an account.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/alerting/silences/update.handler.ts b/packages/cli/src/commands/_generated/alerting/silences/update.handler.ts new file mode 100644 index 0000000000..f41f2eb940 --- /dev/null +++ b/packages/cli/src/commands/_generated/alerting/silences/update.handler.ts @@ -0,0 +1,59 @@ +import operation from "../../_operations/alerting/silences/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "alerting silences update", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.body === undefined) { + throw new Error( + "--body is required for this command. Pass --body '' or --body @path/to/file.json." + ); + } + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf alerting silences update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/silences`, + pathParams: {}, + bodyKind: "json", + body: argv.body !== undefined ? parseBody(argv.body) : undefined, + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + } + ); +} diff --git a/packages/cli/src/commands/_generated/alerting/silences/update.ts b/packages/cli/src/commands/_generated/alerting/silences/update.ts index 21bea454ae..15ed266f42 100644 --- a/packages/cli/src/commands/_generated/alerting/silences/update.ts +++ b/packages/cli/src/commands/_generated/alerting/silences/update.ts @@ -1,88 +1,37 @@ -import operation from "../../_operations/alerting/silences/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/alerting.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 alerting silences update\n\nUpdates existing silences for an account." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update", describe: "Update Silences", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "alerting silences update", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.body === undefined) { - throw new Error( - "--body is required for this command. Pass --body '' or --body @path/to/file.json." - ); - } - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf alerting silences update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/alerting/v3/silences`, - pathParams: {}, - bodyKind: "json", - body: argv.body !== undefined ? parseBody(argv.body) : undefined, - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - } - ), -}; + usage: + "$0 alerting silences update\n\nUpdates existing silences for an account.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/analytics-engine/index.ts b/packages/cli/src/commands/_generated/analytics-engine/index.ts index 4623e17e63..44a1ac2246 100644 --- a/packages/cli/src/commands/_generated/analytics-engine/index.ts +++ b/packages/cli/src/commands/_generated/analytics-engine/index.ts @@ -1,20 +1,17 @@ import $sql from "./sql/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * analytics-engine command * @generated from apis/overlays/analytics-engine.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "analytics-engine", describe: "analytics-engine", - builder: (yargs) => { - return yargs.command($sql).demandCommand(1, "Please specify a subcommand"); + routes: { + sql: $sql, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/analytics-engine/sql/index.ts b/packages/cli/src/commands/_generated/analytics-engine/sql/index.ts index 5e3f42e3e1..84db02c781 100644 --- a/packages/cli/src/commands/_generated/analytics-engine/sql/index.ts +++ b/packages/cli/src/commands/_generated/analytics-engine/sql/index.ts @@ -1,22 +1,17 @@ import $query from "./query.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * sql command group * @generated from apis/overlays/analytics-engine.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "sql", describe: "Operations for sql", - builder: (yargs) => { - return yargs - .command($query) - .demandCommand(1, "Please specify a subcommand"); + routes: { + query: $query, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/analytics-engine/sql/query.handler.ts b/packages/cli/src/commands/_generated/analytics-engine/sql/query.handler.ts new file mode 100644 index 0000000000..2c197b277d --- /dev/null +++ b/packages/cli/src/commands/_generated/analytics-engine/sql/query.handler.ts @@ -0,0 +1,80 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./query.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { readFileForFlag, resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "analytics-engine sql query", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.body === undefined && argv.file === undefined) { + throw new Error( + "--body or --file is required for this command. Pass --body '' or --file path/to/file." + ); + } + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf analytics-engine sql query", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/analytics_engine/sql`, + pathParams: {}, + bodyKind: "octet-stream", + body: argv.file !== undefined ? { file: argv.file } : argv.body, + }); + return; + } + const parsedBody = + argv.file !== undefined + ? undefined + : resolveFileToken(argv.body, "body", "binary"); + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.file !== undefined) { + const fileContent = readFileForFlag(argv.file); + const result = await withProgress(`Loading`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/analytics_engine/sql`, + { body: fileContent, headers: { "Content-Type": "text/plain" } } + ) + ); + formatOutput(result, { successLabel: `Loaded` }); + return; + } + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Loading`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/analytics_engine/sql`, + { body: bodyData, headers: { "Content-Type": "text/plain" } } + ) + ); + formatOutput(result, { successLabel: `Loaded` }); + return; + } + } + ); +} diff --git a/packages/cli/src/commands/_generated/analytics-engine/sql/query.ts b/packages/cli/src/commands/_generated/analytics-engine/sql/query.ts index dee1c84ec8..dc58b5f5a4 100644 --- a/packages/cli/src/commands/_generated/analytics-engine/sql/query.ts +++ b/packages/cli/src/commands/_generated/analytics-engine/sql/query.ts @@ -1,113 +1,43 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * query command * @generated from apis/overlays/analytics-engine.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { readFileForFlag, resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 analytics-engine sql query\n\nExecutes a SQL query against Workers Analytics Engine data. Pass the SQL query in the request body as plain text. The response uses newline-delimited JSON (NDJSON) by default, or a single JSON object when the query includes a FORMAT JSON clause. Prefer this method for longer queries that may exceed URL length limits." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Plain-text request body (without JSON quotes)", - }) - .option("file", { - type: "string", - description: "Path to a file to upload as the request body", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Plain-text request body (without JSON quotes)", + optional: true, + parse: String, + }, + file: { + kind: "parsed", + brief: "Path to a file to upload as the request body", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "query", describe: "Execute an Analytics Engine SQL query via request body", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "analytics-engine sql query", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.body === undefined && argv.file === undefined) { - throw new Error( - "--body or --file is required for this command. Pass --body '' or --file path/to/file." - ); - } - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf analytics-engine sql query", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/analytics_engine/sql`, - pathParams: {}, - bodyKind: "octet-stream", - body: argv.file !== undefined ? { file: argv.file } : argv.body, - }); - return; - } - const parsedBody = - argv.file !== undefined - ? undefined - : resolveFileToken(argv.body, "body", "binary"); - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.file !== undefined) { - const fileContent = readFileForFlag(argv.file); - const result = await withProgress(`Loading`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/analytics_engine/sql`, - { body: fileContent, headers: { "Content-Type": "text/plain" } } - ) - ); - formatOutput(result, { successLabel: `Loaded` }); - return; - } - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Loading`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/analytics_engine/sql`, - { body: bodyData, headers: { "Content-Type": "text/plain" } } - ) - ); - formatOutput(result, { successLabel: `Loaded` }); - return; - } - } - ), -}; + usage: + "$0 analytics-engine sql query\n\nExecutes a SQL query against Workers Analytics Engine data. Pass the SQL query in the request body as plain text. The response uses newline-delimited JSON (NDJSON) by default, or a single JSON object when the query includes a FORMAT JSON clause. Prefer this method for longer queries that may exceed URL length limits.", + ...parameters, + loader: () => import("./query.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/analytics/index.ts b/packages/cli/src/commands/_generated/analytics/index.ts index 51653028e9..82252d2a9a 100644 --- a/packages/cli/src/commands/_generated/analytics/index.ts +++ b/packages/cli/src/commands/_generated/analytics/index.ts @@ -1,25 +1,20 @@ import $latency from "./latency/index.js"; import $query from "./query/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * analytics command * @generated from apis/overlays/analytics.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "analytics", describe: "Zone-level traffic analytics — dashboard summaries, per-colo breakdowns, and Argo latency metrics", - builder: (yargs) => { - return yargs - .command($latency) - .command($query) - .demandCommand(1, "Please specify a subcommand"); + routes: { + latency: $latency, + query: $query, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/analytics/latency/colos/get.handler.ts b/packages/cli/src/commands/_generated/analytics/latency/colos/get.handler.ts new file mode 100644 index 0000000000..f4b99b9400 --- /dev/null +++ b/packages/cli/src/commands/_generated/analytics/latency/colos/get.handler.ts @@ -0,0 +1,42 @@ +import operation from "../../../_operations/analytics/latency/colos/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "analytics latency colos get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf analytics latency colos get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/analytics/latency/colos`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/analytics/latency/colos/get.ts b/packages/cli/src/commands/_generated/analytics/latency/colos/get.ts index 4ff0d4ac06..bd0b3fc19d 100644 --- a/packages/cli/src/commands/_generated/analytics/latency/colos/get.ts +++ b/packages/cli/src/commands/_generated/analytics/latency/colos/get.ts @@ -1,69 +1,31 @@ -import operation from "../../../_operations/analytics/latency/colos/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/analytics.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 analytics latency colos get\n\nRetrieves Argo Smart Routing analytics broken down by geographic points of presence (PoPs). Shows latency improvements and routing efficiency per location." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "Argo Analytics for a zone at different PoPs", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "analytics latency colos get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf analytics latency colos get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/analytics/latency/colos`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 analytics latency colos get\n\nRetrieves Argo Smart Routing analytics broken down by geographic points of presence (PoPs). Shows latency improvements and routing efficiency per location.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/analytics/latency/colos/index.ts b/packages/cli/src/commands/_generated/analytics/latency/colos/index.ts index 9df844fc63..11d1f5f04d 100644 --- a/packages/cli/src/commands/_generated/analytics/latency/colos/index.ts +++ b/packages/cli/src/commands/_generated/analytics/latency/colos/index.ts @@ -1,20 +1,17 @@ import $get from "./get.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * colos command group * @generated from apis/overlays/analytics.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "colos", describe: "Operations for latency.colos", - builder: (yargs) => { - return yargs.command($get).demandCommand(1, "Please specify a subcommand"); + routes: { + get: $get, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/analytics/latency/get.handler.ts b/packages/cli/src/commands/_generated/analytics/latency/get.handler.ts new file mode 100644 index 0000000000..c66a4dc32d --- /dev/null +++ b/packages/cli/src/commands/_generated/analytics/latency/get.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/analytics/latency/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "analytics latency get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + bins: argv["bins"], + }; + if (argv.dryRun) { + formatDryRun({ + command: "cf analytics latency get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/analytics/latency`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { zone_id: zoneId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/analytics/latency/get.ts b/packages/cli/src/commands/_generated/analytics/latency/get.ts index 911e617f02..47e358f4c1 100644 --- a/packages/cli/src/commands/_generated/analytics/latency/get.ts +++ b/packages/cli/src/commands/_generated/analytics/latency/get.ts @@ -1,74 +1,32 @@ -import operation from "../../_operations/analytics/latency/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/analytics.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 analytics latency get\n\nRetrieves aggregate Argo Smart Routing analytics for a zone, including latency improvements, bandwidth savings, and routing statistics." - ) - .option("bins", { type: "string", description: "Bins" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + bins: { kind: "parsed", brief: "Bins", optional: true, parse: String }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "Argo Analytics for a zone", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "analytics latency get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - bins: argv["bins"], - }; - if (argv.dryRun) { - formatDryRun({ - command: "cf analytics latency get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/analytics/latency`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { zone_id: zoneId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 analytics latency get\n\nRetrieves aggregate Argo Smart Routing analytics for a zone, including latency improvements, bandwidth savings, and routing statistics.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/analytics/latency/index.ts b/packages/cli/src/commands/_generated/analytics/latency/index.ts index e0fe69fffa..bec4bac4c7 100644 --- a/packages/cli/src/commands/_generated/analytics/latency/index.ts +++ b/packages/cli/src/commands/_generated/analytics/latency/index.ts @@ -1,25 +1,20 @@ import $colos from "./colos/index.js"; import $get from "./get.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * latency command group * @generated from apis/overlays/analytics.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "latency", describe: "Argo Smart Routing latency analytics showing time-to-first-byte improvements", - builder: (yargs) => { - return yargs - .command($get) - .command($colos) - .demandCommand(1, "Please specify a subcommand"); + routes: { + get: $get, + colos: $colos, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/analytics/query/data-security/content-findings/index.ts b/packages/cli/src/commands/_generated/analytics/query/data-security/content-findings/index.ts index 9596681691..167ac1caf6 100644 --- a/packages/cli/src/commands/_generated/analytics/query/data-security/content-findings/index.ts +++ b/packages/cli/src/commands/_generated/analytics/query/data-security/content-findings/index.ts @@ -1,20 +1,17 @@ import $topn from "./top-n.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * content-findings command group * @generated from apis/overlays/analytics.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "content-findings", describe: "Operations for query.data-security.content-findings", - builder: (yargs) => { - return yargs.command($topn).demandCommand(1, "Please specify a subcommand"); + routes: { + "top-n": $topn, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/analytics/query/data-security/content-findings/top-n.handler.ts b/packages/cli/src/commands/_generated/analytics/query/data-security/content-findings/top-n.handler.ts new file mode 100644 index 0000000000..feae25169c --- /dev/null +++ b/packages/cli/src/commands/_generated/analytics/query/data-security/content-findings/top-n.handler.ts @@ -0,0 +1,116 @@ +import operation from "../../../../_operations/analytics/query/data-security/content-findings/top-n.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./top-n.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "analytics query data-security content-findings top-n", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["filters"] === undefined) { + throw new Error( + "--filters is required (or pass --body with this field set)." + ); + } + if (argv["from"] === undefined) { + argv["from"] = await promptForRequiredField( + "from", + "Start of the query time range (inclusive). RFC3339." + ); + } + if (argv["limit"] === undefined) { + throw new Error( + "--limit is required (or pass --body with this field set)." + ); + } + if (argv["to"] === undefined) { + argv["to"] = await promptForRequiredField( + "to", + "End of the query time range (exclusive). RFC3339." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf analytics query data-security content-findings top-n", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/analytics/query/data-security/content-findings/top-n`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + filters: parseObjectArray(argv["filters"], "filters"), + from: resolveFileToken( + argv["from"] as string | undefined, + "from", + "text" + ), + n: argv["limit"], + to: resolveFileToken( + argv["to"] as string | undefined, + "to", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + filters: parseObjectArray(argv["filters"], "filters"), + from: resolveFileToken( + argv["from"] as string | undefined, + "from", + "text" + ), + n: argv["limit"], + to: resolveFileToken(argv["to"] as string | undefined, "to", "text"), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/analytics/query/data-security/content-findings/top-n.ts b/packages/cli/src/commands/_generated/analytics/query/data-security/content-findings/top-n.ts index 4d5787eb05..bbcd8aa871 100644 --- a/packages/cli/src/commands/_generated/analytics/query/data-security/content-findings/top-n.ts +++ b/packages/cli/src/commands/_generated/analytics/query/data-security/content-findings/top-n.ts @@ -1,162 +1,62 @@ -import operation from "../../../../_operations/analytics/query/data-security/content-findings/top-n.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * top-n command * @generated from apis/overlays/analytics.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 analytics query data-security content-findings top-n\n\nReturns the top N integrations ranked by total content findings." - ) - .option("filters", { - type: "string", - description: +const parameters = { + flags: { + filters: { + kind: "parsed", + brief: 'Filters to apply. `findingType = content` is applied automatically for CASB data. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"name": string, "op": string, "values": [(string | boolean | number)]}].', - }) - .option("from", { - type: "string", - description: "Start of the query time range (inclusive). RFC3339.", - }) - .option("limit", { - type: "number", - description: "Maximum number of integrations to return.", - }) - .option("to", { - type: "string", - description: "End of the query time range (exclusive). RFC3339.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + from: { + kind: "parsed", + brief: "Start of the query time range (inclusive). RFC3339.", + optional: true, + parse: String, + }, + limit: { + kind: "parsed", + brief: "Maximum number of integrations to return.", + optional: true, + parse: Number, + }, + to: { + kind: "parsed", + brief: "End of the query time range (exclusive). RFC3339.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Returns the top N integrations for content findings.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Returns the top N integrations for content findings.", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "top-n", describe: "Top integrations by content findings", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "analytics query data-security content-findings top-n", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["filters"] === undefined) { - throw new Error( - "--filters is required (or pass --body with this field set)." - ); - } - if (argv["from"] === undefined) { - argv["from"] = await promptForRequiredField( - "from", - "Start of the query time range (inclusive). RFC3339." - ); - } - if (argv["limit"] === undefined) { - throw new Error( - "--limit is required (or pass --body with this field set)." - ); - } - if (argv["to"] === undefined) { - argv["to"] = await promptForRequiredField( - "to", - "End of the query time range (exclusive). RFC3339." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf analytics query data-security content-findings top-n", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/analytics/query/data-security/content-findings/top-n`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - filters: parseObjectArray(argv["filters"], "filters"), - from: resolveFileToken( - argv["from"] as string | undefined, - "from", - "text" - ), - n: argv["limit"], - to: resolveFileToken( - argv["to"] as string | undefined, - "to", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - filters: parseObjectArray(argv["filters"], "filters"), - from: resolveFileToken( - argv["from"] as string | undefined, - "from", - "text" - ), - n: argv["limit"], - to: resolveFileToken(argv["to"] as string | undefined, "to", "text"), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 analytics query data-security content-findings top-n\n\nReturns the top N integrations ranked by total content findings.", + ...parameters, + loader: () => import("./top-n.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/analytics/query/data-security/findings/index.ts b/packages/cli/src/commands/_generated/analytics/query/data-security/findings/index.ts index a3cfa0bae6..f7c27644bd 100644 --- a/packages/cli/src/commands/_generated/analytics/query/data-security/findings/index.ts +++ b/packages/cli/src/commands/_generated/analytics/query/data-security/findings/index.ts @@ -1,24 +1,19 @@ import $summary from "./summary.js"; import $timeseries from "./timeseries.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * findings command group * @generated from apis/overlays/analytics.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "findings", describe: "Operations for query.data-security.findings", - builder: (yargs) => { - return yargs - .command($summary) - .command($timeseries) - .demandCommand(1, "Please specify a subcommand"); + routes: { + summary: $summary, + timeseries: $timeseries, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/analytics/query/data-security/findings/summary.handler.ts b/packages/cli/src/commands/_generated/analytics/query/data-security/findings/summary.handler.ts new file mode 100644 index 0000000000..0d5e2c85c5 --- /dev/null +++ b/packages/cli/src/commands/_generated/analytics/query/data-security/findings/summary.handler.ts @@ -0,0 +1,109 @@ +import operation from "../../../../_operations/analytics/query/data-security/findings/summary.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./summary.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "analytics query data-security findings summary", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["filters"] === undefined) { + throw new Error( + "--filters is required (or pass --body with this field set)." + ); + } + if (argv["from"] === undefined) { + argv["from"] = await promptForRequiredField( + "from", + "Start of the query time range (inclusive). RFC3339." + ); + } + if (argv["to"] === undefined) { + argv["to"] = await promptForRequiredField( + "to", + "End of the query time range (exclusive). RFC3339." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf analytics query data-security findings summary", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/analytics/query/data-security/findings/summary`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + filters: parseObjectArray(argv["filters"], "filters"), + from: resolveFileToken( + argv["from"] as string | undefined, + "from", + "text" + ), + to: resolveFileToken( + argv["to"] as string | undefined, + "to", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + filters: parseObjectArray(argv["filters"], "filters"), + from: resolveFileToken( + argv["from"] as string | undefined, + "from", + "text" + ), + to: resolveFileToken(argv["to"] as string | undefined, "to", "text"), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/analytics/query/data-security/findings/summary.ts b/packages/cli/src/commands/_generated/analytics/query/data-security/findings/summary.ts index 5ddc9be597..2c80e508b1 100644 --- a/packages/cli/src/commands/_generated/analytics/query/data-security/findings/summary.ts +++ b/packages/cli/src/commands/_generated/analytics/query/data-security/findings/summary.ts @@ -1,151 +1,56 @@ -import operation from "../../../../_operations/analytics/query/data-security/findings/summary.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * summary command * @generated from apis/overlays/analytics.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 analytics query data-security findings summary\n\nReturns aggregate current-period and previous-period totals for CASB findings." - ) - .option("filters", { - type: "string", - description: +const parameters = { + flags: { + filters: { + kind: "parsed", + brief: 'Filters to apply. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"name": string, "op": string, "values": [(string | boolean | number)]}].', - }) - .option("from", { - type: "string", - description: "Start of the query time range (inclusive). RFC3339.", - }) - .option("to", { - type: "string", - description: "End of the query time range (exclusive). RFC3339.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + from: { + kind: "parsed", + brief: "Start of the query time range (inclusive). RFC3339.", + optional: true, + parse: String, + }, + to: { + kind: "parsed", + brief: "End of the query time range (exclusive). RFC3339.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Query for aggregate findings summary.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Query for aggregate findings summary.", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "summary", describe: "Data security findings summary", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "analytics query data-security findings summary", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["filters"] === undefined) { - throw new Error( - "--filters is required (or pass --body with this field set)." - ); - } - if (argv["from"] === undefined) { - argv["from"] = await promptForRequiredField( - "from", - "Start of the query time range (inclusive). RFC3339." - ); - } - if (argv["to"] === undefined) { - argv["to"] = await promptForRequiredField( - "to", - "End of the query time range (exclusive). RFC3339." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf analytics query data-security findings summary", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/analytics/query/data-security/findings/summary`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - filters: parseObjectArray(argv["filters"], "filters"), - from: resolveFileToken( - argv["from"] as string | undefined, - "from", - "text" - ), - to: resolveFileToken( - argv["to"] as string | undefined, - "to", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - filters: parseObjectArray(argv["filters"], "filters"), - from: resolveFileToken( - argv["from"] as string | undefined, - "from", - "text" - ), - to: resolveFileToken(argv["to"] as string | undefined, "to", "text"), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 analytics query data-security findings summary\n\nReturns aggregate current-period and previous-period totals for CASB findings.", + ...parameters, + loader: () => import("./summary.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/analytics/query/data-security/findings/timeseries.handler.ts b/packages/cli/src/commands/_generated/analytics/query/data-security/findings/timeseries.handler.ts new file mode 100644 index 0000000000..75d13c6839 --- /dev/null +++ b/packages/cli/src/commands/_generated/analytics/query/data-security/findings/timeseries.handler.ts @@ -0,0 +1,109 @@ +import operation from "../../../../_operations/analytics/query/data-security/findings/timeseries.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./timeseries.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "analytics query data-security findings timeseries", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["filters"] === undefined) { + throw new Error( + "--filters is required (or pass --body with this field set)." + ); + } + if (argv["from"] === undefined) { + argv["from"] = await promptForRequiredField( + "from", + "Start of the query time range (inclusive). RFC3339." + ); + } + if (argv["to"] === undefined) { + argv["to"] = await promptForRequiredField( + "to", + "End of the query time range (exclusive). RFC3339." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf analytics query data-security findings timeseries", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/analytics/query/data-security/findings/timeseries`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + filters: parseObjectArray(argv["filters"], "filters"), + from: resolveFileToken( + argv["from"] as string | undefined, + "from", + "text" + ), + to: resolveFileToken( + argv["to"] as string | undefined, + "to", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + filters: parseObjectArray(argv["filters"], "filters"), + from: resolveFileToken( + argv["from"] as string | undefined, + "from", + "text" + ), + to: resolveFileToken(argv["to"] as string | undefined, "to", "text"), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/analytics/query/data-security/findings/timeseries.ts b/packages/cli/src/commands/_generated/analytics/query/data-security/findings/timeseries.ts index 4622fe765b..a8c0ae3b42 100644 --- a/packages/cli/src/commands/_generated/analytics/query/data-security/findings/timeseries.ts +++ b/packages/cli/src/commands/_generated/analytics/query/data-security/findings/timeseries.ts @@ -1,151 +1,56 @@ -import operation from "../../../../_operations/analytics/query/data-security/findings/timeseries.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * timeseries command * @generated from apis/overlays/analytics.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 analytics query data-security findings timeseries\n\nReturns merged time-bucketed CASB findings." - ) - .option("filters", { - type: "string", - description: +const parameters = { + flags: { + filters: { + kind: "parsed", + brief: 'Filters to apply. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"name": string, "op": string, "values": [(string | boolean | number)]}].', - }) - .option("from", { - type: "string", - description: "Start of the query time range (inclusive). RFC3339.", - }) - .option("to", { - type: "string", - description: "End of the query time range (exclusive). RFC3339.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + from: { + kind: "parsed", + brief: "Start of the query time range (inclusive). RFC3339.", + optional: true, + parse: String, + }, + to: { + kind: "parsed", + brief: "End of the query time range (exclusive). RFC3339.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Query for findings timeseries.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Query for findings timeseries.", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "timeseries", describe: "Data security findings timeseries", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "analytics query data-security findings timeseries", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["filters"] === undefined) { - throw new Error( - "--filters is required (or pass --body with this field set)." - ); - } - if (argv["from"] === undefined) { - argv["from"] = await promptForRequiredField( - "from", - "Start of the query time range (inclusive). RFC3339." - ); - } - if (argv["to"] === undefined) { - argv["to"] = await promptForRequiredField( - "to", - "End of the query time range (exclusive). RFC3339." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf analytics query data-security findings timeseries", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/analytics/query/data-security/findings/timeseries`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - filters: parseObjectArray(argv["filters"], "filters"), - from: resolveFileToken( - argv["from"] as string | undefined, - "from", - "text" - ), - to: resolveFileToken( - argv["to"] as string | undefined, - "to", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - filters: parseObjectArray(argv["filters"], "filters"), - from: resolveFileToken( - argv["from"] as string | undefined, - "from", - "text" - ), - to: resolveFileToken(argv["to"] as string | undefined, "to", "text"), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 analytics query data-security findings timeseries\n\nReturns merged time-bucketed CASB findings.", + ...parameters, + loader: () => import("./timeseries.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/analytics/query/data-security/index.ts b/packages/cli/src/commands/_generated/analytics/query/data-security/index.ts index 81261be035..a9d563d499 100644 --- a/packages/cli/src/commands/_generated/analytics/query/data-security/index.ts +++ b/packages/cli/src/commands/_generated/analytics/query/data-security/index.ts @@ -1,24 +1,19 @@ import $contentfindings from "./content-findings/index.js"; import $findings from "./findings/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * data-security command group * @generated from apis/overlays/analytics.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "data-security", describe: "Operations for query.data-security", - builder: (yargs) => { - return yargs - .command($contentfindings) - .command($findings) - .demandCommand(1, "Please specify a subcommand"); + routes: { + "content-findings": $contentfindings, + findings: $findings, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/analytics/query/index.ts b/packages/cli/src/commands/_generated/analytics/query/index.ts index c18be2343d..987e5462d0 100644 --- a/packages/cli/src/commands/_generated/analytics/query/index.ts +++ b/packages/cli/src/commands/_generated/analytics/query/index.ts @@ -2,27 +2,22 @@ import $datasecurity from "./data-security/index.js"; import $summary from "./summary.js"; import $timeseries from "./timeseries.js"; import $topn from "./top-n.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * query command group * @generated from apis/overlays/analytics.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "query", describe: "Operations for query", - builder: (yargs) => { - return yargs - .command($summary) - .command($timeseries) - .command($topn) - .command($datasecurity) - .demandCommand(1, "Please specify a subcommand"); + routes: { + summary: $summary, + timeseries: $timeseries, + "top-n": $topn, + "data-security": $datasecurity, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/analytics/query/summary.handler.ts b/packages/cli/src/commands/_generated/analytics/query/summary.handler.ts new file mode 100644 index 0000000000..fbefffd78c --- /dev/null +++ b/packages/cli/src/commands/_generated/analytics/query/summary.handler.ts @@ -0,0 +1,131 @@ +import operation from "../../_operations/analytics/query/summary.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./summary.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "analytics query summary", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["filters"] === undefined) { + throw new Error( + "--filters is required (or pass --body with this field set)." + ); + } + if (argv["from"] === undefined) { + argv["from"] = await promptForRequiredField( + "from", + "The start of the query time range (inclusive). RFC3339 format with timezone is required (e.g. \`2024-11-05T00:00:00Z\`)." + ); + } + if (argv["group-by"] === undefined) { + throw new Error( + "--group-by is required (or pass --body with this field set)." + ); + } + if (argv["stats"] === undefined) { + throw new Error( + "--stats is required (or pass --body with this field set)." + ); + } + if (argv["to"] === undefined) { + argv["to"] = await promptForRequiredField( + "to", + "Specifies the end of the query time range (exclusive). Requires RFC3339 format with timezone." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf analytics query summary", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/analytics/query/${argv["dataset"] == null ? "" : encodeURIComponent(String(argv["dataset"]))}/summary`, + pathParams: { dataset: String(argv["dataset"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + filters: parseObjectArray(argv["filters"], "filters"), + from: resolveFileToken( + argv["from"] as string | undefined, + "from", + "text" + ), + groupBy: argv["group-by"], + stats: argv["stats"], + to: resolveFileToken( + argv["to"] as string | undefined, + "to", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + dataset: argv["dataset"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + filters: parseObjectArray(argv["filters"], "filters"), + from: resolveFileToken( + argv["from"] as string | undefined, + "from", + "text" + ), + groupBy: argv["group-by"], + stats: argv["stats"], + to: resolveFileToken(argv["to"] as string | undefined, "to", "text"), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + dataset: argv["dataset"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/analytics/query/summary.ts b/packages/cli/src/commands/_generated/analytics/query/summary.ts index 57b9c338a3..b8a4407a72 100644 --- a/packages/cli/src/commands/_generated/analytics/query/summary.ts +++ b/packages/cli/src/commands/_generated/analytics/query/summary.ts @@ -1,193 +1,81 @@ -import operation from "../../_operations/analytics/query/summary.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * summary command * @generated from apis/overlays/analytics.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 analytics query summary \n\nReturns aggregate summary stats for a dataset. Includes current-period and previous-period totals for trend comparison." - ) - .positional("dataset", { - type: "string", - description: - "Dataset name to query. Examples: \`access-logins\`, \`gateway-http\`, \`gateway-dns\`, \`gateway-http\`, \`shadow-it\`.", - demandOption: true, - }) - .option("filters", { - type: "string", - description: +const parameters = { + flags: { + filters: { + kind: "parsed", + brief: 'Filters to apply before aggregating results. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"name": string, "op": string, "values": [(string | boolean | number)]}].', - }) - .option("from", { - type: "string", - description: + optional: true, + parse: String, + }, + from: { + kind: "parsed", + brief: "The start of the query time range (inclusive). RFC3339 format with timezone is required (e.g. `2024-11-05T00:00:00Z`).", - }) - .option("group-by", { - type: "string", - array: true, - description: + optional: true, + parse: String, + }, + "group-by": { + kind: "parsed", + brief: "Specifies the column names to group results by. Requires valid columns for the target dataset.", - }) - .option("stats", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + stats: { + kind: "parsed", + brief: "Specifies the stat names to include in results. Requires valid stats for the target dataset (e.g. `attemptsTotal`, `bytesTotal`).", - }) - .option("to", { - type: "string", - description: + variadic: true, + optional: true, + parse: String, + }, + to: { + kind: "parsed", + brief: "Specifies the end of the query time range (exclusive). Requires RFC3339 format with timezone.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "dataset", + brief: + "Dataset name to query. Examples: \`access-logins\`, \`gateway-http\`, \`gateway-dns\`, \`gateway-http\`, \`shadow-it\`.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "summary ", describe: "Query analytics summary", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "analytics query summary", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["filters"] === undefined) { - throw new Error( - "--filters is required (or pass --body with this field set)." - ); - } - if (argv["from"] === undefined) { - argv["from"] = await promptForRequiredField( - "from", - "The start of the query time range (inclusive). RFC3339 format with timezone is required (e.g. \`2024-11-05T00:00:00Z\`)." - ); - } - if (argv["group-by"] === undefined) { - throw new Error( - "--group-by is required (or pass --body with this field set)." - ); - } - if (argv["stats"] === undefined) { - throw new Error( - "--stats is required (or pass --body with this field set)." - ); - } - if (argv["to"] === undefined) { - argv["to"] = await promptForRequiredField( - "to", - "Specifies the end of the query time range (exclusive). Requires RFC3339 format with timezone." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf analytics query summary", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/analytics/query/${argv["dataset"] == null ? "" : encodeURIComponent(String(argv["dataset"]))}/summary`, - pathParams: { dataset: String(argv["dataset"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - filters: parseObjectArray(argv["filters"], "filters"), - from: resolveFileToken( - argv["from"] as string | undefined, - "from", - "text" - ), - groupBy: argv["group-by"], - stats: argv["stats"], - to: resolveFileToken( - argv["to"] as string | undefined, - "to", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - dataset: argv["dataset"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - filters: parseObjectArray(argv["filters"], "filters"), - from: resolveFileToken( - argv["from"] as string | undefined, - "from", - "text" - ), - groupBy: argv["group-by"], - stats: argv["stats"], - to: resolveFileToken(argv["to"] as string | undefined, "to", "text"), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - dataset: argv["dataset"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 analytics query summary \n\nReturns aggregate summary stats for a dataset. Includes current-period and previous-period totals for trend comparison.", + ...parameters, + loader: () => import("./summary.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/analytics/query/timeseries.handler.ts b/packages/cli/src/commands/_generated/analytics/query/timeseries.handler.ts new file mode 100644 index 0000000000..bbc86c4c7b --- /dev/null +++ b/packages/cli/src/commands/_generated/analytics/query/timeseries.handler.ts @@ -0,0 +1,147 @@ +import operation from "../../_operations/analytics/query/timeseries.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./timeseries.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "analytics query timeseries", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["filters"] === undefined) { + throw new Error( + "--filters is required (or pass --body with this field set)." + ); + } + if (argv["from"] === undefined) { + argv["from"] = await promptForRequiredField( + "from", + "The start of the query time range (inclusive). RFC3339 format with timezone is required (e.g. \`2024-11-05T00:00:00Z\`)." + ); + } + if (argv["group-by"] === undefined) { + throw new Error( + "--group-by is required (or pass --body with this field set)." + ); + } + if (argv["stats"] === undefined) { + throw new Error( + "--stats is required (or pass --body with this field set)." + ); + } + if (argv["to"] === undefined) { + argv["to"] = await promptForRequiredField( + "to", + "Specifies the end of the query time range (exclusive). Requires RFC3339 format with timezone." + ); + } + if (argv["resolution"] === undefined) { + argv["resolution"] = await promptForRequiredField( + "resolution", + "Time bucket size for grouping results. Controls the granularity of the returned time slots. " + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf analytics query timeseries", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/analytics/query/${argv["dataset"] == null ? "" : encodeURIComponent(String(argv["dataset"]))}/timeseries`, + pathParams: { dataset: String(argv["dataset"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + filters: parseObjectArray(argv["filters"], "filters"), + from: resolveFileToken( + argv["from"] as string | undefined, + "from", + "text" + ), + groupBy: argv["group-by"], + stats: argv["stats"], + to: resolveFileToken( + argv["to"] as string | undefined, + "to", + "text" + ), + resolution: resolveFileToken( + argv["resolution"] as string | undefined, + "resolution", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + dataset: argv["dataset"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + filters: parseObjectArray(argv["filters"], "filters"), + from: resolveFileToken( + argv["from"] as string | undefined, + "from", + "text" + ), + groupBy: argv["group-by"], + stats: argv["stats"], + to: resolveFileToken(argv["to"] as string | undefined, "to", "text"), + resolution: resolveFileToken( + argv["resolution"] as string | undefined, + "resolution", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + dataset: argv["dataset"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/analytics/query/timeseries.ts b/packages/cli/src/commands/_generated/analytics/query/timeseries.ts index 4ffd432973..32f2e0a095 100644 --- a/packages/cli/src/commands/_generated/analytics/query/timeseries.ts +++ b/packages/cli/src/commands/_generated/analytics/query/timeseries.ts @@ -1,214 +1,88 @@ -import operation from "../../_operations/analytics/query/timeseries.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * timeseries command * @generated from apis/overlays/analytics.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 analytics query timeseries \n\nReturns time-bucketed analytics data for a dataset. Includes time slots, each containing the requested stats, group-by dimensions, and resolution-controlled bucket size (e.g. `hour`, `day`)." - ) - .positional("dataset", { - type: "string", - description: - "Dataset name to query. Examples: \`access-logins\`, \`gateway-http\`, \`gateway-dns\`, \`gateway-http\`, \`shadow-it\`.", - demandOption: true, - }) - .option("filters", { - type: "string", - description: +const parameters = { + flags: { + filters: { + kind: "parsed", + brief: 'Filters to apply before aggregating results. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"name": string, "op": string, "values": [(string | boolean | number)]}].', - }) - .option("from", { - type: "string", - description: + optional: true, + parse: String, + }, + from: { + kind: "parsed", + brief: "The start of the query time range (inclusive). RFC3339 format with timezone is required (e.g. `2024-11-05T00:00:00Z`).", - }) - .option("group-by", { - type: "string", - array: true, - description: + optional: true, + parse: String, + }, + "group-by": { + kind: "parsed", + brief: "Specifies the column names to group results by. Requires valid columns for the target dataset.", - }) - .option("stats", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + stats: { + kind: "parsed", + brief: "Specifies the stat names to include in results. Requires valid stats for the target dataset (e.g. `attemptsTotal`, `bytesTotal`).", - }) - .option("to", { - type: "string", - description: + variadic: true, + optional: true, + parse: String, + }, + to: { + kind: "parsed", + brief: "Specifies the end of the query time range (exclusive). Requires RFC3339 format with timezone.", - }) - .option("resolution", { - type: "string", - description: + optional: true, + parse: String, + }, + resolution: { + kind: "parsed", + brief: "Time bucket size for grouping results. Controls the granularity of the returned time slots.\n", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "dataset", + brief: + "Dataset name to query. Examples: \`access-logins\`, \`gateway-http\`, \`gateway-dns\`, \`gateway-http\`, \`shadow-it\`.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "timeseries ", describe: "Query analytics timeseries", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "analytics query timeseries", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["filters"] === undefined) { - throw new Error( - "--filters is required (or pass --body with this field set)." - ); - } - if (argv["from"] === undefined) { - argv["from"] = await promptForRequiredField( - "from", - "The start of the query time range (inclusive). RFC3339 format with timezone is required (e.g. \`2024-11-05T00:00:00Z\`)." - ); - } - if (argv["group-by"] === undefined) { - throw new Error( - "--group-by is required (or pass --body with this field set)." - ); - } - if (argv["stats"] === undefined) { - throw new Error( - "--stats is required (or pass --body with this field set)." - ); - } - if (argv["to"] === undefined) { - argv["to"] = await promptForRequiredField( - "to", - "Specifies the end of the query time range (exclusive). Requires RFC3339 format with timezone." - ); - } - if (argv["resolution"] === undefined) { - argv["resolution"] = await promptForRequiredField( - "resolution", - "Time bucket size for grouping results. Controls the granularity of the returned time slots. " - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf analytics query timeseries", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/analytics/query/${argv["dataset"] == null ? "" : encodeURIComponent(String(argv["dataset"]))}/timeseries`, - pathParams: { dataset: String(argv["dataset"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - filters: parseObjectArray(argv["filters"], "filters"), - from: resolveFileToken( - argv["from"] as string | undefined, - "from", - "text" - ), - groupBy: argv["group-by"], - stats: argv["stats"], - to: resolveFileToken( - argv["to"] as string | undefined, - "to", - "text" - ), - resolution: resolveFileToken( - argv["resolution"] as string | undefined, - "resolution", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - dataset: argv["dataset"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - filters: parseObjectArray(argv["filters"], "filters"), - from: resolveFileToken( - argv["from"] as string | undefined, - "from", - "text" - ), - groupBy: argv["group-by"], - stats: argv["stats"], - to: resolveFileToken(argv["to"] as string | undefined, "to", "text"), - resolution: resolveFileToken( - argv["resolution"] as string | undefined, - "resolution", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - dataset: argv["dataset"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 analytics query timeseries \n\nReturns time-bucketed analytics data for a dataset. Includes time slots, each containing the requested stats, group-by dimensions, and resolution-controlled bucket size (e.g. `hour`, `day`).", + ...parameters, + loader: () => import("./timeseries.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/analytics/query/top-n.handler.ts b/packages/cli/src/commands/_generated/analytics/query/top-n.handler.ts new file mode 100644 index 0000000000..f53c0649df --- /dev/null +++ b/packages/cli/src/commands/_generated/analytics/query/top-n.handler.ts @@ -0,0 +1,154 @@ +import operation from "../../_operations/analytics/query/top-n.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./top-n.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "analytics query top-n", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["filters"] === undefined) { + throw new Error( + "--filters is required (or pass --body with this field set)." + ); + } + if (argv["from"] === undefined) { + argv["from"] = await promptForRequiredField( + "from", + "The start of the query time range (inclusive). RFC3339 format with timezone is required (e.g. \`2024-11-05T00:00:00Z\`)." + ); + } + if (argv["group-by"] === undefined) { + throw new Error( + "--group-by is required (or pass --body with this field set)." + ); + } + if (argv["stats"] === undefined) { + throw new Error( + "--stats is required (or pass --body with this field set)." + ); + } + if (argv["to"] === undefined) { + argv["to"] = await promptForRequiredField( + "to", + "Specifies the end of the query time range (exclusive). Requires RFC3339 format with timezone." + ); + } + if (argv["limit"] === undefined) { + throw new Error( + "--limit is required (or pass --body with this field set)." + ); + } + if (argv["order-by"] === undefined) { + argv["order-by"] = await promptForRequiredField( + "order-by", + "Specifies the stat name for sorting results in descending order. Requires a valid stat for the target dataset." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf analytics query top-n", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/analytics/query/${argv["dataset"] == null ? "" : encodeURIComponent(String(argv["dataset"]))}/top-n`, + pathParams: { dataset: String(argv["dataset"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + filters: parseObjectArray(argv["filters"], "filters"), + from: resolveFileToken( + argv["from"] as string | undefined, + "from", + "text" + ), + groupBy: argv["group-by"], + stats: argv["stats"], + to: resolveFileToken( + argv["to"] as string | undefined, + "to", + "text" + ), + n: argv["limit"], + orderBy: resolveFileToken( + argv["order-by"] as string | undefined, + "order-by", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + dataset: argv["dataset"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + filters: parseObjectArray(argv["filters"], "filters"), + from: resolveFileToken( + argv["from"] as string | undefined, + "from", + "text" + ), + groupBy: argv["group-by"], + stats: argv["stats"], + to: resolveFileToken(argv["to"] as string | undefined, "to", "text"), + n: argv["limit"], + orderBy: resolveFileToken( + argv["order-by"] as string | undefined, + "order-by", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + dataset: argv["dataset"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/analytics/query/top-n.ts b/packages/cli/src/commands/_generated/analytics/query/top-n.ts index 4885c15e23..a02d07fec7 100644 --- a/packages/cli/src/commands/_generated/analytics/query/top-n.ts +++ b/packages/cli/src/commands/_generated/analytics/query/top-n.ts @@ -1,225 +1,94 @@ -import operation from "../../_operations/analytics/query/top-n.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * top-n command * @generated from apis/overlays/analytics.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 analytics query top-n \n\nReturns the top N results for a dataset by a specified stat. Includes an array of result rows, each containing the requested stats and group-by dimensions." - ) - .positional("dataset", { - type: "string", - description: - "Dataset name to query. Examples: \`access-logins\`, \`gateway-http\`, \`gateway-dns\`, \`gateway-http\`, \`shadow-it\`.", - demandOption: true, - }) - .option("filters", { - type: "string", - description: +const parameters = { + flags: { + filters: { + kind: "parsed", + brief: 'Filters to apply before aggregating results. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"name": string, "op": string, "values": [(string | boolean | number)]}].', - }) - .option("from", { - type: "string", - description: + optional: true, + parse: String, + }, + from: { + kind: "parsed", + brief: "The start of the query time range (inclusive). RFC3339 format with timezone is required (e.g. `2024-11-05T00:00:00Z`).", - }) - .option("group-by", { - type: "string", - array: true, - description: + optional: true, + parse: String, + }, + "group-by": { + kind: "parsed", + brief: "Specifies the column names to group results by. Requires valid columns for the target dataset.", - }) - .option("stats", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + stats: { + kind: "parsed", + brief: "Specifies the stat names to include in results. Requires valid stats for the target dataset (e.g. `attemptsTotal`, `bytesTotal`).", - }) - .option("to", { - type: "string", - description: + variadic: true, + optional: true, + parse: String, + }, + to: { + kind: "parsed", + brief: "Specifies the end of the query time range (exclusive). Requires RFC3339 format with timezone.", - }) - .option("limit", { - type: "number", - description: "Maximum number of results to return.", - }) - .option("order-by", { - type: "string", - description: + optional: true, + parse: String, + }, + limit: { + kind: "parsed", + brief: "Maximum number of results to return.", + optional: true, + parse: Number, + }, + "order-by": { + kind: "parsed", + brief: "Specifies the stat name for sorting results in descending order. Requires a valid stat for the target dataset.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "dataset", + brief: + "Dataset name to query. Examples: \`access-logins\`, \`gateway-http\`, \`gateway-dns\`, \`gateway-http\`, \`shadow-it\`.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "top-n ", describe: "Query analytics top-N", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "analytics query top-n", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["filters"] === undefined) { - throw new Error( - "--filters is required (or pass --body with this field set)." - ); - } - if (argv["from"] === undefined) { - argv["from"] = await promptForRequiredField( - "from", - "The start of the query time range (inclusive). RFC3339 format with timezone is required (e.g. \`2024-11-05T00:00:00Z\`)." - ); - } - if (argv["group-by"] === undefined) { - throw new Error( - "--group-by is required (or pass --body with this field set)." - ); - } - if (argv["stats"] === undefined) { - throw new Error( - "--stats is required (or pass --body with this field set)." - ); - } - if (argv["to"] === undefined) { - argv["to"] = await promptForRequiredField( - "to", - "Specifies the end of the query time range (exclusive). Requires RFC3339 format with timezone." - ); - } - if (argv["limit"] === undefined) { - throw new Error( - "--limit is required (or pass --body with this field set)." - ); - } - if (argv["order-by"] === undefined) { - argv["order-by"] = await promptForRequiredField( - "order-by", - "Specifies the stat name for sorting results in descending order. Requires a valid stat for the target dataset." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf analytics query top-n", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/analytics/query/${argv["dataset"] == null ? "" : encodeURIComponent(String(argv["dataset"]))}/top-n`, - pathParams: { dataset: String(argv["dataset"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - filters: parseObjectArray(argv["filters"], "filters"), - from: resolveFileToken( - argv["from"] as string | undefined, - "from", - "text" - ), - groupBy: argv["group-by"], - stats: argv["stats"], - to: resolveFileToken( - argv["to"] as string | undefined, - "to", - "text" - ), - n: argv["limit"], - orderBy: resolveFileToken( - argv["order-by"] as string | undefined, - "order-by", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - dataset: argv["dataset"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - filters: parseObjectArray(argv["filters"], "filters"), - from: resolveFileToken( - argv["from"] as string | undefined, - "from", - "text" - ), - groupBy: argv["group-by"], - stats: argv["stats"], - to: resolveFileToken(argv["to"] as string | undefined, "to", "text"), - n: argv["limit"], - orderBy: resolveFileToken( - argv["order-by"] as string | undefined, - "order-by", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - dataset: argv["dataset"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 analytics query top-n \n\nReturns the top N results for a dataset by a specified stat. Includes an array of result rows, each containing the requested stats and group-by dimensions.", + ...parameters, + loader: () => import("./top-n.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/index.ts b/packages/cli/src/commands/_generated/api-security/index.ts index e6a62e11a4..a546ab73b2 100644 --- a/packages/cli/src/commands/_generated/api-security/index.ts +++ b/packages/cli/src/commands/_generated/api-security/index.ts @@ -2,27 +2,22 @@ import $schemavalidation from "./schema-validation/index.js"; import $sessionidentifiers from "./session-identifiers/index.js"; import $tokenvalidation from "./token-validation/index.js"; import $vulnerabilityscanner from "./vulnerability-scanner/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * api-security command * @generated from apis/overlays/api-security.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "api-security", describe: "api-security", - builder: (yargs) => { - return yargs - .command($schemavalidation) - .command($sessionidentifiers) - .command($tokenvalidation) - .command($vulnerabilityscanner) - .demandCommand(1, "Please specify a subcommand"); + routes: { + "schema-validation": $schemavalidation, + "session-identifiers": $sessionidentifiers, + "token-validation": $tokenvalidation, + "vulnerability-scanner": $vulnerabilityscanner, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/index.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/index.ts index d7cdabefa0..2a13b45bbe 100644 --- a/packages/cli/src/commands/_generated/api-security/schema-validation/index.ts +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/index.ts @@ -1,24 +1,19 @@ import $schemas from "./schemas/index.js"; import $settings from "./settings/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * schema-validation command group * @generated from apis/overlays/api-security.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "schema-validation", describe: "Operations for schema-validation", - builder: (yargs) => { - return yargs - .command($schemas) - .command($settings) - .demandCommand(1, "Please specify a subcommand"); + routes: { + schemas: $schemas, + settings: $settings, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/create.handler.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/create.handler.ts new file mode 100644 index 0000000000..e326917eb2 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/create.handler.ts @@ -0,0 +1,121 @@ +import operation from "../../../_operations/api-security/schema-validation/schemas/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { + promptForRequiredEnumField, + promptForRequiredField, +} from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security schema-validation schemas create", + classification: { + safeFlags: ["kind", "validation-enabled", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["kind"] === undefined) { + argv["kind"] = await promptForRequiredEnumField( + "kind", + "The kind of the schema", + ["openapi_v3"] as const + ); + } + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField( + "name", + "A human-readable name for the schema" + ); + } + if (argv["source"] === undefined) { + argv["source"] = await promptForRequiredField( + "source", + "The raw schema, e.g., the OpenAPI schema, either as JSON or YAML" + ); + } + if (argv["validation-enabled"] === undefined) { + throw new Error( + "--validation-enabled is required (or pass --body with this field set)." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + formatDryRun({ + command: "cf api-security schema-validation schemas create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/schemas`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + kind: argv["kind"], + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + source: resolveFileToken( + argv["source"] as string | undefined, + "source", + "text" + ), + validation_enabled: argv["validation-enabled"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + kind: argv["kind"], + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + source: resolveFileToken( + argv["source"] as string | undefined, + "source", + "text" + ), + validation_enabled: argv["validation-enabled"], + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/create.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/create.ts index 7953f212c2..9df6ad2ef2 100644 --- a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/create.ts +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/create.ts @@ -1,171 +1,63 @@ -import operation from "../../../_operations/api-security/schema-validation/schemas/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; import { - promptForRequiredEnumField, - promptForRequiredField, -} from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; +import { resolveFileToken } from "#lib/input-validation.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security schema-validation schemas create\n\nUploads an OpenAPI schema that defines expected request formats for API operations." - ) - .option("kind", { - type: "string", - description: "The kind of the schema", +const parameters = { + flags: { + kind: { + kind: "parsed", + brief: "The kind of the schema", + optional: true, choices: ["openapi_v3"], - }) - .coerce("kind", (value) => resolveFileToken(value, "kind", "text")) - .option("name", { - type: "string", - description: "A human-readable name for the schema", - }) - .option("source", { - type: "string", - description: - "The raw schema, e.g., the OpenAPI schema, either as JSON or YAML", - }) - .option("validation-enabled", { - type: "boolean", - description: "An indicator if this schema is enabled", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => resolveFileToken(value, "kind", "text"), + }, + name: { + kind: "parsed", + brief: "A human-readable name for the schema", + optional: true, + parse: String, + }, + source: { + kind: "parsed", + brief: "The raw schema, e.g., the OpenAPI schema, either as JSON or YAML", + optional: true, + parse: String, + }, + "validation-enabled": { + kind: "boolean", + brief: "An indicator if this schema is enabled", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Upload a schema", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security schema-validation schemas create", - classification: { - safeFlags: ["kind", "validation-enabled", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["kind"] === undefined) { - argv["kind"] = await promptForRequiredEnumField( - "kind", - "The kind of the schema", - ["openapi_v3"] as const - ); - } - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "A human-readable name for the schema" - ); - } - if (argv["source"] === undefined) { - argv["source"] = await promptForRequiredField( - "source", - "The raw schema, e.g., the OpenAPI schema, either as JSON or YAML" - ); - } - if (argv["validation-enabled"] === undefined) { - throw new Error( - "--validation-enabled is required (or pass --body with this field set)." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - formatDryRun({ - command: "cf api-security schema-validation schemas create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/schemas`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - kind: argv["kind"], - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - source: resolveFileToken( - argv["source"] as string | undefined, - "source", - "text" - ), - validation_enabled: argv["validation-enabled"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - kind: argv["kind"], - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - source: resolveFileToken( - argv["source"] as string | undefined, - "source", - "text" - ), - validation_enabled: argv["validation-enabled"], - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 api-security schema-validation schemas create\n\nUploads an OpenAPI schema that defines expected request formats for API operations.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/delete.handler.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/delete.handler.ts new file mode 100644 index 0000000000..8557a19383 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/delete.handler.ts @@ -0,0 +1,59 @@ +import operation from "../../../_operations/api-security/schema-validation/schemas/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security schema-validation schemas delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf api-security schema-validation schemas delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/schemas/${argv["schema-id"] == null ? "" : encodeURIComponent(String(argv["schema-id"]))}`, + pathParams: { + "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), + "schema-id": String(argv["schema-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This operation permanently deletes the uploaded schema and removes its validation coverage.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + zone_id: zoneId, + schema_id: argv["schema-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/delete.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/delete.ts index 3b92c81f82..7e289e9146 100644 --- a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/delete.ts +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/delete.ts @@ -1,95 +1,43 @@ -import operation from "../../../_operations/api-security/schema-validation/schemas/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security schema-validation schemas delete \n\nPermanently removes an uploaded OpenAPI schema from API Security. Operations using this schema will lose their validation rules." - ) - .positional("schema-id", { - type: "string", - description: "The unique identifier of the schema", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "schema-id", + brief: "The unique identifier of the schema", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete a schema", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security schema-validation schemas delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf api-security schema-validation schemas delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/schemas/${argv["schema-id"] == null ? "" : encodeURIComponent(String(argv["schema-id"]))}`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - "schema-id": String(argv["schema-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This operation permanently deletes the uploaded schema and removes its validation coverage.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - zone_id: zoneId, - schema_id: argv["schema-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 api-security schema-validation schemas delete \n\nPermanently removes an uploaded OpenAPI schema from API Security. Operations using this schema will lose their validation rules.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/get.handler.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/get.handler.ts new file mode 100644 index 0000000000..137dc8e9d4 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/get.handler.ts @@ -0,0 +1,53 @@ +import operation from "../../../_operations/api-security/schema-validation/schemas/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security schema-validation schemas get", + classification: { + safeFlags: ["omit-source", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + omit_source: argv["omit-source"], + }; + if (argv.dryRun) { + formatDryRun({ + command: "cf api-security schema-validation schemas get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/schemas/${argv["schema-id"] == null ? "" : encodeURIComponent(String(argv["schema-id"]))}`, + pathParams: { + "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), + "schema-id": String(argv["schema-id"] ?? ""), + }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + zone_id: zoneId, + schema_id: argv["schema-id"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/get.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/get.ts index 682827168c..36aa11f875 100644 --- a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/get.ts +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/get.ts @@ -1,88 +1,43 @@ -import operation from "../../../_operations/api-security/schema-validation/schemas/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security schema-validation schemas get \n\nGets the contents and metadata of a specific OpenAPI schema uploaded to API Security." - ) - .positional("schema-id", { - type: "string", - description: "The unique identifier of the schema", - demandOption: true, - }) - .option("omit-source", { - type: "boolean", - description: +const parameters = { + flags: { + "omit-source": { + kind: "boolean", + brief: "Omit the source-files of schemas and only retrieve their meta-data.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "schema-id", + brief: "The unique identifier of the schema", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get details of a schema", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security schema-validation schemas get", - classification: { - safeFlags: ["omit-source", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - omit_source: argv["omit-source"], - }; - if (argv.dryRun) { - formatDryRun({ - command: "cf api-security schema-validation schemas get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/schemas/${argv["schema-id"] == null ? "" : encodeURIComponent(String(argv["schema-id"]))}`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - "schema-id": String(argv["schema-id"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - zone_id: zoneId, - schema_id: argv["schema-id"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 api-security schema-validation schemas get \n\nGets the contents and metadata of a specific OpenAPI schema uploaded to API Security.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/hosts/index.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/hosts/index.ts index 47935aa5de..d790f62e6c 100644 --- a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/hosts/index.ts +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/hosts/index.ts @@ -1,20 +1,17 @@ import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * hosts command group * @generated from apis/overlays/api-security.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "hosts", describe: "Operations for schema-validation.schemas.hosts", - builder: (yargs) => { - return yargs.command($list).demandCommand(1, "Please specify a subcommand"); + routes: { + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/hosts/list.handler.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/hosts/list.handler.ts new file mode 100644 index 0000000000..aa46a998b1 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/hosts/list.handler.ts @@ -0,0 +1,47 @@ +import operation from "../../../../_operations/api-security/schema-validation/schemas/hosts/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security schema-validation schemas hosts list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + }; + if (argv.dryRun) { + formatDryRun({ + command: "cf api-security schema-validation schemas hosts list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/schemas/hosts`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { zone_id: zoneId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/hosts/list.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/hosts/list.ts index 013ed8d38f..09afe8b104 100644 --- a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/hosts/list.ts +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/hosts/list.ts @@ -1,82 +1,43 @@ -import operation from "../../../../_operations/api-security/schema-validation/schemas/hosts/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security schema-validation schemas hosts list\n\nLists all unique hosts found in uploaded OpenAPI schemas for the zone." - ) - .option("page", { - type: "number", - description: "Page number of paginated results.", - }) - .option("per-page", { - type: "number", - description: "Maximum number of results per page.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + page: { + kind: "parsed", + brief: "Page number of paginated results.", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Maximum number of results per page.", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List hosts covered by uploaded schemas", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security schema-validation schemas hosts list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - }; - if (argv.dryRun) { - formatDryRun({ - command: "cf api-security schema-validation schemas hosts list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/schemas/hosts`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { zone_id: zoneId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 api-security schema-validation schemas hosts list\n\nLists all unique hosts found in uploaded OpenAPI schemas for the zone.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/index.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/index.ts index 2d61778488..d85ae19d44 100644 --- a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/index.ts +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/index.ts @@ -5,30 +5,25 @@ import $hosts from "./hosts/index.js"; import $list from "./list.js"; import $operations from "./operations/index.js"; import $setvalidation from "./set-validation.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * schemas command group * @generated from apis/overlays/api-security.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "schemas", describe: "Operations for schema-validation.schemas", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .command($list) - .command($setvalidation) - .command($hosts) - .command($operations) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, + list: $list, + "set-validation": $setvalidation, + hosts: $hosts, + operations: $operations, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/list.handler.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/list.handler.ts new file mode 100644 index 0000000000..dadd4f7add --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/list.handler.ts @@ -0,0 +1,49 @@ +import operation from "../../../_operations/api-security/schema-validation/schemas/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security schema-validation schemas list", + classification: { + safeFlags: ["omit-source", "validation-enabled", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + omit_source: argv["omit-source"], + validation_enabled: argv["validation-enabled"], + }; + if (argv.dryRun) { + formatDryRun({ + command: "cf api-security schema-validation schemas list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/schemas`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { zone_id: zoneId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/list.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/list.ts index 9fdc4a26ea..42b5297dd9 100644 --- a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/list.ts +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/list.ts @@ -1,93 +1,54 @@ -import operation from "../../../_operations/api-security/schema-validation/schemas/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security schema-validation schemas list\n\nLists all OpenAPI schemas uploaded to API Security." - ) - .option("page", { - type: "number", - description: "Page number of paginated results.", - }) - .option("per-page", { - type: "number", - description: "Maximum number of results per page.", - }) - .option("omit-source", { - type: "boolean", - description: +const parameters = { + flags: { + page: { + kind: "parsed", + brief: "Page number of paginated results.", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Maximum number of results per page.", + optional: true, + parse: Number, + }, + "omit-source": { + kind: "boolean", + brief: "Omit the source-files of schemas and only retrieve their meta-data.", - }) - .option("validation-enabled", { - type: "boolean", - description: "Filter for enabled schemas", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + }, + "validation-enabled": { + kind: "boolean", + brief: "Filter for enabled schemas", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List all uploaded schemas", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security schema-validation schemas list", - classification: { - safeFlags: ["omit-source", "validation-enabled", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - omit_source: argv["omit-source"], - validation_enabled: argv["validation-enabled"], - }; - if (argv.dryRun) { - formatDryRun({ - command: "cf api-security schema-validation schemas list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/schemas`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { zone_id: zoneId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 api-security schema-validation schemas list\n\nLists all OpenAPI schemas uploaded to API Security.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/operations/index.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/operations/index.ts index 1c896de70b..4c6cf8d09e 100644 --- a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/operations/index.ts +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/operations/index.ts @@ -1,20 +1,17 @@ import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * operations command group * @generated from apis/overlays/api-security.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "operations", describe: "Operations for schema-validation.schemas.operations", - builder: (yargs) => { - return yargs.command($list).demandCommand(1, "Please specify a subcommand"); + routes: { + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/operations/list.handler.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/operations/list.handler.ts new file mode 100644 index 0000000000..571ac0824a --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/operations/list.handler.ts @@ -0,0 +1,59 @@ +import operation from "../../../../_operations/api-security/schema-validation/schemas/operations/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security schema-validation schemas operations list", + classification: { + safeFlags: ["operation-status", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + feature: argv["feature"], + host: argv["host"], + method: argv["method"], + endpoint: argv["endpoint"], + page: argv["page"], + per_page: argv["per-page"], + operation_status: argv["operation-status"], + }; + if (argv.dryRun) { + formatDryRun({ + command: "cf api-security schema-validation schemas operations list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/schemas/${argv["schema-id"] == null ? "" : encodeURIComponent(String(argv["schema-id"]))}/operations`, + pathParams: { + "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), + "schema-id": String(argv["schema-id"] ?? ""), + }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + zone_id: zoneId, + schema_id: argv["schema-id"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/operations/list.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/operations/list.ts index e56ed7acfe..95c77d75d4 100644 --- a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/operations/list.ts +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/operations/list.ts @@ -1,134 +1,91 @@ -import operation from "../../../../_operations/api-security/schema-validation/schemas/operations/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security schema-validation schemas operations list\n\nRetrieves all operations from the schema. Operations that already exist in API Shield Endpoint Management will be returned as full operations." - ) - .option("schema-id", { - type: "string", - description: "The unique identifier of the schema", - demandOption: true, - }) - .option("feature", { - type: "string", - array: true, - description: +const parameters = { + flags: { + "schema-id": { + kind: "parsed", + brief: "The unique identifier of the schema", + parse: String, + }, + feature: { + kind: "parsed", + brief: "Add feature(s) to the results. The feature name that is given here corresponds to the resulting feature object. Have a look at the top-level object description for more details on the specific meaning.", + variadic: true, + optional: true, choices: [ "thresholds", "parameter_schemas", "schema_info", "confidence_intervals", ], - }) - .coerce("feature", (values: string[]) => - values.flatMap((value) => value.split(",")) - ) - .option("host", { - type: "string", - array: true, - description: "Filter results to only include the specified hosts.", - }) - .option("method", { - type: "string", - array: true, - description: "Filter results to only include the specified HTTP methods.", - }) - .option("endpoint", { - type: "string", - description: + parse: String, + coerce: (values: string[]) => values.flatMap((value) => value.split(",")), + }, + host: { + kind: "parsed", + brief: "Filter results to only include the specified hosts.", + variadic: true, + optional: true, + parse: String, + }, + method: { + kind: "parsed", + brief: "Filter results to only include the specified HTTP methods.", + variadic: true, + optional: true, + parse: String, + }, + endpoint: { + kind: "parsed", + brief: "Filter results to only include endpoints containing this pattern.", - }) - .option("page", { - type: "number", - description: "Page number of paginated results.", - }) - .option("per-page", { - type: "number", - description: "Maximum number of results per page.", - }) - .option("operation-status", { - type: "string", - description: + optional: true, + parse: String, + }, + page: { + kind: "parsed", + brief: "Page number of paginated results.", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Maximum number of results per page.", + optional: true, + parse: Number, + }, + "operation-status": { + kind: "enum", + brief: "Filter results by whether operations exist in Web Asset Management or not. `new` will just return operations from the schema that do not exist otherwise. `existing` will just return operations from the schema that already exist.", - choices: ["new", "existing"], - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + values: ["new", "existing"], + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "Retrieve all operations from the schema", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security schema-validation schemas operations list", - classification: { - safeFlags: ["operation-status", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - feature: argv["feature"], - host: argv["host"], - method: argv["method"], - endpoint: argv["endpoint"], - page: argv["page"], - per_page: argv["per-page"], - operation_status: argv["operation-status"], - }; - if (argv.dryRun) { - formatDryRun({ - command: - "cf api-security schema-validation schemas operations list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/schemas/${argv["schema-id"] == null ? "" : encodeURIComponent(String(argv["schema-id"]))}/operations`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - "schema-id": String(argv["schema-id"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - zone_id: zoneId, - schema_id: argv["schema-id"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 api-security schema-validation schemas operations list\n\nRetrieves all operations from the schema. Operations that already exist in API Shield Endpoint Management will be returned as full operations.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/set-validation.handler.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/set-validation.handler.ts new file mode 100644 index 0000000000..9904cba8f8 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/set-validation.handler.ts @@ -0,0 +1,75 @@ +import operation from "../../../_operations/api-security/schema-validation/schemas/set-validation.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./set-validation.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security schema-validation schemas set-validation", + classification: { + safeFlags: ["validation-enabled", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf api-security schema-validation schemas set-validation", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/schemas/${argv["schema-id"] == null ? "" : encodeURIComponent(String(argv["schema-id"]))}`, + pathParams: { + "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), + "schema-id": String(argv["schema-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + validation_enabled: argv["validation-enabled"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + zone_id: zoneId, + schema_id: argv["schema-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + validation_enabled: argv["validation-enabled"], + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + zone_id: zoneId, + schema_id: argv["schema-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/set-validation.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/set-validation.ts index b3963c5c81..f655335184 100644 --- a/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/set-validation.ts +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/schemas/set-validation.ts @@ -1,113 +1,48 @@ -import operation from "../../../_operations/api-security/schema-validation/schemas/set-validation.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * set-validation command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security schema-validation schemas set-validation \n\nEnables or disables validation for an uploaded OpenAPI schema without changing the schema document." - ) - .positional("schema-id", { - type: "string", - description: "The unique identifier of the schema", - demandOption: true, - }) - .option("validation-enabled", { - type: "boolean", - description: "Flag whether schema is enabled for validation.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "validation-enabled": { + kind: "boolean", + brief: "Flag whether schema is enabled for validation.", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "schema-id", + brief: "The unique identifier of the schema", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "set-validation ", describe: "Set schema validation state", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security schema-validation schemas set-validation", - classification: { - safeFlags: ["validation-enabled", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf api-security schema-validation schemas set-validation", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/schemas/${argv["schema-id"] == null ? "" : encodeURIComponent(String(argv["schema-id"]))}`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - "schema-id": String(argv["schema-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - validation_enabled: argv["validation-enabled"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - zone_id: zoneId, - schema_id: argv["schema-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - validation_enabled: argv["validation-enabled"], - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - zone_id: zoneId, - schema_id: argv["schema-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 api-security schema-validation schemas set-validation \n\nEnables or disables validation for an uploaded OpenAPI schema without changing the schema document.", + ...parameters, + loader: () => import("./set-validation.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/edit.handler.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/edit.handler.ts new file mode 100644 index 0000000000..2127b25dcc --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/edit.handler.ts @@ -0,0 +1,74 @@ +import operation from "../../../_operations/api-security/schema-validation/settings/edit.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./edit.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security schema-validation settings edit", + classification: { + safeFlags: [ + "validation-default-mitigation-action", + "validation-override-mitigation-action", + "dry-run", + ], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf api-security schema-validation settings edit", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/settings`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + validation_default_mitigation_action: + argv["validation-default-mitigation-action"], + validation_override_mitigation_action: + argv["validation-override-mitigation-action"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + validation_default_mitigation_action: + argv["validation-default-mitigation-action"], + validation_override_mitigation_action: + argv["validation-override-mitigation-action"], + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/edit.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/edit.ts index 75871ece07..71800fe542 100644 --- a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/edit.ts +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/edit.ts @@ -1,124 +1,62 @@ -import operation from "../../../_operations/api-security/schema-validation/settings/edit.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * edit command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security schema-validation settings edit\n\nPartially updates global schema validation settings for a zone using PATCH semantics." - ) - .option("validation-default-mitigation-action", { - type: "string", - description: +const parameters = { + flags: { + "validation-default-mitigation-action": { + kind: "parsed", + brief: 'The default mitigation action used\nMitigation actions are as follows:\n\n - `"log"` - log request when request does not conform to schema\n - `"block"` - deny access to the site when request does not conform to schema\n - `"none"` - skip running schema validation\n', + optional: true, choices: ["none", "log", "block"], - }) - .coerce("validation-default-mitigation-action", (value) => - resolveFileToken(value, "validation-default-mitigation-action", "text") - ) - .option("validation-override-mitigation-action", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "validation-default-mitigation-action", "text"), + }, + "validation-override-mitigation-action": { + kind: "parsed", + brief: 'When set, this overrides both zone level and operation level mitigation actions.\n\n - `"none"` - skip running schema validation entirely for the request\n - `null` - clears any existing override\n', + optional: true, choices: ["none"], - }) - .coerce("validation-override-mitigation-action", (value) => - resolveFileToken(value, "validation-override-mitigation-action", "text") - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "validation-override-mitigation-action", + "text" + ), + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "edit", describe: "Edit global schema validation settings", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security schema-validation settings edit", - classification: { - safeFlags: [ - "validation-default-mitigation-action", - "validation-override-mitigation-action", - "dry-run", - ], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf api-security schema-validation settings edit", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/settings`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - validation_default_mitigation_action: - argv["validation-default-mitigation-action"], - validation_override_mitigation_action: - argv["validation-override-mitigation-action"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - validation_default_mitigation_action: - argv["validation-default-mitigation-action"], - validation_override_mitigation_action: - argv["validation-override-mitigation-action"], - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 api-security schema-validation settings edit\n\nPartially updates global schema validation settings for a zone using PATCH semantics.", + ...parameters, + loader: () => import("./edit.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/get.handler.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/get.handler.ts new file mode 100644 index 0000000000..12dd637d91 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/get.handler.ts @@ -0,0 +1,42 @@ +import operation from "../../../_operations/api-security/schema-validation/settings/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security schema-validation settings get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf api-security schema-validation settings get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/settings`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/get.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/get.ts index 3186233b62..89471200cb 100644 --- a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/get.ts +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/get.ts @@ -1,69 +1,31 @@ -import operation from "../../../_operations/api-security/schema-validation/settings/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security schema-validation settings get\n\nRetrieves the current global schema validation settings for a zone." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "Get global schema validation settings", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security schema-validation settings get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf api-security schema-validation settings get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/settings`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 api-security schema-validation settings get\n\nRetrieves the current global schema validation settings for a zone.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/index.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/index.ts index 8c8ee5e1b3..b188c7f73e 100644 --- a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/index.ts +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/index.ts @@ -2,27 +2,22 @@ import $edit from "./edit.js"; import $get from "./get.js"; import $operations from "./operations/index.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * settings command group * @generated from apis/overlays/api-security.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "settings", describe: "Operations for schema-validation.settings", - builder: (yargs) => { - return yargs - .command($edit) - .command($get) - .command($update) - .command($operations) - .demandCommand(1, "Please specify a subcommand"); + routes: { + edit: $edit, + get: $get, + update: $update, + operations: $operations, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/bulk-edit.handler.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/bulk-edit.handler.ts new file mode 100644 index 0000000000..ddb44b6123 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/bulk-edit.handler.ts @@ -0,0 +1,60 @@ +import operation from "../../../../_operations/api-security/schema-validation/settings/operations/bulk-edit.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./bulk-edit.js"; +import { createCommandClient, getZoneId, requestApi } from "#lib/auth.js"; +import { parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security schema-validation settings operations bulk-edit", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: + "cf api-security schema-validation settings operations bulk-edit", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/settings/operations`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "json", + body: argv.body !== undefined ? parseBody(argv.body) : undefined, + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + const result = await withProgress(`Updating`, async () => + requestApi( + client, + "PATCH", + `/zones/${argv.zoneId}/schema_validation/settings/operations` + ) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/bulk-edit.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/bulk-edit.ts index dbb0a8a962..11653a054c 100644 --- a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/bulk-edit.ts +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/bulk-edit.ts @@ -1,91 +1,37 @@ -import operation from "../../../../_operations/api-security/schema-validation/settings/operations/bulk-edit.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * bulk-edit command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId, requestApi } from "#lib/auth.js"; -import { parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security schema-validation settings operations bulk-edit\n\nUpdates schema validation settings for multiple API operations in a single request. Efficient for applying consistent validation rules across endpoints." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "bulk-edit", describe: "Bulk edit per-operation schema validation settings", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security schema-validation settings operations bulk-edit", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: - "cf api-security schema-validation settings operations bulk-edit", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/settings/operations`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "json", - body: argv.body !== undefined ? parseBody(argv.body) : undefined, - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - const result = await withProgress(`Updating`, async () => - requestApi( - client, - "PATCH", - `/zones/${argv.zoneId}/schema_validation/settings/operations` - ) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 api-security schema-validation settings operations bulk-edit\n\nUpdates schema validation settings for multiple API operations in a single request. Efficient for applying consistent validation rules across endpoints.", + ...parameters, + loader: () => import("./bulk-edit.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/delete.handler.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/delete.handler.ts new file mode 100644 index 0000000000..14d5d001fc --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/delete.handler.ts @@ -0,0 +1,60 @@ +import operation from "../../../../_operations/api-security/schema-validation/settings/operations/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security schema-validation settings operations delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: + "cf api-security schema-validation settings operations delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/settings/operations/${argv["operation-id"] == null ? "" : encodeURIComponent(String(argv["operation-id"]))}`, + pathParams: { + "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), + "operation-id": String(argv["operation-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This operation deletes the operation-specific schema validation setting and restores the zone default.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + zone_id: zoneId, + operation_id: argv["operation-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/delete.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/delete.ts index a36b34e337..75c5a27a40 100644 --- a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/delete.ts +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/delete.ts @@ -1,96 +1,43 @@ -import operation from "../../../../_operations/api-security/schema-validation/settings/operations/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security schema-validation settings operations delete \n\nRemoves custom schema validation settings for a specific API operation, reverting to zone-level defaults." - ) - .positional("operation-id", { - type: "string", - description: "Identifier for the operation", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "operation-id", + brief: "Identifier for the operation", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete per-operation schema validation setting", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security schema-validation settings operations delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: - "cf api-security schema-validation settings operations delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/settings/operations/${argv["operation-id"] == null ? "" : encodeURIComponent(String(argv["operation-id"]))}`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - "operation-id": String(argv["operation-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This operation deletes the operation-specific schema validation setting and restores the zone default.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - zone_id: zoneId, - operation_id: argv["operation-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 api-security schema-validation settings operations delete \n\nRemoves custom schema validation settings for a specific API operation, reverting to zone-level defaults.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/get.handler.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/get.handler.ts new file mode 100644 index 0000000000..338f206fc8 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/get.handler.ts @@ -0,0 +1,48 @@ +import operation from "../../../../_operations/api-security/schema-validation/settings/operations/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security schema-validation settings operations get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf api-security schema-validation settings operations get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/settings/operations/${argv["operation-id"] == null ? "" : encodeURIComponent(String(argv["operation-id"]))}`, + pathParams: { + "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), + "operation-id": String(argv["operation-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + zone_id: zoneId, + operation_id: argv["operation-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/get.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/get.ts index 14b4d8d910..f057601d1a 100644 --- a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/get.ts +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/get.ts @@ -1,79 +1,37 @@ -import operation from "../../../../_operations/api-security/schema-validation/settings/operations/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security schema-validation settings operations get \n\nRetrieves the schema validation settings configured for a specific API operation." - ) - .positional("operation-id", { - type: "string", - description: "Identifier for the operation", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "operation-id", + brief: "Identifier for the operation", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get per-operation schema validation setting", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security schema-validation settings operations get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: - "cf api-security schema-validation settings operations get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/settings/operations/${argv["operation-id"] == null ? "" : encodeURIComponent(String(argv["operation-id"]))}`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - "operation-id": String(argv["operation-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - zone_id: zoneId, - operation_id: argv["operation-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 api-security schema-validation settings operations get \n\nRetrieves the schema validation settings configured for a specific API operation.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/index.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/index.ts index 9d7dbcfc26..bac8e1b3d4 100644 --- a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/index.ts +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/index.ts @@ -3,28 +3,23 @@ import $delete from "./delete.js"; import $get from "./get.js"; import $list from "./list.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * operations command group * @generated from apis/overlays/api-security.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "operations", describe: "Operations for schema-validation.settings.operations", - builder: (yargs) => { - return yargs - .command($bulkedit) - .command($delete) - .command($get) - .command($list) - .command($update) - .demandCommand(1, "Please specify a subcommand"); + routes: { + "bulk-edit": $bulkedit, + delete: $delete, + get: $get, + list: $list, + update: $update, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/list.handler.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/list.handler.ts new file mode 100644 index 0000000000..defbcac304 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/list.handler.ts @@ -0,0 +1,47 @@ +import operation from "../../../../_operations/api-security/schema-validation/settings/operations/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security schema-validation settings operations list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + }; + if (argv.dryRun) { + formatDryRun({ + command: "cf api-security schema-validation settings operations list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/settings/operations`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { zone_id: zoneId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/list.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/list.ts index cfb861e177..bcfa60966c 100644 --- a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/list.ts +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/list.ts @@ -1,83 +1,43 @@ -import operation from "../../../../_operations/api-security/schema-validation/settings/operations/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security schema-validation settings operations list\n\nLists per-operation schema validation settings configured for the zone." - ) - .option("page", { - type: "number", - description: "Page number of paginated results.", - }) - .option("per-page", { - type: "number", - description: "Maximum number of results per page.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + page: { + kind: "parsed", + brief: "Page number of paginated results.", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Maximum number of results per page.", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List per-operation schema validation settings", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security schema-validation settings operations list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - }; - if (argv.dryRun) { - formatDryRun({ - command: - "cf api-security schema-validation settings operations list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/settings/operations`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { zone_id: zoneId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 api-security schema-validation settings operations list\n\nLists per-operation schema validation settings configured for the zone.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/update.handler.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/update.handler.ts new file mode 100644 index 0000000000..c3377c4cc0 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/update.handler.ts @@ -0,0 +1,90 @@ +import operation from "../../../../_operations/api-security/schema-validation/settings/operations/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredEnumField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security schema-validation settings operations update", + classification: { + safeFlags: ["mitigation-action", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["mitigation-action"] === undefined) { + argv["mitigation-action"] = await promptForRequiredEnumField( + "mitigation-action", + 'When set, this applies a mitigation action to this operation - \`"log"\` - log request when request does not conform to schema for this operation - \`"block"\` - deny access to the site when request does not conform to schema for this operation - \`"none"\` - will skip mitigation for this operation - \`null\` - clears any mitigation action ', + ["log", "block", "none"] as const + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + formatDryRun({ + command: + "cf api-security schema-validation settings operations update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/settings/operations/${argv["operation-id"] == null ? "" : encodeURIComponent(String(argv["operation-id"]))}`, + pathParams: { + "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), + "operation-id": String(argv["operation-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + mitigation_action: argv["mitigation-action"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + zone_id: zoneId, + operation_id: argv["operation-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + mitigation_action: argv["mitigation-action"], + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + zone_id: zoneId, + operation_id: argv["operation-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/update.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/update.ts index 300aa74fd0..eb3769d824 100644 --- a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/update.ts +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/operations/update.ts @@ -1,134 +1,54 @@ -import operation from "../../../../_operations/api-security/schema-validation/settings/operations/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredEnumField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security schema-validation settings operations update \n\nFully updates schema validation settings for a specific API operation." - ) - .positional("operation-id", { - type: "string", - description: "Identifier for the operation", - demandOption: true, - }) - .option("mitigation-action", { - type: "string", - description: +const parameters = { + flags: { + "mitigation-action": { + kind: "parsed", + brief: 'When set, this applies a mitigation action to this operation\n\n - `"log"` - log request when request does not conform to schema for this operation\n - `"block"` - deny access to the site when request does not conform to schema for this operation\n - `"none"` - will skip mitigation for this operation\n - `null` - clears any mitigation action\n', + optional: true, choices: ["log", "block", "none"], - }) - .coerce("mitigation-action", (value) => - resolveFileToken(value, "mitigation-action", "text") - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "mitigation-action", "text"), + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "operation-id", + brief: "Identifier for the operation", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update ", describe: "Update per-operation schema validation setting", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security schema-validation settings operations update", - classification: { - safeFlags: ["mitigation-action", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["mitigation-action"] === undefined) { - argv["mitigation-action"] = await promptForRequiredEnumField( - "mitigation-action", - 'When set, this applies a mitigation action to this operation - \`"log"\` - log request when request does not conform to schema for this operation - \`"block"\` - deny access to the site when request does not conform to schema for this operation - \`"none"\` - will skip mitigation for this operation - \`null\` - clears any mitigation action ', - ["log", "block", "none"] as const - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - formatDryRun({ - command: - "cf api-security schema-validation settings operations update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/settings/operations/${argv["operation-id"] == null ? "" : encodeURIComponent(String(argv["operation-id"]))}`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - "operation-id": String(argv["operation-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - mitigation_action: argv["mitigation-action"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - zone_id: zoneId, - operation_id: argv["operation-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - mitigation_action: argv["mitigation-action"], - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - zone_id: zoneId, - operation_id: argv["operation-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 api-security schema-validation settings operations update \n\nFully updates schema validation settings for a specific API operation.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/update.handler.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/update.handler.ts new file mode 100644 index 0000000000..81e3fe7c39 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/update.handler.ts @@ -0,0 +1,89 @@ +import operation from "../../../_operations/api-security/schema-validation/settings/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredEnumField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security schema-validation settings update", + classification: { + safeFlags: [ + "validation-default-mitigation-action", + "validation-override-mitigation-action", + "dry-run", + ], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["validation-default-mitigation-action"] === undefined) { + argv["validation-default-mitigation-action"] = + await promptForRequiredEnumField( + "validation-default-mitigation-action", + 'The default mitigation action used Mitigation actions are as follows: - \`"log"\` - log request when request does not conform to schema - \`"block"\` - deny access to the site when request does not conform to schema - \`"none"\` - skip running schema validation ', + ["none", "log", "block"] as const + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + formatDryRun({ + command: "cf api-security schema-validation settings update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/settings`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + validation_default_mitigation_action: + argv["validation-default-mitigation-action"], + validation_override_mitigation_action: + argv["validation-override-mitigation-action"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + validation_default_mitigation_action: + argv["validation-default-mitigation-action"], + validation_override_mitigation_action: + argv["validation-override-mitigation-action"], + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/update.ts b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/update.ts index 202a20db49..379b69fa50 100644 --- a/packages/cli/src/commands/_generated/api-security/schema-validation/settings/update.ts +++ b/packages/cli/src/commands/_generated/api-security/schema-validation/settings/update.ts @@ -1,139 +1,62 @@ -import operation from "../../../_operations/api-security/schema-validation/settings/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredEnumField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security schema-validation settings update\n\nFully updates global schema validation settings for a zone, replacing existing configuration." - ) - .option("validation-default-mitigation-action", { - type: "string", - description: +const parameters = { + flags: { + "validation-default-mitigation-action": { + kind: "parsed", + brief: 'The default mitigation action used\nMitigation actions are as follows:\n\n - `"log"` - log request when request does not conform to schema\n - `"block"` - deny access to the site when request does not conform to schema\n - `"none"` - skip running schema validation\n', + optional: true, choices: ["none", "log", "block"], - }) - .coerce("validation-default-mitigation-action", (value) => - resolveFileToken(value, "validation-default-mitigation-action", "text") - ) - .option("validation-override-mitigation-action", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "validation-default-mitigation-action", "text"), + }, + "validation-override-mitigation-action": { + kind: "parsed", + brief: 'When set, this overrides both zone level and operation level mitigation actions.\n\n - `"none"` - skip running schema validation entirely for the request\n - `null` - clears any existing override\n', + optional: true, choices: ["none"], - }) - .coerce("validation-override-mitigation-action", (value) => - resolveFileToken(value, "validation-override-mitigation-action", "text") - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => + resolveFileToken( + value, + "validation-override-mitigation-action", + "text" + ), + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update", describe: "Update global schema validation settings", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security schema-validation settings update", - classification: { - safeFlags: [ - "validation-default-mitigation-action", - "validation-override-mitigation-action", - "dry-run", - ], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["validation-default-mitigation-action"] === undefined) { - argv["validation-default-mitigation-action"] = - await promptForRequiredEnumField( - "validation-default-mitigation-action", - 'The default mitigation action used Mitigation actions are as follows: - \`"log"\` - log request when request does not conform to schema - \`"block"\` - deny access to the site when request does not conform to schema - \`"none"\` - skip running schema validation ', - ["none", "log", "block"] as const - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - formatDryRun({ - command: "cf api-security schema-validation settings update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/schema_validation/settings`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - validation_default_mitigation_action: - argv["validation-default-mitigation-action"], - validation_override_mitigation_action: - argv["validation-override-mitigation-action"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - validation_default_mitigation_action: - argv["validation-default-mitigation-action"], - validation_override_mitigation_action: - argv["validation-override-mitigation-action"], - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 api-security schema-validation settings update\n\nFully updates global schema validation settings for a zone, replacing existing configuration.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/session-identifiers/get.handler.ts b/packages/cli/src/commands/_generated/api-security/session-identifiers/get.handler.ts new file mode 100644 index 0000000000..e9eb07031e --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/session-identifiers/get.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/api-security/session-identifiers/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security session-identifiers get", + classification: { + safeFlags: ["normalize", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + normalize: argv["normalize"], + }; + if (argv.dryRun) { + formatDryRun({ + command: "cf api-security session-identifiers get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/api_gateway/configuration`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { zone_id: zoneId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/session-identifiers/get.ts b/packages/cli/src/commands/_generated/api-security/session-identifiers/get.ts index 6248849bef..85fd907f63 100644 --- a/packages/cli/src/commands/_generated/api-security/session-identifiers/get.ts +++ b/packages/cli/src/commands/_generated/api-security/session-identifiers/get.ts @@ -1,78 +1,37 @@ -import operation from "../../_operations/api-security/session-identifiers/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security session-identifiers get\n\nReturns the authentication identifier characteristics configured for the zone. Header, cookie, or JWT claim values identify distinct API sessions." - ) - .option("normalize", { - type: "boolean", - description: +const parameters = { + flags: { + normalize: { + kind: "boolean", + brief: "Ensures that the configuration is written or retrieved in normalized fashion", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "Get session identifier settings", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security session-identifiers get", - classification: { - safeFlags: ["normalize", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - normalize: argv["normalize"], - }; - if (argv.dryRun) { - formatDryRun({ - command: "cf api-security session-identifiers get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/api_gateway/configuration`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { zone_id: zoneId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 api-security session-identifiers get\n\nReturns the authentication identifier characteristics configured for the zone. Header, cookie, or JWT claim values identify distinct API sessions.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/session-identifiers/index.ts b/packages/cli/src/commands/_generated/api-security/session-identifiers/index.ts index a93b886224..a27aee1e6a 100644 --- a/packages/cli/src/commands/_generated/api-security/session-identifiers/index.ts +++ b/packages/cli/src/commands/_generated/api-security/session-identifiers/index.ts @@ -1,24 +1,19 @@ import $get from "./get.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * session-identifiers command group * @generated from apis/overlays/api-security.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "session-identifiers", describe: "Operations for session-identifiers", - builder: (yargs) => { - return yargs - .command($get) - .command($update) - .demandCommand(1, "Please specify a subcommand"); + routes: { + get: $get, + update: $update, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/session-identifiers/update.handler.ts b/packages/cli/src/commands/_generated/api-security/session-identifiers/update.handler.ts new file mode 100644 index 0000000000..05168788a3 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/session-identifiers/update.handler.ts @@ -0,0 +1,103 @@ +import operation from "../../_operations/api-security/session-identifiers/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security session-identifiers update", + classification: { + safeFlags: ["normalize", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + normalize: argv["normalize"], + }; + const resolveRequiredFields = async (): Promise => { + if (argv["auth-id-characteristics"] === undefined) { + throw new Error( + "--auth-id-characteristics is required (or pass --body with this field set)." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + formatDryRun({ + command: "cf api-security session-identifiers update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/api_gateway/configuration`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + query: queryParams, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + auth_id_characteristics: parseObjectArray( + argv["auth-id-characteristics"], + "auth-id-characteristics" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const qs = new URLSearchParams( + Object.entries(queryParams) + .filter(([, v]) => v !== undefined) + .map(([k, v]) => [k, String(v)]) + ).toString(); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + zone_id: zoneId, + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + auth_id_characteristics: parseObjectArray( + argv["auth-id-characteristics"], + "auth-id-characteristics" + ), + }); + const qs = new URLSearchParams( + Object.entries(queryParams) + .filter(([, v]) => v !== undefined) + .map(([k, v]) => [k, String(v)]) + ).toString(); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + zone_id: zoneId, + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/session-identifiers/update.ts b/packages/cli/src/commands/_generated/api-security/session-identifiers/update.ts index 99a9eebe56..763ef83cce 100644 --- a/packages/cli/src/commands/_generated/api-security/session-identifiers/update.ts +++ b/packages/cli/src/commands/_generated/api-security/session-identifiers/update.ts @@ -1,144 +1,50 @@ -import operation from "../../_operations/api-security/session-identifiers/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security session-identifiers update\n\nReplaces the zone's authentication identifier characteristics used to identify distinct API sessions." - ) - .option("normalize", { - type: "boolean", - description: +const parameters = { + flags: { + normalize: { + kind: "boolean", + brief: "Ensures that the configuration is written or retrieved in normalized fashion", - }) - .option("auth-id-characteristics", { - type: "string", - description: + optional: true, + }, + "auth-id-characteristics": { + kind: "parsed", + brief: 'The auth_id_characteristics field. Provide as a JSON array of objects or @path/to/file.json. Shape: [({"name": string, "type": "header" | "cookie"} | {"name": string, "type": "jwt"})].', - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update", describe: "Update session identifier settings", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security session-identifiers update", - classification: { - safeFlags: ["normalize", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - normalize: argv["normalize"], - }; - const resolveRequiredFields = async (): Promise => { - if (argv["auth-id-characteristics"] === undefined) { - throw new Error( - "--auth-id-characteristics is required (or pass --body with this field set)." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - formatDryRun({ - command: "cf api-security session-identifiers update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/api_gateway/configuration`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - query: queryParams, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - auth_id_characteristics: parseObjectArray( - argv["auth-id-characteristics"], - "auth-id-characteristics" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const qs = new URLSearchParams( - Object.entries(queryParams) - .filter(([, v]) => v !== undefined) - .map(([k, v]) => [k, String(v)]) - ).toString(); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - zone_id: zoneId, - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - auth_id_characteristics: parseObjectArray( - argv["auth-id-characteristics"], - "auth-id-characteristics" - ), - }); - const qs = new URLSearchParams( - Object.entries(queryParams) - .filter(([, v]) => v !== undefined) - .map(([k, v]) => [k, String(v)]) - ).toString(); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - zone_id: zoneId, - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 api-security session-identifiers update\n\nReplaces the zone's authentication identifier characteristics used to identify distinct API sessions.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/create.handler.ts b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/create.handler.ts new file mode 100644 index 0000000000..24d7bba853 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/create.handler.ts @@ -0,0 +1,128 @@ +import operation from "../../../_operations/api-security/token-validation/configurations/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { + promptForRequiredEnumField, + promptForRequiredField, +} from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security token-validation configurations create", + classification: { + safeFlags: ["token-type", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["credentials-keys"] === undefined) { + throw new Error( + "--credentials-keys is required (or pass --body with this field set)." + ); + } + if (argv["description"] === undefined) { + argv["description"] = await promptForRequiredField( + "description", + "The description field" + ); + } + if (argv["title"] === undefined) { + argv["title"] = await promptForRequiredField( + "title", + "The title field" + ); + } + if (argv["token-type"] === undefined) { + argv["token-type"] = await promptForRequiredEnumField( + "token-type", + "The token_type field", + ["JWT"] as const + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + formatDryRun({ + command: "cf api-security token-validation configurations create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/config`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + credentials: { + keys: parseObjectArray( + argv["credentials-keys"], + "credentials-keys" + ), + }, + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + title: resolveFileToken( + argv["title"] as string | undefined, + "title", + "text" + ), + token_type: argv["token-type"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + credentials: { + keys: parseObjectArray(argv["credentials-keys"], "credentials-keys"), + }, + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + title: resolveFileToken( + argv["title"] as string | undefined, + "title", + "text" + ), + token_type: argv["token-type"], + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/create.ts b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/create.ts index f9a394d18d..594a8b72b1 100644 --- a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/create.ts +++ b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/create.ts @@ -1,180 +1,65 @@ -import operation from "../../../_operations/api-security/token-validation/configurations/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; import { - promptForRequiredEnumField, - promptForRequiredField, -} from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; +import { resolveFileToken } from "#lib/input-validation.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security token-validation configurations create\n\nCreates a JWT validation configuration for the zone." - ) - .option("credentials-keys", { - type: "string", - description: +const parameters = { + flags: { + "credentials-keys": { + kind: "parsed", + brief: 'The credentials.keys field. Provide as a JSON array of objects or @path/to/file.json. Shape: [(({"kid": string} & {"alg": "RS256" | "RS384" | "RS512" | ...more, "e": string, "kty": "RSA", "n": string}) | ({"kid": string} & {"kty": "EC", "x": string, "y": string} & {"alg": "ES256", "crv": "P-256"}) | ...more)].', - }) - .option("description", { - type: "string", - description: "The description field", - }) - .option("title", { type: "string", description: "The title field" }) - .option("token-type", { - type: "string", - description: "The token_type field", + optional: true, + parse: String, + }, + description: { + kind: "parsed", + brief: "The description field", + optional: true, + parse: String, + }, + title: { + kind: "parsed", + brief: "The title field", + optional: true, + parse: String, + }, + "token-type": { + kind: "parsed", + brief: "The token_type field", + optional: true, choices: ["JWT"], - }) - .coerce("token-type", (value) => - resolveFileToken(value, "token-type", "text") - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => resolveFileToken(value, "token-type", "text"), + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Create a token validation configuration", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security token-validation configurations create", - classification: { - safeFlags: ["token-type", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["credentials-keys"] === undefined) { - throw new Error( - "--credentials-keys is required (or pass --body with this field set)." - ); - } - if (argv["description"] === undefined) { - argv["description"] = await promptForRequiredField( - "description", - "The description field" - ); - } - if (argv["title"] === undefined) { - argv["title"] = await promptForRequiredField( - "title", - "The title field" - ); - } - if (argv["token-type"] === undefined) { - argv["token-type"] = await promptForRequiredEnumField( - "token-type", - "The token_type field", - ["JWT"] as const - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - formatDryRun({ - command: "cf api-security token-validation configurations create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/config`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - credentials: { - keys: parseObjectArray( - argv["credentials-keys"], - "credentials-keys" - ), - }, - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - title: resolveFileToken( - argv["title"] as string | undefined, - "title", - "text" - ), - token_type: argv["token-type"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - credentials: { - keys: parseObjectArray( - argv["credentials-keys"], - "credentials-keys" - ), - }, - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - title: resolveFileToken( - argv["title"] as string | undefined, - "title", - "text" - ), - token_type: argv["token-type"], - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 api-security token-validation configurations create\n\nCreates a JWT validation configuration for the zone.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/credentials/edit.handler.ts b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/credentials/edit.handler.ts new file mode 100644 index 0000000000..1edf9550cd --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/credentials/edit.handler.ts @@ -0,0 +1,87 @@ +import operation from "../../../../_operations/api-security/token-validation/configurations/credentials/edit.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./edit.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security token-validation configurations credentials edit", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["keys"] === undefined) { + throw new Error( + "--keys is required (or pass --body with this field set)." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + formatDryRun({ + command: + "cf api-security token-validation configurations credentials edit", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/config/${argv["config-id"] == null ? "" : encodeURIComponent(String(argv["config-id"]))}/credentials`, + pathParams: { + "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), + "config-id": String(argv["config-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + keys: parseObjectArray(argv["keys"], "keys"), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + zone_id: zoneId, + config_id: argv["config-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + keys: parseObjectArray(argv["keys"], "keys"), + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + zone_id: zoneId, + config_id: argv["config-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/credentials/edit.ts b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/credentials/edit.ts index 5f97a7a0d4..9dfd3bc1d9 100644 --- a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/credentials/edit.ts +++ b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/credentials/edit.ts @@ -1,128 +1,51 @@ -import operation from "../../../../_operations/api-security/token-validation/configurations/credentials/edit.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * edit command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security token-validation configurations credentials edit \n\nUpdates the configuration's complete key set while allowing omitted fields on existing keys to retain stored values. Omitted key identities are removed." - ) - .positional("config-id", { - type: "string", - description: "Token Configuration ID", - demandOption: true, - }) - .option("keys", { - type: "string", - description: +const parameters = { + flags: { + keys: { + kind: "parsed", + brief: 'The keys field. Provide as a JSON array of objects or @path/to/file.json. Shape: [(({"kid": string} & {"alg": "RS256" | "RS384" | "RS512" | ...more, "e": string, "kty": "RSA", "n": string}) | ({"kid": string} & {"kty": "EC", "x": string, "y": string} & {"alg": "ES256", "crv": "P-256"}) | ...more)].', - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: - "Request payload for PATCH credentials. Provided keys define the complete stored key set, and stored keys omitted from payload are removed. For each provided key identity (\`{alg,kid}\`), payload fields overwrite the stored key before validation and omitted fields inherit from the stored key. Key identities must be unique.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: + "Request payload for PATCH credentials. Provided keys define the complete stored key set, and stored keys omitted from payload are removed. For each provided key identity (`{alg,kid}`), payload fields overwrite the stored key before validation and omitted fields inherit from the stored key. Key identities must be unique.", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "config-id", + brief: "Token Configuration ID", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "edit ", describe: "Edit token validation credentials", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: - "api-security token-validation configurations credentials edit", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["keys"] === undefined) { - throw new Error( - "--keys is required (or pass --body with this field set)." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - formatDryRun({ - command: - "cf api-security token-validation configurations credentials edit", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/config/${argv["config-id"] == null ? "" : encodeURIComponent(String(argv["config-id"]))}/credentials`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - "config-id": String(argv["config-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - keys: parseObjectArray(argv["keys"], "keys"), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - zone_id: zoneId, - config_id: argv["config-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - keys: parseObjectArray(argv["keys"], "keys"), - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - zone_id: zoneId, - config_id: argv["config-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 api-security token-validation configurations credentials edit \n\nUpdates the configuration's complete key set while allowing omitted fields on existing keys to retain stored values. Omitted key identities are removed.", + ...parameters, + loader: () => import("./edit.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/credentials/index.ts b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/credentials/index.ts index b0069aa80c..e7e6c84a0f 100644 --- a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/credentials/index.ts +++ b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/credentials/index.ts @@ -1,24 +1,19 @@ import $edit from "./edit.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * credentials command group * @generated from apis/overlays/api-security.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "credentials", describe: "Operations for token-validation.configurations.credentials", - builder: (yargs) => { - return yargs - .command($edit) - .command($update) - .demandCommand(1, "Please specify a subcommand"); + routes: { + edit: $edit, + update: $update, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/credentials/update.handler.ts b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/credentials/update.handler.ts new file mode 100644 index 0000000000..12373cfcbc --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/credentials/update.handler.ts @@ -0,0 +1,88 @@ +import operation from "../../../../_operations/api-security/token-validation/configurations/credentials/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: + "api-security token-validation configurations credentials update", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["keys"] === undefined) { + throw new Error( + "--keys is required (or pass --body with this field set)." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + formatDryRun({ + command: + "cf api-security token-validation configurations credentials update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/config/${argv["config-id"] == null ? "" : encodeURIComponent(String(argv["config-id"]))}/credentials`, + pathParams: { + "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), + "config-id": String(argv["config-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + keys: parseObjectArray(argv["keys"], "keys"), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + zone_id: zoneId, + config_id: argv["config-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + keys: parseObjectArray(argv["keys"], "keys"), + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + zone_id: zoneId, + config_id: argv["config-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/credentials/update.ts b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/credentials/update.ts index 8a6284f2b5..b1ea56a584 100644 --- a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/credentials/update.ts +++ b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/credentials/update.ts @@ -1,128 +1,51 @@ -import operation from "../../../../_operations/api-security/token-validation/configurations/credentials/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security token-validation configurations credentials update \n\nReplaces the configuration's complete key set. Symmetric keys must include their key material." - ) - .positional("config-id", { - type: "string", - description: "Token Configuration ID", - demandOption: true, - }) - .option("keys", { - type: "string", - description: +const parameters = { + flags: { + keys: { + kind: "parsed", + brief: 'The keys field. Provide as a JSON array of objects or @path/to/file.json. Shape: [(({"kid": string} & {"alg": "RS256" | "RS384" | "RS512" | ...more, "e": string, "kty": "RSA", "n": string}) | ({"kid": string} & {"kty": "EC", "x": string, "y": string} & {"alg": "ES256", "crv": "P-256"}) | ...more)].', - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: - "Request payload for create and PUT credentials operations. Provided keys define the complete stored key set. Key identities (\`{alg,kid}\`) must be unique.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: + "Request payload for create and PUT credentials operations. Provided keys define the complete stored key set. Key identities (`{alg,kid}`) must be unique.", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "config-id", + brief: "Token Configuration ID", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update ", describe: "Replace token validation credentials", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: - "api-security token-validation configurations credentials update", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["keys"] === undefined) { - throw new Error( - "--keys is required (or pass --body with this field set)." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - formatDryRun({ - command: - "cf api-security token-validation configurations credentials update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/config/${argv["config-id"] == null ? "" : encodeURIComponent(String(argv["config-id"]))}/credentials`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - "config-id": String(argv["config-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - keys: parseObjectArray(argv["keys"], "keys"), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - zone_id: zoneId, - config_id: argv["config-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - keys: parseObjectArray(argv["keys"], "keys"), - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - zone_id: zoneId, - config_id: argv["config-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 api-security token-validation configurations credentials update \n\nReplaces the configuration's complete key set. Symmetric keys must include their key material.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/delete.handler.ts b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/delete.handler.ts new file mode 100644 index 0000000000..81ccf8a32c --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/delete.handler.ts @@ -0,0 +1,59 @@ +import operation from "../../../_operations/api-security/token-validation/configurations/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security token-validation configurations delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf api-security token-validation configurations delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/config/${argv["config-id"] == null ? "" : encodeURIComponent(String(argv["config-id"]))}`, + pathParams: { + "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), + "config-id": String(argv["config-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This operation deletes the token validation configuration. The request is rejected if rules, operations, or JWT authentication identifiers still reference it.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + zone_id: zoneId, + config_id: argv["config-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/delete.ts b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/delete.ts index 0290584eec..b52bcff654 100644 --- a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/delete.ts +++ b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/delete.ts @@ -1,95 +1,43 @@ -import operation from "../../../_operations/api-security/token-validation/configurations/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security token-validation configurations delete \n\nDeletes a JWT validation configuration from the zone." - ) - .positional("config-id", { - type: "string", - description: "Token Configuration ID", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "config-id", + brief: "Token Configuration ID", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete a token validation configuration", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security token-validation configurations delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf api-security token-validation configurations delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/config/${argv["config-id"] == null ? "" : encodeURIComponent(String(argv["config-id"]))}`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - "config-id": String(argv["config-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This operation deletes the token validation configuration. The request is rejected if rules, operations, or JWT authentication identifiers still reference it.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - zone_id: zoneId, - config_id: argv["config-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 api-security token-validation configurations delete \n\nDeletes a JWT validation configuration from the zone.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/edit.handler.ts b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/edit.handler.ts new file mode 100644 index 0000000000..618fde5284 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/edit.handler.ts @@ -0,0 +1,94 @@ +import operation from "../../../_operations/api-security/token-validation/configurations/edit.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./edit.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security token-validation configurations edit", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf api-security token-validation configurations edit", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/config/${argv["config-id"] == null ? "" : encodeURIComponent(String(argv["config-id"]))}`, + pathParams: { + "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), + "config-id": String(argv["config-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + title: resolveFileToken( + argv["title"] as string | undefined, + "title", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + zone_id: zoneId, + config_id: argv["config-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + title: resolveFileToken( + argv["title"] as string | undefined, + "title", + "text" + ), + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + zone_id: zoneId, + config_id: argv["config-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/edit.ts b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/edit.ts index 4181fcca27..5647418768 100644 --- a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/edit.ts +++ b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/edit.ts @@ -1,133 +1,55 @@ -import operation from "../../../_operations/api-security/token-validation/configurations/edit.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * edit command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security token-validation configurations edit \n\nUpdates only the supplied fields on a JWT validation configuration." - ) - .positional("config-id", { - type: "string", - description: "Token Configuration ID", - demandOption: true, - }) - .option("description", { - type: "string", - description: "The description field", - }) - .option("title", { type: "string", description: "The title field" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + description: { + kind: "parsed", + brief: "The description field", + optional: true, + parse: String, + }, + title: { + kind: "parsed", + brief: "The title field", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "config-id", + brief: "Token Configuration ID", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "edit ", describe: "Edit a token validation configuration", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security token-validation configurations edit", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf api-security token-validation configurations edit", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/config/${argv["config-id"] == null ? "" : encodeURIComponent(String(argv["config-id"]))}`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - "config-id": String(argv["config-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - title: resolveFileToken( - argv["title"] as string | undefined, - "title", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - zone_id: zoneId, - config_id: argv["config-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - title: resolveFileToken( - argv["title"] as string | undefined, - "title", - "text" - ), - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - zone_id: zoneId, - config_id: argv["config-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 api-security token-validation configurations edit \n\nUpdates only the supplied fields on a JWT validation configuration.", + ...parameters, + loader: () => import("./edit.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/get.handler.ts b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/get.handler.ts new file mode 100644 index 0000000000..e269e02460 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/get.handler.ts @@ -0,0 +1,48 @@ +import operation from "../../../_operations/api-security/token-validation/configurations/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security token-validation configurations get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf api-security token-validation configurations get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/config/${argv["config-id"] == null ? "" : encodeURIComponent(String(argv["config-id"]))}`, + pathParams: { + "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), + "config-id": String(argv["config-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + zone_id: zoneId, + config_id: argv["config-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/get.ts b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/get.ts index 21b25648e3..f41fa3facf 100644 --- a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/get.ts +++ b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/get.ts @@ -1,78 +1,37 @@ -import operation from "../../../_operations/api-security/token-validation/configurations/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security token-validation configurations get \n\nReturns a JWT validation configuration by ID." - ) - .positional("config-id", { - type: "string", - description: "Token Configuration ID", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "config-id", + brief: "Token Configuration ID", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get a token validation configuration", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security token-validation configurations get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf api-security token-validation configurations get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/config/${argv["config-id"] == null ? "" : encodeURIComponent(String(argv["config-id"]))}`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - "config-id": String(argv["config-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - zone_id: zoneId, - config_id: argv["config-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 api-security token-validation configurations get \n\nReturns a JWT validation configuration by ID.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/index.ts b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/index.ts index 1cb74de98c..72f2f3115b 100644 --- a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/index.ts +++ b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/index.ts @@ -4,29 +4,24 @@ import $delete from "./delete.js"; import $edit from "./edit.js"; import $get from "./get.js"; import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * configurations command group * @generated from apis/overlays/api-security.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "configurations", describe: "Operations for token-validation.configurations", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($edit) - .command($get) - .command($list) - .command($credentials) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + edit: $edit, + get: $get, + list: $list, + credentials: $credentials, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/list.handler.ts b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/list.handler.ts new file mode 100644 index 0000000000..58de8d273f --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/list.handler.ts @@ -0,0 +1,47 @@ +import operation from "../../../_operations/api-security/token-validation/configurations/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security token-validation configurations list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + }; + if (argv.dryRun) { + formatDryRun({ + command: "cf api-security token-validation configurations list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/config`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { zone_id: zoneId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/list.ts b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/list.ts index e4d5193b6c..937cf1e2ce 100644 --- a/packages/cli/src/commands/_generated/api-security/token-validation/configurations/list.ts +++ b/packages/cli/src/commands/_generated/api-security/token-validation/configurations/list.ts @@ -1,82 +1,43 @@ -import operation from "../../../_operations/api-security/token-validation/configurations/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security token-validation configurations list\n\nLists the JWT validation configurations defined for the zone." - ) - .option("page", { - type: "number", - description: "Page number of paginated results.", - }) - .option("per-page", { - type: "number", - description: "Maximum number of results per page.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + page: { + kind: "parsed", + brief: "Page number of paginated results.", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Maximum number of results per page.", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List token validation configurations", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security token-validation configurations list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - }; - if (argv.dryRun) { - formatDryRun({ - command: "cf api-security token-validation configurations list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/config`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { zone_id: zoneId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 api-security token-validation configurations list\n\nLists the JWT validation configurations defined for the zone.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/index.ts b/packages/cli/src/commands/_generated/api-security/token-validation/index.ts index e4c18c264f..a6d8b883ac 100644 --- a/packages/cli/src/commands/_generated/api-security/token-validation/index.ts +++ b/packages/cli/src/commands/_generated/api-security/token-validation/index.ts @@ -1,24 +1,19 @@ import $configurations from "./configurations/index.js"; import $rules from "./rules/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * token-validation command group * @generated from apis/overlays/api-security.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "token-validation", describe: "Operations for token-validation", - builder: (yargs) => { - return yargs - .command($configurations) - .command($rules) - .demandCommand(1, "Please specify a subcommand"); + routes: { + configurations: $configurations, + rules: $rules, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/rules/bulk-create.handler.ts b/packages/cli/src/commands/_generated/api-security/token-validation/rules/bulk-create.handler.ts new file mode 100644 index 0000000000..1c74db4888 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/token-validation/rules/bulk-create.handler.ts @@ -0,0 +1,55 @@ +import operation from "../../../_operations/api-security/token-validation/rules/bulk-create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./bulk-create.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security token-validation rules bulk-create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.body === undefined) { + throw new Error( + "--body is required for this command. Pass --body '' or --body @path/to/file.json." + ); + } + if (argv.dryRun) { + formatDryRun({ + command: "cf api-security token-validation rules bulk-create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/rules/bulk`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "json", + body: argv.body !== undefined ? parseBody(argv.body) : undefined, + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/rules/bulk-create.ts b/packages/cli/src/commands/_generated/api-security/token-validation/rules/bulk-create.ts index 3094dc076b..feb9e5cdf5 100644 --- a/packages/cli/src/commands/_generated/api-security/token-validation/rules/bulk-create.ts +++ b/packages/cli/src/commands/_generated/api-security/token-validation/rules/bulk-create.ts @@ -1,86 +1,37 @@ -import operation from "../../../_operations/api-security/token-validation/rules/bulk-create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * bulk-create command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security token-validation rules bulk-create\n\nCreates multiple token validation rules for the zone in one request." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "bulk-create", describe: "Create token validation rules", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security token-validation rules bulk-create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.body === undefined) { - throw new Error( - "--body is required for this command. Pass --body '' or --body @path/to/file.json." - ); - } - if (argv.dryRun) { - formatDryRun({ - command: "cf api-security token-validation rules bulk-create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/rules/bulk`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "json", - body: argv.body !== undefined ? parseBody(argv.body) : undefined, - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - } - ), -}; + usage: + "$0 api-security token-validation rules bulk-create\n\nCreates multiple token validation rules for the zone in one request.", + ...parameters, + loader: () => import("./bulk-create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/rules/bulk-edit.handler.ts b/packages/cli/src/commands/_generated/api-security/token-validation/rules/bulk-edit.handler.ts new file mode 100644 index 0000000000..159427ccfb --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/token-validation/rules/bulk-edit.handler.ts @@ -0,0 +1,55 @@ +import operation from "../../../_operations/api-security/token-validation/rules/bulk-edit.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./bulk-edit.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security token-validation rules bulk-edit", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.body === undefined) { + throw new Error( + "--body is required for this command. Pass --body '' or --body @path/to/file.json." + ); + } + if (argv.dryRun) { + formatDryRun({ + command: "cf api-security token-validation rules bulk-edit", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/rules/bulk`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "json", + body: argv.body !== undefined ? parseBody(argv.body) : undefined, + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/rules/bulk-edit.ts b/packages/cli/src/commands/_generated/api-security/token-validation/rules/bulk-edit.ts index bab0e1942d..f8751ae903 100644 --- a/packages/cli/src/commands/_generated/api-security/token-validation/rules/bulk-edit.ts +++ b/packages/cli/src/commands/_generated/api-security/token-validation/rules/bulk-edit.ts @@ -1,86 +1,37 @@ -import operation from "../../../_operations/api-security/token-validation/rules/bulk-edit.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * bulk-edit command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security token-validation rules bulk-edit\n\nUpdates and reorders multiple token validation rules in one request, then returns the updated rules." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "bulk-edit", describe: "Edit token validation rules", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security token-validation rules bulk-edit", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.body === undefined) { - throw new Error( - "--body is required for this command. Pass --body '' or --body @path/to/file.json." - ); - } - if (argv.dryRun) { - formatDryRun({ - command: "cf api-security token-validation rules bulk-edit", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/rules/bulk`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "json", - body: argv.body !== undefined ? parseBody(argv.body) : undefined, - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - } - ), -}; + usage: + "$0 api-security token-validation rules bulk-edit\n\nUpdates and reorders multiple token validation rules in one request, then returns the updated rules.", + ...parameters, + loader: () => import("./bulk-edit.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/rules/create.handler.ts b/packages/cli/src/commands/_generated/api-security/token-validation/rules/create.handler.ts new file mode 100644 index 0000000000..2423b85b0a --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/token-validation/rules/create.handler.ts @@ -0,0 +1,161 @@ +import operation from "../../../_operations/api-security/token-validation/rules/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { + promptForRequiredEnumField, + promptForRequiredField, +} from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security token-validation rules create", + classification: { + safeFlags: ["action", "enabled", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["action"] === undefined) { + argv["action"] = await promptForRequiredEnumField( + "action", + "Action to take on requests that match operations included in \`selector\` and fail \`expression\`.", + ["log", "block"] as const + ); + } + if (argv["description"] === undefined) { + argv["description"] = await promptForRequiredField( + "description", + "A human-readable description that gives more details than \`title\`." + ); + } + if (argv["enabled"] === undefined) { + throw new Error( + "--enabled is required (or pass --body with this field set)." + ); + } + if (argv["expression"] === undefined) { + argv["expression"] = await promptForRequiredField( + "expression", + "Rule expression. Requests that fail to match this expression will be subject to \`action\`. For details on expressions, see the [Cloudflare Docs](https://developers.cloudflare.com/api-shield/security/jwt-validation/). " + ); + } + if (argv["title"] === undefined) { + argv["title"] = await promptForRequiredField( + "title", + "A human-readable name for the rule." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + formatDryRun({ + command: "cf api-security token-validation rules create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/rules`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + action: argv["action"], + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + enabled: argv["enabled"], + expression: resolveFileToken( + argv["expression"] as string | undefined, + "expression", + "text" + ), + selector: { + exclude: parseObjectArray( + argv["selector-exclude"], + "selector-exclude", + true + ), + include: parseObjectArray( + argv["selector-include"], + "selector-include", + true + ), + }, + title: resolveFileToken( + argv["title"] as string | undefined, + "title", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + action: argv["action"], + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + enabled: argv["enabled"], + expression: resolveFileToken( + argv["expression"] as string | undefined, + "expression", + "text" + ), + selector: { + exclude: parseObjectArray( + argv["selector-exclude"], + "selector-exclude", + true + ), + include: parseObjectArray( + argv["selector-include"], + "selector-include", + true + ), + }, + title: resolveFileToken( + argv["title"] as string | undefined, + "title", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/rules/create.ts b/packages/cli/src/commands/_generated/api-security/token-validation/rules/create.ts index 45f890b4be..fbeba8670e 100644 --- a/packages/cli/src/commands/_generated/api-security/token-validation/rules/create.ts +++ b/packages/cli/src/commands/_generated/api-security/token-validation/rules/create.ts @@ -1,227 +1,86 @@ -import operation from "../../../_operations/api-security/token-validation/rules/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; import { - promptForRequiredEnumField, - promptForRequiredField, -} from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; +import { resolveFileToken } from "#lib/input-validation.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security token-validation rules create\n\nCreates a token validation rule for the zone." - ) - .option("action", { - type: "string", - description: +const parameters = { + flags: { + action: { + kind: "parsed", + brief: "Action to take on requests that match operations included in `selector` and fail `expression`.", + optional: true, choices: ["log", "block"], - }) - .coerce("action", (value) => resolveFileToken(value, "action", "text")) - .option("description", { - type: "string", - description: + parse: String, + coerce: (value: string) => resolveFileToken(value, "action", "text"), + }, + description: { + kind: "parsed", + brief: "A human-readable description that gives more details than `title`.", - }) - .option("enabled", { - type: "boolean", - description: "Toggle rule on or off.", - }) - .option("expression", { - type: "string", - description: + optional: true, + parse: String, + }, + enabled: { + kind: "boolean", + brief: "Toggle rule on or off.", + optional: true, + }, + expression: { + kind: "parsed", + brief: "Rule expression. Requests that fail to match this expression will be subject to `action`.\n\nFor details on expressions, see the [Cloudflare Docs](https://developers.cloudflare.com/api-shield/security/jwt-validation/).\n", - }) - .option("selector-exclude", { - type: "string", - description: + optional: true, + parse: String, + }, + "selector-exclude": { + kind: "parsed", + brief: 'Ignore operations that were otherwise included by `include`. Provide as a JSON array of objects, null, or @path/to/file.json. Shape: [{"operation_ids"?: [string]}]. ? marks optional keys.', - }) - .option("selector-include", { - type: "string", - description: + optional: true, + parse: String, + }, + "selector-include": { + kind: "parsed", + brief: 'Select all matching operations. Provide as a JSON array of objects, null, or @path/to/file.json. Shape: [{"host"?: [string]}]. ? marks optional keys.', - }) - .option("title", { - type: "string", - description: "A human-readable name for the rule.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + title: { + kind: "parsed", + brief: "A human-readable name for the rule.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Create a token validation rule", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security token-validation rules create", - classification: { - safeFlags: ["action", "enabled", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["action"] === undefined) { - argv["action"] = await promptForRequiredEnumField( - "action", - "Action to take on requests that match operations included in \`selector\` and fail \`expression\`.", - ["log", "block"] as const - ); - } - if (argv["description"] === undefined) { - argv["description"] = await promptForRequiredField( - "description", - "A human-readable description that gives more details than \`title\`." - ); - } - if (argv["enabled"] === undefined) { - throw new Error( - "--enabled is required (or pass --body with this field set)." - ); - } - if (argv["expression"] === undefined) { - argv["expression"] = await promptForRequiredField( - "expression", - "Rule expression. Requests that fail to match this expression will be subject to \`action\`. For details on expressions, see the [Cloudflare Docs](https://developers.cloudflare.com/api-shield/security/jwt-validation/). " - ); - } - if (argv["title"] === undefined) { - argv["title"] = await promptForRequiredField( - "title", - "A human-readable name for the rule." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - formatDryRun({ - command: "cf api-security token-validation rules create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/rules`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - action: argv["action"], - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - enabled: argv["enabled"], - expression: resolveFileToken( - argv["expression"] as string | undefined, - "expression", - "text" - ), - selector: { - exclude: parseObjectArray( - argv["selector-exclude"], - "selector-exclude", - true - ), - include: parseObjectArray( - argv["selector-include"], - "selector-include", - true - ), - }, - title: resolveFileToken( - argv["title"] as string | undefined, - "title", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - action: argv["action"], - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - enabled: argv["enabled"], - expression: resolveFileToken( - argv["expression"] as string | undefined, - "expression", - "text" - ), - selector: { - exclude: parseObjectArray( - argv["selector-exclude"], - "selector-exclude", - true - ), - include: parseObjectArray( - argv["selector-include"], - "selector-include", - true - ), - }, - title: resolveFileToken( - argv["title"] as string | undefined, - "title", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 api-security token-validation rules create\n\nCreates a token validation rule for the zone.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/rules/delete.handler.ts b/packages/cli/src/commands/_generated/api-security/token-validation/rules/delete.handler.ts new file mode 100644 index 0000000000..92878321c7 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/token-validation/rules/delete.handler.ts @@ -0,0 +1,56 @@ +import operation from "../../../_operations/api-security/token-validation/rules/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security token-validation rules delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf api-security token-validation rules delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/rules/${argv["rule-id"] == null ? "" : encodeURIComponent(String(argv["rule-id"]))}`, + pathParams: { + "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), + "rule-id": String(argv["rule-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This operation deletes the token validation rule from the zone.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { zone_id: zoneId, rule_id: argv["rule-id"] }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/rules/delete.ts b/packages/cli/src/commands/_generated/api-security/token-validation/rules/delete.ts index 942fc40884..473f36a8d8 100644 --- a/packages/cli/src/commands/_generated/api-security/token-validation/rules/delete.ts +++ b/packages/cli/src/commands/_generated/api-security/token-validation/rules/delete.ts @@ -1,92 +1,43 @@ -import operation from "../../../_operations/api-security/token-validation/rules/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security token-validation rules delete \n\nDeletes a token validation rule from the zone." - ) - .positional("rule-id", { - type: "string", - description: "Token Validation Rule ID", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "rule-id", + brief: "Token Validation Rule ID", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete a token validation rule", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security token-validation rules delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf api-security token-validation rules delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/rules/${argv["rule-id"] == null ? "" : encodeURIComponent(String(argv["rule-id"]))}`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - "rule-id": String(argv["rule-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This operation deletes the token validation rule from the zone.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { zone_id: zoneId, rule_id: argv["rule-id"] }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 api-security token-validation rules delete \n\nDeletes a token validation rule from the zone.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/rules/edit.handler.ts b/packages/cli/src/commands/_generated/api-security/token-validation/rules/edit.handler.ts new file mode 100644 index 0000000000..208bff6035 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/token-validation/rules/edit.handler.ts @@ -0,0 +1,158 @@ +import operation from "../../../_operations/api-security/token-validation/rules/edit.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./edit.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security token-validation rules edit", + classification: { + safeFlags: ["action", "enabled", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf api-security token-validation rules edit", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/rules/${argv["rule-id"] == null ? "" : encodeURIComponent(String(argv["rule-id"]))}`, + pathParams: { + "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), + "rule-id": String(argv["rule-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + action: argv["action"], + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + enabled: argv["enabled"], + expression: resolveFileToken( + argv["expression"] as string | undefined, + "expression", + "text" + ), + selector: { + exclude: parseObjectArray( + argv["selector-exclude"], + "selector-exclude", + true + ), + include: parseObjectArray( + argv["selector-include"], + "selector-include", + true + ), + }, + title: resolveFileToken( + argv["title"] as string | undefined, + "title", + "text" + ), + position: { + index: argv["position-index"], + before: resolveFileToken( + argv["position-before"] as string | undefined, + "position-before", + "text" + ), + after: resolveFileToken( + argv["position-after"] as string | undefined, + "position-after", + "text" + ), + }, + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + zone_id: zoneId, + rule_id: argv["rule-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + action: argv["action"], + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + enabled: argv["enabled"], + expression: resolveFileToken( + argv["expression"] as string | undefined, + "expression", + "text" + ), + selector: { + exclude: parseObjectArray( + argv["selector-exclude"], + "selector-exclude", + true + ), + include: parseObjectArray( + argv["selector-include"], + "selector-include", + true + ), + }, + title: resolveFileToken( + argv["title"] as string | undefined, + "title", + "text" + ), + position: { + index: argv["position-index"], + before: resolveFileToken( + argv["position-before"] as string | undefined, + "position-before", + "text" + ), + after: resolveFileToken( + argv["position-after"] as string | undefined, + "position-after", + "text" + ), + }, + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + zone_id: zoneId, + rule_id: argv["rule-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/rules/edit.ts b/packages/cli/src/commands/_generated/api-security/token-validation/rules/edit.ts index f03f0d3a36..8c3627056a 100644 --- a/packages/cli/src/commands/_generated/api-security/token-validation/rules/edit.ts +++ b/packages/cli/src/commands/_generated/api-security/token-validation/rules/edit.ts @@ -1,242 +1,115 @@ -import operation from "../../../_operations/api-security/token-validation/rules/edit.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * edit command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security token-validation rules edit \n\nUpdates only the supplied fields on a token validation rule." - ) - .positional("rule-id", { - type: "string", - description: "Token Validation Rule ID", - demandOption: true, - }) - .option("action", { - type: "string", - description: +const parameters = { + flags: { + action: { + kind: "parsed", + brief: "Action to take on requests that match operations included in `selector` and fail `expression`.", + optional: true, choices: ["log", "block"], - }) - .coerce("action", (value) => resolveFileToken(value, "action", "text")) - .option("description", { - type: "string", - description: + parse: String, + coerce: (value: string) => resolveFileToken(value, "action", "text"), + }, + description: { + kind: "parsed", + brief: "A human-readable description that gives more details than `title`.", - }) - .option("enabled", { - type: "boolean", - description: "Toggle rule on or off.", - }) - .option("expression", { - type: "string", - description: + optional: true, + parse: String, + }, + enabled: { + kind: "boolean", + brief: "Toggle rule on or off.", + optional: true, + }, + expression: { + kind: "parsed", + brief: "Rule expression. Requests that fail to match this expression will be subject to `action`.\n\nFor details on expressions, see the [Cloudflare Docs](https://developers.cloudflare.com/api-shield/security/jwt-validation/).\n", - }) - .option("selector-exclude", { - type: "string", - description: + optional: true, + parse: String, + }, + "selector-exclude": { + kind: "parsed", + brief: 'Ignore operations that were otherwise included by `include`. Provide as a JSON array of objects, null, or @path/to/file.json. Shape: [{"operation_ids"?: [string]}]. ? marks optional keys.', - }) - .option("selector-include", { - type: "string", - description: + optional: true, + parse: String, + }, + "selector-include": { + kind: "parsed", + brief: 'Select all matching operations. Provide as a JSON array of objects, null, or @path/to/file.json. Shape: [{"host"?: [string]}]. ? marks optional keys.', - }) - .option("title", { - type: "string", - description: "A human-readable name for the rule.", - }) - .option("position-index", { - type: "number", - description: "Move rule to this position", - }) - .option("position-before", { - type: "string", - description: "Move rule to before rule with this ID.", - }) - .option("position-after", { - type: "string", - description: "Move rule to after rule with this ID.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + title: { + kind: "parsed", + brief: "A human-readable name for the rule.", + optional: true, + parse: String, + }, + "position-index": { + kind: "parsed", + brief: "Move rule to this position", + optional: true, + parse: Number, + }, + "position-before": { + kind: "parsed", + brief: "Move rule to before rule with this ID.", + optional: true, + parse: String, + }, + "position-after": { + kind: "parsed", + brief: "Move rule to after rule with this ID.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }) - .conflicts("position-index", ["position-before", "position-after"]) - .conflicts("position-before", ["position-index", "position-after"]) - .conflicts("position-after", ["position-index", "position-before"]); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "rule-id", + brief: "Token Validation Rule ID", + parse: String, + }, + ], + rules(rules) { + rules.conflicts("position-index", ["position-before", "position-after"]); + rules.conflicts("position-before", ["position-index", "position-after"]); + rules.conflicts("position-after", ["position-index", "position-before"]); + }, +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "edit ", describe: "Edit a token validation rule", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security token-validation rules edit", - classification: { - safeFlags: ["action", "enabled", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf api-security token-validation rules edit", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/rules/${argv["rule-id"] == null ? "" : encodeURIComponent(String(argv["rule-id"]))}`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - "rule-id": String(argv["rule-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - action: argv["action"], - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - enabled: argv["enabled"], - expression: resolveFileToken( - argv["expression"] as string | undefined, - "expression", - "text" - ), - selector: { - exclude: parseObjectArray( - argv["selector-exclude"], - "selector-exclude", - true - ), - include: parseObjectArray( - argv["selector-include"], - "selector-include", - true - ), - }, - title: resolveFileToken( - argv["title"] as string | undefined, - "title", - "text" - ), - position: { - index: argv["position-index"], - before: resolveFileToken( - argv["position-before"] as string | undefined, - "position-before", - "text" - ), - after: resolveFileToken( - argv["position-after"] as string | undefined, - "position-after", - "text" - ), - }, - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - zone_id: zoneId, - rule_id: argv["rule-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - action: argv["action"], - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - enabled: argv["enabled"], - expression: resolveFileToken( - argv["expression"] as string | undefined, - "expression", - "text" - ), - selector: { - exclude: parseObjectArray( - argv["selector-exclude"], - "selector-exclude", - true - ), - include: parseObjectArray( - argv["selector-include"], - "selector-include", - true - ), - }, - title: resolveFileToken( - argv["title"] as string | undefined, - "title", - "text" - ), - position: { - index: argv["position-index"], - before: resolveFileToken( - argv["position-before"] as string | undefined, - "position-before", - "text" - ), - after: resolveFileToken( - argv["position-after"] as string | undefined, - "position-after", - "text" - ), - }, - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - zone_id: zoneId, - rule_id: argv["rule-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 api-security token-validation rules edit \n\nUpdates only the supplied fields on a token validation rule.", + ...parameters, + loader: () => import("./edit.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/rules/get.handler.ts b/packages/cli/src/commands/_generated/api-security/token-validation/rules/get.handler.ts new file mode 100644 index 0000000000..0ad4a9ec51 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/token-validation/rules/get.handler.ts @@ -0,0 +1,45 @@ +import operation from "../../../_operations/api-security/token-validation/rules/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security token-validation rules get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf api-security token-validation rules get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/rules/${argv["rule-id"] == null ? "" : encodeURIComponent(String(argv["rule-id"]))}`, + pathParams: { + "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), + "rule-id": String(argv["rule-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { zone_id: zoneId, rule_id: argv["rule-id"] }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/rules/get.ts b/packages/cli/src/commands/_generated/api-security/token-validation/rules/get.ts index 845d14896b..5136a375b7 100644 --- a/packages/cli/src/commands/_generated/api-security/token-validation/rules/get.ts +++ b/packages/cli/src/commands/_generated/api-security/token-validation/rules/get.ts @@ -1,75 +1,37 @@ -import operation from "../../../_operations/api-security/token-validation/rules/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security token-validation rules get \n\nReturns a token validation rule by ID." - ) - .positional("rule-id", { - type: "string", - description: "Token Validation Rule ID", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "rule-id", + brief: "Token Validation Rule ID", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get a token validation rule", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security token-validation rules get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf api-security token-validation rules get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/rules/${argv["rule-id"] == null ? "" : encodeURIComponent(String(argv["rule-id"]))}`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - "rule-id": String(argv["rule-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { zone_id: zoneId, rule_id: argv["rule-id"] }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 api-security token-validation rules get \n\nReturns a token validation rule by ID.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/rules/index.ts b/packages/cli/src/commands/_generated/api-security/token-validation/rules/index.ts index ac8c36b345..198aaab4b8 100644 --- a/packages/cli/src/commands/_generated/api-security/token-validation/rules/index.ts +++ b/packages/cli/src/commands/_generated/api-security/token-validation/rules/index.ts @@ -5,30 +5,25 @@ import $delete from "./delete.js"; import $edit from "./edit.js"; import $get from "./get.js"; import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * rules command group * @generated from apis/overlays/api-security.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "rules", describe: "Operations for token-validation.rules", - builder: (yargs) => { - return yargs - .command($bulkcreate) - .command($bulkedit) - .command($create) - .command($delete) - .command($edit) - .command($get) - .command($list) - .demandCommand(1, "Please specify a subcommand"); + routes: { + "bulk-create": $bulkcreate, + "bulk-edit": $bulkedit, + create: $create, + delete: $delete, + edit: $edit, + get: $get, + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/rules/list.handler.ts b/packages/cli/src/commands/_generated/api-security/token-validation/rules/list.handler.ts new file mode 100644 index 0000000000..4425bc7834 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/token-validation/rules/list.handler.ts @@ -0,0 +1,54 @@ +import operation from "../../../_operations/api-security/token-validation/rules/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security token-validation rules list", + classification: { + safeFlags: ["action", "enabled", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + per_page: argv["per-page"], + page: argv["page"], + token_configuration: argv["token-configuration"], + action: argv["action"], + enabled: argv["enabled"], + id: argv["id"], + rule_id: argv["rule-id"], + host: argv["host"], + hostname: argv["hostname"], + }; + if (argv.dryRun) { + formatDryRun({ + command: "cf api-security token-validation rules list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/rules`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { zone_id: zoneId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/token-validation/rules/list.ts b/packages/cli/src/commands/_generated/api-security/token-validation/rules/list.ts index c2d9ad2cfd..c88a9b6e6a 100644 --- a/packages/cli/src/commands/_generated/api-security/token-validation/rules/list.ts +++ b/packages/cli/src/commands/_generated/api-security/token-validation/rules/list.ts @@ -1,120 +1,86 @@ -import operation from "../../../_operations/api-security/token-validation/rules/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security token-validation rules list\n\nLists token validation rules for the zone, with filters for configuration, action, state, ID, and host." - ) - .option("per-page", { - type: "number", - description: "Maximum number of results per page.", - }) - .option("page", { - type: "number", - description: "Page number of paginated results.", - }) - .option("token-configuration", { - type: "string", - array: true, - description: "Select rules using any of these token configurations.", - }) - .option("action", { - type: "string", - description: +const parameters = { + flags: { + "per-page": { + kind: "parsed", + brief: "Maximum number of results per page.", + optional: true, + parse: Number, + }, + page: { + kind: "parsed", + brief: "Page number of paginated results.", + optional: true, + parse: Number, + }, + "token-configuration": { + kind: "parsed", + brief: "Select rules using any of these token configurations.", + variadic: true, + optional: true, + parse: String, + }, + action: { + kind: "enum", + brief: "Action to take on requests that match operations included in `selector` and fail `expression`.", - choices: ["log", "block"], - }) - .option("enabled", { - type: "boolean", - description: "Toggle rule on or off.", - }) - .option("id", { - type: "string", - description: "Select rules with these IDs.", - }) - .option("rule-id", { - type: "string", - description: "Select rules with these IDs.", - }) - .option("host", { - type: "string", - description: "Select rules with this host in `include`.", - }) - .option("hostname", { - type: "string", - description: "Select rules with this host in `include`.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + values: ["log", "block"], + optional: true, + }, + enabled: { + kind: "boolean", + brief: "Toggle rule on or off.", + optional: true, + }, + id: { + kind: "parsed", + brief: "Select rules with these IDs.", + optional: true, + parse: String, + }, + "rule-id": { + kind: "parsed", + brief: "Select rules with these IDs.", + optional: true, + parse: String, + }, + host: { + kind: "parsed", + brief: "Select rules with this host in `include`.", + optional: true, + parse: String, + }, + hostname: { + kind: "parsed", + brief: "Select rules with this host in `include`.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List token validation rules", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security token-validation rules list", - classification: { - safeFlags: ["action", "enabled", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - per_page: argv["per-page"], - page: argv["page"], - token_configuration: argv["token-configuration"], - action: argv["action"], - enabled: argv["enabled"], - id: argv["id"], - rule_id: argv["rule-id"], - host: argv["host"], - hostname: argv["hostname"], - }; - if (argv.dryRun) { - formatDryRun({ - command: "cf api-security token-validation rules list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/token_validation/rules`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { zone_id: zoneId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 api-security token-validation rules list\n\nLists token validation rules for the zone, with filters for configuration, action, state, ID, and host.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/create.handler.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/create.handler.ts new file mode 100644 index 0000000000..6f9dac6b91 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/create.handler.ts @@ -0,0 +1,91 @@ +import operation from "../../../_operations/api-security/vulnerability-scanner/credential-sets/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security vulnerability-scanner credential-sets create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField( + "name", + "Human-readable name." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: + "cf api-security vulnerability-scanner credential-sets create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/credential_sets`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/create.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/create.ts index 1bada2bb78..350db79e88 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/create.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/create.ts @@ -1,121 +1,43 @@ -import operation from "../../../_operations/api-security/vulnerability-scanner/credential-sets/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security vulnerability-scanner credential-sets create\n\nCreates a new credential set." - ) - .option("name", { type: "string", description: "Human-readable name." }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + name: { + kind: "parsed", + brief: "Human-readable name.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Create credential set", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security vulnerability-scanner credential-sets create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "Human-readable name." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: - "cf api-security vulnerability-scanner credential-sets create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/credential_sets`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 api-security vulnerability-scanner credential-sets create\n\nCreates a new credential set.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/create.handler.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/create.handler.ts new file mode 100644 index 0000000000..9853676eb4 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/create.handler.ts @@ -0,0 +1,148 @@ +import operation from "../../../../_operations/api-security/vulnerability-scanner/credential-sets/credentials/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { + promptForRequiredEnumField, + promptForRequiredField, +} from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: + "api-security vulnerability-scanner credential-sets credentials create", + classification: { + safeFlags: ["location", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["location"] === undefined) { + argv["location"] = await promptForRequiredEnumField( + "location", + "Where the credential is attached in outgoing requests.", + ["header", "cookie"] as const + ); + } + if (argv["location-name"] === undefined) { + argv["location-name"] = await promptForRequiredField( + "location-name", + "Name of the header or cookie where the credential is attached. " + ); + } + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField( + "name", + "Human-readable name." + ); + } + if (argv["value"] === undefined) { + argv["value"] = await promptForRequiredField( + "value", + "The credential value (e.g. API key, session token). Write-only. Never returned in responses. ", + { kind: "secret" } + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: + "cf api-security vulnerability-scanner credential-sets credentials create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/credential_sets/${argv["credential-set-id"] == null ? "" : encodeURIComponent(String(argv["credential-set-id"]))}/credentials`, + pathParams: { + "credential-set-id": String(argv["credential-set-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + location: argv["location"], + location_name: resolveFileToken( + argv["location-name"] as string | undefined, + "location-name", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + value: resolveFileToken( + argv["value"] as string | undefined, + "value", + "text" + ), + }), + sensitiveBodyPaths: [["value"]], + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + credential_set_id: argv["credential-set-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + location: argv["location"], + location_name: resolveFileToken( + argv["location-name"] as string | undefined, + "location-name", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + value: resolveFileToken( + argv["value"] as string | undefined, + "value", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + credential_set_id: argv["credential-set-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/create.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/create.ts index 556f0e788b..b9b23ab5e6 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/create.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/create.ts @@ -1,199 +1,71 @@ -import operation from "../../../../_operations/api-security/vulnerability-scanner/credential-sets/credentials/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { - promptForRequiredEnumField, - promptForRequiredField, -} from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security vulnerability-scanner credential-sets credentials create \n\nCreates a new credential within a credential set." - ) - .positional("credential-set-id", { - type: "string", - description: "Credential set identifier.", - demandOption: true, - }) - .option("location", { - type: "string", - description: "Where the credential is attached in outgoing requests.", +const parameters = { + flags: { + location: { + kind: "parsed", + brief: "Where the credential is attached in outgoing requests.", + optional: true, choices: ["header", "cookie"], - }) - .coerce("location", (value) => resolveFileToken(value, "location", "text")) - .option("location-name", { - type: "string", - description: - "Name of the header or cookie where the credential is attached.\n", - }) - .option("name", { type: "string", description: "Human-readable name." }) - .option("value", { - type: "string", - description: + parse: String, + coerce: (value: string) => resolveFileToken(value, "location", "text"), + }, + "location-name": { + kind: "parsed", + brief: "Name of the header or cookie where the credential is attached.\n", + optional: true, + parse: String, + }, + name: { + kind: "parsed", + brief: "Human-readable name.", + optional: true, + parse: String, + }, + value: { + kind: "parsed", + brief: "The credential value (e.g. API key, session token). Write-only.\nNever returned in responses.\n", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "credential-set-id", + brief: "Credential set identifier.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Create credential", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: - "api-security vulnerability-scanner credential-sets credentials create", - classification: { - safeFlags: ["location", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["location"] === undefined) { - argv["location"] = await promptForRequiredEnumField( - "location", - "Where the credential is attached in outgoing requests.", - ["header", "cookie"] as const - ); - } - if (argv["location-name"] === undefined) { - argv["location-name"] = await promptForRequiredField( - "location-name", - "Name of the header or cookie where the credential is attached. " - ); - } - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "Human-readable name." - ); - } - if (argv["value"] === undefined) { - argv["value"] = await promptForRequiredField( - "value", - "The credential value (e.g. API key, session token). Write-only. Never returned in responses. ", - { kind: "secret" } - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: - "cf api-security vulnerability-scanner credential-sets credentials create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/credential_sets/${argv["credential-set-id"] == null ? "" : encodeURIComponent(String(argv["credential-set-id"]))}/credentials`, - pathParams: { - "credential-set-id": String(argv["credential-set-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - location: argv["location"], - location_name: resolveFileToken( - argv["location-name"] as string | undefined, - "location-name", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - value: resolveFileToken( - argv["value"] as string | undefined, - "value", - "text" - ), - }), - sensitiveBodyPaths: [["value"]], - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - credential_set_id: argv["credential-set-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - location: argv["location"], - location_name: resolveFileToken( - argv["location-name"] as string | undefined, - "location-name", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - value: resolveFileToken( - argv["value"] as string | undefined, - "value", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - credential_set_id: argv["credential-set-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 api-security vulnerability-scanner credential-sets credentials create \n\nCreates a new credential within a credential set.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/delete.handler.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/delete.handler.ts new file mode 100644 index 0000000000..567bbcaa4a --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/delete.handler.ts @@ -0,0 +1,66 @@ +import operation from "../../../../_operations/api-security/vulnerability-scanner/credential-sets/credentials/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: + "api-security vulnerability-scanner credential-sets credentials delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: + "cf api-security vulnerability-scanner credential-sets credentials delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/credential_sets/${argv["credential-set-id"] == null ? "" : encodeURIComponent(String(argv["credential-set-id"]))}/credentials/${argv["credential-id"] == null ? "" : encodeURIComponent(String(argv["credential-id"]))}`, + pathParams: { + "credential-set-id": String(argv["credential-set-id"] ?? ""), + "credential-id": String(argv["credential-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This operation permanently deletes the credential from the credential set.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + credential_set_id: argv["credential-set-id"], + credential_id: argv["credential-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/delete.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/delete.ts index 10dc449905..9fa5745c50 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/delete.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/delete.ts @@ -1,107 +1,48 @@ -import operation from "../../../../_operations/api-security/vulnerability-scanner/credential-sets/credentials/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security vulnerability-scanner credential-sets credentials delete \n\nDeletes a credential." - ) - .positional("credential-id", { - type: "string", - description: "Credential identifier.", - demandOption: true, - }) - .option("credential-set-id", { - type: "string", - description: "Credential set identifier.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "credential-set-id": { + kind: "parsed", + brief: "Credential set identifier.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "credential-id", + brief: "Credential identifier.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete credential", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: - "api-security vulnerability-scanner credential-sets credentials delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: - "cf api-security vulnerability-scanner credential-sets credentials delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/credential_sets/${argv["credential-set-id"] == null ? "" : encodeURIComponent(String(argv["credential-set-id"]))}/credentials/${argv["credential-id"] == null ? "" : encodeURIComponent(String(argv["credential-id"]))}`, - pathParams: { - "credential-set-id": String(argv["credential-set-id"] ?? ""), - "credential-id": String(argv["credential-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This operation permanently deletes the credential from the credential set.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - credential_set_id: argv["credential-set-id"], - credential_id: argv["credential-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 api-security vulnerability-scanner credential-sets credentials delete \n\nDeletes a credential.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/edit.handler.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/edit.handler.ts new file mode 100644 index 0000000000..f97baf5d12 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/edit.handler.ts @@ -0,0 +1,115 @@ +import operation from "../../../../_operations/api-security/vulnerability-scanner/credential-sets/credentials/edit.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./edit.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: + "api-security vulnerability-scanner credential-sets credentials edit", + classification: { + safeFlags: ["location", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: + "cf api-security vulnerability-scanner credential-sets credentials edit", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/credential_sets/${argv["credential-set-id"] == null ? "" : encodeURIComponent(String(argv["credential-set-id"]))}/credentials/${argv["credential-id"] == null ? "" : encodeURIComponent(String(argv["credential-id"]))}`, + pathParams: { + "credential-set-id": String(argv["credential-set-id"] ?? ""), + "credential-id": String(argv["credential-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + location: argv["location"], + location_name: resolveFileToken( + argv["location-name"] as string | undefined, + "location-name", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + value: resolveFileToken( + argv["value"] as string | undefined, + "value", + "text" + ), + }), + sensitiveBodyPaths: [["value"]], + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + credential_set_id: argv["credential-set-id"], + credential_id: argv["credential-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + location: argv["location"], + location_name: resolveFileToken( + argv["location-name"] as string | undefined, + "location-name", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + value: resolveFileToken( + argv["value"] as string | undefined, + "value", + "text" + ), + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + credential_set_id: argv["credential-set-id"], + credential_id: argv["credential-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/edit.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/edit.ts index 8dba60da1a..13596ce866 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/edit.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/edit.ts @@ -1,172 +1,76 @@ -import operation from "../../../../_operations/api-security/vulnerability-scanner/credential-sets/credentials/edit.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * edit command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security vulnerability-scanner credential-sets credentials edit \n\nUpdates a credential with only the provided fields; omitted fields remain unchanged." - ) - .positional("credential-id", { - type: "string", - description: "Credential identifier.", - demandOption: true, - }) - .option("credential-set-id", { - type: "string", - description: "Credential set identifier.", - demandOption: true, - }) - .option("location", { - type: "string", - description: "Where the credential is attached in outgoing requests.", +const parameters = { + flags: { + "credential-set-id": { + kind: "parsed", + brief: "Credential set identifier.", + parse: String, + }, + location: { + kind: "parsed", + brief: "Where the credential is attached in outgoing requests.", + optional: true, choices: ["header", "cookie"], - }) - .coerce("location", (value) => resolveFileToken(value, "location", "text")) - .option("location-name", { - type: "string", - description: - "Name of the header or cookie where the credential is attached.\n", - }) - .option("name", { type: "string", description: "Human-readable name." }) - .option("value", { - type: "string", - description: - "The credential value. Write-only. Never returned in responses.\n", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => resolveFileToken(value, "location", "text"), + }, + "location-name": { + kind: "parsed", + brief: "Name of the header or cookie where the credential is attached.\n", + optional: true, + parse: String, + }, + name: { + kind: "parsed", + brief: "Human-readable name.", + optional: true, + parse: String, + }, + value: { + kind: "parsed", + brief: "The credential value. Write-only. Never returned in responses.\n", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: + }, + body: { + kind: "parsed", + brief: "Applies a partial update. Only the provided fields change; omitted fields remain unchanged.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "credential-id", + brief: "Credential identifier.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "edit ", describe: "Edit credential", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: - "api-security vulnerability-scanner credential-sets credentials edit", - classification: { - safeFlags: ["location", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: - "cf api-security vulnerability-scanner credential-sets credentials edit", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/credential_sets/${argv["credential-set-id"] == null ? "" : encodeURIComponent(String(argv["credential-set-id"]))}/credentials/${argv["credential-id"] == null ? "" : encodeURIComponent(String(argv["credential-id"]))}`, - pathParams: { - "credential-set-id": String(argv["credential-set-id"] ?? ""), - "credential-id": String(argv["credential-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - location: argv["location"], - location_name: resolveFileToken( - argv["location-name"] as string | undefined, - "location-name", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - value: resolveFileToken( - argv["value"] as string | undefined, - "value", - "text" - ), - }), - sensitiveBodyPaths: [["value"]], - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - credential_set_id: argv["credential-set-id"], - credential_id: argv["credential-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - location: argv["location"], - location_name: resolveFileToken( - argv["location-name"] as string | undefined, - "location-name", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - value: resolveFileToken( - argv["value"] as string | undefined, - "value", - "text" - ), - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - credential_set_id: argv["credential-set-id"], - credential_id: argv["credential-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 api-security vulnerability-scanner credential-sets credentials edit \n\nUpdates a credential with only the provided fields; omitted fields remain unchanged.", + ...parameters, + loader: () => import("./edit.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/get.handler.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/get.handler.ts new file mode 100644 index 0000000000..2926970c1f --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/get.handler.ts @@ -0,0 +1,55 @@ +import operation from "../../../../_operations/api-security/vulnerability-scanner/credential-sets/credentials/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: + "api-security vulnerability-scanner credential-sets credentials get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: + "cf api-security vulnerability-scanner credential-sets credentials get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/credential_sets/${argv["credential-set-id"] == null ? "" : encodeURIComponent(String(argv["credential-set-id"]))}/credentials/${argv["credential-id"] == null ? "" : encodeURIComponent(String(argv["credential-id"]))}`, + pathParams: { + "credential-set-id": String(argv["credential-set-id"] ?? ""), + "credential-id": String(argv["credential-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + credential_set_id: argv["credential-set-id"], + credential_id: argv["credential-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/get.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/get.ts index 1ce8c0db7a..8284ac85a6 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/get.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/get.ts @@ -1,90 +1,42 @@ -import operation from "../../../../_operations/api-security/vulnerability-scanner/credential-sets/credentials/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security vulnerability-scanner credential-sets credentials get \n\nReturns a single credential by ID." - ) - .positional("credential-id", { - type: "string", - description: "Credential identifier.", - demandOption: true, - }) - .option("credential-set-id", { - type: "string", - description: "Credential set identifier.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "credential-set-id": { + kind: "parsed", + brief: "Credential set identifier.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "credential-id", + brief: "Credential identifier.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get credential", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: - "api-security vulnerability-scanner credential-sets credentials get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: - "cf api-security vulnerability-scanner credential-sets credentials get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/credential_sets/${argv["credential-set-id"] == null ? "" : encodeURIComponent(String(argv["credential-set-id"]))}/credentials/${argv["credential-id"] == null ? "" : encodeURIComponent(String(argv["credential-id"]))}`, - pathParams: { - "credential-set-id": String(argv["credential-set-id"] ?? ""), - "credential-id": String(argv["credential-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - credential_set_id: argv["credential-set-id"], - credential_id: argv["credential-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 api-security vulnerability-scanner credential-sets credentials get \n\nReturns a single credential by ID.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/index.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/index.ts index 3b0a63f40d..c28a68abd5 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/index.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/index.ts @@ -4,29 +4,24 @@ import $edit from "./edit.js"; import $get from "./get.js"; import $list from "./list.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * credentials command group * @generated from apis/overlays/api-security.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "credentials", describe: "Operations for vulnerability-scanner.credential-sets.credentials", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($edit) - .command($get) - .command($list) - .command($update) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + edit: $edit, + get: $get, + list: $list, + update: $update, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/list.handler.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/list.handler.ts new file mode 100644 index 0000000000..b6df8d3865 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/list.handler.ts @@ -0,0 +1,59 @@ +import operation from "../../../../_operations/api-security/vulnerability-scanner/credential-sets/credentials/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: + "api-security vulnerability-scanner credential-sets credentials list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: + "cf api-security vulnerability-scanner credential-sets credentials list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/credential_sets/${argv["credential-set-id"] == null ? "" : encodeURIComponent(String(argv["credential-set-id"]))}/credentials`, + pathParams: { + "credential-set-id": String(argv["credential-set-id"] ?? ""), + }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + credential_set_id: argv["credential-set-id"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/list.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/list.ts index 7b10ad8b3d..6ac9319d74 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/list.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/list.ts @@ -1,97 +1,48 @@ -import operation from "../../../../_operations/api-security/vulnerability-scanner/credential-sets/credentials/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security vulnerability-scanner credential-sets credentials list\n\nReturns all credentials within a credential set." - ) - .option("credential-set-id", { - type: "string", - description: "Credential set identifier.", - demandOption: true, - }) - .option("page", { - type: "number", - description: "Page number of paginated results.", - }) - .option("per-page", { - type: "number", - description: "Number of results per page.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "credential-set-id": { + kind: "parsed", + brief: "Credential set identifier.", + parse: String, + }, + page: { + kind: "parsed", + brief: "Page number of paginated results.", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Number of results per page.", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List credentials", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: - "api-security vulnerability-scanner credential-sets credentials list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: - "cf api-security vulnerability-scanner credential-sets credentials list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/credential_sets/${argv["credential-set-id"] == null ? "" : encodeURIComponent(String(argv["credential-set-id"]))}/credentials`, - pathParams: { - "credential-set-id": String(argv["credential-set-id"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - credential_set_id: argv["credential-set-id"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 api-security vulnerability-scanner credential-sets credentials list\n\nReturns all credentials within a credential set.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/update.handler.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/update.handler.ts new file mode 100644 index 0000000000..5f6bffe937 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/update.handler.ts @@ -0,0 +1,151 @@ +import operation from "../../../../_operations/api-security/vulnerability-scanner/credential-sets/credentials/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { + promptForRequiredEnumField, + promptForRequiredField, +} from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: + "api-security vulnerability-scanner credential-sets credentials update", + classification: { + safeFlags: ["location", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["location"] === undefined) { + argv["location"] = await promptForRequiredEnumField( + "location", + "Where the credential is attached in outgoing requests.", + ["header", "cookie"] as const + ); + } + if (argv["location-name"] === undefined) { + argv["location-name"] = await promptForRequiredField( + "location-name", + "Name of the header or cookie where the credential is attached. " + ); + } + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField( + "name", + "Human-readable name." + ); + } + if (argv["value"] === undefined) { + argv["value"] = await promptForRequiredField( + "value", + "The credential value. Write-only. Never returned in responses. ", + { kind: "secret" } + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: + "cf api-security vulnerability-scanner credential-sets credentials update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/credential_sets/${argv["credential-set-id"] == null ? "" : encodeURIComponent(String(argv["credential-set-id"]))}/credentials/${argv["credential-id"] == null ? "" : encodeURIComponent(String(argv["credential-id"]))}`, + pathParams: { + "credential-set-id": String(argv["credential-set-id"] ?? ""), + "credential-id": String(argv["credential-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + location: argv["location"], + location_name: resolveFileToken( + argv["location-name"] as string | undefined, + "location-name", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + value: resolveFileToken( + argv["value"] as string | undefined, + "value", + "text" + ), + }), + sensitiveBodyPaths: [["value"]], + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + credential_set_id: argv["credential-set-id"], + credential_id: argv["credential-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + location: argv["location"], + location_name: resolveFileToken( + argv["location-name"] as string | undefined, + "location-name", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + value: resolveFileToken( + argv["value"] as string | undefined, + "value", + "text" + ), + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + credential_set_id: argv["credential-set-id"], + credential_id: argv["credential-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/update.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/update.ts index 2a9ea2551b..d2c2486b87 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/update.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/credentials/update.ts @@ -1,207 +1,75 @@ -import operation from "../../../../_operations/api-security/vulnerability-scanner/credential-sets/credentials/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { - promptForRequiredEnumField, - promptForRequiredField, -} from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security vulnerability-scanner credential-sets credentials update \n\nReplaces a credential. All fields must be provided." - ) - .positional("credential-id", { - type: "string", - description: "Credential identifier.", - demandOption: true, - }) - .option("credential-set-id", { - type: "string", - description: "Credential set identifier.", - demandOption: true, - }) - .option("location", { - type: "string", - description: "Where the credential is attached in outgoing requests.", +const parameters = { + flags: { + "credential-set-id": { + kind: "parsed", + brief: "Credential set identifier.", + parse: String, + }, + location: { + kind: "parsed", + brief: "Where the credential is attached in outgoing requests.", + optional: true, choices: ["header", "cookie"], - }) - .coerce("location", (value) => resolveFileToken(value, "location", "text")) - .option("location-name", { - type: "string", - description: - "Name of the header or cookie where the credential is attached.\n", - }) - .option("name", { type: "string", description: "Human-readable name." }) - .option("value", { - type: "string", - description: - "The credential value. Write-only. Never returned in responses.\n", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => resolveFileToken(value, "location", "text"), + }, + "location-name": { + kind: "parsed", + brief: "Name of the header or cookie where the credential is attached.\n", + optional: true, + parse: String, + }, + name: { + kind: "parsed", + brief: "Human-readable name.", + optional: true, + parse: String, + }, + value: { + kind: "parsed", + brief: "The credential value. Write-only. Never returned in responses.\n", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Full replacement. Provide all fields.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Full replacement. Provide all fields.", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "credential-id", + brief: "Credential identifier.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update ", describe: "Update credential", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: - "api-security vulnerability-scanner credential-sets credentials update", - classification: { - safeFlags: ["location", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["location"] === undefined) { - argv["location"] = await promptForRequiredEnumField( - "location", - "Where the credential is attached in outgoing requests.", - ["header", "cookie"] as const - ); - } - if (argv["location-name"] === undefined) { - argv["location-name"] = await promptForRequiredField( - "location-name", - "Name of the header or cookie where the credential is attached. " - ); - } - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "Human-readable name." - ); - } - if (argv["value"] === undefined) { - argv["value"] = await promptForRequiredField( - "value", - "The credential value. Write-only. Never returned in responses. ", - { kind: "secret" } - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: - "cf api-security vulnerability-scanner credential-sets credentials update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/credential_sets/${argv["credential-set-id"] == null ? "" : encodeURIComponent(String(argv["credential-set-id"]))}/credentials/${argv["credential-id"] == null ? "" : encodeURIComponent(String(argv["credential-id"]))}`, - pathParams: { - "credential-set-id": String(argv["credential-set-id"] ?? ""), - "credential-id": String(argv["credential-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - location: argv["location"], - location_name: resolveFileToken( - argv["location-name"] as string | undefined, - "location-name", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - value: resolveFileToken( - argv["value"] as string | undefined, - "value", - "text" - ), - }), - sensitiveBodyPaths: [["value"]], - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - credential_set_id: argv["credential-set-id"], - credential_id: argv["credential-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - location: argv["location"], - location_name: resolveFileToken( - argv["location-name"] as string | undefined, - "location-name", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - value: resolveFileToken( - argv["value"] as string | undefined, - "value", - "text" - ), - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - credential_set_id: argv["credential-set-id"], - credential_id: argv["credential-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 api-security vulnerability-scanner credential-sets credentials update \n\nReplaces a credential. All fields must be provided.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/delete.handler.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/delete.handler.ts new file mode 100644 index 0000000000..92e93a1ef9 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/delete.handler.ts @@ -0,0 +1,63 @@ +import operation from "../../../_operations/api-security/vulnerability-scanner/credential-sets/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security vulnerability-scanner credential-sets delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: + "cf api-security vulnerability-scanner credential-sets delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/credential_sets/${argv["credential-set-id"] == null ? "" : encodeURIComponent(String(argv["credential-set-id"]))}`, + pathParams: { + "credential-set-id": String(argv["credential-set-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This operation permanently deletes the credential set and every credential it contains.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + credential_set_id: argv["credential-set-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/delete.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/delete.ts index d063547523..53eddd3e86 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/delete.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/delete.ts @@ -1,99 +1,43 @@ -import operation from "../../../_operations/api-security/vulnerability-scanner/credential-sets/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security vulnerability-scanner credential-sets delete \n\nDeletes a credential set and all of its credentials." - ) - .positional("credential-set-id", { - type: "string", - description: "Credential set identifier.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "credential-set-id", + brief: "Credential set identifier.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete credential set", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security vulnerability-scanner credential-sets delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: - "cf api-security vulnerability-scanner credential-sets delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/credential_sets/${argv["credential-set-id"] == null ? "" : encodeURIComponent(String(argv["credential-set-id"]))}`, - pathParams: { - "credential-set-id": String(argv["credential-set-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This operation permanently deletes the credential set and every credential it contains.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - credential_set_id: argv["credential-set-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 api-security vulnerability-scanner credential-sets delete \n\nDeletes a credential set and all of its credentials.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/edit.handler.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/edit.handler.ts new file mode 100644 index 0000000000..eb01d59288 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/edit.handler.ts @@ -0,0 +1,87 @@ +import operation from "../../../_operations/api-security/vulnerability-scanner/credential-sets/edit.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./edit.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security vulnerability-scanner credential-sets edit", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf api-security vulnerability-scanner credential-sets edit", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/credential_sets/${argv["credential-set-id"] == null ? "" : encodeURIComponent(String(argv["credential-set-id"]))}`, + pathParams: { + "credential-set-id": String(argv["credential-set-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + credential_set_id: argv["credential-set-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + credential_set_id: argv["credential-set-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/edit.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/edit.ts index 280735ba3f..d584925d6d 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/edit.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/edit.ts @@ -1,124 +1,50 @@ -import operation from "../../../_operations/api-security/vulnerability-scanner/credential-sets/edit.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * edit command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security vulnerability-scanner credential-sets edit \n\nUpdates a credential set with only the provided fields; omitted fields remain unchanged." - ) - .positional("credential-set-id", { - type: "string", - description: "Credential set identifier.", - demandOption: true, - }) - .option("name", { type: "string", description: "Human-readable name." }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + name: { + kind: "parsed", + brief: "Human-readable name.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: + }, + body: { + kind: "parsed", + brief: "Applies a partial update. Only the provided fields change; omitted fields remain unchanged.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "credential-set-id", + brief: "Credential set identifier.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "edit ", describe: "Edit credential set", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security vulnerability-scanner credential-sets edit", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: - "cf api-security vulnerability-scanner credential-sets edit", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/credential_sets/${argv["credential-set-id"] == null ? "" : encodeURIComponent(String(argv["credential-set-id"]))}`, - pathParams: { - "credential-set-id": String(argv["credential-set-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - credential_set_id: argv["credential-set-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - credential_set_id: argv["credential-set-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 api-security vulnerability-scanner credential-sets edit \n\nUpdates a credential set with only the provided fields; omitted fields remain unchanged.", + ...parameters, + loader: () => import("./edit.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/get.handler.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/get.handler.ts new file mode 100644 index 0000000000..f3887d2850 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/get.handler.ts @@ -0,0 +1,51 @@ +import operation from "../../../_operations/api-security/vulnerability-scanner/credential-sets/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security vulnerability-scanner credential-sets get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf api-security vulnerability-scanner credential-sets get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/credential_sets/${argv["credential-set-id"] == null ? "" : encodeURIComponent(String(argv["credential-set-id"]))}`, + pathParams: { + "credential-set-id": String(argv["credential-set-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + credential_set_id: argv["credential-set-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/get.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/get.ts index d9f97b3e47..f389b4f1db 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/get.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/get.ts @@ -1,82 +1,37 @@ -import operation from "../../../_operations/api-security/vulnerability-scanner/credential-sets/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security vulnerability-scanner credential-sets get \n\nReturns a single credential set by ID." - ) - .positional("credential-set-id", { - type: "string", - description: "Credential set identifier.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "credential-set-id", + brief: "Credential set identifier.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get credential set", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security vulnerability-scanner credential-sets get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: - "cf api-security vulnerability-scanner credential-sets get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/credential_sets/${argv["credential-set-id"] == null ? "" : encodeURIComponent(String(argv["credential-set-id"]))}`, - pathParams: { - "credential-set-id": String(argv["credential-set-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - credential_set_id: argv["credential-set-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 api-security vulnerability-scanner credential-sets get \n\nReturns a single credential set by ID.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/index.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/index.ts index f41a2f2e55..ab2e62f506 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/index.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/index.ts @@ -5,30 +5,25 @@ import $edit from "./edit.js"; import $get from "./get.js"; import $list from "./list.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * credential-sets command group * @generated from apis/overlays/api-security.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "credential-sets", describe: "Operations for vulnerability-scanner.credential-sets", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($edit) - .command($get) - .command($list) - .command($update) - .command($credentials) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + edit: $edit, + get: $get, + list: $list, + update: $update, + credentials: $credentials, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/list.handler.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/list.handler.ts new file mode 100644 index 0000000000..95a30e66c6 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/list.handler.ts @@ -0,0 +1,51 @@ +import operation from "../../../_operations/api-security/vulnerability-scanner/credential-sets/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security vulnerability-scanner credential-sets list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf api-security vulnerability-scanner credential-sets list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/credential_sets`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/list.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/list.ts index f68e00c5f3..95d188b40d 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/list.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/list.ts @@ -1,85 +1,43 @@ -import operation from "../../../_operations/api-security/vulnerability-scanner/credential-sets/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security vulnerability-scanner credential-sets list\n\nReturns all credential sets for the account." - ) - .option("page", { - type: "number", - description: "Page number of paginated results.", - }) - .option("per-page", { - type: "number", - description: "Number of results per page.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + page: { + kind: "parsed", + brief: "Page number of paginated results.", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Number of results per page.", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List credential sets", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security vulnerability-scanner credential-sets list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: - "cf api-security vulnerability-scanner credential-sets list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/credential_sets`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 api-security vulnerability-scanner credential-sets list\n\nReturns all credential sets for the account.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/update.handler.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/update.handler.ts new file mode 100644 index 0000000000..a8e7a33c45 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/update.handler.ts @@ -0,0 +1,101 @@ +import operation from "../../../_operations/api-security/vulnerability-scanner/credential-sets/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security vulnerability-scanner credential-sets update", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField( + "name", + "Human-readable name." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: + "cf api-security vulnerability-scanner credential-sets update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/credential_sets/${argv["credential-set-id"] == null ? "" : encodeURIComponent(String(argv["credential-set-id"]))}`, + pathParams: { + "credential-set-id": String(argv["credential-set-id"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + credential_set_id: argv["credential-set-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + credential_set_id: argv["credential-set-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/update.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/update.ts index aea402dc5e..5f958e18d6 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/update.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/credential-sets/update.ts @@ -1,136 +1,49 @@ -import operation from "../../../_operations/api-security/vulnerability-scanner/credential-sets/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security vulnerability-scanner credential-sets update \n\nReplaces a credential set. All fields must be provided." - ) - .positional("credential-set-id", { - type: "string", - description: "Credential set identifier.", - demandOption: true, - }) - .option("name", { type: "string", description: "Human-readable name." }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + name: { + kind: "parsed", + brief: "Human-readable name.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Full replacement. Provide all fields.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Full replacement. Provide all fields.", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "credential-set-id", + brief: "Credential set identifier.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update ", describe: "Update credential set", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security vulnerability-scanner credential-sets update", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "Human-readable name." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: - "cf api-security vulnerability-scanner credential-sets update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/credential_sets/${argv["credential-set-id"] == null ? "" : encodeURIComponent(String(argv["credential-set-id"]))}`, - pathParams: { - "credential-set-id": String(argv["credential-set-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - credential_set_id: argv["credential-set-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - credential_set_id: argv["credential-set-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 api-security vulnerability-scanner credential-sets update \n\nReplaces a credential set. All fields must be provided.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/index.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/index.ts index e642a2d3fc..44c2ef8b7d 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/index.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/index.ts @@ -1,26 +1,21 @@ import $credentialsets from "./credential-sets/index.js"; import $scans from "./scans/index.js"; import $targetenvironments from "./target-environments/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * vulnerability-scanner command group * @generated from apis/overlays/api-security.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "vulnerability-scanner", describe: "Operations for vulnerability-scanner", - builder: (yargs) => { - return yargs - .command($credentialsets) - .command($scans) - .command($targetenvironments) - .demandCommand(1, "Please specify a subcommand"); + routes: { + "credential-sets": $credentialsets, + scans: $scans, + "target-environments": $targetenvironments, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/create.handler.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/create.handler.ts new file mode 100644 index 0000000000..452a0879ae --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/create.handler.ts @@ -0,0 +1,154 @@ +import operation from "../../../_operations/api-security/vulnerability-scanner/scans/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { + promptForRequiredEnumField, + promptForRequiredField, +} from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security vulnerability-scanner scans create", + classification: { + safeFlags: ["scan-type", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["credential-sets-attacker"] === undefined) { + argv["credential-sets-attacker"] = await promptForRequiredField( + "credential-sets-attacker", + "Credential set ID for the attacker." + ); + } + if (argv["credential-sets-owner"] === undefined) { + argv["credential-sets-owner"] = await promptForRequiredField( + "credential-sets-owner", + "Credential set ID for the resource owner." + ); + } + if (argv["open-api"] === undefined) { + argv["open-api"] = await promptForRequiredField( + "open-api", + "OpenAPI schema definition for the API under test. The scanner uses this to discover endpoints and construct requests. " + ); + } + if (argv["scan-type"] === undefined) { + argv["scan-type"] = await promptForRequiredEnumField( + "scan-type", + "The scan_type field", + ["bola"] as const + ); + } + if (argv["target-environment-id"] === undefined) { + argv["target-environment-id"] = await promptForRequiredField( + "target-environment-id", + "The target environment to scan." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf api-security vulnerability-scanner scans create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/scans`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + credential_sets: { + attacker: resolveFileToken( + argv["credential-sets-attacker"] as string | undefined, + "credential-sets-attacker", + "text" + ), + owner: resolveFileToken( + argv["credential-sets-owner"] as string | undefined, + "credential-sets-owner", + "text" + ), + }, + open_api: resolveFileToken( + argv["open-api"] as string | undefined, + "open-api", + "text" + ), + scan_type: argv["scan-type"], + target_environment_id: resolveFileToken( + argv["target-environment-id"] as string | undefined, + "target-environment-id", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + credential_sets: { + attacker: resolveFileToken( + argv["credential-sets-attacker"] as string | undefined, + "credential-sets-attacker", + "text" + ), + owner: resolveFileToken( + argv["credential-sets-owner"] as string | undefined, + "credential-sets-owner", + "text" + ), + }, + open_api: resolveFileToken( + argv["open-api"] as string | undefined, + "open-api", + "text" + ), + scan_type: argv["scan-type"], + target_environment_id: resolveFileToken( + argv["target-environment-id"] as string | undefined, + "target-environment-id", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/create.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/create.ts index ac98f9cbf7..1ca7a97346 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/create.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/create.ts @@ -1,209 +1,72 @@ -import operation from "../../../_operations/api-security/vulnerability-scanner/scans/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { - promptForRequiredEnumField, - promptForRequiredField, -} from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security vulnerability-scanner scans create\n\nCreates and starts a new vulnerability scan. The response may include non-fatal warnings in the `messages` array." - ) - .option("credential-sets-attacker", { - type: "string", - description: "Credential set ID for the attacker.", - }) - .option("credential-sets-owner", { - type: "string", - description: "Credential set ID for the resource owner.", - }) - .option("open-api", { - type: "string", - description: +const parameters = { + flags: { + "credential-sets-attacker": { + kind: "parsed", + brief: "Credential set ID for the attacker.", + optional: true, + parse: String, + }, + "credential-sets-owner": { + kind: "parsed", + brief: "Credential set ID for the resource owner.", + optional: true, + parse: String, + }, + "open-api": { + kind: "parsed", + brief: "OpenAPI schema definition for the API under test. The scanner\nuses this to discover endpoints and construct requests.\n", - }) - .option("scan-type", { - type: "string", - description: "The scan_type field", + optional: true, + parse: String, + }, + "scan-type": { + kind: "parsed", + brief: "The scan_type field", + optional: true, choices: ["bola"], - }) - .coerce("scan-type", (value) => - resolveFileToken(value, "scan-type", "text") - ) - .option("target-environment-id", { - type: "string", - description: "The target environment to scan.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => resolveFileToken(value, "scan-type", "text"), + }, + "target-environment-id": { + kind: "parsed", + brief: "The target environment to scan.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: - "Create a new vulnerability scan. The \`scan_type\` discriminator selects the scan variant and its required context fields. ", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: + "Create a new vulnerability scan. The `scan_type` discriminator selects the scan variant and its required context fields. ", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Create scan", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security vulnerability-scanner scans create", - classification: { - safeFlags: ["scan-type", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["credential-sets-attacker"] === undefined) { - argv["credential-sets-attacker"] = await promptForRequiredField( - "credential-sets-attacker", - "Credential set ID for the attacker." - ); - } - if (argv["credential-sets-owner"] === undefined) { - argv["credential-sets-owner"] = await promptForRequiredField( - "credential-sets-owner", - "Credential set ID for the resource owner." - ); - } - if (argv["open-api"] === undefined) { - argv["open-api"] = await promptForRequiredField( - "open-api", - "OpenAPI schema definition for the API under test. The scanner uses this to discover endpoints and construct requests. " - ); - } - if (argv["scan-type"] === undefined) { - argv["scan-type"] = await promptForRequiredEnumField( - "scan-type", - "The scan_type field", - ["bola"] as const - ); - } - if (argv["target-environment-id"] === undefined) { - argv["target-environment-id"] = await promptForRequiredField( - "target-environment-id", - "The target environment to scan." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf api-security vulnerability-scanner scans create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/scans`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - credential_sets: { - attacker: resolveFileToken( - argv["credential-sets-attacker"] as string | undefined, - "credential-sets-attacker", - "text" - ), - owner: resolveFileToken( - argv["credential-sets-owner"] as string | undefined, - "credential-sets-owner", - "text" - ), - }, - open_api: resolveFileToken( - argv["open-api"] as string | undefined, - "open-api", - "text" - ), - scan_type: argv["scan-type"], - target_environment_id: resolveFileToken( - argv["target-environment-id"] as string | undefined, - "target-environment-id", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - credential_sets: { - attacker: resolveFileToken( - argv["credential-sets-attacker"] as string | undefined, - "credential-sets-attacker", - "text" - ), - owner: resolveFileToken( - argv["credential-sets-owner"] as string | undefined, - "credential-sets-owner", - "text" - ), - }, - open_api: resolveFileToken( - argv["open-api"] as string | undefined, - "open-api", - "text" - ), - scan_type: argv["scan-type"], - target_environment_id: resolveFileToken( - argv["target-environment-id"] as string | undefined, - "target-environment-id", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 api-security vulnerability-scanner scans create\n\nCreates and starts a new vulnerability scan. The response may include non-fatal warnings in the `messages` array.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/delete.handler.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/delete.handler.ts new file mode 100644 index 0000000000..0243a71c1a --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/delete.handler.ts @@ -0,0 +1,60 @@ +import operation from "../../../_operations/api-security/vulnerability-scanner/scans/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security vulnerability-scanner scans delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf api-security vulnerability-scanner scans delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/scans/${argv["scan-id"] == null ? "" : encodeURIComponent(String(argv["scan-id"]))}`, + pathParams: { "scan-id": String(argv["scan-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This operation permanently deletes the completed or failed scan and all associated scan data.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + scan_id: argv["scan-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/delete.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/delete.ts index 40a47e649f..3bd1ca04bf 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/delete.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/delete.ts @@ -1,96 +1,39 @@ -import operation from "../../../_operations/api-security/vulnerability-scanner/scans/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security vulnerability-scanner scans delete \n\nDeletes a scan and all associated data. Only scans in a terminal state (`finished`, `failed`) may be deleted. Attempting to delete a scan that is still being created or executed (`created`, `scheduled`, `planning`, `running`) returns `400`." - ) - .positional("scan-id", { - type: "string", - description: "Scan identifier.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "scan-id", brief: "Scan identifier.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete scan", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security vulnerability-scanner scans delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf api-security vulnerability-scanner scans delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/scans/${argv["scan-id"] == null ? "" : encodeURIComponent(String(argv["scan-id"]))}`, - pathParams: { "scan-id": String(argv["scan-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This operation permanently deletes the completed or failed scan and all associated scan data.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - scan_id: argv["scan-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 api-security vulnerability-scanner scans delete \n\nDeletes a scan and all associated data. Only scans in a terminal state (`finished`, `failed`) may be deleted. Attempting to delete a scan that is still being created or executed (`created`, `scheduled`, `planning`, `running`) returns `400`.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/get.handler.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/get.handler.ts new file mode 100644 index 0000000000..10e95ec46e --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/get.handler.ts @@ -0,0 +1,49 @@ +import operation from "../../../_operations/api-security/vulnerability-scanner/scans/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security vulnerability-scanner scans get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf api-security vulnerability-scanner scans get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/scans/${argv["scan-id"] == null ? "" : encodeURIComponent(String(argv["scan-id"]))}`, + pathParams: { "scan-id": String(argv["scan-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + scan_id: argv["scan-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/get.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/get.ts index 08953a5dc8..f07f69a53d 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/get.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/get.ts @@ -1,79 +1,33 @@ -import operation from "../../../_operations/api-security/vulnerability-scanner/scans/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security vulnerability-scanner scans get \n\nReturns a single scan by ID." - ) - .positional("scan-id", { - type: "string", - description: "Scan identifier.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "scan-id", brief: "Scan identifier.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get scan", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security vulnerability-scanner scans get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf api-security vulnerability-scanner scans get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/scans/${argv["scan-id"] == null ? "" : encodeURIComponent(String(argv["scan-id"]))}`, - pathParams: { "scan-id": String(argv["scan-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - scan_id: argv["scan-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 api-security vulnerability-scanner scans get \n\nReturns a single scan by ID.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/index.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/index.ts index 72e2a5ad11..d23dfcc455 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/index.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/index.ts @@ -2,27 +2,22 @@ import $create from "./create.js"; import $delete from "./delete.js"; import $get from "./get.js"; import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * scans command group * @generated from apis/overlays/api-security.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "scans", describe: "Operations for vulnerability-scanner.scans", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .command($list) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/list.handler.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/list.handler.ts new file mode 100644 index 0000000000..ddc66c1dce --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/list.handler.ts @@ -0,0 +1,51 @@ +import operation from "../../../_operations/api-security/vulnerability-scanner/scans/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security vulnerability-scanner scans list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf api-security vulnerability-scanner scans list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/scans`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/list.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/list.ts index 067efc3dbe..a9101df309 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/list.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/scans/list.ts @@ -1,84 +1,43 @@ -import operation from "../../../_operations/api-security/vulnerability-scanner/scans/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security vulnerability-scanner scans list\n\nReturns all scans for the account." - ) - .option("page", { - type: "number", - description: "Page number of paginated results.", - }) - .option("per-page", { - type: "number", - description: "Number of results per page.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + page: { + kind: "parsed", + brief: "Page number of paginated results.", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Number of results per page.", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List scans", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security vulnerability-scanner scans list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf api-security vulnerability-scanner scans list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/scans`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 api-security vulnerability-scanner scans list\n\nReturns all scans for the account.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/create.handler.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/create.handler.ts new file mode 100644 index 0000000000..418e0f9b7c --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/create.handler.ts @@ -0,0 +1,133 @@ +import operation from "../../../_operations/api-security/vulnerability-scanner/target-environments/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { + promptForRequiredEnumField, + promptForRequiredField, +} from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security vulnerability-scanner target-environments create", + classification: { + safeFlags: ["target-type", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField( + "name", + "Human-readable name." + ); + } + if (argv["target-type"] === undefined) { + argv["target-type"] = await promptForRequiredEnumField( + "target-type", + "The target.type field", + ["zone"] as const + ); + } + if (argv["target-zone-tag"] === undefined) { + argv["target-zone-tag"] = await promptForRequiredField( + "target-zone-tag", + "Cloudflare zone tag. The zone must belong to the account. " + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: + "cf api-security vulnerability-scanner target-environments create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/target_environments`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + target: { + type: argv["target-type"], + zone_tag: resolveFileToken( + argv["target-zone-tag"] as string | undefined, + "target-zone-tag", + "text" + ), + }, + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + target: { + type: argv["target-type"], + zone_tag: resolveFileToken( + argv["target-zone-tag"] as string | undefined, + "target-zone-tag", + "text" + ), + }, + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/create.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/create.ts index e6cfc220a4..abb09407ee 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/create.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/create.ts @@ -1,181 +1,64 @@ -import operation from "../../../_operations/api-security/vulnerability-scanner/target-environments/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { - promptForRequiredEnumField, - promptForRequiredField, -} from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security vulnerability-scanner target-environments create\n\nCreates a new target environment for the account." - ) - .option("description", { - type: "string", - description: "Optional description.", - }) - .option("name", { type: "string", description: "Human-readable name." }) - .option("target-type", { - type: "string", - description: "The target.type field", +const parameters = { + flags: { + description: { + kind: "parsed", + brief: "Optional description.", + optional: true, + parse: String, + }, + name: { + kind: "parsed", + brief: "Human-readable name.", + optional: true, + parse: String, + }, + "target-type": { + kind: "parsed", + brief: "The target.type field", + optional: true, choices: ["zone"], - }) - .coerce("target-type", (value) => - resolveFileToken(value, "target-type", "text") - ) - .option("target-zone-tag", { - type: "string", - description: - "Cloudflare zone tag. The zone must belong to the account.\n", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => resolveFileToken(value, "target-type", "text"), + }, + "target-zone-tag": { + kind: "parsed", + brief: "Cloudflare zone tag. The zone must belong to the account.\n", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Create target environment", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: - "api-security vulnerability-scanner target-environments create", - classification: { - safeFlags: ["target-type", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "Human-readable name." - ); - } - if (argv["target-type"] === undefined) { - argv["target-type"] = await promptForRequiredEnumField( - "target-type", - "The target.type field", - ["zone"] as const - ); - } - if (argv["target-zone-tag"] === undefined) { - argv["target-zone-tag"] = await promptForRequiredField( - "target-zone-tag", - "Cloudflare zone tag. The zone must belong to the account. " - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: - "cf api-security vulnerability-scanner target-environments create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/target_environments`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - target: { - type: argv["target-type"], - zone_tag: resolveFileToken( - argv["target-zone-tag"] as string | undefined, - "target-zone-tag", - "text" - ), - }, - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - target: { - type: argv["target-type"], - zone_tag: resolveFileToken( - argv["target-zone-tag"] as string | undefined, - "target-zone-tag", - "text" - ), - }, - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 api-security vulnerability-scanner target-environments create\n\nCreates a new target environment for the account.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/delete.handler.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/delete.handler.ts new file mode 100644 index 0000000000..77bd149b7b --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/delete.handler.ts @@ -0,0 +1,65 @@ +import operation from "../../../_operations/api-security/vulnerability-scanner/target-environments/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security vulnerability-scanner target-environments delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: + "cf api-security vulnerability-scanner target-environments delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/target_environments/${argv["target-environment-id"] == null ? "" : encodeURIComponent(String(argv["target-environment-id"]))}`, + pathParams: { + "target-environment-id": String( + argv["target-environment-id"] ?? "" + ), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This operation permanently deletes the target environment from Vulnerability Scanner.`, + })) + ) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + target_environment_id: argv["target-environment-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/delete.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/delete.ts index 49989d1e9f..c5b7b10e3b 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/delete.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/delete.ts @@ -1,102 +1,43 @@ -import operation from "../../../_operations/api-security/vulnerability-scanner/target-environments/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security vulnerability-scanner target-environments delete \n\nRemoves a target environment." - ) - .positional("target-environment-id", { - type: "string", - description: "Target environment identifier.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "target-environment-id", + brief: "Target environment identifier.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete target environment", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: - "api-security vulnerability-scanner target-environments delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: - "cf api-security vulnerability-scanner target-environments delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/target_environments/${argv["target-environment-id"] == null ? "" : encodeURIComponent(String(argv["target-environment-id"]))}`, - pathParams: { - "target-environment-id": String( - argv["target-environment-id"] ?? "" - ), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This operation permanently deletes the target environment from Vulnerability Scanner.`, - })) - ) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - target_environment_id: argv["target-environment-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 api-security vulnerability-scanner target-environments delete \n\nRemoves a target environment.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/edit.handler.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/edit.handler.ts new file mode 100644 index 0000000000..a88d10e96e --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/edit.handler.ts @@ -0,0 +1,116 @@ +import operation from "../../../_operations/api-security/vulnerability-scanner/target-environments/edit.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./edit.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security vulnerability-scanner target-environments edit", + classification: { + safeFlags: ["target-type", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: + "cf api-security vulnerability-scanner target-environments edit", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/target_environments/${argv["target-environment-id"] == null ? "" : encodeURIComponent(String(argv["target-environment-id"]))}`, + pathParams: { + "target-environment-id": String( + argv["target-environment-id"] ?? "" + ), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + target: { + type: argv["target-type"], + zone_tag: resolveFileToken( + argv["target-zone-tag"] as string | undefined, + "target-zone-tag", + "text" + ), + }, + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + target_environment_id: argv["target-environment-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + target: { + type: argv["target-type"], + zone_tag: resolveFileToken( + argv["target-zone-tag"] as string | undefined, + "target-zone-tag", + "text" + ), + }, + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + target_environment_id: argv["target-environment-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/edit.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/edit.ts index 67a90363f6..3a9c313b8b 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/edit.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/edit.ts @@ -1,64 +1,65 @@ -import operation from "../../../_operations/api-security/vulnerability-scanner/target-environments/edit.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * edit command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security vulnerability-scanner target-environments edit \n\nUpdates a target environment with only the provided fields; omitted fields remain unchanged." - ) - .positional("target-environment-id", { - type: "string", - description: "Target environment identifier.", - demandOption: true, - }) - .option("description", { - type: "string", - description: +const parameters = { + flags: { + description: { + kind: "parsed", + brief: "Optional description. Omit to leave unchanged, set to `null`\nto clear, or provide a string to update.\n", - }) - .option("name", { type: "string", description: "Human-readable name." }) - .option("target-type", { - type: "string", - description: "The target.type field", + optional: true, + parse: String, + }, + name: { + kind: "parsed", + brief: "Human-readable name.", + optional: true, + parse: String, + }, + "target-type": { + kind: "parsed", + brief: "The target.type field", + optional: true, choices: ["zone"], - }) - .coerce("target-type", (value) => - resolveFileToken(value, "target-type", "text") - ) - .option("target-zone-tag", { - type: "string", - description: - "Cloudflare zone tag. The zone must belong to the account.\n", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => resolveFileToken(value, "target-type", "text"), + }, + "target-zone-tag": { + kind: "parsed", + brief: "Cloudflare zone tag. The zone must belong to the account.\n", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: - 'Applies a partial update. Only the provided fields change; omitted fields remain unchanged. The \`description\` field supports three states: - **omitted**: leave unchanged - **\`null\`**: clear the description - **\`"value"\`**: set to the given string ', - }) - .check((argv) => { + }, + body: { + kind: "parsed", + brief: + 'Applies a partial update. Only the provided fields change; omitted fields remain unchanged. The `description` field supports three states: - **omitted**: leave unchanged - **`null`**: clear the description - **`"value"`**: set to the given string ', + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "target-environment-id", + brief: "Target environment identifier.", + parse: String, + }, + ], + rules(rules) { + rules.check((argv) => { const groupSet = ["target-type", "target-zone-tag"].some( (k) => argv[k] !== undefined ); @@ -74,113 +75,16 @@ function builder(yargs: Argv) { } return true; }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "edit ", describe: "Edit target environment", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security vulnerability-scanner target-environments edit", - classification: { - safeFlags: ["target-type", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: - "cf api-security vulnerability-scanner target-environments edit", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/target_environments/${argv["target-environment-id"] == null ? "" : encodeURIComponent(String(argv["target-environment-id"]))}`, - pathParams: { - "target-environment-id": String( - argv["target-environment-id"] ?? "" - ), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - target: { - type: argv["target-type"], - zone_tag: resolveFileToken( - argv["target-zone-tag"] as string | undefined, - "target-zone-tag", - "text" - ), - }, - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - target_environment_id: argv["target-environment-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - target: { - type: argv["target-type"], - zone_tag: resolveFileToken( - argv["target-zone-tag"] as string | undefined, - "target-zone-tag", - "text" - ), - }, - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - target_environment_id: argv["target-environment-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 api-security vulnerability-scanner target-environments edit \n\nUpdates a target environment with only the provided fields; omitted fields remain unchanged.", + ...parameters, + loader: () => import("./edit.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/get.handler.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/get.handler.ts new file mode 100644 index 0000000000..7b47c8b079 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/get.handler.ts @@ -0,0 +1,54 @@ +import operation from "../../../_operations/api-security/vulnerability-scanner/target-environments/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security vulnerability-scanner target-environments get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: + "cf api-security vulnerability-scanner target-environments get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/target_environments/${argv["target-environment-id"] == null ? "" : encodeURIComponent(String(argv["target-environment-id"]))}`, + pathParams: { + "target-environment-id": String( + argv["target-environment-id"] ?? "" + ), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + target_environment_id: argv["target-environment-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/get.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/get.ts index e2a020f1de..47303d47b3 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/get.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/get.ts @@ -1,84 +1,37 @@ -import operation from "../../../_operations/api-security/vulnerability-scanner/target-environments/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security vulnerability-scanner target-environments get \n\nReturns a single target environment by ID." - ) - .positional("target-environment-id", { - type: "string", - description: "Target environment identifier.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "target-environment-id", + brief: "Target environment identifier.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get target environment", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security vulnerability-scanner target-environments get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: - "cf api-security vulnerability-scanner target-environments get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/target_environments/${argv["target-environment-id"] == null ? "" : encodeURIComponent(String(argv["target-environment-id"]))}`, - pathParams: { - "target-environment-id": String( - argv["target-environment-id"] ?? "" - ), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - target_environment_id: argv["target-environment-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 api-security vulnerability-scanner target-environments get \n\nReturns a single target environment by ID.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/index.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/index.ts index c87051a9aa..62f3bd1d5b 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/index.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/index.ts @@ -4,29 +4,24 @@ import $edit from "./edit.js"; import $get from "./get.js"; import $list from "./list.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * target-environments command group * @generated from apis/overlays/api-security.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "target-environments", describe: "Operations for vulnerability-scanner.target-environments", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($edit) - .command($get) - .command($list) - .command($update) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + edit: $edit, + get: $get, + list: $list, + update: $update, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/list.handler.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/list.handler.ts new file mode 100644 index 0000000000..721aa15257 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/list.handler.ts @@ -0,0 +1,52 @@ +import operation from "../../../_operations/api-security/vulnerability-scanner/target-environments/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security vulnerability-scanner target-environments list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + page: argv["page"], + per_page: argv["per-page"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: + "cf api-security vulnerability-scanner target-environments list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/target_environments`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/list.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/list.ts index 63b302763c..f1007793f2 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/list.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/list.ts @@ -1,85 +1,43 @@ -import operation from "../../../_operations/api-security/vulnerability-scanner/target-environments/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security vulnerability-scanner target-environments list\n\nReturns all target environments for the account." - ) - .option("page", { - type: "number", - description: "Page number of paginated results.", - }) - .option("per-page", { - type: "number", - description: "Number of results per page.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + page: { + kind: "parsed", + brief: "Page number of paginated results.", + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Number of results per page.", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List target environments", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "api-security vulnerability-scanner target-environments list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page: argv["page"], - per_page: argv["per-page"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: - "cf api-security vulnerability-scanner target-environments list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/target_environments`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 api-security vulnerability-scanner target-environments list\n\nReturns all target environments for the account.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/update.handler.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/update.handler.ts new file mode 100644 index 0000000000..45a9305277 --- /dev/null +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/update.handler.ts @@ -0,0 +1,145 @@ +import operation from "../../../_operations/api-security/vulnerability-scanner/target-environments/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { + promptForRequiredEnumField, + promptForRequiredField, +} from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "api-security vulnerability-scanner target-environments update", + classification: { + safeFlags: ["target-type", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField( + "name", + "Human-readable name." + ); + } + if (argv["target-type"] === undefined) { + argv["target-type"] = await promptForRequiredEnumField( + "target-type", + "The target.type field", + ["zone"] as const + ); + } + if (argv["target-zone-tag"] === undefined) { + argv["target-zone-tag"] = await promptForRequiredField( + "target-zone-tag", + "Cloudflare zone tag. The zone must belong to the account. " + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: + "cf api-security vulnerability-scanner target-environments update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/target_environments/${argv["target-environment-id"] == null ? "" : encodeURIComponent(String(argv["target-environment-id"]))}`, + pathParams: { + "target-environment-id": String( + argv["target-environment-id"] ?? "" + ), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + target: { + type: argv["target-type"], + zone_tag: resolveFileToken( + argv["target-zone-tag"] as string | undefined, + "target-zone-tag", + "text" + ), + }, + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + target_environment_id: argv["target-environment-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + target: { + type: argv["target-type"], + zone_tag: resolveFileToken( + argv["target-zone-tag"] as string | undefined, + "target-zone-tag", + "text" + ), + }, + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + target_environment_id: argv["target-environment-id"], + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/update.ts b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/update.ts index b7bb70575e..7865e44643 100644 --- a/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/update.ts +++ b/packages/cli/src/commands/_generated/api-security/vulnerability-scanner/target-environments/update.ts @@ -1,198 +1,70 @@ -import operation from "../../../_operations/api-security/vulnerability-scanner/target-environments/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/api-security.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { - promptForRequiredEnumField, - promptForRequiredField, -} from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 api-security vulnerability-scanner target-environments update \n\nReplaces a target environment. All fields must be provided." - ) - .positional("target-environment-id", { - type: "string", - description: "Target environment identifier.", - demandOption: true, - }) - .option("description", { - type: "string", - description: "Optional description.", - }) - .option("name", { type: "string", description: "Human-readable name." }) - .option("target-type", { - type: "string", - description: "The target.type field", +const parameters = { + flags: { + description: { + kind: "parsed", + brief: "Optional description.", + optional: true, + parse: String, + }, + name: { + kind: "parsed", + brief: "Human-readable name.", + optional: true, + parse: String, + }, + "target-type": { + kind: "parsed", + brief: "The target.type field", + optional: true, choices: ["zone"], - }) - .coerce("target-type", (value) => - resolveFileToken(value, "target-type", "text") - ) - .option("target-zone-tag", { - type: "string", - description: - "Cloudflare zone tag. The zone must belong to the account.\n", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => resolveFileToken(value, "target-type", "text"), + }, + "target-zone-tag": { + kind: "parsed", + brief: "Cloudflare zone tag. The zone must belong to the account.\n", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Full replacement.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Full replacement.", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "target-environment-id", + brief: "Target environment identifier.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update ", describe: "Update target environment", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: - "api-security vulnerability-scanner target-environments update", - classification: { - safeFlags: ["target-type", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "Human-readable name." - ); - } - if (argv["target-type"] === undefined) { - argv["target-type"] = await promptForRequiredEnumField( - "target-type", - "The target.type field", - ["zone"] as const - ); - } - if (argv["target-zone-tag"] === undefined) { - argv["target-zone-tag"] = await promptForRequiredField( - "target-zone-tag", - "Cloudflare zone tag. The zone must belong to the account. " - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: - "cf api-security vulnerability-scanner target-environments update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/vuln_scanner/target_environments/${argv["target-environment-id"] == null ? "" : encodeURIComponent(String(argv["target-environment-id"]))}`, - pathParams: { - "target-environment-id": String( - argv["target-environment-id"] ?? "" - ), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - target: { - type: argv["target-type"], - zone_tag: resolveFileToken( - argv["target-zone-tag"] as string | undefined, - "target-zone-tag", - "text" - ), - }, - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - target_environment_id: argv["target-environment-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - target: { - type: argv["target-type"], - zone_tag: resolveFileToken( - argv["target-zone-tag"] as string | undefined, - "target-zone-tag", - "text" - ), - }, - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - target_environment_id: argv["target-environment-id"], - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 api-security vulnerability-scanner target-environments update \n\nReplaces a target environment. All fields must be provided.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/argo/index.ts b/packages/cli/src/commands/_generated/argo/index.ts index 5e43eda985..c4ff84d8db 100644 --- a/packages/cli/src/commands/_generated/argo/index.ts +++ b/packages/cli/src/commands/_generated/argo/index.ts @@ -1,25 +1,20 @@ import $smartrouting from "./smart-routing/index.js"; import $tieredcaching from "./tiered-caching/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * argo command * @generated from apis/overlays/argo.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "argo", describe: "Network optimization features that speed up and improve reliability of traffic to your origins", - builder: (yargs) => { - return yargs - .command($smartrouting) - .command($tieredcaching) - .demandCommand(1, "Please specify a subcommand"); + routes: { + "smart-routing": $smartrouting, + "tiered-caching": $tieredcaching, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/argo/smart-routing/count-zones-enabled-for-account.handler.ts b/packages/cli/src/commands/_generated/argo/smart-routing/count-zones-enabled-for-account.handler.ts new file mode 100644 index 0000000000..105cb4b71a --- /dev/null +++ b/packages/cli/src/commands/_generated/argo/smart-routing/count-zones-enabled-for-account.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/argo/smart-routing/count-zones-enabled-for-account.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./count-zones-enabled-for-account.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "argo smart-routing count-zones-enabled-for-account", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf argo smart-routing count-zones-enabled-for-account", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/argo/count_zones_enabled`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/argo/smart-routing/count-zones-enabled-for-account.ts b/packages/cli/src/commands/_generated/argo/smart-routing/count-zones-enabled-for-account.ts index 994a991f8a..07f1f20716 100644 --- a/packages/cli/src/commands/_generated/argo/smart-routing/count-zones-enabled-for-account.ts +++ b/packages/cli/src/commands/_generated/argo/smart-routing/count-zones-enabled-for-account.ts @@ -1,71 +1,31 @@ -import operation from "../../_operations/argo/smart-routing/count-zones-enabled-for-account.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * count-zones-enabled-for-account command * @generated from apis/overlays/argo.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 argo smart-routing count-zones-enabled-for-account\n\nReturns the number of zones that have Argo Smart Routing enabled for the specified account." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "count-zones-enabled-for-account", describe: "Get count of zones with Argo Smart Routing enabled for account", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "argo smart-routing count-zones-enabled-for-account", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf argo smart-routing count-zones-enabled-for-account", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/argo/count_zones_enabled`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 argo smart-routing count-zones-enabled-for-account\n\nReturns the number of zones that have Argo Smart Routing enabled for the specified account.", + ...parameters, + loader: () => import("./count-zones-enabled-for-account.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/argo/smart-routing/count-zones-enabled-for-user.handler.ts b/packages/cli/src/commands/_generated/argo/smart-routing/count-zones-enabled-for-user.handler.ts new file mode 100644 index 0000000000..0771be38a3 --- /dev/null +++ b/packages/cli/src/commands/_generated/argo/smart-routing/count-zones-enabled-for-user.handler.ts @@ -0,0 +1,38 @@ +import operation from "../../_operations/argo/smart-routing/count-zones-enabled-for-user.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./count-zones-enabled-for-user.js"; +import { createCommandClient } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "argo smart-routing count-zones-enabled-for-user", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf argo smart-routing count-zones-enabled-for-user", + method: "GET", + url: `https://api.cloudflare.com/client/v4/user/argo/count_zones_enabled`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + + const result = await withProgress(`Loading`, async () => + client.send(operation) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/argo/smart-routing/count-zones-enabled-for-user.ts b/packages/cli/src/commands/_generated/argo/smart-routing/count-zones-enabled-for-user.ts index da3e0aa88b..acf7cec3c9 100644 --- a/packages/cli/src/commands/_generated/argo/smart-routing/count-zones-enabled-for-user.ts +++ b/packages/cli/src/commands/_generated/argo/smart-routing/count-zones-enabled-for-user.ts @@ -1,63 +1,31 @@ -import operation from "../../_operations/argo/smart-routing/count-zones-enabled-for-user.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * count-zones-enabled-for-user command * @generated from apis/overlays/argo.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 argo smart-routing count-zones-enabled-for-user\n\nReturns the number of zones that have Argo Smart Routing enabled for the authenticated user." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "count-zones-enabled-for-user", describe: "Get count of zones with Argo Smart Routing enabled for user", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "argo smart-routing count-zones-enabled-for-user", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf argo smart-routing count-zones-enabled-for-user", - method: "GET", - url: `https://api.cloudflare.com/client/v4/user/argo/count_zones_enabled`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - - const result = await withProgress(`Loading`, async () => - client.send(operation) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 argo smart-routing count-zones-enabled-for-user\n\nReturns the number of zones that have Argo Smart Routing enabled for the authenticated user.", + ...parameters, + loader: () => import("./count-zones-enabled-for-user.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/argo/smart-routing/edit.handler.ts b/packages/cli/src/commands/_generated/argo/smart-routing/edit.handler.ts new file mode 100644 index 0000000000..e15b5f0c28 --- /dev/null +++ b/packages/cli/src/commands/_generated/argo/smart-routing/edit.handler.ts @@ -0,0 +1,78 @@ +import operation from "../../_operations/argo/smart-routing/edit.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./edit.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredEnumField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "argo smart-routing edit", + classification: { + safeFlags: ["value", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["value"] === undefined) { + argv["value"] = await promptForRequiredEnumField( + "value", + "Specifies the enablement value of Argo Smart Routing.", + ["on", "off"] as const + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + formatDryRun({ + command: "cf argo smart-routing edit", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/argo/smart_routing`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + value: argv["value"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + value: argv["value"], + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/argo/smart-routing/edit.ts b/packages/cli/src/commands/_generated/argo/smart-routing/edit.ts index 0ba4b385c4..ebf3ebcc82 100644 --- a/packages/cli/src/commands/_generated/argo/smart-routing/edit.ts +++ b/packages/cli/src/commands/_generated/argo/smart-routing/edit.ts @@ -1,116 +1,46 @@ -import operation from "../../_operations/argo/smart-routing/edit.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * edit command * @generated from apis/overlays/argo.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredEnumField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 argo smart-routing edit\n\nConfigures the value of the Argo Smart Routing enablement setting." - ) - .option("value", { - type: "string", - description: "Specifies the enablement value of Argo Smart Routing.", +const parameters = { + flags: { + value: { + kind: "parsed", + brief: "Specifies the enablement value of Argo Smart Routing.", + optional: true, choices: ["on", "off"], - }) - .coerce("value", (value) => resolveFileToken(value, "value", "text")) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => resolveFileToken(value, "value", "text"), + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Configures the enablement of Argo Smart Routing.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Configures the enablement of Argo Smart Routing.", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "edit", describe: "Patch Argo Smart Routing setting", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "argo smart-routing edit", - classification: { - safeFlags: ["value", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["value"] === undefined) { - argv["value"] = await promptForRequiredEnumField( - "value", - "Specifies the enablement value of Argo Smart Routing.", - ["on", "off"] as const - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - formatDryRun({ - command: "cf argo smart-routing edit", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/argo/smart_routing`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - value: argv["value"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - value: argv["value"], - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 argo smart-routing edit\n\nConfigures the value of the Argo Smart Routing enablement setting.", + ...parameters, + loader: () => import("./edit.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/argo/smart-routing/get.handler.ts b/packages/cli/src/commands/_generated/argo/smart-routing/get.handler.ts new file mode 100644 index 0000000000..d92bead88d --- /dev/null +++ b/packages/cli/src/commands/_generated/argo/smart-routing/get.handler.ts @@ -0,0 +1,42 @@ +import operation from "../../_operations/argo/smart-routing/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "argo smart-routing get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf argo smart-routing get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/argo/smart_routing`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/argo/smart-routing/get.ts b/packages/cli/src/commands/_generated/argo/smart-routing/get.ts index 05ac3f55e1..63e2913e04 100644 --- a/packages/cli/src/commands/_generated/argo/smart-routing/get.ts +++ b/packages/cli/src/commands/_generated/argo/smart-routing/get.ts @@ -1,69 +1,31 @@ -import operation from "../../_operations/argo/smart-routing/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/argo.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 argo smart-routing get\n\nRetrieves the value of Argo Smart Routing enablement setting." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "Get Argo Smart Routing setting", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "argo smart-routing get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf argo smart-routing get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/argo/smart_routing`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 argo smart-routing get\n\nRetrieves the value of Argo Smart Routing enablement setting.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/argo/smart-routing/index.ts b/packages/cli/src/commands/_generated/argo/smart-routing/index.ts index 4cfa56f71d..948d10c793 100644 --- a/packages/cli/src/commands/_generated/argo/smart-routing/index.ts +++ b/packages/cli/src/commands/_generated/argo/smart-routing/index.ts @@ -2,28 +2,23 @@ import $countzonesenabledforaccount from "./count-zones-enabled-for-account.js"; import $countzonesenabledforuser from "./count-zones-enabled-for-user.js"; import $edit from "./edit.js"; import $get from "./get.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * smart-routing command group * @generated from apis/overlays/argo.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "smart-routing", describe: "Route traffic through the fastest network paths to your origin using real-time latency data", - builder: (yargs) => { - return yargs - .command($countzonesenabledforaccount) - .command($countzonesenabledforuser) - .command($edit) - .command($get) - .demandCommand(1, "Please specify a subcommand"); + routes: { + "count-zones-enabled-for-account": $countzonesenabledforaccount, + "count-zones-enabled-for-user": $countzonesenabledforuser, + edit: $edit, + get: $get, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/argo/tiered-caching/edit.handler.ts b/packages/cli/src/commands/_generated/argo/tiered-caching/edit.handler.ts new file mode 100644 index 0000000000..10087a7490 --- /dev/null +++ b/packages/cli/src/commands/_generated/argo/tiered-caching/edit.handler.ts @@ -0,0 +1,78 @@ +import operation from "../../_operations/argo/tiered-caching/edit.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./edit.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredEnumField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "argo tiered-caching edit", + classification: { + safeFlags: ["value", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["value"] === undefined) { + argv["value"] = await promptForRequiredEnumField( + "value", + "Enables or disables Tiered Cache.", + ["on", "off"] as const + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + formatDryRun({ + command: "cf argo tiered-caching edit", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/argo/tiered_caching`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + value: argv["value"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + value: argv["value"], + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/argo/tiered-caching/edit.ts b/packages/cli/src/commands/_generated/argo/tiered-caching/edit.ts index 9f042fb71d..c9f8aa21e3 100644 --- a/packages/cli/src/commands/_generated/argo/tiered-caching/edit.ts +++ b/packages/cli/src/commands/_generated/argo/tiered-caching/edit.ts @@ -1,116 +1,46 @@ -import operation from "../../_operations/argo/tiered-caching/edit.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * edit command * @generated from apis/overlays/argo.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredEnumField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 argo tiered-caching edit\n\nEnables or disables Tiered Cache for a zone. Tiered Cache reduces origin traffic by serving lower-tier cache misses from upper-tier data centers before requesting content from your origin." - ) - .option("value", { - type: "string", - description: "Enables or disables Tiered Cache.", +const parameters = { + flags: { + value: { + kind: "parsed", + brief: "Enables or disables Tiered Cache.", + optional: true, choices: ["on", "off"], - }) - .coerce("value", (value) => resolveFileToken(value, "value", "text")) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => resolveFileToken(value, "value", "text"), + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Updates whether Tiered Cache is enabled for a zone.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Updates whether Tiered Cache is enabled for a zone.", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "edit", describe: "Update Tiered Cache", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "argo tiered-caching edit", - classification: { - safeFlags: ["value", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["value"] === undefined) { - argv["value"] = await promptForRequiredEnumField( - "value", - "Enables or disables Tiered Cache.", - ["on", "off"] as const - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - formatDryRun({ - command: "cf argo tiered-caching edit", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/argo/tiered_caching`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - value: argv["value"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - value: argv["value"], - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 argo tiered-caching edit\n\nEnables or disables Tiered Cache for a zone. Tiered Cache reduces origin traffic by serving lower-tier cache misses from upper-tier data centers before requesting content from your origin.", + ...parameters, + loader: () => import("./edit.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/argo/tiered-caching/get.handler.ts b/packages/cli/src/commands/_generated/argo/tiered-caching/get.handler.ts new file mode 100644 index 0000000000..923c6c98fd --- /dev/null +++ b/packages/cli/src/commands/_generated/argo/tiered-caching/get.handler.ts @@ -0,0 +1,42 @@ +import operation from "../../_operations/argo/tiered-caching/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "argo tiered-caching get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf argo tiered-caching get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/argo/tiered_caching`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/argo/tiered-caching/get.ts b/packages/cli/src/commands/_generated/argo/tiered-caching/get.ts index 24736a9fad..a169ba0043 100644 --- a/packages/cli/src/commands/_generated/argo/tiered-caching/get.ts +++ b/packages/cli/src/commands/_generated/argo/tiered-caching/get.ts @@ -1,69 +1,31 @@ -import operation from "../../_operations/argo/tiered-caching/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/argo.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 argo tiered-caching get\n\nRetrieves whether Tiered Cache is enabled for a zone. Tiered Cache reduces origin traffic by serving lower-tier cache misses from upper-tier data centers before requesting content from your origin." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "Get Tiered Cache", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "argo tiered-caching get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf argo tiered-caching get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/argo/tiered_caching`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 argo tiered-caching get\n\nRetrieves whether Tiered Cache is enabled for a zone. Tiered Cache reduces origin traffic by serving lower-tier cache misses from upper-tier data centers before requesting content from your origin.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/argo/tiered-caching/index.ts b/packages/cli/src/commands/_generated/argo/tiered-caching/index.ts index 81ea69c553..ec95fa1756 100644 --- a/packages/cli/src/commands/_generated/argo/tiered-caching/index.ts +++ b/packages/cli/src/commands/_generated/argo/tiered-caching/index.ts @@ -1,25 +1,20 @@ import $edit from "./edit.js"; import $get from "./get.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * tiered-caching command group * @generated from apis/overlays/argo.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "tiered-caching", describe: "Reduce origin load by having upper-tier data centers serve cache misses before reaching your origin", - builder: (yargs) => { - return yargs - .command($edit) - .command($get) - .demandCommand(1, "Please specify a subcommand"); + routes: { + edit: $edit, + get: $get, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/index.ts b/packages/cli/src/commands/_generated/artifacts/index.ts index 37717fa80a..3ae072fefc 100644 --- a/packages/cli/src/commands/_generated/artifacts/index.ts +++ b/packages/cli/src/commands/_generated/artifacts/index.ts @@ -1,22 +1,17 @@ import $namespaces from "./namespaces/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * artifacts command * @generated from apis/overlays/artifacts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "artifacts", describe: "artifacts", - builder: (yargs) => { - return yargs - .command($namespaces) - .demandCommand(1, "Please specify a subcommand"); + routes: { + namespaces: $namespaces, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/create.handler.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/create.handler.ts new file mode 100644 index 0000000000..ca76b71823 --- /dev/null +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/create.handler.ts @@ -0,0 +1,92 @@ +import operation from "../../_operations/artifacts/namespaces/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "artifacts namespaces create", + classification: { + safeFlags: ["jurisdiction", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["namespace"] === undefined) { + argv["namespace"] = await promptForRequiredField( + "namespace", + "The namespace field" + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf artifacts namespaces create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + jurisdiction: argv["jurisdiction"], + namespace: resolveFileToken( + argv["namespace"] as string | undefined, + "namespace", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + jurisdiction: argv["jurisdiction"], + namespace: resolveFileToken( + argv["namespace"] as string | undefined, + "namespace", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/create.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/create.ts index e80bdb1ca8..760a51eaba 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/create.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/create.ts @@ -1,131 +1,53 @@ -import operation from "../../_operations/artifacts/namespaces/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/artifacts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 artifacts namespaces create\n\nCreates an empty Artifacts namespace for an account." - ) - .option("jurisdiction", { - type: "string", - description: "The jurisdiction field", - choices: ["unrestricted", "us", "eu", "fedramp"], +const parameters = { + flags: { + jurisdiction: { + kind: "parsed", + brief: "The jurisdiction field", default: "unrestricted", - }) - .coerce("jurisdiction", (value) => - resolveFileToken(value, "jurisdiction", "text") - ) - .option("namespace", { type: "string", description: "The namespace field" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + choices: ["unrestricted", "us", "eu", "fedramp"], + parse: String, + coerce: (value: string) => + resolveFileToken(value, "jurisdiction", "text"), + }, + namespace: { + kind: "parsed", + brief: "The namespace field", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Create a namespace", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "artifacts namespaces create", - classification: { - safeFlags: ["jurisdiction", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["namespace"] === undefined) { - argv["namespace"] = await promptForRequiredField( - "namespace", - "The namespace field" - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf artifacts namespaces create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - jurisdiction: argv["jurisdiction"], - namespace: resolveFileToken( - argv["namespace"] as string | undefined, - "namespace", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - jurisdiction: argv["jurisdiction"], - namespace: resolveFileToken( - argv["namespace"] as string | undefined, - "namespace", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 artifacts namespaces create\n\nCreates an empty Artifacts namespace for an account.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/delete.handler.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/delete.handler.ts new file mode 100644 index 0000000000..b6525d6487 --- /dev/null +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/delete.handler.ts @@ -0,0 +1,55 @@ +import operation from "../../_operations/artifacts/namespaces/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "artifacts namespaces delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf artifacts namespaces delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}`, + pathParams: { namespace: String(argv["namespace"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + namespace: argv["namespace"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/delete.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/delete.ts index f6ade70a65..b18be98af3 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/delete.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/delete.ts @@ -1,91 +1,43 @@ -import operation from "../../_operations/artifacts/namespaces/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/artifacts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 artifacts namespaces delete \n\nDeletes an empty Artifacts namespace." - ) - .positional("namespace", { - type: "string", - description: "Artifacts namespace name.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "namespace", + brief: "Artifacts namespace name.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete a namespace", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "artifacts namespaces delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf artifacts namespaces delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}`, - pathParams: { namespace: String(argv["namespace"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - namespace: argv["namespace"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 artifacts namespaces delete \n\nDeletes an empty Artifacts namespace.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/get.handler.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/get.handler.ts new file mode 100644 index 0000000000..9d8b5dcc4b --- /dev/null +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/get.handler.ts @@ -0,0 +1,49 @@ +import operation from "../../_operations/artifacts/namespaces/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "artifacts namespaces get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf artifacts namespaces get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}`, + pathParams: { namespace: String(argv["namespace"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + namespace: argv["namespace"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/get.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/get.ts index 3f13fbc8a6..db28b51f66 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/get.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/get.ts @@ -1,79 +1,37 @@ -import operation from "../../_operations/artifacts/namespaces/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/artifacts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 artifacts namespaces get \n\nReturns an Artifacts namespace summary." - ) - .positional("namespace", { - type: "string", - description: "Artifacts namespace name.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "namespace", + brief: "Artifacts namespace name.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get a namespace", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "artifacts namespaces get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf artifacts namespaces get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}`, - pathParams: { namespace: String(argv["namespace"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - namespace: argv["namespace"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 artifacts namespaces get \n\nReturns an Artifacts namespace summary.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/index.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/index.ts index cc93003950..c37ee0b0f3 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/index.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/index.ts @@ -4,29 +4,24 @@ import $get from "./get.js"; import $list from "./list.js"; import $repos from "./repos/index.js"; import $tokens from "./tokens/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * namespaces command group * @generated from apis/overlays/artifacts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "namespaces", describe: "Operations for namespaces", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .command($list) - .command($repos) - .command($tokens) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, + list: $list, + repos: $repos, + tokens: $tokens, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/list.handler.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/list.handler.ts new file mode 100644 index 0000000000..a32c681312 --- /dev/null +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/list.handler.ts @@ -0,0 +1,51 @@ +import operation from "../../_operations/artifacts/namespaces/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "artifacts namespaces list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + limit: argv["limit"], + cursor: argv["cursor"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf artifacts namespaces list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/list.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/list.ts index cd1c1dbbda..2cd0f19f63 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/list.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/list.ts @@ -1,78 +1,33 @@ -import operation from "../../_operations/artifacts/namespaces/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/artifacts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 artifacts namespaces list\n\nLists Artifacts namespaces for an account." - ) - .option("limit", { type: "number", description: "Limit" }) - .option("cursor", { type: "string", description: "Cursor" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + limit: { kind: "parsed", brief: "Limit", optional: true, parse: Number }, + cursor: { kind: "parsed", brief: "Cursor", optional: true, parse: String }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List namespaces", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "artifacts namespaces list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - limit: argv["limit"], - cursor: argv["cursor"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf artifacts namespaces list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 artifacts namespaces list\n\nLists Artifacts namespaces for an account.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/blobs/get.handler.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/blobs/get.handler.ts new file mode 100644 index 0000000000..9baa796d77 --- /dev/null +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/blobs/get.handler.ts @@ -0,0 +1,60 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { fetchRawBytes, writeRawOutput } from "#lib/raw-fetch.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "artifacts namespaces repos blobs get", + classification: { + safeFlags: ["dry-run", "text"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf artifacts namespaces repos blobs get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos/${argv["name"] == null ? "" : encodeURIComponent(String(argv["name"]))}/blob/${argv["hash"] == null ? "" : encodeURIComponent(String(argv["hash"]))}`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + name: String(argv["name"] ?? ""), + hash: String(argv["hash"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const __cfRawBytes = await withProgress(`Loading`, async () => + fetchRawBytes( + `/accounts/${accountId}/artifacts/namespaces/${encodeURIComponent(String(argv["namespace"]))}/repos/${encodeURIComponent(String(argv["name"]))}/blob/${encodeURIComponent(String(argv["hash"]))}`, + { + method: "GET", + local: argv.local === true, + persistTo: argv.persistTo as string | undefined, + } + ) + ); + writeRawOutput( + argv.text === true ? __cfRawBytes.toString("utf-8") : __cfRawBytes + ); + return; + } + ); +} diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/blobs/get.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/blobs/get.ts index 97e0a4d8bc..c7a9a4a03d 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/blobs/get.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/blobs/get.ts @@ -1,106 +1,49 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/artifacts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { fetchRawBytes, writeRawOutput } from "#lib/raw-fetch.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 artifacts namespaces repos blobs get \n\nReturns raw bytes for an immutable Git blob object. Blob responses are cacheable forever by hash." - ) - .positional("hash", { - type: "string", - description: "40-character lowercase hexadecimal Git object hash.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Artifacts namespace name.", - demandOption: true, - }) - .option("name", { - type: "string", - description: "Repository name.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Artifacts namespace name.", + parse: String, + }, + name: { kind: "parsed", brief: "Repository name.", parse: String }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("text", { - type: "boolean", - description: + }, + text: { + kind: "boolean", + brief: "Decode the response body as UTF-8 text instead of writing raw bytes", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "hash", + brief: "40-character lowercase hexadecimal Git object hash.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Read a Git blob", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "artifacts namespaces repos blobs get", - classification: { - safeFlags: ["dry-run", "text"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf artifacts namespaces repos blobs get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos/${argv["name"] == null ? "" : encodeURIComponent(String(argv["name"]))}/blob/${argv["hash"] == null ? "" : encodeURIComponent(String(argv["hash"]))}`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - name: String(argv["name"] ?? ""), - hash: String(argv["hash"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const __cfRawBytes = await withProgress(`Loading`, async () => - fetchRawBytes( - `/accounts/${accountId}/artifacts/namespaces/${encodeURIComponent(String(argv["namespace"]))}/repos/${encodeURIComponent(String(argv["name"]))}/blob/${encodeURIComponent(String(argv["hash"]))}`, - { - method: "GET", - local: argv.local === true, - persistTo: argv.persistTo as string | undefined, - } - ) - ); - writeRawOutput( - argv.text === true ? __cfRawBytes.toString("utf-8") : __cfRawBytes - ); - return; - } - ), -}; + usage: + "$0 artifacts namespaces repos blobs get \n\nReturns raw bytes for an immutable Git blob object. Blob responses are cacheable forever by hash.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/blobs/index.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/blobs/index.ts index e2658f6bab..aa8ea15033 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/blobs/index.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/blobs/index.ts @@ -1,20 +1,17 @@ import $get from "./get.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * blobs command group * @generated from apis/overlays/artifacts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "blobs", describe: "Operations for namespaces.repos.blobs", - builder: (yargs) => { - return yargs.command($get).demandCommand(1, "Please specify a subcommand"); + routes: { + get: $get, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/commits/get.handler.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/commits/get.handler.ts new file mode 100644 index 0000000000..2c0c862105 --- /dev/null +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/commits/get.handler.ts @@ -0,0 +1,55 @@ +import operation from "../../../../_operations/artifacts/namespaces/repos/commits/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "artifacts namespaces repos commits get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf artifacts namespaces repos commits get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos/${argv["name"] == null ? "" : encodeURIComponent(String(argv["name"]))}/commit/${argv["hash"] == null ? "" : encodeURIComponent(String(argv["hash"]))}`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + name: String(argv["name"] ?? ""), + hash: String(argv["hash"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + namespace: argv["namespace"], + name: argv["name"], + hash: argv["hash"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/commits/get.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/commits/get.ts index 68c8a0e9b6..7ca3d4e4dc 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/commits/get.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/commits/get.ts @@ -1,95 +1,43 @@ -import operation from "../../../../_operations/artifacts/namespaces/repos/commits/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/artifacts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 artifacts namespaces repos commits get \n\nReturns decoded metadata for an immutable Git commit object. Commit responses are cacheable forever by hash." - ) - .positional("hash", { - type: "string", - description: "40-character lowercase hexadecimal Git object hash.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Artifacts namespace name.", - demandOption: true, - }) - .option("name", { - type: "string", - description: "Repository name.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Artifacts namespace name.", + parse: String, + }, + name: { kind: "parsed", brief: "Repository name.", parse: String }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "hash", + brief: "40-character lowercase hexadecimal Git object hash.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Read a Git commit", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "artifacts namespaces repos commits get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf artifacts namespaces repos commits get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos/${argv["name"] == null ? "" : encodeURIComponent(String(argv["name"]))}/commit/${argv["hash"] == null ? "" : encodeURIComponent(String(argv["hash"]))}`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - name: String(argv["name"] ?? ""), - hash: String(argv["hash"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - namespace: argv["namespace"], - name: argv["name"], - hash: argv["hash"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 artifacts namespaces repos commits get \n\nReturns decoded metadata for an immutable Git commit object. Commit responses are cacheable forever by hash.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/commits/index.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/commits/index.ts index f46859da73..29ee1fb6be 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/commits/index.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/commits/index.ts @@ -1,20 +1,17 @@ import $get from "./get.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * commits command group * @generated from apis/overlays/artifacts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "commits", describe: "Operations for namespaces.repos.commits", - builder: (yargs) => { - return yargs.command($get).demandCommand(1, "Please specify a subcommand"); + routes: { + get: $get, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/create.handler.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/create.handler.ts new file mode 100644 index 0000000000..aa6e38f196 --- /dev/null +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/create.handler.ts @@ -0,0 +1,117 @@ +import operation from "../../../_operations/artifacts/namespaces/repos/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "artifacts namespaces repos create", + classification: { + safeFlags: ["read-only", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField("name", "The name field"); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf artifacts namespaces repos create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos`, + pathParams: { namespace: String(argv["namespace"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + default_branch: resolveFileToken( + argv["default-branch"] as string | undefined, + "default-branch", + "text" + ), + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + read_only: argv["read-only"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + namespace: argv["namespace"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + default_branch: resolveFileToken( + argv["default-branch"] as string | undefined, + "default-branch", + "text" + ), + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + read_only: argv["read-only"], + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + namespace: argv["namespace"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/create.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/create.ts index 20fef1d680..188f9d6671 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/create.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/create.ts @@ -1,168 +1,67 @@ -import operation from "../../../_operations/artifacts/namespaces/repos/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/artifacts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 artifacts namespaces repos create \n\nCreates a Git-compatible Artifacts repository in a namespace." - ) - .positional("namespace", { - type: "string", - description: "Artifacts namespace name.", - demandOption: true, - }) - .option("default-branch", { - type: "string", - description: +const parameters = { + flags: { + "default-branch": { + kind: "parsed", + brief: "Git branch name. Must match /^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/, must not contain '..', and must not end with '/' or '.'.", - }) - .option("description", { - type: "string", - description: "The description field", - }) - .option("name", { type: "string", description: "The name field" }) - .option("read-only", { - type: "boolean", - description: "The read_only field", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + description: { + kind: "parsed", + brief: "The description field", + optional: true, + parse: String, + }, + name: { + kind: "parsed", + brief: "The name field", + optional: true, + parse: String, + }, + "read-only": { + kind: "boolean", + brief: "The read_only field", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "namespace", + brief: "Artifacts namespace name.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Create a repository", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "artifacts namespaces repos create", - classification: { - safeFlags: ["read-only", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "The name field" - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf artifacts namespaces repos create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos`, - pathParams: { namespace: String(argv["namespace"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - default_branch: resolveFileToken( - argv["default-branch"] as string | undefined, - "default-branch", - "text" - ), - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - read_only: argv["read-only"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - namespace: argv["namespace"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - default_branch: resolveFileToken( - argv["default-branch"] as string | undefined, - "default-branch", - "text" - ), - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - read_only: argv["read-only"], - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - namespace: argv["namespace"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 artifacts namespaces repos create \n\nCreates a Git-compatible Artifacts repository in a namespace.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/delete.handler.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/delete.handler.ts new file mode 100644 index 0000000000..98be9e5d9f --- /dev/null +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/delete.handler.ts @@ -0,0 +1,59 @@ +import operation from "../../../_operations/artifacts/namespaces/repos/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "artifacts namespaces repos delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf artifacts namespaces repos delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos/${argv["name"] == null ? "" : encodeURIComponent(String(argv["name"]))}`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + name: String(argv["name"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + namespace: argv["namespace"], + name: argv["name"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/delete.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/delete.ts index f3746a7e5e..972bb8e9b3 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/delete.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/delete.ts @@ -1,100 +1,42 @@ -import operation from "../../../_operations/artifacts/namespaces/repos/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/artifacts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 artifacts namespaces repos delete \n\nDeletes a repository and schedules cleanup of its backing data." - ) - .positional("name", { - type: "string", - description: "Repository name.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Artifacts namespace name.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Artifacts namespace name.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "name", brief: "Repository name.", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete a repository", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "artifacts namespaces repos delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf artifacts namespaces repos delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos/${argv["name"] == null ? "" : encodeURIComponent(String(argv["name"]))}`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - name: String(argv["name"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - namespace: argv["namespace"], - name: argv["name"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 artifacts namespaces repos delete \n\nDeletes a repository and schedules cleanup of its backing data.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/files/get.handler.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/files/get.handler.ts new file mode 100644 index 0000000000..d40f168725 --- /dev/null +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/files/get.handler.ts @@ -0,0 +1,69 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { fetchRawBytes, writeRawOutput } from "#lib/raw-fetch.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "artifacts namespaces repos files get", + classification: { + safeFlags: ["dry-run", "text"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + ref: argv["ref"], + path: argv["path"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf artifacts namespaces repos files get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos/${argv["name"] == null ? "" : encodeURIComponent(String(argv["name"]))}/file`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + name: String(argv["name"] ?? ""), + }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const qs = new URLSearchParams( + Object.entries(queryParams) + .filter(([, v]) => v !== undefined) + .map(([k, v]) => [k, String(v)]) + ).toString(); + const __cfRawBytes = await withProgress(`Loading`, async () => + fetchRawBytes( + `/accounts/${accountId}/artifacts/namespaces/${encodeURIComponent(String(argv["namespace"]))}/repos/${encodeURIComponent(String(argv["name"]))}/file${qs ? "?" + qs : ""}`, + { + method: "GET", + local: argv.local === true, + persistTo: argv.persistTo as string | undefined, + } + ) + ); + writeRawOutput( + argv.text === true ? __cfRawBytes.toString("utf-8") : __cfRawBytes + ); + return; + } + ); +} diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/files/get.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/files/get.ts index d79572c71e..708e30d739 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/files/get.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/files/get.ts @@ -1,120 +1,48 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/artifacts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { fetchRawBytes, writeRawOutput } from "#lib/raw-fetch.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 artifacts namespaces repos files get \n\nReturns raw bytes for a file resolved by ref and path." - ) - .positional("name", { - type: "string", - description: "Repository name.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Artifacts namespace name.", - demandOption: true, - }) - .option("ref", { - type: "string", - description: "Git ref, branch, tag, or commit hash.", - demandOption: true, - }) - .option("path", { - type: "string", - description: "File path.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Artifacts namespace name.", + parse: String, + }, + ref: { + kind: "parsed", + brief: "Git ref, branch, tag, or commit hash.", + parse: String, + }, + path: { kind: "parsed", brief: "File path.", parse: String }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("text", { - type: "boolean", - description: + }, + text: { + kind: "boolean", + brief: "Decode the response body as UTF-8 text instead of writing raw bytes", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "name", brief: "Repository name.", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Read a file", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "artifacts namespaces repos files get", - classification: { - safeFlags: ["dry-run", "text"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - ref: argv["ref"], - path: argv["path"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf artifacts namespaces repos files get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos/${argv["name"] == null ? "" : encodeURIComponent(String(argv["name"]))}/file`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - name: String(argv["name"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const qs = new URLSearchParams( - Object.entries(queryParams) - .filter(([, v]) => v !== undefined) - .map(([k, v]) => [k, String(v)]) - ).toString(); - const __cfRawBytes = await withProgress(`Loading`, async () => - fetchRawBytes( - `/accounts/${accountId}/artifacts/namespaces/${encodeURIComponent(String(argv["namespace"]))}/repos/${encodeURIComponent(String(argv["name"]))}/file${qs ? "?" + qs : ""}`, - { - method: "GET", - local: argv.local === true, - persistTo: argv.persistTo as string | undefined, - } - ) - ); - writeRawOutput( - argv.text === true ? __cfRawBytes.toString("utf-8") : __cfRawBytes - ); - return; - } - ), -}; + usage: + "$0 artifacts namespaces repos files get \n\nReturns raw bytes for a file resolved by ref and path.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/files/index.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/files/index.ts index 6b11bee285..41e1a6ecd0 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/files/index.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/files/index.ts @@ -1,20 +1,17 @@ import $get from "./get.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * files command group * @generated from apis/overlays/artifacts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "files", describe: "Operations for namespaces.repos.files", - builder: (yargs) => { - return yargs.command($get).demandCommand(1, "Please specify a subcommand"); + routes: { + get: $get, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/fork.handler.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/fork.handler.ts new file mode 100644 index 0000000000..53e1b112bb --- /dev/null +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/fork.handler.ts @@ -0,0 +1,94 @@ +import operation from "../../../_operations/artifacts/namespaces/repos/fork.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./fork.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "artifacts namespaces repos fork", + classification: { + safeFlags: ["default-branch-only", "read-only", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf artifacts namespaces repos fork", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos/${argv["name"] == null ? "" : encodeURIComponent(String(argv["name"]))}/fork`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + name: String(argv["name"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + default_branch_only: argv["default-branch-only"], + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + read_only: argv["read-only"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + namespace: argv["namespace"], + name: argv["name"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + default_branch_only: argv["default-branch-only"], + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + read_only: argv["read-only"], + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + namespace: argv["namespace"], + name: argv["name"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/fork.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/fork.ts index 1f6044ed7e..bf3a7a5e55 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/fork.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/fork.ts @@ -1,145 +1,58 @@ -import operation from "../../../_operations/artifacts/namespaces/repos/fork.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * fork command * @generated from apis/overlays/artifacts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 artifacts namespaces repos fork \n\nForks a source repository into a new repository." - ) - .positional("name", { - type: "string", - description: "Repository name.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Artifacts namespace name.", - demandOption: true, - }) - .option("default-branch-only", { - type: "boolean", - description: "The default_branch_only field", - }) - .option("description", { - type: "string", - description: "The description field", - }) - .option("read-only", { - type: "boolean", - description: "The read_only field", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Artifacts namespace name.", + parse: String, + }, + "default-branch-only": { + kind: "boolean", + brief: "The default_branch_only field", + optional: true, + }, + description: { + kind: "parsed", + brief: "The description field", + optional: true, + parse: String, + }, + "read-only": { + kind: "boolean", + brief: "The read_only field", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [{ placeholder: "name", brief: "Repository name.", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "fork ", describe: "Fork a repository", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "artifacts namespaces repos fork", - classification: { - safeFlags: ["default-branch-only", "read-only", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf artifacts namespaces repos fork", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos/${argv["name"] == null ? "" : encodeURIComponent(String(argv["name"]))}/fork`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - name: String(argv["name"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - default_branch_only: argv["default-branch-only"], - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - read_only: argv["read-only"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - namespace: argv["namespace"], - name: argv["name"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - default_branch_only: argv["default-branch-only"], - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - read_only: argv["read-only"], - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - namespace: argv["namespace"], - name: argv["name"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 artifacts namespaces repos fork \n\nForks a source repository into a new repository.", + ...parameters, + loader: () => import("./fork.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/get.handler.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/get.handler.ts new file mode 100644 index 0000000000..ea2e5df00c --- /dev/null +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/get.handler.ts @@ -0,0 +1,53 @@ +import operation from "../../../_operations/artifacts/namespaces/repos/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "artifacts namespaces repos get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf artifacts namespaces repos get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos/${argv["name"] == null ? "" : encodeURIComponent(String(argv["name"]))}`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + name: String(argv["name"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + namespace: argv["namespace"], + name: argv["name"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/get.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/get.ts index 48d0089d6d..06230f69f0 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/get.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/get.ts @@ -1,88 +1,36 @@ -import operation from "../../../_operations/artifacts/namespaces/repos/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/artifacts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 artifacts namespaces repos get \n\nReturns repository metadata." - ) - .positional("name", { - type: "string", - description: "Repository name.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Artifacts namespace name.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Artifacts namespace name.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "name", brief: "Repository name.", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get a repository", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "artifacts namespaces repos get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf artifacts namespaces repos get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos/${argv["name"] == null ? "" : encodeURIComponent(String(argv["name"]))}`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - name: String(argv["name"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - namespace: argv["namespace"], - name: argv["name"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 artifacts namespaces repos get \n\nReturns repository metadata.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/import.handler.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/import.handler.ts new file mode 100644 index 0000000000..5781d7ab42 --- /dev/null +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/import.handler.ts @@ -0,0 +1,110 @@ +import operation from "../../../_operations/artifacts/namespaces/repos/import.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./import.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "artifacts namespaces repos import", + classification: { + safeFlags: ["read-only", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["url"] === undefined) { + argv["url"] = await promptForRequiredField("url", "The url field"); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf artifacts namespaces repos import", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos/${argv["name"] == null ? "" : encodeURIComponent(String(argv["name"]))}/import`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + name: String(argv["name"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + branch: resolveFileToken( + argv["branch"] as string | undefined, + "branch", + "text" + ), + depth: argv["depth"], + read_only: argv["read-only"], + url: resolveFileToken( + argv["url"] as string | undefined, + "url", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + namespace: argv["namespace"], + name: argv["name"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + branch: resolveFileToken( + argv["branch"] as string | undefined, + "branch", + "text" + ), + depth: argv["depth"], + read_only: argv["read-only"], + url: resolveFileToken(argv["url"] as string | undefined, "url", "text"), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + namespace: argv["namespace"], + name: argv["name"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/import.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/import.ts index 537e321a82..b029149cb4 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/import.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/import.ts @@ -1,164 +1,66 @@ -import operation from "../../../_operations/artifacts/namespaces/repos/import.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * import command * @generated from apis/overlays/artifacts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 artifacts namespaces repos import \n\nImports an HTTPS Git repository into an Artifacts repository." - ) - .positional("name", { - type: "string", - description: "Repository name.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Artifacts namespace name.", - demandOption: true, - }) - .option("branch", { - type: "string", - description: +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Artifacts namespace name.", + parse: String, + }, + branch: { + kind: "parsed", + brief: "Git branch name. Must match /^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/, must not contain '..', and must not end with '/' or '.'.", - }) - .option("depth", { type: "number", description: "The depth field" }) - .option("read-only", { - type: "boolean", - description: "The read_only field", - }) - .option("url", { type: "string", description: "The url field" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + depth: { + kind: "parsed", + brief: "The depth field", + optional: true, + parse: Number, + }, + "read-only": { + kind: "boolean", + brief: "The read_only field", + optional: true, + }, + url: { + kind: "parsed", + brief: "The url field", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [{ placeholder: "name", brief: "Repository name.", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "import ", describe: "Import a repository", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "artifacts namespaces repos import", - classification: { - safeFlags: ["read-only", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["url"] === undefined) { - argv["url"] = await promptForRequiredField("url", "The url field"); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf artifacts namespaces repos import", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos/${argv["name"] == null ? "" : encodeURIComponent(String(argv["name"]))}/import`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - name: String(argv["name"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - branch: resolveFileToken( - argv["branch"] as string | undefined, - "branch", - "text" - ), - depth: argv["depth"], - read_only: argv["read-only"], - url: resolveFileToken( - argv["url"] as string | undefined, - "url", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - namespace: argv["namespace"], - name: argv["name"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - branch: resolveFileToken( - argv["branch"] as string | undefined, - "branch", - "text" - ), - depth: argv["depth"], - read_only: argv["read-only"], - url: resolveFileToken( - argv["url"] as string | undefined, - "url", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - namespace: argv["namespace"], - name: argv["name"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 artifacts namespaces repos import \n\nImports an HTTPS Git repository into an Artifacts repository.", + ...parameters, + loader: () => import("./import.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/index.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/index.ts index 09b5066c13..91f759ed1b 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/index.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/index.ts @@ -11,36 +11,31 @@ import $logs from "./logs/index.js"; import $raw from "./raw/index.js"; import $tokens from "./tokens/index.js"; import $trees from "./trees/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * repos command group * @generated from apis/overlays/artifacts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "repos", describe: "Operations for namespaces.repos", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($fork) - .command($get) - .command($import) - .command($list) - .command($blobs) - .command($commits) - .command($files) - .command($logs) - .command($raw) - .command($tokens) - .command($trees) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + fork: $fork, + get: $get, + import: $import, + list: $list, + blobs: $blobs, + commits: $commits, + files: $files, + logs: $logs, + raw: $raw, + tokens: $tokens, + trees: $trees, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/list.handler.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/list.handler.ts new file mode 100644 index 0000000000..3e23ab10b4 --- /dev/null +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/list.handler.ts @@ -0,0 +1,58 @@ +import operation from "../../../_operations/artifacts/namespaces/repos/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "artifacts namespaces repos list", + classification: { + safeFlags: ["sort", "direction", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + limit: argv["limit"], + cursor: argv["cursor"], + search: argv["search"], + sort: argv["sort"], + direction: argv["direction"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf artifacts namespaces repos list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos`, + pathParams: { namespace: String(argv["namespace"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + namespace: argv["namespace"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/list.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/list.ts index e799a93318..892682bca0 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/list.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/list.ts @@ -1,101 +1,51 @@ -import operation from "../../../_operations/artifacts/namespaces/repos/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/artifacts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 artifacts namespaces repos list\n\nLists repositories in a namespace." - ) - .option("namespace", { - type: "string", - description: "Artifacts namespace name.", - demandOption: true, - }) - .option("limit", { type: "number", description: "Limit" }) - .option("cursor", { type: "string", description: "Cursor" }) - .option("search", { type: "string", description: "Search" }) - .option("sort", { - type: "string", - description: "Sort", - choices: ["created_at", "updated_at", "last_push_at", "name"], - }) - .option("direction", { - type: "string", - description: "Direction", - choices: ["asc", "desc"], - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Artifacts namespace name.", + parse: String, + }, + limit: { kind: "parsed", brief: "Limit", optional: true, parse: Number }, + cursor: { kind: "parsed", brief: "Cursor", optional: true, parse: String }, + search: { kind: "parsed", brief: "Search", optional: true, parse: String }, + sort: { + kind: "enum", + brief: "Sort", + values: ["created_at", "updated_at", "last_push_at", "name"], + optional: true, + }, + direction: { + kind: "enum", + brief: "Direction", + values: ["asc", "desc"], + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List repositories", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "artifacts namespaces repos list", - classification: { - safeFlags: ["sort", "direction", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - limit: argv["limit"], - cursor: argv["cursor"], - search: argv["search"], - sort: argv["sort"], - direction: argv["direction"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf artifacts namespaces repos list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos`, - pathParams: { namespace: String(argv["namespace"] ?? "") }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - namespace: argv["namespace"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 artifacts namespaces repos list\n\nLists repositories in a namespace.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/logs/get.handler.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/logs/get.handler.ts new file mode 100644 index 0000000000..8c3779be10 --- /dev/null +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/logs/get.handler.ts @@ -0,0 +1,60 @@ +import operation from "../../../../_operations/artifacts/namespaces/repos/logs/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "artifacts namespaces repos logs get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + ref: argv["ref"], + limit: argv["limit"], + offset: argv["offset"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf artifacts namespaces repos logs get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos/${argv["name"] == null ? "" : encodeURIComponent(String(argv["name"]))}/log`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + name: String(argv["name"] ?? ""), + }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + namespace: argv["namespace"], + name: argv["name"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/logs/get.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/logs/get.ts index 7fe2e3cf5b..3c8ae8251a 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/logs/get.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/logs/get.ts @@ -1,101 +1,44 @@ -import operation from "../../../../_operations/artifacts/namespaces/repos/logs/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/artifacts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 artifacts namespaces repos logs get \n\nReturns commit metadata walking backwards from a ref, branch, tag, or HEAD." - ) - .positional("name", { - type: "string", - description: "Repository name.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Artifacts namespace name.", - demandOption: true, - }) - .option("ref", { - type: "string", - description: "Git ref, branch, tag, or commit hash. Defaults to HEAD.", - }) - .option("limit", { type: "number", description: "Limit" }) - .option("offset", { type: "number", description: "Offset" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Artifacts namespace name.", + parse: String, + }, + ref: { + kind: "parsed", + brief: "Git ref, branch, tag, or commit hash. Defaults to HEAD.", + optional: true, + parse: String, + }, + limit: { kind: "parsed", brief: "Limit", optional: true, parse: Number }, + offset: { kind: "parsed", brief: "Offset", optional: true, parse: Number }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "name", brief: "Repository name.", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Read commit history", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "artifacts namespaces repos logs get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - ref: argv["ref"], - limit: argv["limit"], - offset: argv["offset"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf artifacts namespaces repos logs get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos/${argv["name"] == null ? "" : encodeURIComponent(String(argv["name"]))}/log`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - name: String(argv["name"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - namespace: argv["namespace"], - name: argv["name"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 artifacts namespaces repos logs get \n\nReturns commit metadata walking backwards from a ref, branch, tag, or HEAD.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/logs/index.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/logs/index.ts index bbbe067e98..ba8e645359 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/logs/index.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/logs/index.ts @@ -1,20 +1,17 @@ import $get from "./get.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * logs command group * @generated from apis/overlays/artifacts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "logs", describe: "Operations for namespaces.repos.logs", - builder: (yargs) => { - return yargs.command($get).demandCommand(1, "Please specify a subcommand"); + routes: { + get: $get, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/raw/get.handler.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/raw/get.handler.ts new file mode 100644 index 0000000000..a6ac3ff418 --- /dev/null +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/raw/get.handler.ts @@ -0,0 +1,61 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { fetchRawBytes, writeRawOutput } from "#lib/raw-fetch.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "artifacts namespaces repos raw get", + classification: { + safeFlags: ["dry-run", "text"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf artifacts namespaces repos raw get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos/${argv["name"] == null ? "" : encodeURIComponent(String(argv["name"]))}/raw/${argv["ref"] == null ? "" : encodeURIComponent(String(argv["ref"]))}/${argv["path"] == null ? "" : encodeURIComponent(String(argv["path"]))}`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + name: String(argv["name"] ?? ""), + ref: String(argv["ref"] ?? ""), + path: String(argv["path"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const __cfRawBytes = await withProgress(`Loading`, async () => + fetchRawBytes( + `/accounts/${accountId}/artifacts/namespaces/${encodeURIComponent(String(argv["namespace"]))}/repos/${encodeURIComponent(String(argv["name"]))}/raw/${encodeURIComponent(String(argv["ref"]))}/${encodeURIComponent(String(argv["path"]))}`, + { + method: "GET", + local: argv.local === true, + persistTo: argv.persistTo as string | undefined, + } + ) + ); + writeRawOutput( + argv.text === true ? __cfRawBytes.toString("utf-8") : __cfRawBytes + ); + return; + } + ); +} diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/raw/get.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/raw/get.ts index 57afe0a1d3..a6a9cc95cf 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/raw/get.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/raw/get.ts @@ -1,112 +1,54 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/artifacts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { fetchRawBytes, writeRawOutput } from "#lib/raw-fetch.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 artifacts namespaces repos raw get \n\nReturns file bytes resolved by ref and path, with a sniffed content type and browser-safe response headers." - ) - .positional("path", { - type: "string", - description: "File path. May contain slashes.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Artifacts namespace name.", - demandOption: true, - }) - .option("name", { - type: "string", - description: "Repository name.", - demandOption: true, - }) - .option("ref", { - type: "string", - description: "Git ref, branch, tag, or 40-character commit hash.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Artifacts namespace name.", + parse: String, + }, + name: { kind: "parsed", brief: "Repository name.", parse: String }, + ref: { + kind: "parsed", + brief: "Git ref, branch, tag, or 40-character commit hash.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("text", { - type: "boolean", - description: + }, + text: { + kind: "boolean", + brief: "Decode the response body as UTF-8 text instead of writing raw bytes", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "path", + brief: "File path. May contain slashes.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Read a raw file with content type", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "artifacts namespaces repos raw get", - classification: { - safeFlags: ["dry-run", "text"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf artifacts namespaces repos raw get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos/${argv["name"] == null ? "" : encodeURIComponent(String(argv["name"]))}/raw/${argv["ref"] == null ? "" : encodeURIComponent(String(argv["ref"]))}/${argv["path"] == null ? "" : encodeURIComponent(String(argv["path"]))}`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - name: String(argv["name"] ?? ""), - ref: String(argv["ref"] ?? ""), - path: String(argv["path"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const __cfRawBytes = await withProgress(`Loading`, async () => - fetchRawBytes( - `/accounts/${accountId}/artifacts/namespaces/${encodeURIComponent(String(argv["namespace"]))}/repos/${encodeURIComponent(String(argv["name"]))}/raw/${encodeURIComponent(String(argv["ref"]))}/${encodeURIComponent(String(argv["path"]))}`, - { - method: "GET", - local: argv.local === true, - persistTo: argv.persistTo as string | undefined, - } - ) - ); - writeRawOutput( - argv.text === true ? __cfRawBytes.toString("utf-8") : __cfRawBytes - ); - return; - } - ), -}; + usage: + "$0 artifacts namespaces repos raw get \n\nReturns file bytes resolved by ref and path, with a sniffed content type and browser-safe response headers.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/raw/index.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/raw/index.ts index 7433785633..1c02906800 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/raw/index.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/raw/index.ts @@ -1,20 +1,17 @@ import $get from "./get.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * raw command group * @generated from apis/overlays/artifacts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "raw", describe: "Operations for namespaces.repos.raw", - builder: (yargs) => { - return yargs.command($get).demandCommand(1, "Please specify a subcommand"); + routes: { + get: $get, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/tokens/index.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/tokens/index.ts index 7b96d46d33..777668a436 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/tokens/index.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/tokens/index.ts @@ -1,20 +1,17 @@ import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * tokens command group * @generated from apis/overlays/artifacts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "tokens", describe: "Operations for namespaces.repos.tokens", - builder: (yargs) => { - return yargs.command($list).demandCommand(1, "Please specify a subcommand"); + routes: { + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/tokens/list.handler.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/tokens/list.handler.ts new file mode 100644 index 0000000000..0561113f4e --- /dev/null +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/tokens/list.handler.ts @@ -0,0 +1,60 @@ +import operation from "../../../../_operations/artifacts/namespaces/repos/tokens/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "artifacts namespaces repos tokens list", + classification: { + safeFlags: ["state", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + state: argv["state"], + page: argv["page"], + per_page: argv["per-page"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf artifacts namespaces repos tokens list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos/${argv["name"] == null ? "" : encodeURIComponent(String(argv["name"]))}/tokens`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + name: String(argv["name"] ?? ""), + }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + namespace: argv["namespace"], + name: argv["name"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/tokens/list.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/tokens/list.ts index 22dcf91e38..b1ae514304 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/tokens/list.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/tokens/list.ts @@ -1,102 +1,50 @@ -import operation from "../../../../_operations/artifacts/namespaces/repos/tokens/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/artifacts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 artifacts namespaces repos tokens list\n\nLists tokens for a repository." - ) - .option("namespace", { - type: "string", - description: "Artifacts namespace name.", - demandOption: true, - }) - .option("name", { - type: "string", - description: "Repository name.", - demandOption: true, - }) - .option("state", { - type: "string", - description: "State", - choices: ["active", "expired", "revoked", "all"], - }) - .option("page", { type: "number", description: "Page" }) - .option("per-page", { type: "number", description: "Per page" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Artifacts namespace name.", + parse: String, + }, + name: { kind: "parsed", brief: "Repository name.", parse: String }, + state: { + kind: "enum", + brief: "State", + values: ["active", "expired", "revoked", "all"], + optional: true, + }, + page: { kind: "parsed", brief: "Page", optional: true, parse: Number }, + "per-page": { + kind: "parsed", + brief: "Per page", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List repository tokens", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "artifacts namespaces repos tokens list", - classification: { - safeFlags: ["state", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - state: argv["state"], - page: argv["page"], - per_page: argv["per-page"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf artifacts namespaces repos tokens list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos/${argv["name"] == null ? "" : encodeURIComponent(String(argv["name"]))}/tokens`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - name: String(argv["name"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - namespace: argv["namespace"], - name: argv["name"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 artifacts namespaces repos tokens list\n\nLists tokens for a repository.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/trees/get.handler.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/trees/get.handler.ts new file mode 100644 index 0000000000..3d5d9eb9f3 --- /dev/null +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/trees/get.handler.ts @@ -0,0 +1,55 @@ +import operation from "../../../../_operations/artifacts/namespaces/repos/trees/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "artifacts namespaces repos trees get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf artifacts namespaces repos trees get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos/${argv["name"] == null ? "" : encodeURIComponent(String(argv["name"]))}/tree/${argv["hash"] == null ? "" : encodeURIComponent(String(argv["hash"]))}`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + name: String(argv["name"] ?? ""), + hash: String(argv["hash"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + namespace: argv["namespace"], + name: argv["name"], + hash: argv["hash"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/trees/get.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/trees/get.ts index 89beb5135d..e50277fb3a 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/trees/get.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/trees/get.ts @@ -1,95 +1,43 @@ -import operation from "../../../../_operations/artifacts/namespaces/repos/trees/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/artifacts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 artifacts namespaces repos trees get \n\nReturns decoded entries for an immutable Git tree object. A commit hash returns that commit's root tree; a blob or tag hash returns 422. Tree responses are cacheable forever by hash." - ) - .positional("hash", { - type: "string", - description: "40-character lowercase hexadecimal Git object hash.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Artifacts namespace name.", - demandOption: true, - }) - .option("name", { - type: "string", - description: "Repository name.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Artifacts namespace name.", + parse: String, + }, + name: { kind: "parsed", brief: "Repository name.", parse: String }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "hash", + brief: "40-character lowercase hexadecimal Git object hash.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Read a Git tree", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "artifacts namespaces repos trees get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf artifacts namespaces repos trees get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/repos/${argv["name"] == null ? "" : encodeURIComponent(String(argv["name"]))}/tree/${argv["hash"] == null ? "" : encodeURIComponent(String(argv["hash"]))}`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - name: String(argv["name"] ?? ""), - hash: String(argv["hash"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - namespace: argv["namespace"], - name: argv["name"], - hash: argv["hash"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 artifacts namespaces repos trees get \n\nReturns decoded entries for an immutable Git tree object. A commit hash returns that commit's root tree; a blob or tag hash returns 422. Tree responses are cacheable forever by hash.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/trees/index.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/trees/index.ts index 45a3f00e08..9278f174f1 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/repos/trees/index.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/repos/trees/index.ts @@ -1,20 +1,17 @@ import $get from "./get.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * trees command group * @generated from apis/overlays/artifacts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "trees", describe: "Operations for namespaces.repos.trees", - builder: (yargs) => { - return yargs.command($get).demandCommand(1, "Please specify a subcommand"); + routes: { + get: $get, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/tokens/create.handler.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/tokens/create.handler.ts new file mode 100644 index 0000000000..03bd5121f3 --- /dev/null +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/tokens/create.handler.ts @@ -0,0 +1,99 @@ +import operation from "../../../_operations/artifacts/namespaces/tokens/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "artifacts namespaces tokens create", + classification: { + safeFlags: ["scope", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["repo"] === undefined) { + argv["repo"] = await promptForRequiredField("repo", "The repo field"); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf artifacts namespaces tokens create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/tokens`, + pathParams: { namespace: String(argv["namespace"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + repo: resolveFileToken( + argv["repo"] as string | undefined, + "repo", + "text" + ), + scope: argv["scope"], + ttl: argv["ttl"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + namespace: argv["namespace"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + repo: resolveFileToken( + argv["repo"] as string | undefined, + "repo", + "text" + ), + scope: argv["scope"], + ttl: argv["ttl"], + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + namespace: argv["namespace"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/tokens/create.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/tokens/create.ts index 0473b0d684..b644f10df0 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/tokens/create.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/tokens/create.ts @@ -1,144 +1,64 @@ -import operation from "../../../_operations/artifacts/namespaces/tokens/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/artifacts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 artifacts namespaces tokens create \n\nCreates a scoped Git token for a repository." - ) - .positional("namespace", { - type: "string", - description: "Artifacts namespace name.", - demandOption: true, - }) - .option("repo", { type: "string", description: "The repo field" }) - .option("scope", { - type: "string", - description: "The scope field", +const parameters = { + flags: { + repo: { + kind: "parsed", + brief: "The repo field", + optional: true, + parse: String, + }, + scope: { + kind: "parsed", + brief: "The scope field", + optional: true, choices: ["read", "write"], - }) - .coerce("scope", (value) => resolveFileToken(value, "scope", "text")) - .option("ttl", { type: "number", description: "The ttl field" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => resolveFileToken(value, "scope", "text"), + }, + ttl: { + kind: "parsed", + brief: "The ttl field", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "namespace", + brief: "Artifacts namespace name.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Create a repository token", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "artifacts namespaces tokens create", - classification: { - safeFlags: ["scope", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["repo"] === undefined) { - argv["repo"] = await promptForRequiredField( - "repo", - "The repo field" - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf artifacts namespaces tokens create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/tokens`, - pathParams: { namespace: String(argv["namespace"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - repo: resolveFileToken( - argv["repo"] as string | undefined, - "repo", - "text" - ), - scope: argv["scope"], - ttl: argv["ttl"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - namespace: argv["namespace"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - repo: resolveFileToken( - argv["repo"] as string | undefined, - "repo", - "text" - ), - scope: argv["scope"], - ttl: argv["ttl"], - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - namespace: argv["namespace"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 artifacts namespaces tokens create \n\nCreates a scoped Git token for a repository.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/tokens/index.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/tokens/index.ts index 939e0fe892..8c0944e0d3 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/tokens/index.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/tokens/index.ts @@ -1,24 +1,19 @@ import $create from "./create.js"; import $revoke from "./revoke.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * tokens command group * @generated from apis/overlays/artifacts.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "tokens", describe: "Operations for namespaces.tokens", - builder: (yargs) => { - return yargs - .command($create) - .command($revoke) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + revoke: $revoke, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/tokens/revoke.handler.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/tokens/revoke.handler.ts new file mode 100644 index 0000000000..9faf5f5f05 --- /dev/null +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/tokens/revoke.handler.ts @@ -0,0 +1,59 @@ +import operation from "../../../_operations/artifacts/namespaces/tokens/revoke.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./revoke.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "artifacts namespaces tokens revoke", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf artifacts namespaces tokens revoke", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/tokens/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, + pathParams: { + namespace: String(argv["namespace"] ?? ""), + id: String(argv["id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + namespace: argv["namespace"], + id: argv["id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/artifacts/namespaces/tokens/revoke.ts b/packages/cli/src/commands/_generated/artifacts/namespaces/tokens/revoke.ts index 9851de6a3f..9d041310d0 100644 --- a/packages/cli/src/commands/_generated/artifacts/namespaces/tokens/revoke.ts +++ b/packages/cli/src/commands/_generated/artifacts/namespaces/tokens/revoke.ts @@ -1,100 +1,48 @@ -import operation from "../../../_operations/artifacts/namespaces/tokens/revoke.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * revoke command * @generated from apis/overlays/artifacts.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 artifacts namespaces tokens revoke \n\nRevokes an Artifacts repository token. Token IDs are resolved through an eventually consistent index, so revoking a token within about a second of creating it can return 404; retry after a short delay." - ) - .positional("id", { - type: "string", - description: "Token ID. Must match /^[0-9a-z]{16}$/.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Artifacts namespace name.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + namespace: { + kind: "parsed", + brief: "Artifacts namespace name.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "id", + brief: "Token ID. Must match /^[0-9a-z]{16}$/.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "revoke ", describe: "Revoke a token", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "artifacts namespaces tokens revoke", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf artifacts namespaces tokens revoke", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/artifacts/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/tokens/${argv["id"] == null ? "" : encodeURIComponent(String(argv["id"]))}`, - pathParams: { - namespace: String(argv["namespace"] ?? ""), - id: String(argv["id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - namespace: argv["namespace"], - id: argv["id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 artifacts namespaces tokens revoke \n\nRevokes an Artifacts repository token. Token IDs are resolved through an eventually consistent index, so revoking a token within about a second of creating it can return 404; retry after a short delay.", + ...parameters, + loader: () => import("./revoke.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/audit-logs/index.ts b/packages/cli/src/commands/_generated/audit-logs/index.ts index 3e1515900c..19826b2d80 100644 --- a/packages/cli/src/commands/_generated/audit-logs/index.ts +++ b/packages/cli/src/commands/_generated/audit-logs/index.ts @@ -1,20 +1,17 @@ import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * audit-logs command * @generated from apis/overlays/audit-logs.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "audit-logs", describe: "audit-logs", - builder: (yargs) => { - return yargs.command($list).demandCommand(1, "Please specify a subcommand"); + routes: { + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/audit-logs/list.handler.ts b/packages/cli/src/commands/_generated/audit-logs/list.handler.ts new file mode 100644 index 0000000000..c2341d38fc --- /dev/null +++ b/packages/cli/src/commands/_generated/audit-logs/list.handler.ts @@ -0,0 +1,61 @@ +import operation from "../_operations/audit-logs/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "audit-logs list", + classification: { + safeFlags: ["export", "direction", "hide-user-logs", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + id: argv["id"], + export: argv["export"], + "action.type": argv["action-type"], + "actor.ip": argv["actor-ip"], + "actor.email": argv["actor-email"], + since: argv["since"], + before: argv["before"], + "zone.name": argv["zone-name"], + direction: argv["direction"], + per_page: argv["per-page"], + page: argv["page"], + hide_user_logs: argv["hide-user-logs"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf audit-logs list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/audit_logs`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/audit-logs/list.ts b/packages/cli/src/commands/_generated/audit-logs/list.ts index 6872387af4..ddebfe20de 100644 --- a/packages/cli/src/commands/_generated/audit-logs/list.ts +++ b/packages/cli/src/commands/_generated/audit-logs/list.ts @@ -1,132 +1,92 @@ -import operation from "../_operations/audit-logs/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/audit-logs.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 audit-logs list\n\nGets a list of audit logs for an account. Can be filtered by who made the change, on which zone, and the timeframe of the change." - ) - .option("id", { - type: "string", - description: "Finds a specific log by its ID.", - }) - .option("export", { - type: "boolean", - description: - "Indicates that this request is an export of logs in CSV format.", - }) - .option("action-type", { - type: "string", - description: "Filters by the action type.", - }) - .option("actor-ip", { - type: "string", - description: +const parameters = { + flags: { + id: { + kind: "parsed", + brief: "Finds a specific log by its ID.", + optional: true, + parse: String, + }, + export: { + kind: "boolean", + brief: "Indicates that this request is an export of logs in CSV format.", + optional: true, + }, + "action-type": { + kind: "parsed", + brief: "Filters by the action type.", + optional: true, + parse: String, + }, + "actor-ip": { + kind: "parsed", + brief: "Filters by the IP address of the request that made the change by specific IP address or valid CIDR Range.", - }) - .option("actor-email", { - type: "string", - description: - "Filters by the email address of the actor that made the change.", - }) - .option("since", { type: "string", description: "Since" }) - .option("before", { type: "string", description: "Before" }) - .option("zone-name", { - type: "string", - description: "Filters by the name of the zone associated to the change.", - }) - .option("direction", { - type: "string", - description: "Changes the direction of the chronological sorting.", - choices: ["desc", "asc"], - }) - .option("per-page", { - type: "number", - description: "Sets the number of results to return per page.", - }) - .option("page", { - type: "number", - description: "Defines which page of results to return.", - }) - .option("hide-user-logs", { - type: "boolean", - description: "Indicates whether or not to hide user level audit logs.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "actor-email": { + kind: "parsed", + brief: "Filters by the email address of the actor that made the change.", + optional: true, + parse: String, + }, + since: { kind: "parsed", brief: "Since", optional: true, parse: String }, + before: { kind: "parsed", brief: "Before", optional: true, parse: String }, + "zone-name": { + kind: "parsed", + brief: "Filters by the name of the zone associated to the change.", + optional: true, + parse: String, + }, + direction: { + kind: "enum", + brief: "Changes the direction of the chronological sorting.", + values: ["desc", "asc"], + optional: true, + }, + "per-page": { + kind: "parsed", + brief: "Sets the number of results to return per page.", + optional: true, + parse: Number, + }, + page: { + kind: "parsed", + brief: "Defines which page of results to return.", + optional: true, + parse: Number, + }, + "hide-user-logs": { + kind: "boolean", + brief: "Indicates whether or not to hide user level audit logs.", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "Get account audit logs", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "audit-logs list", - classification: { - safeFlags: ["export", "direction", "hide-user-logs", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - id: argv["id"], - export: argv["export"], - "action.type": argv["action-type"], - "actor.ip": argv["actor-ip"], - "actor.email": argv["actor-email"], - since: argv["since"], - before: argv["before"], - "zone.name": argv["zone-name"], - direction: argv["direction"], - per_page: argv["per-page"], - page: argv["page"], - hide_user_logs: argv["hide-user-logs"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf audit-logs list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/audit_logs`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 audit-logs list\n\nGets a list of audit logs for an account. Can be filtered by who made the change, on which zone, and the timeframe of the change.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/basin-catalog/credentials/create.handler.ts b/packages/cli/src/commands/_generated/basin-catalog/credentials/create.handler.ts new file mode 100644 index 0000000000..3063a322a0 --- /dev/null +++ b/packages/cli/src/commands/_generated/basin-catalog/credentials/create.handler.ts @@ -0,0 +1,100 @@ +import operation from "../../_operations/basin-catalog/credentials/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "basin-catalog credentials create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["token"] === undefined) { + argv["token"] = await promptForRequiredField( + "token", + "Provides the Cloudflare API token for accessing R2.", + { kind: "secret" } + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf basin-catalog credentials create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/credential`, + pathParams: { "bucket-name": String(argv["bucket-name"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + token: resolveFileToken( + argv["token"] as string | undefined, + "token", + "text" + ), + }), + sensitiveBodyPaths: [["token"]], + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + bucket_name: argv["bucket-name"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + token: resolveFileToken( + argv["token"] as string | undefined, + "token", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + bucket_name: argv["bucket-name"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/basin-catalog/credentials/create.ts b/packages/cli/src/commands/_generated/basin-catalog/credentials/create.ts index c95b3f8ce9..81dc63e91d 100644 --- a/packages/cli/src/commands/_generated/basin-catalog/credentials/create.ts +++ b/packages/cli/src/commands/_generated/basin-catalog/credentials/create.ts @@ -1,138 +1,49 @@ -import operation from "../../_operations/basin-catalog/credentials/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/basin-catalog.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 basin-catalog credentials create \n\nStore authentication credentials for a catalog. These credentials are used to authenticate with R2 storage when performing catalog operations." - ) - .positional("bucket-name", { - type: "string", - description: "Specifies the R2 bucket name.", - demandOption: true, - }) - .option("token", { - type: "string", - description: "Provides the Cloudflare API token for accessing R2.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + token: { + kind: "parsed", + brief: "Provides the Cloudflare API token for accessing R2.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Contains request to store catalog credentials.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Contains request to store catalog credentials.", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "bucket-name", + brief: "Specifies the R2 bucket name.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Store catalog credentials", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "basin-catalog credentials create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["token"] === undefined) { - argv["token"] = await promptForRequiredField( - "token", - "Provides the Cloudflare API token for accessing R2.", - { kind: "secret" } - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf basin-catalog credentials create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/credential`, - pathParams: { "bucket-name": String(argv["bucket-name"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - token: resolveFileToken( - argv["token"] as string | undefined, - "token", - "text" - ), - }), - sensitiveBodyPaths: [["token"]], - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - bucket_name: argv["bucket-name"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - token: resolveFileToken( - argv["token"] as string | undefined, - "token", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - bucket_name: argv["bucket-name"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 basin-catalog credentials create \n\nStore authentication credentials for a catalog. These credentials are used to authenticate with R2 storage when performing catalog operations.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/basin-catalog/credentials/index.ts b/packages/cli/src/commands/_generated/basin-catalog/credentials/index.ts index b826165fb6..580d1e35ab 100644 --- a/packages/cli/src/commands/_generated/basin-catalog/credentials/index.ts +++ b/packages/cli/src/commands/_generated/basin-catalog/credentials/index.ts @@ -1,25 +1,20 @@ import $create from "./create.js"; import $status from "./status.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * credentials command group * @generated from apis/overlays/basin-catalog.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "credentials", describe: "Catalog access credentials for external query engines (Spark, Trino, etc.)", - builder: (yargs) => { - return yargs - .command($create) - .command($status) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + status: $status, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/basin-catalog/credentials/status.handler.ts b/packages/cli/src/commands/_generated/basin-catalog/credentials/status.handler.ts new file mode 100644 index 0000000000..ce6e21bd8c --- /dev/null +++ b/packages/cli/src/commands/_generated/basin-catalog/credentials/status.handler.ts @@ -0,0 +1,49 @@ +import operation from "../../_operations/basin-catalog/credentials/status.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./status.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "basin-catalog credentials status", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf basin-catalog credentials status", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/credential/status`, + pathParams: { "bucket-name": String(argv["bucket-name"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + bucket_name: argv["bucket-name"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/basin-catalog/credentials/status.ts b/packages/cli/src/commands/_generated/basin-catalog/credentials/status.ts index 6f80bc7e4e..9e46dc42fc 100644 --- a/packages/cli/src/commands/_generated/basin-catalog/credentials/status.ts +++ b/packages/cli/src/commands/_generated/basin-catalog/credentials/status.ts @@ -1,79 +1,37 @@ -import operation from "../../_operations/basin-catalog/credentials/status.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * status command * @generated from apis/overlays/basin-catalog.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 basin-catalog credentials status \n\nCheck whether the configured catalog credentials are valid, invalid, or absent by probing authentication against the catalog." - ) - .positional("bucket-name", { - type: "string", - description: "Specifies the R2 bucket name.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "bucket-name", + brief: "Specifies the R2 bucket name.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "status ", describe: "Get Basin Catalog credential status", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "basin-catalog credentials status", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf basin-catalog credentials status", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/credential/status`, - pathParams: { "bucket-name": String(argv["bucket-name"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - bucket_name: argv["bucket-name"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 basin-catalog credentials status \n\nCheck whether the configured catalog credentials are valid, invalid, or absent by probing authentication against the catalog.", + ...parameters, + loader: () => import("./status.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/basin-catalog/delete.handler.ts b/packages/cli/src/commands/_generated/basin-catalog/delete.handler.ts new file mode 100644 index 0000000000..64ff470e0c --- /dev/null +++ b/packages/cli/src/commands/_generated/basin-catalog/delete.handler.ts @@ -0,0 +1,65 @@ +import operation from "../_operations/basin-catalog/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "basin-catalog delete", + classification: { + safeFlags: ["cascade", "dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + force: argv["cascade"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf basin-catalog delete", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/delete`, + pathParams: { "bucket-name": String(argv["bucket-name"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This removes catalog metadata. R2 bucket objects are retained.`, + })) + ) { + return; + } + + const result = await withProgress(`Processing`, async () => + client.send(operation, { + account_id: accountId, + bucket_name: argv["bucket-name"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Done` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/basin-catalog/delete.ts b/packages/cli/src/commands/_generated/basin-catalog/delete.ts index aa6ae9ead6..546fe8ab5a 100644 --- a/packages/cli/src/commands/_generated/basin-catalog/delete.ts +++ b/packages/cli/src/commands/_generated/basin-catalog/delete.ts @@ -1,105 +1,48 @@ -import operation from "../_operations/basin-catalog/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/basin-catalog.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 basin-catalog delete \n\nRemoves the catalog from the control plane without deleting R2 bucket objects. Set force=true to remove catalog namespaces, tables, views, and maintenance metadata. Force deletion is limited to a configured catalog object count." - ) - .positional("bucket-name", { - type: "string", - description: "Specifies the R2 bucket name.", - demandOption: true, - }) - .option("cascade", { - type: "boolean", - description: "Remove child metadata before deleting the catalog.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + cascade: { + kind: "boolean", + brief: "Remove child metadata before deleting the catalog.", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "bucket-name", + brief: "Specifies the R2 bucket name.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete Basin Catalog metadata", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "basin-catalog delete", - classification: { - safeFlags: ["cascade", "dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - force: argv["cascade"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf basin-catalog delete", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/delete`, - pathParams: { "bucket-name": String(argv["bucket-name"] ?? "") }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This removes catalog metadata. R2 bucket objects are retained.`, - })) - ) { - return; - } - - const result = await withProgress(`Processing`, async () => - client.send(operation, { - account_id: accountId, - bucket_name: argv["bucket-name"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Done` }); - } - ), -}; + usage: + "$0 basin-catalog delete \n\nRemoves the catalog from the control plane without deleting R2 bucket objects. Set force=true to remove catalog namespaces, tables, views, and maintenance metadata. Force deletion is limited to a configured catalog object count.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/basin-catalog/disable.handler.ts b/packages/cli/src/commands/_generated/basin-catalog/disable.handler.ts new file mode 100644 index 0000000000..9d4e5cc0ef --- /dev/null +++ b/packages/cli/src/commands/_generated/basin-catalog/disable.handler.ts @@ -0,0 +1,60 @@ +import operation from "../_operations/basin-catalog/disable.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./disable.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "basin-catalog disable", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf basin-catalog disable", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/disable`, + pathParams: { "bucket-name": String(argv["bucket-name"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if ( + !(await confirmDelete({ + force: Boolean(argv.force), + message: `This operation turns off the data catalog for the bucket. Existing namespace or table state remains, but writes stop.`, + })) + ) { + return; + } + + const result = await withProgress(`Processing`, async () => + client.send(operation, { + account_id: accountId, + bucket_name: argv["bucket-name"], + }) + ); + formatOutput(result, { successLabel: `Done` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/basin-catalog/disable.ts b/packages/cli/src/commands/_generated/basin-catalog/disable.ts index 6040a41906..508b43170a 100644 --- a/packages/cli/src/commands/_generated/basin-catalog/disable.ts +++ b/packages/cli/src/commands/_generated/basin-catalog/disable.ts @@ -1,96 +1,43 @@ -import operation from "../_operations/basin-catalog/disable.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * disable command * @generated from apis/overlays/basin-catalog.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 basin-catalog disable \n\nDisable an R2 bucket as a catalog. This operation deactivates the catalog but preserves existing metadata and data files. The catalog can be re-enabled later." - ) - .positional("bucket-name", { - type: "string", - description: "Specifies the R2 bucket name to disable as catalog.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "bucket-name", + brief: "Specifies the R2 bucket name to disable as catalog.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "disable ", describe: "Disable Basin Catalog", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "basin-catalog disable", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf basin-catalog disable", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/disable`, - pathParams: { "bucket-name": String(argv["bucket-name"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if ( - !(await confirmDelete({ - force: Boolean(argv.force), - message: `This operation turns off the data catalog for the bucket. Existing namespace or table state remains, but writes stop.`, - })) - ) { - return; - } - - const result = await withProgress(`Processing`, async () => - client.send(operation, { - account_id: accountId, - bucket_name: argv["bucket-name"], - }) - ); - formatOutput(result, { successLabel: `Done` }); - } - ), -}; + usage: + "$0 basin-catalog disable \n\nDisable an R2 bucket as a catalog. This operation deactivates the catalog but preserves existing metadata and data files. The catalog can be re-enabled later.", + ...parameters, + loader: () => import("./disable.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/basin-catalog/enable.handler.ts b/packages/cli/src/commands/_generated/basin-catalog/enable.handler.ts new file mode 100644 index 0000000000..cf6a6fba77 --- /dev/null +++ b/packages/cli/src/commands/_generated/basin-catalog/enable.handler.ts @@ -0,0 +1,90 @@ +import operation from "../_operations/basin-catalog/enable.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./enable.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "basin-catalog enable", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf basin-catalog enable", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/enable`, + pathParams: { "bucket-name": String(argv["bucket-name"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + credential: { + token: resolveFileToken( + argv["credential-token"] as string | undefined, + "credential-token", + "text" + ), + }, + }), + sensitiveBodyPaths: [["credential", "token"]], + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + bucket_name: argv["bucket-name"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + credential: { + token: resolveFileToken( + argv["credential-token"] as string | undefined, + "credential-token", + "text" + ), + }, + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + bucket_name: argv["bucket-name"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/basin-catalog/enable.ts b/packages/cli/src/commands/_generated/basin-catalog/enable.ts index c2d73c4361..c19996577b 100644 --- a/packages/cli/src/commands/_generated/basin-catalog/enable.ts +++ b/packages/cli/src/commands/_generated/basin-catalog/enable.ts @@ -1,129 +1,50 @@ -import operation from "../_operations/basin-catalog/enable.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * enable command * @generated from apis/overlays/basin-catalog.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 basin-catalog enable \n\nEnable an R2 bucket as an Apache Iceberg catalog. This operation creates the necessary catalog infrastructure and activates the bucket for storing Iceberg metadata and data files." - ) - .positional("bucket-name", { - type: "string", - description: "Specifies the R2 bucket name to enable as catalog.", - demandOption: true, - }) - .option("credential-token", { - type: "string", - description: "Provides the Cloudflare API token for accessing R2.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "credential-token": { + kind: "parsed", + brief: "Provides the Cloudflare API token for accessing R2.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: - "Contains the optional request to enable a catalog. Send an empty body to keep the defaults. If you include \`credential\`, the service checks that the token can access the bucket, then stores it as the catalog's maintenance credential, like the store credentials operation. ", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: + "Contains the optional request to enable a catalog. Send an empty body to keep the defaults. If you include `credential`, the service checks that the token can access the bucket, then stores it as the catalog's maintenance credential, like the store credentials operation. ", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "bucket-name", + brief: "Specifies the R2 bucket name to enable as catalog.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "enable ", describe: "Enable R2 bucket as a catalog", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "basin-catalog enable", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf basin-catalog enable", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/enable`, - pathParams: { "bucket-name": String(argv["bucket-name"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - credential: { - token: resolveFileToken( - argv["credential-token"] as string | undefined, - "credential-token", - "text" - ), - }, - }), - sensitiveBodyPaths: [["credential", "token"]], - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - bucket_name: argv["bucket-name"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - credential: { - token: resolveFileToken( - argv["credential-token"] as string | undefined, - "credential-token", - "text" - ), - }, - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - bucket_name: argv["bucket-name"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 basin-catalog enable \n\nEnable an R2 bucket as an Apache Iceberg catalog. This operation creates the necessary catalog infrastructure and activates the bucket for storing Iceberg metadata and data files.", + ...parameters, + loader: () => import("./enable.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/basin-catalog/get.handler.ts b/packages/cli/src/commands/_generated/basin-catalog/get.handler.ts new file mode 100644 index 0000000000..f73f8e510e --- /dev/null +++ b/packages/cli/src/commands/_generated/basin-catalog/get.handler.ts @@ -0,0 +1,49 @@ +import operation from "../_operations/basin-catalog/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "basin-catalog get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf basin-catalog get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}`, + pathParams: { "bucket-name": String(argv["bucket-name"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + bucket_name: argv["bucket-name"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/basin-catalog/get.ts b/packages/cli/src/commands/_generated/basin-catalog/get.ts index 137e812d0f..22b81cb422 100644 --- a/packages/cli/src/commands/_generated/basin-catalog/get.ts +++ b/packages/cli/src/commands/_generated/basin-catalog/get.ts @@ -1,79 +1,37 @@ -import operation from "../_operations/basin-catalog/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/basin-catalog.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 basin-catalog get \n\nRetrieve detailed information about a specific Basin Catalog by bucket name. Returns catalog status, maintenance configuration, and credential status." - ) - .positional("bucket-name", { - type: "string", - description: "Specifies the R2 bucket name.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "bucket-name", + brief: "Specifies the R2 bucket name.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get Basin Catalog details", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "basin-catalog get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf basin-catalog get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}`, - pathParams: { "bucket-name": String(argv["bucket-name"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - bucket_name: argv["bucket-name"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 basin-catalog get \n\nRetrieve detailed information about a specific Basin Catalog by bucket name. Returns catalog status, maintenance configuration, and credential status.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/basin-catalog/index.ts b/packages/cli/src/commands/_generated/basin-catalog/index.ts index 2eb12a86f4..ad9f13f406 100644 --- a/packages/cli/src/commands/_generated/basin-catalog/index.ts +++ b/packages/cli/src/commands/_generated/basin-catalog/index.ts @@ -6,32 +6,27 @@ import $get from "./get.js"; import $list from "./list.js"; import $maintenanceconfigs from "./maintenance-configs/index.js"; import $namespaces from "./namespaces/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * basin-catalog command * @generated from apis/overlays/basin-catalog.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "basin-catalog", describe: "Iceberg-compatible data catalog for R2 — organize objects into tables and namespaces for SQL query engines", - builder: (yargs) => { - return yargs - .command($delete) - .command($disable) - .command($enable) - .command($get) - .command($list) - .command($credentials) - .command($maintenanceconfigs) - .command($namespaces) - .demandCommand(1, "Please specify a subcommand"); + routes: { + delete: $delete, + disable: $disable, + enable: $enable, + get: $get, + list: $list, + credentials: $credentials, + "maintenance-configs": $maintenanceconfigs, + namespaces: $namespaces, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/basin-catalog/list.handler.ts b/packages/cli/src/commands/_generated/basin-catalog/list.handler.ts new file mode 100644 index 0000000000..868f617b13 --- /dev/null +++ b/packages/cli/src/commands/_generated/basin-catalog/list.handler.ts @@ -0,0 +1,46 @@ +import operation from "../_operations/basin-catalog/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "basin-catalog list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf basin-catalog list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/basin-catalog/list.ts b/packages/cli/src/commands/_generated/basin-catalog/list.ts index 7756525fa9..b656befa9a 100644 --- a/packages/cli/src/commands/_generated/basin-catalog/list.ts +++ b/packages/cli/src/commands/_generated/basin-catalog/list.ts @@ -1,71 +1,31 @@ -import operation from "../_operations/basin-catalog/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/basin-catalog.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 basin-catalog list\n\nReturns a list of R2 buckets that have been enabled as Apache Iceberg catalogs for the specified account. Each catalog represents an R2 bucket configured to store Iceberg metadata and data files." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Basin Catalogs", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "basin-catalog list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf basin-catalog list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 basin-catalog list\n\nReturns a list of R2 buckets that have been enabled as Apache Iceberg catalogs for the specified account. Each catalog represents an R2 bucket configured to store Iceberg metadata and data files.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/basin-catalog/maintenance-configs/get.handler.ts b/packages/cli/src/commands/_generated/basin-catalog/maintenance-configs/get.handler.ts new file mode 100644 index 0000000000..806d47361b --- /dev/null +++ b/packages/cli/src/commands/_generated/basin-catalog/maintenance-configs/get.handler.ts @@ -0,0 +1,49 @@ +import operation from "../../_operations/basin-catalog/maintenance-configs/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "basin-catalog maintenance-configs get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf basin-catalog maintenance-configs get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/maintenance-configs`, + pathParams: { "bucket-name": String(argv["bucket-name"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + bucket_name: argv["bucket-name"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/basin-catalog/maintenance-configs/get.ts b/packages/cli/src/commands/_generated/basin-catalog/maintenance-configs/get.ts index 2a111632f8..b85c0122b0 100644 --- a/packages/cli/src/commands/_generated/basin-catalog/maintenance-configs/get.ts +++ b/packages/cli/src/commands/_generated/basin-catalog/maintenance-configs/get.ts @@ -1,79 +1,37 @@ -import operation from "../../_operations/basin-catalog/maintenance-configs/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/basin-catalog.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 basin-catalog maintenance-configs get \n\nRetrieve the maintenance configuration for a specific catalog, including compaction settings and credential status." - ) - .positional("bucket-name", { - type: "string", - description: "Specifies the R2 bucket name.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "bucket-name", + brief: "Specifies the R2 bucket name.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get catalog maintenance configuration", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "basin-catalog maintenance-configs get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf basin-catalog maintenance-configs get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/maintenance-configs`, - pathParams: { "bucket-name": String(argv["bucket-name"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - bucket_name: argv["bucket-name"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 basin-catalog maintenance-configs get \n\nRetrieve the maintenance configuration for a specific catalog, including compaction settings and credential status.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/basin-catalog/maintenance-configs/index.ts b/packages/cli/src/commands/_generated/basin-catalog/maintenance-configs/index.ts index de974ec7c2..c43fdfefa5 100644 --- a/packages/cli/src/commands/_generated/basin-catalog/maintenance-configs/index.ts +++ b/packages/cli/src/commands/_generated/basin-catalog/maintenance-configs/index.ts @@ -1,25 +1,20 @@ import $get from "./get.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * maintenance-configs command group * @generated from apis/overlays/basin-catalog.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "maintenance-configs", describe: "Table maintenance settings — compaction schedules and snapshot expiration policies", - builder: (yargs) => { - return yargs - .command($get) - .command($update) - .demandCommand(1, "Please specify a subcommand"); + routes: { + get: $get, + update: $update, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/basin-catalog/maintenance-configs/update.handler.ts b/packages/cli/src/commands/_generated/basin-catalog/maintenance-configs/update.handler.ts new file mode 100644 index 0000000000..bf240af276 --- /dev/null +++ b/packages/cli/src/commands/_generated/basin-catalog/maintenance-configs/update.handler.ts @@ -0,0 +1,110 @@ +import operation from "../../_operations/basin-catalog/maintenance-configs/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "basin-catalog maintenance-configs update", + classification: { + safeFlags: [ + "compaction-state", + "compaction-target-size-mb", + "snapshot-expiration-state", + "dry-run", + ], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf basin-catalog maintenance-configs update", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/maintenance-configs`, + pathParams: { "bucket-name": String(argv["bucket-name"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + compaction: { + state: argv["compaction-state"], + target_size_mb: argv["compaction-target-size-mb"], + }, + snapshot_expiration: { + max_snapshot_age: resolveFileToken( + argv["snapshot-expiration-max-snapshot-age"] as + | string + | undefined, + "snapshot-expiration-max-snapshot-age", + "text" + ), + min_snapshots_to_keep: + argv["snapshot-expiration-min-snapshots-to-keep"], + state: argv["snapshot-expiration-state"], + }, + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + bucket_name: argv["bucket-name"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + compaction: { + state: argv["compaction-state"], + target_size_mb: argv["compaction-target-size-mb"], + }, + snapshot_expiration: { + max_snapshot_age: resolveFileToken( + argv["snapshot-expiration-max-snapshot-age"] as string | undefined, + "snapshot-expiration-max-snapshot-age", + "text" + ), + min_snapshots_to_keep: + argv["snapshot-expiration-min-snapshots-to-keep"], + state: argv["snapshot-expiration-state"], + }, + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + bucket_name: argv["bucket-name"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/basin-catalog/maintenance-configs/update.ts b/packages/cli/src/commands/_generated/basin-catalog/maintenance-configs/update.ts index 8b7a11ea7c..4dade93ca1 100644 --- a/packages/cli/src/commands/_generated/basin-catalog/maintenance-configs/update.ts +++ b/packages/cli/src/commands/_generated/basin-catalog/maintenance-configs/update.ts @@ -1,181 +1,84 @@ -import operation from "../../_operations/basin-catalog/maintenance-configs/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/basin-catalog.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 basin-catalog maintenance-configs update \n\nUpdate the maintenance configuration for a catalog. This allows you to enable or disable compaction and adjust target file sizes for optimization." - ) - .positional("bucket-name", { - type: "string", - description: "Specifies the R2 bucket name.", - demandOption: true, - }) - .option("compaction-state", { - type: "string", - description: "Specifies the state of maintenance operations.", +const parameters = { + flags: { + "compaction-state": { + kind: "parsed", + brief: "Specifies the state of maintenance operations.", + optional: true, choices: ["enabled", "disabled"], - }) - .coerce("compaction-state", (value) => - resolveFileToken(value, "compaction-state", "text") - ) - .option("compaction-target-size-mb", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "compaction-state", "text"), + }, + "compaction-target-size-mb": { + kind: "parsed", + brief: 'Sets the target file size for compaction in megabytes. Defaults to "128".', + optional: true, choices: ["64", "128", "256", "512"], - }) - .coerce("compaction-target-size-mb", (value) => - resolveFileToken(value, "compaction-target-size-mb", "text") - ) - .option("snapshot-expiration-max-snapshot-age", { - type: "string", - description: "Updates the maximum age for snapshots optionally.", - }) - .option("snapshot-expiration-min-snapshots-to-keep", { - type: "number", - description: - "Updates the minimum number of snapshots to retain optionally.", - }) - .option("snapshot-expiration-state", { - type: "string", - description: "Specifies the state of maintenance operations.", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "compaction-target-size-mb", "text"), + }, + "snapshot-expiration-max-snapshot-age": { + kind: "parsed", + brief: "Updates the maximum age for snapshots optionally.", + optional: true, + parse: String, + }, + "snapshot-expiration-min-snapshots-to-keep": { + kind: "parsed", + brief: "Updates the minimum number of snapshots to retain optionally.", + optional: true, + parse: Number, + }, + "snapshot-expiration-state": { + kind: "parsed", + brief: "Specifies the state of maintenance operations.", + optional: true, choices: ["enabled", "disabled"], - }) - .coerce("snapshot-expiration-state", (value) => - resolveFileToken(value, "snapshot-expiration-state", "text") - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "snapshot-expiration-state", "text"), + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: - "Contains request to update catalog maintenance configuration.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Contains request to update catalog maintenance configuration.", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "bucket-name", + brief: "Specifies the R2 bucket name.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update ", describe: "Update catalog maintenance configuration", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "basin-catalog maintenance-configs update", - classification: { - safeFlags: [ - "compaction-state", - "compaction-target-size-mb", - "snapshot-expiration-state", - "dry-run", - ], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf basin-catalog maintenance-configs update", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/maintenance-configs`, - pathParams: { "bucket-name": String(argv["bucket-name"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - compaction: { - state: argv["compaction-state"], - target_size_mb: argv["compaction-target-size-mb"], - }, - snapshot_expiration: { - max_snapshot_age: resolveFileToken( - argv["snapshot-expiration-max-snapshot-age"] as - | string - | undefined, - "snapshot-expiration-max-snapshot-age", - "text" - ), - min_snapshots_to_keep: - argv["snapshot-expiration-min-snapshots-to-keep"], - state: argv["snapshot-expiration-state"], - }, - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - bucket_name: argv["bucket-name"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - compaction: { - state: argv["compaction-state"], - target_size_mb: argv["compaction-target-size-mb"], - }, - snapshot_expiration: { - max_snapshot_age: resolveFileToken( - argv["snapshot-expiration-max-snapshot-age"] as - | string - | undefined, - "snapshot-expiration-max-snapshot-age", - "text" - ), - min_snapshots_to_keep: - argv["snapshot-expiration-min-snapshots-to-keep"], - state: argv["snapshot-expiration-state"], - }, - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - bucket_name: argv["bucket-name"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 basin-catalog maintenance-configs update \n\nUpdate the maintenance configuration for a catalog. This allows you to enable or disable compaction and adjust target file sizes for optimization.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/basin-catalog/namespaces/index.ts b/packages/cli/src/commands/_generated/basin-catalog/namespaces/index.ts index cc3fcc84cd..b4d8aa4709 100644 --- a/packages/cli/src/commands/_generated/basin-catalog/namespaces/index.ts +++ b/packages/cli/src/commands/_generated/basin-catalog/namespaces/index.ts @@ -1,25 +1,20 @@ import $list from "./list.js"; import $tables from "./tables/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * namespaces command group * @generated from apis/overlays/basin-catalog.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "namespaces", describe: "Logical namespaces that group related tables within the data catalog", - builder: (yargs) => { - return yargs - .command($list) - .command($tables) - .demandCommand(1, "Please specify a subcommand"); + routes: { + list: $list, + tables: $tables, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/basin-catalog/namespaces/list.handler.ts b/packages/cli/src/commands/_generated/basin-catalog/namespaces/list.handler.ts new file mode 100644 index 0000000000..66513f63f7 --- /dev/null +++ b/packages/cli/src/commands/_generated/basin-catalog/namespaces/list.handler.ts @@ -0,0 +1,58 @@ +import operation from "../../_operations/basin-catalog/namespaces/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "basin-catalog namespaces list", + classification: { + safeFlags: ["return-uuids", "return-details", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + page_token: argv["page-token"], + page_size: argv["page-size"], + parent: argv["parent"], + return_uuids: argv["return-uuids"], + return_details: argv["return-details"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf basin-catalog namespaces list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/namespaces`, + pathParams: { "bucket-name": String(argv["bucket-name"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + bucket_name: argv["bucket-name"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/basin-catalog/namespaces/list.ts b/packages/cli/src/commands/_generated/basin-catalog/namespaces/list.ts index e3f6bfbd40..42c9cb47a6 100644 --- a/packages/cli/src/commands/_generated/basin-catalog/namespaces/list.ts +++ b/packages/cli/src/commands/_generated/basin-catalog/namespaces/list.ts @@ -1,113 +1,69 @@ -import operation from "../../_operations/basin-catalog/namespaces/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/basin-catalog.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 basin-catalog namespaces list\n\nReturns a list of namespaces in the specified Basin Catalog. Supports hierarchical filtering and pagination for efficient traversal of large namespace hierarchies." - ) - .option("bucket-name", { - type: "string", - description: "Specifies the R2 bucket name.", - demandOption: true, - }) - .option("page-token", { - type: "string", - description: +const parameters = { + flags: { + "bucket-name": { + kind: "parsed", + brief: "Specifies the R2 bucket name.", + parse: String, + }, + "page-token": { + kind: "parsed", + brief: "Opaque pagination token from a previous response.\nUse this to fetch the next page of results.", - }) - .option("page-size", { - type: "number", - description: + optional: true, + parse: String, + }, + "page-size": { + kind: "parsed", + brief: "Maximum number of namespaces to return per page.\nDefaults to 100, maximum 1000.", - }) - .option("parent", { - type: "string", - description: + optional: true, + parse: Number, + }, + parent: { + kind: "parsed", + brief: 'Parent namespace to filter by. Only returns direct children of this namespace.\nFor nested namespaces, use %1F as separator (e.g., "bronze%1Fanalytics").\nOmit this parameter to list top-level namespaces.', - }) - .option("return-uuids", { - type: "boolean", - description: + optional: true, + parse: String, + }, + "return-uuids": { + kind: "boolean", + brief: "Whether to include namespace UUIDs in the response.\nSet to true to receive the namespace_uuids array.", - }) - .option("return-details", { - type: "boolean", - description: + optional: true, + }, + "return-details": { + kind: "boolean", + brief: "Whether to include additional metadata (timestamps).\nWhen true, response includes created_at and updated_at arrays.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List namespaces in catalog", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "basin-catalog namespaces list", - classification: { - safeFlags: ["return-uuids", "return-details", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page_token: argv["page-token"], - page_size: argv["page-size"], - parent: argv["parent"], - return_uuids: argv["return-uuids"], - return_details: argv["return-details"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf basin-catalog namespaces list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/namespaces`, - pathParams: { "bucket-name": String(argv["bucket-name"] ?? "") }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - bucket_name: argv["bucket-name"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 basin-catalog namespaces list\n\nReturns a list of namespaces in the specified Basin Catalog. Supports hierarchical filtering and pagination for efficient traversal of large namespace hierarchies.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/get.handler.ts b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/get.handler.ts new file mode 100644 index 0000000000..50a9c4c8ed --- /dev/null +++ b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/get.handler.ts @@ -0,0 +1,55 @@ +import operation from "../../../_operations/basin-catalog/namespaces/tables/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "basin-catalog namespaces tables get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf basin-catalog namespaces tables get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/tables/${argv["table-name"] == null ? "" : encodeURIComponent(String(argv["table-name"]))}`, + pathParams: { + "bucket-name": String(argv["bucket-name"] ?? ""), + namespace: String(argv["namespace"] ?? ""), + "table-name": String(argv["table-name"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + bucket_name: argv["bucket-name"], + namespace: argv["namespace"], + table_name: argv["table-name"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/get.ts b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/get.ts index f4cf7fe564..fa8db602d2 100644 --- a/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/get.ts +++ b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/get.ts @@ -1,96 +1,48 @@ -import operation from "../../../_operations/basin-catalog/namespaces/tables/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/basin-catalog.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 basin-catalog namespaces tables get \n\nReturns full Apache Iceberg metadata for a single table: schema, partition specs, sort orders, properties, and recent snapshot history. Designed for catalog introspection UIs that need per-table details without holding R2 credentials. The `metadata.snapshots`, `metadata.snapshot-log`, and `metadata.metadata-log` arrays are pruned to the most recent 10 entries by `timestamp-ms`. Use `total_snapshots` and `returned_snapshots` to surface the truncation to end users." - ) - .positional("table-name", { - type: "string", - description: "The table name within the given namespace.", - demandOption: true, - }) - .option("bucket-name", { - type: "string", - description: "Specifies the R2 bucket name.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: +const parameters = { + flags: { + "bucket-name": { + kind: "parsed", + brief: "Specifies the R2 bucket name.", + parse: String, + }, + namespace: { + kind: "parsed", + brief: 'The namespace identifier.\nFor nested namespaces, use %1F as separator (e.g., "bronze%1Fanalytics").', - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "table-name", + brief: "The table name within the given namespace.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get table details", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "basin-catalog namespaces tables get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf basin-catalog namespaces tables get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/tables/${argv["table-name"] == null ? "" : encodeURIComponent(String(argv["table-name"]))}`, - pathParams: { - "bucket-name": String(argv["bucket-name"] ?? ""), - namespace: String(argv["namespace"] ?? ""), - "table-name": String(argv["table-name"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - bucket_name: argv["bucket-name"], - namespace: argv["namespace"], - table_name: argv["table-name"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 basin-catalog namespaces tables get \n\nReturns full Apache Iceberg metadata for a single table: schema, partition specs, sort orders, properties, and recent snapshot history. Designed for catalog introspection UIs that need per-table details without holding R2 credentials. The `metadata.snapshots`, `metadata.snapshot-log`, and `metadata.metadata-log` arrays are pruned to the most recent 10 entries by `timestamp-ms`. Use `total_snapshots` and `returned_snapshots` to surface the truncation to end users.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/index.ts b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/index.ts index fefcaf9401..c92b238c49 100644 --- a/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/index.ts +++ b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/index.ts @@ -2,27 +2,22 @@ import $get from "./get.js"; import $list from "./list.js"; import $maintenanceconfigs from "./maintenance-configs/index.js"; import $maintenanceruns from "./maintenance-runs/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * tables command group * @generated from apis/overlays/basin-catalog.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "tables", describe: "Tables within catalog namespaces", - builder: (yargs) => { - return yargs - .command($get) - .command($list) - .command($maintenanceconfigs) - .command($maintenanceruns) - .demandCommand(1, "Please specify a subcommand"); + routes: { + get: $get, + list: $list, + "maintenance-configs": $maintenanceconfigs, + "maintenance-runs": $maintenanceruns, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/list.handler.ts b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/list.handler.ts new file mode 100644 index 0000000000..b1ea1ebf13 --- /dev/null +++ b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/list.handler.ts @@ -0,0 +1,61 @@ +import operation from "../../../_operations/basin-catalog/namespaces/tables/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "basin-catalog namespaces tables list", + classification: { + safeFlags: ["return-uuids", "return-details", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + page_token: argv["page-token"], + page_size: argv["page-size"], + return_uuids: argv["return-uuids"], + return_details: argv["return-details"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf basin-catalog namespaces tables list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/tables`, + pathParams: { + "bucket-name": String(argv["bucket-name"] ?? ""), + namespace: String(argv["namespace"] ?? ""), + }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + bucket_name: argv["bucket-name"], + namespace: argv["namespace"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/list.ts b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/list.ts index 64ec415f89..72814ce3cc 100644 --- a/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/list.ts +++ b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/list.ts @@ -1,117 +1,68 @@ -import operation from "../../../_operations/basin-catalog/namespaces/tables/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/basin-catalog.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 basin-catalog namespaces tables list\n\nReturns a list of tables in the specified namespace within a Basin Catalog. Supports pagination for efficient traversal of large table collections." - ) - .option("bucket-name", { - type: "string", - description: "Specifies the R2 bucket name.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: +const parameters = { + flags: { + "bucket-name": { + kind: "parsed", + brief: "Specifies the R2 bucket name.", + parse: String, + }, + namespace: { + kind: "parsed", + brief: 'The namespace identifier.\nFor nested namespaces, use %1F as separator (e.g., "bronze%1Fanalytics").', - demandOption: true, - }) - .option("page-token", { - type: "string", - description: + parse: String, + }, + "page-token": { + kind: "parsed", + brief: "Opaque pagination token from a previous response.\nUse this to fetch the next page of results.", - }) - .option("page-size", { - type: "number", - description: + optional: true, + parse: String, + }, + "page-size": { + kind: "parsed", + brief: "Maximum number of tables to return per page.\nDefaults to 100, maximum 1000.", - }) - .option("return-uuids", { - type: "boolean", - description: + optional: true, + parse: Number, + }, + "return-uuids": { + kind: "boolean", + brief: "Whether to include table UUIDs in the response.\nSet to true to receive the table_uuids array.", - }) - .option("return-details", { - type: "boolean", - description: + optional: true, + }, + "return-details": { + kind: "boolean", + brief: "Whether to include additional metadata (timestamps, locations).\nWhen true, response includes created_at, updated_at, metadata_locations, and locations arrays.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List tables in namespace", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "basin-catalog namespaces tables list", - classification: { - safeFlags: ["return-uuids", "return-details", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page_token: argv["page-token"], - page_size: argv["page-size"], - return_uuids: argv["return-uuids"], - return_details: argv["return-details"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf basin-catalog namespaces tables list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/tables`, - pathParams: { - "bucket-name": String(argv["bucket-name"] ?? ""), - namespace: String(argv["namespace"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - bucket_name: argv["bucket-name"], - namespace: argv["namespace"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 basin-catalog namespaces tables list\n\nReturns a list of tables in the specified namespace within a Basin Catalog. Supports pagination for efficient traversal of large table collections.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/get.handler.ts b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/get.handler.ts new file mode 100644 index 0000000000..ea9133c40d --- /dev/null +++ b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/get.handler.ts @@ -0,0 +1,55 @@ +import operation from "../../../../_operations/basin-catalog/namespaces/tables/maintenance-configs/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "basin-catalog namespaces tables maintenance-configs get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf basin-catalog namespaces tables maintenance-configs get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/tables/${argv["table-name"] == null ? "" : encodeURIComponent(String(argv["table-name"]))}/maintenance-configs`, + pathParams: { + "bucket-name": String(argv["bucket-name"] ?? ""), + namespace: String(argv["namespace"] ?? ""), + "table-name": String(argv["table-name"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + bucket_name: argv["bucket-name"], + namespace: argv["namespace"], + table_name: argv["table-name"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/get.ts b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/get.ts index 81d7de5cac..686b49fd7f 100644 --- a/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/get.ts +++ b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/get.ts @@ -1,97 +1,44 @@ -import operation from "../../../../_operations/basin-catalog/namespaces/tables/maintenance-configs/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/basin-catalog.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 basin-catalog namespaces tables maintenance-configs get \n\nRetrieve the maintenance configuration for a specific table, including compaction settings." - ) - .positional("table-name", { - type: "string", - description: "The table name.", - demandOption: true, - }) - .option("bucket-name", { - type: "string", - description: "Specifies the R2 bucket name.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: +const parameters = { + flags: { + "bucket-name": { + kind: "parsed", + brief: "Specifies the R2 bucket name.", + parse: String, + }, + namespace: { + kind: "parsed", + brief: "The namespace identifier (use %1F as separator for nested namespaces).", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "table-name", brief: "The table name.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get table maintenance configuration", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "basin-catalog namespaces tables maintenance-configs get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: - "cf basin-catalog namespaces tables maintenance-configs get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/tables/${argv["table-name"] == null ? "" : encodeURIComponent(String(argv["table-name"]))}/maintenance-configs`, - pathParams: { - "bucket-name": String(argv["bucket-name"] ?? ""), - namespace: String(argv["namespace"] ?? ""), - "table-name": String(argv["table-name"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - bucket_name: argv["bucket-name"], - namespace: argv["namespace"], - table_name: argv["table-name"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 basin-catalog namespaces tables maintenance-configs get \n\nRetrieve the maintenance configuration for a specific table, including compaction settings.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/index.ts b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/index.ts index 7d253be3f1..6e1bbb59ba 100644 --- a/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/index.ts +++ b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/index.ts @@ -1,26 +1,21 @@ import $get from "./get.js"; import $queue from "./queue.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * maintenance-configs command group * @generated from apis/overlays/basin-catalog.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "maintenance-configs", describe: "Table-level maintenance configurations and operations", - builder: (yargs) => { - return yargs - .command($get) - .command($queue) - .command($update) - .demandCommand(1, "Please specify a subcommand"); + routes: { + get: $get, + queue: $queue, + update: $update, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/queue.handler.ts b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/queue.handler.ts new file mode 100644 index 0000000000..4737841173 --- /dev/null +++ b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/queue.handler.ts @@ -0,0 +1,97 @@ +import operation from "../../../../_operations/basin-catalog/namespaces/tables/maintenance-configs/queue.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./queue.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "basin-catalog namespaces tables maintenance-configs queue", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: + "cf basin-catalog namespaces tables maintenance-configs queue", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/tables/${argv["table-name"] == null ? "" : encodeURIComponent(String(argv["table-name"]))}/maintenance-configs/${argv["configuration-type"] == null ? "" : encodeURIComponent(String(argv["configuration-type"]))}/queue`, + pathParams: { + "bucket-name": String(argv["bucket-name"] ?? ""), + namespace: String(argv["namespace"] ?? ""), + "table-name": String(argv["table-name"] ?? ""), + "configuration-type": String(argv["configuration-type"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + request_id: resolveFileToken( + argv["request-id"] as string | undefined, + "request-id", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + bucket_name: argv["bucket-name"], + namespace: argv["namespace"], + table_name: argv["table-name"], + configuration_type: argv["configuration-type"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + request_id: resolveFileToken( + argv["request-id"] as string | undefined, + "request-id", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + bucket_name: argv["bucket-name"], + namespace: argv["namespace"], + table_name: argv["table-name"], + configuration_type: argv["configuration-type"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/queue.ts b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/queue.ts index 973423889a..2186820dba 100644 --- a/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/queue.ts +++ b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/queue.ts @@ -1,150 +1,56 @@ -import operation from "../../../../_operations/basin-catalog/namespaces/tables/maintenance-configs/queue.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * queue command * @generated from apis/overlays/basin-catalog.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 basin-catalog namespaces tables maintenance-configs queue \n\nQueue maintenance for normal polling. This request does not start a run." - ) - .positional("configuration-type", { - type: "string", - description: "Configuration type", - demandOption: true, - }) - .option("bucket-name", { - type: "string", - description: "Specifies the R2 bucket name.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Namespace", - demandOption: true, - }) - .option("table-name", { - type: "string", - description: "Table name", - demandOption: true, - }) - .option("request-id", { - type: "string", - description: "The request_id field", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "bucket-name": { + kind: "parsed", + brief: "Specifies the R2 bucket name.", + parse: String, + }, + namespace: { kind: "parsed", brief: "Namespace", parse: String }, + "table-name": { kind: "parsed", brief: "Table name", parse: String }, + "request-id": { + kind: "parsed", + brief: "The request_id field", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "configuration-type", + brief: "Configuration type", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "queue ", describe: "Queue table maintenance", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "basin-catalog namespaces tables maintenance-configs queue", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: - "cf basin-catalog namespaces tables maintenance-configs queue", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/tables/${argv["table-name"] == null ? "" : encodeURIComponent(String(argv["table-name"]))}/maintenance-configs/${argv["configuration-type"] == null ? "" : encodeURIComponent(String(argv["configuration-type"]))}/queue`, - pathParams: { - "bucket-name": String(argv["bucket-name"] ?? ""), - namespace: String(argv["namespace"] ?? ""), - "table-name": String(argv["table-name"] ?? ""), - "configuration-type": String(argv["configuration-type"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - request_id: resolveFileToken( - argv["request-id"] as string | undefined, - "request-id", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - bucket_name: argv["bucket-name"], - namespace: argv["namespace"], - table_name: argv["table-name"], - configuration_type: argv["configuration-type"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - request_id: resolveFileToken( - argv["request-id"] as string | undefined, - "request-id", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - bucket_name: argv["bucket-name"], - namespace: argv["namespace"], - table_name: argv["table-name"], - configuration_type: argv["configuration-type"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 basin-catalog namespaces tables maintenance-configs queue \n\nQueue maintenance for normal polling. This request does not start a run.", + ...parameters, + loader: () => import("./queue.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/update.handler.ts b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/update.handler.ts new file mode 100644 index 0000000000..9941caa1cf --- /dev/null +++ b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/update.handler.ts @@ -0,0 +1,119 @@ +import operation from "../../../../_operations/basin-catalog/namespaces/tables/maintenance-configs/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "basin-catalog namespaces tables maintenance-configs update", + classification: { + safeFlags: [ + "compaction-state", + "compaction-target-size-mb", + "snapshot-expiration-state", + "dry-run", + ], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: + "cf basin-catalog namespaces tables maintenance-configs update", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/tables/${argv["table-name"] == null ? "" : encodeURIComponent(String(argv["table-name"]))}/maintenance-configs`, + pathParams: { + "bucket-name": String(argv["bucket-name"] ?? ""), + namespace: String(argv["namespace"] ?? ""), + "table-name": String(argv["table-name"] ?? ""), + }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + compaction: { + state: argv["compaction-state"], + target_size_mb: argv["compaction-target-size-mb"], + }, + snapshot_expiration: { + max_snapshot_age: resolveFileToken( + argv["snapshot-expiration-max-snapshot-age"] as + | string + | undefined, + "snapshot-expiration-max-snapshot-age", + "text" + ), + min_snapshots_to_keep: + argv["snapshot-expiration-min-snapshots-to-keep"], + state: argv["snapshot-expiration-state"], + }, + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + bucket_name: argv["bucket-name"], + namespace: argv["namespace"], + table_name: argv["table-name"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + compaction: { + state: argv["compaction-state"], + target_size_mb: argv["compaction-target-size-mb"], + }, + snapshot_expiration: { + max_snapshot_age: resolveFileToken( + argv["snapshot-expiration-max-snapshot-age"] as string | undefined, + "snapshot-expiration-max-snapshot-age", + "text" + ), + min_snapshots_to_keep: + argv["snapshot-expiration-min-snapshots-to-keep"], + state: argv["snapshot-expiration-state"], + }, + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + bucket_name: argv["bucket-name"], + namespace: argv["namespace"], + table_name: argv["table-name"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/update.ts b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/update.ts index 2842ca2836..65ee55316f 100644 --- a/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/update.ts +++ b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-configs/update.ts @@ -1,201 +1,91 @@ -import operation from "../../../../_operations/basin-catalog/namespaces/tables/maintenance-configs/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/basin-catalog.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 basin-catalog namespaces tables maintenance-configs update \n\nUpdate the maintenance configuration for a specific table. This allows you to enable or disable compaction and adjust target file sizes for optimization." - ) - .positional("table-name", { - type: "string", - description: "The table name.", - demandOption: true, - }) - .option("bucket-name", { - type: "string", - description: "Specifies the R2 bucket name.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: +const parameters = { + flags: { + "bucket-name": { + kind: "parsed", + brief: "Specifies the R2 bucket name.", + parse: String, + }, + namespace: { + kind: "parsed", + brief: "The namespace identifier (use %1F as separator for nested namespaces).", - demandOption: true, - }) - .option("compaction-state", { - type: "string", - description: "Specifies the state of maintenance operations.", + parse: String, + }, + "compaction-state": { + kind: "parsed", + brief: "Specifies the state of maintenance operations.", + optional: true, choices: ["enabled", "disabled"], - }) - .coerce("compaction-state", (value) => - resolveFileToken(value, "compaction-state", "text") - ) - .option("compaction-target-size-mb", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "compaction-state", "text"), + }, + "compaction-target-size-mb": { + kind: "parsed", + brief: 'Sets the target file size for compaction in megabytes. Defaults to "128".', + optional: true, choices: ["64", "128", "256", "512"], - }) - .coerce("compaction-target-size-mb", (value) => - resolveFileToken(value, "compaction-target-size-mb", "text") - ) - .option("snapshot-expiration-max-snapshot-age", { - type: "string", - description: "Updates the maximum age for snapshots optionally.", - }) - .option("snapshot-expiration-min-snapshots-to-keep", { - type: "number", - description: - "Updates the minimum number of snapshots to retain optionally.", - }) - .option("snapshot-expiration-state", { - type: "string", - description: "Specifies the state of maintenance operations.", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "compaction-target-size-mb", "text"), + }, + "snapshot-expiration-max-snapshot-age": { + kind: "parsed", + brief: "Updates the maximum age for snapshots optionally.", + optional: true, + parse: String, + }, + "snapshot-expiration-min-snapshots-to-keep": { + kind: "parsed", + brief: "Updates the minimum number of snapshots to retain optionally.", + optional: true, + parse: Number, + }, + "snapshot-expiration-state": { + kind: "parsed", + brief: "Specifies the state of maintenance operations.", + optional: true, choices: ["enabled", "disabled"], - }) - .coerce("snapshot-expiration-state", (value) => - resolveFileToken(value, "snapshot-expiration-state", "text") - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "snapshot-expiration-state", "text"), + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: - "Contains request to update table maintenance configuration.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Contains request to update table maintenance configuration.", + optional: true, + parse: String, + }, + }, + operands: [ + { placeholder: "table-name", brief: "The table name.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update ", describe: "Update table maintenance configuration", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "basin-catalog namespaces tables maintenance-configs update", - classification: { - safeFlags: [ - "compaction-state", - "compaction-target-size-mb", - "snapshot-expiration-state", - "dry-run", - ], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: - "cf basin-catalog namespaces tables maintenance-configs update", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/tables/${argv["table-name"] == null ? "" : encodeURIComponent(String(argv["table-name"]))}/maintenance-configs`, - pathParams: { - "bucket-name": String(argv["bucket-name"] ?? ""), - namespace: String(argv["namespace"] ?? ""), - "table-name": String(argv["table-name"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - compaction: { - state: argv["compaction-state"], - target_size_mb: argv["compaction-target-size-mb"], - }, - snapshot_expiration: { - max_snapshot_age: resolveFileToken( - argv["snapshot-expiration-max-snapshot-age"] as - | string - | undefined, - "snapshot-expiration-max-snapshot-age", - "text" - ), - min_snapshots_to_keep: - argv["snapshot-expiration-min-snapshots-to-keep"], - state: argv["snapshot-expiration-state"], - }, - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - bucket_name: argv["bucket-name"], - namespace: argv["namespace"], - table_name: argv["table-name"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - compaction: { - state: argv["compaction-state"], - target_size_mb: argv["compaction-target-size-mb"], - }, - snapshot_expiration: { - max_snapshot_age: resolveFileToken( - argv["snapshot-expiration-max-snapshot-age"] as - | string - | undefined, - "snapshot-expiration-max-snapshot-age", - "text" - ), - min_snapshots_to_keep: - argv["snapshot-expiration-min-snapshots-to-keep"], - state: argv["snapshot-expiration-state"], - }, - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - bucket_name: argv["bucket-name"], - namespace: argv["namespace"], - table_name: argv["table-name"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 basin-catalog namespaces tables maintenance-configs update \n\nUpdate the maintenance configuration for a specific table. This allows you to enable or disable compaction and adjust target file sizes for optimization.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-runs/index.ts b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-runs/index.ts index b09e6cc81c..6d6e967c59 100644 --- a/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-runs/index.ts +++ b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-runs/index.ts @@ -1,20 +1,17 @@ import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * maintenance-runs command group * @generated from apis/overlays/basin-catalog.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "maintenance-runs", describe: "History of maintenance runs performed on tables", - builder: (yargs) => { - return yargs.command($list).demandCommand(1, "Please specify a subcommand"); + routes: { + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-runs/list.handler.ts b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-runs/list.handler.ts new file mode 100644 index 0000000000..d83ac2d7d6 --- /dev/null +++ b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-runs/list.handler.ts @@ -0,0 +1,61 @@ +import operation from "../../../../_operations/basin-catalog/namespaces/tables/maintenance-runs/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "basin-catalog namespaces tables maintenance-runs list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + page_size: argv["page-size"], + page_token: argv["page-token"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf basin-catalog namespaces tables maintenance-runs list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/tables/${argv["table-name"] == null ? "" : encodeURIComponent(String(argv["table-name"]))}/maintenance-runs`, + pathParams: { + "bucket-name": String(argv["bucket-name"] ?? ""), + namespace: String(argv["namespace"] ?? ""), + "table-name": String(argv["table-name"] ?? ""), + }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + bucket_name: argv["bucket-name"], + namespace: argv["namespace"], + table_name: argv["table-name"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-runs/list.ts b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-runs/list.ts index 84a7955200..e9eda4f883 100644 --- a/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-runs/list.ts +++ b/packages/cli/src/commands/_generated/basin-catalog/namespaces/tables/maintenance-runs/list.ts @@ -1,103 +1,50 @@ -import operation from "../../../../_operations/basin-catalog/namespaces/tables/maintenance-runs/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/basin-catalog.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 basin-catalog namespaces tables maintenance-runs list\n\nRetrieves recent table maintenance runs for the current table." - ) - .option("bucket-name", { - type: "string", - description: "Specifies the R2 bucket name.", - demandOption: true, - }) - .option("namespace", { - type: "string", - description: "Namespace", - demandOption: true, - }) - .option("table-name", { - type: "string", - description: "Table name", - demandOption: true, - }) - .option("page-size", { type: "number", description: "Page size" }) - .option("page-token", { type: "string", description: "Page token" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "bucket-name": { + kind: "parsed", + brief: "Specifies the R2 bucket name.", + parse: String, + }, + namespace: { kind: "parsed", brief: "Namespace", parse: String }, + "table-name": { kind: "parsed", brief: "Table name", parse: String }, + "page-size": { + kind: "parsed", + brief: "Page size", + optional: true, + parse: Number, + }, + "page-token": { + kind: "parsed", + brief: "Page token", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List table maintenance runs", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "basin-catalog namespaces tables maintenance-runs list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - page_size: argv["page-size"], - page_token: argv["page-token"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf basin-catalog namespaces tables maintenance-runs list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/basin-catalog/${argv["bucket-name"] == null ? "" : encodeURIComponent(String(argv["bucket-name"]))}/namespaces/${argv["namespace"] == null ? "" : encodeURIComponent(String(argv["namespace"]))}/tables/${argv["table-name"] == null ? "" : encodeURIComponent(String(argv["table-name"]))}/maintenance-runs`, - pathParams: { - "bucket-name": String(argv["bucket-name"] ?? ""), - namespace: String(argv["namespace"] ?? ""), - "table-name": String(argv["table-name"] ?? ""), - }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - bucket_name: argv["bucket-name"], - namespace: argv["namespace"], - table_name: argv["table-name"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 basin-catalog namespaces tables maintenance-runs list\n\nRetrieves recent table maintenance runs for the current table.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/addresses/index.ts b/packages/cli/src/commands/_generated/billing/addresses/index.ts index 6fd108118a..9220a13410 100644 --- a/packages/cli/src/commands/_generated/billing/addresses/index.ts +++ b/packages/cli/src/commands/_generated/billing/addresses/index.ts @@ -1,22 +1,17 @@ import $validate from "./validate.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * addresses command group * @generated from apis/overlays/billing.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "addresses", describe: "Operations for addresses", - builder: (yargs) => { - return yargs - .command($validate) - .demandCommand(1, "Please specify a subcommand"); + routes: { + validate: $validate, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/addresses/validate.handler.ts b/packages/cli/src/commands/_generated/billing/addresses/validate.handler.ts new file mode 100644 index 0000000000..7d7fbfc5ec --- /dev/null +++ b/packages/cli/src/commands/_generated/billing/addresses/validate.handler.ts @@ -0,0 +1,119 @@ +import operation from "../../_operations/billing/addresses/validate.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./validate.js"; +import { createCommandClient } from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "billing addresses validate", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf billing addresses validate", + method: "POST", + url: `https://api.cloudflare.com/client/v4/billing/address-validation`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + address: resolveFileToken( + argv["address"] as string | undefined, + "address", + "text" + ), + address2: resolveFileToken( + argv["address2"] as string | undefined, + "address2", + "text" + ), + city: resolveFileToken( + argv["city"] as string | undefined, + "city", + "text" + ), + country: resolveFileToken( + argv["country"] as string | undefined, + "country", + "text" + ), + state: resolveFileToken( + argv["state"] as string | undefined, + "state", + "text" + ), + zipcode: resolveFileToken( + argv["zipcode"] as string | undefined, + "zipcode", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Validating`, async () => + client.send(operation, { body: bodyData }) + ); + formatOutput(result, { successLabel: `Validated` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + address: resolveFileToken( + argv["address"] as string | undefined, + "address", + "text" + ), + address2: resolveFileToken( + argv["address2"] as string | undefined, + "address2", + "text" + ), + city: resolveFileToken( + argv["city"] as string | undefined, + "city", + "text" + ), + country: resolveFileToken( + argv["country"] as string | undefined, + "country", + "text" + ), + state: resolveFileToken( + argv["state"] as string | undefined, + "state", + "text" + ), + zipcode: resolveFileToken( + argv["zipcode"] as string | undefined, + "zipcode", + "text" + ), + }); + const result = await withProgress(`Validating`, async () => + client.send(operation, { body: bodyData }) + ); + formatOutput(result, { successLabel: `Validated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/billing/addresses/validate.ts b/packages/cli/src/commands/_generated/billing/addresses/validate.ts index 854d51a5ba..6be585f850 100644 --- a/packages/cli/src/commands/_generated/billing/addresses/validate.ts +++ b/packages/cli/src/commands/_generated/billing/addresses/validate.ts @@ -1,154 +1,68 @@ -import operation from "../../_operations/billing/addresses/validate.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * validate command * @generated from apis/overlays/billing.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient } from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 billing addresses validate\n\nValidates a billing address and returns validated address suggestions. Authentication is not enforced to support pre-signup address validation flows, so credentials are accepted but not required." - ) - .option("address", { type: "string", description: "Address line 1." }) - .option("address2", { type: "string", description: "Address line 2." }) - .option("city", { type: "string", description: "City." }) - .option("country", { type: "string", description: "Country code." }) - .option("state", { type: "string", description: "State or province." }) - .option("zipcode", { type: "string", description: "Postal or zip code." }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + address: { + kind: "parsed", + brief: "Address line 1.", + optional: true, + parse: String, + }, + address2: { + kind: "parsed", + brief: "Address line 2.", + optional: true, + parse: String, + }, + city: { kind: "parsed", brief: "City.", optional: true, parse: String }, + country: { + kind: "parsed", + brief: "Country code.", + optional: true, + parse: String, + }, + state: { + kind: "parsed", + brief: "State or province.", + optional: true, + parse: String, + }, + zipcode: { + kind: "parsed", + brief: "Postal or zip code.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "validate", describe: "Validate Billing Address", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "billing addresses validate", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf billing addresses validate", - method: "POST", - url: `https://api.cloudflare.com/client/v4/billing/address-validation`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - address: resolveFileToken( - argv["address"] as string | undefined, - "address", - "text" - ), - address2: resolveFileToken( - argv["address2"] as string | undefined, - "address2", - "text" - ), - city: resolveFileToken( - argv["city"] as string | undefined, - "city", - "text" - ), - country: resolveFileToken( - argv["country"] as string | undefined, - "country", - "text" - ), - state: resolveFileToken( - argv["state"] as string | undefined, - "state", - "text" - ), - zipcode: resolveFileToken( - argv["zipcode"] as string | undefined, - "zipcode", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Validating`, async () => - client.send(operation, { body: bodyData }) - ); - formatOutput(result, { successLabel: `Validated` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - address: resolveFileToken( - argv["address"] as string | undefined, - "address", - "text" - ), - address2: resolveFileToken( - argv["address2"] as string | undefined, - "address2", - "text" - ), - city: resolveFileToken( - argv["city"] as string | undefined, - "city", - "text" - ), - country: resolveFileToken( - argv["country"] as string | undefined, - "country", - "text" - ), - state: resolveFileToken( - argv["state"] as string | undefined, - "state", - "text" - ), - zipcode: resolveFileToken( - argv["zipcode"] as string | undefined, - "zipcode", - "text" - ), - }); - const result = await withProgress(`Validating`, async () => - client.send(operation, { body: bodyData }) - ); - formatOutput(result, { successLabel: `Validated` }); - } - ), -}; + usage: + "$0 billing addresses validate\n\nValidates a billing address and returns validated address suggestions. Authentication is not enforced to support pre-signup address validation flows, so credentials are accepted but not required.", + ...parameters, + loader: () => import("./validate.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/index.ts b/packages/cli/src/commands/_generated/billing/index.ts index 62b1584b49..afe5c630d9 100644 --- a/packages/cli/src/commands/_generated/billing/index.ts +++ b/packages/cli/src/commands/_generated/billing/index.ts @@ -3,29 +3,24 @@ import $profiles from "./profiles/index.js"; import $rateplans from "./rate-plans/index.js"; import $spendpolicies from "./spend-policies/index.js"; import $usage from "./usage/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * billing command * @generated from apis/overlays/billing.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "billing", describe: "Account billing profiles and usage data for Cloudflare subscriptions and add-on services", - builder: (yargs) => { - return yargs - .command($addresses) - .command($profiles) - .command($rateplans) - .command($spendpolicies) - .command($usage) - .demandCommand(1, "Please specify a subcommand"); + routes: { + addresses: $addresses, + profiles: $profiles, + "rate-plans": $rateplans, + "spend-policies": $spendpolicies, + usage: $usage, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/profiles/create-payment-intent.handler.ts b/packages/cli/src/commands/_generated/billing/profiles/create-payment-intent.handler.ts new file mode 100644 index 0000000000..01689157cf --- /dev/null +++ b/packages/cli/src/commands/_generated/billing/profiles/create-payment-intent.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/billing/profiles/create-payment-intent.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create-payment-intent.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "billing profiles create-payment-intent", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf billing profiles create-payment-intent", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/profile/payment-method`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Creating`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/billing/profiles/create-payment-intent.ts b/packages/cli/src/commands/_generated/billing/profiles/create-payment-intent.ts index db9e4894bf..3da73ada64 100644 --- a/packages/cli/src/commands/_generated/billing/profiles/create-payment-intent.ts +++ b/packages/cli/src/commands/_generated/billing/profiles/create-payment-intent.ts @@ -1,71 +1,31 @@ -import operation from "../../_operations/billing/profiles/create-payment-intent.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create-payment-intent command * @generated from apis/overlays/billing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 billing profiles create-payment-intent\n\nCreates a Stripe payment intent for adding or updating a payment method on the account's billing profile. Returns a client secret for frontend payment method collection." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create-payment-intent", describe: "Create Payment Intent for Billing Profile", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "billing profiles create-payment-intent", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf billing profiles create-payment-intent", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/profile/payment-method`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Creating`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 billing profiles create-payment-intent\n\nCreates a Stripe payment intent for adding or updating a payment method on the account's billing profile. Returns a client secret for frontend payment method collection.", + ...parameters, + loader: () => import("./create-payment-intent.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/profiles/create.handler.ts b/packages/cli/src/commands/_generated/billing/profiles/create.handler.ts new file mode 100644 index 0000000000..765505d0b5 --- /dev/null +++ b/packages/cli/src/commands/_generated/billing/profiles/create.handler.ts @@ -0,0 +1,253 @@ +import operation from "../../_operations/billing/profiles/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "billing profiles create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf billing profiles create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/profile`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + address: resolveFileToken( + argv["address"] as string | undefined, + "address", + "text" + ), + address2: resolveFileToken( + argv["address2"] as string | undefined, + "address2", + "text" + ), + billing_email: resolveFileToken( + argv["billing-email"] as string | undefined, + "billing-email", + "text" + ), + buying_rate_plan: resolveFileToken( + argv["buying-rate-plan"] as string | undefined, + "buying-rate-plan", + "text" + ), + captcha_challenge_jwt: resolveFileToken( + argv["captcha-challenge-jwt"] as string | undefined, + "captcha-challenge-jwt", + "text" + ), + cf_turnstile_response: resolveFileToken( + argv["cf-turnstile-response"] as string | undefined, + "cf-turnstile-response", + "text" + ), + city: resolveFileToken( + argv["city"] as string | undefined, + "city", + "text" + ), + company: resolveFileToken( + argv["company"] as string | undefined, + "company", + "text" + ), + country: resolveFileToken( + argv["country"] as string | undefined, + "country", + "text" + ), + first_name: resolveFileToken( + argv["first-name"] as string | undefined, + "first-name", + "text" + ), + h_captcha_response: resolveFileToken( + argv["h-captcha-response"] as string | undefined, + "h-captcha-response", + "text" + ), + last_name: resolveFileToken( + argv["last-name"] as string | undefined, + "last-name", + "text" + ), + preferred_locale: resolveFileToken( + argv["preferred-locale"] as string | undefined, + "preferred-locale", + "text" + ), + secondary_billing_email: resolveFileToken( + argv["secondary-billing-email"] as string | undefined, + "secondary-billing-email", + "text" + ), + state: resolveFileToken( + argv["state"] as string | undefined, + "state", + "text" + ), + tax_id_type: resolveFileToken( + argv["tax-id-type"] as string | undefined, + "tax-id-type", + "text" + ), + telephone: resolveFileToken( + argv["telephone"] as string | undefined, + "telephone", + "text" + ), + vat: resolveFileToken( + argv["vat"] as string | undefined, + "vat", + "text" + ), + zipcode: resolveFileToken( + argv["zipcode"] as string | undefined, + "zipcode", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + address: resolveFileToken( + argv["address"] as string | undefined, + "address", + "text" + ), + address2: resolveFileToken( + argv["address2"] as string | undefined, + "address2", + "text" + ), + billing_email: resolveFileToken( + argv["billing-email"] as string | undefined, + "billing-email", + "text" + ), + buying_rate_plan: resolveFileToken( + argv["buying-rate-plan"] as string | undefined, + "buying-rate-plan", + "text" + ), + captcha_challenge_jwt: resolveFileToken( + argv["captcha-challenge-jwt"] as string | undefined, + "captcha-challenge-jwt", + "text" + ), + cf_turnstile_response: resolveFileToken( + argv["cf-turnstile-response"] as string | undefined, + "cf-turnstile-response", + "text" + ), + city: resolveFileToken( + argv["city"] as string | undefined, + "city", + "text" + ), + company: resolveFileToken( + argv["company"] as string | undefined, + "company", + "text" + ), + country: resolveFileToken( + argv["country"] as string | undefined, + "country", + "text" + ), + first_name: resolveFileToken( + argv["first-name"] as string | undefined, + "first-name", + "text" + ), + h_captcha_response: resolveFileToken( + argv["h-captcha-response"] as string | undefined, + "h-captcha-response", + "text" + ), + last_name: resolveFileToken( + argv["last-name"] as string | undefined, + "last-name", + "text" + ), + preferred_locale: resolveFileToken( + argv["preferred-locale"] as string | undefined, + "preferred-locale", + "text" + ), + secondary_billing_email: resolveFileToken( + argv["secondary-billing-email"] as string | undefined, + "secondary-billing-email", + "text" + ), + state: resolveFileToken( + argv["state"] as string | undefined, + "state", + "text" + ), + tax_id_type: resolveFileToken( + argv["tax-id-type"] as string | undefined, + "tax-id-type", + "text" + ), + telephone: resolveFileToken( + argv["telephone"] as string | undefined, + "telephone", + "text" + ), + vat: resolveFileToken(argv["vat"] as string | undefined, "vat", "text"), + zipcode: resolveFileToken( + argv["zipcode"] as string | undefined, + "zipcode", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/billing/profiles/create.ts b/packages/cli/src/commands/_generated/billing/profiles/create.ts index 36e4b9cf30..1a2ee1398a 100644 --- a/packages/cli/src/commands/_generated/billing/profiles/create.ts +++ b/packages/cli/src/commands/_generated/billing/profiles/create.ts @@ -1,356 +1,151 @@ -import operation from "../../_operations/billing/profiles/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/billing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 billing profiles create\n\nCreates a billing profile for an account." - ) - .option("address", { - type: "string", - description: "Street address line 1.", - }) - .option("address2", { - type: "string", - description: "Street address line 2 (apt, suite, etc.).", - }) - .option("billing-email", { - type: "string", - description: "Primary billing email address.", - }) - .option("buying-rate-plan", { - type: "string", - description: "Rate plan being purchased right after profile setup.", - }) - .option("captcha-challenge-jwt", { - type: "string", - description: "Captcha challenge JWT issued during onboarding.", - }) - .option("cf-turnstile-response", { - type: "string", - description: "Cloudflare Turnstile response.", - }) - .option("city", { - type: "string", - description: "City on the billing profile.", - }) - .option("company", { - type: "string", - description: "Company name on the billing profile.", - }) - .option("country", { - type: "string", - description: "ISO 3166-1 alpha-2 country code.", - }) - .option("first-name", { - type: "string", - description: "First name on the billing profile.", - }) - .option("h-captcha-response", { - type: "string", - description: "hCaptcha response.", - }) - .option("last-name", { - type: "string", - description: "Last name on the billing profile.", - }) - .option("preferred-locale", { - type: "string", - description: "Preferred locale for invoice rendering (BCP 47).", - }) - .option("secondary-billing-email", { - type: "string", - description: "Secondary billing email address for CC on invoices.", - }) - .option("state", { - type: "string", - description: "State or region on the billing profile.", - }) - .option("tax-id-type", { - type: "string", - description: "Type of tax ID provided.", - }) - .option("telephone", { - type: "string", - description: "Contact phone number.", - }) - .option("vat", { type: "string", description: "VAT identifier." }) - .option("zipcode", { type: "string", description: "ZIP or postal code." }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + address: { + kind: "parsed", + brief: "Street address line 1.", + optional: true, + parse: String, + }, + address2: { + kind: "parsed", + brief: "Street address line 2 (apt, suite, etc.).", + optional: true, + parse: String, + }, + "billing-email": { + kind: "parsed", + brief: "Primary billing email address.", + optional: true, + parse: String, + }, + "buying-rate-plan": { + kind: "parsed", + brief: "Rate plan being purchased right after profile setup.", + optional: true, + parse: String, + }, + "captcha-challenge-jwt": { + kind: "parsed", + brief: "Captcha challenge JWT issued during onboarding.", + optional: true, + parse: String, + }, + "cf-turnstile-response": { + kind: "parsed", + brief: "Cloudflare Turnstile response.", + optional: true, + parse: String, + }, + city: { + kind: "parsed", + brief: "City on the billing profile.", + optional: true, + parse: String, + }, + company: { + kind: "parsed", + brief: "Company name on the billing profile.", + optional: true, + parse: String, + }, + country: { + kind: "parsed", + brief: "ISO 3166-1 alpha-2 country code.", + optional: true, + parse: String, + }, + "first-name": { + kind: "parsed", + brief: "First name on the billing profile.", + optional: true, + parse: String, + }, + "h-captcha-response": { + kind: "parsed", + brief: "hCaptcha response.", + optional: true, + parse: String, + }, + "last-name": { + kind: "parsed", + brief: "Last name on the billing profile.", + optional: true, + parse: String, + }, + "preferred-locale": { + kind: "parsed", + brief: "Preferred locale for invoice rendering (BCP 47).", + optional: true, + parse: String, + }, + "secondary-billing-email": { + kind: "parsed", + brief: "Secondary billing email address for CC on invoices.", + optional: true, + parse: String, + }, + state: { + kind: "parsed", + brief: "State or region on the billing profile.", + optional: true, + parse: String, + }, + "tax-id-type": { + kind: "parsed", + brief: "Type of tax ID provided.", + optional: true, + parse: String, + }, + telephone: { + kind: "parsed", + brief: "Contact phone number.", + optional: true, + parse: String, + }, + vat: { + kind: "parsed", + brief: "VAT identifier.", + optional: true, + parse: String, + }, + zipcode: { + kind: "parsed", + brief: "ZIP or postal code.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Request body for creating or updating a billing profile.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Request body for creating or updating a billing profile.", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Create Billing Profile", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "billing profiles create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf billing profiles create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/profile`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - address: resolveFileToken( - argv["address"] as string | undefined, - "address", - "text" - ), - address2: resolveFileToken( - argv["address2"] as string | undefined, - "address2", - "text" - ), - billing_email: resolveFileToken( - argv["billing-email"] as string | undefined, - "billing-email", - "text" - ), - buying_rate_plan: resolveFileToken( - argv["buying-rate-plan"] as string | undefined, - "buying-rate-plan", - "text" - ), - captcha_challenge_jwt: resolveFileToken( - argv["captcha-challenge-jwt"] as string | undefined, - "captcha-challenge-jwt", - "text" - ), - cf_turnstile_response: resolveFileToken( - argv["cf-turnstile-response"] as string | undefined, - "cf-turnstile-response", - "text" - ), - city: resolveFileToken( - argv["city"] as string | undefined, - "city", - "text" - ), - company: resolveFileToken( - argv["company"] as string | undefined, - "company", - "text" - ), - country: resolveFileToken( - argv["country"] as string | undefined, - "country", - "text" - ), - first_name: resolveFileToken( - argv["first-name"] as string | undefined, - "first-name", - "text" - ), - h_captcha_response: resolveFileToken( - argv["h-captcha-response"] as string | undefined, - "h-captcha-response", - "text" - ), - last_name: resolveFileToken( - argv["last-name"] as string | undefined, - "last-name", - "text" - ), - preferred_locale: resolveFileToken( - argv["preferred-locale"] as string | undefined, - "preferred-locale", - "text" - ), - secondary_billing_email: resolveFileToken( - argv["secondary-billing-email"] as string | undefined, - "secondary-billing-email", - "text" - ), - state: resolveFileToken( - argv["state"] as string | undefined, - "state", - "text" - ), - tax_id_type: resolveFileToken( - argv["tax-id-type"] as string | undefined, - "tax-id-type", - "text" - ), - telephone: resolveFileToken( - argv["telephone"] as string | undefined, - "telephone", - "text" - ), - vat: resolveFileToken( - argv["vat"] as string | undefined, - "vat", - "text" - ), - zipcode: resolveFileToken( - argv["zipcode"] as string | undefined, - "zipcode", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - address: resolveFileToken( - argv["address"] as string | undefined, - "address", - "text" - ), - address2: resolveFileToken( - argv["address2"] as string | undefined, - "address2", - "text" - ), - billing_email: resolveFileToken( - argv["billing-email"] as string | undefined, - "billing-email", - "text" - ), - buying_rate_plan: resolveFileToken( - argv["buying-rate-plan"] as string | undefined, - "buying-rate-plan", - "text" - ), - captcha_challenge_jwt: resolveFileToken( - argv["captcha-challenge-jwt"] as string | undefined, - "captcha-challenge-jwt", - "text" - ), - cf_turnstile_response: resolveFileToken( - argv["cf-turnstile-response"] as string | undefined, - "cf-turnstile-response", - "text" - ), - city: resolveFileToken( - argv["city"] as string | undefined, - "city", - "text" - ), - company: resolveFileToken( - argv["company"] as string | undefined, - "company", - "text" - ), - country: resolveFileToken( - argv["country"] as string | undefined, - "country", - "text" - ), - first_name: resolveFileToken( - argv["first-name"] as string | undefined, - "first-name", - "text" - ), - h_captcha_response: resolveFileToken( - argv["h-captcha-response"] as string | undefined, - "h-captcha-response", - "text" - ), - last_name: resolveFileToken( - argv["last-name"] as string | undefined, - "last-name", - "text" - ), - preferred_locale: resolveFileToken( - argv["preferred-locale"] as string | undefined, - "preferred-locale", - "text" - ), - secondary_billing_email: resolveFileToken( - argv["secondary-billing-email"] as string | undefined, - "secondary-billing-email", - "text" - ), - state: resolveFileToken( - argv["state"] as string | undefined, - "state", - "text" - ), - tax_id_type: resolveFileToken( - argv["tax-id-type"] as string | undefined, - "tax-id-type", - "text" - ), - telephone: resolveFileToken( - argv["telephone"] as string | undefined, - "telephone", - "text" - ), - vat: resolveFileToken( - argv["vat"] as string | undefined, - "vat", - "text" - ), - zipcode: resolveFileToken( - argv["zipcode"] as string | undefined, - "zipcode", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 billing profiles create\n\nCreates a billing profile for an account.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/profiles/delete.handler.ts b/packages/cli/src/commands/_generated/billing/profiles/delete.handler.ts new file mode 100644 index 0000000000..0cffa66806 --- /dev/null +++ b/packages/cli/src/commands/_generated/billing/profiles/delete.handler.ts @@ -0,0 +1,52 @@ +import operation from "../../_operations/billing/profiles/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "billing profiles delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf billing profiles delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/profile`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/billing/profiles/delete.ts b/packages/cli/src/commands/_generated/billing/profiles/delete.ts index aa323a16b4..4afce132fa 100644 --- a/packages/cli/src/commands/_generated/billing/profiles/delete.ts +++ b/packages/cli/src/commands/_generated/billing/profiles/delete.ts @@ -1,83 +1,37 @@ -import operation from "../../_operations/billing/profiles/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/billing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 billing profiles delete\n\nDeletes the billing profile for an account." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete", describe: "Delete Billing Profile", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "billing profiles delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf billing profiles delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/profile`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 billing profiles delete\n\nDeletes the billing profile for an account.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/profiles/get.handler.ts b/packages/cli/src/commands/_generated/billing/profiles/get.handler.ts new file mode 100644 index 0000000000..bee88d901f --- /dev/null +++ b/packages/cli/src/commands/_generated/billing/profiles/get.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/billing/profiles/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "billing profiles get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf billing profiles get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/profile`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/billing/profiles/get.ts b/packages/cli/src/commands/_generated/billing/profiles/get.ts index ff612aa519..0f38829b0f 100644 --- a/packages/cli/src/commands/_generated/billing/profiles/get.ts +++ b/packages/cli/src/commands/_generated/billing/profiles/get.ts @@ -1,71 +1,31 @@ -import operation from "../../_operations/billing/profiles/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/billing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 billing profiles get\n\nGets the current billing profile for the account." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "Get Billing Profile", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "billing profiles get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf billing profiles get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/profile`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 billing profiles get\n\nGets the current billing profile for the account.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/profiles/index.ts b/packages/cli/src/commands/_generated/billing/profiles/index.ts index 5928fd9540..8dcbfa8b7e 100644 --- a/packages/cli/src/commands/_generated/billing/profiles/index.ts +++ b/packages/cli/src/commands/_generated/billing/profiles/index.ts @@ -4,30 +4,25 @@ import $delete from "./delete.js"; import $get from "./get.js"; import $updateemail from "./update-email.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * profiles command group * @generated from apis/overlays/billing.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "profiles", describe: "Billing profile with payment method, address, and invoice preferences", - builder: (yargs) => { - return yargs - .command($create) - .command($createpaymentintent) - .command($delete) - .command($get) - .command($update) - .command($updateemail) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + "create-payment-intent": $createpaymentintent, + delete: $delete, + get: $get, + update: $update, + "update-email": $updateemail, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/profiles/update-email.handler.ts b/packages/cli/src/commands/_generated/billing/profiles/update-email.handler.ts new file mode 100644 index 0000000000..fddc544212 --- /dev/null +++ b/packages/cli/src/commands/_generated/billing/profiles/update-email.handler.ts @@ -0,0 +1,97 @@ +import operation from "../../_operations/billing/profiles/update-email.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update-email.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "billing profiles update-email", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf billing profiles update-email", + method: "PATCH", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/profile`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + billing_email: resolveFileToken( + argv["billing-email"] as string | undefined, + "billing-email", + "text" + ), + preferred_locale: resolveFileToken( + argv["preferred-locale"] as string | undefined, + "preferred-locale", + "text" + ), + secondary_billing_email: resolveFileToken( + argv["secondary-billing-email"] as string | undefined, + "secondary-billing-email", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + billing_email: resolveFileToken( + argv["billing-email"] as string | undefined, + "billing-email", + "text" + ), + preferred_locale: resolveFileToken( + argv["preferred-locale"] as string | undefined, + "preferred-locale", + "text" + ), + secondary_billing_email: resolveFileToken( + argv["secondary-billing-email"] as string | undefined, + "secondary-billing-email", + "text" + ), + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/billing/profiles/update-email.ts b/packages/cli/src/commands/_generated/billing/profiles/update-email.ts index dab74b9fac..da957d3f14 100644 --- a/packages/cli/src/commands/_generated/billing/profiles/update-email.ts +++ b/packages/cli/src/commands/_generated/billing/profiles/update-email.ts @@ -1,138 +1,55 @@ -import operation from "../../_operations/billing/profiles/update-email.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update-email command * @generated from apis/overlays/billing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 billing profiles update-email\n\nUpdates the billing email addresses and preferred locale for an account." - ) - .option("billing-email", { - type: "string", - description: "The billing_email field", - }) - .option("preferred-locale", { - type: "string", - description: "The preferred_locale field", - }) - .option("secondary-billing-email", { - type: "string", - description: "The secondary_billing_email field", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "billing-email": { + kind: "parsed", + brief: "The billing_email field", + optional: true, + parse: String, + }, + "preferred-locale": { + kind: "parsed", + brief: "The preferred_locale field", + optional: true, + parse: String, + }, + "secondary-billing-email": { + kind: "parsed", + brief: "The secondary_billing_email field", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update-email", describe: "Update Billing Email", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "billing profiles update-email", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf billing profiles update-email", - method: "PATCH", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/profile`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - billing_email: resolveFileToken( - argv["billing-email"] as string | undefined, - "billing-email", - "text" - ), - preferred_locale: resolveFileToken( - argv["preferred-locale"] as string | undefined, - "preferred-locale", - "text" - ), - secondary_billing_email: resolveFileToken( - argv["secondary-billing-email"] as string | undefined, - "secondary-billing-email", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - billing_email: resolveFileToken( - argv["billing-email"] as string | undefined, - "billing-email", - "text" - ), - preferred_locale: resolveFileToken( - argv["preferred-locale"] as string | undefined, - "preferred-locale", - "text" - ), - secondary_billing_email: resolveFileToken( - argv["secondary-billing-email"] as string | undefined, - "secondary-billing-email", - "text" - ), - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 billing profiles update-email\n\nUpdates the billing email addresses and preferred locale for an account.", + ...parameters, + loader: () => import("./update-email.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/profiles/update.handler.ts b/packages/cli/src/commands/_generated/billing/profiles/update.handler.ts new file mode 100644 index 0000000000..400bc48f82 --- /dev/null +++ b/packages/cli/src/commands/_generated/billing/profiles/update.handler.ts @@ -0,0 +1,253 @@ +import operation from "../../_operations/billing/profiles/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "billing profiles update", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf billing profiles update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/profile`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + address: resolveFileToken( + argv["address"] as string | undefined, + "address", + "text" + ), + address2: resolveFileToken( + argv["address2"] as string | undefined, + "address2", + "text" + ), + billing_email: resolveFileToken( + argv["billing-email"] as string | undefined, + "billing-email", + "text" + ), + buying_rate_plan: resolveFileToken( + argv["buying-rate-plan"] as string | undefined, + "buying-rate-plan", + "text" + ), + captcha_challenge_jwt: resolveFileToken( + argv["captcha-challenge-jwt"] as string | undefined, + "captcha-challenge-jwt", + "text" + ), + cf_turnstile_response: resolveFileToken( + argv["cf-turnstile-response"] as string | undefined, + "cf-turnstile-response", + "text" + ), + city: resolveFileToken( + argv["city"] as string | undefined, + "city", + "text" + ), + company: resolveFileToken( + argv["company"] as string | undefined, + "company", + "text" + ), + country: resolveFileToken( + argv["country"] as string | undefined, + "country", + "text" + ), + first_name: resolveFileToken( + argv["first-name"] as string | undefined, + "first-name", + "text" + ), + h_captcha_response: resolveFileToken( + argv["h-captcha-response"] as string | undefined, + "h-captcha-response", + "text" + ), + last_name: resolveFileToken( + argv["last-name"] as string | undefined, + "last-name", + "text" + ), + preferred_locale: resolveFileToken( + argv["preferred-locale"] as string | undefined, + "preferred-locale", + "text" + ), + secondary_billing_email: resolveFileToken( + argv["secondary-billing-email"] as string | undefined, + "secondary-billing-email", + "text" + ), + state: resolveFileToken( + argv["state"] as string | undefined, + "state", + "text" + ), + tax_id_type: resolveFileToken( + argv["tax-id-type"] as string | undefined, + "tax-id-type", + "text" + ), + telephone: resolveFileToken( + argv["telephone"] as string | undefined, + "telephone", + "text" + ), + vat: resolveFileToken( + argv["vat"] as string | undefined, + "vat", + "text" + ), + zipcode: resolveFileToken( + argv["zipcode"] as string | undefined, + "zipcode", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + address: resolveFileToken( + argv["address"] as string | undefined, + "address", + "text" + ), + address2: resolveFileToken( + argv["address2"] as string | undefined, + "address2", + "text" + ), + billing_email: resolveFileToken( + argv["billing-email"] as string | undefined, + "billing-email", + "text" + ), + buying_rate_plan: resolveFileToken( + argv["buying-rate-plan"] as string | undefined, + "buying-rate-plan", + "text" + ), + captcha_challenge_jwt: resolveFileToken( + argv["captcha-challenge-jwt"] as string | undefined, + "captcha-challenge-jwt", + "text" + ), + cf_turnstile_response: resolveFileToken( + argv["cf-turnstile-response"] as string | undefined, + "cf-turnstile-response", + "text" + ), + city: resolveFileToken( + argv["city"] as string | undefined, + "city", + "text" + ), + company: resolveFileToken( + argv["company"] as string | undefined, + "company", + "text" + ), + country: resolveFileToken( + argv["country"] as string | undefined, + "country", + "text" + ), + first_name: resolveFileToken( + argv["first-name"] as string | undefined, + "first-name", + "text" + ), + h_captcha_response: resolveFileToken( + argv["h-captcha-response"] as string | undefined, + "h-captcha-response", + "text" + ), + last_name: resolveFileToken( + argv["last-name"] as string | undefined, + "last-name", + "text" + ), + preferred_locale: resolveFileToken( + argv["preferred-locale"] as string | undefined, + "preferred-locale", + "text" + ), + secondary_billing_email: resolveFileToken( + argv["secondary-billing-email"] as string | undefined, + "secondary-billing-email", + "text" + ), + state: resolveFileToken( + argv["state"] as string | undefined, + "state", + "text" + ), + tax_id_type: resolveFileToken( + argv["tax-id-type"] as string | undefined, + "tax-id-type", + "text" + ), + telephone: resolveFileToken( + argv["telephone"] as string | undefined, + "telephone", + "text" + ), + vat: resolveFileToken(argv["vat"] as string | undefined, "vat", "text"), + zipcode: resolveFileToken( + argv["zipcode"] as string | undefined, + "zipcode", + "text" + ), + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/billing/profiles/update.ts b/packages/cli/src/commands/_generated/billing/profiles/update.ts index 3768c7af70..677004c09e 100644 --- a/packages/cli/src/commands/_generated/billing/profiles/update.ts +++ b/packages/cli/src/commands/_generated/billing/profiles/update.ts @@ -1,356 +1,151 @@ -import operation from "../../_operations/billing/profiles/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/billing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 billing profiles update\n\nUpdates the billing profile for an account." - ) - .option("address", { - type: "string", - description: "Street address line 1.", - }) - .option("address2", { - type: "string", - description: "Street address line 2 (apt, suite, etc.).", - }) - .option("billing-email", { - type: "string", - description: "Primary billing email address.", - }) - .option("buying-rate-plan", { - type: "string", - description: "Rate plan being purchased right after profile setup.", - }) - .option("captcha-challenge-jwt", { - type: "string", - description: "Captcha challenge JWT issued during onboarding.", - }) - .option("cf-turnstile-response", { - type: "string", - description: "Cloudflare Turnstile response.", - }) - .option("city", { - type: "string", - description: "City on the billing profile.", - }) - .option("company", { - type: "string", - description: "Company name on the billing profile.", - }) - .option("country", { - type: "string", - description: "ISO 3166-1 alpha-2 country code.", - }) - .option("first-name", { - type: "string", - description: "First name on the billing profile.", - }) - .option("h-captcha-response", { - type: "string", - description: "hCaptcha response.", - }) - .option("last-name", { - type: "string", - description: "Last name on the billing profile.", - }) - .option("preferred-locale", { - type: "string", - description: "Preferred locale for invoice rendering (BCP 47).", - }) - .option("secondary-billing-email", { - type: "string", - description: "Secondary billing email address for CC on invoices.", - }) - .option("state", { - type: "string", - description: "State or region on the billing profile.", - }) - .option("tax-id-type", { - type: "string", - description: "Type of tax ID provided.", - }) - .option("telephone", { - type: "string", - description: "Contact phone number.", - }) - .option("vat", { type: "string", description: "VAT identifier." }) - .option("zipcode", { type: "string", description: "ZIP or postal code." }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + address: { + kind: "parsed", + brief: "Street address line 1.", + optional: true, + parse: String, + }, + address2: { + kind: "parsed", + brief: "Street address line 2 (apt, suite, etc.).", + optional: true, + parse: String, + }, + "billing-email": { + kind: "parsed", + brief: "Primary billing email address.", + optional: true, + parse: String, + }, + "buying-rate-plan": { + kind: "parsed", + brief: "Rate plan being purchased right after profile setup.", + optional: true, + parse: String, + }, + "captcha-challenge-jwt": { + kind: "parsed", + brief: "Captcha challenge JWT issued during onboarding.", + optional: true, + parse: String, + }, + "cf-turnstile-response": { + kind: "parsed", + brief: "Cloudflare Turnstile response.", + optional: true, + parse: String, + }, + city: { + kind: "parsed", + brief: "City on the billing profile.", + optional: true, + parse: String, + }, + company: { + kind: "parsed", + brief: "Company name on the billing profile.", + optional: true, + parse: String, + }, + country: { + kind: "parsed", + brief: "ISO 3166-1 alpha-2 country code.", + optional: true, + parse: String, + }, + "first-name": { + kind: "parsed", + brief: "First name on the billing profile.", + optional: true, + parse: String, + }, + "h-captcha-response": { + kind: "parsed", + brief: "hCaptcha response.", + optional: true, + parse: String, + }, + "last-name": { + kind: "parsed", + brief: "Last name on the billing profile.", + optional: true, + parse: String, + }, + "preferred-locale": { + kind: "parsed", + brief: "Preferred locale for invoice rendering (BCP 47).", + optional: true, + parse: String, + }, + "secondary-billing-email": { + kind: "parsed", + brief: "Secondary billing email address for CC on invoices.", + optional: true, + parse: String, + }, + state: { + kind: "parsed", + brief: "State or region on the billing profile.", + optional: true, + parse: String, + }, + "tax-id-type": { + kind: "parsed", + brief: "Type of tax ID provided.", + optional: true, + parse: String, + }, + telephone: { + kind: "parsed", + brief: "Contact phone number.", + optional: true, + parse: String, + }, + vat: { + kind: "parsed", + brief: "VAT identifier.", + optional: true, + parse: String, + }, + zipcode: { + kind: "parsed", + brief: "ZIP or postal code.", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Request body for creating or updating a billing profile.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Request body for creating or updating a billing profile.", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update", describe: "Update Billing Profile", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "billing profiles update", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf billing profiles update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/profile`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - address: resolveFileToken( - argv["address"] as string | undefined, - "address", - "text" - ), - address2: resolveFileToken( - argv["address2"] as string | undefined, - "address2", - "text" - ), - billing_email: resolveFileToken( - argv["billing-email"] as string | undefined, - "billing-email", - "text" - ), - buying_rate_plan: resolveFileToken( - argv["buying-rate-plan"] as string | undefined, - "buying-rate-plan", - "text" - ), - captcha_challenge_jwt: resolveFileToken( - argv["captcha-challenge-jwt"] as string | undefined, - "captcha-challenge-jwt", - "text" - ), - cf_turnstile_response: resolveFileToken( - argv["cf-turnstile-response"] as string | undefined, - "cf-turnstile-response", - "text" - ), - city: resolveFileToken( - argv["city"] as string | undefined, - "city", - "text" - ), - company: resolveFileToken( - argv["company"] as string | undefined, - "company", - "text" - ), - country: resolveFileToken( - argv["country"] as string | undefined, - "country", - "text" - ), - first_name: resolveFileToken( - argv["first-name"] as string | undefined, - "first-name", - "text" - ), - h_captcha_response: resolveFileToken( - argv["h-captcha-response"] as string | undefined, - "h-captcha-response", - "text" - ), - last_name: resolveFileToken( - argv["last-name"] as string | undefined, - "last-name", - "text" - ), - preferred_locale: resolveFileToken( - argv["preferred-locale"] as string | undefined, - "preferred-locale", - "text" - ), - secondary_billing_email: resolveFileToken( - argv["secondary-billing-email"] as string | undefined, - "secondary-billing-email", - "text" - ), - state: resolveFileToken( - argv["state"] as string | undefined, - "state", - "text" - ), - tax_id_type: resolveFileToken( - argv["tax-id-type"] as string | undefined, - "tax-id-type", - "text" - ), - telephone: resolveFileToken( - argv["telephone"] as string | undefined, - "telephone", - "text" - ), - vat: resolveFileToken( - argv["vat"] as string | undefined, - "vat", - "text" - ), - zipcode: resolveFileToken( - argv["zipcode"] as string | undefined, - "zipcode", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - address: resolveFileToken( - argv["address"] as string | undefined, - "address", - "text" - ), - address2: resolveFileToken( - argv["address2"] as string | undefined, - "address2", - "text" - ), - billing_email: resolveFileToken( - argv["billing-email"] as string | undefined, - "billing-email", - "text" - ), - buying_rate_plan: resolveFileToken( - argv["buying-rate-plan"] as string | undefined, - "buying-rate-plan", - "text" - ), - captcha_challenge_jwt: resolveFileToken( - argv["captcha-challenge-jwt"] as string | undefined, - "captcha-challenge-jwt", - "text" - ), - cf_turnstile_response: resolveFileToken( - argv["cf-turnstile-response"] as string | undefined, - "cf-turnstile-response", - "text" - ), - city: resolveFileToken( - argv["city"] as string | undefined, - "city", - "text" - ), - company: resolveFileToken( - argv["company"] as string | undefined, - "company", - "text" - ), - country: resolveFileToken( - argv["country"] as string | undefined, - "country", - "text" - ), - first_name: resolveFileToken( - argv["first-name"] as string | undefined, - "first-name", - "text" - ), - h_captcha_response: resolveFileToken( - argv["h-captcha-response"] as string | undefined, - "h-captcha-response", - "text" - ), - last_name: resolveFileToken( - argv["last-name"] as string | undefined, - "last-name", - "text" - ), - preferred_locale: resolveFileToken( - argv["preferred-locale"] as string | undefined, - "preferred-locale", - "text" - ), - secondary_billing_email: resolveFileToken( - argv["secondary-billing-email"] as string | undefined, - "secondary-billing-email", - "text" - ), - state: resolveFileToken( - argv["state"] as string | undefined, - "state", - "text" - ), - tax_id_type: resolveFileToken( - argv["tax-id-type"] as string | undefined, - "tax-id-type", - "text" - ), - telephone: resolveFileToken( - argv["telephone"] as string | undefined, - "telephone", - "text" - ), - vat: resolveFileToken( - argv["vat"] as string | undefined, - "vat", - "text" - ), - zipcode: resolveFileToken( - argv["zipcode"] as string | undefined, - "zipcode", - "text" - ), - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 billing profiles update\n\nUpdates the billing profile for an account.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/rate-plans/get.handler.ts b/packages/cli/src/commands/_generated/billing/rate-plans/get.handler.ts new file mode 100644 index 0000000000..38c0c359bf --- /dev/null +++ b/packages/cli/src/commands/_generated/billing/rate-plans/get.handler.ts @@ -0,0 +1,38 @@ +import operation from "../../_operations/billing/rate-plans/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { createCommandClient } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "billing rate-plans get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf billing rate-plans get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/billing/rate_plans/${argv["public-key"] == null ? "" : encodeURIComponent(String(argv["public-key"]))}`, + pathParams: { "public-key": String(argv["public-key"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + + const result = await withProgress(`Loading`, async () => + client.send(operation, { public_key: argv["public-key"] }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/billing/rate-plans/get.ts b/packages/cli/src/commands/_generated/billing/rate-plans/get.ts index cb1f44e4d7..cffa7e5760 100644 --- a/packages/cli/src/commands/_generated/billing/rate-plans/get.ts +++ b/packages/cli/src/commands/_generated/billing/rate-plans/get.ts @@ -1,68 +1,37 @@ -import operation from "../../_operations/billing/rate-plans/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/billing.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 billing rate-plans get \n\nGets a rate plan's details by its public key (e.g., 'teams_free', 'cf_pro_20_20'). This is a public catalog endpoint, so authentication is not enforced and credentials are accepted but not required." - ) - .positional("public-key", { - type: "string", - description: "The public key identifier for the rate plan.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "public-key", + brief: "The public key identifier for the rate plan.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get Rate Plan by Public Key", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "billing rate-plans get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf billing rate-plans get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/billing/rate_plans/${argv["public-key"] == null ? "" : encodeURIComponent(String(argv["public-key"]))}`, - pathParams: { "public-key": String(argv["public-key"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - - const result = await withProgress(`Loading`, async () => - client.send(operation, { public_key: argv["public-key"] }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 billing rate-plans get \n\nGets a rate plan's details by its public key (e.g., 'teams_free', 'cf_pro_20_20'). This is a public catalog endpoint, so authentication is not enforced and credentials are accepted but not required.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/rate-plans/index.ts b/packages/cli/src/commands/_generated/billing/rate-plans/index.ts index fc1576ceee..651d07a72b 100644 --- a/packages/cli/src/commands/_generated/billing/rate-plans/index.ts +++ b/packages/cli/src/commands/_generated/billing/rate-plans/index.ts @@ -1,20 +1,17 @@ import $get from "./get.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * rate-plans command group * @generated from apis/overlays/billing.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "rate-plans", describe: "Operations for rate-plans", - builder: (yargs) => { - return yargs.command($get).demandCommand(1, "Please specify a subcommand"); + routes: { + get: $get, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/spend-policies/activity/index.ts b/packages/cli/src/commands/_generated/billing/spend-policies/activity/index.ts index d4e817b715..85d0eab49c 100644 --- a/packages/cli/src/commands/_generated/billing/spend-policies/activity/index.ts +++ b/packages/cli/src/commands/_generated/billing/spend-policies/activity/index.ts @@ -1,20 +1,17 @@ import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * activity command group * @generated from apis/overlays/billing.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "activity", describe: "Operations for spend-policies.activity", - builder: (yargs) => { - return yargs.command($list).demandCommand(1, "Please specify a subcommand"); + routes: { + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/spend-policies/activity/list.handler.ts b/packages/cli/src/commands/_generated/billing/spend-policies/activity/list.handler.ts new file mode 100644 index 0000000000..bbbe647ef3 --- /dev/null +++ b/packages/cli/src/commands/_generated/billing/spend-policies/activity/list.handler.ts @@ -0,0 +1,52 @@ +import operation from "../../../_operations/billing/spend-policies/activity/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "billing spend-policies activity list", + classification: { + safeFlags: ["period", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + limit: argv["limit"], + period: argv["period"], + cursor: argv["cursor"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf billing spend-policies activity list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/spend-policies/activity`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/billing/spend-policies/activity/list.ts b/packages/cli/src/commands/_generated/billing/spend-policies/activity/list.ts index 4febe16d62..153db7b004 100644 --- a/packages/cli/src/commands/_generated/billing/spend-policies/activity/list.ts +++ b/packages/cli/src/commands/_generated/billing/spend-policies/activity/list.ts @@ -1,93 +1,52 @@ -import operation from "../../../_operations/billing/spend-policies/activity/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/billing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 billing spend-policies activity list\n\nReturns configuration history from immutable policy revisions for the account, including deleted policies. Entries contain before/after values and verified actor attribution. Pages use descending revision IDs, not event or commit order; refresh the first page for new entries. This cursor is not an incremental consumer checkpoint. Defaults to `period=current_billing_cycle`: each revision's timestamp must be within its product's current subscription cycle (inclusive start, exclusive end). Each product's cycle is resolved independently from canonical aggregates, including for disabled or deleted policies. Set `period=all` for history across cycles. Filtering happens before pagination. No current cycles returns an empty page; unavailable or disabled cycle resolution returns `503` with code `1013`. Cursors pin resolved cycle bounds across pages and must be used with the same period selection. Cursors obtained before this filter was introduced must be refreshed." - ) - .option("limit", { - type: "number", - description: +const parameters = { + flags: { + limit: { + kind: "parsed", + brief: "Maximum number of audit entries to return. Defaults to 50. Values above 100 are capped at 100 rather than rejected.", - }) - .option("period", { - type: "string", - description: + optional: true, + parse: Number, + }, + period: { + kind: "enum", + brief: "Select current subscription billing-cycle history or history across all cycles.", - choices: ["current_billing_cycle", "all"], - }) - .option("cursor", { - type: "string", - description: + values: ["current_billing_cycle", "all"], + optional: true, + }, + cursor: { + kind: "parsed", + brief: "Opaque token from the preceding response's result_info.cursor. Pass it unchanged to retrieve older entries.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Spend Policy Activity", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "billing spend-policies activity list", - classification: { - safeFlags: ["period", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - limit: argv["limit"], - period: argv["period"], - cursor: argv["cursor"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf billing spend-policies activity list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/spend-policies/activity`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 billing spend-policies activity list\n\nReturns configuration history from immutable policy revisions for the account, including deleted policies. Entries contain before/after values and verified actor attribution. Pages use descending revision IDs, not event or commit order; refresh the first page for new entries. This cursor is not an incremental consumer checkpoint. Defaults to `period=current_billing_cycle`: each revision's timestamp must be within its product's current subscription cycle (inclusive start, exclusive end). Each product's cycle is resolved independently from canonical aggregates, including for disabled or deleted policies. Set `period=all` for history across cycles. Filtering happens before pagination. No current cycles returns an empty page; unavailable or disabled cycle resolution returns `503` with code `1013`. Cursors pin resolved cycle bounds across pages and must be used with the same period selection. Cursors obtained before this filter was introduced must be refreshed.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/spend-policies/audit/index.ts b/packages/cli/src/commands/_generated/billing/spend-policies/audit/index.ts index 336a64529f..2e6530c0aa 100644 --- a/packages/cli/src/commands/_generated/billing/spend-policies/audit/index.ts +++ b/packages/cli/src/commands/_generated/billing/spend-policies/audit/index.ts @@ -1,20 +1,17 @@ import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * audit command group * @generated from apis/overlays/billing.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "audit", describe: "Operations for spend-policies.audit", - builder: (yargs) => { - return yargs.command($list).demandCommand(1, "Please specify a subcommand"); + routes: { + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/spend-policies/audit/list.handler.ts b/packages/cli/src/commands/_generated/billing/spend-policies/audit/list.handler.ts new file mode 100644 index 0000000000..1a6686e606 --- /dev/null +++ b/packages/cli/src/commands/_generated/billing/spend-policies/audit/list.handler.ts @@ -0,0 +1,55 @@ +import operation from "../../../_operations/billing/spend-policies/audit/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "billing spend-policies audit list", + classification: { + safeFlags: ["period", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + limit: argv["limit"], + period: argv["period"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf billing spend-policies audit list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/spend-policies/${argv["policy-id"] == null ? "" : encodeURIComponent(String(argv["policy-id"]))}/audit`, + pathParams: { "policy-id": String(argv["policy-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + policy_id: argv["policy-id"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/billing/spend-policies/audit/list.ts b/packages/cli/src/commands/_generated/billing/spend-policies/audit/list.ts index bf73b218d4..80865ac8e7 100644 --- a/packages/cli/src/commands/_generated/billing/spend-policies/audit/list.ts +++ b/packages/cli/src/commands/_generated/billing/spend-policies/audit/list.ts @@ -1,96 +1,50 @@ -import operation from "../../../_operations/billing/spend-policies/audit/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/billing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 billing spend-policies audit list\n\nReturns the policy's evaluation history, newest first. At most one threshold-crossing entry (`limit_reached`) is recorded per policy version and billing period, so a policy update can record a new entry without any change in balance. Disabled policies still return their history; deleted policies return `404`. There is no pagination: use `limit` to set how many entries come back. Defaults to `period=current_billing_cycle`, resolved from the product's canonical aggregates, not calendar months. Crossings match their recorded billing-period bounds, even if recorded late. Set `period=all` for history across cycles. Filtering happens before LIMIT. No current cycle returns an empty array; unavailable or disabled cycle resolution returns `503` with code `1013`, never an empty success." - ) - .option("policy-id", { - type: "string", - description: "Identifies the spend policy.", - demandOption: true, - }) - .option("limit", { - type: "number", - description: +const parameters = { + flags: { + "policy-id": { + kind: "parsed", + brief: "Identifies the spend policy.", + parse: String, + }, + limit: { + kind: "parsed", + brief: "Maximum number of audit entries to return. Defaults to 50. Values above 100 are capped at 100 rather than rejected.", - }) - .option("period", { - type: "string", - description: + optional: true, + parse: Number, + }, + period: { + kind: "enum", + brief: "Select current subscription billing-cycle history or history across all cycles.", - choices: ["current_billing_cycle", "all"], - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + values: ["current_billing_cycle", "all"], + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Spend Policy Audit Entries", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "billing spend-policies audit list", - classification: { - safeFlags: ["period", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - limit: argv["limit"], - period: argv["period"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf billing spend-policies audit list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/spend-policies/${argv["policy-id"] == null ? "" : encodeURIComponent(String(argv["policy-id"]))}/audit`, - pathParams: { "policy-id": String(argv["policy-id"] ?? "") }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - policy_id: argv["policy-id"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 billing spend-policies audit list\n\nReturns the policy's evaluation history, newest first. At most one threshold-crossing entry (`limit_reached`) is recorded per policy version and billing period, so a policy update can record a new entry without any change in balance. Disabled policies still return their history; deleted policies return `404`. There is no pagination: use `limit` to set how many entries come back. Defaults to `period=current_billing_cycle`, resolved from the product's canonical aggregates, not calendar months. Crossings match their recorded billing-period bounds, even if recorded late. Set `period=all` for history across cycles. Filtering happens before LIMIT. No current cycle returns an empty array; unavailable or disabled cycle resolution returns `503` with code `1013`, never an empty success.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/spend-policies/create.handler.ts b/packages/cli/src/commands/_generated/billing/spend-policies/create.handler.ts new file mode 100644 index 0000000000..ca45934685 --- /dev/null +++ b/packages/cli/src/commands/_generated/billing/spend-policies/create.handler.ts @@ -0,0 +1,135 @@ +import operation from "../../_operations/billing/spend-policies/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { + promptForRequiredEnumField, + promptForRequiredField, +} from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "billing spend-policies create", + classification: { + safeFlags: ["action", "enabled", "product-id", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["action"] === undefined) { + argv["action"] = await promptForRequiredEnumField( + "action", + "The action taken when the threshold is reached. \`notification\` sends an email to \`notification_email\`. \`usage_block\` blocks further usage of the product until the end of the billing period. Raising the threshold above the current balance, disabling the policy, or deleting it lifts the block early.", + ["notification", "usage_block"] as const + ); + } + if (argv["enabled"] === undefined) { + throw new Error( + "--enabled is required (or pass --body with this field set)." + ); + } + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField( + "name", + "Display name of the policy. After surrounding whitespace is trimmed, it must be 1 to 200 bytes long. The value is stored as sent, untrimmed." + ); + } + if (argv["product-id"] === undefined) { + argv["product-id"] = await promptForRequiredEnumField( + "product-id", + "The product the policy applies to: \`workers\` or \`durable_objects\`. Each product's balance and policies are separate. Both products support \`notification\` and \`usage_block\` policies on create and update.", + ["workers", "durable_objects"] as const + ); + } + if (argv["threshold-cents"] === undefined) { + throw new Error( + "--threshold-cents is required (or pass --body with this field set)." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf billing spend-policies create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/spend-policies`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + action: argv["action"], + enabled: argv["enabled"], + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + notification_email: resolveFileToken( + argv["notification-email"] as string | undefined, + "notification-email", + "text" + ), + product_id: argv["product-id"], + threshold_cents: argv["threshold-cents"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + action: argv["action"], + enabled: argv["enabled"], + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + notification_email: resolveFileToken( + argv["notification-email"] as string | undefined, + "notification-email", + "text" + ), + product_id: argv["product-id"], + threshold_cents: argv["threshold-cents"], + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/billing/spend-policies/create.ts b/packages/cli/src/commands/_generated/billing/spend-policies/create.ts index 69aa07489c..8d903cbe95 100644 --- a/packages/cli/src/commands/_generated/billing/spend-policies/create.ts +++ b/packages/cli/src/commands/_generated/billing/spend-policies/create.ts @@ -1,200 +1,83 @@ -import operation from "../../_operations/billing/spend-policies/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/billing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { - promptForRequiredEnumField, - promptForRequiredField, -} from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 billing spend-policies create\n\nCreates a spend policy. Each account can have only one enabled `usage_block` policy per product. A second one returns `409`. There is no limit on `notification` policies." - ) - .option("action", { - type: "string", - description: +const parameters = { + flags: { + action: { + kind: "parsed", + brief: "The action taken when the threshold is reached. `notification` sends an email to `notification_email`. `usage_block` blocks further usage of the product until the end of the billing period. Raising the threshold above the current balance, disabling the policy, or deleting it lifts the block early.", + optional: true, choices: ["notification", "usage_block"], - }) - .coerce("action", (value) => resolveFileToken(value, "action", "text")) - .option("enabled", { - type: "boolean", - description: "Whether the policy is evaluated.", - }) - .option("name", { - type: "string", - description: + parse: String, + coerce: (value: string) => resolveFileToken(value, "action", "text"), + }, + enabled: { + kind: "boolean", + brief: "Whether the policy is evaluated.", + optional: true, + }, + name: { + kind: "parsed", + brief: "Display name of the policy. After surrounding whitespace is trimmed, it must be 1 to 200 bytes long. The value is stored as sent, untrimmed.", - }) - .option("notification-email", { - type: "string", - description: + optional: true, + parse: String, + }, + "notification-email": { + kind: "parsed", + brief: "Email address that receives notifications. Required when `action` is `notification`. When set, it must be a bare address (`user@example.com`); display-name forms such as `Name ` are rejected.", - }) - .option("product-id", { - type: "string", - description: + optional: true, + parse: String, + }, + "product-id": { + kind: "parsed", + brief: "The product the policy applies to: `workers` or `durable_objects`. Each product's balance and policies are separate. Both products support `notification` and `usage_block` policies on create and update.", + optional: true, choices: ["workers", "durable_objects"], - }) - .coerce("product-id", (value) => - resolveFileToken(value, "product-id", "text") - ) - .option("threshold-cents", { - type: "number", - description: + parse: String, + coerce: (value: string) => resolveFileToken(value, "product-id", "text"), + }, + "threshold-cents": { + kind: "parsed", + brief: "The spend threshold for the current billing period, in US cents. Must be greater than zero.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: + }, + body: { + kind: "parsed", + brief: "A spend policy as sent on create and on full replacement. Unknown fields and trailing JSON are rejected. Only the first 1 MiB of the body is read.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Create Spend Policy", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "billing spend-policies create", - classification: { - safeFlags: ["action", "enabled", "product-id", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["action"] === undefined) { - argv["action"] = await promptForRequiredEnumField( - "action", - "The action taken when the threshold is reached. \`notification\` sends an email to \`notification_email\`. \`usage_block\` blocks further usage of the product until the end of the billing period. Raising the threshold above the current balance, disabling the policy, or deleting it lifts the block early.", - ["notification", "usage_block"] as const - ); - } - if (argv["enabled"] === undefined) { - throw new Error( - "--enabled is required (or pass --body with this field set)." - ); - } - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "Display name of the policy. After surrounding whitespace is trimmed, it must be 1 to 200 bytes long. The value is stored as sent, untrimmed." - ); - } - if (argv["product-id"] === undefined) { - argv["product-id"] = await promptForRequiredEnumField( - "product-id", - "The product the policy applies to: \`workers\` or \`durable_objects\`. Each product's balance and policies are separate. Both products support \`notification\` and \`usage_block\` policies on create and update.", - ["workers", "durable_objects"] as const - ); - } - if (argv["threshold-cents"] === undefined) { - throw new Error( - "--threshold-cents is required (or pass --body with this field set)." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf billing spend-policies create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/spend-policies`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - action: argv["action"], - enabled: argv["enabled"], - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - notification_email: resolveFileToken( - argv["notification-email"] as string | undefined, - "notification-email", - "text" - ), - product_id: argv["product-id"], - threshold_cents: argv["threshold-cents"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - action: argv["action"], - enabled: argv["enabled"], - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - notification_email: resolveFileToken( - argv["notification-email"] as string | undefined, - "notification-email", - "text" - ), - product_id: argv["product-id"], - threshold_cents: argv["threshold-cents"], - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 billing spend-policies create\n\nCreates a spend policy. Each account can have only one enabled `usage_block` policy per product. A second one returns `409`. There is no limit on `notification` policies.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/spend-policies/delete.handler.ts b/packages/cli/src/commands/_generated/billing/spend-policies/delete.handler.ts new file mode 100644 index 0000000000..dd4ee06a10 --- /dev/null +++ b/packages/cli/src/commands/_generated/billing/spend-policies/delete.handler.ts @@ -0,0 +1,60 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "billing spend-policies delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const headers: Record = {}; + if (argv["if-match"] !== undefined) + headers["If-Match"] = String(argv["if-match"]); + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf billing spend-policies delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/spend-policies/${argv["policy-id"] == null ? "" : encodeURIComponent(String(argv["policy-id"]))}`, + pathParams: { "policy-id": String(argv["policy-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + requestApi( + client, + "DELETE", + `/accounts/${accountId}/billing/spend-policies/${encodeURIComponent(String(argv["policy-id"]))}`, + { headers: Object.keys(headers).length > 0 ? headers : undefined } + ) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/billing/spend-policies/delete.ts b/packages/cli/src/commands/_generated/billing/spend-policies/delete.ts index d6738eacb0..8127848ee6 100644 --- a/packages/cli/src/commands/_generated/billing/spend-policies/delete.ts +++ b/packages/cli/src/commands/_generated/billing/spend-policies/delete.ts @@ -1,102 +1,49 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/billing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 billing spend-policies delete \n\nSoft-deletes the spend policy. The policy is disabled and no longer appears in list, get or audit responses. The `If-Match` header must equal the policy's current `version`." - ) - .positional("policy-id", { - type: "string", - description: "Identifies the spend policy.", - demandOption: true, - }) - .option("if-match", { - type: "string", - description: +const parameters = { + flags: { + "if-match": { + kind: "parsed", + brief: 'The policy `version` the change is based on, as returned in `ETag`. Quoted (`"3"`) and bare (`3`) values are both accepted. Weak ETags (`W/"3"`) and `*` are not.', - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "policy-id", + brief: "Identifies the spend policy.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete Spend Policy", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "billing spend-policies delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const headers: Record = {}; - if (argv["if-match"] !== undefined) - headers["If-Match"] = String(argv["if-match"]); - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf billing spend-policies delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/spend-policies/${argv["policy-id"] == null ? "" : encodeURIComponent(String(argv["policy-id"]))}`, - pathParams: { "policy-id": String(argv["policy-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - requestApi( - client, - "DELETE", - `/accounts/${accountId}/billing/spend-policies/${encodeURIComponent(String(argv["policy-id"]))}`, - { headers: Object.keys(headers).length > 0 ? headers : undefined } - ) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 billing spend-policies delete \n\nSoft-deletes the spend policy. The policy is disabled and no longer appears in list, get or audit responses. The `If-Match` header must equal the policy's current `version`.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/spend-policies/get.handler.ts b/packages/cli/src/commands/_generated/billing/spend-policies/get.handler.ts new file mode 100644 index 0000000000..0d2e1a2904 --- /dev/null +++ b/packages/cli/src/commands/_generated/billing/spend-policies/get.handler.ts @@ -0,0 +1,49 @@ +import operation from "../../_operations/billing/spend-policies/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "billing spend-policies get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf billing spend-policies get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/spend-policies/${argv["policy-id"] == null ? "" : encodeURIComponent(String(argv["policy-id"]))}`, + pathParams: { "policy-id": String(argv["policy-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + policy_id: argv["policy-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/billing/spend-policies/get.ts b/packages/cli/src/commands/_generated/billing/spend-policies/get.ts index c4061df78f..b2aa2e061f 100644 --- a/packages/cli/src/commands/_generated/billing/spend-policies/get.ts +++ b/packages/cli/src/commands/_generated/billing/spend-policies/get.ts @@ -1,79 +1,37 @@ -import operation from "../../_operations/billing/spend-policies/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/billing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 billing spend-policies get \n\nReturns one spend policy. The `ETag` response header holds the current `version`; send it as `If-Match` on a later update or delete." - ) - .positional("policy-id", { - type: "string", - description: "Identifies the spend policy.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "policy-id", + brief: "Identifies the spend policy.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get Spend Policy", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "billing spend-policies get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf billing spend-policies get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/spend-policies/${argv["policy-id"] == null ? "" : encodeURIComponent(String(argv["policy-id"]))}`, - pathParams: { "policy-id": String(argv["policy-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - policy_id: argv["policy-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 billing spend-policies get \n\nReturns one spend policy. The `ETag` response header holds the current `version`; send it as `If-Match` on a later update or delete.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/spend-policies/index.ts b/packages/cli/src/commands/_generated/billing/spend-policies/index.ts index 1a705c387a..11a5c1405c 100644 --- a/packages/cli/src/commands/_generated/billing/spend-policies/index.ts +++ b/packages/cli/src/commands/_generated/billing/spend-policies/index.ts @@ -5,30 +5,25 @@ import $delete from "./delete.js"; import $get from "./get.js"; import $list from "./list.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * spend-policies command group * @generated from apis/overlays/billing.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "spend-policies", describe: "Operations for spend-policies", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .command($list) - .command($update) - .command($activity) - .command($audit) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, + list: $list, + update: $update, + activity: $activity, + audit: $audit, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/spend-policies/list.handler.ts b/packages/cli/src/commands/_generated/billing/spend-policies/list.handler.ts new file mode 100644 index 0000000000..afa557d6b2 --- /dev/null +++ b/packages/cli/src/commands/_generated/billing/spend-policies/list.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/billing/spend-policies/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "billing spend-policies list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf billing spend-policies list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/spend-policies`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/billing/spend-policies/list.ts b/packages/cli/src/commands/_generated/billing/spend-policies/list.ts index 7349919e53..b4c2ed624b 100644 --- a/packages/cli/src/commands/_generated/billing/spend-policies/list.ts +++ b/packages/cli/src/commands/_generated/billing/spend-policies/list.ts @@ -1,71 +1,31 @@ -import operation from "../../_operations/billing/spend-policies/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/billing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 billing spend-policies list\n\nReturns every spend policy on the account that has not been deleted, including disabled ones. Results are sorted by `name`, then `id`. There is no pagination." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List Spend Policies", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "billing spend-policies list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf billing spend-policies list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/spend-policies`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 billing spend-policies list\n\nReturns every spend policy on the account that has not been deleted, including disabled ones. Results are sorted by `name`, then `id`. There is no pagination.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/spend-policies/update.handler.ts b/packages/cli/src/commands/_generated/billing/spend-policies/update.handler.ts new file mode 100644 index 0000000000..63e1bbfd87 --- /dev/null +++ b/packages/cli/src/commands/_generated/billing/spend-policies/update.handler.ts @@ -0,0 +1,163 @@ +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, setNestedValue } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { + promptForRequiredEnumField, + promptForRequiredField, +} from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "billing spend-policies update", + classification: { + safeFlags: ["action", "enabled", "product-id", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const headers: Record = {}; + if (argv["if-match"] !== undefined) + headers["If-Match"] = String(argv["if-match"]); + const resolveRequiredFields = async (): Promise => { + if (argv["action"] === undefined) { + argv["action"] = await promptForRequiredEnumField( + "action", + "The action taken when the threshold is reached. \`notification\` sends an email to \`notification_email\`. \`usage_block\` blocks further usage of the product until the end of the billing period. Raising the threshold above the current balance, disabling the policy, or deleting it lifts the block early.", + ["notification", "usage_block"] as const + ); + } + if (argv["enabled"] === undefined) { + throw new Error( + "--enabled is required (or pass --body with this field set)." + ); + } + if (argv["name"] === undefined) { + argv["name"] = await promptForRequiredField( + "name", + "Display name of the policy. After surrounding whitespace is trimmed, it must be 1 to 200 bytes long. The value is stored as sent, untrimmed." + ); + } + if (argv["product-id"] === undefined) { + argv["product-id"] = await promptForRequiredEnumField( + "product-id", + "The product the policy applies to: \`workers\` or \`durable_objects\`. Each product's balance and policies are separate. Both products support \`notification\` and \`usage_block\` policies on create and update.", + ["workers", "durable_objects"] as const + ); + } + if (argv["threshold-cents"] === undefined) { + throw new Error( + "--threshold-cents is required (or pass --body with this field set)." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf billing spend-policies update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/spend-policies/${argv["policy-id"] == null ? "" : encodeURIComponent(String(argv["policy-id"]))}`, + pathParams: { "policy-id": String(argv["policy-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + action: argv["action"], + enabled: argv["enabled"], + name: resolveFileToken( + argv["name"] as string | undefined, + "name", + "text" + ), + notification_email: resolveFileToken( + argv["notification-email"] as string | undefined, + "notification-email", + "text" + ), + product_id: argv["product-id"], + threshold_cents: argv["threshold-cents"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + requestApi( + client, + "PUT", + `/accounts/${accountId}/billing/spend-policies/${encodeURIComponent(String(argv["policy-id"]))}`, + { + body: bodyData, + headers: Object.keys(headers).length > 0 ? headers : undefined, + } + ) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData: Record = {}; + if (argv["action"] !== undefined) + setNestedValue(bodyData, ["action"], argv["action"]); + if (argv["enabled"] !== undefined) + setNestedValue(bodyData, ["enabled"], argv["enabled"]); + if (argv["name"] !== undefined) + setNestedValue( + bodyData, + ["name"], + resolveFileToken(argv["name"] as string | undefined, "name", "text") + ); + if (argv["notification-email"] !== undefined) + setNestedValue( + bodyData, + ["notification_email"], + resolveFileToken( + argv["notification-email"] as string | undefined, + "notification-email", + "text" + ) + ); + if (argv["product-id"] !== undefined) + setNestedValue(bodyData, ["product_id"], argv["product-id"]); + if (argv["threshold-cents"] !== undefined) + setNestedValue(bodyData, ["threshold_cents"], argv["threshold-cents"]); + const result = await withProgress(`Updating`, async () => + requestApi( + client, + "PUT", + `/accounts/${accountId}/billing/spend-policies/${encodeURIComponent(String(argv["policy-id"]))}`, + { + body: bodyData, + headers: Object.keys(headers).length > 0 ? headers : undefined, + } + ) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/billing/spend-policies/update.ts b/packages/cli/src/commands/_generated/billing/spend-policies/update.ts index 5e667feb23..a7da4488df 100644 --- a/packages/cli/src/commands/_generated/billing/spend-policies/update.ts +++ b/packages/cli/src/commands/_generated/billing/spend-policies/update.ts @@ -1,243 +1,95 @@ -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/billing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, setNestedValue } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { - promptForRequiredEnumField, - promptForRequiredField, -} from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 billing spend-policies update \n\nReplaces the whole spend policy. Every field is required, as on create; there are no partial updates and `PATCH` is not supported. The `If-Match` header must equal the policy's current `version`. On success, `version` goes up by one and the new value is returned in `ETag`." - ) - .positional("policy-id", { - type: "string", - description: "Identifies the spend policy.", - demandOption: true, - }) - .option("if-match", { - type: "string", - description: +const parameters = { + flags: { + "if-match": { + kind: "parsed", + brief: 'The policy `version` the change is based on, as returned in `ETag`. Quoted (`"3"`) and bare (`3`) values are both accepted. Weak ETags (`W/"3"`) and `*` are not.', - demandOption: true, - }) - .option("action", { - type: "string", - description: + parse: String, + }, + action: { + kind: "parsed", + brief: "The action taken when the threshold is reached. `notification` sends an email to `notification_email`. `usage_block` blocks further usage of the product until the end of the billing period. Raising the threshold above the current balance, disabling the policy, or deleting it lifts the block early.", + optional: true, choices: ["notification", "usage_block"], - }) - .coerce("action", (value) => resolveFileToken(value, "action", "text")) - .option("enabled", { - type: "boolean", - description: "Whether the policy is evaluated.", - }) - .option("name", { - type: "string", - description: + parse: String, + coerce: (value: string) => resolveFileToken(value, "action", "text"), + }, + enabled: { + kind: "boolean", + brief: "Whether the policy is evaluated.", + optional: true, + }, + name: { + kind: "parsed", + brief: "Display name of the policy. After surrounding whitespace is trimmed, it must be 1 to 200 bytes long. The value is stored as sent, untrimmed.", - }) - .option("notification-email", { - type: "string", - description: + optional: true, + parse: String, + }, + "notification-email": { + kind: "parsed", + brief: "Email address that receives notifications. Required when `action` is `notification`. When set, it must be a bare address (`user@example.com`); display-name forms such as `Name ` are rejected.", - }) - .option("product-id", { - type: "string", - description: + optional: true, + parse: String, + }, + "product-id": { + kind: "parsed", + brief: "The product the policy applies to: `workers` or `durable_objects`. Each product's balance and policies are separate. Both products support `notification` and `usage_block` policies on create and update.", + optional: true, choices: ["workers", "durable_objects"], - }) - .coerce("product-id", (value) => - resolveFileToken(value, "product-id", "text") - ) - .option("threshold-cents", { - type: "number", - description: + parse: String, + coerce: (value: string) => resolveFileToken(value, "product-id", "text"), + }, + "threshold-cents": { + kind: "parsed", + brief: "The spend threshold for the current billing period, in US cents. Must be greater than zero.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: + }, + body: { + kind: "parsed", + brief: "A spend policy as sent on create and on full replacement. Unknown fields and trailing JSON are rejected. Only the first 1 MiB of the body is read.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + optional: true, + parse: String, + }, + }, + operands: [ + { + placeholder: "policy-id", + brief: "Identifies the spend policy.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update ", describe: "Update Spend Policy", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "billing spend-policies update", - classification: { - safeFlags: ["action", "enabled", "product-id", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const headers: Record = {}; - if (argv["if-match"] !== undefined) - headers["If-Match"] = String(argv["if-match"]); - const resolveRequiredFields = async (): Promise => { - if (argv["action"] === undefined) { - argv["action"] = await promptForRequiredEnumField( - "action", - "The action taken when the threshold is reached. \`notification\` sends an email to \`notification_email\`. \`usage_block\` blocks further usage of the product until the end of the billing period. Raising the threshold above the current balance, disabling the policy, or deleting it lifts the block early.", - ["notification", "usage_block"] as const - ); - } - if (argv["enabled"] === undefined) { - throw new Error( - "--enabled is required (or pass --body with this field set)." - ); - } - if (argv["name"] === undefined) { - argv["name"] = await promptForRequiredField( - "name", - "Display name of the policy. After surrounding whitespace is trimmed, it must be 1 to 200 bytes long. The value is stored as sent, untrimmed." - ); - } - if (argv["product-id"] === undefined) { - argv["product-id"] = await promptForRequiredEnumField( - "product-id", - "The product the policy applies to: \`workers\` or \`durable_objects\`. Each product's balance and policies are separate. Both products support \`notification\` and \`usage_block\` policies on create and update.", - ["workers", "durable_objects"] as const - ); - } - if (argv["threshold-cents"] === undefined) { - throw new Error( - "--threshold-cents is required (or pass --body with this field set)." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf billing spend-policies update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billing/spend-policies/${argv["policy-id"] == null ? "" : encodeURIComponent(String(argv["policy-id"]))}`, - pathParams: { "policy-id": String(argv["policy-id"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - action: argv["action"], - enabled: argv["enabled"], - name: resolveFileToken( - argv["name"] as string | undefined, - "name", - "text" - ), - notification_email: resolveFileToken( - argv["notification-email"] as string | undefined, - "notification-email", - "text" - ), - product_id: argv["product-id"], - threshold_cents: argv["threshold-cents"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - requestApi( - client, - "PUT", - `/accounts/${accountId}/billing/spend-policies/${encodeURIComponent(String(argv["policy-id"]))}`, - { - body: bodyData, - headers: Object.keys(headers).length > 0 ? headers : undefined, - } - ) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData: Record = {}; - if (argv["action"] !== undefined) - setNestedValue(bodyData, ["action"], argv["action"]); - if (argv["enabled"] !== undefined) - setNestedValue(bodyData, ["enabled"], argv["enabled"]); - if (argv["name"] !== undefined) - setNestedValue( - bodyData, - ["name"], - resolveFileToken(argv["name"] as string | undefined, "name", "text") - ); - if (argv["notification-email"] !== undefined) - setNestedValue( - bodyData, - ["notification_email"], - resolveFileToken( - argv["notification-email"] as string | undefined, - "notification-email", - "text" - ) - ); - if (argv["product-id"] !== undefined) - setNestedValue(bodyData, ["product_id"], argv["product-id"]); - if (argv["threshold-cents"] !== undefined) - setNestedValue( - bodyData, - ["threshold_cents"], - argv["threshold-cents"] - ); - const result = await withProgress(`Updating`, async () => - requestApi( - client, - "PUT", - `/accounts/${accountId}/billing/spend-policies/${encodeURIComponent(String(argv["policy-id"]))}`, - { - body: bodyData, - headers: Object.keys(headers).length > 0 ? headers : undefined, - } - ) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 billing spend-policies update \n\nReplaces the whole spend policy. Every field is required, as on create; there are no partial updates and `PATCH` is not supported. The `If-Match` header must equal the policy's current `version`. On success, `version` goes up by one and the new value is returned in `ETag`.", + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/usage/get-account-billable-metrics.handler.ts b/packages/cli/src/commands/_generated/billing/usage/get-account-billable-metrics.handler.ts new file mode 100644 index 0000000000..f0c81e0228 --- /dev/null +++ b/packages/cli/src/commands/_generated/billing/usage/get-account-billable-metrics.handler.ts @@ -0,0 +1,51 @@ +import operation from "../../_operations/billing/usage/get-account-billable-metrics.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get-account-billable-metrics.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "billing usage get-account-billable-metrics", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + from: argv["from"], + to: argv["to"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf billing usage get-account-billable-metrics", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billable/usage/billable-metrics`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/billing/usage/get-account-billable-metrics.ts b/packages/cli/src/commands/_generated/billing/usage/get-account-billable-metrics.ts index 9f4c243186..9ddb491159 100644 --- a/packages/cli/src/commands/_generated/billing/usage/get-account-billable-metrics.ts +++ b/packages/cli/src/commands/_generated/billing/usage/get-account-billable-metrics.ts @@ -1,86 +1,45 @@ -import operation from "../../_operations/billing/usage/get-account-billable-metrics.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get-account-billable-metrics command * @generated from apis/overlays/billing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 billing usage get-account-billable-metrics\n\nLists billable metrics available to the account through contracts and subscriptions that overlap the requested period. Results are deduplicated and ordered. If no qualifying contract exists, the result is an empty array. When `from` and `to` are omitted, the period defaults to the start of the current month through today. The maximum date range is 31 days." - ) - .option("from", { - type: "string", - description: +const parameters = { + flags: { + from: { + kind: "parsed", + brief: "Start date for the usage query (ISO 8601). Required if `to` is set. When omitted along with `to`, defaults to the start of the current month. Filters by charge period (when consumption happened), not billing period. The maximum date range is 31 days.", - }) - .option("to", { - type: "string", - description: + optional: true, + parse: String, + }, + to: { + kind: "parsed", + brief: "End date for the usage query (ISO 8601). Required if `from` is set. When omitted along with `from`, defaults to today. Filters by charge period (when consumption happened), not billing period. The maximum date range is 31 days.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get-account-billable-metrics", describe: "List Account Billable Metrics (Version 2, Alpha, Restricted)", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "billing usage get-account-billable-metrics", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - from: argv["from"], - to: argv["to"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf billing usage get-account-billable-metrics", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billable/usage/billable-metrics`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 billing usage get-account-billable-metrics\n\nLists billable metrics available to the account through contracts and subscriptions that overlap the requested period. Results are deduplicated and ordered. If no qualifying contract exists, the result is an empty array. When `from` and `to` are omitted, the period defaults to the start of the current month through today. The maximum date range is 31 days.", + ...parameters, + loader: () => import("./get-account-billable-metrics.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/usage/get-account-usage-v2.handler.ts b/packages/cli/src/commands/_generated/billing/usage/get-account-usage-v2.handler.ts new file mode 100644 index 0000000000..a21011797b --- /dev/null +++ b/packages/cli/src/commands/_generated/billing/usage/get-account-usage-v2.handler.ts @@ -0,0 +1,51 @@ +import operation from "../../_operations/billing/usage/get-account-usage-v2.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get-account-usage-v2.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "billing usage get-account-usage-v2", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + from: argv["from"], + to: argv["to"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf billing usage get-account-usage-v2", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billable/usage`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/billing/usage/get-account-usage-v2.ts b/packages/cli/src/commands/_generated/billing/usage/get-account-usage-v2.ts index 2479807cf7..03dc3fb0b8 100644 --- a/packages/cli/src/commands/_generated/billing/usage/get-account-usage-v2.ts +++ b/packages/cli/src/commands/_generated/billing/usage/get-account-usage-v2.ts @@ -1,86 +1,45 @@ -import operation from "../../_operations/billing/usage/get-account-usage-v2.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get-account-usage-v2 command * @generated from apis/overlays/billing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 billing usage get-account-usage-v2\n\nReturns cost and usage data for a single Cloudflare account, aligned with the [FinOps FOCUS v1.3](https://focus.finops.org/focus-specification/v1-3/) Cost and Usage dataset specification. Each record represents one billable metric for one account on one day. This includes all metered usage, including usage that falls within free-tier allowances and may result in zero cost. **Note:** This endpoint serves `usage` records only; cost and pricing fields are absent from responses. To retrieve rated costs, use `POST` on the same path with `Metric: cost`. When `from` and `to` are omitted, defaults to the start of the current month through today. The maximum date range is 31 days." - ) - .option("from", { - type: "string", - description: +const parameters = { + flags: { + from: { + kind: "parsed", + brief: "Start date for the usage query (ISO 8601). Required if `to` is set. When omitted along with `to`, defaults to the start of the current month. Filters by charge period (when consumption happened), not billing period. The maximum date range is 31 days.", - }) - .option("to", { - type: "string", - description: + optional: true, + parse: String, + }, + to: { + kind: "parsed", + brief: "End date for the usage query (ISO 8601). Required if `from` is set. When omitted along with `from`, defaults to today. Filters by charge period (when consumption happened), not billing period. The maximum date range is 31 days.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get-account-usage-v2", describe: "Get Account Usage (Version 2, Alpha, Restricted)", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "billing usage get-account-usage-v2", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - from: argv["from"], - to: argv["to"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf billing usage get-account-usage-v2", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billable/usage`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 billing usage get-account-usage-v2\n\nReturns cost and usage data for a single Cloudflare account, aligned with the [FinOps FOCUS v1.3](https://focus.finops.org/focus-specification/v1-3/) Cost and Usage dataset specification. Each record represents one billable metric for one account on one day. This includes all metered usage, including usage that falls within free-tier allowances and may result in zero cost. **Note:** This endpoint serves `usage` records only; cost and pricing fields are absent from responses. To retrieve rated costs, use `POST` on the same path with `Metric: cost`. When `from` and `to` are omitted, defaults to the start of the current month through today. The maximum date range is 31 days.", + ...parameters, + loader: () => import("./get-account-usage-v2.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/usage/get-info-v1.handler.ts b/packages/cli/src/commands/_generated/billing/usage/get-info-v1.handler.ts new file mode 100644 index 0000000000..500387d916 --- /dev/null +++ b/packages/cli/src/commands/_generated/billing/usage/get-info-v1.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../_operations/billing/usage/get-info-v1.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get-info-v1.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "billing usage get-info-v1", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf billing usage get-info-v1", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billable-usage/info`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/billing/usage/get-info-v1.ts b/packages/cli/src/commands/_generated/billing/usage/get-info-v1.ts index 70664cbc65..03f81ff30f 100644 --- a/packages/cli/src/commands/_generated/billing/usage/get-info-v1.ts +++ b/packages/cli/src/commands/_generated/billing/usage/get-info-v1.ts @@ -1,71 +1,31 @@ -import operation from "../../_operations/billing/usage/get-info-v1.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get-info-v1 command * @generated from apis/overlays/billing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 billing usage get-info-v1\n\nReturns high-level usage information for the account, including coverage, and subscription metadata." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get-info-v1", describe: "Get Account Billable Usage Info (Version 1, Alpha)", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "billing usage get-info-v1", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf billing usage get-info-v1", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billable-usage/info`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 billing usage get-info-v1\n\nReturns high-level usage information for the account, including coverage, and subscription metadata.", + ...parameters, + loader: () => import("./get-info-v1.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/usage/get-v1.handler.ts b/packages/cli/src/commands/_generated/billing/usage/get-v1.handler.ts new file mode 100644 index 0000000000..0b24adb300 --- /dev/null +++ b/packages/cli/src/commands/_generated/billing/usage/get-v1.handler.ts @@ -0,0 +1,51 @@ +import operation from "../../_operations/billing/usage/get-v1.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get-v1.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "billing usage get-v1", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + from: argv["from"], + to: argv["to"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf billing usage get-v1", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billable-usage`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/billing/usage/get-v1.ts b/packages/cli/src/commands/_generated/billing/usage/get-v1.ts index f7e90d0fb2..1ff2de0b7a 100644 --- a/packages/cli/src/commands/_generated/billing/usage/get-v1.ts +++ b/packages/cli/src/commands/_generated/billing/usage/get-v1.ts @@ -1,85 +1,44 @@ -import operation from "../../_operations/billing/usage/get-v1.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get-v1 command * @generated from apis/overlays/billing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 billing usage get-v1\n\nReturns billable usage data for the account. When no query parameters are provided, returns usage for the current billing period." - ) - .option("from", { - type: "string", - description: +const parameters = { + flags: { + from: { + kind: "parsed", + brief: "Start date for the usage query (ISO 8601). The provided time range must include the subscription billing cycle anchor day, otherwise no usage data is returned. Use the info endpoint to retrieve the subscription anchor day.", - }) - .option("to", { - type: "string", - description: "End date for the usage query (ISO 8601).", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + to: { + kind: "parsed", + brief: "End date for the usage query (ISO 8601).", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get-v1", describe: "Get Account Billable Usage (Version 1, Alpha)", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "billing usage get-v1", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - from: argv["from"], - to: argv["to"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf billing usage get-v1", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billable-usage`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 billing usage get-v1\n\nReturns billable usage data for the account. When no query parameters are provided, returns usage for the current billing period.", + ...parameters, + loader: () => import("./get-v1.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/usage/index.ts b/packages/cli/src/commands/_generated/billing/usage/index.ts index c8b568c96f..2bdac0d2a1 100644 --- a/packages/cli/src/commands/_generated/billing/usage/index.ts +++ b/packages/cli/src/commands/_generated/billing/usage/index.ts @@ -3,29 +3,24 @@ import $getaccountusagev2 from "./get-account-usage-v2.js"; import $getinfov1 from "./get-info-v1.js"; import $getv1 from "./get-v1.js"; import $query from "./query.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * usage command group * @generated from apis/overlays/billing.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "usage", describe: "Metered usage data for billed services — requests, bandwidth, and feature consumption", - builder: (yargs) => { - return yargs - .command($getaccountbillablemetrics) - .command($getaccountusagev2) - .command($getinfov1) - .command($getv1) - .command($query) - .demandCommand(1, "Please specify a subcommand"); + routes: { + "get-account-billable-metrics": $getaccountbillablemetrics, + "get-account-usage-v2": $getaccountusagev2, + "get-info-v1": $getinfov1, + "get-v1": $getv1, + query: $query, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/billing/usage/query.handler.ts b/packages/cli/src/commands/_generated/billing/usage/query.handler.ts new file mode 100644 index 0000000000..06bfab02c4 --- /dev/null +++ b/packages/cli/src/commands/_generated/billing/usage/query.handler.ts @@ -0,0 +1,110 @@ +import operation from "../../_operations/billing/usage/query.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./query.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "billing usage query", + classification: { + safeFlags: ["granularity", "metric", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf billing usage query", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billable/usage`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + FilterBy: { + BillableMetricIds: argv["filter-by-billable-metric-ids"], + ProductFamilyIds: argv["filter-by-product-family-ids"], + Tags: parseObjectArray( + argv["filter-by-tags"], + "filter-by-tags" + ), + }, + Granularity: argv["granularity"], + GroupBy: parseObjectArray(argv["group-by"], "group-by"), + Metric: argv["metric"], + TimePeriod: { + From: resolveFileToken( + argv["time-period-from"] as string | undefined, + "time-period-from", + "text" + ), + To: resolveFileToken( + argv["time-period-to"] as string | undefined, + "time-period-to", + "text" + ), + }, + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Loading`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + FilterBy: { + BillableMetricIds: argv["filter-by-billable-metric-ids"], + ProductFamilyIds: argv["filter-by-product-family-ids"], + Tags: parseObjectArray(argv["filter-by-tags"], "filter-by-tags"), + }, + Granularity: argv["granularity"], + GroupBy: parseObjectArray(argv["group-by"], "group-by"), + Metric: argv["metric"], + TimePeriod: { + From: resolveFileToken( + argv["time-period-from"] as string | undefined, + "time-period-from", + "text" + ), + To: resolveFileToken( + argv["time-period-to"] as string | undefined, + "time-period-to", + "text" + ), + }, + }); + const result = await withProgress(`Loading`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/billing/usage/query.ts b/packages/cli/src/commands/_generated/billing/usage/query.ts index 3303a6631d..8068731a3e 100644 --- a/packages/cli/src/commands/_generated/billing/usage/query.ts +++ b/packages/cli/src/commands/_generated/billing/usage/query.ts @@ -1,188 +1,100 @@ -import operation from "../../_operations/billing/usage/query.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * query command * @generated from apis/overlays/billing.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 billing usage query\n\nReturns cost and usage data for a single Cloudflare account, aligned with the [FinOps FOCUS v1.3](https://focus.finops.org/focus-specification/v1-3/) Cost and Usage dataset specification. This is the filterable counterpart to `GET` on the same path. It is a read-only operation and requires only the `#billing:read` permission; `POST` is used so that filter criteria can be supplied in a request body rather than in the query string. Each record represents one billable metric for one account on one day. This includes all metered usage, including usage that falls within free-tier allowances and may result in zero cost. **Note:** Cost and pricing fields are populated only when `Metric` is `cost`; otherwise they are absent from responses. The request body is optional. When it is omitted, or when `TimePeriod` is omitted, the range defaults to the start of the current month through today. The maximum date range is 31 days. Filters of different kinds are combined with AND. Values within one tag filter are combined with OR. Filter values that do not match usage produce an empty result set. Results can be grouped by up to two groups, in any combination of dimension keys and resource-tag keys. Tag groups are returned in the `Tags` field. Usage without a requested tag remains in an untagged group, with that key omitted from `Tags`. Requests that use tag filtering or tag grouping return HTTP 400 when the underlying usage data source does not support tags. Requests that use dimension grouping return HTTP 400 when the underlying usage data source does not support dimensions. `Granularity` is optional. When it is omitted, the response is as described above. With `DAILY`, each record covers one day. With `PERIOD`, each record covers the whole time period: `ChargePeriodStart` is the first day of the period and `ChargePeriodEnd` is the day after its last day. For `usage`, `ConsumedQuantity` is the sum of the daily quantities in the bucket. When `Granularity` is set and `Metric` is `cost`, each record is one billable metric for one bucket. `PricingQuantity` and `BilledCost` are summed across pricing tiers, so unit prices and the list and contracted costs derived from them are absent. Only cost held in US dollars is summed, so a total can be lower than the sum of the `cost` records returned without `Granularity` for the same range when that range also holds cost in another credit type. Requests for `usage` that use `PERIOD` granularity return HTTP 400 when the underlying usage data source does not support it." - ) - .option("filter-by-billable-metric-ids", { - type: "string", - array: true, - description: +const parameters = { + flags: { + "filter-by-billable-metric-ids": { + kind: "parsed", + brief: "Restrict results to rows whose `x_BillableMetricId` matches one of these billable metric ids (e.g. `workers_standard_requests`). Values must be unique. Cost billed under an archived billable metric carries that metric's catalog public id as `x_BillableMetricId` and is never matched by this filter; omit the filter to include it.", - }) - .option("filter-by-product-family-ids", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + "filter-by-product-family-ids": { + kind: "parsed", + brief: "Restrict results to billable metrics belonging to these product families. Values must be unique UUIDs.", - }) - .option("filter-by-tags", { - type: "string", - description: + variadic: true, + optional: true, + parse: String, + }, + "filter-by-tags": { + kind: "parsed", + brief: 'Restrict results by resource tags. Filters for different keys are combined with AND, while values within one filter are combined with OR. Keys must be unique and are case-sensitive. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"Key": string, "Values": [string]}].', - }) - .option("granularity", { - type: "string", - description: + optional: true, + parse: String, + }, + granularity: { + kind: "parsed", + brief: "Optional time bucket to sum records over. `DAILY` returns one record per day. `PERIOD` returns one record for the whole time period. When set with `Metric` `cost`, cost is summed across pricing tiers into one record per billable metric per bucket. When omitted, records are not summed: `usage` returns daily records and `cost` returns one record per rated breakdown. Available only on `POST` account usage.", + optional: true, choices: ["DAILY", "PERIOD"], - }) - .coerce("granularity", (value) => - resolveFileToken(value, "granularity", "text") - ) - .option("group-by", { - type: "string", - description: + parse: String, + coerce: (value: string) => resolveFileToken(value, "granularity", "text"), + }, + "group-by": { + kind: "parsed", + brief: 'Grouping definitions used to split result rows. At most two unique keys may be supplied. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"Key": string, "Type": "TAG" | "DIMENSION"}].', - }) - .option("metric", { - type: "string", - description: + optional: true, + parse: String, + }, + metric: { + kind: "parsed", + brief: "Type of cost/usage records to retrieve. `usage` returns unrated usage quantities. `cost` returns rated usage with cost and pricing fields; it is available only on `POST` account usage and only when the underlying usage data source is ClickHouse (other sources return an empty result set). Requests that combine `cost` with `GroupBy` or `FilterBy.Tags` return HTTP 400. Unrelated to `FilterBy.BillableMetricIds`. Defaults to `usage` when omitted.", - choices: ["usage", "cost"], default: "usage", - }) - .coerce("metric", (value) => resolveFileToken(value, "metric", "text")) - .option("time-period-from", { - type: "string", - description: "Start of the range (ISO 8601). Required if `To` is set.", - }) - .option("time-period-to", { - type: "string", - description: + choices: ["usage", "cost"], + parse: String, + coerce: (value: string) => resolveFileToken(value, "metric", "text"), + }, + "time-period-from": { + kind: "parsed", + brief: "Start of the range (ISO 8601). Required if `To` is set.", + optional: true, + parse: String, + }, + "time-period-to": { + kind: "parsed", + brief: "End of the range (ISO 8601). Required if `From` is set. Must be after `From` and no more than 31 days after it.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: + }, + body: { + kind: "parsed", + brief: "Filter criteria for a usage query. Every field is optional; an empty object is equivalent to omitting the body entirely. Unknown fields are rejected.", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "query", describe: "Query Account Usage (Version 2, Alpha, Restricted)", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "billing usage query", - classification: { - safeFlags: ["granularity", "metric", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf billing usage query", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/billable/usage`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - FilterBy: { - BillableMetricIds: argv["filter-by-billable-metric-ids"], - ProductFamilyIds: argv["filter-by-product-family-ids"], - Tags: parseObjectArray( - argv["filter-by-tags"], - "filter-by-tags" - ), - }, - Granularity: argv["granularity"], - GroupBy: parseObjectArray(argv["group-by"], "group-by"), - Metric: argv["metric"], - TimePeriod: { - From: resolveFileToken( - argv["time-period-from"] as string | undefined, - "time-period-from", - "text" - ), - To: resolveFileToken( - argv["time-period-to"] as string | undefined, - "time-period-to", - "text" - ), - }, - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Loading`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - FilterBy: { - BillableMetricIds: argv["filter-by-billable-metric-ids"], - ProductFamilyIds: argv["filter-by-product-family-ids"], - Tags: parseObjectArray(argv["filter-by-tags"], "filter-by-tags"), - }, - Granularity: argv["granularity"], - GroupBy: parseObjectArray(argv["group-by"], "group-by"), - Metric: argv["metric"], - TimePeriod: { - From: resolveFileToken( - argv["time-period-from"] as string | undefined, - "time-period-from", - "text" - ), - To: resolveFileToken( - argv["time-period-to"] as string | undefined, - "time-period-to", - "text" - ), - }, - }); - const result = await withProgress(`Loading`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 billing usage query\n\nReturns cost and usage data for a single Cloudflare account, aligned with the [FinOps FOCUS v1.3](https://focus.finops.org/focus-specification/v1-3/) Cost and Usage dataset specification. This is the filterable counterpart to `GET` on the same path. It is a read-only operation and requires only the `#billing:read` permission; `POST` is used so that filter criteria can be supplied in a request body rather than in the query string. Each record represents one billable metric for one account on one day. This includes all metered usage, including usage that falls within free-tier allowances and may result in zero cost. **Note:** Cost and pricing fields are populated only when `Metric` is `cost`; otherwise they are absent from responses. The request body is optional. When it is omitted, or when `TimePeriod` is omitted, the range defaults to the start of the current month through today. The maximum date range is 31 days. Filters of different kinds are combined with AND. Values within one tag filter are combined with OR. Filter values that do not match usage produce an empty result set. Results can be grouped by up to two groups, in any combination of dimension keys and resource-tag keys. Tag groups are returned in the `Tags` field. Usage without a requested tag remains in an untagged group, with that key omitted from `Tags`. Requests that use tag filtering or tag grouping return HTTP 400 when the underlying usage data source does not support tags. Requests that use dimension grouping return HTTP 400 when the underlying usage data source does not support dimensions. `Granularity` is optional. When it is omitted, the response is as described above. With `DAILY`, each record covers one day. With `PERIOD`, each record covers the whole time period: `ChargePeriodStart` is the first day of the period and `ChargePeriodEnd` is the day after its last day. For `usage`, `ConsumedQuantity` is the sum of the daily quantities in the bucket. When `Granularity` is set and `Metric` is `cost`, each record is one billable metric for one bucket. `PricingQuantity` and `BilledCost` are summed across pricing tiers, so unit prices and the list and contracted costs derived from them are absent. Only cost held in US dollars is summed, so a total can be lower than the sum of the `cost` records returned without `Granularity` for the same range when that range also holds cost in another credit type. Requests for `usage` that use `PERIOD` granularity return HTTP 400 when the underlying usage data source does not support it.", + ...parameters, + loader: () => import("./query.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/bot-management/feedback/create.handler.ts b/packages/cli/src/commands/_generated/bot-management/feedback/create.handler.ts new file mode 100644 index 0000000000..c1d72df760 --- /dev/null +++ b/packages/cli/src/commands/_generated/bot-management/feedback/create.handler.ts @@ -0,0 +1,244 @@ +import operation from "../../_operations/bot-management/feedback/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { compactBody, parseBody, parseJsonMap } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { + promptForRequiredEnumField, + promptForRequiredField, +} from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "bot-management feedback create", + classification: { + safeFlags: ["type", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["description"] === undefined) { + argv["description"] = await promptForRequiredField( + "description", + "The description field" + ); + } + if (argv["expression"] === undefined) { + argv["expression"] = await promptForRequiredField( + "expression", + "Wirefilter expression describing the traffic being reported." + ); + } + if (argv["first-request-seen-at"] === undefined) { + argv["first-request-seen-at"] = await promptForRequiredField( + "first-request-seen-at", + "The first_request_seen_at field" + ); + } + if (argv["last-request-seen-at"] === undefined) { + argv["last-request-seen-at"] = await promptForRequiredField( + "last-request-seen-at", + "The last_request_seen_at field" + ); + } + if (argv["requests"] === undefined) { + throw new Error( + "--requests is required (or pass --body with this field set)." + ); + } + if (argv["requests-by-attribute"] === undefined) { + throw new Error( + "--requests-by-attribute is required (or pass --body with this field set)." + ); + } + if (argv["requests-by-score"] === undefined) { + throw new Error( + "--requests-by-score is required (or pass --body with this field set)." + ); + } + if (argv["requests-by-score-src"] === undefined) { + throw new Error( + "--requests-by-score-src is required (or pass --body with this field set)." + ); + } + if (argv["type"] === undefined) { + argv["type"] = await promptForRequiredEnumField( + "type", + "Type of feedback report.", + ["false_positive", "false_negative"] as const + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + formatDryRun({ + command: "cf bot-management feedback create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/bot_management/feedback`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body, [ + { + path: ["requests_by_attribute"], + flag: "requests-by-attribute", + }, + { path: ["requests_by_score"], flag: "requests-by-score" }, + { + path: ["requests_by_score_src"], + flag: "requests-by-score-src", + }, + ]) + : compactBody( + { + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + expression: resolveFileToken( + argv["expression"] as string | undefined, + "expression", + "text" + ), + first_request_seen_at: resolveFileToken( + argv["first-request-seen-at"] as string | undefined, + "first-request-seen-at", + "text" + ), + last_request_seen_at: resolveFileToken( + argv["last-request-seen-at"] as string | undefined, + "last-request-seen-at", + "text" + ), + requests: argv["requests"], + requests_by_attribute: parseJsonMap( + argv["requests-by-attribute"], + "requests-by-attribute", + true + ), + requests_by_score: parseJsonMap( + argv["requests-by-score"], + "requests-by-score", + true + ), + requests_by_score_src: parseJsonMap( + argv["requests-by-score-src"], + "requests-by-score-src", + true + ), + subtype: resolveFileToken( + argv["subtype"] as string | undefined, + "subtype", + "text" + ), + type: argv["type"], + }, + [ + ["requests_by_attribute"], + ["requests_by_score"], + ["requests_by_score_src"], + ] + ), + }); + return; + } + const parsedBody = + argv.body !== undefined + ? parseBody(argv.body, [ + { + path: ["requests_by_attribute"], + flag: "requests-by-attribute", + }, + { path: ["requests_by_score"], flag: "requests-by-score" }, + { + path: ["requests_by_score_src"], + flag: "requests-by-score-src", + }, + ]) + : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody( + { + description: resolveFileToken( + argv["description"] as string | undefined, + "description", + "text" + ), + expression: resolveFileToken( + argv["expression"] as string | undefined, + "expression", + "text" + ), + first_request_seen_at: resolveFileToken( + argv["first-request-seen-at"] as string | undefined, + "first-request-seen-at", + "text" + ), + last_request_seen_at: resolveFileToken( + argv["last-request-seen-at"] as string | undefined, + "last-request-seen-at", + "text" + ), + requests: argv["requests"], + requests_by_attribute: parseJsonMap( + argv["requests-by-attribute"], + "requests-by-attribute", + true + ), + requests_by_score: parseJsonMap( + argv["requests-by-score"], + "requests-by-score", + true + ), + requests_by_score_src: parseJsonMap( + argv["requests-by-score-src"], + "requests-by-score-src", + true + ), + subtype: resolveFileToken( + argv["subtype"] as string | undefined, + "subtype", + "text" + ), + type: argv["type"], + }, + [ + ["requests_by_attribute"], + ["requests_by_score"], + ["requests_by_score_src"], + ] + ); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/bot-management/feedback/create.ts b/packages/cli/src/commands/_generated/bot-management/feedback/create.ts index 265e589be6..3cafcf9488 100644 --- a/packages/cli/src/commands/_generated/bot-management/feedback/create.ts +++ b/packages/cli/src/commands/_generated/bot-management/feedback/create.ts @@ -1,315 +1,103 @@ -import operation from "../../_operations/bot-management/feedback/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/bot-management.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { compactBody, parseBody, parseJsonMap } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; import { - promptForRequiredEnumField, - promptForRequiredField, -} from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; +import { resolveFileToken } from "#lib/input-validation.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 bot-management feedback create\n\nSubmit a feedback report for the specified zone. Use `type` to indicate whether the report is a false positive (good traffic flagged as bot) or a false negative (bot traffic missed). Furthermore, you can also use `expression` as a wirefilter to identify the affected traffic sample. See more accepted API fields and expression types at https://developers.cloudflare.com/bots/concepts/feedback-loop/#api-fields and https://developers.cloudflare.com/bots/concepts/feedback-loop/#expression-fields, respectively." - ) - .option("description", { - type: "string", - description: "The description field", - }) - .option("expression", { - type: "string", - description: - "Wirefilter expression describing the traffic being reported.", - }) - .option("first-request-seen-at", { - type: "string", - description: "The first_request_seen_at field", - }) - .option("last-request-seen-at", { - type: "string", - description: "The last_request_seen_at field", - }) - .option("requests", { type: "number", description: "The requests field" }) - .option("requests-by-attribute", { - type: "string", - description: +const parameters = { + flags: { + description: { + kind: "parsed", + brief: "The description field", + optional: true, + parse: String, + }, + expression: { + kind: "parsed", + brief: "Wirefilter expression describing the traffic being reported.", + optional: true, + parse: String, + }, + "first-request-seen-at": { + kind: "parsed", + brief: "The first_request_seen_at field", + optional: true, + parse: String, + }, + "last-request-seen-at": { + kind: "parsed", + brief: "The last_request_seen_at field", + optional: true, + parse: String, + }, + requests: { + kind: "parsed", + brief: "The requests field", + optional: true, + parse: Number, + }, + "requests-by-attribute": { + kind: "parsed", + brief: 'Top attributes contributing to the feedback sample. Keys include topASNs, topCountries, topHosts, topIPs, topJA3Hashes, topJA4s, topPaths, topUserAgents. Provide as a JSON object or @path/to/file.json. Shape: {"": [{...}]}.', - }) - .option("requests-by-score", { - type: "string", - description: + optional: true, + parse: String, + }, + "requests-by-score": { + kind: "parsed", + brief: 'Map of bot scores (1-99) to request counts. Sum must equal `requests`. Provide as a JSON object or @path/to/file.json. Shape: {"": number}.', - }) - .option("requests-by-score-src", { - type: "string", - description: + optional: true, + parse: String, + }, + "requests-by-score-src": { + kind: "parsed", + brief: 'Map of score source to request counts. Sum must equal `requests`. Provide as a JSON object or @path/to/file.json. Shape: {"": number}.', - }) - .option("subtype", { type: "string", description: "The subtype field" }) - .option("type", { - type: "string", - description: "Type of feedback report.", + optional: true, + parse: String, + }, + subtype: { + kind: "parsed", + brief: "The subtype field", + optional: true, + parse: String, + }, + type: { + kind: "parsed", + brief: "Type of feedback report.", + optional: true, choices: ["false_positive", "false_negative"], - }) - .coerce("type", (value) => resolveFileToken(value, "type", "text")) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + parse: String, + coerce: (value: string) => resolveFileToken(value, "type", "text"), + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Submit a feedback report", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "bot-management feedback create", - classification: { - safeFlags: ["type", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["description"] === undefined) { - argv["description"] = await promptForRequiredField( - "description", - "The description field" - ); - } - if (argv["expression"] === undefined) { - argv["expression"] = await promptForRequiredField( - "expression", - "Wirefilter expression describing the traffic being reported." - ); - } - if (argv["first-request-seen-at"] === undefined) { - argv["first-request-seen-at"] = await promptForRequiredField( - "first-request-seen-at", - "The first_request_seen_at field" - ); - } - if (argv["last-request-seen-at"] === undefined) { - argv["last-request-seen-at"] = await promptForRequiredField( - "last-request-seen-at", - "The last_request_seen_at field" - ); - } - if (argv["requests"] === undefined) { - throw new Error( - "--requests is required (or pass --body with this field set)." - ); - } - if (argv["requests-by-attribute"] === undefined) { - throw new Error( - "--requests-by-attribute is required (or pass --body with this field set)." - ); - } - if (argv["requests-by-score"] === undefined) { - throw new Error( - "--requests-by-score is required (or pass --body with this field set)." - ); - } - if (argv["requests-by-score-src"] === undefined) { - throw new Error( - "--requests-by-score-src is required (or pass --body with this field set)." - ); - } - if (argv["type"] === undefined) { - argv["type"] = await promptForRequiredEnumField( - "type", - "Type of feedback report.", - ["false_positive", "false_negative"] as const - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - formatDryRun({ - command: "cf bot-management feedback create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/bot_management/feedback`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body, [ - { - path: ["requests_by_attribute"], - flag: "requests-by-attribute", - }, - { path: ["requests_by_score"], flag: "requests-by-score" }, - { - path: ["requests_by_score_src"], - flag: "requests-by-score-src", - }, - ]) - : compactBody( - { - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - expression: resolveFileToken( - argv["expression"] as string | undefined, - "expression", - "text" - ), - first_request_seen_at: resolveFileToken( - argv["first-request-seen-at"] as string | undefined, - "first-request-seen-at", - "text" - ), - last_request_seen_at: resolveFileToken( - argv["last-request-seen-at"] as string | undefined, - "last-request-seen-at", - "text" - ), - requests: argv["requests"], - requests_by_attribute: parseJsonMap( - argv["requests-by-attribute"], - "requests-by-attribute", - true - ), - requests_by_score: parseJsonMap( - argv["requests-by-score"], - "requests-by-score", - true - ), - requests_by_score_src: parseJsonMap( - argv["requests-by-score-src"], - "requests-by-score-src", - true - ), - subtype: resolveFileToken( - argv["subtype"] as string | undefined, - "subtype", - "text" - ), - type: argv["type"], - }, - [ - ["requests_by_attribute"], - ["requests_by_score"], - ["requests_by_score_src"], - ] - ), - }); - return; - } - const parsedBody = - argv.body !== undefined - ? parseBody(argv.body, [ - { - path: ["requests_by_attribute"], - flag: "requests-by-attribute", - }, - { path: ["requests_by_score"], flag: "requests-by-score" }, - { - path: ["requests_by_score_src"], - flag: "requests-by-score-src", - }, - ]) - : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody( - { - description: resolveFileToken( - argv["description"] as string | undefined, - "description", - "text" - ), - expression: resolveFileToken( - argv["expression"] as string | undefined, - "expression", - "text" - ), - first_request_seen_at: resolveFileToken( - argv["first-request-seen-at"] as string | undefined, - "first-request-seen-at", - "text" - ), - last_request_seen_at: resolveFileToken( - argv["last-request-seen-at"] as string | undefined, - "last-request-seen-at", - "text" - ), - requests: argv["requests"], - requests_by_attribute: parseJsonMap( - argv["requests-by-attribute"], - "requests-by-attribute", - true - ), - requests_by_score: parseJsonMap( - argv["requests-by-score"], - "requests-by-score", - true - ), - requests_by_score_src: parseJsonMap( - argv["requests-by-score-src"], - "requests-by-score-src", - true - ), - subtype: resolveFileToken( - argv["subtype"] as string | undefined, - "subtype", - "text" - ), - type: argv["type"], - }, - [ - ["requests_by_attribute"], - ["requests_by_score"], - ["requests_by_score_src"], - ] - ); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 bot-management feedback create\n\nSubmit a feedback report for the specified zone. Use `type` to indicate whether the report is a false positive (good traffic flagged as bot) or a false negative (bot traffic missed). Furthermore, you can also use `expression` as a wirefilter to identify the affected traffic sample. See more accepted API fields and expression types at https://developers.cloudflare.com/bots/concepts/feedback-loop/#api-fields and https://developers.cloudflare.com/bots/concepts/feedback-loop/#expression-fields, respectively.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/bot-management/feedback/index.ts b/packages/cli/src/commands/_generated/bot-management/feedback/index.ts index 79a70d65c0..940aed45e6 100644 --- a/packages/cli/src/commands/_generated/bot-management/feedback/index.ts +++ b/packages/cli/src/commands/_generated/bot-management/feedback/index.ts @@ -1,24 +1,19 @@ import $create from "./create.js"; import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * feedback command group * @generated from apis/overlays/bot-management.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "feedback", describe: "Operations for feedback", - builder: (yargs) => { - return yargs - .command($create) - .command($list) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/bot-management/feedback/list.handler.ts b/packages/cli/src/commands/_generated/bot-management/feedback/list.handler.ts new file mode 100644 index 0000000000..cfe0b9b392 --- /dev/null +++ b/packages/cli/src/commands/_generated/bot-management/feedback/list.handler.ts @@ -0,0 +1,42 @@ +import operation from "../../_operations/bot-management/feedback/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "bot-management feedback list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf bot-management feedback list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/bot_management/feedback`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/bot-management/feedback/list.ts b/packages/cli/src/commands/_generated/bot-management/feedback/list.ts index 74721ad19b..365578a2b7 100644 --- a/packages/cli/src/commands/_generated/bot-management/feedback/list.ts +++ b/packages/cli/src/commands/_generated/bot-management/feedback/list.ts @@ -1,69 +1,31 @@ -import operation from "../../_operations/bot-management/feedback/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/bot-management.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 bot-management feedback list\n\nReturns all feedback reports previously submitted for the specified zone. Feedback reports help improve detection by sharing samples of traffic that were misclassified as bots or humans." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List zone feedback reports", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "bot-management feedback list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf bot-management feedback list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/bot_management/feedback`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 bot-management feedback list\n\nReturns all feedback reports previously submitted for the specified zone. Feedback reports help improve detection by sharing samples of traffic that were misclassified as bots or humans.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/bot-management/get.handler.ts b/packages/cli/src/commands/_generated/bot-management/get.handler.ts new file mode 100644 index 0000000000..f2a43307e3 --- /dev/null +++ b/packages/cli/src/commands/_generated/bot-management/get.handler.ts @@ -0,0 +1,42 @@ +import operation from "../_operations/bot-management/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "bot-management get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf bot-management get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/bot_management`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/bot-management/get.ts b/packages/cli/src/commands/_generated/bot-management/get.ts index 0b1445de8f..8eb210bcc2 100644 --- a/packages/cli/src/commands/_generated/bot-management/get.ts +++ b/packages/cli/src/commands/_generated/bot-management/get.ts @@ -1,67 +1,30 @@ -import operation from "../_operations/bot-management/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/bot-management.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage("$0 bot-management get\n\nRetrieve a zone's Bot Management Config") - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "Get Zone Bot Management Config", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "bot-management get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf bot-management get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/bot_management`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: "$0 bot-management get\n\nRetrieve a zone's Bot Management Config", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/bot-management/index.ts b/packages/cli/src/commands/_generated/bot-management/index.ts index 7c909b1bc4..f3c42785ee 100644 --- a/packages/cli/src/commands/_generated/bot-management/index.ts +++ b/packages/cli/src/commands/_generated/bot-management/index.ts @@ -1,26 +1,21 @@ import $feedback from "./feedback/index.js"; import $get from "./get.js"; import $update from "./update.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * bot-management command * @generated from apis/overlays/bot-management.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "bot-management", describe: "bot-management", - builder: (yargs) => { - return yargs - .command($get) - .command($update) - .command($feedback) - .demandCommand(1, "Please specify a subcommand"); + routes: { + get: $get, + update: $update, + feedback: $feedback, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/bot-management/update.handler.ts b/packages/cli/src/commands/_generated/bot-management/update.handler.ts new file mode 100644 index 0000000000..47a8f7170b --- /dev/null +++ b/packages/cli/src/commands/_generated/bot-management/update.handler.ts @@ -0,0 +1,223 @@ +import operation from "../_operations/bot-management/update.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./update.js"; +import { createCommandClient, getZoneId } from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "bot-management update", + classification: { + safeFlags: [ + "ai-agents-anthropic-agent", + "ai-agents-google-agent", + "ai-agents-instinct", + "ai-agents-muse", + "ai-agents-openai-agent", + "ai-bots-migration-opt-out", + "ai-bots-protection", + "ai-search", + "ai-training", + "ai-user", + "bot-preference-sync-enabled", + "cf-robots-variant", + "content-bots-protection", + "crawler-protection", + "enable-js", + "is-robots-txt-managed", + "jsd-api-results-enabled", + "fight-mode", + "stale-zone-configuration-optimize-wordpress", + "stale-zone-configuration-suppress-session-score", + "stale-zone-configuration-fight-mode", + "optimize-wordpress", + "sbfm-definitely-automated", + "sbfm-static-resource-protection", + "sbfm-verified-bots", + "sbfm-likely-automated", + "auto-update-model", + "bm-cookie-enabled", + "suppress-session-score", + "dry-run", + ], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + formatDryRun({ + command: "cf bot-management update", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/bot_management`, + pathParams: { "zone-id": String(argv.zone ?? argv["zone-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + ai_agents: { + anthropic_agent: argv["ai-agents-anthropic-agent"], + google_agent: argv["ai-agents-google-agent"], + instinct: argv["ai-agents-instinct"], + muse: argv["ai-agents-muse"], + openai_agent: argv["ai-agents-openai-agent"], + }, + ai_bots_migration_opt_out: argv["ai-bots-migration-opt-out"], + ai_bots_protection: argv["ai-bots-protection"], + ai_search: argv["ai-search"], + ai_training: argv["ai-training"], + ai_user: argv["ai-user"], + bot_preference_sync_enabled: + argv["bot-preference-sync-enabled"], + cf_robots_variant: argv["cf-robots-variant"], + content_bots_protection: argv["content-bots-protection"], + crawler_protection: argv["crawler-protection"], + enable_js: argv["enable-js"], + is_robots_txt_managed: argv["is-robots-txt-managed"], + jsd_api_results_enabled: argv["jsd-api-results-enabled"], + fight_mode: argv["fight-mode"], + stale_zone_configuration: { + optimize_wordpress: + argv["stale-zone-configuration-optimize-wordpress"], + sbfm_definitely_automated: resolveFileToken( + argv[ + "stale-zone-configuration-sbfm-definitely-automated" + ] as string | undefined, + "stale-zone-configuration-sbfm-definitely-automated", + "text" + ), + sbfm_likely_automated: resolveFileToken( + argv["stale-zone-configuration-sbfm-likely-automated"] as + | string + | undefined, + "stale-zone-configuration-sbfm-likely-automated", + "text" + ), + sbfm_static_resource_protection: resolveFileToken( + argv[ + "stale-zone-configuration-sbfm-static-resource-protection" + ] as string | undefined, + "stale-zone-configuration-sbfm-static-resource-protection", + "text" + ), + sbfm_verified_bots: resolveFileToken( + argv["stale-zone-configuration-sbfm-verified-bots"] as + | string + | undefined, + "stale-zone-configuration-sbfm-verified-bots", + "text" + ), + suppress_session_score: + argv["stale-zone-configuration-suppress-session-score"], + fight_mode: argv["stale-zone-configuration-fight-mode"], + }, + optimize_wordpress: argv["optimize-wordpress"], + sbfm_definitely_automated: argv["sbfm-definitely-automated"], + sbfm_static_resource_protection: + argv["sbfm-static-resource-protection"], + sbfm_verified_bots: argv["sbfm-verified-bots"], + sbfm_likely_automated: argv["sbfm-likely-automated"], + auto_update_model: argv["auto-update-model"], + bm_cookie_enabled: argv["bm-cookie-enabled"], + suppress_session_score: argv["suppress-session-score"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const zoneId = await getZoneId({ zone: argv.zone }, client, { + quiet: argv.quiet, + }); + argv.zoneId = zoneId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Updated` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + ai_agents: { + anthropic_agent: argv["ai-agents-anthropic-agent"], + google_agent: argv["ai-agents-google-agent"], + instinct: argv["ai-agents-instinct"], + muse: argv["ai-agents-muse"], + openai_agent: argv["ai-agents-openai-agent"], + }, + ai_bots_migration_opt_out: argv["ai-bots-migration-opt-out"], + ai_bots_protection: argv["ai-bots-protection"], + ai_search: argv["ai-search"], + ai_training: argv["ai-training"], + ai_user: argv["ai-user"], + bot_preference_sync_enabled: argv["bot-preference-sync-enabled"], + cf_robots_variant: argv["cf-robots-variant"], + content_bots_protection: argv["content-bots-protection"], + crawler_protection: argv["crawler-protection"], + enable_js: argv["enable-js"], + is_robots_txt_managed: argv["is-robots-txt-managed"], + jsd_api_results_enabled: argv["jsd-api-results-enabled"], + fight_mode: argv["fight-mode"], + stale_zone_configuration: { + optimize_wordpress: + argv["stale-zone-configuration-optimize-wordpress"], + sbfm_definitely_automated: resolveFileToken( + argv["stale-zone-configuration-sbfm-definitely-automated"] as + | string + | undefined, + "stale-zone-configuration-sbfm-definitely-automated", + "text" + ), + sbfm_likely_automated: resolveFileToken( + argv["stale-zone-configuration-sbfm-likely-automated"] as + | string + | undefined, + "stale-zone-configuration-sbfm-likely-automated", + "text" + ), + sbfm_static_resource_protection: resolveFileToken( + argv["stale-zone-configuration-sbfm-static-resource-protection"] as + | string + | undefined, + "stale-zone-configuration-sbfm-static-resource-protection", + "text" + ), + sbfm_verified_bots: resolveFileToken( + argv["stale-zone-configuration-sbfm-verified-bots"] as + | string + | undefined, + "stale-zone-configuration-sbfm-verified-bots", + "text" + ), + suppress_session_score: + argv["stale-zone-configuration-suppress-session-score"], + fight_mode: argv["stale-zone-configuration-fight-mode"], + }, + optimize_wordpress: argv["optimize-wordpress"], + sbfm_definitely_automated: argv["sbfm-definitely-automated"], + sbfm_static_resource_protection: + argv["sbfm-static-resource-protection"], + sbfm_verified_bots: argv["sbfm-verified-bots"], + sbfm_likely_automated: argv["sbfm-likely-automated"], + auto_update_model: argv["auto-update-model"], + bm_cookie_enabled: argv["bm-cookie-enabled"], + suppress_session_score: argv["suppress-session-score"], + }); + const result = await withProgress(`Updating`, async () => + client.send(operation, { body: bodyData, zone_id: zoneId }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/bot-management/update.ts b/packages/cli/src/commands/_generated/bot-management/update.ts index 28ccc8ea81..f328372d45 100644 --- a/packages/cli/src/commands/_generated/bot-management/update.ts +++ b/packages/cli/src/commands/_generated/bot-management/update.ts @@ -1,469 +1,283 @@ -import operation from "../_operations/bot-management/update.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * update command * @generated from apis/overlays/bot-management.ts */ -import type { Argv, CommandModule } from "yargs"; -import { createCommandClient, getZoneId } from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; +import { + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - '$0 bot-management update\n\nUpdates the Bot Management configuration for a zone. This API is used to update: - **Bot Fight Mode** - **Super Bot Fight Mode** - **Bot Management for Enterprise** See [Bot Plans](https://developers.cloudflare.com/bots/plans/) for more information on the different plans \\ If you recently upgraded or downgraded your plan, refer to the following examples to clean up old configurations. Copy and paste the example body to remove old zone configurations based on your current plan. #### Clean up configuration for Bot Fight Mode plan ```json { "sbfm_likely_automated": "allow", "sbfm_definitely_automated": "allow", "sbfm_verified_bots": "allow", "sbfm_static_resource_protection": false, "optimize_wordpress": false, "suppress_session_score": false } ``` #### Clean up configuration for SBFM Pro plan ```json { "sbfm_likely_automated": "allow", "fight_mode": false } ``` #### Clean up configuration for SBFM Biz plan ```json { "fight_mode": false } ``` #### Clean up configuration for BM Enterprise Subscription plan It is strongly recommended that you ensure you have [custom rules](https://developers.cloudflare.com/waf/custom-rules/) in place to protect your zone before disabling the SBFM rules. Without these protections, your zone is vulnerable to attacks. ```json { "sbfm_likely_automated": "allow", "sbfm_definitely_automated": "allow", "sbfm_verified_bots": "allow", "sbfm_static_resource_protection": false, "optimize_wordpress": false, "fight_mode": false } ```' - ) - .option("ai-agents-anthropic-agent", { - type: "string", - description: "Action to apply to one supported personal AI agent.", +const parameters = { + flags: { + "ai-agents-anthropic-agent": { + kind: "parsed", + brief: "Action to apply to one supported personal AI agent.", + optional: true, choices: ["disabled", "block", "only_on_ad_pages"], - }) - .coerce("ai-agents-anthropic-agent", (value) => - resolveFileToken(value, "ai-agents-anthropic-agent", "text") - ) - .option("ai-agents-google-agent", { - type: "string", - description: "Action to apply to one supported personal AI agent.", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "ai-agents-anthropic-agent", "text"), + }, + "ai-agents-google-agent": { + kind: "parsed", + brief: "Action to apply to one supported personal AI agent.", + optional: true, choices: ["disabled", "block", "only_on_ad_pages"], - }) - .coerce("ai-agents-google-agent", (value) => - resolveFileToken(value, "ai-agents-google-agent", "text") - ) - .option("ai-agents-instinct", { - type: "string", - description: "Action to apply to one supported personal AI agent.", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "ai-agents-google-agent", "text"), + }, + "ai-agents-instinct": { + kind: "parsed", + brief: "Action to apply to one supported personal AI agent.", + optional: true, choices: ["disabled", "block", "only_on_ad_pages"], - }) - .coerce("ai-agents-instinct", (value) => - resolveFileToken(value, "ai-agents-instinct", "text") - ) - .option("ai-agents-muse", { - type: "string", - description: "Action to apply to one supported personal AI agent.", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "ai-agents-instinct", "text"), + }, + "ai-agents-muse": { + kind: "parsed", + brief: "Action to apply to one supported personal AI agent.", + optional: true, choices: ["disabled", "block", "only_on_ad_pages"], - }) - .coerce("ai-agents-muse", (value) => - resolveFileToken(value, "ai-agents-muse", "text") - ) - .option("ai-agents-openai-agent", { - type: "string", - description: "Action to apply to one supported personal AI agent.", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "ai-agents-muse", "text"), + }, + "ai-agents-openai-agent": { + kind: "parsed", + brief: "Action to apply to one supported personal AI agent.", + optional: true, choices: ["disabled", "block", "only_on_ad_pages"], - }) - .coerce("ai-agents-openai-agent", (value) => - resolveFileToken(value, "ai-agents-openai-agent", "text") - ) - .option("ai-bots-migration-opt-out", { - type: "boolean", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "ai-agents-openai-agent", "text"), + }, + "ai-bots-migration-opt-out": { + kind: "boolean", + brief: "Temporary migration flag tracking zones opted out of AI bots managed-rule updates.", - }) - .option("ai-bots-protection", { - type: "string", - description: "Enable rule to block AI Scrapers and Crawlers.", + optional: true, + }, + "ai-bots-protection": { + kind: "parsed", + brief: "Enable rule to block AI Scrapers and Crawlers.", + optional: true, choices: ["block", "disabled", "only_on_ad_pages"], - }) - .coerce("ai-bots-protection", (value) => - resolveFileToken(value, "ai-bots-protection", "text") - ) - .option("ai-search", { - type: "string", - description: "Configure robots.txt policy for AI search bots.", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "ai-bots-protection", "text"), + }, + "ai-search": { + kind: "parsed", + brief: "Configure robots.txt policy for AI search bots.", + optional: true, choices: ["disabled", "block", "only_on_ad_pages"], - }) - .coerce("ai-search", (value) => - resolveFileToken(value, "ai-search", "text") - ) - .option("ai-training", { - type: "string", - description: "Configure robots.txt policy for AI model training bots.", + parse: String, + coerce: (value: string) => resolveFileToken(value, "ai-search", "text"), + }, + "ai-training": { + kind: "parsed", + brief: "Configure robots.txt policy for AI model training bots.", + optional: true, choices: ["disabled", "disallow", "block", "only_on_ad_pages"], - }) - .coerce("ai-training", (value) => - resolveFileToken(value, "ai-training", "text") - ) - .option("ai-user", { - type: "string", - description: - "Configure robots.txt policy for AI assistant and agent bots.", + parse: String, + coerce: (value: string) => resolveFileToken(value, "ai-training", "text"), + }, + "ai-user": { + kind: "parsed", + brief: "Configure robots.txt policy for AI assistant and agent bots.", + optional: true, choices: ["disabled", "block", "only_on_ad_pages"], - }) - .coerce("ai-user", (value) => resolveFileToken(value, "ai-user", "text")) - .option("bot-preference-sync-enabled", { - type: "boolean", - description: + parse: String, + coerce: (value: string) => resolveFileToken(value, "ai-user", "text"), + }, + "bot-preference-sync-enabled": { + kind: "boolean", + brief: "Enable Bot Preference Sync for this zone. When enabled, Cloudflare can serve robots.txt content derived from the zone's AI Search, AI User, and AI Training preferences.", - }) - .option("cf-robots-variant", { - type: "string", - description: - "Specifies the Robots Access Control License variant to use.", + optional: true, + }, + "cf-robots-variant": { + kind: "parsed", + brief: "Specifies the Robots Access Control License variant to use.", + optional: true, choices: ["off", "policy_only"], - }) - .coerce("cf-robots-variant", (value) => - resolveFileToken(value, "cf-robots-variant", "text") - ) - .option("content-bots-protection", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "cf-robots-variant", "text"), + }, + "content-bots-protection": { + kind: "parsed", + brief: "Enable rule to block content bots. When enabled, blocks automated traffic with low bot scores, excluding safe verified bot categories. Exceptions should be managed via skip rules.", + optional: true, choices: ["block", "disabled"], - }) - .coerce("content-bots-protection", (value) => - resolveFileToken(value, "content-bots-protection", "text") - ) - .option("crawler-protection", { - type: "string", - description: - "Enable rule to punish AI Scrapers and Crawlers via a link maze.", + parse: String, + coerce: (value: string) => + resolveFileToken(value, "content-bots-protection", "text"), + }, + "crawler-protection": { + kind: "parsed", + brief: "Enable rule to punish AI Scrapers and Crawlers via a link maze.", + optional: true, choices: ["enabled", "disabled"], - }) - .coerce("crawler-protection", (value) => - resolveFileToken(value, "crawler-protection", "text") - ) - .option("enable-js", { - type: "boolean", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "crawler-protection", "text"), + }, + "enable-js": { + kind: "boolean", + brief: "Use lightweight, invisible JavaScript detections to improve Bot Management. [Learn more about JavaScript Detections](https://developers.cloudflare.com/bots/reference/javascript-detections/).", - }) - .option("is-robots-txt-managed", { - type: "boolean", - description: + optional: true, + }, + "is-robots-txt-managed": { + kind: "boolean", + brief: "Enable cloudflare managed robots.txt. If an existing robots.txt is detected, then managed robots.txt will be prepended to the existing robots.txt.", - }) - .option("jsd-api-results-enabled", { - type: "boolean", - description: + optional: true, + }, + "jsd-api-results-enabled": { + kind: "boolean", + brief: "Whether to use JavaScript Detection results submitted through the API for this zone.", - }) - .option("fight-mode", { - type: "boolean", - description: "Whether to enable Bot Fight Mode.", - }) - .option("stale-zone-configuration-optimize-wordpress", { - type: "boolean", - description: + optional: true, + }, + "fight-mode": { + kind: "boolean", + brief: "Whether to enable Bot Fight Mode.", + optional: true, + }, + "stale-zone-configuration-optimize-wordpress": { + kind: "boolean", + brief: "Indicates that the zone's wordpress optimization for SBFM is turned on.", - }) - .option("stale-zone-configuration-sbfm-definitely-automated", { - type: "string", - description: + optional: true, + }, + "stale-zone-configuration-sbfm-definitely-automated": { + kind: "parsed", + brief: "Indicates that the zone's definitely automated requests are being blocked or challenged.", - }) - .option("stale-zone-configuration-sbfm-likely-automated", { - type: "string", - description: + optional: true, + parse: String, + }, + "stale-zone-configuration-sbfm-likely-automated": { + kind: "parsed", + brief: "Indicates that the zone's likely automated requests are being blocked or challenged.", - }) - .option("stale-zone-configuration-sbfm-static-resource-protection", { - type: "string", - description: + optional: true, + parse: String, + }, + "stale-zone-configuration-sbfm-static-resource-protection": { + kind: "parsed", + brief: "Indicates that the zone's static resource protection is turned on.", - }) - .option("stale-zone-configuration-sbfm-verified-bots", { - type: "string", - description: + optional: true, + parse: String, + }, + "stale-zone-configuration-sbfm-verified-bots": { + kind: "parsed", + brief: "Indicates that the zone's verified bot requests are being blocked.", - }) - .option("stale-zone-configuration-suppress-session-score", { - type: "boolean", - description: - "Indicates that the zone's session score tracking is disabled.", - }) - .option("stale-zone-configuration-fight-mode", { - type: "boolean", - description: "Indicates that the zone's Bot Fight Mode is turned on.", - }) - .option("optimize-wordpress", { - type: "boolean", - description: + optional: true, + parse: String, + }, + "stale-zone-configuration-suppress-session-score": { + kind: "boolean", + brief: "Indicates that the zone's session score tracking is disabled.", + optional: true, + }, + "stale-zone-configuration-fight-mode": { + kind: "boolean", + brief: "Indicates that the zone's Bot Fight Mode is turned on.", + optional: true, + }, + "optimize-wordpress": { + kind: "boolean", + brief: "Whether to optimize Super Bot Fight Mode protections for Wordpress.", - }) - .option("sbfm-definitely-automated", { - type: "string", - description: + optional: true, + }, + "sbfm-definitely-automated": { + kind: "parsed", + brief: "Super Bot Fight Mode (SBFM) action to take on definitely automated requests.", + optional: true, choices: ["allow", "block", "managed_challenge"], - }) - .coerce("sbfm-definitely-automated", (value) => - resolveFileToken(value, "sbfm-definitely-automated", "text") - ) - .option("sbfm-static-resource-protection", { - type: "boolean", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "sbfm-definitely-automated", "text"), + }, + "sbfm-static-resource-protection": { + kind: "boolean", + brief: "Super Bot Fight Mode (SBFM) to enable static resource protection.\nEnable if static resources on your application need bot protection.\nNote: Static resource protection can also result in legitimate traffic being blocked.", - }) - .option("sbfm-verified-bots", { - type: "string", - description: + optional: true, + }, + "sbfm-verified-bots": { + kind: "parsed", + brief: "Super Bot Fight Mode (SBFM) action to take on verified bots requests.", + optional: true, choices: ["allow", "block"], - }) - .coerce("sbfm-verified-bots", (value) => - resolveFileToken(value, "sbfm-verified-bots", "text") - ) - .option("sbfm-likely-automated", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "sbfm-verified-bots", "text"), + }, + "sbfm-likely-automated": { + kind: "parsed", + brief: "Super Bot Fight Mode (SBFM) action to take on likely automated requests.", + optional: true, choices: ["allow", "block", "managed_challenge"], - }) - .coerce("sbfm-likely-automated", (value) => - resolveFileToken(value, "sbfm-likely-automated", "text") - ) - .option("auto-update-model", { - type: "boolean", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "sbfm-likely-automated", "text"), + }, + "auto-update-model": { + kind: "boolean", + brief: "Automatically update to the newest bot detection models created by Cloudflare as they are released. [Learn more.](https://developers.cloudflare.com/bots/reference/machine-learning-models#model-versions-and-release-notes)", - }) - .option("bm-cookie-enabled", { - type: "boolean", - description: + optional: true, + }, + "bm-cookie-enabled": { + kind: "boolean", + brief: "Indicates that the bot management cookie can be placed on end user devices accessing the site. Defaults to true", - }) - .option("suppress-session-score", { - type: "boolean", - description: + optional: true, + }, + "suppress-session-score": { + kind: "boolean", + brief: "Whether to disable tracking the highest bot score for a session in the Bot Management cookie.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "update", describe: "Update Zone Bot Management Config", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "bot-management update", - classification: { - safeFlags: [ - "ai-agents-anthropic-agent", - "ai-agents-google-agent", - "ai-agents-instinct", - "ai-agents-muse", - "ai-agents-openai-agent", - "ai-bots-migration-opt-out", - "ai-bots-protection", - "ai-search", - "ai-training", - "ai-user", - "bot-preference-sync-enabled", - "cf-robots-variant", - "content-bots-protection", - "crawler-protection", - "enable-js", - "is-robots-txt-managed", - "jsd-api-results-enabled", - "fight-mode", - "stale-zone-configuration-optimize-wordpress", - "stale-zone-configuration-suppress-session-score", - "stale-zone-configuration-fight-mode", - "optimize-wordpress", - "sbfm-definitely-automated", - "sbfm-static-resource-protection", - "sbfm-verified-bots", - "sbfm-likely-automated", - "auto-update-model", - "bm-cookie-enabled", - "suppress-session-score", - "dry-run", - ], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - formatDryRun({ - command: "cf bot-management update", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/zones/${argv.zone ?? argv.zoneId ?? ""}/bot_management`, - pathParams: { - "zone-id": String(argv.zone ?? argv["zone-id"] ?? ""), - }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - ai_agents: { - anthropic_agent: argv["ai-agents-anthropic-agent"], - google_agent: argv["ai-agents-google-agent"], - instinct: argv["ai-agents-instinct"], - muse: argv["ai-agents-muse"], - openai_agent: argv["ai-agents-openai-agent"], - }, - ai_bots_migration_opt_out: - argv["ai-bots-migration-opt-out"], - ai_bots_protection: argv["ai-bots-protection"], - ai_search: argv["ai-search"], - ai_training: argv["ai-training"], - ai_user: argv["ai-user"], - bot_preference_sync_enabled: - argv["bot-preference-sync-enabled"], - cf_robots_variant: argv["cf-robots-variant"], - content_bots_protection: argv["content-bots-protection"], - crawler_protection: argv["crawler-protection"], - enable_js: argv["enable-js"], - is_robots_txt_managed: argv["is-robots-txt-managed"], - jsd_api_results_enabled: argv["jsd-api-results-enabled"], - fight_mode: argv["fight-mode"], - stale_zone_configuration: { - optimize_wordpress: - argv["stale-zone-configuration-optimize-wordpress"], - sbfm_definitely_automated: resolveFileToken( - argv[ - "stale-zone-configuration-sbfm-definitely-automated" - ] as string | undefined, - "stale-zone-configuration-sbfm-definitely-automated", - "text" - ), - sbfm_likely_automated: resolveFileToken( - argv[ - "stale-zone-configuration-sbfm-likely-automated" - ] as string | undefined, - "stale-zone-configuration-sbfm-likely-automated", - "text" - ), - sbfm_static_resource_protection: resolveFileToken( - argv[ - "stale-zone-configuration-sbfm-static-resource-protection" - ] as string | undefined, - "stale-zone-configuration-sbfm-static-resource-protection", - "text" - ), - sbfm_verified_bots: resolveFileToken( - argv["stale-zone-configuration-sbfm-verified-bots"] as - | string - | undefined, - "stale-zone-configuration-sbfm-verified-bots", - "text" - ), - suppress_session_score: - argv["stale-zone-configuration-suppress-session-score"], - fight_mode: argv["stale-zone-configuration-fight-mode"], - }, - optimize_wordpress: argv["optimize-wordpress"], - sbfm_definitely_automated: - argv["sbfm-definitely-automated"], - sbfm_static_resource_protection: - argv["sbfm-static-resource-protection"], - sbfm_verified_bots: argv["sbfm-verified-bots"], - sbfm_likely_automated: argv["sbfm-likely-automated"], - auto_update_model: argv["auto-update-model"], - bm_cookie_enabled: argv["bm-cookie-enabled"], - suppress_session_score: argv["suppress-session-score"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const zoneId = await getZoneId({ zone: argv.zone }, client, { - quiet: argv.quiet, - }); - argv.zoneId = zoneId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Updated` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - ai_agents: { - anthropic_agent: argv["ai-agents-anthropic-agent"], - google_agent: argv["ai-agents-google-agent"], - instinct: argv["ai-agents-instinct"], - muse: argv["ai-agents-muse"], - openai_agent: argv["ai-agents-openai-agent"], - }, - ai_bots_migration_opt_out: argv["ai-bots-migration-opt-out"], - ai_bots_protection: argv["ai-bots-protection"], - ai_search: argv["ai-search"], - ai_training: argv["ai-training"], - ai_user: argv["ai-user"], - bot_preference_sync_enabled: argv["bot-preference-sync-enabled"], - cf_robots_variant: argv["cf-robots-variant"], - content_bots_protection: argv["content-bots-protection"], - crawler_protection: argv["crawler-protection"], - enable_js: argv["enable-js"], - is_robots_txt_managed: argv["is-robots-txt-managed"], - jsd_api_results_enabled: argv["jsd-api-results-enabled"], - fight_mode: argv["fight-mode"], - stale_zone_configuration: { - optimize_wordpress: - argv["stale-zone-configuration-optimize-wordpress"], - sbfm_definitely_automated: resolveFileToken( - argv["stale-zone-configuration-sbfm-definitely-automated"] as - | string - | undefined, - "stale-zone-configuration-sbfm-definitely-automated", - "text" - ), - sbfm_likely_automated: resolveFileToken( - argv["stale-zone-configuration-sbfm-likely-automated"] as - | string - | undefined, - "stale-zone-configuration-sbfm-likely-automated", - "text" - ), - sbfm_static_resource_protection: resolveFileToken( - argv[ - "stale-zone-configuration-sbfm-static-resource-protection" - ] as string | undefined, - "stale-zone-configuration-sbfm-static-resource-protection", - "text" - ), - sbfm_verified_bots: resolveFileToken( - argv["stale-zone-configuration-sbfm-verified-bots"] as - | string - | undefined, - "stale-zone-configuration-sbfm-verified-bots", - "text" - ), - suppress_session_score: - argv["stale-zone-configuration-suppress-session-score"], - fight_mode: argv["stale-zone-configuration-fight-mode"], - }, - optimize_wordpress: argv["optimize-wordpress"], - sbfm_definitely_automated: argv["sbfm-definitely-automated"], - sbfm_static_resource_protection: - argv["sbfm-static-resource-protection"], - sbfm_verified_bots: argv["sbfm-verified-bots"], - sbfm_likely_automated: argv["sbfm-likely-automated"], - auto_update_model: argv["auto-update-model"], - bm_cookie_enabled: argv["bm-cookie-enabled"], - suppress_session_score: argv["suppress-session-score"], - }); - const result = await withProgress(`Updating`, async () => - client.send(operation, { body: bodyData, zone_id: zoneId }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + '$0 bot-management update\n\nUpdates the Bot Management configuration for a zone. This API is used to update: - **Bot Fight Mode** - **Super Bot Fight Mode** - **Bot Management for Enterprise** See [Bot Plans](https://developers.cloudflare.com/bots/plans/) for more information on the different plans \\ If you recently upgraded or downgraded your plan, refer to the following examples to clean up old configurations. Copy and paste the example body to remove old zone configurations based on your current plan. #### Clean up configuration for Bot Fight Mode plan ```json { "sbfm_likely_automated": "allow", "sbfm_definitely_automated": "allow", "sbfm_verified_bots": "allow", "sbfm_static_resource_protection": false, "optimize_wordpress": false, "suppress_session_score": false } ``` #### Clean up configuration for SBFM Pro plan ```json { "sbfm_likely_automated": "allow", "fight_mode": false } ``` #### Clean up configuration for SBFM Biz plan ```json { "fight_mode": false } ``` #### Clean up configuration for BM Enterprise Subscription plan It is strongly recommended that you ensure you have [custom rules](https://developers.cloudflare.com/waf/custom-rules/) in place to protect your zone before disabling the SBFM rules. Without these protections, your zone is vulnerable to attacks. ```json { "sbfm_likely_automated": "allow", "sbfm_definitely_automated": "allow", "sbfm_verified_bots": "allow", "sbfm_static_resource_protection": false, "optimize_wordpress": false, "fight_mode": false } ```', + ...parameters, + loader: () => import("./update.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/botnet-feed/asn/day-report.handler.ts b/packages/cli/src/commands/_generated/botnet-feed/asn/day-report.handler.ts new file mode 100644 index 0000000000..51026d9a89 --- /dev/null +++ b/packages/cli/src/commands/_generated/botnet-feed/asn/day-report.handler.ts @@ -0,0 +1,54 @@ +import operation from "../../_operations/botnet-feed/asn/day-report.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./day-report.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "botnet-feed asn day-report", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + date: argv["date"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf botnet-feed asn day-report", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/botnet_feed/asn/${argv["asn-id"] == null ? "" : encodeURIComponent(String(argv["asn-id"]))}/day_report`, + pathParams: { "asn-id": String(argv["asn-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + asn_id: argv["asn-id"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/botnet-feed/asn/day-report.ts b/packages/cli/src/commands/_generated/botnet-feed/asn/day-report.ts index 97ea1f5b45..b2aa4d947f 100644 --- a/packages/cli/src/commands/_generated/botnet-feed/asn/day-report.ts +++ b/packages/cli/src/commands/_generated/botnet-feed/asn/day-report.ts @@ -1,85 +1,32 @@ -import operation from "../../_operations/botnet-feed/asn/day-report.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * day-report command * @generated from apis/overlays/botnet-feed.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 botnet-feed asn day-report \n\nGets all the data the botnet tracking database has for a given ASN registered to user account for given date. If no date is given, it will return results for the previous day." - ) - .positional("asn-id", { - type: "string", - description: "Asn ID", - demandOption: true, - }) - .option("date", { type: "string", description: "Date" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + date: { kind: "parsed", brief: "Date", optional: true, parse: String }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "asn-id", brief: "Asn ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "day-report ", describe: "Get daily report", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "botnet-feed asn day-report", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - date: argv["date"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf botnet-feed asn day-report", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/botnet_feed/asn/${argv["asn-id"] == null ? "" : encodeURIComponent(String(argv["asn-id"]))}/day_report`, - pathParams: { "asn-id": String(argv["asn-id"] ?? "") }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - asn_id: argv["asn-id"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 botnet-feed asn day-report \n\nGets all the data the botnet tracking database has for a given ASN registered to user account for given date. If no date is given, it will return results for the previous day.", + ...parameters, + loader: () => import("./day-report.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/botnet-feed/asn/full-report.handler.ts b/packages/cli/src/commands/_generated/botnet-feed/asn/full-report.handler.ts new file mode 100644 index 0000000000..2c00423c41 --- /dev/null +++ b/packages/cli/src/commands/_generated/botnet-feed/asn/full-report.handler.ts @@ -0,0 +1,49 @@ +import operation from "../../_operations/botnet-feed/asn/full-report.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./full-report.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "botnet-feed asn full-report", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf botnet-feed asn full-report", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/botnet_feed/asn/${argv["asn-id"] == null ? "" : encodeURIComponent(String(argv["asn-id"]))}/full_report`, + pathParams: { "asn-id": String(argv["asn-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + asn_id: argv["asn-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/botnet-feed/asn/full-report.ts b/packages/cli/src/commands/_generated/botnet-feed/asn/full-report.ts index d689e23d57..8e07109495 100644 --- a/packages/cli/src/commands/_generated/botnet-feed/asn/full-report.ts +++ b/packages/cli/src/commands/_generated/botnet-feed/asn/full-report.ts @@ -1,79 +1,31 @@ -import operation from "../../_operations/botnet-feed/asn/full-report.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * full-report command * @generated from apis/overlays/botnet-feed.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 botnet-feed asn full-report \n\nGets all the data the botnet threat feed tracking database has for a given ASN registered to user account." - ) - .positional("asn-id", { - type: "string", - description: "Asn ID", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "asn-id", brief: "Asn ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "full-report ", describe: "Get full report", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "botnet-feed asn full-report", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf botnet-feed asn full-report", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/botnet_feed/asn/${argv["asn-id"] == null ? "" : encodeURIComponent(String(argv["asn-id"]))}/full_report`, - pathParams: { "asn-id": String(argv["asn-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - asn_id: argv["asn-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 botnet-feed asn full-report \n\nGets all the data the botnet threat feed tracking database has for a given ASN registered to user account.", + ...parameters, + loader: () => import("./full-report.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/botnet-feed/asn/index.ts b/packages/cli/src/commands/_generated/botnet-feed/asn/index.ts index bcabff34ef..3b62dbe1c2 100644 --- a/packages/cli/src/commands/_generated/botnet-feed/asn/index.ts +++ b/packages/cli/src/commands/_generated/botnet-feed/asn/index.ts @@ -1,25 +1,20 @@ import $dayreport from "./day-report.js"; import $fullreport from "./full-report.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * asn command group * @generated from apis/overlays/botnet-feed.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "asn", describe: "ASN-level botnet activity data showing networks with known C2 infrastructure", - builder: (yargs) => { - return yargs - .command($dayreport) - .command($fullreport) - .demandCommand(1, "Please specify a subcommand"); + routes: { + "day-report": $dayreport, + "full-report": $fullreport, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/botnet-feed/configs/asn/delete.handler.ts b/packages/cli/src/commands/_generated/botnet-feed/configs/asn/delete.handler.ts new file mode 100644 index 0000000000..59332b0d4a --- /dev/null +++ b/packages/cli/src/commands/_generated/botnet-feed/configs/asn/delete.handler.ts @@ -0,0 +1,55 @@ +import operation from "../../../_operations/botnet-feed/configs/asn/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "botnet-feed configs asn delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf botnet-feed configs asn delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/botnet_feed/configs/asn/${argv["asn-id"] == null ? "" : encodeURIComponent(String(argv["asn-id"]))}`, + pathParams: { "asn-id": String(argv["asn-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + asn_id: argv["asn-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/botnet-feed/configs/asn/delete.ts b/packages/cli/src/commands/_generated/botnet-feed/configs/asn/delete.ts index beccebea12..37d843e92c 100644 --- a/packages/cli/src/commands/_generated/botnet-feed/configs/asn/delete.ts +++ b/packages/cli/src/commands/_generated/botnet-feed/configs/asn/delete.ts @@ -1,91 +1,37 @@ -import operation from "../../../_operations/botnet-feed/configs/asn/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/botnet-feed.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 botnet-feed configs asn delete \n\nDelete an ASN from botnet threat feed for a given user." - ) - .positional("asn-id", { - type: "string", - description: "Asn ID", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "asn-id", brief: "Asn ID", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete an ASN", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "botnet-feed configs asn delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf botnet-feed configs asn delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/botnet_feed/configs/asn/${argv["asn-id"] == null ? "" : encodeURIComponent(String(argv["asn-id"]))}`, - pathParams: { "asn-id": String(argv["asn-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - asn_id: argv["asn-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 botnet-feed configs asn delete \n\nDelete an ASN from botnet threat feed for a given user.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/botnet-feed/configs/asn/get.handler.ts b/packages/cli/src/commands/_generated/botnet-feed/configs/asn/get.handler.ts new file mode 100644 index 0000000000..58ebad882e --- /dev/null +++ b/packages/cli/src/commands/_generated/botnet-feed/configs/asn/get.handler.ts @@ -0,0 +1,46 @@ +import operation from "../../../_operations/botnet-feed/configs/asn/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "botnet-feed configs asn get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf botnet-feed configs asn get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/botnet_feed/configs/asn`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/botnet-feed/configs/asn/get.ts b/packages/cli/src/commands/_generated/botnet-feed/configs/asn/get.ts index 1d81842e3f..df00c7e151 100644 --- a/packages/cli/src/commands/_generated/botnet-feed/configs/asn/get.ts +++ b/packages/cli/src/commands/_generated/botnet-feed/configs/asn/get.ts @@ -1,71 +1,31 @@ -import operation from "../../../_operations/botnet-feed/configs/asn/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/botnet-feed.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 botnet-feed configs asn get\n\nGets a list of all ASNs registered for a user for the DDoS Botnet Feed API." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "Get list of ASNs", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "botnet-feed configs asn get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf botnet-feed configs asn get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/botnet_feed/configs/asn`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 botnet-feed configs asn get\n\nGets a list of all ASNs registered for a user for the DDoS Botnet Feed API.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/botnet-feed/configs/asn/index.ts b/packages/cli/src/commands/_generated/botnet-feed/configs/asn/index.ts index eb2310df9a..8ee4cfad74 100644 --- a/packages/cli/src/commands/_generated/botnet-feed/configs/asn/index.ts +++ b/packages/cli/src/commands/_generated/botnet-feed/configs/asn/index.ts @@ -1,24 +1,19 @@ import $delete from "./delete.js"; import $get from "./get.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * asn command group * @generated from apis/overlays/botnet-feed.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "asn", describe: "Operations for configs.asn", - builder: (yargs) => { - return yargs - .command($delete) - .command($get) - .demandCommand(1, "Please specify a subcommand"); + routes: { + delete: $delete, + get: $get, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/botnet-feed/configs/index.ts b/packages/cli/src/commands/_generated/botnet-feed/configs/index.ts index 0e8bc2335e..c9b007dfec 100644 --- a/packages/cli/src/commands/_generated/botnet-feed/configs/index.ts +++ b/packages/cli/src/commands/_generated/botnet-feed/configs/index.ts @@ -1,21 +1,18 @@ import $asn from "./asn/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * configs command group * @generated from apis/overlays/botnet-feed.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "configs", describe: "Botnet feed subscription configuration and notification preferences", - builder: (yargs) => { - return yargs.command($asn).demandCommand(1, "Please specify a subcommand"); + routes: { + asn: $asn, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/botnet-feed/index.ts b/packages/cli/src/commands/_generated/botnet-feed/index.ts index 5d827db809..d158465cbe 100644 --- a/packages/cli/src/commands/_generated/botnet-feed/index.ts +++ b/packages/cli/src/commands/_generated/botnet-feed/index.ts @@ -1,25 +1,20 @@ import $asn from "./asn/index.js"; import $configs from "./configs/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * botnet-feed command * @generated from apis/overlays/botnet-feed.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "botnet-feed", describe: "Botnet threat intelligence feeds — IP and ASN-level data on known command-and-control infrastructure", - builder: (yargs) => { - return yargs - .command($asn) - .command($configs) - .demandCommand(1, "Please specify a subcommand"); + routes: { + asn: $asn, + configs: $configs, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/brand-protection/index.ts b/packages/cli/src/commands/_generated/brand-protection/index.ts index aca9575953..fcb506bb77 100644 --- a/packages/cli/src/commands/_generated/brand-protection/index.ts +++ b/packages/cli/src/commands/_generated/brand-protection/index.ts @@ -6,31 +6,26 @@ import $submit from "./submit.js"; import $trial from "./trial/index.js"; import $urlinfo from "./url-info.js"; import $urls from "./urls/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * brand-protection command * @generated from apis/overlays/brand-protection.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "brand-protection", describe: "brand-protection", - builder: (yargs) => { - return yargs - .command($submit) - .command($urlinfo) - .command($logomatches) - .command($logos) - .command($matches) - .command($queries) - .command($trial) - .command($urls) - .demandCommand(1, "Please specify a subcommand"); + routes: { + submit: $submit, + "url-info": $urlinfo, + "logo-matches": $logomatches, + logos: $logos, + matches: $matches, + queries: $queries, + trial: $trial, + urls: $urls, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/brand-protection/logo-matches/get.handler.ts b/packages/cli/src/commands/_generated/brand-protection/logo-matches/get.handler.ts new file mode 100644 index 0000000000..f445d6ba5d --- /dev/null +++ b/packages/cli/src/commands/_generated/brand-protection/logo-matches/get.handler.ts @@ -0,0 +1,55 @@ +import operation from "../../_operations/brand-protection/logo-matches/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "brand-protection logo-matches get", + classification: { + safeFlags: ["order-by", "order", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + offset: argv["offset"], + limit: argv["limit"], + query_id: argv["query-id"], + download: argv["download"], + orderBy: argv["order-by"], + order: argv["order"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf brand-protection logo-matches get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/logo/matches`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/brand-protection/logo-matches/get.ts b/packages/cli/src/commands/_generated/brand-protection/logo-matches/get.ts index ae1bc84e6c..5e10360fb7 100644 --- a/packages/cli/src/commands/_generated/brand-protection/logo-matches/get.ts +++ b/packages/cli/src/commands/_generated/brand-protection/logo-matches/get.ts @@ -1,109 +1,68 @@ -import operation from "../../_operations/brand-protection/logo-matches/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/brand-protection.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 brand-protection logo-matches get\n\nLists images that matched a saved logo query, most recently matched first by default. Set `download=true` to include each matched image as base64 data." - ) - .option("offset", { - type: "string", - description: "Number of matches to skip, for pagination. Defaults to 0.", - }) - .option("limit", { - type: "string", - description: "Maximum number of matches to return. Defaults to 50.", - }) - .option("query-id", { - type: "string", - description: "ID of the logo query whose matches to list.", - demandOption: true, - }) - .option("download", { - type: "string", - description: +const parameters = { + flags: { + offset: { + kind: "parsed", + brief: "Number of matches to skip, for pagination. Defaults to 0.", + optional: true, + parse: String, + }, + limit: { + kind: "parsed", + brief: "Maximum number of matches to return. Defaults to 50.", + optional: true, + parse: String, + }, + "query-id": { + kind: "parsed", + brief: "ID of the logo query whose matches to list.", + parse: String, + }, + download: { + kind: "parsed", + brief: "Set to `true` to include each matched image as base64 data in `image_data`, with its MIME type in `content_type`.", - }) - .option("order-by", { - type: "string", - description: + optional: true, + parse: String, + }, + "order-by": { + kind: "enum", + brief: "Field to sort by: `matchedAt`, `domain`, `similarityScore`, or `registrar`. Defaults to `matchedAt`.", - choices: ["matchedAt", "domain", "similarityScore", "registrar"], - }) - .option("order", { - type: "string", - description: "Sort direction: `asc` or `desc`. Defaults to `desc`.", - choices: ["asc", "desc"], - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + values: ["matchedAt", "domain", "similarityScore", "registrar"], + optional: true, + }, + order: { + kind: "enum", + brief: "Sort direction: `asc` or `desc`. Defaults to `desc`.", + values: ["asc", "desc"], + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "List logo matches", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "brand-protection logo-matches get", - classification: { - safeFlags: ["order-by", "order", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - offset: argv["offset"], - limit: argv["limit"], - query_id: argv["query-id"], - download: argv["download"], - orderBy: argv["order-by"], - order: argv["order"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf brand-protection logo-matches get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/logo/matches`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 brand-protection logo-matches get\n\nLists images that matched a saved logo query, most recently matched first by default. Set `download=true` to include each matched image as base64 data.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/brand-protection/logo-matches/index.ts b/packages/cli/src/commands/_generated/brand-protection/logo-matches/index.ts index 268fe51f88..4776323bc2 100644 --- a/packages/cli/src/commands/_generated/brand-protection/logo-matches/index.ts +++ b/packages/cli/src/commands/_generated/brand-protection/logo-matches/index.ts @@ -1,20 +1,17 @@ import $get from "./get.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * logo-matches command group * @generated from apis/overlays/brand-protection.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "logo-matches", describe: "Operations for logo-matches", - builder: (yargs) => { - return yargs.command($get).demandCommand(1, "Please specify a subcommand"); + routes: { + get: $get, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/brand-protection/logos/create.handler.ts b/packages/cli/src/commands/_generated/brand-protection/logos/create.handler.ts new file mode 100644 index 0000000000..76decbe004 --- /dev/null +++ b/packages/cli/src/commands/_generated/brand-protection/logos/create.handler.ts @@ -0,0 +1,111 @@ +import operation from "../../_operations/brand-protection/logos/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "brand-protection logos create", + classification: { + safeFlags: ["search-lookback", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["image-data"] === undefined) { + argv["image-data"] = await promptForRequiredField( + "image-data", + "Base64 encoded image data. Can include data URI prefix (e.g., 'data:image/png;base64,...') or just the base64 string. Supported formats: PNG, JPEG, GIF, WebP, BMP, and SVG. ICO is also accepted when the data includes a \`data:image/x-icon;base64,\` prefix." + ); + } + if (argv["similarity-threshold"] === undefined) { + throw new Error( + "--similarity-threshold is required (or pass --body with this field set)." + ); + } + if (argv["tag"] === undefined) { + argv["tag"] = await promptForRequiredField( + "tag", + "Name of the logo query. Must be unique among the account's logo queries." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf brand-protection logos create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/logo/queries`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + image_data: resolveFileToken( + argv["image-data"] as string | undefined, + "image-data", + "text" + ), + search_lookback: argv["search-lookback"], + similarity_threshold: argv["similarity-threshold"], + tag: resolveFileToken( + argv["tag"] as string | undefined, + "tag", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + image_data: resolveFileToken( + argv["image-data"] as string | undefined, + "image-data", + "text" + ), + search_lookback: argv["search-lookback"], + similarity_threshold: argv["similarity-threshold"], + tag: resolveFileToken(argv["tag"] as string | undefined, "tag", "text"), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/brand-protection/logos/create.ts b/packages/cli/src/commands/_generated/brand-protection/logos/create.ts index dc012a392a..e22a707af1 100644 --- a/packages/cli/src/commands/_generated/brand-protection/logos/create.ts +++ b/packages/cli/src/commands/_generated/brand-protection/logos/create.ts @@ -1,164 +1,63 @@ -import operation from "../../_operations/brand-protection/logos/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/brand-protection.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 brand-protection logos create\n\nUploads a logo and creates a saved logo query that finds visually similar images on scanned websites. The tag must be unique among the account's logo queries. By default, the new query also searches previously scanned images (see `search_lookback`). Creation fails when the account has reached its Brand Protection query limit, which counts domain and logo queries together." - ) - .option("image-data", { - type: "string", - description: +const parameters = { + flags: { + "image-data": { + kind: "parsed", + brief: "Base64 encoded image data. Can include data URI prefix (e.g., 'data:image/png;base64,...') or just the base64 string. Supported formats: PNG, JPEG, GIF, WebP, BMP, and SVG. ICO is also accepted when the data includes a `data:image/x-icon;base64,` prefix.", - }) - .option("search-lookback", { - type: "boolean", - description: + optional: true, + parse: String, + }, + "search-lookback": { + kind: "boolean", + brief: "If true, also search previously scanned images for matches above the similarity threshold. Defaults to `true`.", default: true, - }) - .option("similarity-threshold", { - type: "number", - description: "Minimum similarity score (0-1) required for visual matches", - }) - .option("tag", { - type: "string", - description: + }, + "similarity-threshold": { + kind: "parsed", + brief: "Minimum similarity score (0-1) required for visual matches", + optional: true, + parse: Number, + }, + tag: { + kind: "parsed", + brief: "Name of the logo query. Must be unique among the account's logo queries.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Create logo query", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "brand-protection logos create", - classification: { - safeFlags: ["search-lookback", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["image-data"] === undefined) { - argv["image-data"] = await promptForRequiredField( - "image-data", - "Base64 encoded image data. Can include data URI prefix (e.g., 'data:image/png;base64,...') or just the base64 string. Supported formats: PNG, JPEG, GIF, WebP, BMP, and SVG. ICO is also accepted when the data includes a \`data:image/x-icon;base64,\` prefix." - ); - } - if (argv["similarity-threshold"] === undefined) { - throw new Error( - "--similarity-threshold is required (or pass --body with this field set)." - ); - } - if (argv["tag"] === undefined) { - argv["tag"] = await promptForRequiredField( - "tag", - "Name of the logo query. Must be unique among the account's logo queries." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf brand-protection logos create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/logo/queries`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - image_data: resolveFileToken( - argv["image-data"] as string | undefined, - "image-data", - "text" - ), - search_lookback: argv["search-lookback"], - similarity_threshold: argv["similarity-threshold"], - tag: resolveFileToken( - argv["tag"] as string | undefined, - "tag", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - image_data: resolveFileToken( - argv["image-data"] as string | undefined, - "image-data", - "text" - ), - search_lookback: argv["search-lookback"], - similarity_threshold: argv["similarity-threshold"], - tag: resolveFileToken( - argv["tag"] as string | undefined, - "tag", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 brand-protection logos create\n\nUploads a logo and creates a saved logo query that finds visually similar images on scanned websites. The tag must be unique among the account's logo queries. By default, the new query also searches previously scanned images (see `search_lookback`). Creation fails when the account has reached its Brand Protection query limit, which counts domain and logo queries together.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/brand-protection/logos/delete.handler.ts b/packages/cli/src/commands/_generated/brand-protection/logos/delete.handler.ts new file mode 100644 index 0000000000..b63781f0cd --- /dev/null +++ b/packages/cli/src/commands/_generated/brand-protection/logos/delete.handler.ts @@ -0,0 +1,55 @@ +import operation from "../../_operations/brand-protection/logos/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "brand-protection logos delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf brand-protection logos delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/logo/queries/${argv["query-id"] == null ? "" : encodeURIComponent(String(argv["query-id"]))}`, + pathParams: { "query-id": String(argv["query-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + query_id: argv["query-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/brand-protection/logos/delete.ts b/packages/cli/src/commands/_generated/brand-protection/logos/delete.ts index 50d2d45d31..f2fcfed782 100644 --- a/packages/cli/src/commands/_generated/brand-protection/logos/delete.ts +++ b/packages/cli/src/commands/_generated/brand-protection/logos/delete.ts @@ -1,91 +1,39 @@ -import operation from "../../_operations/brand-protection/logos/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/brand-protection.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 brand-protection logos delete \n\nPermanently deletes a saved logo query and all of its matches. If the query does not exist in this account, the request fails with error code 404." - ) - .positional("query-id", { - type: "string", - description: "ID of the logo query.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "query-id", brief: "ID of the logo query.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Delete logo query", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "brand-protection logos delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf brand-protection logos delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/logo/queries/${argv["query-id"] == null ? "" : encodeURIComponent(String(argv["query-id"]))}`, - pathParams: { "query-id": String(argv["query-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - query_id: argv["query-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 brand-protection logos delete \n\nPermanently deletes a saved logo query and all of its matches. If the query does not exist in this account, the request fails with error code 404.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/brand-protection/logos/get.handler.ts b/packages/cli/src/commands/_generated/brand-protection/logos/get.handler.ts new file mode 100644 index 0000000000..0fb99f1c18 --- /dev/null +++ b/packages/cli/src/commands/_generated/brand-protection/logos/get.handler.ts @@ -0,0 +1,51 @@ +import operation from "../../_operations/brand-protection/logos/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "brand-protection logos get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + id: argv["id"], + download: argv["download"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf brand-protection logos get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/logo/queries`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/brand-protection/logos/get.ts b/packages/cli/src/commands/_generated/brand-protection/logos/get.ts index c32d9ab532..8e450f2ebd 100644 --- a/packages/cli/src/commands/_generated/brand-protection/logos/get.ts +++ b/packages/cli/src/commands/_generated/brand-protection/logos/get.ts @@ -1,86 +1,45 @@ -import operation from "../../_operations/brand-protection/logos/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/brand-protection.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 brand-protection logos get\n\nLists the account's saved logo queries. Set `id` to return a single query object instead of an array. Set `download=true` to include each logo image as base64 data." - ) - .option("id", { - type: "string", - description: +const parameters = { + flags: { + id: { + kind: "parsed", + brief: "ID of a logo query. When set, `result` is that single query object instead of an array.", - }) - .option("download", { - type: "string", - description: + optional: true, + parse: String, + }, + download: { + kind: "parsed", + brief: "Set to `true` to include each logo image as base64 data in `image_data`, with its MIME type in `content_type`.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "List logo queries", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "brand-protection logos get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - id: argv["id"], - download: argv["download"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf brand-protection logos get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/logo/queries`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 brand-protection logos get\n\nLists the account's saved logo queries. Set `id` to return a single query object instead of an array. Set `download=true` to include each logo image as base64 data.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/brand-protection/logos/index.ts b/packages/cli/src/commands/_generated/brand-protection/logos/index.ts index aefe3e2f0e..8cab623a0f 100644 --- a/packages/cli/src/commands/_generated/brand-protection/logos/index.ts +++ b/packages/cli/src/commands/_generated/brand-protection/logos/index.ts @@ -1,26 +1,21 @@ import $create from "./create.js"; import $delete from "./delete.js"; import $get from "./get.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * logos command group * @generated from apis/overlays/brand-protection.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "logos", describe: "Operations for logos", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/brand-protection/matches/bulk-dismiss.handler.ts b/packages/cli/src/commands/_generated/brand-protection/matches/bulk-dismiss.handler.ts new file mode 100644 index 0000000000..7f2f1cbcf2 --- /dev/null +++ b/packages/cli/src/commands/_generated/brand-protection/matches/bulk-dismiss.handler.ts @@ -0,0 +1,86 @@ +import operation from "../../_operations/brand-protection/matches/bulk-dismiss.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./bulk-dismiss.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredEnumField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "brand-protection matches bulk-dismiss", + classification: { + safeFlags: ["action", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["action"] === undefined) { + argv["action"] = await promptForRequiredEnumField( + "action", + "\`dismiss\` to dismiss the matches, or \`undismiss\` to restore them.", + ["dismiss", "undismiss"] as const + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf brand-protection matches bulk-dismiss", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/domain/matches/bulk-dismiss`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + action: argv["action"], + match_ids: argv["match-ids"], + matches: parseObjectArray(argv["matches"], "matches"), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + action: argv["action"], + match_ids: argv["match-ids"], + matches: parseObjectArray(argv["matches"], "matches"), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/brand-protection/matches/bulk-dismiss.ts b/packages/cli/src/commands/_generated/brand-protection/matches/bulk-dismiss.ts index f89babbbe7..6e21b904ec 100644 --- a/packages/cli/src/commands/_generated/brand-protection/matches/bulk-dismiss.ts +++ b/packages/cli/src/commands/_generated/brand-protection/matches/bulk-dismiss.ts @@ -1,134 +1,62 @@ -import operation from "../../_operations/brand-protection/matches/bulk-dismiss.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * bulk-dismiss command * @generated from apis/overlays/brand-protection.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody, parseObjectArray } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredEnumField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 brand-protection matches bulk-dismiss\n\nDismisses or undismisses up to 100 domain matches in one request and returns a result for each item. Send `matches` as (`query_id`, `domain_id`) pairs to change each match for one query. The legacy `match_ids` format is still accepted, but it changes each match for every query that shares it; prefer `matches`." - ) - .option("action", { - type: "string", - description: +const parameters = { + flags: { + action: { + kind: "parsed", + brief: "`dismiss` to dismiss the matches, or `undismiss` to restore them.", + optional: true, choices: ["dismiss", "undismiss"], - }) - .coerce("action", (value) => resolveFileToken(value, "action", "text")) - .option("match-ids", { - type: "string", - array: true, - description: + parse: String, + coerce: (value: string) => resolveFileToken(value, "action", "text"), + }, + "match-ids": { + kind: "parsed", + brief: "Legacy format; prefer `matches`. Match IDs to update. Each ID changes the match for every query that shares it, not just one query. 1 to 100 items; duplicate IDs are rejected.", - }) - .option("matches", { - type: "string", - description: + variadic: true, + optional: true, + parse: String, + }, + matches: { + kind: "parsed", + brief: 'Matches to update, as (`query_id`, `domain_id`) pairs. Each pair changes the match for that query only. 1 to 100 items; duplicate pairs are rejected. Send only one format. If both are supplied, `match_ids` takes precedence and `matches` is ignored. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"domain_id": number, "query_id": number}].', - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "bulk-dismiss", describe: "Bulk dismiss or undismiss matches", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "brand-protection matches bulk-dismiss", - classification: { - safeFlags: ["action", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["action"] === undefined) { - argv["action"] = await promptForRequiredEnumField( - "action", - "\`dismiss\` to dismiss the matches, or \`undismiss\` to restore them.", - ["dismiss", "undismiss"] as const - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf brand-protection matches bulk-dismiss", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/domain/matches/bulk-dismiss`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - action: argv["action"], - match_ids: argv["match-ids"], - matches: parseObjectArray(argv["matches"], "matches"), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - action: argv["action"], - match_ids: argv["match-ids"], - matches: parseObjectArray(argv["matches"], "matches"), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 brand-protection matches bulk-dismiss\n\nDismisses or undismisses up to 100 domain matches in one request and returns a result for each item. Send `matches` as (`query_id`, `domain_id`) pairs to change each match for one query. The legacy `match_ids` format is still accepted, but it changes each match for every query that shares it; prefer `matches`.", + ...parameters, + loader: () => import("./bulk-dismiss.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/brand-protection/matches/get.handler.ts b/packages/cli/src/commands/_generated/brand-protection/matches/get.handler.ts new file mode 100644 index 0000000000..a2338c7666 --- /dev/null +++ b/packages/cli/src/commands/_generated/brand-protection/matches/get.handler.ts @@ -0,0 +1,58 @@ +import operation from "../../_operations/brand-protection/matches/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "brand-protection matches get", + classification: { + safeFlags: ["quality", "order-by", "order", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + offset: argv["offset"], + limit: argv["limit"], + query_id: argv["query-id"], + include_domain_id: argv["include-domain-id"], + include_dismissed: argv["include-dismissed"], + domain_search: argv["domain-search"], + quality: argv["quality"], + orderBy: argv["order-by"], + order: argv["order"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf brand-protection matches get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/domain/matches`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/brand-protection/matches/get.ts b/packages/cli/src/commands/_generated/brand-protection/matches/get.ts index 67dcfafeec..6275bde1b8 100644 --- a/packages/cli/src/commands/_generated/brand-protection/matches/get.ts +++ b/packages/cli/src/commands/_generated/brand-protection/matches/get.ts @@ -1,130 +1,91 @@ -import operation from "../../_operations/brand-protection/matches/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/brand-protection.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 brand-protection matches get\n\nLists domains that matched one or more saved domain queries, most recently matched first by default. When you pass several comma-separated `query_id` values, matches are deduplicated by domain and each match includes a `match_details` array with per-query dismissed state. Set `include_domain_id=true` to get the `domain_id` needed to dismiss or undismiss a match." - ) - .option("offset", { - type: "string", - description: "Number of matches to skip, for pagination. Defaults to 0.", - }) - .option("limit", { - type: "string", - description: "Maximum number of matches to return. Defaults to 50.", - }) - .option("query-id", { - type: "string", - array: true, - description: +const parameters = { + flags: { + offset: { + kind: "parsed", + brief: "Number of matches to skip, for pagination. Defaults to 0.", + optional: true, + parse: String, + }, + limit: { + kind: "parsed", + brief: "Maximum number of matches to return. Defaults to 50.", + optional: true, + parse: String, + }, + "query-id": { + kind: "parsed", + brief: "ID of a domain query, or a comma-separated list of domain query IDs. When you pass several IDs, matches are deduplicated by domain and each match includes a `match_details` array with per-query metadata and dismissed state.", - demandOption: true, - }) - .option("include-domain-id", { - type: "string", - description: + variadic: true, + parse: String, + }, + "include-domain-id": { + kind: "parsed", + brief: "Set to `true` to include `domain_id` on each match. Required to dismiss or undismiss a match. Defaults to `false`.", - }) - .option("include-dismissed", { - type: "string", - description: + optional: true, + parse: String, + }, + "include-dismissed": { + kind: "parsed", + brief: "Set to `false` to exclude dismissed matches. Dismissed matches are included when this is omitted or `true`.", - }) - .option("domain-search", { - type: "string", - description: + optional: true, + parse: String, + }, + "domain-search": { + kind: "parsed", + brief: "Return only matches whose domain contains this text (case-insensitive).", - }) - .option("quality", { - type: "string", - description: "Filter matches by quality. Options: 'high' or 'low'", - choices: ["high", "low"], - }) - .option("order-by", { - type: "string", - description: + optional: true, + parse: String, + }, + quality: { + kind: "enum", + brief: "Filter matches by quality. Options: 'high' or 'low'", + values: ["high", "low"], + optional: true, + }, + "order-by": { + kind: "enum", + brief: "Field to sort by: `domain`, `first_seen`, or `registrar`. Defaults to `first_seen`.", - choices: ["domain", "first_seen", "registrar"], - }) - .option("order", { - type: "string", - description: + values: ["domain", "first_seen", "registrar"], + optional: true, + }, + order: { + kind: "enum", + brief: "Sort direction: `asc` or `desc`. Defaults to `desc`. For single-query requests, `asc` applies only when `orderBy` is set.", - choices: ["asc", "desc"], - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + values: ["asc", "desc"], + optional: true, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "List domain matches", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "brand-protection matches get", - classification: { - safeFlags: ["quality", "order-by", "order", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - offset: argv["offset"], - limit: argv["limit"], - query_id: argv["query-id"], - include_domain_id: argv["include-domain-id"], - include_dismissed: argv["include-dismissed"], - domain_search: argv["domain-search"], - quality: argv["quality"], - orderBy: argv["order-by"], - order: argv["order"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf brand-protection matches get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/domain/matches`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 brand-protection matches get\n\nLists domains that matched one or more saved domain queries, most recently matched first by default. When you pass several comma-separated `query_id` values, matches are deduplicated by domain and each match includes a `match_details` array with per-query dismissed state. Set `include_domain_id=true` to get the `domain_id` needed to dismiss or undismiss a match.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/brand-protection/matches/index.ts b/packages/cli/src/commands/_generated/brand-protection/matches/index.ts index 26e5371804..3422aa0cb5 100644 --- a/packages/cli/src/commands/_generated/brand-protection/matches/index.ts +++ b/packages/cli/src/commands/_generated/brand-protection/matches/index.ts @@ -1,24 +1,19 @@ import $bulkdismiss from "./bulk-dismiss.js"; import $get from "./get.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * matches command group * @generated from apis/overlays/brand-protection.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "matches", describe: "Operations for matches", - builder: (yargs) => { - return yargs - .command($bulkdismiss) - .command($get) - .demandCommand(1, "Please specify a subcommand"); + routes: { + "bulk-dismiss": $bulkdismiss, + get: $get, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/brand-protection/queries/dismiss.handler.ts b/packages/cli/src/commands/_generated/brand-protection/queries/dismiss.handler.ts new file mode 100644 index 0000000000..4839eec371 --- /dev/null +++ b/packages/cli/src/commands/_generated/brand-protection/queries/dismiss.handler.ts @@ -0,0 +1,53 @@ +import operation from "../../_operations/brand-protection/queries/dismiss.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./dismiss.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "brand-protection queries dismiss", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf brand-protection queries dismiss", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/queries/${argv["query-id"] == null ? "" : encodeURIComponent(String(argv["query-id"]))}/matches/${argv["domain-id"] == null ? "" : encodeURIComponent(String(argv["domain-id"]))}/dismiss`, + pathParams: { + "query-id": String(argv["query-id"] ?? ""), + "domain-id": String(argv["domain-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Creating`, async () => + client.send(operation, { + account_id: accountId, + query_id: argv["query-id"], + domain_id: argv["domain-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/brand-protection/queries/dismiss.ts b/packages/cli/src/commands/_generated/brand-protection/queries/dismiss.ts index 311854c3d7..bd4b7f17e2 100644 --- a/packages/cli/src/commands/_generated/brand-protection/queries/dismiss.ts +++ b/packages/cli/src/commands/_generated/brand-protection/queries/dismiss.ts @@ -1,89 +1,43 @@ -import operation from "../../_operations/brand-protection/queries/dismiss.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * dismiss command * @generated from apis/overlays/brand-protection.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 brand-protection queries dismiss \n\nMarks a matched domain as dismissed for one domain query. Dismissals are per query: dismissing a domain in one query does not affect other queries. Get `domain_id` from List domain matches with `include_domain_id=true`. Dismissing an already dismissed match succeeds. If the query or match does not exist, the request fails with error code 404." - ) - .positional("domain-id", { - type: "string", - description: - "ID of the matched domain, as returned in \`domain_id\` by List domain matches with \`include_domain_id=true\`.", - demandOption: true, - }) - .option("query-id", { - type: "string", - description: "ID of the domain query that the match belongs to.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "query-id": { + kind: "parsed", + brief: "ID of the domain query that the match belongs to.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "domain-id", + brief: + "ID of the matched domain, as returned in \`domain_id\` by List domain matches with \`include_domain_id=true\`.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "dismiss ", describe: "Dismiss a domain match", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "brand-protection queries dismiss", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf brand-protection queries dismiss", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/queries/${argv["query-id"] == null ? "" : encodeURIComponent(String(argv["query-id"]))}/matches/${argv["domain-id"] == null ? "" : encodeURIComponent(String(argv["domain-id"]))}/dismiss`, - pathParams: { - "query-id": String(argv["query-id"] ?? ""), - "domain-id": String(argv["domain-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Creating`, async () => - client.send(operation, { - account_id: accountId, - query_id: argv["query-id"], - domain_id: argv["domain-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 brand-protection queries dismiss \n\nMarks a matched domain as dismissed for one domain query. Dismissals are per query: dismissing a domain in one query does not affect other queries. Get `domain_id` from List domain matches with `include_domain_id=true`. Dismissing an already dismissed match succeeds. If the query or match does not exist, the request fails with error code 404.", + ...parameters, + loader: () => import("./dismiss.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/brand-protection/queries/get.handler.ts b/packages/cli/src/commands/_generated/brand-protection/queries/get.handler.ts new file mode 100644 index 0000000000..c565393aa8 --- /dev/null +++ b/packages/cli/src/commands/_generated/brand-protection/queries/get.handler.ts @@ -0,0 +1,52 @@ +import operation from "../../_operations/brand-protection/queries/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "brand-protection queries get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + id: argv["id"], + page: argv["page"], + per_page: argv["per-page"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf brand-protection queries get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/domain/queries`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/brand-protection/queries/get.ts b/packages/cli/src/commands/_generated/brand-protection/queries/get.ts index c438e360f4..3e01cbb850 100644 --- a/packages/cli/src/commands/_generated/brand-protection/queries/get.ts +++ b/packages/cli/src/commands/_generated/brand-protection/queries/get.ts @@ -1,92 +1,52 @@ -import operation from "../../_operations/brand-protection/queries/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/brand-protection.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 brand-protection queries get\n\nLists the account's saved domain queries, most recently updated first. Set `id` to return a single query object instead of an array. Set `page` or `per_page` to paginate the list; the response then includes `result_info`. Without them, every query is returned." - ) - .option("id", { - type: "string", - description: +const parameters = { + flags: { + id: { + kind: "parsed", + brief: "ID of a domain query. When set, `result` is that single query object instead of an array, and `page` and `per_page` are ignored.", - }) - .option("page", { - type: "number", - description: + optional: true, + parse: String, + }, + page: { + kind: "parsed", + brief: "Page number for paginated list requests. Defaults to 1 when only per_page is supplied. Omit page and per_page to return every query.", - }) - .option("per-page", { - type: "number", - description: + optional: true, + parse: Number, + }, + "per-page": { + kind: "parsed", + brief: "Number of queries per page for paginated list requests. Defaults to 100 when only page is supplied. Maximum 100. Omit page and per_page to return every query.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "List domain queries", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "brand-protection queries get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - id: argv["id"], - page: argv["page"], - per_page: argv["per-page"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf brand-protection queries get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/domain/queries`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 brand-protection queries get\n\nLists the account's saved domain queries, most recently updated first. Set `id` to return a single query object instead of an array. Set `page` or `per_page` to paginate the list; the response then includes `result_info`. Without them, every query is returned.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/brand-protection/queries/index.ts b/packages/cli/src/commands/_generated/brand-protection/queries/index.ts index 5b7c25ea61..dfaa60f9e4 100644 --- a/packages/cli/src/commands/_generated/brand-protection/queries/index.ts +++ b/packages/cli/src/commands/_generated/brand-protection/queries/index.ts @@ -1,26 +1,21 @@ import $dismiss from "./dismiss.js"; import $get from "./get.js"; import $undismiss from "./undismiss.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * queries command group * @generated from apis/overlays/brand-protection.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "queries", describe: "Operations for queries", - builder: (yargs) => { - return yargs - .command($dismiss) - .command($get) - .command($undismiss) - .demandCommand(1, "Please specify a subcommand"); + routes: { + dismiss: $dismiss, + get: $get, + undismiss: $undismiss, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/brand-protection/queries/undismiss.handler.ts b/packages/cli/src/commands/_generated/brand-protection/queries/undismiss.handler.ts new file mode 100644 index 0000000000..a47c6a0573 --- /dev/null +++ b/packages/cli/src/commands/_generated/brand-protection/queries/undismiss.handler.ts @@ -0,0 +1,53 @@ +import operation from "../../_operations/brand-protection/queries/undismiss.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./undismiss.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "brand-protection queries undismiss", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf brand-protection queries undismiss", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/queries/${argv["query-id"] == null ? "" : encodeURIComponent(String(argv["query-id"]))}/matches/${argv["domain-id"] == null ? "" : encodeURIComponent(String(argv["domain-id"]))}/undismiss`, + pathParams: { + "query-id": String(argv["query-id"] ?? ""), + "domain-id": String(argv["domain-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Creating`, async () => + client.send(operation, { + account_id: accountId, + query_id: argv["query-id"], + domain_id: argv["domain-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/brand-protection/queries/undismiss.ts b/packages/cli/src/commands/_generated/brand-protection/queries/undismiss.ts index 040ae3df52..f5a637dc63 100644 --- a/packages/cli/src/commands/_generated/brand-protection/queries/undismiss.ts +++ b/packages/cli/src/commands/_generated/brand-protection/queries/undismiss.ts @@ -1,89 +1,43 @@ -import operation from "../../_operations/brand-protection/queries/undismiss.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * undismiss command * @generated from apis/overlays/brand-protection.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 brand-protection queries undismiss \n\nRemoves the dismissed status from a matched domain for one domain query. Undismissing a domain in one query does not affect other queries. Get `domain_id` from List domain matches with `include_domain_id=true`. Undismissing a match that is not dismissed succeeds. If the query or match does not exist, the request fails with error code 404." - ) - .positional("domain-id", { - type: "string", - description: - "ID of the matched domain, as returned in \`domain_id\` by List domain matches with \`include_domain_id=true\`.", - demandOption: true, - }) - .option("query-id", { - type: "string", - description: "ID of the domain query that the match belongs to.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "query-id": { + kind: "parsed", + brief: "ID of the domain query that the match belongs to.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "domain-id", + brief: + "ID of the matched domain, as returned in \`domain_id\` by List domain matches with \`include_domain_id=true\`.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "undismiss ", describe: "Undismiss a domain match", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "brand-protection queries undismiss", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf brand-protection queries undismiss", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/queries/${argv["query-id"] == null ? "" : encodeURIComponent(String(argv["query-id"]))}/matches/${argv["domain-id"] == null ? "" : encodeURIComponent(String(argv["domain-id"]))}/undismiss`, - pathParams: { - "query-id": String(argv["query-id"] ?? ""), - "domain-id": String(argv["domain-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Creating`, async () => - client.send(operation, { - account_id: accountId, - query_id: argv["query-id"], - domain_id: argv["domain-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 brand-protection queries undismiss \n\nRemoves the dismissed status from a matched domain for one domain query. Undismissing a domain in one query does not affect other queries. Get `domain_id` from List domain matches with `include_domain_id=true`. Undismissing a match that is not dismissed succeeds. If the query or match does not exist, the request fails with error code 404.", + ...parameters, + loader: () => import("./undismiss.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/brand-protection/submit.handler.ts b/packages/cli/src/commands/_generated/brand-protection/submit.handler.ts new file mode 100644 index 0000000000..d3bb015a2b --- /dev/null +++ b/packages/cli/src/commands/_generated/brand-protection/submit.handler.ts @@ -0,0 +1,117 @@ +import operation from "../_operations/brand-protection/submit.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./submit.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "brand-protection submit", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + showHistoric: argv["show-historic"], + download: argv["download"], + }; + const resolveRequiredFields = async (): Promise => { + if (argv["image-data"] === undefined) { + argv["image-data"] = await promptForRequiredField( + "image-data", + "Base64 encoded image data. Can include data URI prefix (e.g., 'data:image/png;base64,...') or just the base64 string." + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf brand-protection submit", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/logo/search`, + pathParams: {}, + query: queryParams, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + image_data: resolveFileToken( + argv["image-data"] as string | undefined, + "image-data", + "text" + ), + score_threshold: argv["score-threshold"], + top_k: argv["top-k"], + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const qs = new URLSearchParams( + Object.entries(queryParams) + .filter(([, v]) => v !== undefined) + .map(([k, v]) => [k, String(v)]) + ).toString(); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + image_data: resolveFileToken( + argv["image-data"] as string | undefined, + "image-data", + "text" + ), + score_threshold: argv["score-threshold"], + top_k: argv["top-k"], + }); + const qs = new URLSearchParams( + Object.entries(queryParams) + .filter(([, v]) => v !== undefined) + .map(([k, v]) => [k, String(v)]) + ).toString(); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/brand-protection/submit.ts b/packages/cli/src/commands/_generated/brand-protection/submit.ts index 945f0477f2..8bf9be681d 100644 --- a/packages/cli/src/commands/_generated/brand-protection/submit.ts +++ b/packages/cli/src/commands/_generated/brand-protection/submit.ts @@ -1,172 +1,70 @@ -import operation from "../_operations/brand-protection/submit.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * submit command * @generated from apis/overlays/brand-protection.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 brand-protection submit\n\nSubmit an image and find the n closest matches from the scanned images index without creating any match records. Returns similarity scores and metadata for each match." - ) - .option("show-historic", { - type: "string", - description: +const parameters = { + flags: { + "show-historic": { + kind: "parsed", + brief: "Include scanned images without domain metadata (historic data). Default: false (only show images with domain)", - }) - .option("download", { - type: "string", - description: "If true, include base64-encoded image data in the response", - }) - .option("image-data", { - type: "string", - description: + optional: true, + parse: String, + }, + download: { + kind: "parsed", + brief: "If true, include base64-encoded image data in the response", + optional: true, + parse: String, + }, + "image-data": { + kind: "parsed", + brief: "Base64 encoded image data. Can include data URI prefix (e.g., 'data:image/png;base64,...') or just the base64 string.", - }) - .option("score-threshold", { - type: "number", - description: - "Minimum similarity score threshold for matches (0-1, default: 0)", - default: 0, - }) - .option("top-k", { - type: "number", - description: + optional: true, + parse: String, + }, + "score-threshold": { + kind: "parsed", + brief: "Minimum similarity score threshold for matches (0-1, default: 0)", + default: "0", + parse: Number, + }, + "top-k": { + kind: "parsed", + brief: "Number of closest matches to return. Defaults to 10. Accepts 1 to 100, but values above 50 are treated as 50.", - default: 10, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + default: "10", + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "submit", describe: "Search scanned images", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "brand-protection submit", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - showHistoric: argv["show-historic"], - download: argv["download"], - }; - const resolveRequiredFields = async (): Promise => { - if (argv["image-data"] === undefined) { - argv["image-data"] = await promptForRequiredField( - "image-data", - "Base64 encoded image data. Can include data URI prefix (e.g., 'data:image/png;base64,...') or just the base64 string." - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf brand-protection submit", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/logo/search`, - pathParams: {}, - query: queryParams, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - image_data: resolveFileToken( - argv["image-data"] as string | undefined, - "image-data", - "text" - ), - score_threshold: argv["score-threshold"], - top_k: argv["top-k"], - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const qs = new URLSearchParams( - Object.entries(queryParams) - .filter(([, v]) => v !== undefined) - .map(([k, v]) => [k, String(v)]) - ).toString(); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - image_data: resolveFileToken( - argv["image-data"] as string | undefined, - "image-data", - "text" - ), - score_threshold: argv["score-threshold"], - top_k: argv["top-k"], - }); - const qs = new URLSearchParams( - Object.entries(queryParams) - .filter(([, v]) => v !== undefined) - .map(([k, v]) => [k, String(v)]) - ).toString(); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 brand-protection submit\n\nSubmit an image and find the n closest matches from the scanned images index without creating any match records. Returns similarity scores and metadata for each match.", + ...parameters, + loader: () => import("./submit.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/brand-protection/trial/create.handler.ts b/packages/cli/src/commands/_generated/brand-protection/trial/create.handler.ts new file mode 100644 index 0000000000..0acc923dcc --- /dev/null +++ b/packages/cli/src/commands/_generated/brand-protection/trial/create.handler.ts @@ -0,0 +1,90 @@ +import operation from "../../_operations/brand-protection/trial/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { promptForRequiredField } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "brand-protection trial create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const resolveRequiredFields = async (): Promise => { + if (argv["brand"] === undefined) { + argv["brand"] = await promptForRequiredField( + "brand", + "The brand field" + ); + } + }; + if (argv.dryRun) { + if (argv.body === undefined) { + await resolveRequiredFields(); + } + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf brand-protection trial create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/domain/trial`, + pathParams: {}, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + brand: resolveFileToken( + argv["brand"] as string | undefined, + "brand", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + await resolveRequiredFields(); + + // Assemble request body from individual flags + const bodyData = compactBody({ + brand: resolveFileToken( + argv["brand"] as string | undefined, + "brand", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { body: bodyData, account_id: accountId }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/brand-protection/trial/create.ts b/packages/cli/src/commands/_generated/brand-protection/trial/create.ts index 14229202f8..2fbc3ed375 100644 --- a/packages/cli/src/commands/_generated/brand-protection/trial/create.ts +++ b/packages/cli/src/commands/_generated/brand-protection/trial/create.ts @@ -1,120 +1,43 @@ -import operation from "../../_operations/brand-protection/trial/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/brand-protection.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { promptForRequiredField } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 brand-protection trial create\n\nUses AI to scan all domains in the lookback table and identify potential phishing or impersonation attempts against the given brand string." - ) - .option("brand", { type: "string", description: "The brand field" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + brand: { + kind: "parsed", + brief: "The brand field", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Analyze domains for brand impersonation", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "brand-protection trial create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const resolveRequiredFields = async (): Promise => { - if (argv["brand"] === undefined) { - argv["brand"] = await promptForRequiredField( - "brand", - "The brand field" - ); - } - }; - if (argv.dryRun) { - if (argv.body === undefined) { - await resolveRequiredFields(); - } - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf brand-protection trial create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/domain/trial`, - pathParams: {}, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - brand: resolveFileToken( - argv["brand"] as string | undefined, - "brand", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - await resolveRequiredFields(); - - // Assemble request body from individual flags - const bodyData = compactBody({ - brand: resolveFileToken( - argv["brand"] as string | undefined, - "brand", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { body: bodyData, account_id: accountId }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 brand-protection trial create\n\nUses AI to scan all domains in the lookback table and identify potential phishing or impersonation attempts against the given brand string.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/brand-protection/trial/index.ts b/packages/cli/src/commands/_generated/brand-protection/trial/index.ts index 3cb82133ac..1d856c1154 100644 --- a/packages/cli/src/commands/_generated/brand-protection/trial/index.ts +++ b/packages/cli/src/commands/_generated/brand-protection/trial/index.ts @@ -1,22 +1,17 @@ import $create from "./create.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * trial command group * @generated from apis/overlays/brand-protection.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "trial", describe: "Operations for trial", - builder: (yargs) => { - return yargs - .command($create) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/brand-protection/url-info.handler.ts b/packages/cli/src/commands/_generated/brand-protection/url-info.handler.ts new file mode 100644 index 0000000000..aafe96c1d5 --- /dev/null +++ b/packages/cli/src/commands/_generated/brand-protection/url-info.handler.ts @@ -0,0 +1,46 @@ +import operation from "../_operations/brand-protection/url-info.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./url-info.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "brand-protection url-info", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf brand-protection url-info", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/total-queries`, + pathParams: {}, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/brand-protection/url-info.ts b/packages/cli/src/commands/_generated/brand-protection/url-info.ts index 29abf30223..82cb13e533 100644 --- a/packages/cli/src/commands/_generated/brand-protection/url-info.ts +++ b/packages/cli/src/commands/_generated/brand-protection/url-info.ts @@ -1,71 +1,31 @@ -import operation from "../_operations/brand-protection/url-info.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * url-info command * @generated from apis/overlays/brand-protection.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 brand-protection url-info\n\nReturns the number of saved domain and logo queries in the account. This is the count checked against the account's Brand Protection query limit." - ) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "url-info", describe: "Get total query count", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "brand-protection url-info", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf brand-protection url-info", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/total-queries`, - pathParams: {}, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 brand-protection url-info\n\nReturns the number of saved domain and logo queries in the account. This is the count checked against the account's Brand Protection query limit.", + ...parameters, + loader: () => import("./url-info.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/brand-protection/urls/get.handler.ts b/packages/cli/src/commands/_generated/brand-protection/urls/get.handler.ts new file mode 100644 index 0000000000..38ab655403 --- /dev/null +++ b/packages/cli/src/commands/_generated/brand-protection/urls/get.handler.ts @@ -0,0 +1,51 @@ +import operation from "../../_operations/brand-protection/urls/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "brand-protection urls get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + url: argv["url"], + url_id: argv["url-id"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf brand-protection urls get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/url/info`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/brand-protection/urls/get.ts b/packages/cli/src/commands/_generated/brand-protection/urls/get.ts index 193b08cb3c..52261beff4 100644 --- a/packages/cli/src/commands/_generated/brand-protection/urls/get.ts +++ b/packages/cli/src/commands/_generated/brand-protection/urls/get.ts @@ -1,78 +1,43 @@ -import operation from "../../_operations/brand-protection/urls/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/brand-protection.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 brand-protection urls get\n\nGet account-scoped URL Scanner summaries by submitted URL or scan UUID. Lookups cover scans submitted within about the last 30 days; a daily cleanup at 00:00 UTC removes older ownership records. Completed results may be served from a cache that is cleared daily, so a cached copy is kept for at most about 48 hours. The response is a v2 migration contract, not the v1 enrichment shape." - ) - .option("url", { type: "string", description: "An HTTP or HTTPS URL." }) - .option("url-id", { type: "string", description: "Url ID" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + url: { + kind: "parsed", + brief: "An HTTP or HTTPS URL.", + optional: true, + parse: String, + }, + "url-id": { + kind: "parsed", + brief: "Url ID", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get", describe: "Get URL scan information", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "brand-protection urls get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - url: argv["url"], - url_id: argv["url-id"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf brand-protection urls get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/url/info`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 brand-protection urls get\n\nGet account-scoped URL Scanner summaries by submitted URL or scan UUID. Lookups cover scans submitted within about the last 30 days; a daily cleanup at 00:00 UTC removes older ownership records. Completed results may be served from a cache that is cleared daily, so a cached copy is kept for at most about 48 hours. The response is a v2 migration contract, not the v1 enrichment shape.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/brand-protection/urls/index.ts b/packages/cli/src/commands/_generated/brand-protection/urls/index.ts index d395a326b8..b6375586d5 100644 --- a/packages/cli/src/commands/_generated/brand-protection/urls/index.ts +++ b/packages/cli/src/commands/_generated/brand-protection/urls/index.ts @@ -1,24 +1,19 @@ import $get from "./get.js"; import $submit from "./submit.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * urls command group * @generated from apis/overlays/brand-protection.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "urls", describe: "Operations for urls", - builder: (yargs) => { - return yargs - .command($get) - .command($submit) - .demandCommand(1, "Please specify a subcommand"); + routes: { + get: $get, + submit: $submit, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/brand-protection/urls/submit.handler.ts b/packages/cli/src/commands/_generated/brand-protection/urls/submit.handler.ts new file mode 100644 index 0000000000..695505f917 --- /dev/null +++ b/packages/cli/src/commands/_generated/brand-protection/urls/submit.handler.ts @@ -0,0 +1,50 @@ +import operation from "../../_operations/brand-protection/urls/submit.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./submit.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "brand-protection urls submit", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + url: argv["url"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf brand-protection urls submit", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/url/submit`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Creating`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/brand-protection/urls/submit.ts b/packages/cli/src/commands/_generated/brand-protection/urls/submit.ts index 73c382c347..ade622218f 100644 --- a/packages/cli/src/commands/_generated/brand-protection/urls/submit.ts +++ b/packages/cli/src/commands/_generated/brand-protection/urls/submit.ts @@ -1,80 +1,32 @@ -import operation from "../../_operations/brand-protection/urls/submit.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * submit command * @generated from apis/overlays/brand-protection.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 brand-protection urls submit\n\nSubmit one unlisted URL Scanner scan. The returned URL Scanner UUID replaces the numeric v1 URL ID." - ) - .option("url", { - type: "string", - description: "An HTTP or HTTPS URL.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + url: { kind: "parsed", brief: "An HTTP or HTTPS URL.", parse: String }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "submit", describe: "Submit a URL for scanning", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "brand-protection urls submit", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - url: argv["url"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf brand-protection urls submit", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/cloudforce-one/v2/brand-protection/url/submit`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Creating`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 brand-protection urls submit\n\nSubmit one unlisted URL Scanner scan. The returned URL Scanner UUID replaces the numeric v1 URL ID.", + ...parameters, + loader: () => import("./submit.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/crawl/create.handler.ts b/packages/cli/src/commands/_generated/browser-run/crawl/create.handler.ts new file mode 100644 index 0000000000..a205b82bca --- /dev/null +++ b/packages/cli/src/commands/_generated/browser-run/crawl/create.handler.ts @@ -0,0 +1,78 @@ +import operation from "../../_operations/browser-run/crawl/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + requestApi, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "browser-run crawl create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + cacheTTL: argv["cache-ttl"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf browser-run crawl create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/crawl`, + pathParams: {}, + query: queryParams, + bodyKind: "json", + body: argv.body !== undefined ? parseBody(argv.body) : undefined, + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const qs = new URLSearchParams( + Object.entries(queryParams) + .filter(([, v]) => v !== undefined) + .map(([k, v]) => [k, String(v)]) + ).toString(); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + const result = await withProgress(`Creating`, async () => + requestApi( + client, + "POST", + `/accounts/${accountId}/browser-rendering/crawl`, + { query: queryParams } + ) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/browser-run/crawl/create.ts b/packages/cli/src/commands/_generated/browser-run/crawl/create.ts index 82b30962eb..e1bead5327 100644 --- a/packages/cli/src/commands/_generated/browser-run/crawl/create.ts +++ b/packages/cli/src/commands/_generated/browser-run/crawl/create.ts @@ -1,111 +1,43 @@ -import operation from "../../_operations/browser-run/crawl/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/browser-run.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - requestApi, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 browser-run crawl create\n\nStarts a crawl job for the provided URL and its children. Check available options like `gotoOptions` and `waitFor*` to control page load behaviour." - ) - .option("cache-ttl", { - type: "number", - description: "Cache TTL default is 5s. Set to 0 to disable.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "cache-ttl": { + kind: "parsed", + brief: "Cache TTL default is 5s. Set to 0 to disable.", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Crawl websites.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "browser-run crawl create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - cacheTTL: argv["cache-ttl"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf browser-run crawl create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/crawl`, - pathParams: {}, - query: queryParams, - bodyKind: "json", - body: argv.body !== undefined ? parseBody(argv.body) : undefined, - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const qs = new URLSearchParams( - Object.entries(queryParams) - .filter(([, v]) => v !== undefined) - .map(([k, v]) => [k, String(v)]) - ).toString(); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - const result = await withProgress(`Creating`, async () => - requestApi( - client, - "POST", - `/accounts/${accountId}/browser-rendering/crawl`, - { query: queryParams } - ) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 browser-run crawl create\n\nStarts a crawl job for the provided URL and its children. Check available options like `gotoOptions` and `waitFor*` to control page load behaviour.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/crawl/delete.handler.ts b/packages/cli/src/commands/_generated/browser-run/crawl/delete.handler.ts new file mode 100644 index 0000000000..b3079a2445 --- /dev/null +++ b/packages/cli/src/commands/_generated/browser-run/crawl/delete.handler.ts @@ -0,0 +1,55 @@ +import operation from "../../_operations/browser-run/crawl/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "browser-run crawl delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf browser-run crawl delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/crawl/${argv["job-id"] == null ? "" : encodeURIComponent(String(argv["job-id"]))}`, + pathParams: { "job-id": String(argv["job-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + job_id: argv["job-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/browser-run/crawl/delete.ts b/packages/cli/src/commands/_generated/browser-run/crawl/delete.ts index bd648263b6..4b0ea488b4 100644 --- a/packages/cli/src/commands/_generated/browser-run/crawl/delete.ts +++ b/packages/cli/src/commands/_generated/browser-run/crawl/delete.ts @@ -1,91 +1,43 @@ -import operation from "../../_operations/browser-run/crawl/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/browser-run.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 browser-run crawl delete \n\nCancels an ongoing crawl job by setting its status to cancelled and stopping all queued URLs." - ) - .positional("job-id", { - type: "string", - description: "The ID of the crawl job to cancel.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "job-id", + brief: "The ID of the crawl job to cancel.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Cancel a crawl job.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "browser-run crawl delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf browser-run crawl delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/crawl/${argv["job-id"] == null ? "" : encodeURIComponent(String(argv["job-id"]))}`, - pathParams: { "job-id": String(argv["job-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - job_id: argv["job-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 browser-run crawl delete \n\nCancels an ongoing crawl job by setting its status to cancelled and stopping all queued URLs.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/crawl/get.handler.ts b/packages/cli/src/commands/_generated/browser-run/crawl/get.handler.ts new file mode 100644 index 0000000000..c99a8e9766 --- /dev/null +++ b/packages/cli/src/commands/_generated/browser-run/crawl/get.handler.ts @@ -0,0 +1,57 @@ +import operation from "../../_operations/browser-run/crawl/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "browser-run crawl get", + classification: { + safeFlags: ["status", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + cacheTTL: argv["cache-ttl"], + status: argv["status"], + cursor: argv["cursor"], + limit: argv["limit"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf browser-run crawl get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/crawl/${argv["job-id"] == null ? "" : encodeURIComponent(String(argv["job-id"]))}`, + pathParams: { "job-id": String(argv["job-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + job_id: argv["job-id"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/browser-run/crawl/get.ts b/packages/cli/src/commands/_generated/browser-run/crawl/get.ts index 079d578871..e29bb88032 100644 --- a/packages/cli/src/commands/_generated/browser-run/crawl/get.ts +++ b/packages/cli/src/commands/_generated/browser-run/crawl/get.ts @@ -1,40 +1,25 @@ -import operation from "../../_operations/browser-run/crawl/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/browser-run.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 browser-run crawl get \n\nReturns the result of a crawl job." - ) - .positional("job-id", { - type: "string", - description: "Crawl job ID.", - demandOption: true, - }) - .option("cache-ttl", { - type: "number", - description: "Cache TTL default is 5s. Set to 0 to disable.", - }) - .option("status", { - type: "string", - description: "Filter by URL status.", - choices: [ +const parameters = { + flags: { + "cache-ttl": { + kind: "parsed", + brief: "Cache TTL default is 5s. Set to 0 to disable.", + optional: true, + parse: Number, + }, + status: { + kind: "enum", + brief: "Filter by URL status.", + values: [ "queued", "errored", "completed", @@ -42,64 +27,36 @@ function builder(yargs: Argv) { "skipped", "cancelled", ], - }) - .option("cursor", { type: "number", description: "Cursor for pagination." }) - .option("limit", { type: "number", description: "Limit for pagination." }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + }, + cursor: { + kind: "parsed", + brief: "Cursor for pagination.", + optional: true, + parse: Number, + }, + limit: { + kind: "parsed", + brief: "Limit for pagination.", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "job-id", brief: "Crawl job ID.", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get crawl result.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "browser-run crawl get", - classification: { - safeFlags: ["status", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - cacheTTL: argv["cache-ttl"], - status: argv["status"], - cursor: argv["cursor"], - limit: argv["limit"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf browser-run crawl get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/crawl/${argv["job-id"] == null ? "" : encodeURIComponent(String(argv["job-id"]))}`, - pathParams: { "job-id": String(argv["job-id"] ?? "") }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - job_id: argv["job-id"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 browser-run crawl get \n\nReturns the result of a crawl job.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/crawl/index.ts b/packages/cli/src/commands/_generated/browser-run/crawl/index.ts index 7db4bd0afd..06db58e330 100644 --- a/packages/cli/src/commands/_generated/browser-run/crawl/index.ts +++ b/packages/cli/src/commands/_generated/browser-run/crawl/index.ts @@ -1,26 +1,21 @@ import $create from "./create.js"; import $delete from "./delete.js"; import $get from "./get.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * crawl command group * @generated from apis/overlays/browser-run.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "crawl", describe: "Operations for crawl", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($get) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + get: $get, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/browser/create.handler.ts b/packages/cli/src/commands/_generated/browser-run/devtools/browser/create.handler.ts new file mode 100644 index 0000000000..ff3280c1cd --- /dev/null +++ b/packages/cli/src/commands/_generated/browser-run/devtools/browser/create.handler.ts @@ -0,0 +1,100 @@ +import operation from "../../../_operations/browser-run/devtools/browser/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "browser-run devtools browser create", + classification: { + safeFlags: ["lab", "targets", "recording", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + keep_alive: argv["keep-alive"], + lab: argv["lab"], + targets: argv["targets"], + liveViewUrlExpiresInMs: argv["live-view-url-expires-in-ms"], + recording: argv["recording"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf browser-run devtools browser create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/browser`, + pathParams: {}, + query: queryParams, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + guardrails: { + allowedDomainSets: argv["guardrails-allowed-domain-sets"], + allowedDomains: argv["guardrails-allowed-domains"], + }, + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const qs = new URLSearchParams( + Object.entries(queryParams) + .filter(([, v]) => v !== undefined) + .map(([k, v]) => [k, String(v)]) + ).toString(); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + guardrails: { + allowedDomainSets: argv["guardrails-allowed-domain-sets"], + allowedDomains: argv["guardrails-allowed-domains"], + }, + }); + const qs = new URLSearchParams( + Object.entries(queryParams) + .filter(([, v]) => v !== undefined) + .map(([k, v]) => [k, String(v)]) + ).toString(); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/browser/create.ts b/packages/cli/src/commands/_generated/browser-run/devtools/browser/create.ts index 962a5a3a34..7da1fac268 100644 --- a/packages/cli/src/commands/_generated/browser-run/devtools/browser/create.ts +++ b/packages/cli/src/commands/_generated/browser-run/devtools/browser/create.ts @@ -1,159 +1,77 @@ -import operation from "../../../_operations/browser-run/devtools/browser/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/browser-run.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 browser-run devtools browser create\n\nAcquires a browser and returns its session ID and websocket URL. Optionally accepts a JSON body with session guardrails to restrict outbound HTTP/S traffic." - ) - .option("keep-alive", { - type: "number", - description: "Keep-alive time in milliseconds.", - }) - .option("lab", { - type: "boolean", - description: "Use experimental browser.", - }) - .option("targets", { - type: "boolean", - description: "Include browser targets in response.", - }) - .option("live-view-url-expires-in-ms", { - type: "number", - description: +const parameters = { + flags: { + "keep-alive": { + kind: "parsed", + brief: "Keep-alive time in milliseconds.", + optional: true, + parse: Number, + }, + lab: { + kind: "boolean", + brief: "Use experimental browser.", + optional: true, + }, + targets: { + kind: "boolean", + brief: "Include browser targets in response.", + optional: true, + }, + "live-view-url-expires-in-ms": { + kind: "parsed", + brief: "How long the live view URL remains valid, in milliseconds (max 60 minutes). Only used when targets is true.", - }) - .option("recording", { type: "boolean", description: "Recording" }) - .option("guardrails-allowed-domain-sets", { - type: "string", - array: true, - description: + optional: true, + parse: Number, + }, + recording: { kind: "boolean", brief: "Recording", optional: true }, + "guardrails-allowed-domain-sets": { + kind: "parsed", + brief: "Max 4 entries: curated preset names (common-cdns) and/or https URLs of newline-separated hostname lists.", - }) - .option("guardrails-allowed-domains", { - type: "string", - array: true, - description: + variadic: true, + optional: true, + parse: String, + }, + "guardrails-allowed-domains": { + kind: "parsed", + brief: "Hostname patterns, max 50. Supports exact hosts (example.com) or a single * wildcard anywhere. Prefer *.example.com (subdomain wildcard) over *example.com (prefix wildcard) to avoid matching overbroad lookalikes like evilexample.com.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + variadic: true, + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create", describe: "Get a browser session ID.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "browser-run devtools browser create", - classification: { - safeFlags: ["lab", "targets", "recording", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - keep_alive: argv["keep-alive"], - lab: argv["lab"], - targets: argv["targets"], - liveViewUrlExpiresInMs: argv["live-view-url-expires-in-ms"], - recording: argv["recording"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf browser-run devtools browser create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/browser`, - pathParams: {}, - query: queryParams, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - guardrails: { - allowedDomainSets: argv["guardrails-allowed-domain-sets"], - allowedDomains: argv["guardrails-allowed-domains"], - }, - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const qs = new URLSearchParams( - Object.entries(queryParams) - .filter(([, v]) => v !== undefined) - .map(([k, v]) => [k, String(v)]) - ).toString(); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - guardrails: { - allowedDomainSets: argv["guardrails-allowed-domain-sets"], - allowedDomains: argv["guardrails-allowed-domains"], - }, - }); - const qs = new URLSearchParams( - Object.entries(queryParams) - .filter(([, v]) => v !== undefined) - .map(([k, v]) => [k, String(v)]) - ).toString(); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 browser-run devtools browser create\n\nAcquires a browser and returns its session ID and websocket URL. Optionally accepts a JSON body with session guardrails to restrict outbound HTTP/S traffic.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/browser/delete.handler.ts b/packages/cli/src/commands/_generated/browser-run/devtools/browser/delete.handler.ts new file mode 100644 index 0000000000..34d65541e8 --- /dev/null +++ b/packages/cli/src/commands/_generated/browser-run/devtools/browser/delete.handler.ts @@ -0,0 +1,55 @@ +import operation from "../../../_operations/browser-run/devtools/browser/delete.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./delete.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { confirmDelete } from "#lib/prompt.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "browser-run devtools browser delete", + classification: { + safeFlags: ["dry-run", "force"], + shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf browser-run devtools browser delete", + method: "DELETE", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/browser/${argv["session-id"] == null ? "" : encodeURIComponent(String(argv["session-id"]))}`, + pathParams: { "session-id": String(argv["session-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (!(await confirmDelete({ force: Boolean(argv.force) }))) { + return; + } + + const result = await withProgress(`Deleting`, async () => + client.send(operation, { + account_id: accountId, + session_id: argv["session-id"], + }) + ); + formatOutput(result, { successLabel: `Deleted` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/browser/delete.ts b/packages/cli/src/commands/_generated/browser-run/devtools/browser/delete.ts index eced16ec03..af464bd2a9 100644 --- a/packages/cli/src/commands/_generated/browser-run/devtools/browser/delete.ts +++ b/packages/cli/src/commands/_generated/browser-run/devtools/browser/delete.ts @@ -1,91 +1,43 @@ -import operation from "../../../_operations/browser-run/devtools/browser/delete.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * delete command * @generated from apis/overlays/browser-run.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { confirmDelete } from "#lib/prompt.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 browser-run devtools browser delete \n\nCloses an existing browser session." - ) - .positional("session-id", { - type: "string", - description: "Browser session ID to close.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("force", { - type: "boolean", + }, + force: { + kind: "boolean", + brief: "Skip confirmation (useful in scripts and CI)", alias: "f", - description: "Skip confirmation (useful in scripts and CI)", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "session-id", + brief: "Browser session ID to close.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "delete ", describe: "Close browser session.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "browser-run devtools browser delete", - classification: { - safeFlags: ["dry-run", "force"], - shortFlagAliases: { f: { canonical: "force", type: "boolean" } }, - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf browser-run devtools browser delete", - method: "DELETE", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/browser/${argv["session-id"] == null ? "" : encodeURIComponent(String(argv["session-id"]))}`, - pathParams: { "session-id": String(argv["session-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (!(await confirmDelete({ force: Boolean(argv.force) }))) { - return; - } - - const result = await withProgress(`Deleting`, async () => - client.send(operation, { - account_id: accountId, - session_id: argv["session-id"], - }) - ); - formatOutput(result, { successLabel: `Deleted` }); - } - ), -}; + usage: + "$0 browser-run devtools browser delete \n\nCloses an existing browser session.", + ...parameters, + loader: () => import("./delete.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/browser/index.ts b/packages/cli/src/commands/_generated/browser-run/devtools/browser/index.ts index 575d5ba1a0..809cc7184a 100644 --- a/packages/cli/src/commands/_generated/browser-run/devtools/browser/index.ts +++ b/packages/cli/src/commands/_generated/browser-run/devtools/browser/index.ts @@ -4,29 +4,24 @@ import $liveview from "./live-view/index.js"; import $protocol from "./protocol.js"; import $targets from "./targets/index.js"; import $version from "./version.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * browser command group * @generated from apis/overlays/browser-run.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "browser", describe: "Operations for devtools.browser", - builder: (yargs) => { - return yargs - .command($create) - .command($delete) - .command($protocol) - .command($version) - .command($liveview) - .command($targets) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, + delete: $delete, + protocol: $protocol, + version: $version, + "live-view": $liveview, + targets: $targets, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/browser/live-view/create.handler.ts b/packages/cli/src/commands/_generated/browser-run/devtools/browser/live-view/create.handler.ts new file mode 100644 index 0000000000..e5225b8de0 --- /dev/null +++ b/packages/cli/src/commands/_generated/browser-run/devtools/browser/live-view/create.handler.ts @@ -0,0 +1,95 @@ +import operation from "../../../../_operations/browser-run/devtools/browser/live-view/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { compactBody, parseBody } from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "browser-run devtools browser live-view create", + classification: { + safeFlags: ["guardrails-mode", "view-mode", "dry-run"], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf browser-run devtools browser live-view create", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/browser/${argv["session-id"] == null ? "" : encodeURIComponent(String(argv["session-id"]))}/live_view`, + pathParams: { "session-id": String(argv["session-id"] ?? "") }, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody({ + expiresInMs: argv["expires-in-ms"], + guardrails: { + mode: argv["guardrails-mode"], + }, + mode: argv["view-mode"], + targetId: resolveFileToken( + argv["target-id"] as string | undefined, + "target-id", + "text" + ), + }), + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + session_id: argv["session-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody({ + expiresInMs: argv["expires-in-ms"], + guardrails: { + mode: argv["guardrails-mode"], + }, + mode: argv["view-mode"], + targetId: resolveFileToken( + argv["target-id"] as string | undefined, + "target-id", + "text" + ), + }); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + session_id: argv["session-id"], + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/browser/live-view/create.ts b/packages/cli/src/commands/_generated/browser-run/devtools/browser/live-view/create.ts index b4d8f58657..274241485e 100644 --- a/packages/cli/src/commands/_generated/browser-run/devtools/browser/live-view/create.ts +++ b/packages/cli/src/commands/_generated/browser-run/devtools/browser/live-view/create.ts @@ -1,158 +1,72 @@ -import operation from "../../../../_operations/browser-run/devtools/browser/live-view/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/browser-run.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { compactBody, parseBody } from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 browser-run devtools browser live-view create \n\nGenerates time-limited URLs to view a remote browser session. Set `guardrails: { mode: 'readonly' }` to create a view-only link." - ) - .positional("session-id", { - type: "string", - description: "Browser session ID", - demandOption: true, - }) - .option("expires-in-ms", { - type: "number", - description: +const parameters = { + flags: { + "expires-in-ms": { + kind: "parsed", + brief: "How long the live view URLs remain valid, in milliseconds. Default: 5 minutes. Max: 60 minutes.", - default: 300000, - }) - .option("guardrails-mode", { - type: "string", - description: "The guardrails.mode field", + default: "300000", + parse: Number, + }, + "guardrails-mode": { + kind: "parsed", + brief: "The guardrails.mode field", + optional: true, choices: ["readonly"], - }) - .coerce("guardrails-mode", (value) => - resolveFileToken(value, "guardrails-mode", "text") - ) - .option("view-mode", { - type: "string", - description: + parse: String, + coerce: (value: string) => + resolveFileToken(value, "guardrails-mode", "text"), + }, + "view-mode": { + kind: "parsed", + brief: "UI mode: 'devtools' (Chrome DevTools), 'tab' (single tab view), 'full' (multi-tab browser)", - choices: ["devtools", "tab", "full"], default: "devtools", - }) - .coerce("view-mode", (value) => - resolveFileToken(value, "view-mode", "text") - ) - .option("target-id", { - type: "string", - description: + choices: ["devtools", "tab", "full"], + parse: String, + coerce: (value: string) => resolveFileToken(value, "view-mode", "text"), + }, + "target-id": { + kind: "parsed", + brief: "Target ID (page) to connect to. If omitted, auto-resolves to the first active page.", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }) - .option("body", { - type: "string", - description: "Raw JSON request body (bypasses individual flags)", - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + body: { + kind: "parsed", + brief: "Raw JSON request body (bypasses individual flags)", + optional: true, + parse: String, + }, + }, + operands: [ + { placeholder: "session-id", brief: "Browser session ID", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Mint live view URLs for a browser session", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "browser-run devtools browser live-view create", - classification: { - safeFlags: ["guardrails-mode", "view-mode", "dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf browser-run devtools browser live-view create", - method: "POST", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/browser/${argv["session-id"] == null ? "" : encodeURIComponent(String(argv["session-id"]))}/live_view`, - pathParams: { "session-id": String(argv["session-id"] ?? "") }, - bodyKind: "json", - body: - argv.body !== undefined - ? parseBody(argv.body) - : compactBody({ - expiresInMs: argv["expires-in-ms"], - guardrails: { - mode: argv["guardrails-mode"], - }, - mode: argv["view-mode"], - targetId: resolveFileToken( - argv["target-id"] as string | undefined, - "target-id", - "text" - ), - }), - }); - return; - } - const parsedBody = - argv.body !== undefined ? parseBody(argv.body) : undefined; - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - if (argv.body !== undefined) { - const bodyData = parsedBody; - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - session_id: argv["session-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - return; - } - - // Assemble request body from individual flags - const bodyData = compactBody({ - expiresInMs: argv["expires-in-ms"], - guardrails: { - mode: argv["guardrails-mode"], - }, - mode: argv["view-mode"], - targetId: resolveFileToken( - argv["target-id"] as string | undefined, - "target-id", - "text" - ), - }); - const result = await withProgress(`Creating`, async () => - client.send(operation, { - body: bodyData, - account_id: accountId, - session_id: argv["session-id"], - }) - ); - formatOutput(result, { successLabel: `Created` }); - } - ), -}; + usage: + "$0 browser-run devtools browser live-view create \n\nGenerates time-limited URLs to view a remote browser session. Set `guardrails: { mode: 'readonly' }` to create a view-only link.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/browser/live-view/index.ts b/packages/cli/src/commands/_generated/browser-run/devtools/browser/live-view/index.ts index 1a424501e9..c571e673f4 100644 --- a/packages/cli/src/commands/_generated/browser-run/devtools/browser/live-view/index.ts +++ b/packages/cli/src/commands/_generated/browser-run/devtools/browser/live-view/index.ts @@ -1,22 +1,17 @@ import $create from "./create.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * live-view command group * @generated from apis/overlays/browser-run.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "live-view", describe: "Operations for devtools.browser.live-view", - builder: (yargs) => { - return yargs - .command($create) - .demandCommand(1, "Please specify a subcommand"); + routes: { + create: $create, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/browser/protocol.handler.ts b/packages/cli/src/commands/_generated/browser-run/devtools/browser/protocol.handler.ts new file mode 100644 index 0000000000..63ab94f38a --- /dev/null +++ b/packages/cli/src/commands/_generated/browser-run/devtools/browser/protocol.handler.ts @@ -0,0 +1,49 @@ +import operation from "../../../_operations/browser-run/devtools/browser/protocol.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./protocol.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "browser-run devtools browser protocol", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf browser-run devtools browser protocol", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/browser/${argv["session-id"] == null ? "" : encodeURIComponent(String(argv["session-id"]))}/json/protocol`, + pathParams: { "session-id": String(argv["session-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + session_id: argv["session-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/browser/protocol.ts b/packages/cli/src/commands/_generated/browser-run/devtools/browser/protocol.ts index 3324793920..eee54293d8 100644 --- a/packages/cli/src/commands/_generated/browser-run/devtools/browser/protocol.ts +++ b/packages/cli/src/commands/_generated/browser-run/devtools/browser/protocol.ts @@ -1,79 +1,33 @@ -import operation from "../../../_operations/browser-run/devtools/browser/protocol.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * protocol command * @generated from apis/overlays/browser-run.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 browser-run devtools browser protocol \n\nReturns the complete Chrome DevTools Protocol schema including all domains, commands, events, and types. This schema describes the entire CDP API surface." - ) - .positional("session-id", { - type: "string", - description: "Browser session ID.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "session-id", brief: "Browser session ID.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "protocol ", describe: "Get Chrome DevTools Protocol schema.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "browser-run devtools browser protocol", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf browser-run devtools browser protocol", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/browser/${argv["session-id"] == null ? "" : encodeURIComponent(String(argv["session-id"]))}/json/protocol`, - pathParams: { "session-id": String(argv["session-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - session_id: argv["session-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 browser-run devtools browser protocol \n\nReturns the complete Chrome DevTools Protocol schema including all domains, commands, events, and types. This schema describes the entire CDP API surface.", + ...parameters, + loader: () => import("./protocol.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/activate.handler.ts b/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/activate.handler.ts new file mode 100644 index 0000000000..5d7cac2618 --- /dev/null +++ b/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/activate.handler.ts @@ -0,0 +1,53 @@ +import operation from "../../../../_operations/browser-run/devtools/browser/targets/activate.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./activate.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "browser-run devtools browser targets activate", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf browser-run devtools browser targets activate", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/browser/${argv["session-id"] == null ? "" : encodeURIComponent(String(argv["session-id"]))}/json/activate/${argv["target-id"] == null ? "" : encodeURIComponent(String(argv["target-id"]))}`, + pathParams: { + "session-id": String(argv["session-id"] ?? ""), + "target-id": String(argv["target-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + session_id: argv["session-id"], + target_id: argv["target-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/activate.ts b/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/activate.ts index 990ee9bf97..4a18f178bb 100644 --- a/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/activate.ts +++ b/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/activate.ts @@ -1,88 +1,42 @@ -import operation from "../../../../_operations/browser-run/devtools/browser/targets/activate.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * activate command * @generated from apis/overlays/browser-run.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 browser-run devtools browser targets activate \n\nActivates (brings to front) a specific browser target by its ID." - ) - .positional("target-id", { - type: "string", - description: "Target ID to activate.", - demandOption: true, - }) - .option("session-id", { - type: "string", - description: "Browser session ID.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "session-id": { + kind: "parsed", + brief: "Browser session ID.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { + placeholder: "target-id", + brief: "Target ID to activate.", + parse: String, + }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "activate ", describe: "Activate a browser target.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "browser-run devtools browser targets activate", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf browser-run devtools browser targets activate", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/browser/${argv["session-id"] == null ? "" : encodeURIComponent(String(argv["session-id"]))}/json/activate/${argv["target-id"] == null ? "" : encodeURIComponent(String(argv["target-id"]))}`, - pathParams: { - "session-id": String(argv["session-id"] ?? ""), - "target-id": String(argv["target-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - session_id: argv["session-id"], - target_id: argv["target-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 browser-run devtools browser targets activate \n\nActivates (brings to front) a specific browser target by its ID.", + ...parameters, + loader: () => import("./activate.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/close.handler.ts b/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/close.handler.ts new file mode 100644 index 0000000000..193cd50c64 --- /dev/null +++ b/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/close.handler.ts @@ -0,0 +1,53 @@ +import operation from "../../../../_operations/browser-run/devtools/browser/targets/close.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./close.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "browser-run devtools browser targets close", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf browser-run devtools browser targets close", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/browser/${argv["session-id"] == null ? "" : encodeURIComponent(String(argv["session-id"]))}/json/close/${argv["target-id"] == null ? "" : encodeURIComponent(String(argv["target-id"]))}`, + pathParams: { + "session-id": String(argv["session-id"] ?? ""), + "target-id": String(argv["target-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + session_id: argv["session-id"], + target_id: argv["target-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/close.ts b/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/close.ts index 0fa58e869e..12d013ef81 100644 --- a/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/close.ts +++ b/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/close.ts @@ -1,88 +1,38 @@ -import operation from "../../../../_operations/browser-run/devtools/browser/targets/close.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * close command * @generated from apis/overlays/browser-run.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 browser-run devtools browser targets close \n\nCloses a specific browser target (tab, page, etc.) by its ID. Returns 'Target is closing' on success or an error if the target is not found." - ) - .positional("target-id", { - type: "string", - description: "Target ID to close.", - demandOption: true, - }) - .option("session-id", { - type: "string", - description: "Browser session ID.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "session-id": { + kind: "parsed", + brief: "Browser session ID.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "target-id", brief: "Target ID to close.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "close ", describe: "Close a browser target.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "browser-run devtools browser targets close", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf browser-run devtools browser targets close", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/browser/${argv["session-id"] == null ? "" : encodeURIComponent(String(argv["session-id"]))}/json/close/${argv["target-id"] == null ? "" : encodeURIComponent(String(argv["target-id"]))}`, - pathParams: { - "session-id": String(argv["session-id"] ?? ""), - "target-id": String(argv["target-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - session_id: argv["session-id"], - target_id: argv["target-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 browser-run devtools browser targets close \n\nCloses a specific browser target (tab, page, etc.) by its ID. Returns 'Target is closing' on success or an error if the target is not found.", + ...parameters, + loader: () => import("./close.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/create.handler.ts b/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/create.handler.ts new file mode 100644 index 0000000000..ad10888f2c --- /dev/null +++ b/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/create.handler.ts @@ -0,0 +1,55 @@ +import operation from "../../../../_operations/browser-run/devtools/browser/targets/create.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./create.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "browser-run devtools browser targets create", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + url: argv["url"], + liveViewUrlExpiresInMs: argv["live-view-url-expires-in-ms"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf browser-run devtools browser targets create", + method: "PUT", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/browser/${argv["session-id"] == null ? "" : encodeURIComponent(String(argv["session-id"]))}/json/new`, + pathParams: { "session-id": String(argv["session-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Updating`, async () => + client.send(operation, { + account_id: accountId, + session_id: argv["session-id"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Updated` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/create.ts b/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/create.ts index 6195c3fcdd..5945c35108 100644 --- a/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/create.ts +++ b/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/create.ts @@ -1,91 +1,41 @@ -import operation from "../../../../_operations/browser-run/devtools/browser/targets/create.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * create command * @generated from apis/overlays/browser-run.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 browser-run devtools browser targets create \n\nOpens a new tab in the browser. Optionally specify a URL to navigate to." - ) - .positional("session-id", { - type: "string", - description: "Browser session ID.", - demandOption: true, - }) - .option("url", { type: "string", description: "Url" }) - .option("live-view-url-expires-in-ms", { - type: "number", - description: +const parameters = { + flags: { + url: { kind: "parsed", brief: "Url", optional: true, parse: String }, + "live-view-url-expires-in-ms": { + kind: "parsed", + brief: "How long the live view URL remains valid, in milliseconds (max 60 minutes)", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "session-id", brief: "Browser session ID.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "create ", describe: "Open a new browser tab.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "browser-run devtools browser targets create", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - url: argv["url"], - liveViewUrlExpiresInMs: argv["live-view-url-expires-in-ms"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf browser-run devtools browser targets create", - method: "PUT", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/browser/${argv["session-id"] == null ? "" : encodeURIComponent(String(argv["session-id"]))}/json/new`, - pathParams: { "session-id": String(argv["session-id"] ?? "") }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Updating`, async () => - client.send(operation, { - account_id: accountId, - session_id: argv["session-id"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Updated` }); - } - ), -}; + usage: + "$0 browser-run devtools browser targets create \n\nOpens a new tab in the browser. Optionally specify a URL to navigate to.", + ...parameters, + loader: () => import("./create.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/get.handler.ts b/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/get.handler.ts new file mode 100644 index 0000000000..32e643f6f9 --- /dev/null +++ b/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/get.handler.ts @@ -0,0 +1,53 @@ +import operation from "../../../../_operations/browser-run/devtools/browser/targets/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "browser-run devtools browser targets get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf browser-run devtools browser targets get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/browser/${argv["session-id"] == null ? "" : encodeURIComponent(String(argv["session-id"]))}/json/list/${argv["target-id"] == null ? "" : encodeURIComponent(String(argv["target-id"]))}`, + pathParams: { + "session-id": String(argv["session-id"] ?? ""), + "target-id": String(argv["target-id"] ?? ""), + }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + session_id: argv["session-id"], + target_id: argv["target-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/get.ts b/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/get.ts index aa23b22c07..05a6b3920c 100644 --- a/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/get.ts +++ b/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/get.ts @@ -1,88 +1,36 @@ -import operation from "../../../../_operations/browser-run/devtools/browser/targets/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/browser-run.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 browser-run devtools browser targets get \n\nReturns the debuggable target with the given ID." - ) - .positional("target-id", { - type: "string", - description: "Target ID.", - demandOption: true, - }) - .option("session-id", { - type: "string", - description: "Browser session ID.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "session-id": { + kind: "parsed", + brief: "Browser session ID.", + parse: String, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [{ placeholder: "target-id", brief: "Target ID.", parse: String }], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get a target by ID.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "browser-run devtools browser targets get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf browser-run devtools browser targets get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/browser/${argv["session-id"] == null ? "" : encodeURIComponent(String(argv["session-id"]))}/json/list/${argv["target-id"] == null ? "" : encodeURIComponent(String(argv["target-id"]))}`, - pathParams: { - "session-id": String(argv["session-id"] ?? ""), - "target-id": String(argv["target-id"] ?? ""), - }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - session_id: argv["session-id"], - target_id: argv["target-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 browser-run devtools browser targets get \n\nReturns the debuggable target with the given ID.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/index.ts b/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/index.ts index 3835a5d861..a71d2b5cbe 100644 --- a/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/index.ts +++ b/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/index.ts @@ -3,28 +3,23 @@ import $close from "./close.js"; import $create from "./create.js"; import $get from "./get.js"; import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * targets command group * @generated from apis/overlays/browser-run.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "targets", describe: "Operations for devtools.browser.targets", - builder: (yargs) => { - return yargs - .command($activate) - .command($close) - .command($create) - .command($get) - .command($list) - .demandCommand(1, "Please specify a subcommand"); + routes: { + activate: $activate, + close: $close, + create: $create, + get: $get, + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/list.handler.ts b/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/list.handler.ts new file mode 100644 index 0000000000..ab6b1353b5 --- /dev/null +++ b/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/list.handler.ts @@ -0,0 +1,54 @@ +import operation from "../../../../_operations/browser-run/devtools/browser/targets/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "browser-run devtools browser targets list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + liveViewUrlExpiresInMs: argv["live-view-url-expires-in-ms"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf browser-run devtools browser targets list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/browser/${argv["session-id"] == null ? "" : encodeURIComponent(String(argv["session-id"]))}/json/list`, + pathParams: { "session-id": String(argv["session-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + session_id: argv["session-id"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/list.ts b/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/list.ts index 5ff2394137..e69a77a6a0 100644 --- a/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/list.ts +++ b/packages/cli/src/commands/_generated/browser-run/devtools/browser/targets/list.ts @@ -1,89 +1,43 @@ -import operation from "../../../../_operations/browser-run/devtools/browser/targets/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/browser-run.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 browser-run devtools browser targets list\n\nReturns a list of all debuggable targets including tabs, pages, service workers, and other browser contexts." - ) - .option("session-id", { - type: "string", - description: "Browser session ID.", - demandOption: true, - }) - .option("live-view-url-expires-in-ms", { - type: "number", - description: +const parameters = { + flags: { + "session-id": { + kind: "parsed", + brief: "Browser session ID.", + parse: String, + }, + "live-view-url-expires-in-ms": { + kind: "parsed", + brief: "How long the live view URLs remain valid, in milliseconds (max 60 minutes)", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List targets.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "browser-run devtools browser targets list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - liveViewUrlExpiresInMs: argv["live-view-url-expires-in-ms"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf browser-run devtools browser targets list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/browser/${argv["session-id"] == null ? "" : encodeURIComponent(String(argv["session-id"]))}/json/list`, - pathParams: { "session-id": String(argv["session-id"] ?? "") }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - session_id: argv["session-id"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 browser-run devtools browser targets list\n\nReturns a list of all debuggable targets including tabs, pages, service workers, and other browser contexts.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/browser/version.handler.ts b/packages/cli/src/commands/_generated/browser-run/devtools/browser/version.handler.ts new file mode 100644 index 0000000000..165faf922d --- /dev/null +++ b/packages/cli/src/commands/_generated/browser-run/devtools/browser/version.handler.ts @@ -0,0 +1,49 @@ +import operation from "../../../_operations/browser-run/devtools/browser/version.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./version.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "browser-run devtools browser version", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf browser-run devtools browser version", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/browser/${argv["session-id"] == null ? "" : encodeURIComponent(String(argv["session-id"]))}/json/version`, + pathParams: { "session-id": String(argv["session-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + session_id: argv["session-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/browser/version.ts b/packages/cli/src/commands/_generated/browser-run/devtools/browser/version.ts index 8d228f43c6..19bda5240a 100644 --- a/packages/cli/src/commands/_generated/browser-run/devtools/browser/version.ts +++ b/packages/cli/src/commands/_generated/browser-run/devtools/browser/version.ts @@ -1,79 +1,33 @@ -import operation from "../../../_operations/browser-run/devtools/browser/version.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * version command * @generated from apis/overlays/browser-run.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 browser-run devtools browser version \n\nGet browser version metadata." - ) - .positional("session-id", { - type: "string", - description: "Browser session ID.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "session-id", brief: "Browser session ID.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "version ", describe: "Get browser version metadata.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "browser-run devtools browser version", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf browser-run devtools browser version", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/browser/${argv["session-id"] == null ? "" : encodeURIComponent(String(argv["session-id"]))}/json/version`, - pathParams: { "session-id": String(argv["session-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - session_id: argv["session-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 browser-run devtools browser version \n\nGet browser version metadata.", + ...parameters, + loader: () => import("./version.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/index.ts b/packages/cli/src/commands/_generated/browser-run/devtools/index.ts index de06c7ca9a..f9aa268d6e 100644 --- a/packages/cli/src/commands/_generated/browser-run/devtools/index.ts +++ b/packages/cli/src/commands/_generated/browser-run/devtools/index.ts @@ -1,26 +1,21 @@ import $browser from "./browser/index.js"; import $json from "./json/index.js"; import $session from "./session/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * devtools command group * @generated from apis/overlays/browser-run.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "devtools", describe: "Operations for devtools", - builder: (yargs) => { - return yargs - .command($browser) - .command($json) - .command($session) - .demandCommand(1, "Please specify a subcommand"); + routes: { + browser: $browser, + json: $json, + session: $session, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/json/get.handler.ts b/packages/cli/src/commands/_generated/browser-run/devtools/json/get.handler.ts new file mode 100644 index 0000000000..3097ed0907 --- /dev/null +++ b/packages/cli/src/commands/_generated/browser-run/devtools/json/get.handler.ts @@ -0,0 +1,54 @@ +import operation from "../../../_operations/browser-run/devtools/json/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "browser-run devtools json get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + liveViewUrlExpiresInMs: argv["live-view-url-expires-in-ms"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf browser-run devtools json get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/browser/${argv["session-id"] == null ? "" : encodeURIComponent(String(argv["session-id"]))}/json`, + pathParams: { "session-id": String(argv["session-id"] ?? "") }, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + session_id: argv["session-id"], + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/json/get.ts b/packages/cli/src/commands/_generated/browser-run/devtools/json/get.ts index 45fac5273b..f7ef24998e 100644 --- a/packages/cli/src/commands/_generated/browser-run/devtools/json/get.ts +++ b/packages/cli/src/commands/_generated/browser-run/devtools/json/get.ts @@ -1,89 +1,40 @@ -import operation from "../../../_operations/browser-run/devtools/json/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/browser-run.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 browser-run devtools json get \n\nReturns a list of all debuggable targets including tabs, pages, service workers, and other browser contexts." - ) - .positional("session-id", { - type: "string", - description: "Browser session ID.", - demandOption: true, - }) - .option("live-view-url-expires-in-ms", { - type: "number", - description: +const parameters = { + flags: { + "live-view-url-expires-in-ms": { + kind: "parsed", + brief: "How long the live view URLs remain valid, in milliseconds (max 60 minutes)", - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", + optional: true, + parse: Number, + }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "session-id", brief: "Browser session ID.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "List targets.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "browser-run devtools json get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - liveViewUrlExpiresInMs: argv["live-view-url-expires-in-ms"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf browser-run devtools json get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/browser/${argv["session-id"] == null ? "" : encodeURIComponent(String(argv["session-id"]))}/json`, - pathParams: { "session-id": String(argv["session-id"] ?? "") }, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - session_id: argv["session-id"], - ...queryParams, - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 browser-run devtools json get \n\nReturns a list of all debuggable targets including tabs, pages, service workers, and other browser contexts.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/json/index.ts b/packages/cli/src/commands/_generated/browser-run/devtools/json/index.ts index 47a597d454..dc225d09f3 100644 --- a/packages/cli/src/commands/_generated/browser-run/devtools/json/index.ts +++ b/packages/cli/src/commands/_generated/browser-run/devtools/json/index.ts @@ -1,20 +1,17 @@ import $get from "./get.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * json command group * @generated from apis/overlays/browser-run.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "json", describe: "Operations for devtools.json", - builder: (yargs) => { - return yargs.command($get).demandCommand(1, "Please specify a subcommand"); + routes: { + get: $get, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/session/get.handler.ts b/packages/cli/src/commands/_generated/browser-run/devtools/session/get.handler.ts new file mode 100644 index 0000000000..5343e617ba --- /dev/null +++ b/packages/cli/src/commands/_generated/browser-run/devtools/session/get.handler.ts @@ -0,0 +1,49 @@ +import operation from "../../../_operations/browser-run/devtools/session/get.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./get.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "browser-run devtools session get", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf browser-run devtools session get", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/session/${argv["session-id"] == null ? "" : encodeURIComponent(String(argv["session-id"]))}`, + pathParams: { "session-id": String(argv["session-id"] ?? "") }, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { + account_id: accountId, + session_id: argv["session-id"], + }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/session/get.ts b/packages/cli/src/commands/_generated/browser-run/devtools/session/get.ts index fabe0654d6..9906027cc3 100644 --- a/packages/cli/src/commands/_generated/browser-run/devtools/session/get.ts +++ b/packages/cli/src/commands/_generated/browser-run/devtools/session/get.ts @@ -1,79 +1,33 @@ -import operation from "../../../_operations/browser-run/devtools/session/get.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * get command * @generated from apis/overlays/browser-run.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 browser-run devtools session get \n\nGet details for a specific browser session." - ) - .positional("session-id", { - type: "string", - description: "Session ID.", - demandOption: true, - }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [ + { placeholder: "session-id", brief: "Session ID.", parse: String }, + ], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "get ", describe: "Get session details.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "browser-run devtools session get", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf browser-run devtools session get", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/session/${argv["session-id"] == null ? "" : encodeURIComponent(String(argv["session-id"]))}`, - pathParams: { "session-id": String(argv["session-id"] ?? "") }, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { - account_id: accountId, - session_id: argv["session-id"], - }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 browser-run devtools session get \n\nGet details for a specific browser session.", + ...parameters, + loader: () => import("./get.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/session/index.ts b/packages/cli/src/commands/_generated/browser-run/devtools/session/index.ts index b9f4ae9e28..94c46330d5 100644 --- a/packages/cli/src/commands/_generated/browser-run/devtools/session/index.ts +++ b/packages/cli/src/commands/_generated/browser-run/devtools/session/index.ts @@ -1,24 +1,19 @@ import $get from "./get.js"; import $list from "./list.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * session command group * @generated from apis/overlays/browser-run.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "session", describe: "Operations for devtools.session", - builder: (yargs) => { - return yargs - .command($get) - .command($list) - .demandCommand(1, "Please specify a subcommand"); + routes: { + get: $get, + list: $list, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/session/list.handler.ts b/packages/cli/src/commands/_generated/browser-run/devtools/session/list.handler.ts new file mode 100644 index 0000000000..67af9caf2d --- /dev/null +++ b/packages/cli/src/commands/_generated/browser-run/devtools/session/list.handler.ts @@ -0,0 +1,51 @@ +import operation from "../../../_operations/browser-run/devtools/session/list.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./list.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "browser-run devtools session list", + classification: { safeFlags: ["dry-run"] } satisfies ArgClassification< + typeof argv + >, + }, + argv as Record, + async () => { + const queryParams: Record = { + limit: argv["limit"], + offset: argv["offset"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf browser-run devtools session list", + method: "GET", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/session`, + pathParams: {}, + query: queryParams, + bodyKind: "none", + }); + return; + } + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + const result = await withProgress(`Loading`, async () => + client.send(operation, { account_id: accountId, ...queryParams }) + ); + formatOutput(result, { successLabel: `Loaded` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/browser-run/devtools/session/list.ts b/packages/cli/src/commands/_generated/browser-run/devtools/session/list.ts index c7ada8e12b..3f1e486ca6 100644 --- a/packages/cli/src/commands/_generated/browser-run/devtools/session/list.ts +++ b/packages/cli/src/commands/_generated/browser-run/devtools/session/list.ts @@ -1,78 +1,33 @@ -import operation from "../../../_operations/browser-run/devtools/session/list.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * list command * @generated from apis/overlays/browser-run.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 browser-run devtools session list\n\nList active browser sessions." - ) - .option("limit", { type: "number", description: "Limit" }) - .option("offset", { type: "number", description: "Offset" }) - .option("dry-run", { - type: "boolean", - description: "Validate and show what would happen without executing", +const parameters = { + flags: { + limit: { kind: "parsed", brief: "Limit", optional: true, parse: Number }, + offset: { kind: "parsed", brief: "Offset", optional: true, parse: Number }, + "dry-run": { + kind: "boolean", + brief: "Validate and show what would happen without executing", default: false, - }); -} - -type Args = InferArgs; - -const command: CommandModule = { + }, + }, + operands: [], +} as const satisfies ApiParameters; +export type Args = ApiInputs; +const command = apiCommand({ command: "list", describe: "List sessions.", - builder, - handler: async (argv): Promise => - runWithTelemetry( - { - command: "browser-run devtools session list", - classification: { - safeFlags: ["dry-run"], - } satisfies ArgClassification, - }, - argv as Record, - async () => { - const queryParams: Record = { - limit: argv["limit"], - offset: argv["offset"], - }; - if (argv.dryRun) { - const __cfDryRunAccountId = await resolveAccountIdSilent(); - formatDryRun({ - command: "cf browser-run devtools session list", - method: "GET", - url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/devtools/session`, - pathParams: {}, - query: queryParams, - bodyKind: "none", - }); - return; - } - const client = await createCommandClient(argv); - const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); - argv.accountId = accountId; - - const result = await withProgress(`Loading`, async () => - client.send(operation, { account_id: accountId, ...queryParams }) - ); - formatOutput(result, { successLabel: `Loaded` }); - } - ), -}; + usage: + "$0 browser-run devtools session list\n\nList active browser sessions.", + ...parameters, + loader: () => import("./list.handler.js"), +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/index.ts b/packages/cli/src/commands/_generated/browser-run/index.ts index 72ed39f8ad..3a3d882776 100644 --- a/packages/cli/src/commands/_generated/browser-run/index.ts +++ b/packages/cli/src/commands/_generated/browser-run/index.ts @@ -3,28 +3,23 @@ import $devtools from "./devtools/index.js"; import $quickaction from "./quick-action/index.js"; import $recording from "./recording/index.js"; import $script from "./script/index.js"; -import type { CommonYargsOptions } from "#lib/cli-types.js"; /** * browser-run command * @generated from apis/overlays/browser-run.ts */ -import type { CommandModule } from "yargs"; +import { apiGroup } from "#lib/api-command.js"; -const command: CommandModule = { +const command = apiGroup({ command: "browser-run", describe: "browser-run", - builder: (yargs) => { - return yargs - .command($crawl) - .command($devtools) - .command($quickaction) - .command($recording) - .command($script) - .demandCommand(1, "Please specify a subcommand"); + routes: { + crawl: $crawl, + devtools: $devtools, + "quick-action": $quickaction, + recording: $recording, + script: $script, }, - - handler: () => {}, -}; +}); export default command; diff --git a/packages/cli/src/commands/_generated/browser-run/quick-action/accessibility-tree.handler.ts b/packages/cli/src/commands/_generated/browser-run/quick-action/accessibility-tree.handler.ts new file mode 100644 index 0000000000..7e404e8da0 --- /dev/null +++ b/packages/cli/src/commands/_generated/browser-run/quick-action/accessibility-tree.handler.ts @@ -0,0 +1,294 @@ +import operation from "../../_operations/browser-run/quick-action/accessibility-tree.js"; +import type { ArgClassification } from "#lib/telemetry/index.js"; +import type { Args } from "./accessibility-tree.js"; +import { + createCommandClient, + getAccountId, + resolveAccountIdSilent, +} from "#lib/auth.js"; +import { + compactBody, + parseBody, + parseJsonMap, + parseObjectArray, +} from "#lib/body-parser.js"; +import { formatDryRun } from "#lib/dry-run.js"; +import { resolveFileToken } from "#lib/input-validation.js"; +import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; +import { formatOutput } from "#lib/output.js"; +import { withProgress } from "#lib/progress.js"; +import { runWithTelemetry } from "#lib/telemetry/index.js"; + +export default async function handle(argv: Args): Promise { + return runWithTelemetry( + { + command: "browser-run quick-action accessibility-tree", + classification: { + safeFlags: [ + "browser", + "best-attempt", + "interesting-only", + "set-java-script-enabled", + "viewport-has-touch", + "viewport-is-landscape", + "viewport-is-mobile", + "wait-for-selector-hidden", + "wait-for-selector-visible", + "dry-run", + ], + } satisfies ArgClassification, + }, + argv as Record, + async () => { + const queryParams: Record = { + cacheTTL: argv["cache-ttl"], + browser: argv["browser"], + }; + if (argv.dryRun) { + const __cfDryRunAccountId = await resolveAccountIdSilent(); + formatDryRun({ + command: "cf browser-run quick-action accessibility-tree", + method: "POST", + url: `https://api.cloudflare.com/client/v4/accounts/${__cfDryRunAccountId ?? ""}/browser-rendering/accessibilityTree`, + pathParams: {}, + query: queryParams, + bodyKind: "json", + body: + argv.body !== undefined + ? parseBody(argv.body) + : compactBody( + { + actionTimeout: argv["action-timeout"], + addScriptTag: parseObjectArray( + argv["add-script-tag"], + "add-script-tag" + ), + addStyleTag: parseObjectArray( + argv["add-style-tag"], + "add-style-tag" + ), + allowRequestPattern: argv["allow-request-pattern"], + allowResourceTypes: argv["allow-resource-types"], + authenticate: { + password: resolveFileToken( + argv["authenticate-password"] as string | undefined, + "authenticate-password", + "text" + ), + username: resolveFileToken( + argv["authenticate-username"] as string | undefined, + "authenticate-username", + "text" + ), + }, + bestAttempt: argv["best-attempt"], + cookies: parseObjectArray(argv["cookies"], "cookies"), + emulateMediaType: resolveFileToken( + argv["emulate-media-type"] as string | undefined, + "emulate-media-type", + "text" + ), + gotoOptions: { + referer: resolveFileToken( + argv["goto-options-referer"] as string | undefined, + "goto-options-referer", + "text" + ), + referrerPolicy: resolveFileToken( + argv["goto-options-referrer-policy"] as + | string + | undefined, + "goto-options-referrer-policy", + "text" + ), + timeout: argv["goto-options-timeout"], + }, + html: resolveFileToken( + argv["html"] as string | undefined, + "html", + "text" + ), + interestingOnly: argv["interesting-only"], + rejectRequestPattern: argv["reject-request-pattern"], + rejectResourceTypes: argv["reject-resource-types"], + root: resolveFileToken( + argv["root"] as string | undefined, + "root", + "text" + ), + setExtraHTTPHeaders: parseJsonMap( + argv["set-extra-httpheaders"], + "set-extra-httpheaders" + ), + setJavaScriptEnabled: argv["set-java-script-enabled"], + url: resolveFileToken( + argv["url"] as string | undefined, + "url", + "text" + ), + userAgent: resolveFileToken( + argv["user-agent"] as string | undefined, + "user-agent", + "text" + ), + viewport: { + deviceScaleFactor: argv["viewport-device-scale-factor"], + hasTouch: argv["viewport-has-touch"], + height: argv["viewport-height"], + isLandscape: argv["viewport-is-landscape"], + isMobile: argv["viewport-is-mobile"], + width: argv["viewport-width"], + }, + waitForSelector: { + hidden: argv["wait-for-selector-hidden"], + selector: resolveFileToken( + argv["wait-for-selector-selector"] as + | string + | undefined, + "wait-for-selector-selector", + "text" + ), + timeout: argv["wait-for-selector-timeout"], + visible: argv["wait-for-selector-visible"], + }, + waitForTimeout: argv["wait-for-timeout"], + }, + [["setExtraHTTPHeaders"]] + ), + sensitiveBodyPaths: [["authenticate", "password"]], + }); + return; + } + const parsedBody = + argv.body !== undefined ? parseBody(argv.body) : undefined; + const client = await createCommandClient(argv); + const accountId = argv.local ? LOCAL_ACCOUNT_ID : await getAccountId(); + argv.accountId = accountId; + + if (argv.body !== undefined) { + const bodyData = parsedBody; + const qs = new URLSearchParams( + Object.entries(queryParams) + .filter(([, v]) => v !== undefined) + .map(([k, v]) => [k, String(v)]) + ).toString(); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Created` }); + return; + } + + // Assemble request body from individual flags + const bodyData = compactBody( + { + actionTimeout: argv["action-timeout"], + addScriptTag: parseObjectArray( + argv["add-script-tag"], + "add-script-tag" + ), + addStyleTag: parseObjectArray(argv["add-style-tag"], "add-style-tag"), + allowRequestPattern: argv["allow-request-pattern"], + allowResourceTypes: argv["allow-resource-types"], + authenticate: { + password: resolveFileToken( + argv["authenticate-password"] as string | undefined, + "authenticate-password", + "text" + ), + username: resolveFileToken( + argv["authenticate-username"] as string | undefined, + "authenticate-username", + "text" + ), + }, + bestAttempt: argv["best-attempt"], + cookies: parseObjectArray(argv["cookies"], "cookies"), + emulateMediaType: resolveFileToken( + argv["emulate-media-type"] as string | undefined, + "emulate-media-type", + "text" + ), + gotoOptions: { + referer: resolveFileToken( + argv["goto-options-referer"] as string | undefined, + "goto-options-referer", + "text" + ), + referrerPolicy: resolveFileToken( + argv["goto-options-referrer-policy"] as string | undefined, + "goto-options-referrer-policy", + "text" + ), + timeout: argv["goto-options-timeout"], + }, + html: resolveFileToken( + argv["html"] as string | undefined, + "html", + "text" + ), + interestingOnly: argv["interesting-only"], + rejectRequestPattern: argv["reject-request-pattern"], + rejectResourceTypes: argv["reject-resource-types"], + root: resolveFileToken( + argv["root"] as string | undefined, + "root", + "text" + ), + setExtraHTTPHeaders: parseJsonMap( + argv["set-extra-httpheaders"], + "set-extra-httpheaders" + ), + setJavaScriptEnabled: argv["set-java-script-enabled"], + url: resolveFileToken( + argv["url"] as string | undefined, + "url", + "text" + ), + userAgent: resolveFileToken( + argv["user-agent"] as string | undefined, + "user-agent", + "text" + ), + viewport: { + deviceScaleFactor: argv["viewport-device-scale-factor"], + hasTouch: argv["viewport-has-touch"], + height: argv["viewport-height"], + isLandscape: argv["viewport-is-landscape"], + isMobile: argv["viewport-is-mobile"], + width: argv["viewport-width"], + }, + waitForSelector: { + hidden: argv["wait-for-selector-hidden"], + selector: resolveFileToken( + argv["wait-for-selector-selector"] as string | undefined, + "wait-for-selector-selector", + "text" + ), + timeout: argv["wait-for-selector-timeout"], + visible: argv["wait-for-selector-visible"], + }, + waitForTimeout: argv["wait-for-timeout"], + }, + [["setExtraHTTPHeaders"]] + ); + const qs = new URLSearchParams( + Object.entries(queryParams) + .filter(([, v]) => v !== undefined) + .map(([k, v]) => [k, String(v)]) + ).toString(); + const result = await withProgress(`Creating`, async () => + client.send(operation, { + body: bodyData, + account_id: accountId, + ...queryParams, + }) + ); + formatOutput(result, { successLabel: `Created` }); + } + ); +} diff --git a/packages/cli/src/commands/_generated/browser-run/quick-action/accessibility-tree.ts b/packages/cli/src/commands/_generated/browser-run/quick-action/accessibility-tree.ts index a1d203137f..793660f52a 100644 --- a/packages/cli/src/commands/_generated/browser-run/quick-action/accessibility-tree.ts +++ b/packages/cli/src/commands/_generated/browser-run/quick-action/accessibility-tree.ts @@ -1,199 +1,247 @@ -import operation from "../../_operations/browser-run/quick-action/accessibility-tree.js"; -import type { CommonYargsOptions, InferArgs } from "#lib/cli-types.js"; -import type { ArgClassification } from "#lib/telemetry/index.js"; /** * accessibility-tree command * @generated from apis/overlays/browser-run.ts */ -import type { Argv, CommandModule } from "yargs"; import { - createCommandClient, - getAccountId, - resolveAccountIdSilent, -} from "#lib/auth.js"; -import { - compactBody, - parseBody, - parseJsonMap, - parseObjectArray, -} from "#lib/body-parser.js"; -import { formatDryRun } from "#lib/dry-run.js"; -import { resolveFileToken } from "#lib/input-validation.js"; -import { LOCAL_ACCOUNT_ID } from "#lib/local.js"; -import { formatOutput } from "#lib/output.js"; -import { withProgress } from "#lib/progress.js"; -import { runWithTelemetry } from "#lib/telemetry/index.js"; + apiCommand, + type ApiInputs, + type ApiParameters, +} from "#lib/api-command.js"; -function builder(yargs: Argv) { - return yargs - .usage( - "$0 browser-run quick-action accessibility-tree\n\nReturns the page's accessibility tree. Use `interestingOnly` to only return semantically meaningful nodes; use `root` to scope the tree to a CSS-selector-anchored subtree. Control page loading with `gotoOptions` and `waitFor*` options." - ) - .option("cache-ttl", { - type: "number", - description: "Cache TTL default is 5s. Set to 0 to disable.", - }) - .option("browser", { - type: "string", - description: - "Rendering backend. Set to `kitesurf` to use Kitesurf (beta).", - choices: ["kitesurf"], - }) - .option("action-timeout", { - type: "number", - description: +const parameters = { + flags: { + "cache-ttl": { + kind: "parsed", + brief: "Cache TTL default is 5s. Set to 0 to disable.", + optional: true, + parse: Number, + }, + browser: { + kind: "enum", + brief: "Rendering backend. Set to `kitesurf` to use Kitesurf (beta).", + values: ["kitesurf"], + optional: true, + }, + "action-timeout": { + kind: "parsed", + brief: "The maximum duration allowed for the browser action to complete after the page has loaded (such as taking screenshots, extracting content, or generating PDFs). If this time limit is exceeded, the action stops and returns a timeout error.", - }) - .option("add-script-tag", { - type: "string", - description: + optional: true, + parse: Number, + }, + "add-script-tag": { + kind: "parsed", + brief: 'Adds a script element into the page with the desired URL or content. Provide as a JSON array of objects or @path/to/file.json. Shape: [{"content"?: string, "id"?: string, "type"?: string, "url"?: string}]. ? marks optional keys.', - }) - .option("add-style-tag", { - type: "string", - description: + optional: true, + parse: String, + }, + "add-style-tag": { + kind: "parsed", + brief: 'Adds a `` tag into the page with the desired URL or a `