import * as fs from "fs" import * as pathModule from "path" import { TSHost, TSProject, TSFile, ClassSpec, Kinds, InvokeSpec, MethodSpec, PropertySpec } from "./tsParser" import * as ts from "typescript" import * as glob from "glob" import * as Leaf from "leaf-ts" import { APISpec } from "../lib/route" import { format } from "./tsFormatter"; export class TSRouteParser { constructor(seeds: string[]) { let todos: string[] = [] for (let seed of seeds) { if (pathModule.extname(seed) == ".ts") { todos.push(seed) continue } let files = glob.sync(`${seed}/**/*.ts`) todos.push(...files) } this.project = new TSProject(todos) this.seeds = todos } seeds: string[] project: TSProject // TODO filter out those APISpec not included in the root seeds. parse(seeds: string[] = this.seeds) { let reg = /^.*APIService$/ let infos: APIServiceInfo[] = [] for (let seed of this.seeds) { let file = this.project.getFile(seed) if (!file) { throw new Error(`seed ${seed} not found`) } let clas = file.getClasses() for (let cla of clas) { if (reg.test(cla.name)) { let info = this.getRouteInfoRecursive(file, cla.name) info.seed = seed infos.push(info) } } } return infos } extractAPIImplementation(file: TSFile, name: string): { class: ClassSpec initializer: MethodSpec implementations: APIImplementation[] } { let cla = file.getClass(name) let result = { class: null, initializer: null, implementations: [] } if (!cla) { return result } result.class = cla if (!cla.methods.initialize) return result result.initializer = cla.methods.initialize let init = cla.methods.initialize.node let node = file.querySelect(init, "Block") let impls = [] ts.forEachChild(node, child => { if (child.kind !== Kinds.ExpressionStatement) return let call = file.querySelect(child, "CallExpression") as ts.CallExpression // not a invoke if (!call) return let spec = file.parseInvoke(call) if (!spec.invoke.access || !spec.invoke.access) return let accs = spec.invoke.access.accesses let last = accs[accs.length - 1] if (last != "api") return let name = spec.params[0] if (name.literalType != "string") { console.error(`Invoke api without providing name ${file.source.fileName}: ${name.node.pos} `) return } impls.push({ spec, className: cla.name, api: name.literalValue, start: child.getFullStart(), width: child.getFullWidth(), parent: cla.methods.initialize }) //console.log(spec.invoke, spec.params.length) }) result.implementations = impls return result } getRouteInfoRecursive(file: TSFile, name: string): APIServiceInfo { // 1. look up class with specific API names recursively look up spec in it's base class // 2. look up specs incurrent file and over write let info: APIServiceInfo = { className: null, name: null, routes: {}, prefix: "", class: null, initializer: null, implementations: [], parent: null, seed: file.source.fileName } let impl = this.extractAPIImplementation(file, name) let cla = impl.class if (!cla) return null info.class = cla if (cla.base && cla.base.class) { let file = new TSFile(this.project, cla.base.class.node.getSourceFile()) let base = this.getRouteInfoRecursive(file, cla.base.name) if (base) { for (let name in base.routes) { info.routes[name] = base.routes[name] } info.name = base.name || info.name info.prefix = base.prefix info.parent = base info.implementations.push(...base.implementations) } } info.implementations.push(...impl.implementations) if (impl.initializer) { info.initializer = impl.initializer } info.className = cla.name let specName = info.className + "Spec" let nss = file.getNamespaces() let ns = nss.find(ns => ns.name == specName) if (!ns) return info let nameVar = ns.block.variables.name info.name = nameVar && nameVar.value && nameVar.value.literalValue || info.name let prefixVar = ns.block.variables.prefix if (prefixVar && prefixVar.value && prefixVar.value.literalType == "string") { info.prefix = prefixVar.value.literalValue } if (!info.name) { } let canonicalName = Leaf.Util.slugToCamel(info.name.replace("api.", "").replace(/\./, "-")) let apiVar = ns.block.variables.API ts.forEachChild(apiVar.value.node, child => { let id = file.querySelect(child, "Identifier".split(".")) as ts.Identifier let apiSpecClaNode = file.querySelect(child, "NewExpression.ClassExpression".split(".")) if (!apiSpecClaNode) return let apiSpecCla = file.parseClass(apiSpecClaNode as ts.ClassDeclaration) let methodProp = apiSpecCla.properties.method let pathProp = apiSpecCla.properties.path let returnProp = apiSpecCla.properties.return let bodyProp = apiSpecCla.properties.body let queryProp = apiSpecCla.properties.query let paramsProp = apiSpecCla.properties.params if (returnProp && !returnProp.type) { file.inspectKind(returnProp.node) //console.error(returnProp.type.node.getText()) } info.routes[id.text] = { name: id.text, path: pathProp && pathProp.value && pathProp.value.literalValue || canonicalName + "/" + id.text, method: methodProp && methodProp.value && methodProp.value.literalValue || methodProp && methodProp.type && JSON.parse(methodProp.type.literal) || "POST", returnTypeString: this.typeFromProp(returnProp) || null, bodyTypeString: this.typeFromProp(bodyProp) || null, queryTypeString: this.typeFromProp(queryProp) || null, paramsTypeString: this.typeFromProp(paramsProp) || null, } }) return info } private typeFromProp(prop: PropertySpec) { if (!prop) return null if (prop.type) { return prop.type.literal || prop.type.node.getText() } if (prop.value) { return prop.value.literal } } } export class TSRouteFile { constructor(public readonly file: TSFile) { } isRouteFile() { } } export type RouteInfo = { name: string path: string method: string returnTypeString: string paramsTypeString: string queryTypeString: string bodyTypeString: string } export type APIServiceInfo = { name: string seed?: string className: string prefix: string routes: { [name: string]: RouteInfo } class: ClassSpec initializer: MethodSpec implementations: APIImplementation[] parent: APIServiceInfo } export type APIImplementation = { spec: InvokeSpec className: string api: string start: number width: number parent: MethodSpec } export class RouteAPIGenerator { constructor(public readonly services: APIServiceInfo[]) { } build() { let header = `import * as Leaf from "leaf-ts" ` let codes = this.services.map(info => this.buildAPIService(info)) codes.push(this.buildAPIBundle(this.services)) let code = codes.join("\n") return format(header + code) } private buildAPIBundle(services: APIServiceInfo[]) { let apis = services.map(info => { if (!info.name) { console.error("Invalid API INFO", info) throw new Error("Invalid API Info") } let name = Leaf.Util.slugToCamel(info.name.replace("api.", "").replace(/\./g, "-")) return `readonly ${name} = new (Generate${info.className} ()) ()` }).join("\n") return ` export class APIService extends Leaf.Service { readonly name = "APIService" ${ apis} } export function GenerateAPI() { return new APIService() } ` } private buildAPIService(info: APIServiceInfo) { let apis = Object.keys(info.routes).map(key => { let api = info.routes[key] let requestTypes: string[] = [] if (api.paramsTypeString) { requestTypes.push(api.paramsTypeString) } if (api.queryTypeString) { requestTypes.push(api.queryTypeString) } if (api.bodyTypeString) { requestTypes.push(api.bodyTypeString) } requestTypes = requestTypes.filter(item => !!item) return ` ${ key} = factory.createAPIFunction < ${requestTypes.join("&") || "{}"} , ${api.returnTypeString || "null"}> ({ method: "${api.method}", path: "${api.path}" }) ` }) let result = ` export function Generate${ info.className} {}) = new (...args: any[]) => {}>(factory: Leaf.APIFactory = new Leaf.APIFactory({ prefix: "${info.prefix}", bodyType: "json", serializer: Leaf.Serializer.getDefault() }), Base: T = class { } as any){ return class extends Base { public factory = factory ${ apis.join("\n")} } }` return result } } export class RouteAPISyncer { constructor(public readonly parser: TSRouteParser, public readonly info: APIServiceInfo) { } merge(option: { path: string purge?: boolean guess?: boolean }) { let file = this.parser.project.getFile(option.path) if (!file) { throw new Error("File not exists") } let origContent = file.source.getFullText() let replacer = new Replacer(origContent) if (!this.info.class) { return format(replacer.add(origContent.length, this.buildClass()).apply()) } if (!this.info.initializer) { let last = this.info.class.children[this.info.class.children.length - 1] let offset = last.getFullText().lastIndexOf("}") - 1 let start = last.getFullStart() + offset return format(replacer.add(start, "\n" + this.buildInitializer()).apply()) } let impls = this.info.implementations let diff = Leaf.Util.arrayDiffTyped(this.info.implementations, Object.keys(this.info.routes), (a, b) => { if (a.api == b) return true return false }) if (diff.left.length == 0 && diff.right.length == 0) return format(file.source.getFullText()) if (impls.length == 0) { let start = this.info.initializer.block.node.getFullStart() let at = this.info.initializer.block.node.getFullText().lastIndexOf("}") - 1 replacer.add(start + at, this.buildDefaultImplementations(Object.keys(this.info.routes).map(key => this.info.routes[key]))) return format(replacer.apply()) } let block = this.info.initializer.block.node let start = block.getFullText().lastIndexOf("}") + block.getFullStart() if (diff.left.length == diff.right.length && diff.right && option.guess) { for (let item of diff.left) { replacer.delete(item.start, item.width) } } let content = this.buildDefaultImplementations(diff.right.map(item => this.info.routes[item])) replacer.add(start, content) return format(replacer.apply()) } buildDefaultImplementations(infos: RouteInfo[]) { return infos.map(info => ` this.api("${info.name}", ctx => { ctx.error(new Error("API ${info.name} not implemented")) }) `).join("\n") } buildFile(routePath: string, path: string) { let routeSpecPath = pathModule.relative(pathModule.dirname(path), routePath).replace(".ts", "") return format(`import * as RouteSpec from "${routeSpecPath}" import * as Leaf from "leaf-ts" ${ this.buildClass()} `) } buildClass() { return ` export class ${this.info.className} extends RouteSpec.${this.info.className} { ${ this.buildInitializer()} } ` } buildInitializer(apis?: RouteInfo[]) { apis = apis || Object.keys(this.info.routes).map(key => { if (this.info.implementations.find(impl => impl.api == key)) return null return this.info.routes[key] }).filter(item => !!item) let codes = this.buildDefaultImplementations(apis) return `initialize(){ super.initialize() ${ codes} } ` } } class Replacer { constructor(public readonly content: string) { } todos: { start: number width: number replacement: string }[] = [] add(at: number, content: string) { this.todos.push({ start: at, width: 0, replacement: content }) return this } delete(at: number, width: number) { this.todos.push({ start: at, width, replacement: "" }) return this } apply() { let content = this.content let prev this.todos.sort((a, b) => a.start - b.start) for (let todo of this.todos) { if (!prev) { prev = todo continue } if (todo.start < prev.start + prev.width) throw new Error("Invalid replacer build") } let adjustment = 0 for (let todo of this.todos) { let start = todo.start + adjustment let end = start + todo.width content = content.slice(0, start) + todo.replacement + content.slice(end) adjustment += todo.replacement.length - todo.width } return content } }