@synvert-hq/node-mutation
v1.17.3
Published
ast node mutation apis
Downloads
49
Readme
NodeMutation
NodeMutation provides a set of APIs to rewrite node source code.
Table of Contents
Installation
Install NodeMutation using npm:
npm install --save @synvert-hq/node-mutation
Or yarn;
yarn add @synvert-hq/node-mutation
Usage
- initialize the NodeMutation instance:
import { Node } from "typescript"
mutation = new NodeMutation<Node>(filePath: string, source: string, { adapter: "typescript" | "espree" | "gonzales-pe" })
- call the rewrite apis:
// append the code to the current node.
mutation.append(node: Node, code: string)
// delete source code of the child ast node
mutation.delete(node: Node, selectors: string | string[], options: DeleteOptions)
// insert code to the ast node.
mutation.insert(node: Node, code: string, options: InsertOptions)
// prepend code to the ast node.
mutation.prepend(node: Node, code: string)
// remove source code of the ast node
mutation.remove(node: Node, options: RemoveOptions)
// replace child node of the ast node with new code
mutation.replace(node: Node, selectors: string | string[], options: ReplaceOptions)
// replace the ast node with new code
mutation.replaceWith(node: Node, code: string)
// no operation
mutation.noop(node: Node)
// group actions
mutation.group(() => {
mutation.delete(node: Node, selectors: string | string[], options: DeleteOptions)
mutation.insert(node: Node, code: string, options: InsertOptions)
})
- process actions and write the new source code to file:
mutation.process()
Evaluated Value
NodeMutation supports to evaluate the value of the node, and use the evaluated value to rewrite the source code.
source = 'class Synvert {}'
node = espree.parse(source)
mutation.replace node, '{{id}}', with: 'Foobar'
source # class Foobar {}
See more in TypescriptAdapter, SyntaxTreeAdapter, and GonzalesPeAdapter
Configuration
adapter
Different parsers, like typescript and espree, will generate different AST nodes, to make NodeMutation work for them all, we define an Adapter interface, if you implement the Adapter interface, you can set it as NodeMutation's adapter.
It provides 3 adapters:
TypescriptAdapter
EspreeAdapter
GonzalesPeAdapter
NodeMutation.configure({ adapter: new EspreeAdapter() }); // default is TypescriptAdapter
strategy
It provides 2 strategies to handle conflicts when processing actions:
Strategy.KEEP_RUNNING
: keep running and ignore the conflict action.Strategy.THROW_ERROR
: throw error when conflict action is found.
NodeMutation.configure({ strategy: Strategy.KEEP_RUNNING }); // default is Strategy.THROW_ERROR
tabWidth
NodeMutation.configure({ tabWidth: 4 }); // default is 2
Contributing Guide
Fork and clone the repo.
Run
npm install
to install dependencies.Run
npm run test
ornpm run watch:test
to run tests.Make some changes and make tests all passed.
Push the changes to the repo.