@babel/traverse
- Version 8.1.3
- Published
- 365 kB
- 7 dependencies
- MIT license
Install
npm i @babel/traverseyarn add @babel/traversepnpm add @babel/traverseOverview
The Babel Traverse module maintains the overall tree state, and is responsible for replacing, removing, and adding nodes
Index
Variables
Functions
- addComment()
- addComments()
- arrowFunctionToExpression()
- baseTypeStrictlyMatches()
- canHaveVariableDeclarationOrExpression()
- canSwapBetweenExpressionAndStatement()
- clear()
- clearPath()
- clearScope()
- couldBeBaseType()
- ensureBlock()
- ensureFunctionName()
- environmentVisitor()
- evaluate()
- evaluateTruthy()
- explode$1()
- find()
- findParent()
- get()
- getAllNextSiblings()
- getAllPrevSiblings()
- getAncestry()
- getAssignmentIdentifiers()
- getBindingIdentifierPaths()
- getBindingIdentifiers()
- getCachedPaths()
- getCompletionRecords()
- getDeepestCommonAncestorFrom()
- getEarliestCommonAncestorFrom()
- getFunctionParent()
- getNextSibling()
- getOpposite()
- getOrCreateCachedPaths()
- getOuterBindingIdentifierPaths()
- getOuterBindingIdentifiers()
- getPrevSibling()
- getSibling()
- getSource()
- getStatementParent()
- getTypeAnnotation()
- insertAfter()
- insertBefore()
- inType()
- isAncestor()
- isBaseType()
- isCompletionRecord()
- isConstantExpression()
- isDenylisted()
- isDescendant()
- isExplodedVisitor()
- isGenericType()
- isInStrictMode()
- isNodeType()
- isStatementOrBlock()
- isStatic()
- matchesPattern()
- merge()
- pushContainer()
- referencesImport()
- remove()
- replaceExpressionWithStatements()
- replaceInline()
- replaceWith()
- replaceWithMultiple()
- replaceWithSourceString()
- requeue()
- requeueComputedKeyAndDecorators()
- resolve()
- setContext()
- shareCommentsWithSiblings()
- skip()
- skipKey()
- splitExportDeclaration()
- stop()
- traverse()
- unshiftContainer()
- unwrapFunctionEnvironment()
- verify$1()
- willIMaybeExecuteBefore()
Classes
Scope
- addGlobal()
- bindingIdentifierEquals()
- bindings
- block
- checkBlockScopedCollisions()
- contextVariables
- crawl()
- crawling
- data
- dump()
- generateDeclaredUidIdentifier()
- generateUid()
- generateUidBasedOnNode()
- generateUidIdentifier()
- generateUidIdentifierBasedOnNode()
- getAllBindings()
- getBinding()
- getBindingIdentifier()
- getBlockParent()
- getData()
- getFunctionParent()
- getLabel()
- getOwnBinding()
- getOwnBindingIdentifier()
- getPatternParent()
- getProgramParent()
- globals
- globals
- hasBinding()
- hasGlobal()
- hasLabel()
- hasOwnBinding()
- hasReference()
- hasUid()
- hoistVariables()
- init()
- inited
- isPure()
- isStatic()
- labels
- maybeGenerateMemoised()
- moveBindingTo()
- parent
- parentHasBinding()
- path
- push()
- references
- referencesSet
- registerBinding()
- registerConstantViolation()
- registerDeclaration()
- registerLabel()
- removeBinding()
- removeData()
- removeOwnBinding()
- rename()
- setData()
- uid
- uids
- uidsSet
Interfaces
Type Aliases
Namespaces
Variables
variable methods
const methods: { findParent: typeof findParent; find: typeof find; getFunctionParent: typeof getFunctionParent; getStatementParent: typeof getStatementParent; getEarliestCommonAncestorFrom: typeof getEarliestCommonAncestorFrom; getDeepestCommonAncestorFrom: typeof getDeepestCommonAncestorFrom; getAncestry: typeof getAncestry; isAncestor: typeof isAncestor; isDescendant: typeof isDescendant; inType: typeof inType; getTypeAnnotation: typeof getTypeAnnotation; isBaseType: typeof isBaseType; couldBeBaseType: typeof couldBeBaseType; baseTypeStrictlyMatches: typeof baseTypeStrictlyMatches; isGenericType: typeof isGenericType; replaceWithMultiple: typeof replaceWithMultiple; replaceWithSourceString: typeof replaceWithSourceString; replaceWith: typeof replaceWith; replaceExpressionWithStatements: typeof replaceExpressionWithStatements; replaceInline: typeof replaceInline; evaluateTruthy: typeof evaluateTruthy; evaluate: typeof evaluate; ensureBlock: typeof ensureBlock; unwrapFunctionEnvironment: typeof unwrapFunctionEnvironment; arrowFunctionToExpression: typeof arrowFunctionToExpression; splitExportDeclaration: typeof splitExportDeclaration; ensureFunctionName: typeof ensureFunctionName; matchesPattern: typeof matchesPattern; isStatic: typeof isStatic; isNodeType: typeof isNodeType; canHaveVariableDeclarationOrExpression: typeof canHaveVariableDeclarationOrExpression; canSwapBetweenExpressionAndStatement: typeof canSwapBetweenExpressionAndStatement; isCompletionRecord: typeof isCompletionRecord; isStatementOrBlock: typeof isStatementOrBlock; referencesImport: typeof referencesImport; getSource: typeof getSource; willIMaybeExecuteBefore: typeof willIMaybeExecuteBefore; _guessExecutionStatusRelativeTo: typeof _guessExecutionStatusRelativeTo; resolve: typeof resolve; isConstantExpression: typeof isConstantExpression; isInStrictMode: typeof isInStrictMode; isDenylisted: typeof isDenylisted; skip: typeof skip; skipKey: typeof skipKey; stop: typeof stop; setContext: typeof setContext; requeue: typeof requeue; requeueComputedKeyAndDecorators: typeof requeueComputedKeyAndDecorators; remove: typeof remove; insertBefore: typeof insertBefore; insertAfter: typeof insertAfter; unshiftContainer: typeof unshiftContainer; pushContainer: typeof pushContainer; getOpposite: typeof getOpposite; getCompletionRecords: typeof getCompletionRecords; getSibling: typeof getSibling; getPrevSibling: typeof getPrevSibling; getNextSibling: typeof getNextSibling; getAllNextSiblings: typeof getAllNextSiblings; getAllPrevSiblings: typeof getAllPrevSiblings; get: typeof get; getAssignmentIdentifiers: typeof getAssignmentIdentifiers; getBindingIdentifiers: typeof getBindingIdentifiers; getOuterBindingIdentifiers: typeof getOuterBindingIdentifiers; getBindingIdentifierPaths: typeof getBindingIdentifierPaths; getOuterBindingIdentifierPaths: typeof getOuterBindingIdentifierPaths; shareCommentsWithSiblings: typeof shareCommentsWithSiblings; addComment: typeof addComment; addComments: typeof addComments;};variable NodePath
const NodePath: { new (hub: HubInterface | undefined, parent: t.Node): { parent: t.Node; hub: HubInterface; data: Record<string | symbol, unknown> | null; context: TraversalContext; scope: Scope; contexts: TraversalContext[]; state: any; opts: TraverseOptions & ExplodedVisitor; _traverseFlags: number; removed: boolean; shouldStop: boolean; shouldSkip: boolean; skipKeys: Record<string, boolean> | null; parentPath: NodePath_Final | null; container: t.Node | t.Node[] | null; listKey: string | null | undefined; key: string | number | null; node: t.Node | null; type: t.Node['type'] | null; _store: Map<t.Node, NodePath_Final> | null; getScope(this: NodePath<t.Node, any, any>, scope: Scope): Scope; setData<T>(key: string | symbol, val: T): T; getData(key: string | symbol, def?: any): any; hasNode(): boolean; buildCodeFrameError(msg: string, Error?: new () => Error): Error; traverse<S, T extends object>( this: NodePath<t.Node, any, any>, visitor: { [P in keyof T]: VisitorProp<S, P & string> }, state: S ): void; traverse<T extends object>( this: NodePath<t.Node, any, any>, visitor: { [P in keyof T]: VisitorProp<any, P & string> } ): void; traverse<S>( this: NodePath<t.Node, any, any>, visitor: TraverseOptions & Visitor<S>, state: S ): void; traverse( this: NodePath<t.Node, any, any>, visitor: TraverseOptions & Visitor<any> ): void; set(key: string, node: any): void; getPathLocation(this: NodePath_Final<t.Node | null>): string; debug(this: NodePath_Final<t.Node | null>, message: string): void; toString(): string; inList: boolean; readonly parentKey: string; }; get({ hub, parentPath, parent, container, listKey, key, }: { hub?: HubInterface; parentPath: NodePath_Final | null | undefined; parent: t.Node; container: t.Node | t.Node[]; listKey?: string | null; key: string | number; }): NodePath<t.Node, any, any>;};variable pathsCache
let pathsCache: WeakMap<Node, Map<Node, NodePath<t.Node, any, any>>>;variable scope
let scope: WeakMap<Node, Scope>;Functions
function addComment
addComment: ( this: NodePath<t.Node, any, any>, type: t.CommentTypeShorthand, content: string, line?: boolean) => void;function addComments
addComments: ( this: NodePath<t.Node, any, any>, type: t.CommentTypeShorthand, comments: t.Comment[]) => void;Give node
commentsof the specifiedtype.
function arrowFunctionToExpression
arrowFunctionToExpression: ( this: NodePath_Final<t.ArrowFunctionExpression>, { allowInsertArrow, allowInsertArrowWithRest, noNewArrows, }?: { allowInsertArrow?: boolean; allowInsertArrowWithRest?: boolean; noNewArrows?: boolean; }) => NodePath_Final< Exclude<t.Function, t.Method | t.ArrowFunctionExpression> | t.CallExpression>;Convert a given arrow function into a normal ES5 function expression.
function baseTypeStrictlyMatches
baseTypeStrictlyMatches: ( this: NodePath<t.Node, any, any>, rightArg: NodePath<t.Node, any, any>) => boolean;function canHaveVariableDeclarationOrExpression
canHaveVariableDeclarationOrExpression: ( this: NodePath_Final<t.Node | null>) => boolean;This checks whether or not we're in one of the following positions:
for (KEY in right); for (KEY;;);
This is because these spots allow VariableDeclarations AND normal expressions so we need to tell the path replacement that it's ok to replace this with an expression.
function canSwapBetweenExpressionAndStatement
canSwapBetweenExpressionAndStatement: ( this: NodePath_Final<t.Node | null>, replacement: t.Node) => boolean;This checks whether we are swapping an arrow function's body between an expression and a block statement (or vice versa).
This is because arrow functions may implicitly return an expression, which is the same as containing a block statement.
function clear
clear: () => void;function clearPath
clearPath: () => void;function clearScope
clearScope: () => void;function couldBeBaseType
couldBeBaseType: (this: NodePath<t.Node, any, any>, name: string) => boolean;function ensureBlock
ensureBlock: ( this: NodePath_Final< t.Loop | t.WithStatement | t.Function | t.LabeledStatement | t.CatchClause >) => void;function ensureFunctionName
ensureFunctionName: <N extends unknown>( this: NodePath_Final<N>, supportUnicodeId: boolean) => null | NodePath_Final<N>;function environmentVisitor
environmentVisitor: <S>(visitor: Visitor<S>) => ExplodedVisitor<S>;function evaluate
evaluate: (this: NodePath<t.Node, any, any>) => { confident: boolean; value: any; deopt: NodePath_Final | null;};Walk the input
nodeand statically evaluate it.Returns an object in the form
{ confident, value, deopt }.confidentindicates whether or not we had to drop out of evaluating the expression because of hitting an unknown node that we couldn't confidently find the value of, in which casedeoptis the path of said node.Example:
t.evaluate(parse("5 + 5")) // { confident: true, value: 10 } t.evaluate(parse("!true")) // { confident: true, value: false } t.evaluate(parse("foo + foo")) // { confident: false, value: undefined, deopt: NodePath }
function evaluateTruthy
evaluateTruthy: (this: NodePath<t.Node, any, any>) => boolean | undefined;Walk the input
nodeand statically evaluate if it's truthy.Returning
truewhen we're sure that the expression will evaluate to a truthy value,falseif we're sure that it will evaluate to a falsy value andundefinedif we aren't sure. Because of this please do not rely on coercion when using this method and check with === if it's false.For example do:
if (t.evaluateTruthy(node) === false) falsyLogic();
**AND NOT**
if (!t.evaluateTruthy(node)) falsyLogic();
function explode$1
explode$1: { <S, T extends object>(visitor: { [P in keyof T]: VisitorProp<S, P & string>; }): ExplodedVisitor<S>; <S>(visitor: Visitor<S>): ExplodedVisitor<S>;};explode() will take a visitor object with all of the various shorthands that we support, and validates & normalizes it into a common format, ready to be used in traversal
The various shorthands are: *
Identifier() { ... }->Identifier: { enter() { ... } }*"Identifier|NumericLiteral": { ... }->Identifier: { ... }, NumericLiteral: { ... }* Aliases in@babel/types: e.g.Property: { ... }->ObjectProperty: { ... }, ClassProperty: { ... }Other normalizations are: * Visitors of virtual types are wrapped, so that they are only visited when their dynamic check passes *enterandexitfunctions are wrapped in arrays, to ease merging of visitors
function find
find: ( this: NodePath<t.Node, any, any>, callback: (path: NodePath<t.Node, any, any>) => boolean) => NodePath_Final | null;Starting at current
NodePathand going up the tree, return the firstNodePaththat causes the providedcallbackto return a truthy value, ornullif thecallbacknever returns a truthy value.
function findParent
findParent: ( this: NodePath_Final<t.Node | null>, callback: (path: NodePath<t.Node, any, any>) => boolean) => NodePath_Final | null;Starting at the parent path of the current
NodePathand going up the tree, return the firstNodePaththat causes the providedcallbackto return a truthy value, ornullif thecallbacknever returns a truthy value.
function get
get: { <T extends NodePath<t.Node, any, any>, K extends keyof T['node']>( this: T, key: K, context?: true | TraversalContext ): T extends any ? T['node'][K] extends (infer U extends unknown)[] ? NodePath_Final<U>[] : T['node'][K] extends infer U extends unknown ? NodePath_Final<U> : never : never; <T extends NodePath<t.Node, any, any>, K extends string>( this: T, key: K, context?: true | TraversalContext<unknown> ): string extends K ? NodePath<any, any, any> | NodePath<any, any, any>[] : T extends any ? ToNodePath<Trav<T['node'], Split<K>>> : never; ( this: NodePath<t.Node, any, any>, key: string, context?: true | TraversalContext<unknown> ): NodePath<any, any, any> | NodePath<any, any, any>[];};function getAllNextSiblings
getAllNextSiblings: ( this: NodePath_Final<t.Node | null>) => NodePath_Final<t.Node | null>[];function getAllPrevSiblings
getAllPrevSiblings: ( this: NodePath_Final<t.Node | null>) => NodePath_Final<t.Node | null>[];function getAncestry
getAncestry: (this: NodePath<t.Node, any, any>) => NodePath_Final[];Build an array of node paths containing the entire ancestry of the current node path.
NOTE: The current node path is included in this.
function getAssignmentIdentifiers
getAssignmentIdentifiers: ( this: NodePath<t.Node, any, any>) => Record<string, t.Identifier>;function getBindingIdentifierPaths
getBindingIdentifierPaths: { (duplicates: true, outerOnly?: boolean): Record< string, NodePath_Final<t.Identifier>[] >; (duplicates: false, outerOnly?: boolean): Record< string, NodePath<t.Identifier, any, any> >; (duplicates?: boolean, outerOnly?: boolean): Record< string, NodePath<t.Identifier, any, any> | NodePath<t.Identifier, any, any>[] >;};function getBindingIdentifiers
getBindingIdentifiers: { (duplicates: true): Record<string, t.Identifier[]>; (duplicates?: false): Record<string, t.Identifier>; (duplicates: boolean): Record<string, any>;};function getCachedPaths
getCachedPaths: ( path: NodePath_Final<Node | null>) => Map<Node, NodePath_Final> | null | undefined;function getCompletionRecords
getCompletionRecords: ( this: NodePath<t.Node, any, any>, shouldPreserveBreak?: boolean) => NodePath_Final[];Retrieve the completion records of a given path. Note: to ensure proper support on
breakstatement, this method will manipulate the AST around the break statement. Do not call the method twice for the same path.Parameter this
Parameter shouldPreserveBreak
Whether the
breakstatement should be preserved.Returns
{NodePath[]} Completion records
function getDeepestCommonAncestorFrom
getDeepestCommonAncestorFrom: ( this: NodePath<t.Node, any, any>, paths: NodePath_Final[], filter?: ( deepest: NodePath<t.Node, any, any>, i: number, ancestries: NodePath_Final[][] ) => NodePath<t.Node, any, any>) => NodePath<t.Node, any, any>;Get the earliest path in the tree where the provided
pathsintersect.TODO: Possible optimisation target.
function getEarliestCommonAncestorFrom
getEarliestCommonAncestorFrom: ( this: NodePath<t.Node, any, any>, paths: NodePath_Final[]) => NodePath<t.Node, any, any>;Get the deepest common ancestor and then from it, get the earliest relationship path to that ancestor.
Earliest is defined as being "before" all the other nodes in terms of list container position and visiting key.
function getFunctionParent
getFunctionParent: ( this: NodePath_Final<t.Node | null>) => NodePath_Final<t.Function> | null;Get the parent function of the current path.
function getNextSibling
getNextSibling: ( this: NodePath_Final<t.Node | null>) => NodePath_Final<t.Node | null>;function getOpposite
getOpposite: ( this: NodePath<t.Node, any, any>) => NodePath_Final<t.Node | null> | null;function getOrCreateCachedPaths
getOrCreateCachedPaths: ( node: Node, parentPath?: NodePath_Final | null) => Map<any, any>;function getOuterBindingIdentifierPaths
getOuterBindingIdentifierPaths: { (duplicates: true): Record<string, NodePath_Final<t.Identifier>[]>; (duplicates?: false): Record<string, NodePath<t.Identifier, any, any>>; (duplicates?: boolean): Record< string, NodePath<t.Identifier, any, any> | NodePath<t.Identifier, any, any>[] >;};function getOuterBindingIdentifiers
getOuterBindingIdentifiers: { (duplicates: true): Record<string, t.Identifier[]>; (duplicates?: false): Record<string, t.Identifier>; (duplicates: boolean): Record<string, any>;};function getPrevSibling
getPrevSibling: ( this: NodePath_Final<t.Node | null>) => NodePath_Final<t.Node | null>;function getSibling
getSibling: ( this: NodePath_Final<t.Node | null>, key: string | number) => NodePath_Final<t.Node | null>;function getSource
getSource: (this: NodePath<t.Node, any, any>) => string;Get the source code associated with this node.
function getStatementParent
getStatementParent: ( this: NodePath_Final<t.Node | null>) => NodePath_Final<t.Statement>;Walk up the tree until we hit a parent node path in a list.
function getTypeAnnotation
getTypeAnnotation: ( this: NodePath_Final<t.Node | null>) => t.FlowType | t.TSType;Infer the type of the current
NodePath.
function insertAfter
insertAfter: <Nodes extends unknown>( this: NodePath_Final<t.Node | null>, nodes_: Nodes) => NodePaths<Nodes>;Insert the provided nodes after the current one. When inserting nodes after an expression, ensure that the completion record is correct by pushing the current node.
function insertBefore
insertBefore: <Nodes extends unknown>( this: NodePath_Final<t.Node | null>, nodes_: Nodes) => NodePaths<Nodes>;Insert the provided nodes before the current one.
function inType
inType: ( this: NodePath<t.Node, any, any>, ...candidateTypes: string[]) => boolean;function isAncestor
isAncestor: ( this: NodePath<t.Node, any, any>, maybeDescendant: NodePath<t.Node, any, any>) => boolean;A helper to find if
thispath is an ancestor ofParameter maybeDescendant
function isBaseType
isBaseType: ( this: NodePath<t.Node, any, any>, baseName: string, soft?: boolean) => boolean;function isCompletionRecord
isCompletionRecord: ( this: NodePath<t.Node, any, any>, allowInsideFunction?: boolean) => boolean;Check whether the current path references a completion record
function isConstantExpression
isConstantExpression: (this: NodePath_Final<t.Node | null>) => boolean;function isDenylisted
isDenylisted: (this: NodePath<t.Node, any, any>) => boolean;function isDescendant
isDescendant: ( this: NodePath<t.Node, any, any>, maybeAncestor: NodePath<t.Node, any, any>) => boolean;A helper to find if
thispath is a descendant ofParameter maybeAncestor
function isExplodedVisitor
isExplodedVisitor: ( visitor: Visitor<any>) => visitor is ExplodedVisitor<unknown>;function isGenericType
isGenericType: ( this: NodePath<t.Node, any, any>, genericName: string) => boolean;function isInStrictMode
isInStrictMode: (this: NodePath_Final<t.Node | null>) => boolean;function isNodeType
isNodeType: (this: NodePath_Final<t.Node | null>, type: string) => boolean;Check the type against our stored internal type of the node. This is handy when a node has been removed yet we still internally know the type and need it to calculate node replacement.
function isStatementOrBlock
isStatementOrBlock: (this: NodePath_Final<t.Node | null>) => boolean;Check whether or not the current
keyallows either a single statement or block statement so we can explode it if necessary.
function isStatic
isStatic: (this: NodePath<t.Node, any, any>) => boolean;function matchesPattern
matchesPattern: ( this: NodePath<t.Node, any, any>, pattern: string, allowPartial?: boolean) => boolean;Match the current node if it matches the provided
pattern.For example, given the match
React.createClassit would match the parsed nodes ofReact.createClassandReact["createClass"].
function merge
merge: { <State>(visitors: Visitor<State>[]): ExplodedVisitor<State>; <State>( visitors: Visitor<State>[], states?: State[], wrapper?: VisitWrapper<State> ): ExplodedVisitor<State>;};function pushContainer
pushContainer: < N extends t.Node, K extends NodeKeyOfArrays<N>, Nodes extends NodeOrNodeList<NodeListType<N, K>>>( this: NodePath_Final<N>, listKey: K, nodes: Nodes) => NodePaths<Nodes>;function referencesImport
referencesImport: ( this: NodePath<t.Node, any, any>, moduleSource: string, importName: string) => boolean;Check if the currently assigned path references the
importNameofmoduleSource.
function remove
remove: (this: NodePath_Final<t.Node | null>) => void;function replaceExpressionWithStatements
replaceExpressionWithStatements: ( this: NodePath_Final<t.Node | null>, nodes: t.Statement[]) => | NodePath_Final<null> | NodePath_Final<t.Expression | t.TSType>[] | NodePath_Final<t.Statement>[];This method takes an array of statements nodes and then explodes it into expressions. This method retains completion records which is extremely important to retain original semantics.
function replaceInline
replaceInline: ( this: NodePath_Final<t.Node | null>, nodes: t.Node | t.Node[]) => NodePath_Final[];function replaceWith
replaceWith: { <R extends t.Node>(this: NodePath_Final<t.Node | null>, replacementPath: R): [ NodePath_Final<R> ]; <R extends NodePath<t.Node, any, any>>( this: NodePath<any, any, any>, replacementPath: R ): [R];};Replace the current node with another.
function replaceWithMultiple
replaceWithMultiple: <Nodes extends unknown>( this: NodePath_Final<t.Node | null>, nodes: Nodes) => NodePaths<Nodes>;function replaceWithSourceString
replaceWithSourceString: ( this: NodePath_Final<t.Node | null>, replacement: string) => [NodePath_Final<t.Expression>];Parse a string as an expression and replace the current node with the result.
NOTE: This is typically not a good idea to use. Building source strings when transforming ASTs is an antipattern and SHOULD NOT be encouraged. Even if it's easier to use, your transforms will be extremely brittle.
function requeue
requeue: ( this: NodePath_Final<t.Node | null>, pathToQueue?: NodePath_Final<t.Node | null>) => void;function requeueComputedKeyAndDecorators
requeueComputedKeyAndDecorators: ( this: NodePath_Final<t.Method | t.Property>) => void;function resolve
resolve: ( this: NodePath<t.Node, any, any>, dangerous?: boolean, resolved?: NodePath_Final[]) => NodePath<t.Node, any, any>;Resolve the value pointed to by a NodePath e.g.
var a = 1;var b = a;b;b.resolve()will return1
function setContext
setContext: <S = unknown>( this: NodePath_Final<t.Node | null>, context?: TraversalContext<S>) => NodePath_Final<t.Node | null>;function shareCommentsWithSiblings
shareCommentsWithSiblings: (this: NodePath_Final<t.Node | null>) => void;Share comments amongst siblings.
function skip
skip: (this: NodePath<t.Node, any, any>) => void;function skipKey
skipKey: (this: NodePath<t.Node, any, any>, key: string) => void;function splitExportDeclaration
splitExportDeclaration: ( this: NodePath_Final<t.ExportDefaultDeclaration | t.ExportNamedDeclaration>) => NodePath_Final<t.Declaration>;function stop
stop: (this: NodePath<t.Node, any, any>) => void;function traverse
traverse: typeof traverse;function unshiftContainer
unshiftContainer: < N extends t.Node, K extends NodeKeyOfArrays<N>, Nodes extends NodeOrNodeList<NodeListType<N, K>>>( this: NodePath_Final<N>, listKey: K, nodes: Nodes) => NodePaths<Nodes>;function unwrapFunctionEnvironment
unwrapFunctionEnvironment: ( this: NodePath_Final< t.ArrayExpression | t.FunctionExpression | t.FunctionDeclaration >) => void;Given an arbitrary function, process its content as if it were an arrow function, moving references to "this", "arguments", "super", and such into the function's parent scope. This method is useful if you have wrapped some set of items in an IIFE or other function, but want "this", "arguments", and super" to continue behaving as expected.
function verify$1
verify$1: (visitor: Visitor<any>) => void;function willIMaybeExecuteBefore
willIMaybeExecuteBefore: ( this: NodePath<t.Node, any, any>, target: NodePath<t.Node, any, any>) => boolean;Classes
class Binding
class Binding {}This class is responsible for a binding inside of a scope.
It tracks the following:
* Node path. * Amount of times referenced by other nodes. * Paths to nodes that reassign or modify this binding. * The kind of binding. (Is it a parameter, declaration etc)
constructor
constructor({ identifier, scope, path, kind,}: { identifier: t.Identifier; scope: Scope; path: NodePath<t.Node, any, any>; kind: BindingKind;});property constant
constant: boolean;property constantViolations
constantViolations: NodePath<t.Node, any, any>[];property hasDeoptedValue
hasDeoptedValue: boolean;property hasValue
hasValue: boolean;property identifier
identifier: t.Identifier;property kind
kind: BindingKind;property path
path: NodePath<t.Node, any, any>;property referenced
referenced: boolean;property referencePaths
referencePaths: NodePath<t.Node, any, any>[];property references
references: number;property scope
scope: Scope;property value
value: any;method clearValue
clearValue: () => void;method deoptValue
deoptValue: () => void;method dereference
dereference: () => void;Decrement the amount of references to this binding.
method reassign
reassign: (path: NodePath<t.Node, any, any>) => void;Register a constant violation with the provided
path.
method reference
reference: (path: NodePath<t.Node, any, any>) => void;Increment the amount of references to this binding.
method setValue
setValue: (value: any) => void;class Hub
class Hub implements HubInterface {}method addHelper
addHelper: () => void;method buildError
buildError: ( node: Node, msg: string, Error?: new (msg: string) => Error) => Error;method getCode
getCode: () => void;method getScope
getScope: () => void;class Scope
class Scope {}constructor
constructor(path: NodePath<any, any, any>);This searches the current "scope" and collects all references/bindings within.
property bindings
bindings: Record<string, Binding>;property block
block: any;property contextVariables
static contextVariables: string[];Variables available in current context.
property crawling
crawling: boolean;property data
data: Record<string | symbol, unknown>;property globals
static globals: string[];Globals.
property globals
globals: Record<string, any>;property inited
inited: boolean;property labels
labels: Map<string, NodePath<t.LabeledStatement, any, any>>;property parent
readonly parent: Scope;property path
path: NodePath<t.Node, any, any>;property references
readonly references: void;property referencesSet
referencesSet?: Set<string>;Only defined in the program scope
property uid
uid: number;property uids
readonly uids: void;property uidsSet
uidsSet?: Set<string>;Only defined in the program scope
method addGlobal
addGlobal: (node: t.Identifier | t.JSXIdentifier) => void;method bindingIdentifierEquals
bindingIdentifierEquals: (name: string, node: t.Node) => boolean;method checkBlockScopedCollisions
checkBlockScopedCollisions: ( local: Binding, kind: BindingKind, name: string, id: any) => void;method crawl
crawl: () => void;method dump
dump: () => void;method generateDeclaredUidIdentifier
generateDeclaredUidIdentifier: (name?: string) => t.Identifier;Generate a unique identifier and add it to the current scope.
method generateUid
generateUid: (name?: string) => string;Generate a unique
_id1binding.
method generateUidBasedOnNode
generateUidBasedOnNode: ( node: t.Node | undefined | null, defaultName?: string) => string;method generateUidIdentifier
generateUidIdentifier: (name?: string) => t.Identifier;Generate a unique identifier.
method generateUidIdentifierBasedOnNode
generateUidIdentifierBasedOnNode: ( node: t.Node | undefined | null, defaultName?: string) => t.Identifier;Generate a unique identifier based on a node.
method getAllBindings
getAllBindings: () => Record<string, Binding>;Walks the scope tree and gathers **all** bindings.
method getBinding
getBinding: (name: string) => Binding | undefined;method getBindingIdentifier
getBindingIdentifier: (name: string) => t.Identifier | undefined;method getBlockParent
getBlockParent: () => Scope;Walk up the scope tree until we hit either a BlockStatement/Loop/Program/Function/Switch or reach the very top and hit Program.
method getData
getData: (key: string | symbol) => any;Recursively walk up scope tree looking for the data
key.
method getFunctionParent
getFunctionParent: () => Scope | null;Walk up the scope tree until we hit either a Function or return null.
method getLabel
getLabel: ( name: string) => | NodePath< t.LabeledStatement, 'LabeledStatement', NonNullable< | t.BlockStatement | t.DoWhileStatement | t.ForInStatement | t.ForOfStatement | t.ForStatement | t.IfStatement | t.LabeledStatement | t.Program | t.StaticBlock | t.SwitchCase | t.TSModuleBlock | t.WhileStatement | t.WithStatement > > | undefined;method getOwnBinding
getOwnBinding: (name: string) => Binding | undefined;method getOwnBindingIdentifier
getOwnBindingIdentifier: (name: string) => t.Identifier | undefined;method getPatternParent
getPatternParent: () => Scope;Walk up from a pattern scope (function param initializer) until we hit a non-pattern scope, then returns its block parent
Returns
An ancestry scope whose path is a block parent
method getProgramParent
getProgramParent: () => Scope & { referencesSet: Set<string>; uidsSet: Set<string>;};Walk up to the top of the scope tree and get the
Program.
method hasBinding
hasBinding: ( name: string, opts?: boolean | { noGlobals?: boolean; noUids?: boolean; upToScope?: Scope }) => boolean;method hasGlobal
hasGlobal: (name: string) => boolean;method hasLabel
hasLabel: (name: string) => boolean;method hasOwnBinding
hasOwnBinding: (name: string) => boolean;method hasReference
hasReference: (name: string) => boolean;method hasUid
hasUid: (name: string) => boolean;method hoistVariables
hoistVariables: (emit?: (id: t.Identifier, hasInit: boolean) => void) => void;Hoist all the
varvariable to the beginning of the function/program scope where their binding will be actually defined. For exmaple, { var x = 2 } will be transformed to var x; { x = 2 }Parameter emit
A custom function to emit
vardeclarations, for example to emit them in a different scope.
method init
init: () => void;method isPure
isPure: (node: t.Node | null | undefined, constantsOnly?: boolean) => boolean;method isStatic
isStatic: (node: t.Node | null) => boolean;Determine whether evaluating the specific input
nodeis a consequenceless reference. ie. evaluating it won't result in potentially arbitrary code from being ran. The following are allowed and determined not to cause side effects:-
thisexpressions -superexpressions - Bound identifiers
method maybeGenerateMemoised
maybeGenerateMemoised: (node: t.Node, dontPush?: boolean) => t.Identifier | null;Possibly generate a memoised identifier if it is not static and has consequences.
method moveBindingTo
moveBindingTo: (name: string, scope: Scope) => void;Move a binding of
nameto anotherscope.
method parentHasBinding
parentHasBinding: ( name: string, opts?: { noGlobals?: boolean; noUids?: boolean }) => boolean | undefined;method push
push: (opts: { id: t.ArrayPattern | t.Identifier | t.ObjectPattern; init?: t.Expression; unique?: boolean; _blockHoist?: number | undefined; kind?: 'var' | 'let' | 'const';}) => void;method registerBinding
registerBinding: ( kind: Binding['kind'], path: NodePath_Final<t.Node>, bindingPath?: NodePath_Final<t.Node>) => void;method registerConstantViolation
registerConstantViolation: (path: NodePath_Final<t.Node>) => void;method registerDeclaration
registerDeclaration: (path: NodePath_Final<t.Node>) => void;method registerLabel
registerLabel: (path: NodePath_Final<t.LabeledStatement>) => void;method removeBinding
removeBinding: (name: string) => void;method removeData
removeData: (key: string) => void;Recursively walk up scope tree looking for the data
keyand if it exists, remove it.
method removeOwnBinding
removeOwnBinding: (name: string) => void;method rename
rename: (oldName: string, newName?: string) => void;method setData
setData: (key: string | symbol, val: any) => any;Set some arbitrary data on the current scope.
Interfaces
interface ExplodedVisitor
interface ExplodedVisitor<S = unknown> extends ExplVisitorBase<S>, ExplVisitNode<S, t.Node> {}interface HubInterface
interface HubInterface {}method addHelper
addHelper: (name: string) => any;method buildError
buildError: ( node: Node, msg: string, Error: new (msg: string) => Error) => Error;method getCode
getCode: () => string | void;method getScope
getScope: () => Scope | void;interface VisitorBase
interface VisitorBase<S> extends VisitNodeObject<S, t.Node>, VisitorBaseNodes<S>, VisitorBaseAliases<S>, VisitorVirtualAliases<S>, Record<`${string}|${string}`, VisitNode<S, t.Node>> {}Type Aliases
type BindingKind
type BindingKind = | 'var' | 'let' | 'const' | 'module' | 'hoisted' | 'param' | 'local' | 'unknown';type NodePath
type NodePath_Final<T extends t.Node | null = t.Node> = T extends any ? NodePath<T> : never;type TraverseOptions
type TraverseOptions = { scope?: Scope; noScope?: boolean; denylist?: string[]; shouldSkip?: (node: NodePath_Final) => boolean;};type Visitor
type Visitor<S = unknown> = VisitorBase<S> | ExplodedVisitor<S>;type VisitWrapper
type VisitWrapper<S = any> = ( stateName: string | undefined, visitorType: VisitPhase, callback: VisitNodeFunction<S, Node>) => VisitNodeFunction<S, Node>;Namespaces
namespace traverse
namespace traverse {}variable cache
var cache: typeof __cache_ts;variable explode
var explode: { <S, T extends object>(visitor: { [P in keyof T]: VisitorProp<S, P & string>; }): ExplodedVisitor<S>; <S>(visitor: Visitor<S>): ExplodedVisitor<S>;};variable verify
var verify: (visitor: Visitor<any>) => void;variable visitors
var visitors: typeof __visitors_ts;function cheap
cheap: (node: t.Node, enter: (node: t.Node) => void) => void;function clearNode
clearNode: (node: t.Node, opts?: RemovePropertiesOptions) => void;function hasType
hasType: (tree: t.Node, type: t.Node, denylistTypes?: string[]) => boolean;function node
node: ( node: t.Node, opts: TraverseOptions & ExplodedVisitor, scope?: Scope, state?: any, path?: NodePath<t.Node, any, any>, skipKeys?: Record<string, boolean>) => void;function removeProperties
removeProperties: (tree: t.Node, opts?: RemovePropertiesOptions) => t.Node;namespace visitors
namespace visitors {}variable environmentVisitor
const environmentVisitor: <S>(visitor: Visitor<S>) => ExplodedVisitor<S>;variable isExplodedVisitor
const isExplodedVisitor: ( visitor: Visitor<any>) => visitor is ExplodedVisitor<unknown>;variable merge
const merge: { <State>(visitors: Visitor<State>[]): ExplodedVisitor<State>; <State>( visitors: Visitor<State>[], states?: State[], wrapper?: VisitWrapper<State> ): ExplodedVisitor<State>;};function explode
explode: { <S, T extends object>(visitor: { [P in keyof T]: VisitorProp<S, P & string>; }): ExplodedVisitor<S>; <S>(visitor: Visitor<S>): ExplodedVisitor<S>;};explode() will take a visitor object with all of the various shorthands that we support, and validates & normalizes it into a common format, ready to be used in traversal
The various shorthands are: *
Identifier() { ... }->Identifier: { enter() { ... } }*"Identifier|NumericLiteral": { ... }->Identifier: { ... }, NumericLiteral: { ... }* Aliases in@babel/types: e.g.Property: { ... }->ObjectProperty: { ... }, ClassProperty: { ... }Other normalizations are: * Visitors of virtual types are wrapped, so that they are only visited when their dynamic check passes *enterandexitfunctions are wrapped in arrays, to ease merging of visitors
function verify
verify: (visitor: Visitor<any>) => void;type VisitWrapper
type __visitors_ts_VisitWrapper<S = any> = VisitWrapper<S>;Package Files (1)
Dependencies (7)
Dev Dependencies (2)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@babel/traverse.
- Markdown[](https://www.jsdocs.io/package/@babel/traverse)
- HTML<a href="https://www.jsdocs.io/package/@babel/traverse"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 7798 ms. - Missing or incorrect documentation? Open an issue for this package.
