@babel/traverse 8.0.0-alpha.1 → 8.0.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cache.js +16 -2
- package/lib/cache.js.map +1 -1
- package/lib/index.js +42 -33
- package/lib/index.js.map +1 -1
- package/lib/path/index.js +2 -6
- package/lib/path/index.js.map +1 -1
- package/lib/path/lib/virtual-types-validator.js +1 -6
- package/lib/path/lib/virtual-types-validator.js.map +1 -1
- package/lib/path/modification.js +2 -2
- package/lib/path/modification.js.map +1 -1
- package/lib/path/removal.js +4 -2
- package/lib/path/removal.js.map +1 -1
- package/lib/path/replacement.js +3 -3
- package/lib/path/replacement.js.map +1 -1
- package/lib/traverse-node.js +6 -2
- package/lib/traverse-node.js.map +1 -1
- package/lib/visitors.js.map +1 -1
- package/package.json +11 -10
package/lib/path/index.js
CHANGED
@@ -7,7 +7,7 @@ const {
|
|
7
7
|
validate
|
8
8
|
} = _t;
|
9
9
|
import * as t from "@babel/types";
|
10
|
-
import
|
10
|
+
import * as cache from "../cache.js";
|
11
11
|
import generator from "@babel/generator";
|
12
12
|
import * as NodePath_ancestry from "./ancestry.js";
|
13
13
|
import * as NodePath_inference from "./inference/index.js";
|
@@ -59,11 +59,7 @@ class NodePath {
|
|
59
59
|
throw new Error("To get a node path the parent needs to exist");
|
60
60
|
}
|
61
61
|
const targetNode = container[key];
|
62
|
-
|
63
|
-
if (!paths) {
|
64
|
-
paths = new Map();
|
65
|
-
pathCache.set(parent, paths);
|
66
|
-
}
|
62
|
+
const paths = cache.getOrCreateCachedPaths(hub, parent);
|
67
63
|
let path = paths.get(targetNode);
|
68
64
|
if (!path) {
|
69
65
|
path = new NodePath(hub, parent);
|
package/lib/path/index.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"names":["virtualTypes","buildDebug","traverse","Scope","_t","validate","t","path","pathCache","generator","NodePath_ancestry","NodePath_inference","NodePath_replacement","NodePath_evaluation","NodePath_conversion","NodePath_introspection","NodePath_context","NodePath_removal","NodePath_modification","NodePath_family","NodePath_comments","NodePath_virtual_types_validator","debug","REMOVED","SHOULD_STOP","SHOULD_SKIP","NodePath","constructor","hub","parent","data","context","scope","contexts","state","opts","_traverseFlags","skipKeys","parentPath","container","listKey","key","node","type","get","Error","targetNode","paths","Map","set","setup","getScope","isScope","setData","val","Object","create","getData","def","undefined","hasNode","buildCodeFrameError","msg","SyntaxError","buildError","visitor","getPathLocation","parts","inList","unshift","join","message","enabled","toString","code","parentKey","shouldSkip","v","shouldStop","removed","assign","prototype","TYPES","typeKey","fn","TypeError","keys","includes","push"],"sources":["../../src/path/index.ts"],"sourcesContent":["import type { HubInterface } from \"../hub\";\nimport type TraversalContext from \"../context\";\nimport type { ExplodedTraverseOptions } from \"..\";\nimport * as virtualTypes from \"./lib/virtual-types\";\nimport buildDebug from \"debug\";\nimport traverse from \"../index\";\nimport type { Visitor } from \"../types\";\nimport Scope from \"../scope\";\nimport { validate } from \"@babel/types\";\nimport * as t from \"@babel/types\";\nimport { path as pathCache } from \"../cache\";\nimport generator from \"@babel/generator\";\n\n// NodePath is split across many files.\nimport * as NodePath_ancestry from \"./ancestry\";\nimport * as NodePath_inference from \"./inference\";\nimport * as NodePath_replacement from \"./replacement\";\nimport * as NodePath_evaluation from \"./evaluation\";\nimport * as NodePath_conversion from \"./conversion\";\nimport * as NodePath_introspection from \"./introspection\";\nimport * as NodePath_context from \"./context\";\nimport * as NodePath_removal from \"./removal\";\nimport * as NodePath_modification from \"./modification\";\nimport * as NodePath_family from \"./family\";\nimport * as NodePath_comments from \"./comments\";\nimport * as NodePath_virtual_types_validator from \"./lib/virtual-types-validator\";\nimport type { NodePathAssertions } from \"./generated/asserts\";\nimport type { NodePathValidators } from \"./generated/validators\";\n\nconst debug = buildDebug(\"babel\");\n\nexport const REMOVED = 1 << 0;\nexport const SHOULD_STOP = 1 << 1;\nexport const SHOULD_SKIP = 1 << 2;\n\nclass NodePath<T extends t.Node = t.Node> {\n constructor(hub: HubInterface, parent: t.ParentMaps[T[\"type\"]]) {\n this.parent = parent;\n this.hub = hub;\n this.data = null;\n\n this.context = null;\n this.scope = null;\n }\n\n declare parent: t.ParentMaps[T[\"type\"]];\n declare hub: HubInterface;\n declare data: Record<string | symbol, unknown>;\n // TraversalContext is configured by setContext\n declare context: TraversalContext;\n declare scope: Scope;\n\n contexts: Array<TraversalContext> = [];\n state: any = null;\n opts: ExplodedTraverseOptions | null = null;\n // this.shouldSkip = false; this.shouldStop = false; this.removed = false;\n _traverseFlags: number = 0;\n skipKeys: Record<string, boolean> | null = null;\n parentPath: t.ParentMaps[T[\"type\"]] extends null\n ? null\n : NodePath<t.ParentMaps[T[\"type\"]]> | null = null;\n container: t.Node | Array<t.Node> | null = null;\n listKey: string | null = null;\n key: string | number | null = null;\n node: T = null;\n type: T[\"type\"] | null = null;\n\n static get({\n hub,\n parentPath,\n parent,\n container,\n listKey,\n key,\n }: {\n hub?: HubInterface;\n parentPath: NodePath | null;\n parent: t.Node;\n container: t.Node | t.Node[];\n listKey?: string;\n key: string | number;\n }): NodePath {\n if (!hub && parentPath) {\n hub = parentPath.hub;\n }\n\n if (!parent) {\n throw new Error(\"To get a node path the parent needs to exist\");\n }\n\n const targetNode =\n // @ts-expect-error key must present in container\n container[key];\n\n let paths = pathCache.get(parent);\n if (!paths) {\n paths = new Map();\n pathCache.set(parent, paths);\n }\n\n let path = paths.get(targetNode);\n if (!path) {\n path = new NodePath(hub, parent);\n if (targetNode) paths.set(targetNode, path);\n }\n\n path.setup(parentPath, container, listKey, key);\n\n return path;\n }\n\n getScope(scope: Scope): Scope {\n return this.isScope() ? new Scope(this) : scope;\n }\n\n setData(key: string | symbol, val: any): any {\n if (this.data == null) {\n this.data = Object.create(null);\n }\n return (this.data[key] = val);\n }\n\n getData(key: string | symbol, def?: any): any {\n if (this.data == null) {\n this.data = Object.create(null);\n }\n let val = this.data[key];\n if (val === undefined && def !== undefined) val = this.data[key] = def;\n return val;\n }\n\n hasNode(): this is NodePath<NonNullable<this[\"node\"]>> {\n return this.node != null;\n }\n\n buildCodeFrameError(\n msg: string,\n Error: new () => Error = SyntaxError,\n ): Error {\n return this.hub.buildError(this.node, msg, Error);\n }\n\n traverse<T>(visitor: Visitor<T>, state: T): void;\n traverse(visitor: Visitor): void;\n traverse(visitor: any, state?: any) {\n traverse(this.node, visitor, this.scope, state, this);\n }\n\n set(key: string, node: any) {\n validate(this.node, key, node);\n // @ts-expect-error key must present in this.node\n this.node[key] = node;\n }\n\n getPathLocation(): string {\n const parts = [];\n let path: NodePath = this;\n do {\n let key = path.key;\n if (path.inList) key = `${path.listKey}[${key}]`;\n parts.unshift(key);\n } while ((path = path.parentPath));\n return parts.join(\".\");\n }\n\n debug(message: string) {\n if (!debug.enabled) return;\n debug(`${this.getPathLocation()} ${this.type}: ${message}`);\n }\n\n toString() {\n return generator(this.node).code;\n }\n\n get inList() {\n return !!this.listKey;\n }\n\n set inList(inList) {\n if (!inList) {\n this.listKey = null;\n }\n // ignore inList = true as it should depend on `listKey`\n }\n\n get parentKey(): string {\n return (this.listKey || this.key) as string;\n }\n\n get shouldSkip() {\n return !!(this._traverseFlags & SHOULD_SKIP);\n }\n\n set shouldSkip(v) {\n if (v) {\n this._traverseFlags |= SHOULD_SKIP;\n } else {\n this._traverseFlags &= ~SHOULD_SKIP;\n }\n }\n\n get shouldStop() {\n return !!(this._traverseFlags & SHOULD_STOP);\n }\n\n set shouldStop(v) {\n if (v) {\n this._traverseFlags |= SHOULD_STOP;\n } else {\n this._traverseFlags &= ~SHOULD_STOP;\n }\n }\n\n get removed() {\n return !!(this._traverseFlags & REMOVED);\n }\n set removed(v) {\n if (v) {\n this._traverseFlags |= REMOVED;\n } else {\n this._traverseFlags &= ~REMOVED;\n }\n }\n}\n\nObject.assign(\n NodePath.prototype,\n NodePath_ancestry,\n NodePath_inference,\n NodePath_replacement,\n NodePath_evaluation,\n NodePath_conversion,\n NodePath_introspection,\n NodePath_context,\n NodePath_removal,\n NodePath_modification,\n NodePath_family,\n NodePath_comments,\n);\n\nif (!process.env.BABEL_8_BREAKING) {\n // @ts-expect-error The original _guessExecutionStatusRelativeToDifferentFunctions only worked for paths in\n // different functions, but _guessExecutionStatusRelativeTo works as a replacement in those cases.\n NodePath.prototype._guessExecutionStatusRelativeToDifferentFunctions =\n NodePath_introspection._guessExecutionStatusRelativeTo;\n}\n\n// we can not use `import { TYPES } from \"@babel/types\"` here\n// because the transformNamedBabelTypesImportToDestructuring plugin in babel.config.js\n// does not offer live bindings for `TYPES`\n// we can change to `import { TYPES }` when we are publishing ES modules only\nfor (const type of t.TYPES) {\n const typeKey = `is${type}`;\n // @ts-expect-error typeKey must present in t\n const fn = t[typeKey];\n // @ts-expect-error augmenting NodePath prototype\n NodePath.prototype[typeKey] = function (opts: any) {\n return fn(this.node, opts);\n };\n\n // @ts-expect-error augmenting NodePath prototype\n NodePath.prototype[`assert${type}`] = function (opts: any) {\n if (!fn(this.node, opts)) {\n throw new TypeError(`Expected node path of type ${type}`);\n }\n };\n}\n\n// Register virtual types validators after base types validators\nObject.assign(NodePath.prototype, NodePath_virtual_types_validator);\n\nfor (const type of Object.keys(virtualTypes) as (keyof typeof virtualTypes)[]) {\n if (type[0] === \"_\") continue;\n if (!t.TYPES.includes(type)) t.TYPES.push(type);\n}\n\ntype NodePathMixins = typeof NodePath_ancestry &\n typeof NodePath_inference &\n typeof NodePath_replacement &\n typeof NodePath_evaluation &\n typeof NodePath_conversion &\n typeof NodePath_introspection &\n typeof NodePath_context &\n typeof NodePath_removal &\n typeof NodePath_modification &\n typeof NodePath_family &\n typeof NodePath_comments;\n\n// @ts-expect-error TS throws because ensureBlock returns the body node path\n// however, we don't use the return value and treat it as a transform and\n// assertion utilities. For better type inference we annotate it as an\n// assertion method\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\ninterface NodePath<T>\n extends NodePathAssertions,\n NodePathValidators,\n NodePathMixins {\n /**\n * @see ./conversion.ts for implementation\n */\n ensureBlock<\n T extends\n | t.Loop\n | t.WithStatement\n | t.Function\n | t.LabeledStatement\n | t.CatchClause,\n >(\n this: NodePath<T>,\n ): asserts this is NodePath<T & { body: t.BlockStatement }>;\n}\n\nexport default NodePath;\n"],"mappings":"AAGA,OAAO,KAAKA,YAAY,MAAM,wBAAqB;AACnD,OAAOC,UAAU,MAAM,OAAO;AAC9B,OAAOC,QAAQ,MAAM,aAAU;AAE/B,OAAOC,KAAK,MAAM,mBAAU;AAC5B,YAAAC,EAAA,MAAyB,cAAc;AAAC;EAA/BC;AAAQ,IAAAD,EAAA;AACjB,OAAO,KAAKE,CAAC,MAAM,cAAc;AACjC,SAASC,IAAI,IAAIC,SAAS,QAAQ,aAAU;AAC5C,OAAOC,SAAS,MAAM,kBAAkB;AAGxC,OAAO,KAAKC,iBAAiB,MAAM,eAAY;AAC/C,OAAO,KAAKC,kBAAkB,MAAM,sBAAa;AACjD,OAAO,KAAKC,oBAAoB,MAAM,kBAAe;AACrD,OAAO,KAAKC,mBAAmB,MAAM,iBAAc;AACnD,OAAO,KAAKC,mBAAmB,MAAM,iBAAc;AACnD,OAAO,KAAKC,sBAAsB,MAAM,oBAAiB;AACzD,OAAO,KAAKC,gBAAgB,MAAM,cAAW;AAC7C,OAAO,KAAKC,gBAAgB,MAAM,cAAW;AAC7C,OAAO,KAAKC,qBAAqB,MAAM,mBAAgB;AACvD,OAAO,KAAKC,eAAe,MAAM,aAAU;AAC3C,OAAO,KAAKC,iBAAiB,MAAM,eAAY;AAC/C,OAAO,KAAKC,gCAAgC,MAAM,kCAA+B;AAIjF,MAAMC,KAAK,GAAGrB,UAAU,CAAC,OAAO,CAAC;AAEjC,OAAO,MAAMsB,OAAO,GAAG,CAAC,IAAI,CAAC;AAC7B,OAAO,MAAMC,WAAW,GAAG,CAAC,IAAI,CAAC;AACjC,OAAO,MAAMC,WAAW,GAAG,CAAC,IAAI,CAAC;AAEjC,MAAMC,QAAQ,CAA4B;EACxCC,WAAWA,CAACC,GAAiB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AO,GAAI,KAAIxC,IAAK,EAAC;EAE3B,MAAMyC,EAAE,GAAG9E,CAAC,CAAC6E,OAAO,CAAC;EAErBzD,QAAQ,CAACuD,SAAS,CAACE,OAAO,CAAC,GAAG,UAAUhD,IAAS,EAAE;IACjD,OAAOiD,EAAE,CAAC,IAAI,CAAC1C,IAAI,EAAEP,IAAI,CAAC;EAC5B,CAAC;EAGDT,QAAQ,CAACuD,SAAS,CAAE,SAAQtC,IAAK,EAAC,CAAC,GAAG,UAAUR,IAAS,EAAE;IACzD,IAAI,CAACiD,EAAE,CAAC,IAAI,CAAC1C,IAAI,EAAEP,IAAI,CAAC,EAAE;MACxB,MAAM,IAAIkD,SAAS,CAAE,8BAA6B1C,IAAK,EAAC,CAAC;IAC3D;EACF,CAAC;AACH;AAGAY,MAAM,CAACyB,MAAM,CAACtD,QAAQ,CAACuD,SAAS,EAAE5D,gCAAgC,CAAC;AAEnE,KAAK,MAAMsB,IAAI,IAAIY,MAAM,CAAC+B,IAAI,CAACtF,YAAY,CAAC,EAAmC;EAC7E,IAAI2C,IAAI,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE;EACrB,IAAI,CAACrC,CAAC,CAAC4E,KAAK,CAACK,QAAQ,CAAC5C,IAAI,CAAC,EAAErC,CAAC,CAAC4E,KAAK,CAACM,IAAI,CAAC7C,IAAI,CAAC;AACjD;AAsCA,eAAejB,QAAQ"}
|
1
|
+
{"version":3,"names":["virtualTypes","buildDebug","traverse","Scope","_t","validate","t","cache","generator","NodePath_ancestry","NodePath_inference","NodePath_replacement","NodePath_evaluation","NodePath_conversion","NodePath_introspection","NodePath_context","NodePath_removal","NodePath_modification","NodePath_family","NodePath_comments","NodePath_virtual_types_validator","debug","REMOVED","SHOULD_STOP","SHOULD_SKIP","NodePath","constructor","hub","parent","data","context","scope","contexts","state","opts","_traverseFlags","skipKeys","parentPath","container","listKey","key","node","type","get","Error","targetNode","paths","getOrCreateCachedPaths","path","set","setup","getScope","isScope","setData","val","Object","create","getData","def","undefined","hasNode","buildCodeFrameError","msg","SyntaxError","buildError","visitor","getPathLocation","parts","inList","unshift","join","message","enabled","toString","code","parentKey","shouldSkip","v","shouldStop","removed","assign","prototype","TYPES","typeKey","fn","TypeError","keys","includes","push"],"sources":["../../src/path/index.ts"],"sourcesContent":["import type { HubInterface } from \"../hub\";\nimport type TraversalContext from \"../context\";\nimport type { ExplodedTraverseOptions } from \"..\";\nimport * as virtualTypes from \"./lib/virtual-types\";\nimport buildDebug from \"debug\";\nimport traverse from \"../index\";\nimport type { Visitor } from \"../types\";\nimport Scope from \"../scope\";\nimport { validate } from \"@babel/types\";\nimport * as t from \"@babel/types\";\nimport * as cache from \"../cache\";\nimport generator from \"@babel/generator\";\n\n// NodePath is split across many files.\nimport * as NodePath_ancestry from \"./ancestry\";\nimport * as NodePath_inference from \"./inference\";\nimport * as NodePath_replacement from \"./replacement\";\nimport * as NodePath_evaluation from \"./evaluation\";\nimport * as NodePath_conversion from \"./conversion\";\nimport * as NodePath_introspection from \"./introspection\";\nimport * as NodePath_context from \"./context\";\nimport * as NodePath_removal from \"./removal\";\nimport * as NodePath_modification from \"./modification\";\nimport * as NodePath_family from \"./family\";\nimport * as NodePath_comments from \"./comments\";\nimport * as NodePath_virtual_types_validator from \"./lib/virtual-types-validator\";\nimport type { NodePathAssertions } from \"./generated/asserts\";\nimport type { NodePathValidators } from \"./generated/validators\";\n\nconst debug = buildDebug(\"babel\");\n\nexport const REMOVED = 1 << 0;\nexport const SHOULD_STOP = 1 << 1;\nexport const SHOULD_SKIP = 1 << 2;\n\nclass NodePath<T extends t.Node = t.Node> {\n constructor(hub: HubInterface, parent: t.ParentMaps[T[\"type\"]]) {\n this.parent = parent;\n this.hub = hub;\n this.data = null;\n\n this.context = null;\n this.scope = null;\n }\n\n declare parent: t.ParentMaps[T[\"type\"]];\n declare hub: HubInterface;\n declare data: Record<string | symbol, unknown>;\n // TraversalContext is configured by setContext\n declare context: TraversalContext;\n declare scope: Scope;\n\n contexts: Array<TraversalContext> = [];\n state: any = null;\n opts: ExplodedTraverseOptions | null = null;\n // this.shouldSkip = false; this.shouldStop = false; this.removed = false;\n _traverseFlags: number = 0;\n skipKeys: Record<string, boolean> | null = null;\n parentPath: t.ParentMaps[T[\"type\"]] extends null\n ? null\n : NodePath<t.ParentMaps[T[\"type\"]]> | null = null;\n container: t.Node | Array<t.Node> | null = null;\n listKey: string | null = null;\n key: string | number | null = null;\n node: T = null;\n type: T[\"type\"] | null = null;\n\n static get({\n hub,\n parentPath,\n parent,\n container,\n listKey,\n key,\n }: {\n hub?: HubInterface;\n parentPath: NodePath | null;\n parent: t.Node;\n container: t.Node | t.Node[];\n listKey?: string;\n key: string | number;\n }): NodePath {\n if (!hub && parentPath) {\n hub = parentPath.hub;\n }\n\n if (!parent) {\n throw new Error(\"To get a node path the parent needs to exist\");\n }\n\n const targetNode =\n // @ts-expect-error key must present in container\n container[key];\n\n const paths = cache.getOrCreateCachedPaths(hub, parent);\n\n let path = paths.get(targetNode);\n if (!path) {\n path = new NodePath(hub, parent);\n if (targetNode) paths.set(targetNode, path);\n }\n\n path.setup(parentPath, container, listKey, key);\n\n return path;\n }\n\n getScope(scope: Scope): Scope {\n return this.isScope() ? new Scope(this) : scope;\n }\n\n setData(key: string | symbol, val: any): any {\n if (this.data == null) {\n this.data = Object.create(null);\n }\n return (this.data[key] = val);\n }\n\n getData(key: string | symbol, def?: any): any {\n if (this.data == null) {\n this.data = Object.create(null);\n }\n let val = this.data[key];\n if (val === undefined && def !== undefined) val = this.data[key] = def;\n return val;\n }\n\n hasNode(): this is NodePath<NonNullable<this[\"node\"]>> {\n return this.node != null;\n }\n\n buildCodeFrameError(\n msg: string,\n Error: new () => Error = SyntaxError,\n ): Error {\n return this.hub.buildError(this.node, msg, Error);\n }\n\n traverse<T>(visitor: Visitor<T>, state: T): void;\n traverse(visitor: Visitor): void;\n traverse(visitor: any, state?: any) {\n traverse(this.node, visitor, this.scope, state, this);\n }\n\n set(key: string, node: any) {\n validate(this.node, key, node);\n // @ts-expect-error key must present in this.node\n this.node[key] = node;\n }\n\n getPathLocation(): string {\n const parts = [];\n let path: NodePath = this;\n do {\n let key = path.key;\n if (path.inList) key = `${path.listKey}[${key}]`;\n parts.unshift(key);\n } while ((path = path.parentPath));\n return parts.join(\".\");\n }\n\n debug(message: string) {\n if (!debug.enabled) return;\n debug(`${this.getPathLocation()} ${this.type}: ${message}`);\n }\n\n toString() {\n return generator(this.node).code;\n }\n\n get inList() {\n return !!this.listKey;\n }\n\n set inList(inList) {\n if (!inList) {\n this.listKey = null;\n }\n // ignore inList = true as it should depend on `listKey`\n }\n\n get parentKey(): string {\n return (this.listKey || this.key) as string;\n }\n\n get shouldSkip() {\n return !!(this._traverseFlags & SHOULD_SKIP);\n }\n\n set shouldSkip(v) {\n if (v) {\n this._traverseFlags |= SHOULD_SKIP;\n } else {\n this._traverseFlags &= ~SHOULD_SKIP;\n }\n }\n\n get shouldStop() {\n return !!(this._traverseFlags & SHOULD_STOP);\n }\n\n set shouldStop(v) {\n if (v) {\n this._traverseFlags |= SHOULD_STOP;\n } else {\n this._traverseFlags &= ~SHOULD_STOP;\n }\n }\n\n get removed() {\n return !!(this._traverseFlags & REMOVED);\n }\n set removed(v) {\n if (v) {\n this._traverseFlags |= REMOVED;\n } else {\n this._traverseFlags &= ~REMOVED;\n }\n }\n}\n\nObject.assign(\n NodePath.prototype,\n NodePath_ancestry,\n NodePath_inference,\n NodePath_replacement,\n NodePath_evaluation,\n NodePath_conversion,\n NodePath_introspection,\n NodePath_context,\n NodePath_removal,\n NodePath_modification,\n NodePath_family,\n NodePath_comments,\n);\n\nif (!process.env.BABEL_8_BREAKING) {\n // @ts-expect-error The original _guessExecutionStatusRelativeToDifferentFunctions only worked for paths in\n // different functions, but _guessExecutionStatusRelativeTo works as a replacement in those cases.\n NodePath.prototype._guessExecutionStatusRelativeToDifferentFunctions =\n NodePath_introspection._guessExecutionStatusRelativeTo;\n}\n\n// we can not use `import { TYPES } from \"@babel/types\"` here\n// because the transformNamedBabelTypesImportToDestructuring plugin in babel.config.js\n// does not offer live bindings for `TYPES`\n// we can change to `import { TYPES }` when we are publishing ES modules only\nfor (const type of t.TYPES) {\n const typeKey = `is${type}`;\n // @ts-expect-error typeKey must present in t\n const fn = t[typeKey];\n // @ts-expect-error augmenting NodePath prototype\n NodePath.prototype[typeKey] = function (opts: any) {\n return fn(this.node, opts);\n };\n\n // @ts-expect-error augmenting NodePath prototype\n NodePath.prototype[`assert${type}`] = function (opts: any) {\n if (!fn(this.node, opts)) {\n throw new TypeError(`Expected node path of type ${type}`);\n }\n };\n}\n\n// Register virtual types validators after base types validators\nObject.assign(NodePath.prototype, NodePath_virtual_types_validator);\n\nfor (const type of Object.keys(virtualTypes) as (keyof typeof virtualTypes)[]) {\n if (type[0] === \"_\") continue;\n if (!t.TYPES.includes(type)) t.TYPES.push(type);\n}\n\ntype NodePathMixins = typeof NodePath_ancestry &\n typeof NodePath_inference &\n typeof NodePath_replacement &\n typeof NodePath_evaluation &\n typeof NodePath_conversion &\n typeof NodePath_introspection &\n typeof NodePath_context &\n typeof NodePath_removal &\n typeof NodePath_modification &\n typeof NodePath_family &\n typeof NodePath_comments;\n\n// @ts-expect-error TS throws because ensureBlock returns the body node path\n// however, we don't use the return value and treat it as a transform and\n// assertion utilities. For better type inference we annotate it as an\n// assertion method\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\ninterface NodePath<T>\n extends NodePathAssertions,\n NodePathValidators,\n NodePathMixins {\n /**\n * @see ./conversion.ts for implementation\n */\n ensureBlock<\n T extends\n | t.Loop\n | t.WithStatement\n | t.Function\n | t.LabeledStatement\n | t.CatchClause,\n >(\n this: NodePath<T>,\n ): asserts this is NodePath<T & { body: t.BlockStatement }>;\n}\n\nexport default NodePath;\n"],"mappings":"AAGA,OAAO,KAAKA,YAAY,MAAM,wBAAqB;AACnD,OAAOC,UAAU,MAAM,OAAO;AAC9B,OAAOC,QAAQ,MAAM,aAAU;AAE/B,OAAOC,KAAK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D,SAAS,CAAE,8BAA6B3C,IAAK,EAAC,CAAC;IAC3D;EACF,CAAC;AACH;AAGAa,MAAM,CAACyB,MAAM,CAACvD,QAAQ,CAACwD,SAAS,EAAE7D,gCAAgC,CAAC;AAEnE,KAAK,MAAMsB,IAAI,IAAIa,MAAM,CAAC+B,IAAI,CAACtF,YAAY,CAAC,EAAmC;EAC7E,IAAI0C,IAAI,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE;EACrB,IAAI,CAACpC,CAAC,CAAC4E,KAAK,CAACK,QAAQ,CAAC7C,IAAI,CAAC,EAAEpC,CAAC,CAAC4E,KAAK,CAACM,IAAI,CAAC9C,IAAI,CAAC;AACjD;AAsCA,eAAejB,QAAQ"}
|
@@ -128,11 +128,6 @@ export function isForAwaitStatement() {
|
|
128
128
|
await: true
|
129
129
|
});
|
130
130
|
}
|
131
|
-
|
132
|
-
throw new Error("`path.isExistentialTypeParam` has been renamed to `path.isExistsTypeAnnotation()` in Babel 7.");
|
133
|
-
}
|
134
|
-
export function isNumericLiteralTypeAnnotation() {
|
135
|
-
throw new Error("`path.isNumericLiteralTypeAnnotation()` has been renamed to `path.isNumberLiteralTypeAnnotation()` in Babel 7.");
|
136
|
-
}
|
131
|
+
;
|
137
132
|
|
138
133
|
//# sourceMappingURL=virtual-types-validator.js.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"names":["_t","isBinding","isBlockScoped","nodeIsBlockScoped","isExportDeclaration","isExpression","nodeIsExpression","isFlow","nodeIsFlow","isForStatement","isForXStatement","isIdentifier","isImportDeclaration","isImportSpecifier","isJSXIdentifier","isJSXMemberExpression","isMemberExpression","isRestElement","nodeIsRestElement","isReferenced","nodeIsReferenced","isScope","nodeIsScope","isStatement","nodeIsStatement","isVar","nodeIsVar","isVariableDeclaration","react","isForOfStatement","isCompatTag","isReferencedIdentifier","opts","node","parent","name","parentPath","isReferencedMemberExpression","isBindingIdentifier","grandparent","left","init","isUser","loc","isGenerated","isPure","constantsOnly","scope","importKind","exportKind","isRestProperty","isObjectPattern","isSpreadProperty","isObjectExpression","isForAwaitStatement","await","isExistentialTypeParam","Error","isNumericLiteralTypeAnnotation"],"sources":["../../../src/path/lib/virtual-types-validator.ts"],"sourcesContent":["import type NodePath from \"../index\";\nimport {\n isBinding,\n isBlockScoped as nodeIsBlockScoped,\n isExportDeclaration,\n isExpression as nodeIsExpression,\n isFlow as nodeIsFlow,\n isForStatement,\n isForXStatement,\n isIdentifier,\n isImportDeclaration,\n isImportSpecifier,\n isJSXIdentifier,\n isJSXMemberExpression,\n isMemberExpression,\n isRestElement as nodeIsRestElement,\n isReferenced as nodeIsReferenced,\n isScope as nodeIsScope,\n isStatement as nodeIsStatement,\n isVar as nodeIsVar,\n isVariableDeclaration,\n react,\n isForOfStatement,\n} from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nconst { isCompatTag } = react;\nimport type { VirtualTypeAliases } from \"./virtual-types\";\n\nexport interface VirtualTypeNodePathValidators {\n isBindingIdentifier<T extends t.Node>(\n this: NodePath<T>,\n opts?: object,\n ): this is NodePath<T & VirtualTypeAliases[\"BindingIdentifier\"]>;\n isBlockScoped(opts?: object): boolean;\n /**\n * @deprecated\n */\n isExistentialTypeParam<T extends t.Node>(\n this: NodePath<T>,\n opts?: object,\n ): this is NodePath<T & VirtualTypeAliases[\"ExistentialTypeParam\"]>;\n isExpression<T extends t.Node>(\n this: NodePath<T>,\n opts?: object,\n ): this is NodePath<T & t.Expression>;\n isFlow<T extends t.Node>(\n this: NodePath<T>,\n opts?: object,\n ): this is NodePath<T & t.Flow>;\n isForAwaitStatement<T extends t.Node>(\n this: NodePath<T>,\n opts?: object,\n ): this is NodePath<T & VirtualTypeAliases[\"ForAwaitStatement\"]>;\n isGenerated(opts?: object): boolean;\n /**\n * @deprecated\n */\n isNumericLiteralTypeAnnotation(opts?: object): void;\n isPure(opts?: object): boolean;\n isReferenced(opts?: object): boolean;\n isReferencedIdentifier<T extends t.Node>(\n this: NodePath<T>,\n opts?: object,\n ): this is NodePath<T & VirtualTypeAliases[\"ReferencedIdentifier\"]>;\n isReferencedMemberExpression<T extends t.Node>(\n this: NodePath<T>,\n opts?: object,\n ): this is NodePath<T & VirtualTypeAliases[\"ReferencedMemberExpression\"]>;\n isRestProperty<T extends t.Node>(\n this: NodePath<T>,\n opts?: object,\n ): this is NodePath<T & t.RestProperty>;\n isScope<T extends t.Node>(\n this: NodePath<T>,\n opts?: object,\n ): this is NodePath<T & VirtualTypeAliases[\"Scope\"]>;\n isSpreadProperty<T extends t.Node>(\n this: NodePath<T>,\n opts?: object,\n ): this is NodePath<T & t.SpreadProperty>;\n isStatement<T extends t.Node>(\n this: NodePath<T>,\n opts?: object,\n ): this is NodePath<T & t.Statement>;\n isUser(opts?: object): boolean;\n isVar<T extends t.Node>(\n this: NodePath<T>,\n opts?: object,\n ): this is NodePath<T & VirtualTypeAliases[\"Var\"]>;\n}\n\nexport function isReferencedIdentifier(this: NodePath, opts?: any): boolean {\n const { node, parent } = this;\n if (!isIdentifier(node, opts) && !isJSXMemberExpression(parent, opts)) {\n if (isJSXIdentifier(node, opts)) {\n if (isCompatTag(node.name)) return false;\n } else {\n // not a JSXIdentifier or an Identifier\n return false;\n }\n }\n\n // check if node is referenced\n return nodeIsReferenced(node, parent, this.parentPath.parent);\n}\n\nexport function isReferencedMemberExpression(this: NodePath): boolean {\n const { node, parent } = this;\n return isMemberExpression(node) && nodeIsReferenced(node, parent);\n}\n\nexport function isBindingIdentifier(this: NodePath): boolean {\n const { node, parent } = this;\n const grandparent = this.parentPath.parent;\n return isIdentifier(node) && isBinding(node, parent, grandparent);\n}\n\nexport function isStatement(this: NodePath): boolean {\n const { node, parent } = this;\n if (nodeIsStatement(node)) {\n if (isVariableDeclaration(node)) {\n if (isForXStatement(parent, { left: node })) return false;\n if (isForStatement(parent, { init: node })) return false;\n }\n\n return true;\n } else {\n return false;\n }\n}\n\nexport function isExpression(this: NodePath): boolean {\n if (this.isIdentifier()) {\n return this.isReferencedIdentifier();\n } else {\n return nodeIsExpression(this.node);\n }\n}\n\nexport function isScope(this: NodePath): boolean {\n return nodeIsScope(this.node, this.parent);\n}\n\nexport function isReferenced(this: NodePath): boolean {\n return nodeIsReferenced(this.node, this.parent);\n}\n\nexport function isBlockScoped(this: NodePath): boolean {\n return nodeIsBlockScoped(this.node);\n}\n\nexport function isVar(this: NodePath): boolean {\n return nodeIsVar(this.node);\n}\n\nexport function isUser(this: NodePath): boolean {\n return this.node && !!this.node.loc;\n}\n\nexport function isGenerated(this: NodePath): boolean {\n return !this.isUser();\n}\n\nexport function isPure(this: NodePath, constantsOnly?: boolean): boolean {\n return this.scope.isPure(this.node, constantsOnly);\n}\n\nexport function isFlow(this: NodePath): boolean {\n const { node } = this;\n if (nodeIsFlow(node)) {\n return true;\n } else if (isImportDeclaration(node)) {\n return node.importKind === \"type\" || node.importKind === \"typeof\";\n } else if (isExportDeclaration(node)) {\n return node.exportKind === \"type\";\n } else if (isImportSpecifier(node)) {\n return node.importKind === \"type\" || node.importKind === \"typeof\";\n } else {\n return false;\n }\n}\n\n// TODO: 7.0 Backwards Compat\nexport function isRestProperty(this: NodePath): boolean {\n return (\n nodeIsRestElement(this.node) &&\n this.parentPath &&\n this.parentPath.isObjectPattern()\n );\n}\n\nexport function isSpreadProperty(this: NodePath): boolean {\n return (\n nodeIsRestElement(this.node) &&\n this.parentPath &&\n this.parentPath.isObjectExpression()\n );\n}\n\nexport function isForAwaitStatement(this: NodePath): boolean {\n return isForOfStatement(this.node, { await: true });\n}\n\nexport function isExistentialTypeParam(this: NodePath): void {\n throw new Error(\n \"`path.isExistentialTypeParam` has been renamed to `path.isExistsTypeAnnotation()` in Babel 7.\",\n );\n}\n\nexport function isNumericLiteralTypeAnnotation(this: NodePath): void {\n throw new Error(\n \"`path.isNumericLiteralTypeAnnotation()` has been renamed to `path.isNumberLiteralTypeAnnotation()` in Babel 7.\",\n );\n}\n"],"mappings":"AACA,YAAAA,EAAA,MAsBO,cAAc;AAAC;EArBpBC,S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e,IAAI,CAAC,IAC5B,IAAI,CAACG,UAAU,IACf,IAAI,CAACA,UAAU,CAACiB,kBAAkB,CAAC,CAAC;AAExC;AAEA,OAAO,SAASC,mBAAmBA,CAAA,EAA0B;EAC3D,OAAOzB,gBAAgB,CAAC,IAAI,CAACI,IAAI,EAAE;IAAEsB,KAAK,EAAE;EAAK,CAAC,CAAC;AACrD;AAEA,OAAO,SAASC,sBAAsBA,CAAA,EAAuB;EAC3D,MAAM,IAAIC,KAAK,CACb,+FACF,CAAC;AACH;AAEA,OAAO,SAASC,8BAA8BA,CAAA,EAAuB;EACnE,MAAM,IAAID,KAAK,CACb,gHACF,CAAC;AACH"}
|
1
|
+
{"version":3,"names":["_t","isBinding","isBlockScoped","nodeIsBlockScoped","isExportDeclaration","isExpression","nodeIsExpression","isFlow","nodeIsFlow","isForStatement","isForXStatement","isIdentifier","isImportDeclaration","isImportSpecifier","isJSXIdentifier","isJSXMemberExpression","isMemberExpression","isRestElement","nodeIsRestElement","isReferenced","nodeIsReferenced","isScope","nodeIsScope","isStatement","nodeIsStatement","isVar","nodeIsVar","isVariableDeclaration","react","isForOfStatement","isCompatTag","isReferencedIdentifier","opts","node","parent","name","parentPath","isReferencedMemberExpression","isBindingIdentifier","grandparent","left","init","isUser","loc","isGenerated","isPure","constantsOnly","scope","importKind","exportKind","isRestProperty","isObjectPattern","isSpreadProperty","isObjectExpression","isForAwaitStatement","await"],"sources":["../../../src/path/lib/virtual-types-validator.ts"],"sourcesContent":["import type NodePath from \"../index\";\nimport {\n isBinding,\n isBlockScoped as nodeIsBlockScoped,\n isExportDeclaration,\n isExpression as nodeIsExpression,\n isFlow as nodeIsFlow,\n isForStatement,\n isForXStatement,\n isIdentifier,\n isImportDeclaration,\n isImportSpecifier,\n isJSXIdentifier,\n isJSXMemberExpression,\n isMemberExpression,\n isRestElement as nodeIsRestElement,\n isReferenced as nodeIsReferenced,\n isScope as nodeIsScope,\n isStatement as nodeIsStatement,\n isVar as nodeIsVar,\n isVariableDeclaration,\n react,\n isForOfStatement,\n} from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nconst { isCompatTag } = react;\nimport type { VirtualTypeAliases } from \"./virtual-types\";\n\ntype Opts<Obj> = Partial<{\n [Prop in keyof Obj]: Obj[Prop] extends t.Node\n ? t.Node\n : Obj[Prop] extends t.Node[]\n ? t.Node[]\n : Obj[Prop];\n}>;\n\nexport interface VirtualTypeNodePathValidators {\n isBindingIdentifier<T extends t.Node>(\n this: NodePath<T>,\n opts?: Opts<VirtualTypeAliases[\"BindingIdentifier\"]>,\n ): this is NodePath<T & VirtualTypeAliases[\"BindingIdentifier\"]>;\n isBlockScoped(opts?: Opts<VirtualTypeAliases[\"BlockScoped\"]>): boolean;\n /**\n * @deprecated\n */\n isExistentialTypeParam<T extends t.Node>(\n this: NodePath<T>,\n opts?: Opts<VirtualTypeAliases[\"ExistentialTypeParam\"]>,\n ): this is NodePath<T & VirtualTypeAliases[\"ExistentialTypeParam\"]>;\n isExpression<T extends t.Node>(\n this: NodePath<T>,\n opts?: Opts<VirtualTypeAliases[\"Expression\"]>,\n ): this is NodePath<T & t.Expression>;\n isFlow<T extends t.Node>(\n this: NodePath<T>,\n opts?: Opts<VirtualTypeAliases[\"Flow\"]>,\n ): this is NodePath<T & t.Flow>;\n isForAwaitStatement<T extends t.Node>(\n this: NodePath<T>,\n opts?: Opts<VirtualTypeAliases[\"ForAwaitStatement\"]>,\n ): this is NodePath<T & VirtualTypeAliases[\"ForAwaitStatement\"]>;\n isGenerated(opts?: VirtualTypeAliases[\"Generated\"]): boolean;\n /**\n * @deprecated\n */\n isNumericLiteralTypeAnnotation(\n opts?: VirtualTypeAliases[\"NumericLiteralTypeAnnotation\"],\n ): void;\n isPure(opts?: VirtualTypeAliases[\"Pure\"]): boolean;\n isReferenced(opts?: VirtualTypeAliases[\"Referenced\"]): boolean;\n isReferencedIdentifier<T extends t.Node>(\n this: NodePath<T>,\n opts?: Opts<VirtualTypeAliases[\"ReferencedIdentifier\"]>,\n ): this is NodePath<T & VirtualTypeAliases[\"ReferencedIdentifier\"]>;\n isReferencedMemberExpression<T extends t.Node>(\n this: NodePath<T>,\n opts?: Opts<VirtualTypeAliases[\"ReferencedMemberExpression\"]>,\n ): this is NodePath<T & VirtualTypeAliases[\"ReferencedMemberExpression\"]>;\n isRestProperty<T extends t.Node>(\n this: NodePath<T>,\n opts?: Opts<VirtualTypeAliases[\"RestProperty\"]>,\n ): this is NodePath<T & t.RestProperty>;\n isScope<T extends t.Node>(\n this: NodePath<T>,\n opts?: Opts<VirtualTypeAliases[\"Scope\"]>,\n ): this is NodePath<T & VirtualTypeAliases[\"Scope\"]>;\n isSpreadProperty<T extends t.Node>(\n this: NodePath<T>,\n opts?: Opts<VirtualTypeAliases[\"SpreadProperty\"]>,\n ): this is NodePath<T & t.SpreadProperty>;\n isStatement<T extends t.Node>(\n this: NodePath<T>,\n opts?: Opts<VirtualTypeAliases[\"Statement\"]>,\n ): this is NodePath<T & t.Statement>;\n isUser(opts?: VirtualTypeAliases[\"User\"]): boolean;\n isVar<T extends t.Node>(\n this: NodePath<T>,\n opts?: Opts<VirtualTypeAliases[\"Var\"]>,\n ): this is NodePath<T & VirtualTypeAliases[\"Var\"]>;\n}\n\nexport function isReferencedIdentifier(this: NodePath, opts?: any): boolean {\n const { node, parent } = this;\n if (!isIdentifier(node, opts) && !isJSXMemberExpression(parent, opts)) {\n if (isJSXIdentifier(node, opts)) {\n if (isCompatTag(node.name)) return false;\n } else {\n // not a JSXIdentifier or an Identifier\n return false;\n }\n }\n\n // check if node is referenced\n return nodeIsReferenced(node, parent, this.parentPath.parent);\n}\n\nexport function isReferencedMemberExpression(this: NodePath): boolean {\n const { node, parent } = this;\n return isMemberExpression(node) && nodeIsReferenced(node, parent);\n}\n\nexport function isBindingIdentifier(this: NodePath): boolean {\n const { node, parent } = this;\n const grandparent = this.parentPath.parent;\n return isIdentifier(node) && isBinding(node, parent, grandparent);\n}\n\nexport function isStatement(this: NodePath): boolean {\n const { node, parent } = this;\n if (nodeIsStatement(node)) {\n if (isVariableDeclaration(node)) {\n if (isForXStatement(parent, { left: node })) return false;\n if (isForStatement(parent, { init: node })) return false;\n }\n\n return true;\n } else {\n return false;\n }\n}\n\nexport function isExpression(this: NodePath): boolean {\n if (this.isIdentifier()) {\n return this.isReferencedIdentifier();\n } else {\n return nodeIsExpression(this.node);\n }\n}\n\nexport function isScope(this: NodePath): boolean {\n return nodeIsScope(this.node, this.parent);\n}\n\nexport function isReferenced(this: NodePath): boolean {\n return nodeIsReferenced(this.node, this.parent);\n}\n\nexport function isBlockScoped(this: NodePath): boolean {\n return nodeIsBlockScoped(this.node);\n}\n\nexport function isVar(this: NodePath): boolean {\n return nodeIsVar(this.node);\n}\n\nexport function isUser(this: NodePath): boolean {\n return this.node && !!this.node.loc;\n}\n\nexport function isGenerated(this: NodePath): boolean {\n return !this.isUser();\n}\n\nexport function isPure(this: NodePath, constantsOnly?: boolean): boolean {\n return this.scope.isPure(this.node, constantsOnly);\n}\n\nexport function isFlow(this: NodePath): boolean {\n const { node } = this;\n if (nodeIsFlow(node)) {\n return true;\n } else if (isImportDeclaration(node)) {\n return node.importKind === \"type\" || node.importKind === \"typeof\";\n } else if (isExportDeclaration(node)) {\n return node.exportKind === \"type\";\n } else if (isImportSpecifier(node)) {\n return node.importKind === \"type\" || node.importKind === \"typeof\";\n } else {\n return false;\n }\n}\n\n// TODO: 7.0 Backwards Compat\nexport function isRestProperty(this: NodePath): boolean {\n return (\n nodeIsRestElement(this.node) &&\n this.parentPath &&\n this.parentPath.isObjectPattern()\n );\n}\n\nexport function isSpreadProperty(this: NodePath): boolean {\n return (\n nodeIsRestElement(this.node) &&\n this.parentPath &&\n this.parentPath.isObjectExpression()\n );\n}\n\nexport function isForAwaitStatement(this: NodePath): boolean {\n return isForOfStatement(this.node, { await: true });\n}\n\nif (!process.env.BABEL_8_BREAKING) {\n if (!USE_ESM) {\n // eslint-disable-next-line no-restricted-globals\n exports.isExistentialTypeParam = function isExistentialTypeParam(\n this: NodePath,\n ): void {\n throw new Error(\n \"`path.isExistentialTypeParam` has been renamed to `path.isExistsTypeAnnotation()` in Babel 7.\",\n );\n };\n\n // eslint-disable-next-line no-restricted-globals\n exports.isNumericLiteralTypeAnnotation =\n function isNumericLiteralTypeAnnotation(this: NodePath): void {\n throw new Error(\n \"`path.isNumericLiteralTypeAnnotation()` has been renamed to `path.isNumberLiteralTypeAnnotation()` in Babel 7.\",\n );\n };\n }\n}\n"],"mappings":"AACA,YAAAA,EAAA,MAsBO,cAAc;AAAC;EArBpBC,SAAS;EACTC,aAAa,EAAIC,iBAAiB;EAClCC,mBAAmB;EACnBC,YAAY,EAAIC,gBAAgB;EAChCC,MAAM,EAAIC,UAAU;EACpBC,cAAc;EACdC,eAAe;EACfC,YAAY;EACZC,mBAAmB;EACnBC,iBAAiB;EACjBC,eAAe;EACfC,qBAAqB;EACrBC,kBAAkB;EAClBC,aAAa,EAAIC,iBAAiB;EAClCC,YAAY,EAAIC,gBAAgB;EAChCC,OAAO,EAAIC,WAAW;EACtBC,WAAW,EAAIC,eAAe;EAC9BC,KAAK,EAAIC,SAAS;EAClBC,qBAAqB;EACrBC,KAAK;EACLC;AAAgB,IAAA7B,EAAA;AAGlB,MAAM;EAAE8B;AAAY,CAAC,GAAGF,KAAK;AA4E7B,OAAO,SAASG,sBAAsBA,CAAiBC,IAAU,EAAW;EAC1E,MAAM;IAAEC,IAAI;IAAEC;EAAO,CAAC,GAAG,IAAI;EAC7B,IAAI,CAACvB,YAAY,CAACsB,IAAI,EAAED,IAAI,CAAC,IAAI,CAACjB,qBAAqB,CAACmB,MAAM,EAAEF,IAAI,CAAC,EAAE;IACrE,IAAIlB,eAAe,CAACmB,IAAI,EAAED,IAAI,CAAC,EAAE;MAC/B,IAAIF,WAAW,CAACG,IAAI,CAACE,IAAI,CAAC,EAAE,OAAO,KAAK;IAC1C,CAAC,MAAM;MAEL,OAAO,KAAK;IACd;EACF;EAGA,OAAOf,gBAAgB,CAACa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ACe,UAAU,KAAK,MAAM,IAAIf,IAAI,CAACe,UAAU,KAAK,QAAQ;EACnE,CAAC,MAAM;IACL,OAAO,KAAK;EACd;AACF;AAGA,OAAO,SAASE,cAAcA,CAAA,EAA0B;EACtD,OACEhC,iBAAiB,CAAC,IAAI,CAACe,IAAI,CAAC,IAC5B,IAAI,CAACG,UAAU,IACf,IAAI,CAACA,UAAU,CAACe,eAAe,CAAC,CAAC;AAErC;AAEA,OAAO,SAASC,gBAAgBA,CAAA,EAA0B;EACxD,OACElC,iBAAiB,CAAC,IAAI,CAACe,IAAI,CAAC,IAC5B,IAAI,CAACG,UAAU,IACf,IAAI,CAACA,UAAU,CAACiB,kBAAkB,CAAC,CAAC;AAExC;AAEA,OAAO,SAASC,mBAAmBA,CAAA,EAA0B;EAC3D,OAAOzB,gBAAgB,CAAC,IAAI,CAACI,IAAI,EAAE;IAAEsB,KAAK,EAAE;EAAK,CAAC,CAAC;AACrD;AAAC"}
|
package/lib/path/modification.js
CHANGED
@@ -1,4 +1,4 @@
|
|
1
|
-
import {
|
1
|
+
import { getCachedPaths } from "../cache.js";
|
2
2
|
import PathHoister from "./lib/hoister.js";
|
3
3
|
import NodePath from "./index.js";
|
4
4
|
import * as _t from "@babel/types";
|
@@ -143,7 +143,7 @@ export function insertAfter(nodes_) {
|
|
143
143
|
}
|
144
144
|
export function updateSiblingKeys(fromIndex, incrementBy) {
|
145
145
|
if (!this.parent) return;
|
146
|
-
const paths =
|
146
|
+
const paths = getCachedPaths(this.hub, this.parent) || [];
|
147
147
|
for (const [, path] of paths) {
|
148
148
|
if (typeof path.key === "number" && path.key >= fromIndex) {
|
149
149
|
path.key += incrementBy;
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"names":["path","pathCache","PathHoister","NodePath","_t","arrowFunctionExpression","assertExpression","assignmentExpression","blockStatement","callExpression","cloneNode","expressionStatement","isAssignmentExpression","isCallExpression","isExportNamedDeclaration","isExpression","isIdentifier","isSequenceExpression","isSuper","thisExpression","insertBefore","nodes_","_assertUnremoved","nodes","_verifyNodeList","parentPath","parent","isExpressionStatement","isLabeledStatement","isExportDefaultDeclaration","isDeclaration","isNodeType","isJSXElement","isForStatement","key","node","push","replaceExpressionWithStatements","Array","isArray","container","_containerInsertBefore","isStatementOrBlock","shouldInsertCurrentNode","expression","replaceWith","unshiftContainer","Error","_containerInsert","from","updateSiblingKeys","length","paths","splice","i","to","getSibling","context","queue","pushContext","contexts","_getQueueContexts","setScope","debug","maybeQueue","_containerInsertAfter","last","arr","isHiddenInSequenceExpression","expressions","isAlmostConstantAssignment","scope","left","blockScope","getBlockParent","hasOwnBinding","name","getOwnBinding","constantViolations","insertAfter","get","map","isPattern","unshift","callee","isPure","isMethod","computed","temp","generateDeclaredUidIdentifier","pushContainer","fromIndex","incrementBy","msg","type","listKey","setContext","verifiedNodes","replaceWithMultiple","hoist","hoister","run"],"sources":["../../src/path/modification.ts"],"sourcesContent":["// This file contains methods that modify the path/node in some ways.\n\nimport { path as pathCache } from \"../cache\";\nimport PathHoister from \"./lib/hoister\";\nimport NodePath from \"./index\";\nimport {\n arrowFunctionExpression,\n assertExpression,\n assignmentExpression,\n blockStatement,\n callExpression,\n cloneNode,\n expressionStatement,\n isAssignmentExpression,\n isCallExpression,\n isExportNamedDeclaration,\n isExpression,\n isIdentifier,\n isSequenceExpression,\n isSuper,\n thisExpression,\n} from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nimport type Scope from \"../scope\";\n\n/**\n * Insert the provided nodes before the current one.\n */\n\nexport function insertBefore(\n this: NodePath,\n nodes_: t.Node | t.Node[],\n): NodePath[] {\n this._assertUnremoved();\n\n const nodes = this._verifyNodeList(nodes_);\n\n const { parentPath, parent } = this;\n\n if (\n parentPath.isExpressionStatement() ||\n parentPath.isLabeledStatement() ||\n // https://github.com/babel/babel/issues/15293\n // When Babel transforms `export class String { field }`, the class properties plugin will inject the defineProperty\n // helper, which depends on the builtins e.g. String, Number, Symbol, etc. To prevent them from being shadowed by local\n // exports, the helper injector replaces the named export into `class _String { field }; export { _String as String }`,\n // with `parentPath` here changed to the moved ClassDeclaration, causing rare inconsistency between `parent` and `parentPath`.\n // Here we retrieve the parent type from the `parent` property. This is a temporary fix and we should revisit when\n // helpers should get injected.\n isExportNamedDeclaration(parent) ||\n (parentPath.isExportDefaultDeclaration() && this.isDeclaration())\n ) {\n return parentPath.insertBefore(nodes);\n } else if (\n (this.isNodeType(\"Expression\") && !this.isJSXElement()) ||\n (parentPath.isForStatement() && this.key === \"init\")\n ) {\n if (this.node) nodes.push(this.node);\n // @ts-expect-error todo(flow->ts): check that nodes is an array of statements\n return this.replaceExpressionWithStatements(nodes);\n } else if (Array.isArray(this.container)) {\n return this._containerInsertBefore(nodes);\n } else if (this.isStatementOrBlock()) {\n const node = this.node as t.Statement;\n const shouldInsertCurrentNode =\n node &&\n (!this.isExpressionStatement() ||\n (node as t.ExpressionStatement).expression != null);\n\n this.replaceWith(blockStatement(shouldInsertCurrentNode ? [node] : []));\n return (this as NodePath<t.BlockStatement>).unshiftContainer(\n \"body\",\n // @ts-expect-error Fixme: refine nodes to t.BlockStatement[\"body\"] when this is a BlockStatement path\n nodes,\n );\n } else {\n throw new Error(\n \"We don't know what to do with this node type. \" +\n \"We were previously a Statement but we can't fit in here?\",\n );\n }\n}\n\nexport function _containerInsert<N extends t.Node>(\n this: NodePath,\n from: number,\n nodes: N[],\n): NodePath<N>[] {\n this.updateSiblingKeys(from, nodes.length);\n\n const paths: NodePath<N>[] = [];\n\n // @ts-expect-error todo(flow->ts): this.container could be a NodePath\n this.container.splice(from, 0, ...nodes);\n for (let i = 0; i < nodes.length; i++) {\n const to = from + i;\n const path = this.getSibling(to) as NodePath<N>;\n paths.push(path);\n\n if (this.context?.queue) {\n path.pushContext(this.context);\n }\n }\n\n const contexts = this._getQueueContexts();\n\n for (const path of paths) {\n path.setScope();\n path.debug(\"Inserted.\");\n\n for (const context of contexts) {\n context.maybeQueue(path, true);\n }\n }\n\n return paths;\n}\n\nexport function _containerInsertBefore<N extends t.Node>(\n this: NodePath,\n nodes: N[],\n) {\n return this._containerInsert(this.key as number, nodes);\n}\n\nexport function _containerInsertAfter<N extends t.Node>(\n this: NodePath,\n nodes: N[],\n) {\n return this._containerInsert((this.key as number) + 1, nodes);\n}\n\nconst last = <T>(arr: T[]) => arr[arr.length - 1];\n\nfunction isHiddenInSequenceExpression(path: NodePath): boolean {\n return (\n isSequenceExpression(path.parent) &&\n (last(path.parent.expressions) !== path.node ||\n isHiddenInSequenceExpression(path.parentPath))\n );\n}\n\nfunction isAlmostConstantAssignment(\n node: t.Node,\n scope: Scope,\n): node is t.AssignmentExpression & { left: t.Identifier } {\n if (!isAssignmentExpression(node) || !isIdentifier(node.left)) {\n return false;\n }\n\n // Not every scope can contain variables. For example, we might be in\n // a ClassScope either in the ClassHeritage or in a computed key.\n const blockScope = scope.getBlockParent();\n\n // If the variable is defined in the current scope and only assigned here,\n // we can be sure that its value won't change.\n return (\n blockScope.hasOwnBinding(node.left.name) &&\n blockScope.getOwnBinding(node.left.name).constantViolations.length <= 1\n );\n}\n\n/**\n * Insert the provided nodes after the current one. When inserting nodes after an\n * expression, ensure that the completion record is correct by pushing the current node.\n */\n\nexport function insertAfter(\n this: NodePath,\n nodes_: t.Node | t.Node[],\n): NodePath[] {\n this._assertUnremoved();\n\n if (this.isSequenceExpression()) {\n return last(this.get(\"expressions\")).insertAfter(nodes_);\n }\n\n const nodes = this._verifyNodeList(nodes_);\n\n const { parentPath, parent } = this;\n if (\n parentPath.isExpressionStatement() ||\n parentPath.isLabeledStatement() ||\n // see insertBefore\n isExportNamedDeclaration(parent) ||\n (parentPath.isExportDefaultDeclaration() && this.isDeclaration())\n ) {\n return parentPath.insertAfter(\n nodes.map(node => {\n // Usually after an expression we can safely insert another expression:\n // A.insertAfter(B)\n // foo = A; -> foo = (A, B);\n // If A is an expression statement, it isn't safe anymore so we need to\n // convert B to an expression statement\n // A; -> A; B // No semicolon! It could break if followed by [!\n return isExpression(node) ? expressionStatement(node) : node;\n }),\n );\n } else if (\n (this.isNodeType(\"Expression\") &&\n !this.isJSXElement() &&\n !parentPath.isJSXElement()) ||\n (parentPath.isForStatement() && this.key === \"init\")\n ) {\n if (this.node) {\n const node = this.node as t.Expression | t.VariableDeclaration;\n let { scope } = this;\n\n if (scope.path.isPattern()) {\n assertExpression(node);\n\n this.replaceWith(callExpression(arrowFunctionExpression([], node), []));\n (this.get(\"callee.body\") as NodePath<t.Expression>).insertAfter(nodes);\n return [this];\n }\n\n if (isHiddenInSequenceExpression(this)) {\n nodes.unshift(node);\n }\n // We need to preserve the value of this expression.\n else if (isCallExpression(node) && isSuper(node.callee)) {\n nodes.unshift(node);\n // `super(...)` always evaluates to `this`.\n nodes.push(thisExpression());\n } else if (isAlmostConstantAssignment(node, scope)) {\n nodes.unshift(node);\n nodes.push(cloneNode(node.left));\n } else if (scope.isPure(node, true)) {\n // Insert the nodes before rather than after; it's not observable.\n nodes.push(node);\n } else {\n // Inserting after the computed key of a method should insert the\n // temporary binding in the method's parent's scope.\n if (parentPath.isMethod({ computed: true, key: node })) {\n scope = scope.parent;\n }\n const temp = scope.generateDeclaredUidIdentifier();\n nodes.unshift(\n expressionStatement(\n // @ts-expect-error todo(flow->ts): This can be a variable\n // declaration in the \"init\" of a for statement, but that's\n // invalid here.\n assignmentExpression(\"=\", cloneNode(temp), node),\n ),\n );\n nodes.push(expressionStatement(cloneNode(temp)));\n }\n }\n // @ts-expect-error todo(flow->ts): check that nodes is an array of statements\n return this.replaceExpressionWithStatements(nodes);\n } else if (Array.isArray(this.container)) {\n return this._containerInsertAfter(nodes);\n } else if (this.isStatementOrBlock()) {\n const node = this.node as t.Statement;\n const shouldInsertCurrentNode =\n node &&\n (!this.isExpressionStatement() ||\n (node as t.ExpressionStatement).expression != null);\n\n this.replaceWith(blockStatement(shouldInsertCurrentNode ? [node] : []));\n // @ts-expect-error Fixme: refine nodes to t.BlockStatement[\"body\"] when this is a BlockStatement path\n return this.pushContainer(\"body\", nodes);\n } else {\n throw new Error(\n \"We don't know what to do with this node type. \" +\n \"We were previously a Statement but we can't fit in here?\",\n );\n }\n}\n\n/**\n * Update all sibling node paths after `fromIndex` by `incrementBy`.\n */\n\nexport function updateSiblingKeys(\n this: NodePath,\n fromIndex: number,\n incrementBy: number,\n) {\n if (!this.parent) return;\n\n const paths = pathCache.get(this.parent);\n\n for (const [, path] of paths) {\n if (typeof path.key === \"number\" && path.key >= fromIndex) {\n path.key += incrementBy;\n }\n }\n}\n\nexport function _verifyNodeList<N extends t.Node>(\n this: NodePath,\n nodes: N | N[],\n): N[] {\n if (!nodes) {\n return [];\n }\n\n if (!Array.isArray(nodes)) {\n nodes = [nodes];\n }\n\n for (let i = 0; i < nodes.length; i++) {\n const node = nodes[i];\n let msg;\n\n if (!node) {\n msg = \"has falsy node\";\n } else if (typeof node !== \"object\") {\n msg = \"contains a non-object node\";\n } else if (!node.type) {\n msg = \"without a type\";\n } else if (node instanceof NodePath) {\n msg = \"has a NodePath when it expected a raw object\";\n }\n\n if (msg) {\n const type = Array.isArray(node) ? \"array\" : typeof node;\n throw new Error(\n `Node list ${msg} with the index of ${i} and type of ${type}`,\n );\n }\n }\n\n return nodes;\n}\n\nexport function unshiftContainer<N extends t.Node, K extends keyof N & string>(\n this: NodePath<N>,\n listKey: K,\n nodes: N[K] extends (infer E)[]\n ? E | E[]\n : // todo: refine to t.Node[]\n // ? E extends t.Node\n // ? E | E[]\n // : never\n never,\n) {\n // todo: NodePaths<Nodes>\n this._assertUnremoved();\n\n // @ts-expect-error fixme\n nodes = this._verifyNodeList(nodes);\n\n // get the first path and insert our nodes before it, if it doesn't exist then it\n // doesn't matter, our nodes will be inserted anyway\n const path = NodePath.get({\n parentPath: this,\n parent: this.node,\n container: this.node[listKey] as unknown as t.Node | t.Node[],\n listKey,\n key: 0,\n }).setContext(this.context);\n\n return path._containerInsertBefore(\n // @ts-expect-error typings needed to narrow down nodes as t.Node[]\n nodes,\n );\n}\n\nexport function pushContainer<N extends t.Node, K extends keyof N & string>(\n this: NodePath<N>,\n listKey: K,\n nodes: N[K] extends (infer E)[]\n ? E | E[]\n : // todo: refine to t.Node[]\n // ? E extends t.Node\n // ? E | E[]\n // : never\n never,\n) {\n this._assertUnremoved();\n\n const verifiedNodes = this._verifyNodeList(\n // @ts-expect-error refine typings\n nodes,\n );\n\n // get an invisible path that represents the last node + 1 and replace it with our\n // nodes, effectively inlining it\n\n const container = this.node[listKey];\n const path = NodePath.get({\n parentPath: this,\n parent: this.node,\n container: container as unknown as t.Node | t.Node[],\n listKey,\n // @ts-expect-error TS cannot infer that container is t.Node[]\n key: container.length,\n }).setContext(this.context);\n\n return path.replaceWithMultiple(verifiedNodes);\n}\n\n/**\n * Hoist the current node to the highest scope possible and return a UID\n * referencing it.\n */\nexport function hoist<T extends t.Node>(\n this: NodePath<T>,\n scope: Scope = this.scope,\n) {\n const hoister = new PathHoister<T>(this, scope);\n return hoister.run();\n}\n"],"mappings":"AAEA,SAASA,IAAI,IAAIC,SAAS,QAAQ,aAAU;AAC5C,OAAOC,WAAW,MAAM,kBAAe;AACvC,OAAOC,QAAQ,MAAM,YAAS;AAC9B,YAAAC,EAAA,MAgBO,cAAc;AAAC;EAfpBC,uBAAuB;EACvBC,gBAAgB;EAChBC,oBAAoB;EACpBC,cAAc;EACdC,cAAc;EACdC,SAAS;EACTC,mBAAmB;EACnBC,sBAAsB;EACtBC,gBAAgB;EAChBC,wBAAwB;EACxBC,YAAY;EACZC,YAAY;EACZC,oBAAoB;EACpBC,OAAO;EACPC;AAAc,IAAAf,EAAA;AAShB,OAAO,SAASgB,YAAYA,CAE1BC,MAAyB,EACb;EACZ,IAAI,CAACC,gBAAgB,CAAC,CAAC;EAEvB,MAAMC,KAAK,GAAG,IAAI,CAACC,eAAe,CAACH,MAAM,CAAC;EAE1C,MAAM;IAAEI,UAAU;IAAEC;EAAO,CAAC,GAAG,IAAI;EAEnC,IACED,UAAU,CAACE,qBAAqB,CAAC,CAAC,IAClCF,UAAU,CAACG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AAyC;IACpDuD,OAAO;IAEP7D,GAAG,EAAEM,SAAS,CAACW;EACjB,CAAC,CAAC,CAAC6C,UAAU,CAAC,IAAI,CAACvC,OAAO,CAAC;EAE3B,OAAOzD,IAAI,CAACkG,mBAAmB,CAACD,aAAa,CAAC;AAChD;AAMA,OAAO,SAASE,KAAKA,CAEnB5B,KAAY,GAAG,IAAI,CAACA,KAAK,EACzB;EACA,MAAM6B,OAAO,GAAG,IAAIlG,WAAW,CAAI,IAAI,EAAEqE,KAAK,CAAC;EAC/C,OAAO6B,OAAO,CAACC,GAAG,CAAC,CAAC;AACtB"}
|
1
|
+
{"version":3,"names":["getCachedPaths","PathHoister","NodePath","_t","arrowFunctionExpression","assertExpression","assignmentExpression","blockStatement","callExpression","cloneNode","expressionStatement","isAssignmentExpression","isCallExpression","isExportNamedDeclaration","isExpression","isIdentifier","isSequenceExpression","isSuper","thisExpression","insertBefore","nodes_","_assertUnremoved","nodes","_verifyNodeList","parentPath","parent","isExpressionStatement","isLabeledStatement","isExportDefaultDeclaration","isDeclaration","isNodeType","isJSXElement","isForStatement","key","node","push","replaceExpressionWithStatements","Array","isArray","container","_containerInsertBefore","isStatementOrBlock","shouldInsertCurrentNode","expression","replaceWith","unshiftContainer","Error","_containerInsert","from","updateSiblingKeys","length","paths","splice","i","to","path","getSibling","context","queue","pushContext","contexts","_getQueueContexts","setScope","debug","maybeQueue","_containerInsertAfter","last","arr","isHiddenInSequenceExpression","expressions","isAlmostConstantAssignment","scope","left","blockScope","getBlockParent","hasOwnBinding","name","getOwnBinding","constantViolations","insertAfter","get","map","isPattern","unshift","callee","isPure","isMethod","computed","temp","generateDeclaredUidIdentifier","pushContainer","fromIndex","incrementBy","hub","msg","type","listKey","setContext","verifiedNodes","replaceWithMultiple","hoist","hoister","run"],"sources":["../../src/path/modification.ts"],"sourcesContent":["// This file contains methods that modify the path/node in some ways.\n\nimport { getCachedPaths } from \"../cache\";\nimport PathHoister from \"./lib/hoister\";\nimport NodePath from \"./index\";\nimport {\n arrowFunctionExpression,\n assertExpression,\n assignmentExpression,\n blockStatement,\n callExpression,\n cloneNode,\n expressionStatement,\n isAssignmentExpression,\n isCallExpression,\n isExportNamedDeclaration,\n isExpression,\n isIdentifier,\n isSequenceExpression,\n isSuper,\n thisExpression,\n} from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nimport type Scope from \"../scope\";\n\n/**\n * Insert the provided nodes before the current one.\n */\n\nexport function insertBefore(\n this: NodePath,\n nodes_: t.Node | t.Node[],\n): NodePath[] {\n this._assertUnremoved();\n\n const nodes = this._verifyNodeList(nodes_);\n\n const { parentPath, parent } = this;\n\n if (\n parentPath.isExpressionStatement() ||\n parentPath.isLabeledStatement() ||\n // https://github.com/babel/babel/issues/15293\n // When Babel transforms `export class String { field }`, the class properties plugin will inject the defineProperty\n // helper, which depends on the builtins e.g. String, Number, Symbol, etc. To prevent them from being shadowed by local\n // exports, the helper injector replaces the named export into `class _String { field }; export { _String as String }`,\n // with `parentPath` here changed to the moved ClassDeclaration, causing rare inconsistency between `parent` and `parentPath`.\n // Here we retrieve the parent type from the `parent` property. This is a temporary fix and we should revisit when\n // helpers should get injected.\n isExportNamedDeclaration(parent) ||\n (parentPath.isExportDefaultDeclaration() && this.isDeclaration())\n ) {\n return parentPath.insertBefore(nodes);\n } else if (\n (this.isNodeType(\"Expression\") && !this.isJSXElement()) ||\n (parentPath.isForStatement() && this.key === \"init\")\n ) {\n if (this.node) nodes.push(this.node);\n // @ts-expect-error todo(flow->ts): check that nodes is an array of statements\n return this.replaceExpressionWithStatements(nodes);\n } else if (Array.isArray(this.container)) {\n return this._containerInsertBefore(nodes);\n } else if (this.isStatementOrBlock()) {\n const node = this.node as t.Statement;\n const shouldInsertCurrentNode =\n node &&\n (!this.isExpressionStatement() ||\n (node as t.ExpressionStatement).expression != null);\n\n this.replaceWith(blockStatement(shouldInsertCurrentNode ? [node] : []));\n return (this as NodePath<t.BlockStatement>).unshiftContainer(\n \"body\",\n // @ts-expect-error Fixme: refine nodes to t.BlockStatement[\"body\"] when this is a BlockStatement path\n nodes,\n );\n } else {\n throw new Error(\n \"We don't know what to do with this node type. \" +\n \"We were previously a Statement but we can't fit in here?\",\n );\n }\n}\n\nexport function _containerInsert<N extends t.Node>(\n this: NodePath,\n from: number,\n nodes: N[],\n): NodePath<N>[] {\n this.updateSiblingKeys(from, nodes.length);\n\n const paths: NodePath<N>[] = [];\n\n // @ts-expect-error todo(flow->ts): this.container could be a NodePath\n this.container.splice(from, 0, ...nodes);\n for (let i = 0; i < nodes.length; i++) {\n const to = from + i;\n const path = this.getSibling(to) as NodePath<N>;\n paths.push(path);\n\n if (this.context?.queue) {\n path.pushContext(this.context);\n }\n }\n\n const contexts = this._getQueueContexts();\n\n for (const path of paths) {\n path.setScope();\n path.debug(\"Inserted.\");\n\n for (const context of contexts) {\n context.maybeQueue(path, true);\n }\n }\n\n return paths;\n}\n\nexport function _containerInsertBefore<N extends t.Node>(\n this: NodePath,\n nodes: N[],\n) {\n return this._containerInsert(this.key as number, nodes);\n}\n\nexport function _containerInsertAfter<N extends t.Node>(\n this: NodePath,\n nodes: N[],\n) {\n return this._containerInsert((this.key as number) + 1, nodes);\n}\n\nconst last = <T>(arr: T[]) => arr[arr.length - 1];\n\nfunction isHiddenInSequenceExpression(path: NodePath): boolean {\n return (\n isSequenceExpression(path.parent) &&\n (last(path.parent.expressions) !== path.node ||\n isHiddenInSequenceExpression(path.parentPath))\n );\n}\n\nfunction isAlmostConstantAssignment(\n node: t.Node,\n scope: Scope,\n): node is t.AssignmentExpression & { left: t.Identifier } {\n if (!isAssignmentExpression(node) || !isIdentifier(node.left)) {\n return false;\n }\n\n // Not every scope can contain variables. For example, we might be in\n // a ClassScope either in the ClassHeritage or in a computed key.\n const blockScope = scope.getBlockParent();\n\n // If the variable is defined in the current scope and only assigned here,\n // we can be sure that its value won't change.\n return (\n blockScope.hasOwnBinding(node.left.name) &&\n blockScope.getOwnBinding(node.left.name).constantViolations.length <= 1\n );\n}\n\n/**\n * Insert the provided nodes after the current one. When inserting nodes after an\n * expression, ensure that the completion record is correct by pushing the current node.\n */\n\nexport function insertAfter(\n this: NodePath,\n nodes_: t.Node | t.Node[],\n): NodePath[] {\n this._assertUnremoved();\n\n if (this.isSequenceExpression()) {\n return last(this.get(\"expressions\")).insertAfter(nodes_);\n }\n\n const nodes = this._verifyNodeList(nodes_);\n\n const { parentPath, parent } = this;\n if (\n parentPath.isExpressionStatement() ||\n parentPath.isLabeledStatement() ||\n // see insertBefore\n isExportNamedDeclaration(parent) ||\n (parentPath.isExportDefaultDeclaration() && this.isDeclaration())\n ) {\n return parentPath.insertAfter(\n nodes.map(node => {\n // Usually after an expression we can safely insert another expression:\n // A.insertAfter(B)\n // foo = A; -> foo = (A, B);\n // If A is an expression statement, it isn't safe anymore so we need to\n // convert B to an expression statement\n // A; -> A; B // No semicolon! It could break if followed by [!\n return isExpression(node) ? expressionStatement(node) : node;\n }),\n );\n } else if (\n (this.isNodeType(\"Expression\") &&\n !this.isJSXElement() &&\n !parentPath.isJSXElement()) ||\n (parentPath.isForStatement() && this.key === \"init\")\n ) {\n if (this.node) {\n const node = this.node as t.Expression | t.VariableDeclaration;\n let { scope } = this;\n\n if (scope.path.isPattern()) {\n assertExpression(node);\n\n this.replaceWith(callExpression(arrowFunctionExpression([], node), []));\n (this.get(\"callee.body\") as NodePath<t.Expression>).insertAfter(nodes);\n return [this];\n }\n\n if (isHiddenInSequenceExpression(this)) {\n nodes.unshift(node);\n }\n // We need to preserve the value of this expression.\n else if (isCallExpression(node) && isSuper(node.callee)) {\n nodes.unshift(node);\n // `super(...)` always evaluates to `this`.\n nodes.push(thisExpression());\n } else if (isAlmostConstantAssignment(node, scope)) {\n nodes.unshift(node);\n nodes.push(cloneNode(node.left));\n } else if (scope.isPure(node, true)) {\n // Insert the nodes before rather than after; it's not observable.\n nodes.push(node);\n } else {\n // Inserting after the computed key of a method should insert the\n // temporary binding in the method's parent's scope.\n if (parentPath.isMethod({ computed: true, key: node })) {\n scope = scope.parent;\n }\n const temp = scope.generateDeclaredUidIdentifier();\n nodes.unshift(\n expressionStatement(\n // @ts-expect-error todo(flow->ts): This can be a variable\n // declaration in the \"init\" of a for statement, but that's\n // invalid here.\n assignmentExpression(\"=\", cloneNode(temp), node),\n ),\n );\n nodes.push(expressionStatement(cloneNode(temp)));\n }\n }\n // @ts-expect-error todo(flow->ts): check that nodes is an array of statements\n return this.replaceExpressionWithStatements(nodes);\n } else if (Array.isArray(this.container)) {\n return this._containerInsertAfter(nodes);\n } else if (this.isStatementOrBlock()) {\n const node = this.node as t.Statement;\n const shouldInsertCurrentNode =\n node &&\n (!this.isExpressionStatement() ||\n (node as t.ExpressionStatement).expression != null);\n\n this.replaceWith(blockStatement(shouldInsertCurrentNode ? [node] : []));\n // @ts-expect-error Fixme: refine nodes to t.BlockStatement[\"body\"] when this is a BlockStatement path\n return this.pushContainer(\"body\", nodes);\n } else {\n throw new Error(\n \"We don't know what to do with this node type. \" +\n \"We were previously a Statement but we can't fit in here?\",\n );\n }\n}\n\n/**\n * Update all sibling node paths after `fromIndex` by `incrementBy`.\n */\n\nexport function updateSiblingKeys(\n this: NodePath,\n fromIndex: number,\n incrementBy: number,\n) {\n if (!this.parent) return;\n\n const paths = getCachedPaths(this.hub, this.parent) || ([] as never[]);\n\n for (const [, path] of paths) {\n if (typeof path.key === \"number\" && path.key >= fromIndex) {\n path.key += incrementBy;\n }\n }\n}\n\nexport function _verifyNodeList<N extends t.Node>(\n this: NodePath,\n nodes: N | N[],\n): N[] {\n if (!nodes) {\n return [];\n }\n\n if (!Array.isArray(nodes)) {\n nodes = [nodes];\n }\n\n for (let i = 0; i < nodes.length; i++) {\n const node = nodes[i];\n let msg;\n\n if (!node) {\n msg = \"has falsy node\";\n } else if (typeof node !== \"object\") {\n msg = \"contains a non-object node\";\n } else if (!node.type) {\n msg = \"without a type\";\n } else if (node instanceof NodePath) {\n msg = \"has a NodePath when it expected a raw object\";\n }\n\n if (msg) {\n const type = Array.isArray(node) ? \"array\" : typeof node;\n throw new Error(\n `Node list ${msg} with the index of ${i} and type of ${type}`,\n );\n }\n }\n\n return nodes;\n}\n\nexport function unshiftContainer<N extends t.Node, K extends keyof N & string>(\n this: NodePath<N>,\n listKey: K,\n nodes: N[K] extends (infer E)[]\n ? E | E[]\n : // todo: refine to t.Node[]\n // ? E extends t.Node\n // ? E | E[]\n // : never\n never,\n) {\n // todo: NodePaths<Nodes>\n this._assertUnremoved();\n\n // @ts-expect-error fixme\n nodes = this._verifyNodeList(nodes);\n\n // get the first path and insert our nodes before it, if it doesn't exist then it\n // doesn't matter, our nodes will be inserted anyway\n const path = NodePath.get({\n parentPath: this,\n parent: this.node,\n container: this.node[listKey] as unknown as t.Node | t.Node[],\n listKey,\n key: 0,\n }).setContext(this.context);\n\n return path._containerInsertBefore(\n // @ts-expect-error typings needed to narrow down nodes as t.Node[]\n nodes,\n );\n}\n\nexport function pushContainer<N extends t.Node, K extends keyof N & string>(\n this: NodePath<N>,\n listKey: K,\n nodes: N[K] extends (infer E)[]\n ? E | E[]\n : // todo: refine to t.Node[]\n // ? E extends t.Node\n // ? E | E[]\n // : never\n never,\n) {\n this._assertUnremoved();\n\n const verifiedNodes = this._verifyNodeList(\n // @ts-expect-error refine typings\n nodes,\n );\n\n // get an invisible path that represents the last node + 1 and replace it with our\n // nodes, effectively inlining it\n\n const container = this.node[listKey];\n const path = NodePath.get({\n parentPath: this,\n parent: this.node,\n container: container as unknown as t.Node | t.Node[],\n listKey,\n // @ts-expect-error TS cannot infer that container is t.Node[]\n key: container.length,\n }).setContext(this.context);\n\n return path.replaceWithMultiple(verifiedNodes);\n}\n\n/**\n * Hoist the current node to the highest scope possible and return a UID\n * referencing it.\n */\nexport function hoist<T extends t.Node>(\n this: NodePath<T>,\n scope: Scope = this.scope,\n) {\n const hoister = new PathHoister<T>(this, scope);\n return hoister.run();\n}\n"],"mappings":"AAEA,SAASA,cAAc,QAAQ,aAAU;AACzC,OAAOC,WAAW,MAAM,kBAA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BK,SAAS,EAAE,IAAI,CAACL,IAAI,CAAC8D,OAAO,CAAiC;IAC7DA,OAAO;IACP/D,GAAG,EAAE;EACP,CAAC,CAAC,CAACgE,UAAU,CAAC,IAAI,CAACxC,OAAO,CAAC;EAE3B,OAAOF,IAAI,CAACf,sBAAsB,CAEhClB,KACF,CAAC;AACH;AAEA,OAAO,SAASoE,aAAaA,CAE3BM,OAAU,EACV1E,KAMS,EACT;EACA,IAAI,CAACD,gBAAgB,CAAC,CAAC;EAEvB,MAAM6E,aAAa,GAAG,IAAI,CAAC3E,eAAe,CAExCD,KACF,CAAC;EAKD,MAAMiB,SAAS,GAAG,IAAI,CAACL,IAAI,CAAC8D,OAAO,CAAC;EACpC,MAAMzC,IAAI,GAAGrD,QAAQ,CAAC8E,GAAG,CAAC;IACxBxD,UAAU,EAAE,IAAI;IAChBC,MAAM,EAAE,IAAI,CAACS,IAAI;IACjBK,SAAS,EAAEA,SAAyC;IACpDyD,OAAO;IAEP/D,GAAG,EAAEM,SAAS,CAACW;EACjB,CAAC,CAAC,CAAC+C,UAAU,CAAC,IAAI,CAACxC,OAAO,CAAC;EAE3B,OAAOF,IAAI,CAAC4C,mBAAmB,CAACD,aAAa,CAAC;AAChD;AAMA,OAAO,SAASE,KAAKA,CAEnB7B,KAAY,GAAG,IAAI,CAACA,KAAK,EACzB;EACA,MAAM8B,OAAO,GAAG,IAAIpG,WAAW,CAAI,IAAI,EAAEsE,KAAK,CAAC;EAC/C,OAAO8B,OAAO,CAACC,GAAG,CAAC,CAAC;AACtB"}
|
package/lib/path/removal.js
CHANGED
@@ -1,5 +1,5 @@
|
|
1
1
|
import { hooks } from "./lib/removal-hooks.js";
|
2
|
-
import {
|
2
|
+
import { getCachedPaths } from "../cache.js";
|
3
3
|
import { REMOVED, SHOULD_SKIP } from "./index.js";
|
4
4
|
export function remove() {
|
5
5
|
this._assertUnremoved();
|
@@ -34,7 +34,9 @@ export function _remove() {
|
|
34
34
|
}
|
35
35
|
export function _markRemoved() {
|
36
36
|
this._traverseFlags |= SHOULD_SKIP | REMOVED;
|
37
|
-
if (this.parent)
|
37
|
+
if (this.parent) {
|
38
|
+
getCachedPaths(this.hub, this.parent).delete(this.node);
|
39
|
+
}
|
38
40
|
this.node = null;
|
39
41
|
}
|
40
42
|
export function _assertUnremoved() {
|
package/lib/path/removal.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"names":["hooks","
|
1
|
+
{"version":3,"names":["hooks","getCachedPaths","REMOVED","SHOULD_SKIP","remove","_assertUnremoved","resync","opts","noScope","_removeFromScope","_callRemovalHooks","_markRemoved","shareCommentsWithSiblings","_remove","bindings","getBindingIdentifiers","Object","keys","forEach","name","scope","removeBinding","fn","parentPath","Array","isArray","container","splice","key","updateSiblingKeys","_replaceWith","_traverseFlags","parent","hub","delete","node","removed","buildCodeFrameError"],"sources":["../../src/path/removal.ts"],"sourcesContent":["// This file contains methods responsible for removing a node.\n\nimport { hooks } from \"./lib/removal-hooks\";\nimport { getCachedPaths } from \"../cache\";\nimport type NodePath from \"./index\";\nimport { REMOVED, SHOULD_SKIP } from \"./index\";\n\nexport function remove(this: NodePath) {\n this._assertUnremoved();\n\n this.resync();\n if (!this.opts?.noScope) {\n this._removeFromScope();\n }\n\n if (this._callRemovalHooks()) {\n this._markRemoved();\n return;\n }\n\n this.shareCommentsWithSiblings();\n this._remove();\n this._markRemoved();\n}\n\nexport function _removeFromScope(this: NodePath) {\n const bindings = this.getBindingIdentifiers();\n Object.keys(bindings).forEach(name => this.scope.removeBinding(name));\n}\n\nexport function _callRemovalHooks(this: NodePath) {\n for (const fn of hooks) {\n if (fn(this, this.parentPath)) return true;\n }\n}\n\nexport function _remove(this: NodePath) {\n if (Array.isArray(this.container)) {\n this.container.splice(this.key as number, 1);\n this.updateSiblingKeys(this.key as number, -1);\n } else {\n this._replaceWith(null);\n }\n}\n\nexport function _markRemoved(this: NodePath) {\n // this.shouldSkip = true; this.removed = true;\n this._traverseFlags |= SHOULD_SKIP | REMOVED;\n if (this.parent) {\n getCachedPaths(this.hub, this.parent).delete(this.node);\n }\n this.node = null;\n}\n\nexport function _assertUnremoved(this: NodePath) {\n if (this.removed) {\n throw this.buildCodeFrameError(\n \"NodePath has been removed so is read-only.\",\n );\n }\n}\n"],"mappings":"AAEA,SAASA,KAAK,QAAQ,wBAAqB;AAC3C,SAASC,cAAc,QAAQ,aAAU;AAEzC,SAASC,OAAO,EAAEC,WAAW,QAAQ,YAAS;AAE9C,OAAO,SAASC,MAAMA,CAAA,EAAiB;EACrC,IAAI,CAACC,gBAAgB,CAAC,CAAC;EAEvB,IAAI,CAACC,MAAM,CAAC,CAAC;EACb,IAAI,CAAC,IAAI,CAACC,IAAI,EAAEC,OAAO,EAAE;IACvB,IAAI,CAACC,gBAAgB,CAAC,CAAC;EACzB;EAEA,IAAI,IAAI,CAACC,iBAAiB,CAAC,CAAC,EAAE;IAC5B,IAAI,CAACC,YAAY,CAAC,CAAC;IACnB;EACF;EAEA,IAAI,CAACC,yBAAyB,CAAC,CAAC;EAChC,IAAI,CAACC,OAAO,CAAC,CAAC;EACd,IAAI,CAACF,YAAY,CAAC,CAAC;AACrB;AAEA,OAAO,SAASF,gBAAgBA,CAAA,EAAiB;EAC/C,MAAMK,QAAQ,GAAG,IAAI,CAACC,qBAAqB,CAAC,CAAC;EAC7CC,MAAM,CAACC,IAAI,CAACH,QAAQ,CAAC,CAACI,OAAO,CAACC,IAAI,IAAI,IAAI,CAACC,KAAK,CAACC,aAAa,CAACF,IAAI,CAAC,CAAC;AACvE;AAEA,OAAO,SAAST,iBAAiBA,CAAA,EAAiB;EAChD,KAAK,MAAMY,EAAE,IAAItB,KAAK,EAAE;IACtB,IAAIsB,EAAE,CAAC,IAAI,EAAE,IAAI,CAACC,UAAU,CAAC,EAAE,OAAO,IAAI;EAC5C;AACF;AAEA,OAAO,SAASV,OAAOA,CAAA,EAAiB;EACtC,IAAIW,KAAK,CAACC,OAAO,CAAC,IAAI,CAACC,SAAS,CAAC,EAAE;IACjC,IAAI,CAACA,SAAS,CAACC,MAAM,CAAC,IAAI,CAACC,GAAG,EAAY,CAAC,CAAC;IAC5C,IAAI,CAACC,iBAAiB,CAAC,IAAI,CAACD,GAAG,EAAY,CAAC,CAAC,CAAC;EAChD,CAAC,MAAM;IACL,IAAI,CAACE,YAAY,CAAC,IAAI,CAAC;EACzB;AACF;AAEA,OAAO,SAASnB,YAAYA,CAAA,EAAiB;EAE3C,IAAI,CAACoB,cAAc,IAAI5B,WAAW,GAAGD,OAAO;EAC5C,IAAI,IAAI,CAAC8B,MAAM,EAAE;IACf/B,cAAc,CAAC,IAAI,CAACgC,GAAG,EAAE,IAAI,CAACD,MAAM,CAAC,CAACE,MAAM,CAAC,IAAI,CAACC,IAAI,CAAC;EACzD;EACA,IAAI,CAACA,IAAI,GAAG,IAAI;AAClB;AAEA,OAAO,SAAS9B,gBAAgBA,CAAA,EAAiB;EAC/C,IAAI,IAAI,CAAC+B,OAAO,EAAE;IAChB,MAAM,IAAI,CAACC,mBAAmB,CAC5B,4CACF,CAAC;EACH;AACF"}
|
package/lib/path/replacement.js
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
import { codeFrameColumns } from "@babel/code-frame";
|
2
2
|
import traverse from "../index.js";
|
3
3
|
import NodePath from "./index.js";
|
4
|
-
import {
|
4
|
+
import { getCachedPaths } from "../cache.js";
|
5
5
|
import { parse } from "@babel/parser";
|
6
6
|
import * as _t from "@babel/types";
|
7
7
|
const {
|
@@ -32,7 +32,7 @@ export function replaceWithMultiple(nodes) {
|
|
32
32
|
nodes = this._verifyNodeList(nodes);
|
33
33
|
inheritLeadingComments(nodes[0], this.node);
|
34
34
|
inheritTrailingComments(nodes[nodes.length - 1], this.node);
|
35
|
-
|
35
|
+
getCachedPaths(this.hub, this.parent)?.delete(this.node);
|
36
36
|
this.node = this.container[this.key] = null;
|
37
37
|
const paths = this.insertAfter(nodes);
|
38
38
|
if (this.node) {
|
@@ -119,7 +119,7 @@ export function _replaceWith(node) {
|
|
119
119
|
validate(this.parent, this.key, node);
|
120
120
|
}
|
121
121
|
this.debug(`Replace with ${node?.type}`);
|
122
|
-
|
122
|
+
getCachedPaths(this.hub, this.parent)?.set(node, this).delete(this.node);
|
123
123
|
this.node = this.container[this.key] = node;
|
124
124
|
}
|
125
125
|
export function replaceExpressionWithStatements(nodes) {
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"names":["codeFrameColumns","traverse","NodePath","path","pathCache","parse","_t","FUNCTION_TYPES","arrowFunctionExpression","assignmentExpression","awaitExpression","blockStatement","callExpression","cloneNode","expressionStatement","identifier","inheritLeadingComments","inheritTrailingComments","inheritsComments","isExpression","isProgram","isStatement","removeComments","returnStatement","toSequenceExpression","validate","yieldExpression","hoistVariables","replaceWithMultiple","nodes","resync","_verifyNodeList","node","length","get","parent","delete","container","key","paths","insertAfter","requeue","remove","replaceWithSourceString","replacement","ast","err","loc","message","start","line","column","code","expressionAST","program","body","expression","removeProperties","replaceWith","replacementPath","removed","Error","Array","isArray","nodePath","isNodeType","canHaveVariableDeclarationOrExpression","canSwapBetweenExpressionAndStatement","parentPath","isExportDefaultDeclaration","replaceExpressionWithStatements","oldNode","_replaceWith","type","setScope","ReferenceError","inList","debug","set","nodesAsSequenceExpression","scope","functionParent","getFunctionParent","isParentAsync","is","isParentGenerator","callee","id","push","completionRecords","getCompletionRecords","isExpressionStatement","loop","findParent","isLoop","uid","getData","generateDeclaredUidIdentifier","pushContainer","setData","name","arrowFunctionToExpression","newCallee","needToAwaitFunction","hasType","needToYieldFunction","replaceInline","_containerInsertAfter"],"sources":["../../src/path/replacement.ts"],"sourcesContent":["// This file contains methods responsible for replacing a node with another.\n\nimport { codeFrameColumns } from \"@babel/code-frame\";\nimport traverse from \"../index\";\nimport NodePath from \"./index\";\nimport { path as pathCache } from \"../cache\";\nimport { parse } from \"@babel/parser\";\nimport {\n FUNCTION_TYPES,\n arrowFunctionExpression,\n assignmentExpression,\n awaitExpression,\n blockStatement,\n callExpression,\n cloneNode,\n expressionStatement,\n identifier,\n inheritLeadingComments,\n inheritTrailingComments,\n inheritsComments,\n isExpression,\n isProgram,\n isStatement,\n removeComments,\n returnStatement,\n toSequenceExpression,\n validate,\n yieldExpression,\n} from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nimport hoistVariables from \"@babel/helper-hoist-variables\";\n\n/**\n * Replace a node with an array of multiple. This method performs the following steps:\n *\n * - Inherit the comments of first provided node with that of the current node.\n * - Insert the provided nodes after the current node.\n * - Remove the current node.\n */\n\nexport function replaceWithMultiple(\n this: NodePath,\n nodes: t.Node | t.Node[],\n): NodePath[] {\n this.resync();\n\n nodes = this._verifyNodeList(nodes);\n inheritLeadingComments(nodes[0], this.node);\n inheritTrailingComments(nodes[nodes.length - 1], this.node);\n pathCache.get(this.parent)?.delete(this.node);\n this.node =\n // @ts-expect-error this.key must present in this.container\n this.container[this.key] = null;\n const paths = this.insertAfter(nodes);\n\n if (this.node) {\n this.requeue();\n } else {\n this.remove();\n }\n return paths;\n}\n\n/**\n * Parse a string as an expression and replace the current node with the result.\n *\n * NOTE: This is typically not a good idea to use. Building source strings when\n * transforming ASTs is an antipattern and SHOULD NOT be encouraged. Even if it's\n * easier to use, your transforms will be extremely brittle.\n */\n\nexport function replaceWithSourceString(this: NodePath, replacement: string) {\n this.resync();\n let ast: t.File;\n\n try {\n replacement = `(${replacement})`;\n // @ts-expect-error todo: use babel-types ast typings in Babel parser\n ast = parse(replacement);\n } catch (err) {\n const loc = err.loc;\n if (loc) {\n err.message +=\n \" - make sure this is an expression.\\n\" +\n codeFrameColumns(replacement, {\n start: {\n line: loc.line,\n column: loc.column + 1,\n },\n });\n err.code = \"BABEL_REPLACE_SOURCE_ERROR\";\n }\n throw err;\n }\n\n const expressionAST = (ast.program.body[0] as t.ExpressionStatement)\n .expression;\n traverse.removeProperties(expressionAST);\n return this.replaceWith(expressionAST);\n}\n\n/**\n * Replace the current node with another.\n */\n\nexport function replaceWith<R extends t.Node>(\n this: NodePath,\n replacementPath: R | NodePath<R>,\n): [NodePath<R>] {\n this.resync();\n\n if (this.removed) {\n throw new Error(\"You can't replace this node, we've already removed it\");\n }\n\n let replacement: t.Node =\n replacementPath instanceof NodePath\n ? replacementPath.node\n : replacementPath;\n\n if (!replacement) {\n throw new Error(\n \"You passed `path.replaceWith()` a falsy node, use `path.remove()` instead\",\n );\n }\n\n if (this.node === replacement) {\n return [this as NodePath<R>];\n }\n\n if (this.isProgram() && !isProgram(replacement)) {\n throw new Error(\n \"You can only replace a Program root node with another Program node\",\n );\n }\n\n if (Array.isArray(replacement)) {\n throw new Error(\n \"Don't use `path.replaceWith()` with an array of nodes, use `path.replaceWithMultiple()`\",\n );\n }\n\n if (typeof replacement === \"string\") {\n throw new Error(\n \"Don't use `path.replaceWith()` with a source string, use `path.replaceWithSourceString()`\",\n );\n }\n\n let nodePath = \"\";\n\n if (this.isNodeType(\"Statement\") && isExpression(replacement)) {\n if (\n !this.canHaveVariableDeclarationOrExpression() &&\n !this.canSwapBetweenExpressionAndStatement(replacement) &&\n !this.parentPath.isExportDefaultDeclaration()\n ) {\n // replacing a statement with an expression so wrap it in an expression statement\n replacement = expressionStatement(replacement);\n nodePath = \"expression\";\n }\n }\n\n if (this.isNodeType(\"Expression\") && isStatement(replacement)) {\n if (\n !this.canHaveVariableDeclarationOrExpression() &&\n !this.canSwapBetweenExpressionAndStatement(replacement)\n ) {\n // replacing an expression with a statement so let's explode it\n return this.replaceExpressionWithStatements([replacement]) as [\n NodePath<R>,\n ];\n }\n }\n\n const oldNode = this.node;\n if (oldNode) {\n inheritsComments(replacement, oldNode);\n removeComments(oldNode);\n }\n\n // replace the node\n this._replaceWith(replacement);\n this.type = replacement.type;\n\n // potentially create new scope\n this.setScope();\n\n // requeue for visiting\n this.requeue();\n\n return [\n nodePath ? (this.get(nodePath) as NodePath<R>) : (this as NodePath<R>),\n ];\n}\n\n/**\n * Description\n */\n\nexport function _replaceWith(this: NodePath, node: t.Node) {\n if (!this.container) {\n throw new ReferenceError(\"Container is falsy\");\n }\n\n if (this.inList) {\n // @ts-expect-error todo(flow->ts): check if validate accepts a numeric key\n validate(this.parent, this.key, [node]);\n } else {\n validate(this.parent, this.key as string, node);\n }\n\n this.debug(`Replace with ${node?.type}`);\n pathCache.get(this.parent)?.set(node, this).delete(this.node);\n\n this.node =\n // @ts-expect-error this.key must present in this.container\n this.container[this.key] = node;\n}\n\n/**\n * This method takes an array of statements nodes and then explodes it\n * into expressions. This method retains completion records which is\n * extremely important to retain original semantics.\n */\n\nexport function replaceExpressionWithStatements(\n this: NodePath,\n nodes: Array<t.Statement>,\n) {\n this.resync();\n\n const nodesAsSequenceExpression = toSequenceExpression(nodes, this.scope);\n\n if (nodesAsSequenceExpression) {\n return this.replaceWith(nodesAsSequenceExpression)[0].get(\"expressions\");\n }\n\n const functionParent = this.getFunctionParent();\n const isParentAsync = functionParent?.is(\"async\");\n const isParentGenerator = functionParent?.is(\"generator\");\n\n const container = arrowFunctionExpression([], blockStatement(nodes));\n\n this.replaceWith(callExpression(container, []));\n // replaceWith changes the type of \"this\", but it isn't trackable by TS\n type ThisType = NodePath<\n t.CallExpression & {\n callee: t.ArrowFunctionExpression & { body: t.BlockStatement };\n }\n >;\n\n // hoist variable declaration in do block\n // `(do { var x = 1; x;})` -> `var x; (() => { x = 1; return x; })()`\n const callee = (this as ThisType).get(\"callee\");\n hoistVariables(\n callee.get(\"body\"),\n (id: t.Identifier) => {\n this.scope.push({ id });\n },\n \"var\",\n );\n\n // add implicit returns to all ending expression statements\n const completionRecords: Array<NodePath> = (this as ThisType)\n .get(\"callee\")\n .getCompletionRecords();\n for (const path of completionRecords) {\n if (!path.isExpressionStatement()) continue;\n\n const loop = path.findParent(path => path.isLoop());\n if (loop) {\n let uid = loop.getData(\"expressionReplacementReturnUid\");\n\n if (!uid) {\n uid = callee.scope.generateDeclaredUidIdentifier(\"ret\");\n callee\n .get(\"body\")\n .pushContainer(\"body\", returnStatement(cloneNode(uid)));\n loop.setData(\"expressionReplacementReturnUid\", uid);\n } else {\n uid = identifier(uid.name);\n }\n\n path\n .get(\"expression\")\n .replaceWith(\n assignmentExpression(\"=\", cloneNode(uid), path.node.expression),\n );\n } else {\n path.replaceWith(returnStatement(path.node.expression));\n }\n }\n\n // This is an IIFE, so we don't need to worry about the noNewArrows assumption\n callee.arrowFunctionToExpression();\n // Fixme: we can not `assert this is NodePath<t.FunctionExpression>` in `arrowFunctionToExpression`\n // because it is not a class method known at compile time.\n const newCallee = callee as unknown as NodePath<t.FunctionExpression>;\n\n // (() => await xxx)() -> await (async () => await xxx)();\n const needToAwaitFunction =\n isParentAsync &&\n traverse.hasType(\n (this.get(\"callee.body\") as NodePath<t.BlockStatement>).node,\n \"AwaitExpression\",\n FUNCTION_TYPES,\n );\n const needToYieldFunction =\n isParentGenerator &&\n traverse.hasType(\n (this.get(\"callee.body\") as NodePath<t.BlockStatement>).node,\n \"YieldExpression\",\n FUNCTION_TYPES,\n );\n if (needToAwaitFunction) {\n newCallee.set(\"async\", true);\n // yield* will await the generator return result\n if (!needToYieldFunction) {\n this.replaceWith(awaitExpression((this as ThisType).node));\n }\n }\n if (needToYieldFunction) {\n newCallee.set(\"generator\", true);\n this.replaceWith(yieldExpression((this as ThisType).node, true));\n }\n\n return newCallee.get(\"body.body\");\n}\n\nexport function replaceInline(this: NodePath, nodes: t.Node | Array<t.Node>) {\n this.resync();\n\n if (Array.isArray(nodes)) {\n if (Array.isArray(this.container)) {\n nodes = this._verifyNodeList(nodes);\n const paths = this._containerInsertAfter(nodes);\n this.remove();\n return paths;\n } else {\n return this.replaceWithMultiple(nodes);\n }\n } else {\n return this.replaceWith(nodes);\n }\n}\n"],"mappings":"AAEA,SAASA,gBAAgB,QAAQ,mBAAmB;AACpD,OAAOC,QAAQ,MAAM,aAAU;AAC/B,OAAOC,QAAQ,MAAM,YAAS;AAC9B,SAASC,IAAI,IAAIC,SAAS,QAAQ,aAAU;AAC5C,SAASC,KAAK,QAAQ,eAAe;AACrC,YAAAC,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iC,KAAK,CAACC,OAAO,CAAC,IAAI,CAAC1B,SAAS,CAAC,EAAE;MACjCR,KAAK,GAAG,IAAI,CAACE,eAAe,CAACF,KAAK,CAAC;MACnC,MAAMU,KAAK,GAAG,IAAI,CAACoE,qBAAqB,CAAC9E,KAAK,CAAC;MAC/C,IAAI,CAACa,MAAM,CAAC,CAAC;MACb,OAAOH,KAAK;IACd,CAAC,MAAM;MACL,OAAO,IAAI,CAACX,mBAAmB,CAACC,KAAK,CAAC;IACxC;EACF,CAAC,MAAM;IACL,OAAO,IAAI,CAAC6B,WAAW,CAAC7B,KAAK,CAAC;EAChC;AACF"}
|
1
|
+
{"version":3,"names":["codeFrameColumns","traverse","NodePath","getCachedPaths","parse","_t","FUNCTION_TYPES","arrowFunctionExpression","assignmentExpression","awaitExpression","blockStatement","callExpression","cloneNode","expressionStatement","identifier","inheritLeadingComments","inheritTrailingComments","inheritsComments","isExpression","isProgram","isStatement","removeComments","returnStatement","toSequenceExpression","validate","yieldExpression","hoistVariables","replaceWithMultiple","nodes","resync","_verifyNodeList","node","length","hub","parent","delete","container","key","paths","insertAfter","requeue","remove","replaceWithSourceString","replacement","ast","err","loc","message","start","line","column","code","expressionAST","program","body","expression","removeProperties","replaceWith","replacementPath","removed","Error","Array","isArray","nodePath","isNodeType","canHaveVariableDeclarationOrExpression","canSwapBetweenExpressionAndStatement","parentPath","isExportDefaultDeclaration","replaceExpressionWithStatements","oldNode","_replaceWith","type","setScope","get","ReferenceError","inList","debug","set","nodesAsSequenceExpression","scope","functionParent","getFunctionParent","isParentAsync","is","isParentGenerator","callee","id","push","completionRecords","getCompletionRecords","path","isExpressionStatement","loop","findParent","isLoop","uid","getData","generateDeclaredUidIdentifier","pushContainer","setData","name","arrowFunctionToExpression","newCallee","needToAwaitFunction","hasType","needToYieldFunction","replaceInline","_containerInsertAfter"],"sources":["../../src/path/replacement.ts"],"sourcesContent":["// This file contains methods responsible for replacing a node with another.\n\nimport { codeFrameColumns } from \"@babel/code-frame\";\nimport traverse from \"../index\";\nimport NodePath from \"./index\";\nimport { getCachedPaths } from \"../cache\";\nimport { parse } from \"@babel/parser\";\nimport {\n FUNCTION_TYPES,\n arrowFunctionExpression,\n assignmentExpression,\n awaitExpression,\n blockStatement,\n callExpression,\n cloneNode,\n expressionStatement,\n identifier,\n inheritLeadingComments,\n inheritTrailingComments,\n inheritsComments,\n isExpression,\n isProgram,\n isStatement,\n removeComments,\n returnStatement,\n toSequenceExpression,\n validate,\n yieldExpression,\n} from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nimport hoistVariables from \"@babel/helper-hoist-variables\";\n\n/**\n * Replace a node with an array of multiple. This method performs the following steps:\n *\n * - Inherit the comments of first provided node with that of the current node.\n * - Insert the provided nodes after the current node.\n * - Remove the current node.\n */\n\nexport function replaceWithMultiple(\n this: NodePath,\n nodes: t.Node | t.Node[],\n): NodePath[] {\n this.resync();\n\n nodes = this._verifyNodeList(nodes);\n inheritLeadingComments(nodes[0], this.node);\n inheritTrailingComments(nodes[nodes.length - 1], this.node);\n getCachedPaths(this.hub, this.parent)?.delete(this.node);\n this.node =\n // @ts-expect-error this.key must present in this.container\n this.container[this.key] = null;\n const paths = this.insertAfter(nodes);\n\n if (this.node) {\n this.requeue();\n } else {\n this.remove();\n }\n return paths;\n}\n\n/**\n * Parse a string as an expression and replace the current node with the result.\n *\n * NOTE: This is typically not a good idea to use. Building source strings when\n * transforming ASTs is an antipattern and SHOULD NOT be encouraged. Even if it's\n * easier to use, your transforms will be extremely brittle.\n */\n\nexport function replaceWithSourceString(this: NodePath, replacement: string) {\n this.resync();\n let ast: t.File;\n\n try {\n replacement = `(${replacement})`;\n // @ts-expect-error todo: use babel-types ast typings in Babel parser\n ast = parse(replacement);\n } catch (err) {\n const loc = err.loc;\n if (loc) {\n err.message +=\n \" - make sure this is an expression.\\n\" +\n codeFrameColumns(replacement, {\n start: {\n line: loc.line,\n column: loc.column + 1,\n },\n });\n err.code = \"BABEL_REPLACE_SOURCE_ERROR\";\n }\n throw err;\n }\n\n const expressionAST = (ast.program.body[0] as t.ExpressionStatement)\n .expression;\n traverse.removeProperties(expressionAST);\n return this.replaceWith(expressionAST);\n}\n\n/**\n * Replace the current node with another.\n */\n\nexport function replaceWith<R extends t.Node>(\n this: NodePath,\n replacementPath: R | NodePath<R>,\n): [NodePath<R>] {\n this.resync();\n\n if (this.removed) {\n throw new Error(\"You can't replace this node, we've already removed it\");\n }\n\n let replacement: t.Node =\n replacementPath instanceof NodePath\n ? replacementPath.node\n : replacementPath;\n\n if (!replacement) {\n throw new Error(\n \"You passed `path.replaceWith()` a falsy node, use `path.remove()` instead\",\n );\n }\n\n if (this.node === replacement) {\n return [this as NodePath<R>];\n }\n\n if (this.isProgram() && !isProgram(replacement)) {\n throw new Error(\n \"You can only replace a Program root node with another Program node\",\n );\n }\n\n if (Array.isArray(replacement)) {\n throw new Error(\n \"Don't use `path.replaceWith()` with an array of nodes, use `path.replaceWithMultiple()`\",\n );\n }\n\n if (typeof replacement === \"string\") {\n throw new Error(\n \"Don't use `path.replaceWith()` with a source string, use `path.replaceWithSourceString()`\",\n );\n }\n\n let nodePath = \"\";\n\n if (this.isNodeType(\"Statement\") && isExpression(replacement)) {\n if (\n !this.canHaveVariableDeclarationOrExpression() &&\n !this.canSwapBetweenExpressionAndStatement(replacement) &&\n !this.parentPath.isExportDefaultDeclaration()\n ) {\n // replacing a statement with an expression so wrap it in an expression statement\n replacement = expressionStatement(replacement);\n nodePath = \"expression\";\n }\n }\n\n if (this.isNodeType(\"Expression\") && isStatement(replacement)) {\n if (\n !this.canHaveVariableDeclarationOrExpression() &&\n !this.canSwapBetweenExpressionAndStatement(replacement)\n ) {\n // replacing an expression with a statement so let's explode it\n return this.replaceExpressionWithStatements([replacement]) as [\n NodePath<R>,\n ];\n }\n }\n\n const oldNode = this.node;\n if (oldNode) {\n inheritsComments(replacement, oldNode);\n removeComments(oldNode);\n }\n\n // replace the node\n this._replaceWith(replacement);\n this.type = replacement.type;\n\n // potentially create new scope\n this.setScope();\n\n // requeue for visiting\n this.requeue();\n\n return [\n nodePath ? (this.get(nodePath) as NodePath<R>) : (this as NodePath<R>),\n ];\n}\n\n/**\n * Description\n */\n\nexport function _replaceWith(this: NodePath, node: t.Node) {\n if (!this.container) {\n throw new ReferenceError(\"Container is falsy\");\n }\n\n if (this.inList) {\n // @ts-expect-error todo(flow->ts): check if validate accepts a numeric key\n validate(this.parent, this.key, [node]);\n } else {\n validate(this.parent, this.key as string, node);\n }\n\n this.debug(`Replace with ${node?.type}`);\n getCachedPaths(this.hub, this.parent)?.set(node, this).delete(this.node);\n\n this.node =\n // @ts-expect-error this.key must present in this.container\n this.container[this.key] = node;\n}\n\n/**\n * This method takes an array of statements nodes and then explodes it\n * into expressions. This method retains completion records which is\n * extremely important to retain original semantics.\n */\n\nexport function replaceExpressionWithStatements(\n this: NodePath,\n nodes: Array<t.Statement>,\n) {\n this.resync();\n\n const nodesAsSequenceExpression = toSequenceExpression(nodes, this.scope);\n\n if (nodesAsSequenceExpression) {\n return this.replaceWith(nodesAsSequenceExpression)[0].get(\"expressions\");\n }\n\n const functionParent = this.getFunctionParent();\n const isParentAsync = functionParent?.is(\"async\");\n const isParentGenerator = functionParent?.is(\"generator\");\n\n const container = arrowFunctionExpression([], blockStatement(nodes));\n\n this.replaceWith(callExpression(container, []));\n // replaceWith changes the type of \"this\", but it isn't trackable by TS\n type ThisType = NodePath<\n t.CallExpression & {\n callee: t.ArrowFunctionExpression & { body: t.BlockStatement };\n }\n >;\n\n // hoist variable declaration in do block\n // `(do { var x = 1; x;})` -> `var x; (() => { x = 1; return x; })()`\n const callee = (this as ThisType).get(\"callee\");\n hoistVariables(\n callee.get(\"body\"),\n (id: t.Identifier) => {\n this.scope.push({ id });\n },\n \"var\",\n );\n\n // add implicit returns to all ending expression statements\n const completionRecords: Array<NodePath> = (this as ThisType)\n .get(\"callee\")\n .getCompletionRecords();\n for (const path of completionRecords) {\n if (!path.isExpressionStatement()) continue;\n\n const loop = path.findParent(path => path.isLoop());\n if (loop) {\n let uid = loop.getData(\"expressionReplacementReturnUid\");\n\n if (!uid) {\n uid = callee.scope.generateDeclaredUidIdentifier(\"ret\");\n callee\n .get(\"body\")\n .pushContainer(\"body\", returnStatement(cloneNode(uid)));\n loop.setData(\"expressionReplacementReturnUid\", uid);\n } else {\n uid = identifier(uid.name);\n }\n\n path\n .get(\"expression\")\n .replaceWith(\n assignmentExpression(\"=\", cloneNode(uid), path.node.expression),\n );\n } else {\n path.replaceWith(returnStatement(path.node.expression));\n }\n }\n\n // This is an IIFE, so we don't need to worry about the noNewArrows assumption\n callee.arrowFunctionToExpression();\n // Fixme: we can not `assert this is NodePath<t.FunctionExpression>` in `arrowFunctionToExpression`\n // because it is not a class method known at compile time.\n const newCallee = callee as unknown as NodePath<t.FunctionExpression>;\n\n // (() => await xxx)() -> await (async () => await xxx)();\n const needToAwaitFunction =\n isParentAsync &&\n traverse.hasType(\n (this.get(\"callee.body\") as NodePath<t.BlockStatement>).node,\n \"AwaitExpression\",\n FUNCTION_TYPES,\n );\n const needToYieldFunction =\n isParentGenerator &&\n traverse.hasType(\n (this.get(\"callee.body\") as NodePath<t.BlockStatement>).node,\n \"YieldExpression\",\n FUNCTION_TYPES,\n );\n if (needToAwaitFunction) {\n newCallee.set(\"async\", true);\n // yield* will await the generator return result\n if (!needToYieldFunction) {\n this.replaceWith(awaitExpression((this as ThisType).node));\n }\n }\n if (needToYieldFunction) {\n newCallee.set(\"generator\", true);\n this.replaceWith(yieldExpression((this as ThisType).node, true));\n }\n\n return newCallee.get(\"body.body\");\n}\n\nexport function replaceInline(this: NodePath, nodes: t.Node | Array<t.Node>) {\n this.resync();\n\n if (Array.isArray(nodes)) {\n if (Array.isArray(this.container)) {\n nodes = this._verifyNodeList(nodes);\n const paths = this._containerInsertAfter(nodes);\n this.remove();\n return paths;\n } else {\n return this.replaceWithMultiple(nodes);\n }\n } else {\n return this.replaceWith(nodes);\n }\n}\n"],"mappings":"AAEA,SAASA,gBAA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,CAAC;AACnC;AAEA,OAAO,SAASiC,aAAaA,CAAiB/E,KAA6B,EAAE;EAC3E,IAAI,CAACC,MAAM,CAAC,CAAC;EAEb,IAAIgC,KAAK,CAACC,OAAO,CAAClC,KAAK,CAAC,EAAE;IACxB,IAAIiC,KAAK,CAACC,OAAO,CAAC,IAAI,CAAC1B,SAAS,CAAC,EAAE;MACjCR,KAAK,GAAG,IAAI,CAACE,eAAe,CAACF,KAAK,CAAC;MACnC,MAAMU,KAAK,GAAG,IAAI,CAACsE,qBAAqB,CAAChF,KAAK,CAAC;MAC/C,IAAI,CAACa,MAAM,CAAC,CAAC;MACb,OAAOH,KAAK;IACd,CAAC,MAAM;MACL,OAAO,IAAI,CAACX,mBAAmB,CAACC,KAAK,CAAC;IACxC;EACF,CAAC,MAAM;IACL,OAAO,IAAI,CAAC6B,WAAW,CAAC7B,KAAK,CAAC;EAChC;AACF"}
|
package/lib/traverse-node.js
CHANGED
@@ -3,12 +3,16 @@ import * as _t from "@babel/types";
|
|
3
3
|
const {
|
4
4
|
VISITOR_KEYS
|
5
5
|
} = _t;
|
6
|
-
export function traverseNode(node, opts, scope, state, path, skipKeys) {
|
6
|
+
export function traverseNode(node, opts, scope, state, path, skipKeys, visitSelf) {
|
7
7
|
const keys = VISITOR_KEYS[node.type];
|
8
8
|
if (!keys) return false;
|
9
9
|
const context = new TraversalContext(scope, opts, state, path);
|
10
|
+
if (visitSelf) {
|
11
|
+
if (skipKeys?.[path.parentKey]) return false;
|
12
|
+
return context.visitQueue([path]);
|
13
|
+
}
|
10
14
|
for (const key of keys) {
|
11
|
-
if (skipKeys
|
15
|
+
if (skipKeys?.[key]) continue;
|
12
16
|
if (context.visit(node, key)) {
|
13
17
|
return true;
|
14
18
|
}
|
package/lib/traverse-node.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"names":["TraversalContext","_t","VISITOR_KEYS","traverseNode","node","opts","scope","state","path","skipKeys","keys","type","context","key","visit"],"sources":["../src/traverse-node.ts"],"sourcesContent":["import TraversalContext from \"./context\";\nimport type { ExplodedTraverseOptions } from \"./index\";\nimport type NodePath from \"./path\";\nimport type Scope from \"./scope\";\nimport type * as t from \"@babel/types\";\nimport { VISITOR_KEYS } from \"@babel/types\";\n\n/**\n * Traverse the children of given node\n * @param {Node} node\n * @param {TraverseOptions} opts The traverse options used to create a new traversal context\n * @param {scope} scope A traversal scope used to create a new traversal context. When opts.noScope is true, scope should not be provided\n * @param {any} state A user data storage provided as the second callback argument for traversal visitors\n * @param {NodePath} path A NodePath of given node\n * @param {Record<string, boolean>} skipKeys A map from key names to whether that should be skipped during traversal. The skipKeys are applied to every descendants\n * @returns {boolean} Whether the traversal stops early\n\n * @note This function does not visit the given `node`.\n */\nexport function traverseNode<S = unknown>(\n node: t.Node,\n opts: ExplodedTraverseOptions<S>,\n scope?: Scope,\n state?: any,\n path?: NodePath,\n skipKeys?: Record<string, boolean>,\n): boolean {\n const keys = VISITOR_KEYS[node.type];\n if (!keys) return false;\n\n const context = new TraversalContext(scope, opts, state, path);\n for (const key of keys) {\n if (skipKeys
|
1
|
+
{"version":3,"names":["TraversalContext","_t","VISITOR_KEYS","traverseNode","node","opts","scope","state","path","skipKeys","visitSelf","keys","type","context","parentKey","visitQueue","key","visit"],"sources":["../src/traverse-node.ts"],"sourcesContent":["import TraversalContext from \"./context\";\nimport type { ExplodedTraverseOptions } from \"./index\";\nimport type NodePath from \"./path\";\nimport type Scope from \"./scope\";\nimport type * as t from \"@babel/types\";\nimport { VISITOR_KEYS } from \"@babel/types\";\n\n/**\n * Traverse the children of given node\n * @param {Node} node\n * @param {TraverseOptions} opts The traverse options used to create a new traversal context\n * @param {scope} scope A traversal scope used to create a new traversal context. When opts.noScope is true, scope should not be provided\n * @param {any} state A user data storage provided as the second callback argument for traversal visitors\n * @param {NodePath} path A NodePath of given node\n * @param {Record<string, boolean>} skipKeys A map from key names to whether that should be skipped during traversal. The skipKeys are applied to every descendants\n * @returns {boolean} Whether the traversal stops early\n\n * @note This function does not visit the given `node`.\n */\nexport function traverseNode<S = unknown>(\n node: t.Node,\n opts: ExplodedTraverseOptions<S>,\n scope?: Scope,\n state?: any,\n path?: NodePath,\n skipKeys?: Record<string, boolean>,\n visitSelf?: boolean,\n): boolean {\n const keys = VISITOR_KEYS[node.type];\n if (!keys) return false;\n\n const context = new TraversalContext(scope, opts, state, path);\n if (visitSelf) {\n if (skipKeys?.[path.parentKey]) return false;\n return context.visitQueue([path]);\n }\n\n for (const key of keys) {\n if (skipKeys?.[key]) continue;\n if (context.visit(node, key)) {\n return true;\n }\n }\n\n return false;\n}\n"],"mappings":"AAAA,OAAOA,gBAAgB,MAAM,cAAW;AAKxC,YAAAC,EAAA,MAA6B,cAAc;AAAC;EAAnCC;AAAY,IAAAD,EAAA;AAcrB,OAAO,SAASE,YAAYA,CAC1BC,IAAY,EACZC,IAAgC,EAChCC,KAAa,EACbC,KAAW,EACXC,IAAe,EACfC,QAAkC,EAClCC,SAAmB,EACV;EACT,MAAMC,IAAI,GAAGT,YAAY,CAACE,IAAI,CAACQ,IAAI,CAAC;EACpC,IAAI,CAACD,IAAI,EAAE,OAAO,KAAK;EAEvB,MAAME,OAAO,GAAG,IAAIb,gBAAgB,CAACM,KAAK,EAAED,IAAI,EAAEE,KAAK,EAAEC,IAAI,CAAC;EAC9D,IAAIE,SAAS,EAAE;IACb,IAAID,QAAQ,GAAGD,IAAI,CAACM,SAAS,CAAC,EAAE,OAAO,KAAK;IAC5C,OAAOD,OAAO,CAACE,UAAU,CAAC,CAACP,IAAI,CAAC,CAAC;EACnC;EAEA,KAAK,MAAMQ,GAAG,IAAIL,IAAI,EAAE;IACtB,IAAIF,QAAQ,GAAGO,GAAG,CAAC,EAAE;IACrB,IAAIH,OAAO,CAACI,KAAK,CAACb,IAAI,EAAEY,GAAG,CAAC,EAAE;MAC5B,OAAO,IAAI;IACb;EACF;EAEA,OAAO,KAAK;AACd"}
|