-
Notifications
You must be signed in to change notification settings - Fork 131
Expand file tree
/
Copy pathoperation-args.ts
More file actions
585 lines (511 loc) · 20 KB
/
operation-args.ts
File metadata and controls
585 lines (511 loc) · 20 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
import { CliError } from './errors';
import { isRecord } from './guards';
import {
ensureValidArgs,
expectNoPositionals,
getBooleanOption,
getNumberOption,
getOptionalBooleanOption,
getStringListOption,
getStringOption,
parseCommandArgs,
resolveDocArg,
type OptionSpec,
type ParsedArgs,
} from './args';
import {
CLI_OPERATION_COMMAND_KEYS,
CLI_OPERATION_METADATA,
CLI_OPERATION_OPTION_SPECS,
getResponseSchema,
toDocApiId,
type CliOperationArgsById,
type CliOperationConstraints,
type CliOperationId,
type CliOperationParamSpec,
type CliTypeSpec,
} from '../cli';
import type { CliExposedOperationId } from '../cli/operation-set.js';
import { RESPONSE_ENVELOPE_KEY, RESPONSE_VALIDATION_KEY } from '../cli/operation-hints.js';
type ParseOperationArgsOptions = {
commandName?: string;
extraOptionSpecs?: OptionSpec[];
allowExtraPositionals?: boolean;
skipConstraints?: boolean;
};
type ParsedOperationArgs<TOperationId extends CliOperationId> = {
parsed: ParsedArgs;
args: CliOperationArgsById[TOperationId];
help: boolean;
positionals: string[];
commandName: string;
};
const HELP_OPTION_SPEC: OptionSpec = { name: 'help', type: 'boolean', aliases: ['h'] };
function buildOptionSpecs(operationId: CliOperationId, extras: OptionSpec[] = []): OptionSpec[] {
const seen = new Set<string>();
const merged: OptionSpec[] = [];
for (const spec of [...CLI_OPERATION_OPTION_SPECS[operationId], ...extras, HELP_OPTION_SPEC]) {
if (seen.has(spec.name)) continue;
seen.add(spec.name);
merged.push(spec);
}
return merged;
}
function parseJsonFlagValue(commandName: string, flag: string, raw: string | undefined): unknown | undefined {
if (raw == null) return undefined;
try {
return JSON.parse(raw) as unknown;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new CliError('JSON_PARSE_ERROR', `${commandName}: invalid --${flag} JSON payload.`, {
message,
flag,
});
}
}
function getParamLabel(param: CliOperationParamSpec): string {
if (param.kind === 'doc') return `<${param.name}>`;
return `--${param.flag}`;
}
function isPresent(value: unknown): boolean {
if (value == null) return false;
if (Array.isArray(value)) return value.length > 0;
return true;
}
function isTextAddressLike(value: unknown): value is {
kind: 'text';
blockId: string;
range: { start: number; end: number };
} {
if (!isRecord(value) || value.kind !== 'text' || typeof value.blockId !== 'string') return false;
if (!isRecord(value.range)) return false;
return typeof value.range.start === 'number' && typeof value.range.end === 'number';
}
function acceptsLegacyTextAddressTarget(
operationId: CliOperationId,
param: CliOperationParamSpec,
value: unknown,
): boolean {
if (param.name !== 'target' || !isTextAddressLike(value)) return false;
const docApiId = toDocApiId(operationId);
return (
docApiId === 'insert' || docApiId === 'replace' || docApiId === 'delete' || docApiId?.startsWith('format.') === true
);
}
/**
* If every variant in a `oneOf` is a `{ const: X }`, return the values as strings.
* Returns an empty array when the pattern doesn't hold (mixed / nested schemas).
*/
function extractConstValues(variants: CliTypeSpec[]): string[] {
const values: string[] = [];
for (const variant of variants) {
if (!('const' in variant)) return [];
values.push(String(variant.const));
}
return values;
}
function isNestedValidationMessage(path: string, message: string): boolean {
return message.startsWith(`${path}.`) || message.startsWith(`${path}[`);
}
function selectRepeatedActionableOneOfError(path: string, errors: string[]): string | null {
const counts = new Map<string, number>();
for (const error of errors) {
counts.set(error, (counts.get(error) ?? 0) + 1);
}
let bestMessage: string | null = null;
let bestScore = 0;
for (const [message, count] of counts.entries()) {
if (count < 2) continue;
const nested = isNestedValidationMessage(path, message);
const isShapeError = message.includes(' is not allowed by schema.') || message.includes(' is required.');
if (!nested && !isShapeError) continue;
const score = count * 10 + (nested ? 2 : 0) + (isShapeError ? 1 : 0);
if (score > bestScore) {
bestScore = score;
bestMessage = message;
}
}
return bestMessage;
}
export function validateValueAgainstTypeSpec(value: unknown, schema: CliTypeSpec, path: string): void {
if ('const' in schema) {
if (value !== schema.const) {
throw new CliError('VALIDATION_ERROR', `${path} must equal ${JSON.stringify(schema.const)}.`);
}
return;
}
if ('oneOf' in schema) {
const variants = schema.oneOf as CliTypeSpec[];
const errors: string[] = [];
for (const variant of variants) {
try {
validateValueAgainstTypeSpec(value, variant, path);
return;
} catch (error) {
errors.push(error instanceof Error ? error.message : String(error));
}
}
const allowedValues = extractConstValues(variants);
const selectedError = selectRepeatedActionableOneOfError(path, errors);
const message =
allowedValues.length > 0
? `${path} must be one of: ${allowedValues.join(', ')}.`
: (selectedError ?? `${path} must match one of the allowed schema variants.`);
throw new CliError('VALIDATION_ERROR', message, { errors, selectedError });
}
if (schema.type === 'json') return;
if (schema.enum) {
if (!schema.enum.includes(value)) {
throw new CliError('VALIDATION_ERROR', `${path} must be one of: ${schema.enum.join(', ')}.`);
}
return;
}
if (schema.type === 'string') {
if (typeof value !== 'string') throw new CliError('VALIDATION_ERROR', `${path} must be a string.`);
return;
}
if (schema.type === 'number') {
if (typeof value !== 'number' || !Number.isFinite(value)) {
throw new CliError('VALIDATION_ERROR', `${path} must be a finite number.`);
}
return;
}
if (schema.type === 'boolean') {
if (typeof value !== 'boolean') throw new CliError('VALIDATION_ERROR', `${path} must be a boolean.`);
return;
}
if (schema.type === 'array') {
if (!Array.isArray(value)) throw new CliError('VALIDATION_ERROR', `${path} must be an array.`);
for (let index = 0; index < value.length; index += 1) {
validateValueAgainstTypeSpec(value[index], schema.items, `${path}[${index}]`);
}
return;
}
if (schema.type === 'object') {
if (!isRecord(value)) throw new CliError('VALIDATION_ERROR', `${path} must be an object.`);
const required = schema.required ?? [];
for (const key of required) {
if (!Object.prototype.hasOwnProperty.call(value, key)) {
throw new CliError('VALIDATION_ERROR', `${path}.${key} is required.`);
}
}
const propertyEntries = schema.properties ? Object.entries(schema.properties) : [];
const shouldRestrictUnknownKeys = propertyEntries.length > 0 || required.length > 0;
// If no object fields are declared, treat it as an unconstrained JSON object.
// This keeps input validation aligned with generated schemas like `{ type: 'object' }`.
if (shouldRestrictUnknownKeys) {
const knownKeys = new Set(propertyEntries.map(([key]) => key));
for (const key of Object.keys(value)) {
if (!knownKeys.has(key)) {
throw new CliError('VALIDATION_ERROR', `${path}.${key} is not allowed by schema.`);
}
}
}
for (const [key, propSchema] of propertyEntries) {
if (!Object.prototype.hasOwnProperty.call(value, key)) continue;
validateValueAgainstTypeSpec(value[key], propSchema, `${path}.${key}`);
}
return;
}
throw new CliError('VALIDATION_ERROR', `${path} uses an unsupported schema type.`);
}
/**
* Loose structural validation — checks required fields and types of known
* properties but does NOT reject additional properties. This matches JSON
* Schema's default `additionalProperties: true` and is appropriate for
* response validation where the doc-api output may include extra fields
* beyond what the schema explicitly enumerates.
*/
function validateResponseValueAgainstTypeSpec(value: unknown, schema: CliTypeSpec, path: string): void {
if ('const' in schema) {
if (value !== schema.const) {
throw new CliError('VALIDATION_ERROR', `${path} must be ${JSON.stringify(schema.const)}.`);
}
return;
}
if ('oneOf' in schema) {
const errors: string[] = [];
for (const variant of schema.oneOf) {
try {
validateResponseValueAgainstTypeSpec(value, variant, path);
return;
} catch (error) {
errors.push(error instanceof Error ? error.message : String(error));
}
}
const selectedError = selectRepeatedActionableOneOfError(path, errors);
throw new CliError('VALIDATION_ERROR', selectedError ?? `${path} must match one of the allowed schema variants.`, {
errors,
selectedError,
});
}
if (schema.type === 'json') return;
if (schema.type === 'string') {
if (typeof value !== 'string') throw new CliError('VALIDATION_ERROR', `${path} must be a string.`);
return;
}
if (schema.type === 'number') {
if (typeof value !== 'number' || !Number.isFinite(value)) {
throw new CliError('VALIDATION_ERROR', `${path} must be a finite number.`);
}
return;
}
if (schema.type === 'boolean') {
if (typeof value !== 'boolean') throw new CliError('VALIDATION_ERROR', `${path} must be a boolean.`);
return;
}
if (schema.type === 'array') {
if (!Array.isArray(value)) throw new CliError('VALIDATION_ERROR', `${path} must be an array.`);
for (let index = 0; index < value.length; index += 1) {
validateResponseValueAgainstTypeSpec(value[index], schema.items, `${path}[${index}]`);
}
return;
}
if (schema.type === 'object') {
if (!isRecord(value)) throw new CliError('VALIDATION_ERROR', `${path} must be an object.`);
const required = schema.required ?? [];
for (const key of required) {
if (!Object.prototype.hasOwnProperty.call(value, key)) {
throw new CliError('VALIDATION_ERROR', `${path}.${key} is required.`);
}
}
// Validate known properties but allow additional properties (JSON Schema default).
const properties = schema.properties ?? {};
for (const [key, propSchema] of Object.entries(properties)) {
if (!Object.prototype.hasOwnProperty.call(value, key)) continue;
validateResponseValueAgainstTypeSpec(value[key], propSchema, `${path}.${key}`);
}
return;
}
}
/**
* Resolves the envelope key for a doc-backed CLI operation.
*
* Derived from the single source of truth in `operation-hints.ts` (RESPONSE_ENVELOPE_KEY).
* Returns `undefined` for CLI-only operations that aren't doc-backed.
*/
function resolveResponsePayloadKey(operationId: CliOperationId): string | null | undefined {
const docApiId = toDocApiId(operationId);
if (!docApiId) return undefined;
const envelopeKey = RESPONSE_ENVELOPE_KEY[docApiId as CliExposedOperationId];
// For operations with null envelope key (result spread across top-level), fall
// back to RESPONSE_VALIDATION_KEY so schema validation still runs on the receipt.
return envelopeKey ?? RESPONSE_VALIDATION_KEY[docApiId as CliExposedOperationId] ?? null;
}
export function validateOperationResponseData(operationId: CliOperationId, value: unknown, commandName: string): void {
const schema = getResponseSchema(operationId);
if (!schema) return;
// CLI-only operations use permissive { type: 'json' } schemas.
if ('type' in schema && schema.type === 'json') return;
// Resolve the envelope key from the single source of truth.
const payloadKey = resolveResponsePayloadKey(operationId);
// Null entries are intentionally exempt (e.g. doc.info which splits output
// across multiple keys).
if (payloadKey === null || payloadKey === undefined) return;
if (!isRecord(value)) {
throw new CliError('VALIDATION_ERROR', `${commandName}:response must be an object.`);
}
// Dry-run responses use a different envelope shape (proposed instead of
// receipt/result), so skip the key-presence check when dryRun is set.
if (!(payloadKey in value)) {
if (value.dryRun === true) return;
throw new CliError(
'VALIDATION_ERROR',
`${commandName}:response.${payloadKey} is required by ${operationId} response schema.`,
);
}
// Validate the payload field against the doc-api output schema. Uses loose
// validation (allows extra properties) to match JSON Schema defaults.
validateResponseValueAgainstTypeSpec(value[payloadKey], schema, `${commandName}:response.${payloadKey}`);
}
function validateValueAgainstParamType(value: unknown, param: CliOperationParamSpec, path: string): void {
if (param.type === 'json') return;
if (param.type === 'string') {
if (typeof value !== 'string') {
throw new CliError('VALIDATION_ERROR', `${path} must be a string.`);
}
return;
}
if (param.type === 'number') {
if (typeof value !== 'number' || !Number.isFinite(value)) {
throw new CliError('VALIDATION_ERROR', `${path} must be a finite number.`);
}
return;
}
if (param.type === 'boolean') {
if (typeof value !== 'boolean') {
throw new CliError('VALIDATION_ERROR', `${path} must be a boolean.`);
}
return;
}
if (param.type === 'string[]') {
if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'string')) {
throw new CliError('VALIDATION_ERROR', `${path} must be an array of strings.`);
}
return;
}
}
function resolveFlagParamValue(parsed: ParsedArgs, commandName: string, param: CliOperationParamSpec): unknown {
if (param.kind === 'doc') return undefined;
const flag = param.flag ?? param.name;
switch (param.type) {
case 'string':
return getStringOption(parsed, flag);
case 'number':
return getNumberOption(parsed, flag);
case 'boolean':
return getOptionalBooleanOption(parsed, flag);
case 'string[]':
return getStringListOption(parsed, flag);
case 'json':
return parseJsonFlagValue(commandName, flag, getStringOption(parsed, flag));
default:
return undefined;
}
}
function applyConstraints(operationId: CliOperationId, commandName: string, args: Record<string, unknown>): void {
const constraints = CLI_OPERATION_METADATA[operationId].constraints;
if (!constraints) return;
const typedConstraints = constraints as CliOperationConstraints;
const mutuallyExclusive: string[][] = Array.isArray(typedConstraints.mutuallyExclusive)
? typedConstraints.mutuallyExclusive.map((group) => [...group])
: [];
const requiresOneOf: string[][] = Array.isArray(typedConstraints.requiresOneOf)
? typedConstraints.requiresOneOf.map((group) => [...group])
: [];
const requiredWhen: Array<{
param: string;
whenParam: string;
equals?: unknown;
present?: boolean;
}> = Array.isArray(typedConstraints.requiredWhen) ? typedConstraints.requiredWhen.map((rule) => ({ ...rule })) : [];
for (const group of mutuallyExclusive) {
const present = group.filter((name) => isPresent(args[name]));
if (present.length > 1) {
throw new CliError(
'INVALID_ARGUMENT',
`${commandName}: options are mutually exclusive: ${group.map((name) => `--${name}`).join(', ')}`,
);
}
}
for (const group of requiresOneOf) {
const hasAny = group.some((name: string) => isPresent(args[name]));
if (!hasAny) {
throw new CliError(
'MISSING_REQUIRED',
`${commandName}: one of ${group.map((name: string) => `--${name}`).join(', ')} is required.`,
);
}
}
for (const rule of requiredWhen) {
const whenValue = args[rule.whenParam];
let shouldRequire = false;
if (Object.prototype.hasOwnProperty.call(rule, 'equals')) {
shouldRequire = whenValue === rule.equals;
} else if (Object.prototype.hasOwnProperty.call(rule, 'present')) {
shouldRequire = rule.present ? isPresent(whenValue) : !isPresent(whenValue);
} else {
shouldRequire = isPresent(whenValue);
}
if (shouldRequire && !isPresent(args[rule.param])) {
throw new CliError('MISSING_REQUIRED', `${commandName}: --${rule.param} is required by argument constraints.`, {
param: rule.param,
whenParam: rule.whenParam,
});
}
}
}
export function validateOperationInputData(operationId: CliOperationId, input: unknown, commandName = 'call'): void {
if (!isRecord(input)) {
throw new CliError('VALIDATION_ERROR', `${commandName}: input must be a JSON object.`);
}
const metadata = CLI_OPERATION_METADATA[operationId];
const paramNames = new Set<string>(metadata.params.map((param) => param.name as string));
for (const key of Object.keys(input)) {
if (!paramNames.has(key)) {
throw new CliError('VALIDATION_ERROR', `${commandName}: input.${key} is not allowed for ${operationId}.`);
}
}
const argsRecord: Record<string, unknown> = {};
for (const param of metadata.params) {
const value = input[param.name];
argsRecord[param.name] = value;
if (!isPresent(value)) continue;
if ('schema' in param && param.schema) {
if (acceptsLegacyTextAddressTarget(operationId, param, value)) {
continue;
}
validateValueAgainstTypeSpec(value, param.schema, `${commandName}:input.${param.name}`);
continue;
}
validateValueAgainstParamType(value, param, `${commandName}:input.${param.name}`);
}
for (const param of metadata.params) {
const isRequired = 'required' in param && Boolean(param.required);
if (!isRequired) continue;
if (isPresent(argsRecord[param.name])) continue;
const requiredLabel = param.kind === 'doc' ? `<${param.name}>` : `input.${param.name}`;
throw new CliError('MISSING_REQUIRED', `${commandName}: missing required ${requiredLabel}.`);
}
applyConstraints(operationId, commandName, argsRecord);
}
export function parseOperationArgs<TOperationId extends CliOperationId>(
operationId: TOperationId,
tokens: string[],
options: ParseOperationArgsOptions = {},
): ParsedOperationArgs<TOperationId> {
const commandName = options.commandName ?? CLI_OPERATION_COMMAND_KEYS[operationId];
const parsed = parseCommandArgs(tokens, buildOptionSpecs(operationId, options.extraOptionSpecs ?? []));
ensureValidArgs(parsed);
const help = getBooleanOption(parsed, 'help');
const metadata = CLI_OPERATION_METADATA[operationId];
const argsRecord: Record<string, unknown> = {};
let remainingPositionals = [...parsed.positionals];
const positionalParamNames = [...metadata.positionalParams];
if (positionalParamNames[0] === 'doc') {
const resolved = resolveDocArg(parsed, commandName);
if (resolved.doc != null) {
argsRecord.doc = resolved.doc;
}
remainingPositionals = [...resolved.positionals];
positionalParamNames.shift();
}
for (const positionalName of positionalParamNames) {
const value = remainingPositionals.shift();
if (value != null) {
argsRecord[positionalName] = value;
}
}
if (!options.allowExtraPositionals) {
expectNoPositionals(parsed, remainingPositionals, commandName);
}
for (const param of metadata.params) {
if (param.kind === 'doc') continue;
argsRecord[param.name] = resolveFlagParamValue(parsed, commandName, param);
}
for (const param of metadata.params) {
if (!('schema' in param) || !param.schema) continue;
const value = argsRecord[param.name];
if (!isPresent(value)) continue;
if (acceptsLegacyTextAddressTarget(operationId, param, value)) continue;
validateValueAgainstTypeSpec(value, param.schema, `${commandName}:${param.name}`);
}
if (!help && !options.skipConstraints) {
for (const param of metadata.params) {
const isRequired = 'required' in param && Boolean(param.required);
if (!isRequired) continue;
const value = argsRecord[param.name];
if (!isPresent(value)) {
throw new CliError('MISSING_REQUIRED', `${commandName}: missing required ${getParamLabel(param)}.`);
}
}
applyConstraints(operationId, commandName, argsRecord);
}
return {
parsed,
args: argsRecord as CliOperationArgsById[TOperationId],
help,
positionals: remainingPositionals,
commandName,
};
}