forked from YousefED/typescript-json-schema
-
Notifications
You must be signed in to change notification settings - Fork 0
/
typescript-json-schema.ts
1891 lines (1706 loc) · 71.9 KB
/
typescript-json-schema.ts
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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as glob from "glob";
import {stringify} from "safe-stable-stringify";
import * as path from "path";
import {createHash} from "crypto";
import * as ts from "typescript";
import {TypeFlags} from "typescript";
import {JSONSchema7, JSONSchema7TypeName} from "json-schema";
import {pathEqual} from "path-equal";
export {Program, CompilerOptions, Symbol} from "typescript";
const vm = require("vm");
const REGEX_FILE_NAME_OR_SPACE = /(\bimport\(".*?"\)|".*?")\.| /g;
const REGEX_TSCONFIG_NAME = /^.*\.json$/;
const REGEX_TJS_JSDOC = /^-([\w]+)\s+(\S|\S[\s\S]*\S)\s*$/g;
const REGEX_GROUP_JSDOC = /^[.]?([\w]+)\s+(\S|\S[\s\S]*\S)\s*$/g;
/**
* Resolve required file, his path and a property name,
* pattern: require([file_path]).[property_name]
*
* the part ".[property_name]" is optional in the regex
*
* will match:
*
* require('./path.ts')
* require('./path.ts').objectName
* require("./path.ts")
* require("./path.ts").objectName
* require('@module-name')
*
* match[2] = file_path (a path to the file with quotes)
* match[3] = (optional) property_name (a property name, exported in the file)
*
* for more details, see tests/require.test.ts
*/
const REGEX_REQUIRE = /^(\s+)?require\((\'@?[a-zA-Z0-9.\/_-]+\'|\"@?[a-zA-Z0-9.\/_-]+\")\)(\.([a-zA-Z0-9_$]+))?(\s+|$)/;
const NUMERIC_INDEX_PATTERN = "^[0-9]+$";
export function getDefaultArgs(): Args {
return {
ref: true,
aliasRef: false,
topRef: false,
titles: false,
defaultProps: false,
noExtraProps: false,
propOrder: false,
typeOfKeyword: false,
required: false,
strictNullChecks: false,
esModuleInterop: false,
skipLibCheck: false,
ignoreErrors: false,
out: "",
validationKeywords: [],
include: [],
excludePrivate: false,
uniqueNames: false,
rejectDateType: false,
id: "",
defaultNumberType: "number",
tsNodeRegister: false,
constAsEnum: false,
};
}
export type ValidationKeywords = {
[prop: string]: boolean;
};
export type Args = {
ref: boolean;
aliasRef: boolean;
topRef: boolean;
titles: boolean;
defaultProps: boolean;
noExtraProps: boolean;
propOrder: boolean;
typeOfKeyword: boolean;
required: boolean;
strictNullChecks: boolean;
esModuleInterop: boolean;
skipLibCheck: boolean;
ignoreErrors: boolean;
out: string;
validationKeywords: string[];
include: string[];
excludePrivate: boolean;
uniqueNames: boolean;
rejectDateType: boolean;
id: string;
defaultNumberType: "number" | "integer";
tsNodeRegister: boolean;
constAsEnum: boolean;
};
export type PartialArgs = Partial<Args>;
export type PrimitiveType = number | boolean | string | null;
type MetaDefinitionFields = "ignore";
type RedefinedFields =
| "items"
| "additionalItems"
| "contains"
| "properties"
| "patternProperties"
| "additionalProperties"
| "dependencies"
| "propertyNames"
| "if"
| "then"
| "else"
| "allOf"
| "anyOf"
| "oneOf"
| "not"
| "definitions";
export type DefinitionOrBoolean = Definition | boolean;
export interface Definition extends Omit<JSONSchema7, RedefinedFields> {
// Non-standard fields
propertyOrder?: string[];
defaultProperties?: string[];
typeof?: "function";
// Fields that must be redefined because they make use of this definition itself
items?: DefinitionOrBoolean | DefinitionOrBoolean[];
additionalItems?: DefinitionOrBoolean;
contains?: JSONSchema7;
properties?: {
[key: string]: DefinitionOrBoolean;
};
patternProperties?: {
[key: string]: DefinitionOrBoolean;
};
additionalProperties?: DefinitionOrBoolean;
dependencies?: {
[key: string]: DefinitionOrBoolean | string[];
};
propertyNames?: DefinitionOrBoolean;
if?: DefinitionOrBoolean;
then?: DefinitionOrBoolean;
else?: DefinitionOrBoolean;
allOf?: DefinitionOrBoolean[];
anyOf?: DefinitionOrBoolean[];
oneOf?: DefinitionOrBoolean[];
not?: DefinitionOrBoolean;
definitions?: {
[key: string]: DefinitionOrBoolean;
};
}
export type SymbolRef = {
name: string;
typeName: string;
fullyQualifiedName: string;
symbol: ts.Symbol;
};
function extend(target: any, ..._: any[]): any {
if (target == null) {
// TypeError if undefined or null
throw new TypeError("Cannot convert undefined or null to object");
}
const to = Object(target);
for (var index = 1; index < arguments.length; index++) {
const nextSource = arguments[index];
if (nextSource != null) {
// Skip over if undefined or null
for (const nextKey in nextSource) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
to[nextKey] = nextSource[nextKey];
}
}
}
}
return to;
}
function unique(arr: string[]): string[] {
const temp = {};
for (const e of arr) {
temp[e] = true;
}
const r: string[] = [];
for (const k in temp) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(temp, k)) {
r.push(k);
}
}
return r;
}
/**
* Resolve required file
*/
function resolveRequiredFile(symbol: ts.Symbol, key: string, fileName: string, objectName: string): any {
const sourceFile = getSourceFile(symbol);
const requiredFilePath = /^[.\/]+/.test(fileName)
? fileName === "."
? path.resolve(sourceFile.fileName)
: path.resolve(path.dirname(sourceFile.fileName), fileName)
: fileName;
const requiredFile = require(requiredFilePath);
if (!requiredFile) {
throw Error("Required: File couldn't be loaded");
}
const requiredObject = objectName ? requiredFile[objectName] : requiredFile.default;
if (requiredObject === undefined) {
throw Error("Required: Variable is undefined");
}
if (typeof requiredObject === "function") {
throw Error("Required: Can't use function as a variable");
}
if (key === "examples" && !Array.isArray(requiredObject)) {
throw Error("Required: Variable isn't an array");
}
return requiredObject;
}
export function regexRequire(value: string) {
return REGEX_REQUIRE.exec(value);
}
/**
* Try to parse a value and returns the string if it fails.
*/
function parseValue(symbol: ts.Symbol, key: string, value: string): any {
const match = regexRequire(value);
if (match) {
const fileName = match[2].substr(1, match[2].length - 2).trim();
const objectName = match[4];
return resolveRequiredFile(symbol, key, fileName, objectName);
}
try {
return JSON.parse(value);
} catch (error) {
return value;
}
}
function extractLiteralValue(typ: ts.Type): PrimitiveType | undefined {
let str = (<ts.LiteralType>typ).value;
if (str === undefined) {
str = (typ as any).text;
}
if (typ.flags & ts.TypeFlags.StringLiteral) {
return str as string;
} else if (typ.flags & ts.TypeFlags.BooleanLiteral) {
return (typ as any).intrinsicName === "true";
} else if (typ.flags & ts.TypeFlags.EnumLiteral) {
// or .text for old TS
const num = parseFloat(str as string);
return isNaN(num) ? (str as string) : num;
} else if (typ.flags & ts.TypeFlags.NumberLiteral) {
return parseFloat(str as string);
}
return undefined;
}
/**
* Checks whether a type is a tuple type.
*/
function resolveTupleType(propertyType: ts.Type): ts.TupleTypeNode | null {
if (
!propertyType.getSymbol() &&
propertyType.getFlags() & ts.TypeFlags.Object &&
(<ts.ObjectType>propertyType).objectFlags & ts.ObjectFlags.Reference
) {
return (propertyType as ts.TypeReference).target as any;
}
if (
!(
propertyType.getFlags() & ts.TypeFlags.Object &&
(<ts.ObjectType>propertyType).objectFlags & ts.ObjectFlags.Tuple
)
) {
return null;
}
return propertyType as any;
}
const simpleTypesAllowedProperties = {
type: true,
description: true,
};
function addSimpleType(def: Definition, type: JSONSchema7TypeName): boolean {
for (const k in def) {
if (!simpleTypesAllowedProperties[k]) {
return false;
}
}
if (!def.type) {
def.type = type;
} else if (typeof def.type !== "string") {
if (
!(<Object[]>def.type).every((val) => {
return typeof val === "string";
})
) {
return false;
}
if (def.type.indexOf("null") === -1) {
def.type.push("null");
}
} else {
if (typeof def.type !== "string") {
return false;
}
if (def.type !== "null") {
def.type = [def.type, "null"];
}
}
return true;
}
function makeNullable(def: Definition): Definition {
if (!addSimpleType(def, "null")) {
const union = def.oneOf || def.anyOf;
if (union) {
union.push({type: "null"});
} else {
const subdef = {};
for (var k in def) {
if (def.hasOwnProperty(k)) {
subdef[k] = def[k];
delete def[k];
}
}
def.anyOf = [subdef, {type: "null"}];
}
}
return def;
}
/**
* Given a Symbol, returns a canonical Definition. That can be either:
* 1) The Symbol's valueDeclaration parameter if defined, or
* 2) The sole entry in the Symbol's declarations array, provided that array has a length of 1.
*
* valueDeclaration is listed as a required parameter in the definition of a Symbol, but I've
* experienced crashes when it's undefined at runtime, which is the reason for this function's
* existence. Not sure if that's a compiler API bug or what.
*/
function getCanonicalDeclaration(sym: ts.Symbol): ts.Declaration {
if (sym.valueDeclaration !== undefined) {
return sym.valueDeclaration;
} else if (sym.declarations?.length === 1) {
return sym.declarations[0];
}
const declarationCount = sym.declarations?.length ?? 0;
throw new Error(`Symbol "${sym.name}" has no valueDeclaration and ${declarationCount} declarations.`);
}
/**
* Given a Symbol, finds the place it was declared and chases parent pointers until we find a
* node where SyntaxKind === SourceFile.
*/
function getSourceFile(sym: ts.Symbol): ts.SourceFile {
let currentDecl: ts.Node = getCanonicalDeclaration(sym);
while (currentDecl.kind !== ts.SyntaxKind.SourceFile) {
if (currentDecl.parent === undefined) {
throw new Error(`Unable to locate source file for declaration "${sym.name}".`);
}
currentDecl = currentDecl.parent;
}
return currentDecl as ts.SourceFile;
}
/**
* JSDoc keywords that should be used to annotate the JSON schema.
*
* Many of these validation keywords are defined here: http://json-schema.org/latest/json-schema-validation.html
*/
// prettier-ignore
const validationKeywords = {
multipleOf: true, // 6.1.
maximum: true, // 6.2.
exclusiveMaximum: true, // 6.3.
minimum: true, // 6.4.
exclusiveMinimum: true, // 6.5.
maxLength: true, // 6.6.
minLength: true, // 6.7.
pattern: true, // 6.8.
items: true, // 6.9.
// additionalItems: true, // 6.10.
maxItems: true, // 6.11.
minItems: true, // 6.12.
uniqueItems: true, // 6.13.
contains: true, // 6.14.
maxProperties: true, // 6.15.
minProperties: true, // 6.16.
// required: true, // 6.17. This is not required. It is auto-generated.
// properties: true, // 6.18. This is not required. It is auto-generated.
// patternProperties: true, // 6.19.
additionalProperties: true, // 6.20.
// dependencies: true, // 6.21.
// propertyNames: true, // 6.22.
enum: true, // 6.23.
// const: true, // 6.24.
type: true, // 6.25.
// allOf: true, // 6.26.
// anyOf: true, // 6.27.
// oneOf: true, // 6.28.
// not: true, // 6.29.
examples: true, // Draft 6 (draft-handrews-json-schema-validation-01)
ignore: true,
description: true,
format: true,
default: true,
$ref: true,
id: true,
$id: true,
title: true
};
/**
* Subset of descriptive, non-type keywords that are permitted alongside a $ref.
* Prior to JSON Schema draft 2019-09, $ref is a special keyword that doesn't
* permit keywords alongside it, and so AJV may raise warnings if it encounters
* any type-related keywords; see https://github.com/ajv-validator/ajv/issues/1121
*/
const annotationKeywords: { [k in keyof typeof validationKeywords]?: true } = {
description: true,
default: true,
examples: true,
title: true,
// A JSDoc $ref annotation can appear as a $ref.
$ref: true,
};
const subDefinitions = {
items: true,
additionalProperties: true,
contains: true,
};
export class JsonSchemaGenerator {
private tc: ts.TypeChecker;
/**
* Holds all symbols within a custom SymbolRef object, containing useful
* information.
*/
private symbols: SymbolRef[];
/**
* All types for declarations of classes, interfaces, enums, and type aliases
* defined in all TS files.
*/
private allSymbols: { [name: string]: ts.Type };
/**
* All symbols for declarations of classes, interfaces, enums, and type aliases
* defined in non-default-lib TS files.
*/
private userSymbols: { [name: string]: ts.Symbol };
/**
* Maps from the names of base types to the names of the types that inherit from
* them.
*/
private inheritingTypes: { [baseName: string]: string[] };
/**
* This map holds references to all reffed definitions, including schema
* overrides and generated definitions.
*/
private reffedDefinitions: { [key: string]: Definition } = {};
/**
* This map only holds explicit schema overrides. This helps differentiate between
* user defined schema overrides and generated definitions.
*/
private schemaOverrides = new Map<string, Definition>();
/**
* This is a set of all the user-defined validation keywords.
*/
private userValidationKeywords: ValidationKeywords;
/**
* If true, this makes constants be defined as enums with a single value. This is useful
* for cases where constant values are not supported, such as OpenAPI.
*/
private constAsEnum: boolean;
/**
* Types are assigned names which are looked up by their IDs. This is the
* map from type IDs to type names.
*/
private typeNamesById: { [id: number]: string } = {};
/**
* Whenever a type is assigned its name, its entry in this dictionary is set,
* so that we don't give the same name to two separate types.
*/
private typeIdsByName: { [name: string]: number } = {};
constructor(
symbols: SymbolRef[],
allSymbols: { [name: string]: ts.Type },
userSymbols: { [name: string]: ts.Symbol },
inheritingTypes: { [baseName: string]: string[] },
tc: ts.TypeChecker,
private args = getDefaultArgs()
) {
this.symbols = symbols;
this.allSymbols = allSymbols;
this.userSymbols = userSymbols;
this.inheritingTypes = inheritingTypes;
this.tc = tc;
this.userValidationKeywords = args.validationKeywords.reduce((acc, word) => ({...acc, [word]: true}), {});
this.constAsEnum = args.constAsEnum;
}
public get ReffedDefinitions(): { [key: string]: Definition } {
return this.reffedDefinitions;
}
private isFromDefaultLib(symbol: ts.Symbol) {
const declarations = symbol.getDeclarations();
if (declarations && declarations.length > 0 && declarations[0].parent) {
return declarations[0].parent.getSourceFile().hasNoDefaultLib;
}
return false;
}
private resetSchemaSpecificProperties() {
this.reffedDefinitions = {};
this.typeIdsByName = {};
this.typeNamesById = {};
// restore schema overrides
this.schemaOverrides.forEach((value, key) => {
this.reffedDefinitions[key] = value;
});
}
/**
* Parse the comments of a symbol into the definition and other annotations.
*/
private parseCommentsIntoDefinition(symbol: ts.Symbol, definition: Definition, otherAnnotations: {}): void {
if (!symbol) {
return;
}
if (!this.isFromDefaultLib(symbol)) {
// the comments for a symbol
const comments = symbol.getDocumentationComment(this.tc);
if (comments.length) {
definition.description = comments
.map((comment) => {
const newlineNormalizedComment = comment.text.replace(/\r\n/g, "\n");
// If a comment contains a "{@link XYZ}" inline tag that could not be
// resolved by the TS checker, then this comment will contain a trailing
// whitespace that we need to remove.
if (comment.kind === "linkText") {
return newlineNormalizedComment.trim();
}
return newlineNormalizedComment;
})
.join("").trim();
}
}
// jsdocs are separate from comments
const jsdocs = symbol.getJsDocTags();
jsdocs.forEach((doc) => {
// if we have @TJS-... annotations, we have to parse them
let name = doc.name;
const originalText = doc.text ? doc.text.map((t) => t.text).join("") : "";
let text = originalText;
// In TypeScript versions prior to 3.7, it stops parsing the annotation
// at the first non-alphanumeric character and puts the rest of the line as the
// "text" of the annotation, so we have a little hack to check for the name
// "TJS" and then we sort of re-parse the annotation to support prior versions
// of TypeScript.
if (name.startsWith("TJS-")) {
name = name.slice(4);
if (!text) {
text = "true";
}
} else if (name === "TJS" && text.startsWith("-")) {
let match: string[] | RegExpExecArray | null = new RegExp(REGEX_TJS_JSDOC).exec(originalText);
if (match) {
name = match[1];
text = match[2];
} else {
// Treat empty text as boolean true
name = (text as string).replace(/^[\s\-]+/, "");
text = "true";
}
}
// In TypeScript ~3.5, the annotation name splits at the dot character so we have
// to process the "." and beyond from the value
if (subDefinitions[name]) {
const match: string[] | RegExpExecArray | null = new RegExp(REGEX_GROUP_JSDOC).exec(text);
if (match) {
const k = match[1];
const v = match[2];
definition[name] = {...definition[name], [k]: v ? parseValue(symbol, k, v) : true};
return;
}
}
// In TypeScript 3.7+, the "." is kept as part of the annotation name
if (name.includes(".")) {
const parts = name.split(".");
if (parts.length === 2 && subDefinitions[parts[0]]) {
definition[parts[0]] = {
...definition[parts[0]],
[parts[1]]: text ? parseValue(symbol, name, text) : true,
};
}
}
if (validationKeywords[name] || this.userValidationKeywords[name]) {
definition[name] = text === undefined ? "" : parseValue(symbol, name, text);
} else {
// special annotations
otherAnnotations[doc.name] = true;
}
});
}
private getDefinitionForRootType(
propertyType: ts.Type,
reffedType: ts.Symbol,
definition: Definition,
defaultNumberType = this.args.defaultNumberType,
ignoreUndefined = false,
): Definition {
const tupleType = resolveTupleType(propertyType);
if (tupleType) {
// tuple
const elemTypes: ts.NodeArray<ts.TypeNode> = (propertyType as any).typeArguments;
const fixedTypes = elemTypes.map((elType) => this.getTypeDefinition(elType as any));
definition.type = "array";
if (fixedTypes.length > 0) {
definition.items = fixedTypes;
}
const targetTupleType = (propertyType as ts.TupleTypeReference).target;
definition.minItems = targetTupleType.minLength;
if (targetTupleType.hasRestElement) {
definition.additionalItems = fixedTypes[fixedTypes.length - 1];
fixedTypes.splice(fixedTypes.length - 1, 1);
} else {
definition.maxItems = targetTupleType.fixedLength;
}
} else {
const propertyTypeString = this.tc.typeToString(
propertyType,
undefined,
ts.TypeFormatFlags.UseFullyQualifiedType
);
const flags = propertyType.flags;
const arrayType = this.tc.getIndexTypeOfType(propertyType, ts.IndexKind.Number);
if (flags & ts.TypeFlags.String) {
definition.type = "string";
} else if (flags & ts.TypeFlags.Number) {
const isInteger =
definition.type === "integer" ||
reffedType?.getName() === "integer" ||
defaultNumberType === "integer";
definition.type = isInteger ? "integer" : "number";
} else if (flags & ts.TypeFlags.Boolean) {
definition.type = "boolean";
} else if (flags & ts.TypeFlags.ESSymbol) {
definition.type = "object";
} else if (flags & ts.TypeFlags.Null) {
definition.type = "null";
} else if (flags & ts.TypeFlags.Undefined || propertyTypeString === "void") {
if (!ignoreUndefined) {
console.log({
propertyType: propertyType,
reffedType: reffedType,
definition: definition,
defaultNumberType: defaultNumberType,
ignoreUndefined: ignoreUndefined,
});
throw new Error("Not supported: root type undefined");
}
// will be deleted
definition.type = "undefined" as any;
} else if (flags & ts.TypeFlags.Any || flags & ts.TypeFlags.Unknown) {
// no type restriction, so that anything will match
} else if (propertyTypeString === "Date" && !this.args.rejectDateType) {
definition.type = "string";
definition.format = definition.format || "date-time";
} else if (propertyTypeString === "object") {
definition.type = "object";
definition.properties = {};
definition.additionalProperties = true;
} else {
const value = extractLiteralValue(propertyType);
if (value !== undefined) {
// typeof value can be: "string", "boolean", "number", or "object" if value is null
const typeofValue = typeof value;
switch (typeofValue) {
case "string":
case "boolean":
definition.type = typeofValue;
break;
case "number":
definition.type = this.args.defaultNumberType;
break;
case "object":
definition.type = "null";
break;
default:
throw new Error(`Not supported: ${value} as a enum value`);
}
if (this.constAsEnum) {
definition.enum = [value];
} else {
definition.const = value;
}
} else if (arrayType !== undefined) {
if (
propertyType.flags & ts.TypeFlags.Object &&
(propertyType as ts.ObjectType).objectFlags &
(ts.ObjectFlags.Anonymous | ts.ObjectFlags.Interface | ts.ObjectFlags.Mapped)
) {
definition.type = "object";
definition.additionalProperties = false;
definition.patternProperties = {
[NUMERIC_INDEX_PATTERN]: this.getTypeDefinition(arrayType),
};
if (!!Array.from((<any>propertyType).members)?.find((member: [string]) => member[0] !== "__index")) {
this.getClassDefinition(propertyType, definition);
}
} else if (propertyType.flags & ts.TypeFlags.TemplateLiteral) {
definition.type = "string";
// @ts-ignore
const {texts, types} = propertyType;
const pattern = [];
for (let i = 0; i < texts.length; i++) {
const text = texts[i];
const type = types[i];
if (i === 0) {
pattern.push(`^`);
}
if (type) {
if (type.flags & ts.TypeFlags.String) {
pattern.push(`${text}.*`);
}
if (type.flags & ts.TypeFlags.Number
|| type.flags & ts.TypeFlags.BigInt) {
pattern.push(`${text}[0-9]*`);
}
if (type.flags & ts.TypeFlags.Undefined) {
pattern.push(`${text}undefined`);
}
if (type.flags & ts.TypeFlags.Null) {
pattern.push(`${text}null`);
}
}
if (i === texts.length - 1) {
pattern.push(`${text}$`);
}
}
definition.pattern = pattern.join("");
} else {
definition.type = "array";
if (!definition.items) {
definition.items = this.getTypeDefinition(arrayType);
}
}
} else if (propertyType.flags === TypeFlags.IndexedAccess) {
const indexedType = propertyType as ts.IndexedAccessType;
let objectType = indexedType.objectType;
const indexType = indexedType.indexType;
let resultingType: ts.Type | undefined;
if (objectType.flags & ts.TypeFlags.TypeParameter) {
const typeParameter = objectType as ts.TypeParameter;
if (typeParameter.getConstraint()) {
objectType = this.tc.getApparentType(typeParameter.getConstraint()!);
}
if (indexType.flags & ts.TypeFlags.StringLiteral) {
resultingType = this.tc.getIndexTypeOfType(objectType, ts.IndexKind.String);
} else if (indexType.flags & ts.TypeFlags.NumberLiteral) {
resultingType = this.tc.getIndexTypeOfType(objectType, ts.IndexKind.Number);
}
}
let indexedSymbolType
if (!resultingType && objectType) {
if (indexType.flags & ts.TypeFlags.StringLiteral) {
const stringLiteralType = indexType as ts.StringLiteralType;
const propertyName = stringLiteralType.value; // This should give you "CallOptions"
const indexedSymbol = objectType.getProperty(propertyName);
if (indexedSymbol) {
indexedSymbolType = this.tc.getTypeOfSymbolAtLocation(indexedSymbol, indexedSymbol.valueDeclaration!);
}
}
}
if (indexedSymbolType) {
if (!indexedSymbolType.symbol) {
console.log("no symbol for ", propertyTypeString);
}
this.getClassDefinition(indexedSymbolType, definition);
} else {
const error = new TypeError("Unsupported type: " + propertyTypeString);
(error as any).type = propertyType;
throw error;
}
} else {
// Report that type could not be processed
const error = new TypeError("Unsupported type: " + propertyTypeString);
(error as any).type = propertyType;
throw error;
// definition = this.getTypeDefinition(propertyType, tc);
}
}
}
return definition;
}
private getReferencedTypeSymbol(prop: ts.Symbol): ts.Symbol | undefined {
const decl = prop.getDeclarations();
if (decl?.length) {
const type = <ts.TypeReferenceNode>(<any>decl[0]).type;
if (type && type.kind & ts.SyntaxKind.TypeReference && type.typeName) {
const symbol = this.tc.getSymbolAtLocation(type.typeName);
if (symbol && symbol.flags & ts.SymbolFlags.Alias) {
return this.tc.getAliasedSymbol(symbol);
}
return symbol;
}
}
return undefined;
}
private getDefinitionForProperty(prop: ts.Symbol, node: ts.Node): Definition | null {
if (prop.flags & ts.SymbolFlags.Method) {
return null;
}
const propertyName = prop.getName();
const propertyType = this.tc.getTypeOfSymbolAtLocation(prop, node);
const reffedType = this.getReferencedTypeSymbol(prop);
const definition = this.getTypeDefinition(propertyType, undefined, undefined, prop, reffedType);
if (this.args.titles) {
definition.title = propertyName;
}
if (definition.hasOwnProperty("ignore")) {
return null;
}
// try to get default value
const valDecl = prop.valueDeclaration as ts.VariableDeclaration;
if (valDecl?.initializer) {
let initial = valDecl.initializer;
while (ts.isTypeAssertionExpression(initial)) {
initial = initial.expression;
}
if ((<any>initial).expression) {
// node
console.warn("initializer is expression for property " + propertyName);
} else if ((<any>initial).kind && (<any>initial).kind === ts.SyntaxKind.NoSubstitutionTemplateLiteral) {
definition.default = initial.getText();
} else {
try {
const sandbox = {sandboxvar: null as any};
vm.runInNewContext("sandboxvar=" + initial.getText(), sandbox);
const val = sandbox.sandboxvar;
if (
val === null ||
typeof val === "string" ||
typeof val === "number" ||
typeof val === "boolean" ||
Object.prototype.toString.call(val) === "[object Array]"
) {
definition.default = val;
} else if (val) {
console.warn("unknown initializer for property " + propertyName + ": " + val);
}
} catch (e) {
console.warn("exception evaluating initializer for property " + propertyName);
}
}
}
return definition;
}
private getEnumDefinition(clazzType: ts.Type, definition: Definition): Definition {
const node = clazzType.getSymbol()!.getDeclarations()![0];
const fullName = this.tc.typeToString(clazzType, undefined, ts.TypeFormatFlags.UseFullyQualifiedType);
const members: ts.NodeArray<ts.EnumMember> =
node.kind === ts.SyntaxKind.EnumDeclaration
? (node as ts.EnumDeclaration).members
: ts.factory.createNodeArray([node as ts.EnumMember]);
var enumValues: (number | boolean | string | null)[] = [];
const enumTypes: JSONSchema7TypeName[] = [];
const addType = (type: JSONSchema7TypeName) => {
if (enumTypes.indexOf(type) === -1) {
enumTypes.push(type);
}
};
members.forEach((member) => {
const caseLabel = (<ts.Identifier>member.name).text;
const constantValue = this.tc.getConstantValue(member);
if (constantValue !== undefined) {
enumValues.push(constantValue);
addType(typeof constantValue as JSONSchema7TypeName); // can be only string or number;
} else {
// try to extract the enums value; it will probably by a cast expression
const initial: ts.Expression | undefined = member.initializer;
if (initial) {
if ((<any>initial).expression) {
// node
const exp = (<any>initial).expression;
const text = (<any>exp).text;
// if it is an expression with a text literal, chances are it is the enum convention:
// CASELABEL = 'literal' as any
if (text) {
enumValues.push(text);
addType("string");
} else if (exp.kind === ts.SyntaxKind.TrueKeyword || exp.kind === ts.SyntaxKind.FalseKeyword) {
enumValues.push(exp.kind === ts.SyntaxKind.TrueKeyword);
addType("boolean");
} else {
console.warn("initializer is expression for enum: " + fullName + "." + caseLabel);
}
} else if (initial.kind === ts.SyntaxKind.NoSubstitutionTemplateLiteral) {
enumValues.push(initial.getText());
addType("string");
} else if (initial.kind === ts.SyntaxKind.NullKeyword) {
enumValues.push(null);
addType("null");
}
}
}
});
if (enumTypes.length) {
definition.type = enumTypes.length === 1 ? enumTypes[0] : enumTypes;
}
if (enumValues.length > 0) {
if (enumValues.length > 1) {
definition.enum = enumValues.sort();
} else {
definition.const = enumValues[0];
}
}
return definition;
}
private getUnionDefinition(
unionType: ts.UnionType,
unionModifier: string,
definition: Definition
): Definition {
const enumValues: PrimitiveType[] = [];
const simpleTypes: JSONSchema7TypeName[] = [];
const schemas: Definition[] = [];
const pushSimpleType = (type: JSONSchema7TypeName) => {
if (simpleTypes.indexOf(type) === -1) {
simpleTypes.push(type);
}
};
const pushEnumValue = (val: PrimitiveType) => {