|
| 1 | +import {parseArgs} from 'node:util'; |
| 2 | +import {TypeSystem} from '@jsonjoy.com/json-type/lib/system/TypeSystem'; |
| 3 | +import {ObjectValueCaller} from '@jsonjoy.com/reactive-rpc/lib/common/rpc/caller/ObjectValueCaller'; |
| 4 | +import {bufferToUint8Array} from '@jsonjoy.com/util/lib/buffers/bufferToUint8Array'; |
| 5 | +import {formatError} from './util'; |
| 6 | +import {defineBuiltinRoutes} from './methods'; |
| 7 | +import {defaultParams} from './defaultParams'; |
| 8 | +import {ObjectValue} from '@jsonjoy.com/json-type/lib/value/ObjectValue'; |
| 9 | +import type {CliCodecs} from './CliCodecs'; |
| 10 | +import type {TypeBuilder} from '@jsonjoy.com/json-type/lib/type/TypeBuilder'; |
| 11 | +import type {WriteStream, ReadStream} from 'tty'; |
| 12 | +import type {CliCodec, CliContext, CliParam, CliParamInstance} from './types'; |
| 13 | +import type {Value} from '@jsonjoy.com/json-type/lib/value/Value'; |
| 14 | + |
| 15 | +export interface CliOptions<Router extends ObjectValue<any>> { |
| 16 | + codecs: CliCodecs; |
| 17 | + params?: CliParam[]; |
| 18 | + router?: Router; |
| 19 | + version?: string; |
| 20 | + cmd?: string; |
| 21 | + argv?: string[]; |
| 22 | + stdout?: WriteStream; |
| 23 | + stderr?: WriteStream; |
| 24 | + stdin?: ReadStream; |
| 25 | + exit?: (errno: number) => void; |
| 26 | +} |
| 27 | + |
| 28 | +export class Cli<Router extends ObjectValue<any> = ObjectValue<any>> { |
| 29 | + public router: Router; |
| 30 | + public readonly params: CliParam[]; |
| 31 | + public readonly paramMap: Map<string, CliParam>; |
| 32 | + public readonly types: TypeSystem; |
| 33 | + public readonly t: TypeBuilder; |
| 34 | + public readonly caller: ObjectValueCaller<Router>; |
| 35 | + public readonly codecs: CliCodecs; |
| 36 | + public request?: unknown; |
| 37 | + public response?: unknown; |
| 38 | + public argv: string[]; |
| 39 | + public stdout: WriteStream; |
| 40 | + public stderr: WriteStream; |
| 41 | + public stdin: ReadStream; |
| 42 | + public exit: (errno: number) => void; |
| 43 | + public requestCodec: CliCodec; |
| 44 | + public responseCodec: CliCodec; |
| 45 | + public rawStdinInput?: Uint8Array; |
| 46 | + public stdinInput?: unknown; |
| 47 | + protected paramInstances: CliParamInstance[] = []; |
| 48 | + |
| 49 | + public constructor(public readonly options: CliOptions<Router>) { |
| 50 | + let router = options.router ?? (ObjectValue.create(new TypeSystem()) as any); |
| 51 | + router = defineBuiltinRoutes(router); |
| 52 | + this.router = router; |
| 53 | + this.params = options.params ?? defaultParams; |
| 54 | + this.paramMap = new Map(); |
| 55 | + for (const param of this.params) { |
| 56 | + this.paramMap.set(param.param, param); |
| 57 | + if (param.short) this.paramMap.set(param.short, param); |
| 58 | + } |
| 59 | + this.caller = new ObjectValueCaller({router, wrapInternalError: (err) => err}); |
| 60 | + this.types = router.system; |
| 61 | + this.t = this.types.t; |
| 62 | + this.codecs = options.codecs; |
| 63 | + this.requestCodec = this.codecs.get(this.codecs.defaultCodec); |
| 64 | + this.responseCodec = this.codecs.get(this.codecs.defaultCodec); |
| 65 | + this.argv = options.argv ?? process.argv.slice(2); |
| 66 | + this.stdin = options.stdin ?? process.stdin; |
| 67 | + this.stdout = options.stdout ?? process.stdout; |
| 68 | + this.stderr = options.stderr ?? process.stderr; |
| 69 | + this.exit = options.exit ?? process.exit; |
| 70 | + } |
| 71 | + |
| 72 | + public run(): void { |
| 73 | + this.runAsync(); |
| 74 | + } |
| 75 | + |
| 76 | + public param(param: string): CliParam | undefined { |
| 77 | + return this.paramMap.get(param); |
| 78 | + } |
| 79 | + |
| 80 | + public async runAsync(): Promise<void> { |
| 81 | + try { |
| 82 | + const system = this.router.system; |
| 83 | + for (const key of this.router.keys()) system.alias(key, this.router.get(key).type); |
| 84 | + const args = parseArgs({ |
| 85 | + args: this.argv, |
| 86 | + strict: false, |
| 87 | + allowPositionals: true, |
| 88 | + }); |
| 89 | + for (let argKey of Object.keys(args.values)) { |
| 90 | + let pointer = ''; |
| 91 | + const value = args.values[argKey]; |
| 92 | + const slashIndex = argKey.indexOf('/'); |
| 93 | + if (slashIndex !== -1) { |
| 94 | + pointer = argKey.slice(slashIndex); |
| 95 | + argKey = argKey.slice(0, slashIndex); |
| 96 | + } |
| 97 | + const param = this.param(argKey); |
| 98 | + if (!param) { |
| 99 | + throw new Error(`Unknown parameter "${argKey}"`); |
| 100 | + } |
| 101 | + const instance = param.createInstance(this, pointer, value); |
| 102 | + this.paramInstances.push(instance); |
| 103 | + if (instance.onParam) await instance.onParam(); |
| 104 | + } |
| 105 | + const method = args.positionals[0]; |
| 106 | + if (!method) { |
| 107 | + const param = this.param('help'); |
| 108 | + const instance = param?.createInstance(this, '', undefined); |
| 109 | + instance?.onParam?.(); |
| 110 | + throw new Error('No method specified'); |
| 111 | + } |
| 112 | + this.request = JSON.parse(args.positionals[1] || '{}'); |
| 113 | + await this.readStdin(); |
| 114 | + for (const instance of this.paramInstances) if (instance.onStdin) await instance.onStdin(); |
| 115 | + for (const instance of this.paramInstances) if (instance.onRequest) await instance.onRequest(); |
| 116 | + try { |
| 117 | + const ctx: CliContext<Router> = {cli: this}; |
| 118 | + for (const instance of this.paramInstances) if (instance.onBeforeCall) await instance.onBeforeCall(method, ctx); |
| 119 | + const value = await this.caller.call(method, this.request as any, ctx); |
| 120 | + this.response = (value as Value<any>).data; |
| 121 | + for (const instance of this.paramInstances) if (instance.onResponse) await instance.onResponse(); |
| 122 | + const buf = this.responseCodec.encode(this.response); |
| 123 | + this.stdout.write(buf); |
| 124 | + } catch (err) { |
| 125 | + const error = formatError(err); |
| 126 | + const buf = this.responseCodec.encode(error); |
| 127 | + this.stderr.write(buf); |
| 128 | + this.exit(1); |
| 129 | + } |
| 130 | + } catch (err) { |
| 131 | + const error = formatError(err); |
| 132 | + const buf = JSON.stringify(error, null, 4); |
| 133 | + this.stderr.write(buf); |
| 134 | + this.exit(1); |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + public cmd(): string { |
| 139 | + return this.options.cmd ?? '<cmd>'; |
| 140 | + } |
| 141 | + |
| 142 | + private async getStdin(): Promise<Buffer> { |
| 143 | + const stdin = this.stdin; |
| 144 | + if (stdin.isTTY) return Buffer.alloc(0); |
| 145 | + const result = []; |
| 146 | + let length = 0; |
| 147 | + for await (const chunk of stdin) { |
| 148 | + result.push(chunk); |
| 149 | + length += chunk.length; |
| 150 | + } |
| 151 | + return Buffer.concat(result, length); |
| 152 | + } |
| 153 | + |
| 154 | + private async readStdin(): Promise<void> { |
| 155 | + const stdin = this.stdin; |
| 156 | + const codec = this.requestCodec; |
| 157 | + if (stdin.isTTY) return Object.create(null); |
| 158 | + const input = await this.getStdin(); |
| 159 | + if (codec.id === 'json') { |
| 160 | + const str = input.toString().trim(); |
| 161 | + if (!str) return Object.create(null); |
| 162 | + } |
| 163 | + this.rawStdinInput = bufferToUint8Array(input); |
| 164 | + this.stdinInput = codec.decode(this.rawStdinInput); |
| 165 | + } |
| 166 | +} |
0 commit comments