UNPKG

19.3 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const tslib_1 = require("tslib");
4const debug_1 = (0, tslib_1.__importDefault)(require("debug"));
5const ts = (0, tslib_1.__importStar)(require("typescript"));
6const jsonPointer_1 = require("../jsonPointer");
7const ast = (0, tslib_1.__importStar)(require("./astBuilder"));
8const config_1 = (0, tslib_1.__importDefault)(require("./config"));
9const jsonSchema_1 = require("./jsonSchema");
10const referenceResolver_1 = (0, tslib_1.__importDefault)(require("./referenceResolver"));
11const type_1 = require("./type");
12const typeTree_1 = require("./typeTree");
13const utils = (0, tslib_1.__importStar)(require("./utils"));
14const debug = (0, debug_1.default)('dtsgen');
15class DtsGenerator {
16 constructor(contents) {
17 this.resolver = new referenceResolver_1.default();
18 this.contents = contents;
19 }
20 async generate() {
21 const plugins = await this.getPlugins();
22 const preProcess = await this.getPreProcess(plugins.pre);
23 for (const p of preProcess) {
24 this.contents = p(this.contents);
25 }
26 debug('generate type definition files.');
27 this.contents.forEach((schema) => this.resolver.registerSchema(schema));
28 await this.resolver.resolve();
29 const tree = (0, typeTree_1.buildTypeTree)(this.resolver.getAllRegisteredSchema());
30 const root = this.walk(tree);
31 const file = ts.createSourceFile('_.d.ts', '', config_1.default.target, false, ts.ScriptKind.TS);
32 Object.assign(file, {
33 statements: ts.factory.createNodeArray(root),
34 });
35 const postProcess = await this.getPostProcess(plugins.post);
36 const result = ts.transform(file, postProcess);
37 const transformedNodes = result.transformed[0];
38 const transformedContent = config_1.default.outputAST
39 ? JSON.stringify(transformedNodes, null, 2)
40 : (function () {
41 const printer = ts.createPrinter();
42 return printer.printNode(ts.EmitHint.SourceFile, transformedNodes, file);
43 })();
44 result.dispose();
45 return transformedContent;
46 }
47 async getPlugins() {
48 const pre = [];
49 const post = [];
50 for (const [name, option] of Object.entries(config_1.default.plugins)) {
51 const plugin = await (0, type_1.loadPlugin)(name, option);
52 if (plugin == null) {
53 continue;
54 }
55 if (plugin.preProcess != null) {
56 pre.push({ plugin, option });
57 }
58 if (plugin.postProcess != null) {
59 post.push({ plugin, option });
60 }
61 }
62 return { pre, post };
63 }
64 async getPreProcess(pre) {
65 debug('load pre process plugin.');
66 const result = [];
67 const inputSchemas = this.resolver.getAllRegisteredIdAndSchema();
68 for (const pc of pre) {
69 const p = pc.plugin.preProcess;
70 if (p == null) {
71 continue;
72 }
73 const handler = await p({ inputSchemas, option: pc.option });
74 if (handler != null) {
75 result.push(handler);
76 debug(' pre process plugin:', pc.plugin.meta.name, pc.plugin.meta.description);
77 }
78 }
79 return result;
80 }
81 async getPostProcess(post) {
82 debug('load post process plugin.');
83 const result = [];
84 const inputSchemas = this.resolver.getAllRegisteredIdAndSchema();
85 for (const pc of post) {
86 const p = pc.plugin.postProcess;
87 if (p == null) {
88 continue;
89 }
90 const factory = await p({ inputSchemas, option: pc.option });
91 if (factory != null) {
92 result.push(factory);
93 debug(' pre process plugin:', pc.plugin.meta.name, pc.plugin.meta.description);
94 }
95 }
96 return result;
97 }
98 walk(tree, root = true) {
99 const result = [];
100 const keys = [...tree.children.keys()].sort();
101 for (const key of keys) {
102 const value = tree.children.get(key);
103 if (value === undefined) {
104 continue;
105 }
106 if (value.schema !== undefined) {
107 const schema = value.schema;
108 debug(` walk doProcess: key=${key} schemaId=${schema.id.getAbsoluteId()}`);
109 result.push(this.walkSchema(schema, root));
110 }
111 if (value.children.size > 0) {
112 result.push(ast.buildNamespaceNode(key, this.walk(value, false), root));
113 }
114 }
115 return result;
116 }
117 walkSchema(schema, root) {
118 const normalized = this.normalizeContent(schema);
119 this.currentSchema = normalized;
120 return ast.addOptionalInformation(ast.addComment(this.parseSchema(normalized, root), normalized, true), normalized, true);
121 }
122 parseSchema(schema, root = false) {
123 const type = schema.content.type;
124 switch (type) {
125 case 'any':
126 return this.generateAnyTypeModel(schema, root);
127 case 'array':
128 return this.generateTypeCollection(schema, root);
129 case 'object':
130 default:
131 return this.generateDeclareType(schema, root);
132 }
133 }
134 normalizeContent(schema, pointer) {
135 if (pointer != null) {
136 schema = (0, jsonSchema_1.getSubSchema)(schema, pointer);
137 }
138 return Object.assign(schema, {
139 content: this.normalizeSchemaContent(schema.content),
140 });
141 }
142 normalizeSchemaContent(content) {
143 if (typeof content === 'boolean') {
144 content = content ? {} : { not: {} };
145 }
146 else {
147 if (content.allOf) {
148 const work = {};
149 const allOf = content.allOf;
150 delete content.allOf;
151 for (const sub of allOf) {
152 if (typeof sub === 'object' && sub.$ref) {
153 const ref = this.resolver.dereference(sub.$ref);
154 const normalized = this.normalizeContent(ref).content;
155 utils.mergeSchema(work, normalized);
156 }
157 else {
158 const normalized = this.normalizeSchemaContent(sub);
159 utils.mergeSchema(work, normalized);
160 }
161 }
162 utils.mergeSchema(work, content);
163 content = Object.assign(content, work);
164 }
165 if (content.type === undefined &&
166 (content.properties || content.additionalProperties)) {
167 content.type = 'object';
168 }
169 if (content.nullable) {
170 const type = content.type;
171 const anyOf = content.anyOf;
172 if (Array.isArray(anyOf)) {
173 anyOf.push({ type: 'null' });
174 }
175 else if (type == null) {
176 content.type = 'null';
177 }
178 else if (!Array.isArray(type)) {
179 content.type = [type, 'null'];
180 }
181 else {
182 type.push('null');
183 }
184 }
185 const types = content.type;
186 if (Array.isArray(types)) {
187 const reduced = utils.reduceTypes(types);
188 content.type = reduced.length === 1 ? reduced[0] : reduced;
189 }
190 }
191 return content;
192 }
193 generateDeclareType(schema, root) {
194 const content = schema.content;
195 if (content.$ref ||
196 content.oneOf ||
197 content.anyOf ||
198 content.enum ||
199 'const' in content ||
200 content.type !== 'object') {
201 const type = this.generateTypeProperty(schema);
202 return ast.buildTypeAliasNode(schema.id, type, root);
203 }
204 else {
205 const members = this.generateProperties(schema);
206 return ast.buildInterfaceNode(schema.id, members, root);
207 }
208 }
209 generateAnyTypeModel(schema, root) {
210 const member = ast.buildIndexSignatureNode('name', ast.buildStringKeyword(), ast.buildAnyKeyword());
211 return ast.buildInterfaceNode(schema.id, [member], root);
212 }
213 generateTypeCollection(schema, root) {
214 const type = this.generateArrayTypeProperty(schema);
215 return ast.buildTypeAliasNode(schema.id, type, root);
216 }
217 generateProperties(baseSchema) {
218 const result = [];
219 const content = baseSchema.content;
220 if (content.additionalProperties) {
221 const schema = this.normalizeContent(baseSchema, '/additionalProperties');
222 const valueType = content.additionalProperties === true
223 ? ast.buildAnyKeyword()
224 : this.generateTypeProperty(schema);
225 const node = ast.buildIndexSignatureNode('name', ast.buildStringKeyword(), valueType);
226 result.push(ast.addOptionalInformation(node, schema, true));
227 }
228 if (content.properties) {
229 for (const propertyName of Object.keys(content.properties)) {
230 const schema = this.normalizeContent(baseSchema, '/properties/' + (0, jsonPointer_1.tilde)(propertyName));
231 const node = ast.buildPropertySignature(schema, propertyName, this.generateTypeProperty(schema), baseSchema.content.required, false);
232 result.push(ast.addOptionalInformation(ast.addComment(node, schema, true), schema, true));
233 }
234 }
235 if (content.patternProperties) {
236 const properties = Object.keys(content.patternProperties);
237 const node = ast.buildPropertySignature({ content: { readOnly: false } }, 'pattern', ast.buildUnionTypeNode(properties, (propertyName) => this.generateTypeProperty(this.normalizeContent(baseSchema, '/patternProperties/' + (0, jsonPointer_1.tilde)(propertyName))), true), baseSchema.content.required, true);
238 result.push(ts.addSyntheticTrailingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, ` Patterns: ${properties.join(' | ')} `));
239 }
240 return result;
241 }
242 generateTypeProperty(schema, terminate = true) {
243 const content = schema.content;
244 if (content.$ref) {
245 const ref = this.resolver.dereference(content.$ref);
246 if (ref.id == null) {
247 throw new Error('target referenced id is nothing: ' + content.$ref);
248 }
249 const refSchema = this.normalizeContent(ref);
250 const node = ast.addOptionalInformation(ast.addComment(ast.buildTypeReferenceNode(refSchema, this.currentSchema), refSchema, false), refSchema, false);
251 return node;
252 }
253 if (content.anyOf) {
254 const mergeContent = Object.assign({}, content);
255 delete mergeContent.anyOf;
256 return this.generateUnionType(schema, content.anyOf, mergeContent, '/anyOf/', terminate);
257 }
258 if (content.oneOf) {
259 const mergeContent = Object.assign({}, content);
260 delete mergeContent.oneOf;
261 return this.generateUnionType(schema, content.oneOf, mergeContent, '/oneOf/', terminate);
262 }
263 return this.generateLiteralTypeProperty(schema, terminate);
264 }
265 generateLiteralTypeProperty(schema, terminate = true) {
266 const content = schema.content;
267 if (content.enum) {
268 return ast.buildUnionTypeNode(content.enum, (value) => {
269 return this.generateLiteralTypeNode(content, value);
270 }, terminate);
271 }
272 else if (content.not) {
273 return ast.buildVoidKeyword();
274 }
275 else if ('const' in content) {
276 return this.generateLiteralTypeNode(content, content.const);
277 }
278 else {
279 return this.generateType(schema, terminate);
280 }
281 }
282 checkExistOtherType(content, base) {
283 const schema = Object.assign({}, base, { content });
284 const result = this.generateLiteralTypeProperty(schema, false);
285 if (result.kind === ts.SyntaxKind.AnyKeyword) {
286 return undefined;
287 }
288 else if (result.kind === ts.SyntaxKind.TypeLiteral) {
289 const node = result;
290 if (node.members.length === 1 &&
291 node.members[0].kind === ts.SyntaxKind.IndexSignature) {
292 return undefined;
293 }
294 }
295 return result;
296 }
297 generateLiteralTypeNode(content, value) {
298 switch (content.type) {
299 case 'integer':
300 case 'number':
301 return ast.buildNumericLiteralTypeNode(String(value));
302 case 'boolean':
303 return ast.buildBooleanLiteralTypeNode(Boolean(value));
304 case 'null':
305 return ast.buildNullKeyword();
306 case 'string':
307 return ast.buildStringLiteralTypeNode(String(value));
308 }
309 if (value === null) {
310 return ast.buildNullKeyword();
311 }
312 switch (typeof value) {
313 case 'number':
314 return ast.buildNumericLiteralTypeNode(`${value}`);
315 case 'boolean':
316 return ast.buildBooleanLiteralTypeNode(value);
317 case 'string':
318 return ast.buildStringLiteralTypeNode(value);
319 }
320 return ast.buildStringLiteralTypeNode(String(value));
321 }
322 generateUnionType(baseSchema, contents, mergeContent, path, terminate) {
323 const merged = [];
324 const children = contents.map((_, index) => {
325 const schema = this.normalizeContent(baseSchema, path + index.toString());
326 merged.push(utils.mergeSchema(schema.content, mergeContent));
327 return schema;
328 });
329 const allRef = merged.every((b) => !b);
330 const baseType = this.checkExistOtherType(mergeContent, baseSchema);
331 const result = ast.addOptionalInformation(ast.addComment(ast.buildUnionTypeNode(children, (schema, index) => {
332 const node = schema.id.isEmpty()
333 ? ast.addOptionalInformation(this.generateTypeProperty(schema, false), schema, false)
334 : ast.addOptionalInformation(ast.buildTypeReferenceNode(schema, this.currentSchema), schema, false);
335 if (baseType != null && !allRef && !merged[index]) {
336 return ast.buildIntersectionTypeNode([baseType, node], false);
337 }
338 return node;
339 }, terminate), baseSchema, false), baseSchema, terminate);
340 if (baseType != null && allRef) {
341 return ast.buildIntersectionTypeNode([baseType, result], terminate);
342 }
343 return result;
344 }
345 generateArrayTypeProperty(schema, terminate = true) {
346 const items = schema.content.items;
347 const minItems = schema.content.minItems;
348 const maxItems = schema.content.maxItems;
349 const getAdditionalItemNode = () => {
350 const additionalItems = schema.content.additionalItems
351 ? this.normalizeContent(schema, '/additionalItems')
352 : schema.content.additionalItems === false
353 ? false
354 : undefined;
355 return additionalItems === undefined
356 ? undefined
357 : additionalItems === false
358 ? false
359 : this.generateTypeProperty(additionalItems, false);
360 };
361 if (items == null) {
362 return ast.buildSimpleArrayNode(ast.buildAnyKeyword());
363 }
364 else if (!Array.isArray(items)) {
365 const subSchema = this.normalizeContent(schema, '/items');
366 const node = this.generateTypeProperty(subSchema, false);
367 if (minItems != null && maxItems != null && maxItems < minItems) {
368 return ast.buildNeverKeyword();
369 }
370 else if ((minItems === undefined || minItems === 0) &&
371 maxItems === undefined) {
372 return ast.buildSimpleArrayNode(ast.addOptionalInformation(node, subSchema, false));
373 }
374 else {
375 return ast.addOptionalInformation(ast.buildTupleTypeNode(node, minItems, maxItems), schema, terminate);
376 }
377 }
378 else if (items.length === 0 &&
379 (minItems === undefined || minItems === 0) &&
380 maxItems === undefined) {
381 const additionalItemsNode = getAdditionalItemNode();
382 return additionalItemsNode === false
383 ? ast.buildTupleTypeNode([], 0, 0, additionalItemsNode)
384 : ast.buildSimpleArrayNode(additionalItemsNode === undefined
385 ? ast.buildAnyKeyword()
386 : additionalItemsNode);
387 }
388 else if (minItems != null &&
389 maxItems != null &&
390 maxItems < minItems) {
391 return ast.buildNeverKeyword();
392 }
393 else {
394 const types = [];
395 for (let i = 0; i < items.length; i++) {
396 const type = this.normalizeContent(schema, '/items/' + i.toString());
397 if (type.id.isEmpty()) {
398 types.push(this.generateTypeProperty(type, false));
399 }
400 else {
401 types.push(ast.addOptionalInformation(ast.buildTypeReferenceNode(type, this.currentSchema), type, false));
402 }
403 }
404 const additionalItemsNode = getAdditionalItemNode();
405 return ast.addOptionalInformation(ast.buildTupleTypeNode(types, minItems, maxItems, additionalItemsNode), schema, terminate);
406 }
407 }
408 generateType(schema, terminate) {
409 const type = schema.content.type;
410 if (type == null) {
411 return ast.buildAnyKeyword();
412 }
413 else if (typeof type === 'string') {
414 return this.generateTypeName(schema, type, terminate);
415 }
416 else {
417 const types = utils.reduceTypes(type);
418 if (types.length <= 1) {
419 schema.content.type = types[0];
420 return this.generateType(schema, terminate);
421 }
422 else {
423 return ast.buildUnionTypeNode(types, (t) => {
424 return this.generateTypeName(schema, t, false);
425 }, terminate);
426 }
427 }
428 }
429 generateTypeName(schema, type, terminate) {
430 const tsType = utils.toTSType(type, schema.content);
431 if (tsType) {
432 if (tsType === ts.SyntaxKind.NullKeyword) {
433 return ast.buildNullKeyword();
434 }
435 else {
436 return ast.buildKeyword(tsType);
437 }
438 }
439 else if (type === 'object') {
440 const elements = this.generateProperties(schema);
441 if (elements.length > 0) {
442 return ast.buildTypeLiteralNode(elements);
443 }
444 else {
445 return ast.buildFreeFormObjectTypeLiteralNode();
446 }
447 }
448 else if (type === 'array') {
449 return this.generateArrayTypeProperty(schema, terminate);
450 }
451 else {
452 throw new Error('unknown type: ' + type);
453 }
454 }
455}
456exports.default = DtsGenerator;