forked from YousefED/typescript-json-schema
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtypescript-json-schema.js
730 lines (730 loc) · 30.1 KB
/
typescript-json-schema.js
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
"use strict";
var ts = require("typescript");
var glob = require("glob");
var path = require("path");
var stringify = require("json-stable-stringify");
var vm = require("vm");
function getDefaultArgs() {
return {
useRef: true,
useTypeAliasRef: false,
useRootRef: false,
useTitle: false,
useDefaultProperties: false,
disableExtraProperties: false,
usePropertyOrder: false,
generateRequired: false,
strictNullChecks: false,
out: undefined
};
}
exports.getDefaultArgs = getDefaultArgs;
var JsonSchemaGenerator = (function () {
function JsonSchemaGenerator(allSymbols, inheritingTypes, tc, args) {
if (args === void 0) { args = getDefaultArgs(); }
this.args = args;
this.reffedDefinitions = {};
this.simpleTypesAllowedProperties = [
"type",
"description"
];
this.allSymbols = allSymbols;
this.inheritingTypes = inheritingTypes;
this.tc = tc;
}
Object.defineProperty(JsonSchemaGenerator.prototype, "ReffedDefinitions", {
get: function () {
return this.reffedDefinitions;
},
enumerable: true,
configurable: true
});
JsonSchemaGenerator.prototype.copyValidationKeywords = function (comment, to, otherAnnotations) {
JsonSchemaGenerator.annotedValidationKeywordPattern.lastIndex = 0;
var annotation;
while ((annotation = JsonSchemaGenerator.annotedValidationKeywordPattern.exec(comment))) {
var annotationTokens = annotation[0].split(" ");
var keyword = annotationTokens[0].slice(1);
var path_1 = keyword.split(".");
var context_1 = null;
if (path_1.length > 1) {
context_1 = path_1[0];
keyword = path_1[1];
}
keyword = keyword.replace("TJS-", "");
if (JsonSchemaGenerator.validationKeywords.indexOf(keyword) >= 0 || JsonSchemaGenerator.validationKeywords.indexOf("TJS-" + keyword) >= 0) {
var value = annotationTokens.length > 1 ? annotationTokens.slice(1).join(" ") : "";
value = value.replace(/^\s+|\s+$/gm, "");
try {
value = JSON.parse(value);
}
catch (e) { }
if (context_1) {
if (!to[context_1]) {
to[context_1] = {};
}
to[context_1][keyword] = value;
}
else {
to[keyword] = value;
}
}
else {
otherAnnotations[keyword] = true;
}
}
};
JsonSchemaGenerator.prototype.copyDescription = function (comment, to) {
var delimiter = "@";
var delimiterIndex = comment.indexOf(delimiter);
var description = comment.slice(0, delimiterIndex < 0 ? comment.length : delimiterIndex);
if (description.length > 0) {
to.description = description.replace(/\s+$/g, "");
}
return delimiterIndex < 0 ? "" : comment.slice(delimiterIndex);
};
JsonSchemaGenerator.prototype.parseCommentsIntoDefinition = function (symbol, definition, otherAnnotations) {
if (!symbol) {
return;
}
var comments = symbol.getDocumentationComment();
if (!comments || !comments.length) {
return;
}
var joined = comments.map(function (comment) { return comment.text.trim(); }).join("\n");
joined = this.copyDescription(joined, definition);
this.copyValidationKeywords(joined, definition, otherAnnotations);
};
JsonSchemaGenerator.prototype.extractLiteralValue = function (typ) {
if (typ.flags & ts.TypeFlags.EnumLiteral) {
var str = typ.text;
var num = parseFloat(str);
return isNaN(num) ? str : num;
}
else if (typ.flags & ts.TypeFlags.StringLiteral) {
return typ.text;
}
else if (typ.flags & ts.TypeFlags.NumberLiteral) {
return parseFloat(typ.text);
}
else if (typ.flags & ts.TypeFlags.BooleanLiteral) {
return typ.intrinsicName === "true";
}
return undefined;
};
JsonSchemaGenerator.prototype.resolveTupleType = function (propertyType) {
if (!propertyType.getSymbol() && (propertyType.getFlags() & ts.TypeFlags.Reference)) {
return propertyType.target;
}
if (!(propertyType.flags & ts.TypeFlags.Tuple)) {
return null;
}
return propertyType;
};
JsonSchemaGenerator.prototype.getDefinitionForRootType = function (propertyType, tc, reffedType, definition) {
var _this = this;
var symbol = propertyType.getSymbol();
var tupleType = this.resolveTupleType(propertyType);
if (tupleType) {
var elemTypes = tupleType.elementTypes || propertyType.typeArguments;
var fixedTypes = elemTypes.map(function (elType) { return _this.getTypeDefinition(elType, tc); });
definition.type = "array";
definition.items = fixedTypes;
definition.minItems = fixedTypes.length;
definition.additionalItems = {
"anyOf": fixedTypes
};
}
else {
var propertyTypeString = tc.typeToString(propertyType, undefined, ts.TypeFormatFlags.UseFullyQualifiedType);
switch (propertyTypeString.toLowerCase()) {
case "string":
definition.type = "string";
break;
case "number":
var isInteger = (definition.type === "integer" || (reffedType && reffedType.getName() === "integer"));
definition.type = isInteger ? "integer" : "number";
break;
case "boolean":
definition.type = "boolean";
break;
case "null":
definition.type = "null";
break;
case "undefined":
definition.type = "undefined";
break;
case "any":
break;
case "date":
definition.type = "string";
definition.format = "date-time";
break;
default:
var value = this.extractLiteralValue(propertyType);
if (value !== undefined) {
definition.type = typeof value;
definition.enum = [value];
}
else if (symbol && symbol.getName() === "Array") {
var arrayType = propertyType.typeArguments[0];
definition.type = "array";
definition.items = this.getTypeDefinition(arrayType, tc);
}
else {
var info = propertyType;
try {
info = JSON.stringify(propertyType);
}
catch (err) { }
console.error("Unsupported type: ", info);
}
}
}
return definition;
};
JsonSchemaGenerator.prototype.getReferencedTypeSymbol = function (prop, tc) {
var decl = prop.getDeclarations();
if (decl && decl.length) {
var type = decl[0].type;
if (type && (type.kind & ts.SyntaxKind.TypeReference) && type.typeName) {
return tc.getSymbolAtLocation(type.typeName);
}
}
return null;
};
JsonSchemaGenerator.prototype.getDefinitionForProperty = function (prop, tc, node) {
var propertyName = prop.getName();
var propertyType = tc.getTypeOfSymbolAtLocation(prop, node);
var reffedType = this.getReferencedTypeSymbol(prop, tc);
var definition = this.getTypeDefinition(propertyType, tc, undefined, undefined, prop, reffedType);
if (this.args.useTitle) {
definition.title = propertyName;
}
if (definition.hasOwnProperty("ignore")) {
return null;
}
var initial = prop.valueDeclaration.initializer;
if (initial) {
if (initial.expression) {
console.warn("initializer is expression for property " + propertyName);
}
else if (initial.kind && initial.kind === ts.SyntaxKind.NoSubstitutionTemplateLiteral) {
definition.default = initial.getText();
}
else {
try {
var sandbox = { sandboxvar: null };
vm.runInNewContext("sandboxvar=" + initial.getText(), sandbox);
initial = sandbox.sandboxvar;
if (initial === null || typeof (initial) === "string" || typeof (initial) === "number" || typeof (initial) === "boolean" || Object.prototype.toString.call(initial) === "[object Array]") {
definition.default = initial;
}
else if (initial) {
console.warn("unknown initializer for property " + propertyName + ": " + initial);
}
}
catch (e) {
console.warn("exception evaluating initializer for property " + propertyName);
}
}
}
return definition;
};
JsonSchemaGenerator.prototype.getEnumDefinition = function (clazzType, tc, definition) {
var node = clazzType.getSymbol().getDeclarations()[0];
var fullName = tc.typeToString(clazzType, undefined, ts.TypeFormatFlags.UseFullyQualifiedType);
var enm = node;
var enumValues = [];
var enumTypes = [];
var addType = function (type) {
if (enumTypes.indexOf(type) === -1) {
enumTypes.push(type);
}
};
enm.members.forEach(function (member) {
var caseLabel = member.name.text;
var constantValue = tc.getConstantValue(member);
if (constantValue !== undefined) {
enumValues.push(constantValue);
addType(typeof constantValue);
}
else {
var initial = member.initializer;
if (initial) {
if (initial.expression) {
var exp = initial.expression;
var text = exp.text;
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) {
definition["enum"] = enumValues.sort();
}
return definition;
};
JsonSchemaGenerator.prototype.getUnionDefinition = function (unionType, prop, tc, unionModifier, definition) {
var enumValues = [];
var simpleTypes = [];
var schemas = [];
var addSimpleType = function (type) {
if (simpleTypes.indexOf(type) === -1) {
simpleTypes.push(type);
}
};
var addEnumValue = function (val) {
if (enumValues.indexOf(val) === -1) {
enumValues.push(val);
}
};
for (var i = 0; i < unionType.types.length; ++i) {
var valueType = unionType.types[i];
var value = this.extractLiteralValue(valueType);
if (value !== undefined) {
addEnumValue(value);
}
else {
var def = this.getTypeDefinition(unionType.types[i], tc);
if (def.type === "undefined") {
if (prop) {
prop.mayBeUndefined = true;
}
}
else {
var keys = Object.keys(def);
if (keys.length === 1 && keys[0] === "type") {
addSimpleType(def.type);
}
else {
schemas.push(def);
}
}
}
}
if (enumValues.length > 0) {
var isOnlyBooleans = enumValues.length === 2 &&
typeof enumValues[0] === "boolean" &&
typeof enumValues[1] === "boolean" &&
enumValues[0] !== enumValues[1];
if (isOnlyBooleans) {
addSimpleType("boolean");
}
else {
var enumSchema = { enum: enumValues.sort() };
if (enumValues.every(function (x) { return typeof x === "string"; })) {
enumSchema.type = "string";
}
else if (enumValues.every(function (x) { return typeof x === "number"; })) {
enumSchema.type = "number";
}
else if (enumValues.every(function (x) { return typeof x === "boolean"; })) {
enumSchema.type = "boolean";
}
schemas.push(enumSchema);
}
}
if (simpleTypes.length > 0) {
schemas.push({ type: simpleTypes.length === 1 ? simpleTypes[0] : simpleTypes });
}
if (schemas.length === 1) {
for (var k in schemas[0]) {
if (schemas[0].hasOwnProperty(k)) {
definition[k] = schemas[0][k];
}
}
}
else {
definition[unionModifier] = schemas;
}
return definition;
};
JsonSchemaGenerator.prototype.getClassDefinition = function (clazzType, tc, definition) {
var _this = this;
var node = clazzType.getSymbol().getDeclarations()[0];
var clazz = node;
var props = tc.getPropertiesOfType(clazzType);
var fullName = tc.typeToString(clazzType, undefined, ts.TypeFormatFlags.UseFullyQualifiedType);
if (props.length === 0 && clazz.members && clazz.members.length === 1 && clazz.members[0].kind === ts.SyntaxKind.IndexSignature) {
var indexSignature = clazz.members[0];
if (indexSignature.parameters.length !== 1) {
throw "Not supported: IndexSignatureDeclaration parameters.length != 1";
}
var indexSymbol = indexSignature.parameters[0].symbol;
var indexType = tc.getTypeOfSymbolAtLocation(indexSymbol, node);
var isStringIndexed = (indexType.flags === ts.TypeFlags.String);
if (indexType.flags !== ts.TypeFlags.Number && !isStringIndexed) {
throw "Not supported: IndexSignatureDeclaration with index symbol other than a number or a string";
}
var typ = tc.getTypeAtLocation(indexSignature.type);
var def = this.getTypeDefinition(typ, tc, undefined, "anyOf");
if (isStringIndexed) {
definition.type = "object";
definition.additionalProperties = def;
}
else {
definition.type = "array";
definition.items = def;
}
return definition;
}
else if (clazz.flags & ts.NodeFlags.Abstract) {
var oneOf = this.inheritingTypes[fullName].map(function (typename) {
return _this.getTypeDefinition(_this.allSymbols[typename], tc);
});
definition.oneOf = oneOf;
return definition;
}
else {
var propertyDefinitions = props.reduce(function (all, prop) {
var propertyName = prop.getName();
var propDef = _this.getDefinitionForProperty(prop, tc, node);
if (propDef != null) {
all[propertyName] = propDef;
}
return all;
}, {});
definition.type = "object";
definition.properties = propertyDefinitions;
if (this.args.useDefaultProperties) {
definition.defaultProperties = [];
}
if (this.args.disableExtraProperties && definition.additionalProperties === undefined) {
definition.additionalProperties = false;
}
if (this.args.usePropertyOrder) {
var propertyOrder = props.reduce(function (order, prop) {
order.push(prop.getName());
return order;
}, []);
definition.propertyOrder = propertyOrder;
}
if (this.args.generateRequired) {
var requiredProps = props.reduce(function (required, prop) {
if (!(prop.flags & ts.SymbolFlags.Optional) && !prop.mayBeUndefined) {
required.push(prop.getName());
}
return required;
}, []);
if (requiredProps.length > 0) {
definition.required = requiredProps;
}
}
}
};
JsonSchemaGenerator.prototype.addSimpleType = function (def, type) {
for (var k in def) {
if (this.simpleTypesAllowedProperties.indexOf(k) === -1) {
return false;
}
}
if (!def.type) {
def.type = type;
}
else if (def.type.push) {
if (!def.type.every(function (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;
};
JsonSchemaGenerator.prototype.makeNullable = function (def) {
if (!this.addSimpleType(def, "null")) {
var union = def.oneOf || def.anyOf;
if (union) {
union.push({ type: "null" });
}
else {
var subdef = {};
for (var k in def) {
if (def.hasOwnProperty(k)) {
subdef[k] = def[k];
delete def[k];
}
}
def.anyOf = [subdef, { type: "null" }];
}
}
return def;
};
JsonSchemaGenerator.prototype.getTypeDefinition = function (typ, tc, asRef, unionModifier, prop, reffedType) {
if (asRef === void 0) { asRef = this.args.useRef; }
if (unionModifier === void 0) { unionModifier = "anyOf"; }
var definition = {};
var returnedDefinition = definition;
var symbol = typ.getSymbol();
var isRawType = (!symbol || symbol.name === "integer" || symbol.name === "Array" || symbol.name === "Date");
var isStringEnum = false;
if (typ.flags & ts.TypeFlags.Union) {
var unionType = typ;
isStringEnum = (unionType.types.every(function (propType, i, r) {
return (propType.getFlags() & ts.TypeFlags.StringLiteral) !== 0;
}));
}
var asTypeAliasRef = asRef && reffedType && (this.args.useTypeAliasRef || isStringEnum);
if (!asTypeAliasRef) {
if (isRawType || (typ.getFlags() & ts.TypeFlags.Anonymous)) {
asRef = false;
}
}
var fullTypeName = "";
if (asRef) {
fullTypeName = tc.typeToString(typ, undefined, ts.TypeFormatFlags.UseFullyQualifiedType);
}
else if (asTypeAliasRef) {
fullTypeName = tc.getFullyQualifiedName(reffedType);
}
if (asRef) {
returnedDefinition = {
"$ref": "#/definitions/" + fullTypeName
};
}
var otherAnnotations = {};
this.parseCommentsIntoDefinition(reffedType, definition, otherAnnotations);
if (prop) {
this.parseCommentsIntoDefinition(prop, returnedDefinition, otherAnnotations);
}
else {
this.parseCommentsIntoDefinition(symbol, definition, otherAnnotations);
}
if (!asRef || !this.reffedDefinitions[fullTypeName]) {
if (asRef) {
this.reffedDefinitions[fullTypeName] = definition;
if (this.args.useTitle && fullTypeName) {
definition.title = fullTypeName;
}
}
var node = symbol ? symbol.getDeclarations()[0] : null;
if (typ.flags & ts.TypeFlags.Union) {
this.getUnionDefinition(typ, prop, tc, unionModifier, definition);
}
else if (typ.flags & ts.TypeFlags.Intersection) {
definition.allOf = [];
var types = typ.types;
for (var i = 0; i < types.length; ++i) {
definition.allOf.push(this.getTypeDefinition(types[i], tc));
}
}
else if (isRawType) {
this.getDefinitionForRootType(typ, tc, reffedType, definition);
}
else if (node && (node.kind === ts.SyntaxKind.EnumDeclaration || node.kind === ts.SyntaxKind.EnumMember)) {
this.getEnumDefinition(typ, tc, definition);
}
else {
this.getClassDefinition(typ, tc, definition);
}
if (otherAnnotations["nullable"]) {
this.makeNullable(definition);
}
}
return returnedDefinition;
};
JsonSchemaGenerator.prototype.getSchemaForSymbol = function (symbolName, includeReffedDefinitions) {
if (includeReffedDefinitions === void 0) { includeReffedDefinitions = true; }
if (!this.allSymbols[symbolName]) {
throw "type " + symbolName + " not found";
}
var def = this.getTypeDefinition(this.allSymbols[symbolName], this.tc, this.args.useRootRef);
if (this.args.useRef && includeReffedDefinitions && Object.keys(this.reffedDefinitions).length > 0) {
def.definitions = this.reffedDefinitions;
}
def["$schema"] = "http://json-schema.org/draft-04/schema#";
return def;
};
JsonSchemaGenerator.prototype.getSchemaForSymbols = function (symbols) {
var root = {
"$schema": "http://json-schema.org/draft-04/schema#",
definitions: {}
};
for (var id in symbols) {
if (symbols.hasOwnProperty(id)) {
root.definitions[id] = this.getTypeDefinition(symbols[id], this.tc, this.args.useRootRef);
}
}
return root;
};
JsonSchemaGenerator.validationKeywords = [
"ignore", "description", "type", "minimum", "exclusiveMinimum", "maximum",
"exclusiveMaximum", "multipleOf", "minLength", "maxLength", "format",
"pattern", "minItems", "maxItems", "uniqueItems", "default",
"additionalProperties", "enum"];
JsonSchemaGenerator.annotedValidationKeywordPattern = /@[a-z.-]+\s*[^@]+/gi;
return JsonSchemaGenerator;
}());
exports.JsonSchemaGenerator = JsonSchemaGenerator;
function getProgramFromFiles(files, compilerOptions) {
if (compilerOptions === void 0) { compilerOptions = {}; }
var options = {
noEmit: true, emitDecoratorMetadata: true, experimentalDecorators: true, target: ts.ScriptTarget.ES5, module: ts.ModuleKind.CommonJS
};
for (var k in compilerOptions) {
if (compilerOptions.hasOwnProperty(k)) {
options[k] = compilerOptions[k];
}
}
return ts.createProgram(files, options);
}
exports.getProgramFromFiles = getProgramFromFiles;
function generateSchema(program, fullTypeName, args) {
if (args === void 0) { args = getDefaultArgs(); }
var typeChecker = program.getTypeChecker();
var allSymbols = {};
var userSymbols = {};
var inheritingTypes = {};
program.getSourceFiles().forEach(function (sourceFile, sourceFileIdx) {
function inspect(node, tc) {
if (node.kind === ts.SyntaxKind.ClassDeclaration
|| node.kind === ts.SyntaxKind.InterfaceDeclaration
|| node.kind === ts.SyntaxKind.EnumDeclaration
|| node.kind === ts.SyntaxKind.TypeAliasDeclaration) {
var nodeType = tc.getTypeAtLocation(node);
var fullName_1 = tc.getFullyQualifiedName(node.symbol);
fullName_1 = fullName_1.replace(/".*"\./, "");
allSymbols[fullName_1] = nodeType;
if (!sourceFile.hasNoDefaultLib) {
userSymbols[fullName_1] = nodeType;
}
var baseTypes = nodeType.getBaseTypes() || [];
baseTypes.forEach(function (baseType) {
var baseName = tc.typeToString(baseType, undefined, ts.TypeFormatFlags.UseFullyQualifiedType);
if (!inheritingTypes[baseName]) {
inheritingTypes[baseName] = [];
}
inheritingTypes[baseName].push(fullName_1);
});
}
else {
ts.forEachChild(node, function (n) { return inspect(n, tc); });
}
}
inspect(sourceFile, typeChecker);
});
var generator = new JsonSchemaGenerator(allSymbols, inheritingTypes, typeChecker, args);
var definition;
if (fullTypeName === "*") {
definition = generator.getSchemaForSymbols(userSymbols);
}
else {
definition = generator.getSchemaForSymbol(fullTypeName);
}
return definition;
}
exports.generateSchema = generateSchema;
function programFromConfig(configFileName) {
var result = ts.parseConfigFileTextToJson(configFileName, ts.sys.readFile(configFileName));
var configObject = result.config;
var configParseResult = ts.parseJsonConfigFileContent(configObject, ts.sys, path.dirname(configFileName), {}, configFileName);
var options = configParseResult.options;
options.noEmit = true;
delete options.out;
delete options.outDir;
delete options.outFile;
delete options.declaration;
var program = ts.createProgram(configParseResult.fileNames, options);
return program;
}
exports.programFromConfig = programFromConfig;
function exec(filePattern, fullTypeName, args) {
if (args === void 0) { args = getDefaultArgs(); }
var program;
if (path.basename(filePattern) === "tsconfig.json") {
program = programFromConfig(filePattern);
}
else {
program = getProgramFromFiles(glob.sync(filePattern), {
strictNullChecks: args.strictNullChecks
});
}
var definition = generateSchema(program, fullTypeName, args);
var json = stringify(definition, { space: 4 }) + "\n\n";
if (args.out) {
require("fs").writeFile(args.out, json, function (err) {
if (err) {
console.error("Unable to write output file: " + err.message);
}
});
}
else {
process.stdout.write(json);
}
}
exports.exec = exec;
function run() {
var helpText = "Usage: node typescript-json-schema.js <path-to-typescript-files-or-tsconfig> <type>";
var defaultArgs = getDefaultArgs();
var args = require("yargs")
.usage(helpText)
.demand(2)
.boolean("refs").default("refs", defaultArgs.useRef)
.describe("refs", "Create shared ref definitions.")
.boolean("aliasRefs").default("aliasRefs", defaultArgs.useTypeAliasRef)
.describe("aliasRefs", "Create shared ref definitions for the type aliases.")
.boolean("topRef").default("topRef", defaultArgs.useRootRef)
.describe("topRef", "Create a top-level ref definition.")
.boolean("titles").default("titles", defaultArgs.useTitle)
.describe("titles", "Creates titles in the output schema.")
.boolean("defaultProps").default("defaultProps", defaultArgs.useDefaultProperties)
.describe("defaultProps", "Create default properties definitions.")
.boolean("noExtraProps").default("noExtraProps", defaultArgs.disableExtraProperties)
.describe("noExtraProps", "Disable additional properties in objects by default.")
.boolean("propOrder").default("propOrder", defaultArgs.usePropertyOrder)
.describe("propOrder", "Create property order definitions.")
.boolean("required").default("required", defaultArgs.generateRequired)
.describe("required", "Create required array for non-optional properties.")
.boolean("strictNullChecks").default("strictNullChecks", defaultArgs.strictNullChecks)
.describe("strictNullChecks", "(TypeScript 2) Make values non-nullable by default.")
.alias("out", "o")
.describe("out", "The output file, defaults to using stdout")
.argv;
exec(args._[0], args._[1], {
useRef: args.refs,
useTypeAliasRef: args.aliasRefs,
useRootRef: args.topRef,
useTitle: args.titles,
useDefaultProperties: args.defaultProps,
disableExtraProperties: args.noExtraProps,
usePropertyOrder: args.propOrder,
generateRequired: args.required,
strictNullChecks: args.strictNullChecks,
out: args.out
});
}
exports.run = run;
if (typeof window === "undefined" && require.main === module) {
run();
}
//# sourceMappingURL=typescript-json-schema.js.map