import * as t from "@babel/types"; import { decode } from "html-entities"; import { getConfig, isDynamic, registerImportMethod, filterChildren, getCoverageIgnoreComments, reclaimCoverageIgnoreComments, takeCoverageIgnoreCommentsForParent, trimWhitespace, transformCondition, convertJSXIdentifier } from "./utils"; import { transformNode, getCreateTemplate, thisTagIdentifiers } from "./transform"; import { markPropsLiteral } from "../ssr/props"; import { decodedAttrValue } from "../universal/element"; import { sourceNames, type PluginConfig } from "../config"; import { sourceLocation } from "./location"; import type { BabelPath, JSXNode, TransformResult } from "../types"; type JSXAttributePath = BabelPath; type ComponentTransformResult = TransformResult & { template: ""; component: true; exprs: Array; }; type ComponentChildrenResult = [t.Expression, boolean, t.Comment[]?] | undefined; function isSimpleOptionalMemberExpression( expression: t.Expression | t.JSXEmptyExpression ): expression is t.OptionalMemberExpression & { object: t.Identifier; property: t.Identifier; } { return ( t.isOptionalMemberExpression(expression) && !expression.computed && t.isIdentifier(expression.object) && t.isIdentifier(expression.property) ); } function convertComponentIdentifier( node: t.JSXIdentifier | t.JSXMemberExpression | t.JSXNamespacedName ): t.Expression { if (t.isJSXIdentifier(node)) { if (node.name === "this") return t.thisExpression(); if (t.isValidIdentifier(node.name)) { const identifier = node as unknown as t.Identifier; identifier.type = "Identifier"; return identifier; } else return t.stringLiteral(node.name); } else if (t.isJSXMemberExpression(node)) { const prop = convertComponentIdentifier(node.property); const computed = t.isStringLiteral(prop); return t.memberExpression( convertComponentIdentifier(node.object), prop as t.Identifier | t.Expression, computed ); } return t.stringLiteral(`${node.namespace.name}:${node.name.name}`); } /** * The tag as written in source (`Home`, `Ui.Button`, `this.Row`) — the label * `sourceNames.components` emits. Read before `convertComponentIdentifier` since that * retypes the JSX identifier nodes in place. */ function jsxTagName(node: t.JSXIdentifier | t.JSXMemberExpression | t.JSXNamespacedName): string { if (t.isJSXIdentifier(node)) return thisTagIdentifiers.has(node) ? "this" : node.name; if (t.isJSXMemberExpression(node)) return `${jsxTagName(node.object)}.${jsxTagName(node.property)}`; return `${node.namespace.name}:${node.name.name}`; } export default function transformComponent( path: BabelPath ): ComponentTransformResult { let exprs: Array = [], config = getConfig(path), tagName = jsxTagName(path.node.openingElement.name), tagId = convertComponentIdentifier(path.node.openingElement.name), props: t.Expression[] = [], runningObject: Array = [], dynamicSpread = false, hasChildren = path.node.children.length > 0; // Each props literal this call emits is a candidate for the SSR hoisted // shape (ssr/props.ts), decided at Program exit once every body is final. const propsLiteral = (properties: Array) => { const literal = t.objectExpression(properties); markPropsLiteral(literal, path, config); return literal; }; if ( t.isIdentifier(tagId) && config.builtIns.indexOf(tagId.name) > -1 && !path.scope.hasBinding(tagId.name) ) { const newTagId = registerImportMethod(path, tagId.name); tagId.name = newTagId.name; } path .get("openingElement") .get("attributes") .forEach((attribute: JSXAttributePath) => { const node = attribute.node; if (t.isJSXSpreadAttribute(node)) { if (runningObject.length) { props.push(propsLiteral(runningObject)); runningObject = []; } props.push( isDynamic(attribute.get("argument"), { checkMember: true }) && (dynamicSpread = true) ? // Always a thunk, never the bare callee of `{...fn()}`: // mergeProps memoizes a function source and a memo passes its // previous value, so `fn` would be called with it (#4964). t.arrowFunctionExpression([], node.argument) : (node.argument as t.Expression) ); } else if (t.isJSXAttribute(node)) { const value = decodedAttrValue(node.value) || t.booleanLiteral(true), id = convertJSXIdentifier(node.name), key = t.isIdentifier(id) ? id.name : (id as t.StringLiteral).value; if (hasChildren && key === "children") return; if (t.isJSXExpressionContainer(value)) if (key === "ref") { // Normalize expressions for non-null and type-as while ( t.isTSNonNullExpression(value.expression) || t.isTSAsExpression(value.expression) || t.isTSSatisfiesExpression(value.expression) ) { value.expression = value.expression.expression; } let binding, isConstant = t.isIdentifier(value.expression) && (binding = path.scope.getBinding(value.expression.name)) && (binding.kind === "const" || binding.kind === "module"); if (!isConstant && t.isLVal(value.expression)) { const refIdentifier = path.scope.generateUidIdentifier("_ref$"); runningObject.push( t.objectMethod( "method", t.identifier("ref"), [t.identifier("r$")], t.blockStatement([ t.variableDeclaration("var", [ t.variableDeclarator(refIdentifier, value.expression) ]), t.expressionStatement( t.conditionalExpression( t.logicalExpression( "||", t.binaryExpression( "===", t.unaryExpression("typeof", refIdentifier), t.stringLiteral("function") ), t.callExpression( t.memberExpression(t.identifier("Array"), t.identifier("isArray")), [refIdentifier] ) ), t.callExpression(registerImportMethod(path, "applyRef"), [ refIdentifier, t.identifier("r$") ]), t.assignmentExpression("=", value.expression, t.identifier("r$")) ) ) ]) ) ); } else if (!isConstant && isSimpleOptionalMemberExpression(value.expression)) { const refIdentifier = path.scope.generateUidIdentifier("_ref$"); const object = value.expression.object; const property = value.expression.property; runningObject.push( t.objectMethod( "method", t.identifier("ref"), [t.identifier("r$")], t.blockStatement([ t.variableDeclaration("var", [ t.variableDeclarator(refIdentifier, value.expression) ]), t.expressionStatement( t.conditionalExpression( t.logicalExpression( "||", t.binaryExpression( "===", t.unaryExpression("typeof", refIdentifier), t.stringLiteral("function") ), t.callExpression( t.memberExpression(t.identifier("Array"), t.identifier("isArray")), [refIdentifier] ) ), t.callExpression(registerImportMethod(path, "applyRef"), [ refIdentifier, t.identifier("r$") ]), t.logicalExpression( "&&", t.unaryExpression("!", t.unaryExpression("!", t.identifier(object.name))), t.assignmentExpression( "=", t.memberExpression( t.identifier(object.name), t.identifier(property.name) ), t.identifier("r$") ) ) ) ) ]) ) ); } else if ( isConstant || t.isFunction(value.expression) || t.isArrayExpression(value.expression) ) { runningObject.push( t.objectProperty(t.identifier("ref"), value.expression as t.Expression) ); } else if (t.isCallExpression(value.expression)) { const refIdentifier = path.scope.generateUidIdentifier("_ref$"); exprs.push( t.variableDeclaration("var", [ t.variableDeclarator(refIdentifier, value.expression) ]) ); runningObject.push( t.objectMethod( "method", t.identifier("ref"), [t.identifier("r$")], t.blockStatement([ t.expressionStatement( t.logicalExpression( "&&", t.logicalExpression( "||", t.binaryExpression( "===", t.unaryExpression("typeof", refIdentifier), t.stringLiteral("function") ), t.callExpression( t.memberExpression(t.identifier("Array"), t.identifier("isArray")), [refIdentifier] ) ), t.callExpression(registerImportMethod(path, "applyRef"), [ refIdentifier, t.identifier("r$") ]) ) ) ]) ) ); } } else if ( isDynamic(attribute.get("value").get("expression"), { checkMember: true, checkTags: true }) ) { // No ssr gate: the condition memo must exist on BOTH generates — // the server sync memo allocates an owner id just like the // client's, so skipping it server-side drifts every hydration id // the prop's branch content allocates (#2959, component flavor). // Matches the children-conditional wrap above (transform.ts). if ( config.wrapConditionals && (t.isLogicalExpression(value.expression) || t.isConditionalExpression(value.expression)) ) { const expr = transformCondition(attribute.get("value").get("expression"), true); // Getter keys are never computed: `id` is an identifier or a // string literal (`get "aria-label"()`), the same property as // `get ["aria-label"]()` but on V8's object-literal boilerplate // path — a computed key drops the whole literal to per-property // runtime definition (#3511). Same at every getter site below // and in dom/ssr/universal element.ts. runningObject.push( t.objectMethod( "get", id, [], t.blockStatement([t.returnStatement(expr.body)]), false ) ); } else if ( t.isCallExpression(value.expression) && t.isArrowFunctionExpression(value.expression.callee) && value.expression.callee.params.length === 0 ) { const callee = value.expression.callee; const body = t.isBlockStatement(callee.body) ? callee.body : t.blockStatement([t.returnStatement(callee.body)]); runningObject.push(t.objectMethod("get", id, [], body, false)); } else { runningObject.push( t.objectMethod( "get", id, [], t.blockStatement([t.returnStatement(value.expression as t.Expression)]), false ) ); } } else runningObject.push(t.objectProperty(id, value.expression as t.Expression)); else runningObject.push(t.objectProperty(id, value)); } }); const childResult = transformComponentChildren(path.get("children"), config); // Pragmas written immediately before this component (a parent's // `filterChildren` hand-off) lead this getter, not the parent's (#2138). // When there is no children getter to put them on, leave them on the path // so the parent can fall back (#4701). const beforeComponentComments = getCoverageIgnoreComments(path); if (childResult) { if (childResult[1]) { const body = t.isCallExpression(childResult[0]) && t.isFunction(childResult[0].arguments[0]) ? (childResult[0].arguments[0] as t.Function).body : t.isFunction(childResult[0]) ? childResult[0].body : childResult[0]; const getter = t.objectMethod( "get", t.identifier("children"), [], t.isExpression(body) ? t.blockStatement([t.returnStatement(body)]) : body ); const coverageComments = [...(beforeComponentComments ?? []), ...(childResult[2] ?? [])]; if (coverageComments.length) { getter.leadingComments = coverageComments; // Consumed — parent must not also fall back these onto its getter. path.setData("solid.coverageIgnoreComments", undefined); } runningObject.push(getter); } else runningObject.push(t.objectProperty(t.identifier("children"), childResult[0])); } if (runningObject.length || !props.length) props.push(propsLiteral(runningObject)); if (props.length > 1 || dynamicSpread) { props = [t.callExpression(registerImportMethod(path, "mergeProps"), props)]; } const componentArgs = [tagId, props[0]]; // `sourceNames.components` carries the source tag name into the call so the // dev/observe runtimes can label the owner after minification renames the // function — on the client (`createComponent` in solid-js's client entry) // and on the server (its server entry's, which runs the body under a // transparent `` owner in observe/dev so a server finding's // `ownerPath` reads like the client's). Not for the universal renderer, // whose `createComponent` is user code with a two-argument contract, nor // the dynamic renderer's subtrees. const labelled = sourceNames(config).components && (config.generate === "dom" || config.generate === "ssr"); if (labelled) { componentArgs.push(t.stringLiteral(tagName)); // `sourceNames.locations`: the opening element's start (` 1) { const ret = exprs.pop(); exprs = [ t.callExpression( t.arrowFunctionExpression( [], t.blockStatement([...(exprs as t.Statement[]), t.returnStatement(ret as t.Expression)]) ), [] ) ]; } return { exprs, template: "", component: true, declarations: [], dynamics: [] }; } function transformComponentChildren( children: BabelPath[], config: PluginConfig ): ComponentChildrenResult { const filteredChildren = filterChildren(children); if (!filteredChildren.length) return; let dynamic = false; let pathNodes: t.Node[] = []; let coverageIgnoreComments: t.Comment[] | undefined; let transformedChildren: t.Expression | t.Expression[] = filteredChildren.reduce( (memo: t.Expression[], path: BabelPath) => { const taken = takeCoverageIgnoreCommentsForParent(path); if (taken?.length) { coverageIgnoreComments = [...(coverageIgnoreComments ?? []), ...taken]; } if (t.isJSXText(path.node)) { const v = decode(trimWhitespace((path.node.extra?.raw as string | undefined) ?? "")); if (v.length) { pathNodes.push(path.node); memo.push(t.stringLiteral(v)); } } else { const child = transformNode(path, { topLevel: true, componentChild: true, lastElement: true }); // Nested component with no children getter leaves the hand-off on the // path (fragments transparent) — reclaim for this parent's getter (#4701). const reclaimed = reclaimCoverageIgnoreComments(path); if (reclaimed?.length) { coverageIgnoreComments = [...(coverageIgnoreComments ?? []), ...reclaimed]; } if (!child) return memo; dynamic = dynamic || !!child.dynamic; if ( config.generate === "ssr" && !config.memoWrapper && filteredChildren.length > 1 && child.dynamic && t.isFunction(child.exprs[0]) ) { child.exprs[0] = child.exprs[0].body; } pathNodes.push(path.node); memo.push( getCreateTemplate(config, path, child)( path, child, filteredChildren.length > 1 ) as t.Expression ); } return memo; }, [] ); if (Array.isArray(transformedChildren) && transformedChildren.length === 1) { transformedChildren = transformedChildren[0]; if ( !t.isJSXExpressionContainer(pathNodes[0]) && !t.isJSXSpreadChild(pathNodes[0]) && !t.isJSXText(pathNodes[0]) ) { transformedChildren = t.isCallExpression(transformedChildren) && !transformedChildren.arguments.length && !t.isIdentifier(transformedChildren.callee) ? (transformedChildren.callee as t.Expression) : t.arrowFunctionExpression([], transformedChildren); dynamic = true; } } else if (Array.isArray(transformedChildren)) { transformedChildren = t.arrowFunctionExpression([], t.arrayExpression(transformedChildren)); dynamic = true; } return [transformedChildren as t.Expression, dynamic, coverageIgnoreComments]; }