Repository navigation
Expand file tree
/
Copy pathjson-schema.ts
More file actions
664 lines (573 loc) · 18.7 KB
/
Copy pathjson-schema.ts
File metadata and controls
664 lines (573 loc) · 18.7 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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { isJsonObject, json, strings } from '@angular-devkit/core';
import type { Arguments, Argv, PositionalOptions, Options as YargsOptions } from 'yargs';
import { EventCustomDimension } from '../../analytics/analytics-parameters';
/**
* An option description that can be used by yargs to create a command.
* See: https://github.com/yargs/yargs/blob/main/docs/options.mjs
*/
export interface Option extends YargsOptions {
/**
* The name of the option.
*/
name: string;
/**
* Whether this option is required or not.
*/
required?: boolean;
/**
* Format field of this option.
*/
format?: string;
/**
* Whether this option should be hidden from the help output. It will still show up in JSON help.
*/
hidden?: boolean;
/**
* If this option can be used as an argument, the position of the argument. Otherwise omitted.
*/
positional?: number;
/**
* Whether or not to report this option to the Angular Team, and which custom field to use.
* If this is falsey, do not report this option.
*/
userAnalytics?: string;
/**
* Type of the values in a key/value pair field.
*/
itemValueType?: 'string';
/**
* The supported types of the option.
*/
types?: ReadonlyArray<'string' | 'number' | 'boolean' | 'array' | 'object'>;
/**
* Allowed boolean values when `boolean` is one of the supported types.
*/
booleanValues?: ReadonlySet<boolean>;
}
/**
* A Yargs check function that validates that the given options are in the form of `key=value`.
* @param keyValuePairOptions A set of options that should be in the form of `key=value`.
* @param args The parsed arguments.
* @returns `true` if the options are valid, otherwise an error is thrown.
*/
function checkStringMap(keyValuePairOptions: Set<string>, args: Arguments): boolean {
for (const key of keyValuePairOptions) {
const value = args[key];
if (!Array.isArray(value)) {
// Value has been parsed.
continue;
}
for (const pair of value) {
if (pair === undefined) {
continue;
}
if (!pair.includes('=')) {
throw new Error(
`Invalid value for argument: ${key}, Given: '${pair}', Expected key=value pair`,
);
}
}
}
return true;
}
const ALL_BOOLEAN_VALUES: ReadonlySet<boolean> = new Set([true, false]);
/**
* Coerces a scalar string value to a boolean when permitted by the schema's allowed boolean values.
*/
function coerceStringToBoolean(value: unknown, allowTrue: boolean, allowFalse: boolean): unknown {
if (typeof value === 'string') {
if ((value === '' || value === 'true') && allowTrue) {
return true;
}
if (value === 'false' && allowFalse) {
return false;
}
}
return value;
}
/**
* Creates a Yargs coerce function that converts empty or boolean-like values to a boolean
* when an option supports both `boolean` and another type (`array` or `string`).
* @param type The primary Yargs option type (`array` or `string`).
* @param allowedBooleans The boolean literal values permitted by the option's JSON schema.
* @returns A Yargs coerce function.
*/
function createCoerceToBoolean(
type: 'array' | 'string',
allowedBooleans: ReadonlySet<boolean> = ALL_BOOLEAN_VALUES,
): (value: unknown) => unknown {
const allowTrue = allowedBooleans.has(true);
const allowFalse = allowedBooleans.has(false);
if (type === 'string') {
return (value: unknown) =>
Array.isArray(value)
? value.map((item) => coerceStringToBoolean(item, allowTrue, allowFalse))
: coerceStringToBoolean(value, allowTrue, allowFalse);
}
return (value: unknown) => {
if (!Array.isArray(value)) {
return coerceStringToBoolean(value, allowTrue, allowFalse);
}
if (value.length === 0) {
return allowTrue ? true : value;
}
let result: unknown[] | boolean | undefined;
for (const item of value) {
if (item === true || (item === 'true' && allowTrue)) {
result = true;
} else if (item === false || (item === 'false' && allowFalse)) {
result = false;
} else if (Array.isArray(result)) {
result.push(item);
} else {
result = [item];
}
}
return result;
};
}
/**
* A Yargs coerce function that converts an array of `key=value` strings to an object.
* @param value An array of `key=value` strings.
* @returns An object with the keys and values from the input array.
*/
function coerceToStringMap(
value: (string | undefined)[],
): Record<string, string> | (string | undefined)[] {
const stringMap: Record<string, string> = {};
for (const pair of value) {
// This happens when the flag isn't passed at all.
if (pair === undefined) {
continue;
}
const eqIdx = pair.indexOf('=');
if (eqIdx === -1) {
// In the case it is not valid skip processing this option and handle the error in `checkStringMap`
return value;
}
const key = pair.slice(0, eqIdx);
stringMap[key] = pair.slice(eqIdx + 1);
}
return stringMap;
}
/**
* Checks if a JSON schema node represents a string map.
* A string map is an object with `additionalProperties` of type `string`.
* @param node The JSON schema node to check.
* @returns `true` if the node represents a string map, otherwise `false`.
*/
function isStringMap(node: json.JsonObject): boolean {
// Exclude fields with more specific kinds of properties.
if (node.properties || node.patternProperties) {
return false;
}
// Restrict to additionalProperties with string values.
return (
json.isJsonObject(node.additionalProperties) &&
!node.additionalProperties.enum &&
node.additionalProperties.type === 'string'
);
}
const SUPPORTED_PRIMITIVE_TYPES = new Set(['boolean', 'number', 'string']);
/**
* Checks if a string is a supported primitive type.
* @param value The string to check.
* @returns `true` if the string is a supported primitive type, otherwise `false`.
*/
function isSupportedPrimitiveType(value: string): boolean {
return SUPPORTED_PRIMITIVE_TYPES.has(value);
}
/**
* Recursively checks if a JSON schema for an array's items is a supported primitive type.
* It supports `oneOf` and `anyOf` keywords.
* @param schema The JSON schema for the array's items.
* @returns `true` if the schema is a supported primitive type, otherwise `false`.
*/
function isSupportedArrayItemSchema(schema: json.JsonObject): boolean {
if (typeof schema.type === 'string' && isSupportedPrimitiveType(schema.type)) {
return true;
}
if (json.isJsonArray(schema.enum)) {
return true;
}
if (json.isJsonArray(schema.items)) {
return schema.items.some((item) => isJsonObject(item) && isSupportedArrayItemSchema(item));
}
if (
json.isJsonArray(schema.oneOf) &&
schema.oneOf.some((item) => isJsonObject(item) && isSupportedArrayItemSchema(item))
) {
return true;
}
if (
json.isJsonArray(schema.anyOf) &&
schema.anyOf.some((item) => isJsonObject(item) && isSupportedArrayItemSchema(item))
) {
return true;
}
return false;
}
/**
* Checks if a JSON schema node represents a supported array schema,
* either directly or within `oneOf`/`anyOf` subschemas.
* @param schema The JSON schema node to check.
* @returns `true` if the schema represents a supported array, otherwise `false`.
*/
function isSupportedArraySchema(schema: json.JsonObject): boolean {
if (isJsonObject(schema.items) && isSupportedArrayItemSchema(schema.items)) {
return true;
}
if (
json.isJsonArray(schema.oneOf) &&
schema.oneOf.some((item) => isJsonObject(item) && isSupportedArraySchema(item))
) {
return true;
}
if (
json.isJsonArray(schema.anyOf) &&
schema.anyOf.some((item) => isJsonObject(item) && isSupportedArraySchema(item))
) {
return true;
}
return false;
}
/**
* Gets the boolean literal values permitted by a JSON schema node.
* @param schema The JSON schema node to inspect.
* @returns A set of allowed boolean values (`true`, `false`, or both).
*/
function getAllowedBooleanValues(schema: json.JsonObject): ReadonlySet<boolean> {
if (!json.schema.getTypesOfSchema(schema).has('boolean')) {
return new Set();
}
let allowed = new Set<boolean>(ALL_BOOLEAN_VALUES);
if (schema.const !== undefined) {
if (typeof schema.const === 'boolean') {
allowed = new Set([schema.const]);
} else {
return new Set();
}
}
if (json.isJsonArray(schema.enum)) {
const enumSet = new Set(schema.enum);
allowed = new Set([...allowed].filter((v) => enumSet.has(v)));
}
if (json.isJsonArray(schema.allOf)) {
for (const subSchema of schema.allOf) {
if (isJsonObject(subSchema)) {
const subAllowed = getAllowedBooleanValues(subSchema);
allowed = new Set([...allowed].filter((v) => subAllowed.has(v)));
}
}
}
for (const keyword of ['oneOf', 'anyOf'] as const) {
const subSchemas = schema[keyword];
if (json.isJsonArray(subSchemas)) {
const combined = new Set<boolean>();
for (const subSchema of subSchemas) {
if (isJsonObject(subSchema)) {
for (const value of getAllowedBooleanValues(subSchema)) {
combined.add(value);
}
}
}
allowed = new Set([...allowed].filter((v) => combined.has(v)));
}
}
return allowed;
}
/**
* Gets the supported types for a JSON schema node.
* @param current The JSON schema node to get the supported types for.
* @returns An array of supported types.
*/
function getSupportedTypes(
current: json.JsonObject,
): ReadonlyArray<'string' | 'number' | 'boolean' | 'array' | 'object'> {
const typeSet = json.schema.getTypesOfSchema(current);
if (typeSet.size === 0) {
return [];
}
return [...typeSet].filter((type) => {
switch (type) {
case 'boolean':
case 'number':
case 'string':
return true;
case 'array':
return isSupportedArraySchema(current);
case 'object':
return isStringMap(current);
default:
return false;
}
}) as ReadonlyArray<'string' | 'number' | 'boolean' | 'array' | 'object'>;
}
/**
* Gets the enum values for a JSON schema node.
* @param current The JSON schema node to get the enum values for.
* @returns An array of enum values.
*/
function getEnumValues(
current: json.JsonObject,
): ReadonlyArray<string | number | true> | undefined {
if (json.isJsonArray(current.enum)) {
return current.enum.sort() as ReadonlyArray<string | number | true>;
}
if (isJsonObject(current.items)) {
const enumValues = getEnumValues(current.items);
if (enumValues?.length) {
return enumValues;
}
}
if (typeof current.type === 'string' && isSupportedPrimitiveType(current.type)) {
return [];
}
const subSchemas =
(json.isJsonArray(current.oneOf) && current.oneOf) ||
(json.isJsonArray(current.anyOf) && current.anyOf);
if (subSchemas) {
// Find the first enum.
for (const subSchema of subSchemas) {
if (isJsonObject(subSchema)) {
const enumValues = getEnumValues(subSchema);
if (enumValues) {
return enumValues;
}
}
}
}
return [];
}
/**
* Gets the default value for a JSON schema node.
* @param current The JSON schema node to get the default value for.
* @param type The type of the JSON schema node.
* @returns The default value, or `undefined` if there is no default value.
*/
function getDefaultValue(
current: json.JsonObject,
type: string,
): string | number | boolean | unknown[] | undefined {
const defaultValue = current.default;
if (defaultValue === undefined) {
return undefined;
}
if (type === 'array') {
return Array.isArray(defaultValue) && defaultValue.length > 0 ? defaultValue : undefined;
}
if (typeof defaultValue === type) {
return defaultValue as string | number | boolean;
}
return undefined;
}
/**
* Gets the aliases for a JSON schema node.
* @param current The JSON schema node to get the aliases for.
* @returns An array of aliases.
*/
function getAliases(current: json.JsonObject): string[] {
if (json.isJsonArray(current.aliases)) {
return [...current.aliases].map(String);
}
if (current.alias) {
return [String(current.alias)];
}
return [];
}
/**
* Parses a JSON schema to a list of options that can be used by yargs.
*
* @param registry A schema registry to use for flattening the schema.
* @param schema The JSON schema to parse.
* @param interactive Whether to prompt the user for missing options.
* @returns A list of options.
*
* @note The schema definition are not resolved at this stage. This means that `$ref` will not be resolved,
* and custom keywords like `x-prompt` will not be processed.
*/
export async function parseJsonSchemaToOptions(
registry: json.schema.SchemaRegistry,
schema: json.JsonObject,
interactive = true,
): Promise<Option[]> {
const options: Option[] = [];
function visitor(
current: json.JsonObject | json.JsonArray,
pointer: json.schema.JsonPointer,
parentSchema?: json.JsonObject | json.JsonArray,
) {
if (
!parentSchema ||
json.isJsonArray(current) ||
pointer.split(/\/(?:properties|items|definitions)\//g).length > 2
) {
// Ignore root, arrays, and subitems.
return;
}
if (pointer.includes('/not/')) {
// We don't support anyOf/not.
throw new Error('The "not" keyword is not supported in JSON Schema.');
}
const ptr = json.schema.parseJsonPointer(pointer);
if (ptr[ptr.length - 2] !== 'properties') {
// Skip any non-property items.
return;
}
const name = ptr.at(-1) as string;
const types = getSupportedTypes(current);
if (types.length === 0) {
// This means it's not usable on the command line. e.g. an Object.
return;
}
const type = types.find((t) => t !== 'boolean') ?? types[0];
const $default = current.$default;
const $defaultIndex =
isJsonObject($default) && $default['$source'] === 'argv' ? $default['index'] : undefined;
const positional: number | undefined =
typeof $defaultIndex === 'number' ? $defaultIndex : undefined;
let required = json.isJsonArray(schema.required) && schema.required.includes(name);
if (required && interactive && current['x-prompt']) {
required = false;
}
const visible = current.visible !== false;
const xDeprecated = current['x-deprecated'];
const enumValues = getEnumValues(current);
const option: Option = {
name,
description: String(current.description ?? ''),
default: getDefaultValue(current, type),
choices: enumValues?.length ? enumValues : undefined,
required,
alias: getAliases(current),
format: typeof current.format === 'string' ? current.format : undefined,
hidden: !!current.hidden || !visible,
userAnalytics:
typeof current['x-user-analytics'] === 'string' ? current['x-user-analytics'] : undefined,
deprecated: xDeprecated === true || typeof xDeprecated === 'string' ? xDeprecated : undefined,
positional,
types,
booleanValues: types.includes('boolean') ? getAllowedBooleanValues(current) : undefined,
...(type === 'object'
? {
type: 'array',
itemValueType: 'string',
}
: {
type,
}),
};
options.push(option);
}
const flattenedSchema = await registry.ɵflatten(schema);
json.schema.visitJsonSchema(flattenedSchema, visitor);
// Sort by positional and name.
return options.sort((a, b) => {
if (a.positional !== undefined) {
return b.positional !== undefined ? a.positional - b.positional : -1;
} else if (b.positional !== undefined) {
return 1;
}
return a.name.localeCompare(b.name);
});
}
/**
* Adds schema options to a command also this keeps track of options that are required for analytics.
* **Note:** This method should be called from the command bundler method.
*
* @returns A map from option name to analytics configuration.
*/
export function addSchemaOptionsToCommand<T>(
localYargs: Argv<T>,
options: Option[],
includeDefaultValues: boolean,
): Map<string, EventCustomDimension> {
const booleanOptionsWithNoPrefix = new Set<string>();
const keyValuePairOptions = new Set<string>();
const optionsWithAnalytics = new Map<string, EventCustomDimension>();
for (const option of options) {
const {
default: defaultVal,
positional,
deprecated,
description,
alias,
userAnalytics,
type,
types,
booleanValues,
itemValueType,
hidden,
name,
choices,
} = option;
let dashedName = strings.dasherize(name);
// Handle options which have been defined in the schema with `no` prefix.
if (type === 'boolean' && dashedName.startsWith('no-')) {
dashedName = dashedName.slice(3);
booleanOptionsWithNoPrefix.add(dashedName);
}
if (itemValueType) {
keyValuePairOptions.add(dashedName);
}
let coerce: YargsOptions['coerce'];
if (itemValueType) {
coerce = coerceToStringMap;
} else if (
(type === 'array' || type === 'string') &&
types?.includes('boolean') &&
booleanValues?.size !== 0
) {
coerce = createCoerceToBoolean(type, booleanValues);
}
const sharedOptions: YargsOptions & PositionalOptions = {
alias,
hidden,
description,
deprecated,
choices,
coerce,
// This should only be done when `--help` is used otherwise default will override options set in angular.json.
...(includeDefaultValues && defaultVal !== undefined ? { default: defaultVal } : {}),
};
if (positional === undefined) {
localYargs = localYargs.option(dashedName, {
array: itemValueType ? true : undefined,
type: itemValueType ?? type,
...sharedOptions,
});
} else {
localYargs = localYargs.positional(dashedName, {
type: type === 'array' || type === 'count' ? 'string' : type,
...sharedOptions,
});
}
// Record option of analytics.
if (userAnalytics !== undefined) {
optionsWithAnalytics.set(name, userAnalytics as EventCustomDimension);
}
}
// Valid key/value options
if (keyValuePairOptions.size) {
localYargs.check(checkStringMap.bind(null, keyValuePairOptions), false);
}
// Handle options which have been defined in the schema with `no` prefix.
if (booleanOptionsWithNoPrefix.size) {
localYargs.middleware((options: Arguments) => {
for (const key of booleanOptionsWithNoPrefix) {
if (key in options) {
options[`no-${key}`] = !options[key];
delete options[key];
}
}
}, false);
}
return optionsWithAnalytics;
}