mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-30 12:54:55 +00:00
feat(cli): generate shumai-cli commands from Operations with commander (#496)
Rebuild the CLI on commander. Commands for every cli-surface Operation (project ls, ls, mkdir, rename, move/mv, delete/rm) are generated from @shumai/operations: positionals, options, choices, numeric parsing and help text come from the Zod input schema. They call POST /api/ops/:name with x-shumai-client: cli. Existing invocations keep working. Adds --json, ls --type/--first/ --after, typo suggestions, and generated help. upload and create-version stay hand-written. Drops the unused @shumai/core dependency.
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
import type { z } from 'zod'
|
||||
import type { AnyOperationDefinition } from '@shumai/operations'
|
||||
import { getCliConfig } from '../client'
|
||||
import { CliError } from './errors'
|
||||
|
||||
/** Header that attributes invocations to the CLI (`via: cli`) in audit logs. */
|
||||
const CLIENT_HEADER = 'x-shumai-client'
|
||||
|
||||
/** Signature used by generated commands, which only see type-erased definitions. */
|
||||
export type CallOperation = (
|
||||
definition: AnyOperationDefinition,
|
||||
input: Record<string, unknown>,
|
||||
) => Promise<unknown>
|
||||
|
||||
/** Runs an Operation on the server via `POST /api/ops/:name`. */
|
||||
export async function callOperation<TDef extends AnyOperationDefinition>(
|
||||
definition: TDef,
|
||||
input: z.output<TDef['input']>,
|
||||
): Promise<z.output<TDef['output']>> {
|
||||
const { apiServer, apiKey } = getCliConfig()
|
||||
|
||||
let res: Response
|
||||
try {
|
||||
res = await fetch(`${apiServer}/api/ops/${definition.name}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
'Content-Type': 'application/json',
|
||||
[CLIENT_HEADER]: 'cli',
|
||||
},
|
||||
body: JSON.stringify(input),
|
||||
})
|
||||
} catch (err) {
|
||||
throw new CliError(
|
||||
`Error connecting to API server: ${err instanceof Error ? err.message : String(err)}`,
|
||||
{ prefixed: true },
|
||||
)
|
||||
}
|
||||
|
||||
const body: unknown = await res.json().catch(() => undefined)
|
||||
if (!res.ok) {
|
||||
const message =
|
||||
body && typeof body === 'object' && 'error' in body && typeof body.error === 'string'
|
||||
? body.error
|
||||
: `Request failed with status ${res.status}`
|
||||
throw new CliError(message)
|
||||
}
|
||||
|
||||
const parsed = definition.output.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
throw new CliError(`Unexpected response from server for ${definition.name}`)
|
||||
}
|
||||
// safeParse on the generic schema type loses the concrete shape; the schema guarantees it.
|
||||
return parsed.data as z.output<TDef['output']>
|
||||
}
|
||||
Reference in New Issue
Block a user