1 /**
2 * A minimal, side-effect-free evaluator for the ESTree expressions that MDX
3 * attaches to `{...}` expression nodes and `export const` statements.
4 *
5 * It's intentionally limited to the constructs used in documentation pages
6 * (identifiers, member access, literals, template literals, and simple
7 * operators). Anything else resolves to {@link UNRESOLVED} so callers can decide
8 * what to do with it instead of leaking a raw `{expression}` into the output.
9 */
10
11 /* eslint-disable @typescript-eslint/no-explicit-any */
12
13 export const UNRESOLVED = Symbol("unresolved-expression")
14
15 export type EvaluationScope = Record<string, unknown>
16
17 type AstNode = {
18 type?: string
19 [key: string]: any
20 }
21
22 const isResolved = (value: unknown): boolean => value !== UNRESOLVED
23
24 /**
25 * Evaluates an ESTree expression node against `scope`.
26 *
27 * @returns the resolved value, or {@link UNRESOLVED} if the expression uses a
28 * construct or a variable that can't be resolved statically.
29 */
30 export const evaluateExpression = (
31 expression: AstNode | undefined | null,
32 scope: EvaluationScope
33 ): unknown => {
34 if (!expression?.type) {
35 return UNRESOLVED
36 }
37
38 switch (expression.type) {
39 case "Literal":
40 return expression.value
41 case "Identifier":
42 return expression.name in scope ? scope[expression.name] : UNRESOLVED
43 case "MemberExpression": {
44 const object = evaluateExpression(expression.object, scope)
45 if (!isResolved(object) || object === null || object === undefined) {
46 return UNRESOLVED
47 }
48 const key = expression.computed
49 ? evaluateExpression(expression.property, scope)
50 : expression.property?.name
51 if (!isResolved(key) || key === undefined) {
52 return UNRESOLVED
53 }
54 const value = (object as Record<string, unknown>)[key as string]
55 return value === undefined ? UNRESOLVED : value
56 }
57 case "TemplateLiteral": {
58 const quasis: AstNode[] = expression.quasis || []
59 const expressions: AstNode[] = expression.expressions || []
60 let result = ""
61 for (let i = 0; i < quasis.length; i++) {
62 result += quasis[i].value?.cooked ?? quasis[i].value?.raw ?? ""
63 if (i < expressions.length) {
64 const value = evaluateExpression(expressions[i], scope)
65 const stringified = isResolved(value)
66 ? stringifyValue(value)
67 : undefined
68 if (stringified === undefined) {
69 return UNRESOLVED
70 }
71 result += stringified
72 }
73 }
74 return result
75 }
76 case "BinaryExpression": {
77 if (expression.operator !== "+") {
78 return UNRESOLVED
79 }
80 const left = evaluateExpression(expression.left, scope)
81 const right = evaluateExpression(expression.right, scope)
82 if (!isResolved(left) || !isResolved(right)) {
83 return UNRESOLVED
84 }
85 return (left as any) + (right as any)
86 }
87 case "LogicalExpression": {
88 const left = evaluateExpression(expression.left, scope)
89 if (!isResolved(left)) {
90 return UNRESOLVED
91 }
92 switch (expression.operator) {
93 case "||":
94 if (left) {
95 return left
96 }
97 break
98 case "??":
99 if (left !== null && left !== undefined) {
100 return left
101 }
102 break
103 case "&&":
104 if (!left) {
105 return left
106 }
107 break
108 default:
109 return UNRESOLVED
110 }
111 return evaluateExpression(expression.right, scope)
112 }
113 case "ConditionalExpression": {
114 const test = evaluateExpression(expression.test, scope)
115 if (!isResolved(test)) {
116 return UNRESOLVED
117 }
118 return evaluateExpression(
119 test ? expression.consequent : expression.alternate,
120 scope
121 )
122 }
123 case "ArrayExpression": {
124 const elements: unknown[] = []
125 for (const element of expression.elements || []) {
126 const value = evaluateExpression(element, scope)
127 if (!isResolved(value)) {
128 return UNRESOLVED
129 }
130 elements.push(value)
131 }
132 return elements
133 }
134 case "ObjectExpression": {
135 const object: Record<string, unknown> = {}
136 for (const property of expression.properties || []) {
137 if (property.type !== "Property" || property.computed) {
138 return UNRESOLVED
139 }
140 const key = property.key?.name ?? property.key?.value
141 if (key === undefined) {
142 return UNRESOLVED
143 }
144 const value = evaluateExpression(property.value, scope)
145 if (!isResolved(value)) {
146 return UNRESOLVED
147 }
148 object[key] = value
149 }
150 return object
151 }
152 default:
153 return UNRESOLVED
154 }
155 }
156
157 /**
158 * Evaluates the single expression of an MDX `{...}` node's estree program.
159 */
160 export const evaluateEstreeExpression = (
161 estree: AstNode | undefined,
162 scope: EvaluationScope
163 ): unknown => {
164 const statement = estree?.body?.find(
165 (node: AstNode) => node.type === "ExpressionStatement"
166 )
167
168 return statement
169 ? evaluateExpression(statement.expression, scope)
170 : UNRESOLVED
171 }
172
173 /**
174 * Collects the `export const`/`const` declarations of an MDX ESM node into
175 * `scope`, so that later expressions in the same page can reference them.
176 *
177 * Declarations are evaluated in order against the scope built so far, which
178 * matches how MDX itself resolves them.
179 */
180 export const collectDeclarations = (
181 estree: AstNode | undefined,
182 scope: EvaluationScope
183 ): void => {
184 for (const node of estree?.body || []) {
185 const declaration =
186 node.type === "ExportNamedDeclaration" ? node.declaration : node
187
188 if (declaration?.type !== "VariableDeclaration") {
189 continue
190 }
191
192 for (const declarator of declaration.declarations || []) {
193 if (declarator.id?.type !== "Identifier") {
194 continue
195 }
196 const value = evaluateExpression(declarator.init, scope)
197 if (isResolved(value)) {
198 scope[declarator.id.name] = value
199 }
200 }
201 }
202 }
203
204 /**
205 * Converts a resolved value into the string that should replace the expression
206 * in the Markdown output. Objects and functions have no meaningful Markdown
207 * representation, so they resolve to `undefined` and the expression is dropped.
208 */
209 export const stringifyValue = (value: unknown): string | undefined => {
210 switch (typeof value) {
211 case "string":
212 return value
213 case "number":
214 case "boolean":
215 case "bigint":
216 return String(value)
217 default:
218 return undefined
219 }
220 }