Add resolveIndirection to js-ast-utils
MODIFY
packages/@romejs/js-ast-utils/index.ts
packages/@romejs/js-ast-utils/index.ts
@@ -43,3 +43,4 @@ export {default as getJSXAttribute} from "./getJSXAttribute";
export {default as isJSXElement} from "./isJSXElement";
export {default as tryStaticEvaluation} from "./tryStaticEvaluation";
export {default as tryStaticEvaluationPath} from "./tryStaticEvaluationPath";
+export {default as resolveIndirection} from "./resolveIndirection";

ADD
packages/@romejs/js-ast-utils/resolveIndirection.ts
+import {AnyNode} from "@romejs/ast";
+import {ConstBinding, Scope} from "@romejs/compiler";
+
+export default function resolveIndirection(node: AnyNode, scope: Scope): AnyNode {
+ switch (node.type) {
+ case "JSReferenceIdentifier": {
+ const binding = scope.getBinding(node.name);
+ if (binding instanceof ConstBinding && binding.value !== undefined) {
+ return resolveIndirection(binding.value, binding.scope);
+ }
+ break;
+ }
+
+ case "JSSequenceExpression":
+ return resolveIndirection(
+ node.expressions[node.expressions.length - 1],
+ scope,
+ );
+
+ case "TSAsExpression":
+ case "TSTypeAssertion":
+ case "TSNonNullExpression":
+ return resolveIndirection(node.expression, scope);
+ }
+
+ return node;
+}

MODIFY
packages/@romejs/js-ast-utils/tryStaticEvaluation.ts
packages/@romejs/js-ast-utils/tryStaticEvaluation.ts
@@ -4,7 +4,8 @@ import {
JSTemplateLiteral,
JSUnaryExpression,
} from "@romejs/ast";
-import {ConstBinding, Scope} from "@romejs/compiler";
+import {Scope} from "@romejs/compiler";
+import resolveIndirection from "./resolveIndirection";
export type EvalResult = {
value: undefined | null | string | number | boolean;
@@ -159,6 +160,8 @@ export default function tryStaticEvaluation(
let res: EvalResult = BAILED;
+ node = resolveIndirection(node, scope);
+
switch (node.type) {
case "JSUnaryExpression": {
res = evalUnaryExpression(node, scope, opts);
@@ -186,10 +189,6 @@ export default function tryStaticEvaluation(
const binding = scope.getBinding(node.name);
if (binding === undefined && node.name === "undefined") {
res = createResult(undefined);
- } else {
- if (binding instanceof ConstBinding && binding.value !== undefined) {
- res = tryStaticEvaluation(binding.value, binding.scope, opts);
- }
}
break;
}

Add resolveIndirection to js-ast-utils (#569)