|
| 1 | +import * as ts from 'typescript'; |
| 2 | +import * as _ from 'lodash'; |
| 3 | +import * as fs from 'fs'; |
| 4 | +import * as path from 'path'; |
| 5 | +import * as collector from './metadata/index'; |
| 6 | +import * as printers from './printers/index'; |
| 7 | +import { ActionInterface } from './action-interface'; |
| 8 | + |
| 9 | +export interface ActionMetadata { |
| 10 | + name: string; |
| 11 | + type: string; |
| 12 | + properties: { name: string; optional: boolean }[]; |
| 13 | +} |
| 14 | + |
| 15 | +export function collectMetadata( |
| 16 | + fileName: string, |
| 17 | + sourceFile: ts.SourceFile |
| 18 | +): ts.Node[] | undefined { |
| 19 | + const interfaces = sourceFile.statements |
| 20 | + .filter(ts.isInterfaceDeclaration) |
| 21 | + .filter(collector.isExported) |
| 22 | + .filter(collector.isActionDescendent) |
| 23 | + .filter(m => !!collector.getType(m)) |
| 24 | + .map((enterface): ActionInterface => ({ |
| 25 | + name: enterface.name.getText(), |
| 26 | + actionType: _.trim( |
| 27 | + collector.getType(enterface)!.literal.getFullText(), |
| 28 | + ' \'"`' |
| 29 | + ), |
| 30 | + properties: [ |
| 31 | + ...collector.getRequiredProperties(collector.getProperties(enterface)), |
| 32 | + ...collector.getOptionalProperties(collector.getProperties(enterface)), |
| 33 | + ], |
| 34 | + })); |
| 35 | + |
| 36 | + if (interfaces.length === 0) { |
| 37 | + undefined; |
| 38 | + } |
| 39 | + |
| 40 | + return [ |
| 41 | + printers.printImportDeclaration(fileName, interfaces), |
| 42 | + printers.printEnumDeclaration(interfaces), |
| 43 | + printers.printTypeUnionDeclaration(interfaces), |
| 44 | + printers.printTypeDictionaryDeclaration(interfaces), |
| 45 | + ...interfaces.map(action => printers.printActionFactoryDeclaration(action)), |
| 46 | + ]; |
| 47 | +} |
| 48 | + |
| 49 | +export function printActionFactory(ast: ts.Node[]) { |
| 50 | + const resultFile = ts.createSourceFile( |
| 51 | + '', |
| 52 | + '', |
| 53 | + ts.ScriptTarget.ES2015, |
| 54 | + false, |
| 55 | + ts.ScriptKind.TS |
| 56 | + ); |
| 57 | + |
| 58 | + const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed }); |
| 59 | + |
| 60 | + return ast |
| 61 | + .map(statement => |
| 62 | + printer.printNode(ts.EmitHint.Unspecified, statement, resultFile) |
| 63 | + ) |
| 64 | + .join('\n\n'); |
| 65 | +} |
0 commit comments