i'm trying to merge two typescript AST's created from strings.
I create both with this method
const sourceFile = ts.createSourceFile(
"file.ts", // filePath
"function myFunction() {}", // fileText
ts.ScriptTarget.Latest, // scriptTarget
true // setParentNodes -- sets the `parent` property
);
However, this will create node of type ts.SourceFile, and if i try to merge these two ASTs i get error when trying to print the final sourceFile: "Unhandled SyntaxKind: SourceFile."
How should i properly merge two ASTs?
Thanks
EDIT: Here is full working code example. When i run this it throws me directly into debugger (in browser) with aforementionde error.
I also tried to purposefully extract the ArrowFunction node (in ast2 it is wrapped in SourceFile and ExpressionStatement), then the program runs without error, but completely changes the inner template literal into invalid code.
const createAST = (str: string) =>
ts.createSourceFile(
"file.ts", // filePath
str, // fileText
ts.ScriptTarget.Latest, // scriptTarget
true // setParentNodes -- sets the `parent` property
)
const template1 = `const arr = fields.map(() => {})`
const template2 = `(field) => <Toolbar id={\`\${field.id}.\${field.name}\`} />`
const ast1 = createAST(template1)
const ast2 = createAST(template2)
const replaceTransformer = <T extends ts.Node>(
newNode: T
): ts.TransformerFactory<T> => {
return context => {
const visit: ts.Visitor = node => {
if (ts.isArrowFunction(node)) return newNode
return ts.visitEachChild(node, child => visit(child), context)
}
return node => ts.visitNode(node, visit)
}
}
if (!ast1 || !ast2) return console.log("something went wrong")
const result = ts.transform(ast1, [replaceTransformer(ast2)])
const res = result.transformed[0]
const printer = ts.createPrinter()
const string = printer.printFile(res)
console.log(string)