babel-plugin-essor 0.0.15-beta.5 → 0.0.15-beta.7

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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/program.ts","../src/import.ts","../../shared/src/is.ts","../../shared/src/base.ts","../../shared/src/string.ts","../../shared/src/logger.ts","../../shared/src/escape.ts","../../shared/src/dom.ts","../src/constants.ts","../src/signals/symbol.ts","../src/signals/utils.ts","../src/signals/props.ts","../src/jsx/context.ts","../src/jsx/client.ts","../src/jsx/constants.ts","../src/jsx/shared.ts","../src/jsx/tree.ts","../src/jsx/ssg.ts","../src/jsx/index.ts","../src/index.ts"],"sourcesContent":["import { type NodePath, types as t } from '@babel/core';\nimport { addImport, clearImport, createImport, createImportIdentifiers, importMap } from './import';\nimport { DEFAULT_OPTIONS } from './constants';\nimport {\n replaceSymbol,\n symbolArrayPattern,\n symbolAssignment,\n symbolIdentifier,\n symbolObjectPattern,\n symbolUpdate,\n} from './signals/symbol';\nimport type { PluginState } from './types';\n\n// ============================================\n// Virtual module path - unified use of virtual:essor-hmr\n// ============================================\nfunction getHmrModulePath(): string {\n return '/@essor-refresh';\n}\n// ============================================\n// Create import identifier\n// ============================================\nexport function createImportIdentifier(path: babel.NodePath, importName: string): t.Identifier {\n const source = getHmrModulePath();\n const program = path.scope.getProgramParent().path as babel.NodePath<t.Program>;\n\n // Check if already imported\n let importId: t.Identifier | undefined;\n\n program.traverse({\n ImportDeclaration(importPath) {\n if (importPath.node.source.value === source) {\n const specifier = importPath.node.specifiers.find(\n spec =>\n t.isImportSpecifier(spec) &&\n t.isIdentifier(spec.imported) &&\n spec.imported.name === importName,\n );\n if (specifier && t.isImportSpecifier(specifier)) {\n importId = specifier.local;\n }\n }\n },\n });\n\n if (!importId) {\n // Create new import\n importId = path.scope.generateUidIdentifier(importName);\n const importDecl = t.importDeclaration(\n [t.importSpecifier(importId, t.identifier(importName))],\n t.stringLiteral(source),\n );\n\n // Insert import at the top of program\n program.unshiftContainer('body', importDecl);\n }\n\n return importId;\n}\n\n/**\n * Helper function to automatically set state for visitor paths.\n * This ensures that paths created by traverse() inherit the parent state.\n */\nfunction withState<T>(visitor: (path: NodePath<T>) => void, parentState: any) {\n return (path: NodePath<T>) => {\n path.state = parentState;\n visitor(path);\n };\n}\n\nexport const transformProgram = {\n enter: (path: NodePath<t.Program>, state) => {\n const opts = { ...DEFAULT_OPTIONS, ...state.opts };\n const imports = createImportIdentifiers(path);\n\n // Clear any previous import state to ensure clean transformation\n clearImport();\n\n // Extend path state with plugin-specific data\n path.state = {\n ...state,\n opts,\n imports,\n declarations: [], // Collect template declarations during transformation\n filename: state.filename,\n events: new Set(), // Track delegated events for optimization\n };\n\n // Transform signals BEFORE JSX transformation\n // This ensures that when JSX transformer extracts expression.node,\n // signal variables have already been transformed to access .value\n const parentState = path.state;\n\n path.traverse({\n VariableDeclarator: withState(replaceSymbol, parentState), // let $x = 0 → let $x = signal(0)\n Identifier: withState(symbolIdentifier, parentState), // $x → $x.value\n AssignmentExpression: withState(symbolAssignment, parentState), // $x = 1 → $x.value = 1\n UpdateExpression: withState(symbolUpdate, parentState), // $x++ → $x.value++\n ObjectPattern: withState(symbolObjectPattern, parentState), // { $x } → handle nested patterns\n ArrayPattern: withState(symbolArrayPattern, parentState), // [$x] → handle nested patterns\n });\n },\n\n // eslint-disable-next-line unused-imports/no-unused-vars\n exit: (path: NodePath<t.Program>, state) => {\n const pluginState: PluginState = path.state as PluginState;\n const { imports, declarations, events } = pluginState;\n // const mode = (opts?.mode || RENDER_MODE.CLIENT) as RENDER_MODE;\n\n // Find optimal insertion point after imports but before other code\n const insertIndex = path.node.body.findIndex(\n node => !t.isImportDeclaration(node) && !t.isExportDeclaration(node),\n );\n\n // Insert template declarations for reactive components\n if (declarations?.length) {\n const templateDeclaration = t.variableDeclaration('const', declarations);\n\n // Insert at the appropriate location to maintain code organization\n if (insertIndex !== -1) {\n path.node.body.splice(insertIndex, 0, templateDeclaration);\n } else {\n path.node.body.push(templateDeclaration);\n }\n }\n\n // Setup event delegation for performance optimization\n if (events && events.size > 0) {\n const eventsDeclaration = t.expressionStatement(\n t.callExpression(imports.delegateEvents, [\n t.arrayExpression(Array.from(events).map(event => t.stringLiteral(event))),\n ]),\n );\n addImport(importMap.delegateEvents);\n path.node.body.push(eventsDeclaration);\n }\n\n // Generate and insert required import statements\n createImport(path, imports, 'essor');\n },\n};\n","import { type NodePath, types as t } from '@babel/core';\nimport { error } from '@estjs/shared';\nimport { IMPORTS_MAPS, RENDER_MODE, SSG_IMPORTS_MAPS, SSR_IMPORTS_MAPS } from './constants';\nimport type { PluginState } from './types';\n\nexport type IMPORT_MAP_NAMES = (typeof IMPORTS_MAPS)[number];\n/**\n * Generates a set of unique import identifiers for a given program path.\n\n * @param path - The program path used to generate unique identifiers.\n * @returns A record mapping import names to their corresponding unique identifiers.\n * @throws Will throw an error if identifier generation fails for any import.\n */\nexport function createImportIdentifiers(path: NodePath<t.Program>) {\n // Initialize all required identifiers\n const identifiers = IMPORTS_MAPS.reduce<Record<string, t.Identifier>>((acc, name) => {\n // Generate unique identifier\n const identifier = path.scope?.generateUidIdentifier(`${name}$`) ?? t.identifier(`${name}$`);\n\n // Ensure identifier is valid\n if (!identifier) {\n throw new Error(`Failed to generate identifier for ${name}`);\n }\n acc[name] = identifier;\n return acc;\n }, {});\n\n return identifiers;\n}\nexport const importMap = IMPORTS_MAPS.reduce(\n (acc, name) => ({ ...acc, [name]: name }),\n {},\n) as Record<IMPORT_MAP_NAMES, IMPORT_MAP_NAMES>;\n\n// imported sets\nexport const importedSets = new Set<IMPORT_MAP_NAMES>();\n\n/**\n * Adds the given import name to the set of imported names.\n *\n * @param name The name of the import to add.\n */\nexport function addImport(name: IMPORT_MAP_NAMES): void {\n importedSets.add(name);\n}\n\n/**\n * Clears the set of imported names.\n *\n * This function is useful when the state of the imported names needs to be reset.\n * It will be called when the babel plugin is finished processing the current\n * file.\n */\nexport function clearImport(): void {\n importedSets.clear();\n}\n/**\n * Creates an import declaration for given program path.\n *\n * @param {NodePath<t.Program>} path The program path\n * @param {Record<string, t.Identifier>} imports Imported identifiers\n * @param {string} from The module path to import\n */\nexport function createImport(\n path: NodePath<t.Program>,\n imports: Record<string, t.Identifier>,\n from: string,\n): void {\n const state = path.state as PluginState;\n\n const mode = state.opts.mode;\n\n // Return early if no functions to import\n if (!importedSets.size) {\n return;\n }\n try {\n // Create import specifiers\n const importSpecifiers = Array.from(importedSets).map(name => {\n const importIdentifier = imports[name];\n if (!importIdentifier) {\n throw new Error(`Import identifier not found for: ${name}`);\n }\n const local = t.identifier(importIdentifier.name);\n if (mode === RENDER_MODE.SSG) {\n name = SSG_IMPORTS_MAPS[name] || name;\n }\n if (mode === RENDER_MODE.SSR) {\n name = SSR_IMPORTS_MAPS[name] || name;\n }\n const imported = t.identifier(name);\n return t.importSpecifier(local, imported);\n });\n\n // Create and insert import declaration at program start\n const importDeclaration = t.importDeclaration(importSpecifiers, t.stringLiteral(from));\n\n path.node.body.unshift(importDeclaration);\n } catch (error_) {\n error('Failed to create import declaration:', error);\n throw error_;\n }\n}\n","import { _toString } from './base';\n\n/**\n * Checks if a value is an object\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is an object, false otherwise\n */\nexport const isObject = (val: unknown): val is Record<any, unknown> =>\n val !== null && typeof val === 'object';\n\n/**\n * Checks if a value is a Promise\n * @template T - The type of the Promise's resolved value\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a Promise, false otherwise\n */\nexport function isPromise<T = unknown>(val: unknown): val is Promise<T> {\n return _toString.call(val) === '[object Promise]';\n}\n\n/**\n * Checks if a value is an Array\n * @type {(arg: unknown ) => arg is unknown []}\n */\nexport const isArray = Array.isArray;\n\n/**\n * Checks if a value is a string\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a string, false otherwise\n */\nexport function isString(val: unknown): val is string {\n return typeof val === 'string';\n}\n\n/**\n * Checks if a value is a number\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a number, false otherwise\n */\nexport function isNumber(val: unknown): val is number {\n return typeof val === 'number';\n}\n/**\n * Checks if a value is null\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is null, false otherwise\n */\nexport function isNull(val: unknown): val is null {\n return val === null;\n}\n\n/**\n * Checks if a value is a Symbol\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a Symbol, false otherwise\n */\nexport function isSymbol(val: unknown): val is symbol {\n return typeof val === 'symbol';\n}\n\n/**\n * Checks if a value is a Set\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a Set, false otherwise\n */\nexport function isSet(val: unknown): val is Set<unknown> {\n return _toString.call(val) === '[object Set]';\n}\n\n/**\n * Checks if a value is a WeakMap\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a WeakMap, false otherwise\n */\nexport function isWeakMap(val: unknown): val is WeakMap<any, unknown> {\n return _toString.call(val) === '[object WeakMap]';\n}\n\n/**\n * Checks if a value is a WeakSet\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a WeakSet, false otherwise\n */\nexport function isWeakSet(val: unknown): val is WeakSet<any> {\n return _toString.call(val) === '[object WeakSet]';\n}\n\n/**\n * Checks if a value is a Map\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a Map, false otherwise\n */\nexport function isMap(val: unknown): val is Map<unknown, unknown> {\n return _toString.call(val) === '[object Map]';\n}\n\n/**\n * Checks if a value is null or undefined\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is null or undefined, false otherwise\n */\nexport function isNil(val: unknown): val is null | undefined {\n return val === null || val === undefined;\n}\n\n/**\n * Checks if a value is a function\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a function, false otherwise\n */\nexport const isFunction = (val: unknown): val is Function => typeof val === 'function';\n\n/**\n * Checks if a value is falsy (false, null, or undefined)\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is falsy, false otherwise\n */\nexport function isFalsy(val: unknown): val is false | null | undefined {\n return val === false || val === null || val === undefined;\n}\n\n/**\n * Checks if a value is a primitive type (string, number, boolean, symbol, null, or undefined)\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a primitive type, false otherwise\n */\nexport const isPrimitive = (\n val: unknown,\n): val is string | number | boolean | symbol | null | undefined =>\n ['string', 'number', 'boolean', 'symbol', 'undefined'].includes(typeof val) || isNull(val);\n\n/**\n * Checks if a value is an HTMLElement\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is an HTMLElement, false otherwise\n */\nexport function isHTMLElement(val: unknown): val is HTMLElement {\n return val instanceof HTMLElement;\n}\n\n/**\n * Checks if a value is a plain object (created using Object constructor)\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a plain object, false otherwise\n */\nexport const isPlainObject = (val: unknown): val is object =>\n _toString.call(val) === '[object Object]';\n\n/**\n * String representation of a number\n * @typedef {`${number}`} StringNumber\n */\nexport type StringNumber = `${number}`;\n\n/**\n * Checks if a value is a string representation of a number\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a string number, false otherwise\n */\nexport function isStringNumber(val: unknown): val is StringNumber {\n if (!isString(val) || val === '') {\n return false;\n }\n return !Number.isNaN(Number(val));\n}\n\n/**\n * Checks if a value is undefined\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is undefined, false otherwise\n */\nexport function isUndefined(val: unknown): val is undefined {\n return typeof val === 'undefined';\n}\n\n/**\n * Checks if a value is a boolean\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a boolean, false otherwise\n */\nexport function isBoolean(val: unknown): val is boolean {\n return typeof val === 'boolean';\n}\n\nexport function isNaN(val: unknown): val is number {\n return Number.isNaN(val);\n}\n","import { isArray, isFunction, isString } from './is';\n\n/**\n * Reference to Object.prototype.toString\n * @type {Function}\n */\nexport const _toString = Object.prototype.toString;\nconst hasOwnProperty = Object.prototype.hasOwnProperty;\n\n/**\n * Reference to Object.assign\n * @type {Function}\n */\nexport const extend = Object.assign;\n\n/**\n * Checks if an object has a specific property\n * @template T\n * @param {object} val - The target object to check\n * @param {string | symbol} key - The property name to check for\n * @returns {key is keyof T} - Returns true if the object has the property, false otherwise\n */\nexport const hasOwn = (val: object, key: string | symbol): key is keyof typeof val =>\n hasOwnProperty.call(val, key);\n/**\n * Forces a value to be an array\n * @template T - The type of array elements\n * @param {T | T[]} data - The data to convert, can be a single element or an array\n * @returns {T[]} - The resulting array\n */\nexport function coerceArray<T>(data: T | T[]): T[] {\n return isArray(data) ? data : [data];\n}\n\n/**\n * Checks if a value has changed\n * @param {unknown } value - The new value\n * @param {unknown } oldValue - The old value\n * @returns {boolean} - Returns true if the value has changed, false otherwise\n */\nexport const hasChanged = (value: unknown, oldValue: unknown): boolean =>\n !Object.is(value, oldValue);\n\n/**\n * Empty function, used for defaults and placeholders\n * @type {Function}\n */\nexport const noop = Function.prototype as () => void;\n\n/**\n * Checks if a string starts with a specified substring\n *\n * Uses indexOf for better performance in most cases\n * @see https://www.measurethat.net/Benchmarks/Show/12350/0/startswith-vs-test-vs-match-vs-indexof#latest_results_block\n * @param {string} str - The string to check\n * @param {string} searchString - The substring to search for\n * @returns {boolean} - Returns true if the string starts with the substring, false otherwise\n */\nexport function startsWith(str: string, searchString: string): boolean {\n if (!isString(str)) {\n return false;\n }\n return str.indexOf(searchString) === 0;\n}\n\n/**\n * Generates an 8-character random string as a unique identifier\n *\n * Note: Uses Math.random() which is not cryptographically secure.\n * For security-sensitive use cases, consider using crypto.getRandomValues()\n * @returns {string} - The generated unique identifier\n */\nexport function generateUniqueId(): string {\n const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n let result = '';\n const charactersLength = characters.length;\n for (let i = 0; i < 8; i++) {\n result += characters.charAt(Math.floor(Math.random() * charactersLength));\n }\n return result;\n}\n\n/**\n * Checks if the current environment is a browser\n * @returns {boolean} - Returns true if in a browser environment, false otherwise\n */\nexport function isBrowser(): boolean {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\n/**\n * Creates a cached version of a string processing function\n * @template T - The function type\n * @param {T} fn - The string processing function to cache\n * @returns {T} - The cached function\n */\nexport const cacheStringFunction = <T extends (str: string) => string>(fn: T): T => {\n const cache: Record<string, string> = Object.create(null);\n return ((str: string) => {\n const hit = cache[str];\n return hit || (cache[str] = fn(str));\n }) as T;\n};\n\n/**\n * Read-only empty object\n * @type {Readonly<Record<string, unknown >>}\n */\nexport const EMPTY_OBJ: { readonly [key: string]: unknown } = Object.freeze({});\n\n/**\n * Read-only empty array\n * @type {readonly never[]}\n */\nexport const EMPTY_ARR: readonly never[] = Object.freeze([]);\n\n/**\n * Checks if a property name is an event handler (starts with 'on' followed by uppercase letter)\n *\n * Matches patterns like: onClick, onChange, onKeyDown (but not 'onclick' or 'on123')\n * @param {string} key - The property name to check\n * @returns {boolean} - Returns true if the property is an event handler, false otherwise\n */\nexport const isOn = (key: string): boolean =>\n key.charCodeAt(0) === 111 /* o */ &&\n key.charCodeAt(1) === 110 /* n */ &&\n key.charCodeAt(2) >= 65 && // uppercase letter A-Z\n key.charCodeAt(2) <= 90;\n\ndeclare let global: {};\n\nlet _globalThis: unknown;\n/**\n * Gets the global object for the current environment\n * @returns {unknown } - The global object for the current environment\n */\nexport const getGlobalThis = (): unknown => {\n return (\n _globalThis ||\n (_globalThis =\n typeof globalThis !== 'undefined'\n ? globalThis\n : typeof self !== 'undefined'\n ? self\n : typeof window !== 'undefined'\n ? window\n : typeof global !== 'undefined'\n ? global\n : {})\n );\n};\n\nexport type ExcludeType = ((key: string | symbol) => boolean) | (string | symbol)[];\n\n/**\n * Checks if a key should be excluded\n * @param {string | symbol} key - The key to check\n * @param {ExcludeType} [exclude] - The exclusion condition, can be a function or array\n * @returns {boolean} - Returns true if the key should be excluded, false otherwise\n */\nexport function isExclude(key: string | symbol, exclude?: ExcludeType): boolean {\n if (!exclude) {\n return false;\n }\n return isArray(exclude) ? exclude.includes(key) : isFunction(exclude) ? exclude(key) : false;\n}\n","import { cacheStringFunction } from './base';\n\n/**\n * Regular expression for converting camelCase to kebab-case\n * @type {RegExp}\n */\nconst hyphenateRE = /\\B([A-Z])/g;\n\n/**\n * Converts a camelCase string to kebab-case\n * Example: myFunction -> my-function\n * @param {string} str - The camelCase string to convert\n * @returns {string} - The kebab-case string\n */\nexport const kebabCase: (str: string) => string = cacheStringFunction((str: string) =>\n str.replaceAll(hyphenateRE, '-$1').toLowerCase(),\n);\n\n/**\n * Regular expression for converting kebab-case or snake_case to camelCase\n * @type {RegExp}\n */\nconst camelizeRE = /[_-](\\w)/g;\n\n/**\n * Converts a kebab-case or snake_case string to camelCase\n * Example: my-function or my_function -> myFunction\n * @param {string} str - The kebab-case or snake_case string to convert\n * @returns {string} - The camelCase string\n */\nexport const camelCase: (str: string) => string = cacheStringFunction((str: string): string => {\n // Remove leading and trailing hyphens or underscores\n str = str.replaceAll(/^[_-]+|[_-]+$/g, '');\n // Replace consecutive hyphens or underscores with a single hyphen\n str = str.replaceAll(/[_-]+/g, '-');\n // Convert to camelCase\n return str.replaceAll(camelizeRE, (_, c) => c.toUpperCase());\n});\n\n/**\n * Capitalizes the first letter of a string\n * Example: hello -> Hello\n * @template T - The input string type\n * @param {T} str - The string to capitalize\n * @returns {Capitalize<T>} - The capitalized string\n */\nexport const capitalize: <T extends string>(str: T) => Capitalize<T> = cacheStringFunction(\n <T extends string>(str: T) => {\n return (str.charAt(0).toUpperCase() + str.slice(1)) as Capitalize<T>;\n },\n);\n","/**\n * Outputs a warning level log message\n * @param {string} msg - The warning message\n * @param {...unknown } args - Additional arguments to log\n */\nexport function warn(msg: string, ...args: unknown[]): void {\n console.warn(`[Essor warn]: ${msg}`, ...args);\n}\n\n/**\n * Outputs an info level log message\n * @param {string} msg - The info message\n * @param {...unknown } args - Additional arguments to log\n */\nexport function info(msg: string, ...args: unknown[]): void {\n // eslint-disable-next-line no-console\n console.info(`[Essor info]: ${msg}`, ...args);\n}\n\n/**\n * Outputs an error level log message\n * @param {string} msg - The error message\n * @param {...unknown } args - Additional arguments to log\n */\nexport function error(msg: string, ...args: unknown[]): void {\n console.error(`[Essor error]: ${msg}`, ...args);\n}\n","/**\n * Regular expression for matching HTML special characters\n * @type {RegExp}\n */\nconst escapeRE = /[\"&'<>]/;\n\n/**\n * Escapes HTML special characters in a string to their corresponding entity references\n * @param {unknown} string - The string to escapeHTML\n * @returns {string} - The escaped string\n */\nexport function escapeHTML(string: unknown): string {\n const str = `${string}`;\n const match = escapeRE.exec(str);\n\n if (!match) {\n return str;\n }\n\n let html = '';\n let escaped: string;\n let index: number;\n let lastIndex = 0;\n for (index = match.index; index < str.length; index++) {\n switch (str.charCodeAt(index)) {\n case 34: // \"\n escaped = '&quot;';\n break;\n case 38: // &\n escaped = '&amp;';\n break;\n case 39: // '\n escaped = '&#39;';\n break;\n case 60: // <\n escaped = '&lt;';\n break;\n case 62: // >\n escaped = '&gt;';\n break;\n default:\n continue;\n }\n\n if (lastIndex !== index) {\n html += str.slice(lastIndex, index);\n }\n\n lastIndex = index + 1;\n html += escaped;\n }\n\n return lastIndex !== index ? html + str.slice(lastIndex, index) : html;\n}\n\n/**\n * Regular expression for stripping HTML comment markers\n * Reference: https://www.w3.org/TR/html52/syntax.html#comments\n * @type {RegExp}\n */\nconst commentStripRE = /^-?>|<!--|-->|--!>|<!-$/g;\n\n/**\n * Strips special characters from HTML comments\n * @param {string} src - The source string\n * @returns {string} - The cleaned string\n */\nexport function escapeHTMLComment(src: string): string {\n return src.replaceAll(commentStripRE, '');\n}\n\n/**\n * Regular expression for matching special characters in CSS variable names\n * @type {RegExp}\n */\nexport const cssVarNameEscapeSymbolsRE = /[ !\"#$%&'()*+,./:;<=>?@[\\\\\\]^`{|}~]/g;\n\n/**\n * Escapes special characters in CSS variable names\n * @param {string} key - The CSS variable name\n * @param {boolean} doubleEscape - Whether to apply double escaping\n * @returns {string} - The escaped CSS variable name\n */\nexport function getEscapedCssVarName(key: string, doubleEscape: boolean): string {\n return key.replaceAll(cssVarNameEscapeSymbolsRE, s =>\n doubleEscape ? (s === '\"' ? '\\\\\\\\\\\\\"' : `\\\\\\\\${s}`) : `\\\\${s}`,\n );\n}\n","/**\n * Make a map and return a function for checking if a key\n * is in that map.\n * IMPORTANT: all calls of this function must be prefixed with\n * \\/\\*#\\_\\_PURE\\_\\_\\*\\/\n * So that rollup can tree-shake them if necessary.\n */\n\n/*! #__NO_SIDE_EFFECTS__ */\n\nimport { hasOwn } from './base';\nimport { error } from './logger';\n\nexport function makeMap(str: string): (key: string) => boolean {\n const map = Object.create(null);\n for (const key of str.split(',')) {\n map[key] = 1;\n }\n return val => val in map;\n}\n\n/**\n * On the client we only need to offer special cases for boolean attributes that\n * have different names from their corresponding dom properties:\n * - itemscope -> N/A\n * - allowfullscreen -> allowFullscreen\n * - formnovalidate -> formNoValidate\n * - ismap -> isMap\n * - nomodule -> noModule\n * - novalidate -> noValidate\n * - readonly -> readOnly\n */\nconst specialBooleanAttrs =\n 'itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly';\nexport const isSpecialBooleanAttr: (key: string) => boolean =\n /*@__PURE__*/ makeMap(specialBooleanAttrs);\n\n/**\n * The full list is needed during SSR to produce the correct initial markup.\n */\nexport const isBooleanAttr: (key: string) => boolean = /*@__PURE__*/ makeMap(\n `${specialBooleanAttrs},async,autofocus,autoplay,controls,default,defer,disabled,hidden,inert,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected`,\n);\n\n/**\n * Boolean attributes should be included if the value is truthy or ''.\n * e.g. `<select multiple>` compiles to `{ multiple: '' }`\n */\nexport function includeBooleanAttr(value: unknown): boolean {\n return !!value || value === '';\n}\n\nconst unsafeAttrCharRE = /[\\t\\n\\f \"'/=>]/;\nconst attrValidationCache: Record<string, boolean> = {};\n\nexport function isSSRSafeAttrName(name: string): boolean {\n if (hasOwn(attrValidationCache, name)) {\n return attrValidationCache[name];\n }\n const isUnsafe = unsafeAttrCharRE.test(name);\n if (isUnsafe) {\n if (__DEV__) {\n error(`unsafe attribute name: ${name}`);\n }\n }\n return (attrValidationCache[name] = !isUnsafe);\n}\n\nexport const propsToAttrMap: Record<string, string | undefined> = {\n acceptCharset: 'accept-charset',\n className: 'class',\n htmlFor: 'for',\n httpEquiv: 'http-equiv',\n};\n\n/**\n * Known attributes, this is used for stringification of runtime static nodes\n * so that we don't stringify bindings that cannot be set from HTML.\n * Don't also forget to allow `data-*` and `aria-*`!\n * Generated from https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes\n */\nexport const isKnownHtmlAttr: (key: string) => boolean = /*@__PURE__*/ makeMap(\n 'accept,accept-charset,accesskey,action,align,allow,alt,async,' +\n 'autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,' +\n 'border,buffered,capture,challenge,charset,checked,cite,class,code,' +\n 'codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,' +\n 'coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,' +\n 'disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,' +\n 'formaction,formenctype,formmethod,formnovalidate,formtarget,headers,' +\n 'height,hidden,high,href,hreflang,http-equiv,icon,id,importance,inert,integrity,' +\n 'ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,' +\n 'manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,' +\n 'open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,' +\n 'referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,' +\n 'selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,' +\n 'start,step,style,summary,tabindex,target,title,translate,type,usemap,' +\n 'value,width,wrap',\n);\n\n/**\n * Generated from https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute\n */\nexport const isKnownSvgAttr: (key: string) => boolean = /*@__PURE__*/ makeMap(\n 'xmlns,accent-height,accumulate,additive,alignment-baseline,alphabetic,amplitude,' +\n 'arabic-form,ascent,attributeName,attributeType,azimuth,baseFrequency,' +\n 'baseline-shift,baseProfile,bbox,begin,bias,by,calcMode,cap-height,class,' +\n 'clip,clipPathUnits,clip-path,clip-rule,color,color-interpolation,' +\n 'color-interpolation-filters,color-profile,color-rendering,' +\n 'contentScriptType,contentStyleType,crossorigin,cursor,cx,cy,d,decelerate,' +\n 'descent,diffuseConstant,direction,display,divisor,dominant-baseline,dur,dx,' +\n 'dy,edgeMode,elevation,enable-background,end,exponent,fill,fill-opacity,' +\n 'fill-rule,filter,filterRes,filterUnits,flood-color,flood-opacity,' +\n 'font-family,font-size,font-size-adjust,font-stretch,font-style,' +\n 'font-variant,font-weight,format,from,fr,fx,fy,g1,g2,glyph-name,' +\n 'glyph-orientation-horizontal,glyph-orientation-vertical,glyphRef,' +\n 'gradientTransform,gradientUnits,hanging,height,href,hreflang,horiz-adv-x,' +\n 'horiz-origin-x,id,ideographic,image-rendering,in,in2,intercept,k,k1,k2,k3,' +\n 'k4,kernelMatrix,kernelUnitLength,kerning,keyPoints,keySplines,keyTimes,' +\n 'lang,lengthAdjust,letter-spacing,lighting-color,limitingConeAngle,local,' +\n 'marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,' +\n 'mask,maskContentUnits,maskUnits,mathematical,max,media,method,min,mode,' +\n 'name,numOctaves,offset,opacity,operator,order,orient,orientation,origin,' +\n 'overflow,overline-position,overline-thickness,panose-1,paint-order,path,' +\n 'pathLength,patternContentUnits,patternTransform,patternUnits,ping,' +\n 'pointer-events,points,pointsAtX,pointsAtY,pointsAtZ,preserveAlpha,' +\n 'preserveAspectRatio,primitiveUnits,r,radius,referrerPolicy,refX,refY,rel,' +\n 'rendering-intent,repeatCount,repeatDur,requiredExtensions,requiredFeatures,' +\n 'restart,result,rotate,rx,ry,scale,seed,shape-rendering,slope,spacing,' +\n 'specularConstant,specularExponent,speed,spreadMethod,startOffset,' +\n 'stdDeviation,stemh,stemv,stitchTiles,stop-color,stop-opacity,' +\n 'strikethrough-position,strikethrough-thickness,string,stroke,' +\n 'stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,' +\n 'stroke-miterlimit,stroke-opacity,stroke-width,style,surfaceScale,' +\n 'systemLanguage,tabindex,tableValues,target,targetX,targetY,text-anchor,' +\n 'text-decoration,text-rendering,textLength,to,transform,transform-origin,' +\n 'type,u1,u2,underline-position,underline-thickness,unicode,unicode-bidi,' +\n 'unicode-range,units-per-em,v-alphabetic,v-hanging,v-ideographic,' +\n 'v-mathematical,values,vector-effect,version,vert-adv-y,vert-origin-x,' +\n 'vert-origin-y,viewBox,viewTarget,visibility,width,widths,word-spacing,' +\n 'writing-mode,x,x-height,x1,x2,xChannelSelector,xlink:actuate,xlink:arcrole,' +\n 'xlink:href,xlink:role,xlink:show,xlink:title,xlink:type,xmlns:xlink,xml:base,xml:lang,' +\n 'xml:space,y,y1,y2,yChannelSelector,z,zoomAndPan',\n);\n\n/**\n * Shared between server-renderer and runtime-core hydration logic\n */\nexport function isRenderAbleAttrValue(value: unknown): boolean {\n if (value == null) {\n return false;\n }\n const type = typeof value;\n return type === 'string' || type === 'number' || type === 'boolean';\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/HTML/Element\nconst HTML_TAGS =\n 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +\n 'header,hgroup,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,' +\n 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +\n 'data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,' +\n 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +\n 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +\n 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +\n 'option,output,progress,select,textarea,details,dialog,menu,' +\n 'summary,template,blockquote,iframe,tfoot';\n\n// https://developer.mozilla.org/en-US/docs/Web/SVG/Element\nconst SVG_TAGS =\n 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +\n 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +\n 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +\n 'feDistantLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +\n 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +\n 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +\n 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +\n 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +\n 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +\n 'text,textPath,title,tspan,unknown,use,view';\n\n// https://www.w3.org/TR/mathml4/ (content elements excluded)\nconst MATH_TAGS =\n 'annotation,annotation-xml,maction,maligngroup,malignmark,math,menclose,' +\n 'merror,mfenced,mfrac,mfraction,mglyph,mi,mlabeledtr,mlongdiv,' +\n 'mmultiscripts,mn,mo,mover,mpadded,mphantom,mprescripts,mroot,mrow,ms,' +\n 'mscarries,mscarry,msgroup,msline,mspace,msqrt,msrow,mstack,mstyle,msub,' +\n 'msubsup,msup,mtable,mtd,mtext,mtr,munder,munderover,none,semantics';\n\nconst DELEGATED_EVENTS =\n 'beforeinput,click,dblclick,contextmenu,focusin,focusout,input,keydown,' +\n 'keyup,mousedown,mousemove,mouseout,mouseover,mouseup,pointerdown,' +\n 'pointermove,pointerout,pointerover,pointerup,touchend,touchmove,touchstart';\n\nconst VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';\n\nconst SELFCLOSING_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';\n\nexport const isHTMLTag: (key: string) => boolean = /*@__PURE__*/ makeMap(HTML_TAGS);\n\nexport const isSVGTag: (key: string) => boolean = /*@__PURE__*/ makeMap(SVG_TAGS);\n\nexport const isMathMLTag: (key: string) => boolean = /*@__PURE__*/ makeMap(MATH_TAGS);\n\nexport const isVoidTag: (key: string) => boolean = /*@__PURE__*/ makeMap(VOID_TAGS);\n\nexport const isSelfClosingTag: (key: string) => boolean = /*@__PURE__*/ makeMap(SELFCLOSING_TAGS);\n\nexport const isDelegatedEvent: (key: string) => boolean = /*@__PURE__*/ makeMap(DELEGATED_EVENTS);\n","import type { PluginOptions } from './types';\n\n// default options\nexport const DEFAULT_OPTIONS: PluginOptions = {\n mode: 'client',\n symbol: '$',\n props: true,\n hmr: false,\n styled: false,\n};\n\n// Rendering mode\nexport enum RENDER_MODE {\n CLIENT = 'client',\n SSR = 'ssr',\n SSG = 'ssg',\n}\n\nexport const IMPORTS_MAPS = [\n // Reactive API\n 'signal',\n 'computed',\n 'reactive',\n 'memoEffect',\n 'omitProps',\n\n // component\n 'createComponent',\n 'Fragment',\n 'For',\n 'Suspense',\n 'Portal',\n\n // Template related\n 'mapNodes',\n 'template',\n 'delegateEvents',\n // styled\n 'styled',\n // binding related\n 'insert',\n 'patchStyle',\n 'patchClass',\n 'patchAttr',\n 'bindElement',\n 'setSpread',\n 'addEventListener',\n // rendering related\n 'render',\n 'escapeHTML',\n 'getHydrationKey',\n] as const;\n\n// Static Site Generation API\nexport const SSG_IMPORTS_MAPS = {\n createComponent: 'createSSGComponent',\n patchAttr: 'setSSGAttr',\n} as const;\n\n// Server-side Rendering API\nexport const SSR_IMPORTS_MAPS = {\n mapNodes: 'mapSSRNodes',\n template: 'getElement',\n} as const;\n\n// transform property name\nexport const TRANSFORM_PROPERTY_NAME = '__props';\n","/**\n * Signal Symbol Transformer\n *\n * This module provides AST transformation functions for signal variables in the Babel plugin.\n * It handles the detection and transformation of signal variables based on naming convention.\n *\n * Key responsibilities:\n * - Signal variable detection (pure prefix-based, no global registry)\n * - AST transformations for signal reads, writes, and updates\n * - Destructuring pattern processing (object and array patterns)\n * - Signal declaration transformation (signal() and computed() wrappers)\n *\n * Design philosophy:\n * - Pure naming convention: variables starting with '$' are signals\n * - No global state or cross-file tracking needed\n * - Works automatically across module boundaries\n * - Simple and predictable behavior\n *\n * @module signal/symbol\n */\n\nimport { types as t } from '@babel/core';\nimport { addImport } from '../import';\nimport { isMemberAccessingProperty, isValidPath } from './utils';\nimport type { PluginState } from '../types';\nimport type { VariableDeclarator } from '@babel/types';\nimport type { NodePath } from '@babel/core';\n\n/**\n * Check whether a variable is a signal based on naming convention.\n *\n * Simple rule: any variable starting with '$' is treated as a signal.\n * This works across file boundaries without any global state.\n *\n * @param {string} name - Variable name to check\n * @returns {boolean} True if the variable is a signal\n *\n * @example\n * ```typescript\n * isSignal('$count'); // true\n * isSignal('$value'); // true\n * isSignal('count'); // false\n * isSignal('_private'); // false\n * ```\n */\nexport function isSignal(name: string): boolean {\n return !!name && name.startsWith('$');\n}\n\n/**\n * Rewrite signal variable declarations to `signal()` or `computed()` calls.\n *\n * Transformation rules:\n * 1. **Plain values** → `signal(value)`\n * - Example: `let $count = 0` → `let $count = signal(0)`\n *\n * 2. **Function expressions** → `computed(fn)`\n * - Example: `const $fullName = () => first + last`\n * → `const $fullName = computed(() => first + last)`\n *\n * 3. **Already wrapped** → skip\n * - Detects existing `signal()` / `computed()` calls\n *\n * 4. **Uninitialized** → `signal()`\n * - Example: `let $count;` → `let $count = signal();`\n *\n * @param {NodePath<VariableDeclarator>} path - AST path for the variable declarator\n *\n * @example\n * ```typescript\n * let $count = 0; // → let $count = signal(0);\n * const $fullName = () => first + last; // → const $fullName = computed(() => first + last);\n * let $existing = signal(42); // → unchanged\n * let $uninitialized; // → let $uninitialized = signal();\n * ```\n */\nexport function replaceSymbol(path: NodePath<VariableDeclarator>): void {\n const { init, id } = path.node;\n\n // Only process identifier declarators\n if (!t.isIdentifier(id)) {\n return;\n }\n\n const variableName = id.name;\n\n // Skip non-signal variables\n if (!isSignal(variableName)) {\n return;\n }\n\n // Skip if already wrapped with signal/computed\n if (isAlreadySignalCall(init)) {\n return;\n }\n\n // Use `computed` only when the initializer is a function on a `const`\n const isComputed =\n init &&\n (t.isFunctionExpression(init) || t.isArrowFunctionExpression(init)) &&\n (path.parent as t.VariableDeclaration).kind === 'const';\n\n const importName = isComputed ? 'computed' : 'signal';\n\n // Get plugin state\n const state = path.state as PluginState;\n\n // Build the wrapper call\n const args = init ? [init] : [];\n const newInit = t.callExpression(t.identifier(state.imports[importName].name), args);\n\n addImport(importName as any);\n\n // Update the AST\n path.node.init = newInit;\n}\n\n/**\n * Check whether the initializer already invokes a signal factory.\n *\n * @param {t.Expression | null} init - Initializer expression\n * @returns {boolean} True when the expression already calls a signal helper\n */\nfunction isAlreadySignalCall(init: t.Expression | null | undefined): boolean {\n if (!init || !t.isCallExpression(init) || !t.isIdentifier(init.callee)) {\n return false;\n }\n\n const calleeName = init.callee.name;\n return (\n calleeName === 'signal' ||\n calleeName === 'computed' ||\n calleeName.includes('signal') ||\n calleeName.includes('computed')\n );\n}\n\n/**\n * Rewrite signal references to access the `.value` property.\n *\n * Transforms signal variable reads to access their underlying value.\n *\n * Conversion rules:\n * - `$count` → `$count.value`\n * - `console.log($name)` → `console.log($name.value)`\n *\n * Smart skipping:\n * - Non-signal variables\n * - Already transformed (`.value` already present)\n * - Declaration contexts (variable declarations, imports, etc.)\n * - Object property keys\n *\n * @param {NodePath<t.Identifier>} path - AST path for the identifier node\n *\n * @example\n * ```typescript\n * const result = $count + 1; // → const result = $count.value + 1;\n * console.log($name); // → console.log($name.value);\n *\n * // Skipped contexts\n * let $count = 0; // declaration - not transformed\n * obj.$count = 1; // property key - not transformed\n * $count.value; // already transformed - not transformed\n * ```\n */\nexport function symbolIdentifier(path: NodePath<t.Identifier>): void {\n if (!isValidPath(path)) {\n return;\n }\n\n const name = path.node.name;\n\n // Skip non-signal variables\n if (!isSignal(name)) {\n return;\n }\n\n // Skip if context should not be transformed\n if (!shouldProcessIdentifier(path, path.parentPath)) {\n return;\n }\n\n // Skip if already accessing .value\n if (isAlreadyValueAccess(path)) {\n return;\n }\n\n // This prevents transforming cases like `__props.$value` into `__props.$value.value`\n // which would create an invalid nested structure\n const parent = path.parent;\n if (t.isMemberExpression(parent) && parent.property === path.node) {\n return;\n }\n\n // Transform: $count → $count.value\n path.replaceWith(t.memberExpression(t.identifier(name), t.identifier('value')));\n}\n\n/**\n * Decide whether an identifier should be transformed as a signal reference.\n *\n * Provides fine-grained context checks to avoid incorrect rewrites and maintain\n * program correctness.\n *\n * Contexts to skip:\n * 1. Variable declarations (e.g. `let $count = 1`)\n * 2. Import specifiers (e.g. `import { $value } from 'module'`)\n * 3. Object property keys (e.g. `obj.$prop` as the key)\n * 4. Destructuring patterns (e.g. `const { $x } = obj`)\n * 5. Function parameters and names\n * 6. Labels (e.g. `break $label`)\n * 7. Class names (e.g. `class $Class`)\n * 8. Method names\n *\n * Safe to transform when used inside expressions, as call arguments, in return\n * statements, or on the right-hand side of assignments.\n *\n * @param {NodePath<t.Identifier>} path - Identifier node path\n * @param {NodePath<t.Node> | null} parentPath - Parent AST path\n * @returns {boolean} True when the identifier should be transformed\n *\n * @example\n * ```typescript\n * // Skip\n * let $count = 1;\n * import { $value } from '';\n * obj.$prop = 1;\n *\n * // Transform\n * console.log($count);\n * return $value + 1;\n * ```\n */\nfunction shouldProcessIdentifier(\n path: NodePath<t.Identifier>,\n parentPath: NodePath<t.Node> | null,\n): boolean {\n // Validate parent path exists\n if (!parentPath) {\n return false;\n }\n\n const parent = parentPath.node;\n const currentNode = path.node;\n\n // Group 1: Declaration contexts - skip identifiers that define names\n if (t.isVariableDeclarator(parent) || t.isArrayPattern(parent) || t.isObjectPattern(parent)) {\n return false;\n }\n\n // Group 2: Import/Export contexts - skip module-level identifiers\n if (\n t.isImportSpecifier(parent) ||\n t.isImportDefaultSpecifier(parent) ||\n t.isImportNamespaceSpecifier(parent)\n ) {\n return false;\n }\n\n // Group 3: Function contexts - skip function names and parameters\n if (\n t.isFunctionDeclaration(parent) ||\n t.isFunctionExpression(parent) ||\n t.isArrowFunctionExpression(parent)\n ) {\n return false;\n }\n\n // Group 4: Class contexts - skip class and method names\n if (t.isClassDeclaration(parent) && parent.id === currentNode) {\n return false;\n }\n\n if (t.isObjectMethod(parent) || t.isClassMethod(parent)) {\n return false;\n }\n\n // Group 5: Object property keys - skip keys but allow values\n if (t.isObjectProperty(parent) && parent.key === currentNode) {\n return false;\n }\n\n // Group 6: Label contexts - skip labels in labeled statements\n if (t.isLabeledStatement(parent) && parent.label === currentNode) {\n return false;\n }\n if (\n (t.isBreakStatement(parent) || t.isContinueStatement(parent)) &&\n parent.label === currentNode\n ) {\n return false;\n }\n\n // Otherwise allow the transformation\n return true;\n}\n\n/**\n * Determine whether an identifier is already accessing `.value`.\n *\n * Prevents reprocessing identifiers that have already been rewritten, covering\n * a variety of member-access patterns.\n *\n * Detection patterns:\n * 1. Direct access – `$count.value`\n * 2. Chained access – `$count.value.toString()`\n * 3. Computed access – `$count['value']`\n * 4. Wrapped expressions – `($count).value`\n *\n * @param {NodePath<t.Identifier>} path - Identifier node path\n * @returns {boolean} True when `.value` access is already present\n *\n * @example\n * ```typescript\n * $count.value; // true\n * $count.value.toString(); // true\n * $count; // false\n * $count.other; // false\n * ```\n */\nfunction isAlreadyValueAccess(path: NodePath<t.Identifier>): boolean {\n const parent = path.parent;\n\n // Direct member access `$count.value` or computed `$count['value']`\n // This is the most common case, so check it first\n if (t.isMemberExpression(parent) && parent.object === path.node) {\n return isMemberAccessingProperty(parent, 'value');\n }\n\n if (\n !t.isParenthesizedExpression(parent) &&\n !t.isTSAsExpression(parent) &&\n !t.isTSNonNullExpression(parent)\n ) {\n return false;\n }\n\n // Traverse ancestors for nested member expressions such as ($count).value\n // Only needed for rare cases with parentheses or type assertions\n const ancestorCheck = path.findParent(p => {\n if (!p.isMemberExpression()) {\n return false;\n }\n\n const memberExpr = p.node as t.MemberExpression;\n\n // Confirm the member expression targets the current identifier\n return memberExpr.object === path.node && isMemberAccessingProperty(memberExpr, 'value');\n });\n\n return !!ancestorCheck;\n}\n\n/**\n * Rewrite signal assignments to target `.value`.\n *\n * Transforms signal variable assignments to update their underlying value.\n *\n * Conversion rules:\n * - `$count = 42` → `$count.value = 42`\n * - `$count += 1` → `$count.value += 1`\n *\n * Supported operators: `=`, `+=`, `-=`, `*=`, `/=`, `%=`, `**=`, `&=`, `|=`, `^=`, `<<=`, `>>=`, `>>>=`, `&&=`, `||=`, `??=`\n *\n * @param {NodePath<t.AssignmentExpression>} path - Assignment expression path\n *\n * @example\n * ```typescript\n * $count = 42; // → $count.value = 42;\n * $count += 1; // → $count.value += 1;\n * $name ||= 'default'; // → $name.value ||= 'default';\n *\n * // Skipped\n * obj.prop = 1; // not an identifier\n * $count.value = 1; // already .value\n * regularVar = 1; // not a signal\n * ```\n */\nexport function symbolAssignment(path: NodePath<t.AssignmentExpression>): void {\n if (!isValidPath(path)) {\n return;\n }\n\n const { left } = path.node;\n\n // Only process identifier assignments\n if (!t.isIdentifier(left)) {\n return;\n }\n\n const name = left.name;\n\n // Skip non-signal variables\n if (!isSignal(name)) {\n return;\n }\n\n // Skip if already accessing .value\n if (isAlreadyValueAssignment(left)) {\n return;\n }\n\n // Transform: $count = 1 → $count.value = 1\n path.node.left = t.memberExpression(t.identifier(name), t.identifier('value'));\n}\n\n/**\n * Check whether the assignment already targets the `.value` property.\n *\n * @param {t.LVal} left - Assignment left-hand side\n * @returns {boolean} True when `.value` is already being assigned\n */\nfunction isAlreadyValueAssignment(left: t.LVal): boolean {\n return t.isMemberExpression(left) && isMemberAccessingProperty(left, 'value');\n}\n\n/**\n * Transform signal variable update expressions to .value property updates.\n *\n * Handles increment and decrement operations on signal variables.\n *\n * Transformation rules:\n * - `$count++` → `$count.value++`\n * - `++$index` → `++$index.value`\n * - `$value--` → `$value.value--`\n * - `--$counter` → `--$counter.value`\n *\n * @param {NodePath<t.UpdateExpression>} path - AST path of the update expression node\n *\n * @example\n * ```typescript\n * $count++; // → $count.value++;\n * ++$index; // → ++$index.value;\n * $value--; // → $value.value--;\n * --$counter; // → --$counter.value;\n *\n * // Skipped\n * obj.prop++; // not an identifier\n * $count.value++; // already .value\n * regularVar++; // not a signal\n * ```\n */\nexport function symbolUpdate(path: NodePath<t.UpdateExpression>): void {\n if (!isValidPath(path)) {\n return;\n }\n\n const { argument } = path.node;\n\n // Only process identifier updates\n if (!t.isIdentifier(argument)) {\n return;\n }\n\n const name = argument.name;\n\n // Skip non-signal variables\n if (!isSignal(name)) {\n return;\n }\n\n // Skip if already accessing .value\n if (isAlreadyValueUpdate(argument)) {\n return;\n }\n\n // Transform: $count++ → $count.value++\n path.node.argument = t.memberExpression(t.identifier(name), t.identifier('value'));\n}\n\n/**\n * Check if the update expression argument is already a .value property access\n *\n * @param {t.Expression} argument - The update expression argument\n * @returns {boolean} Returns true if it's already a .value update\n */\nfunction isAlreadyValueUpdate(argument: t.Expression): boolean {\n return t.isMemberExpression(argument) && isMemberAccessingProperty(argument, 'value');\n}\n\n/**\n * Process signal-aware object destructuring patterns.\n *\n * Recursively processes object destructuring to handle nested patterns.\n * Note: This function doesn't transform the destructuring itself, but ensures\n * nested patterns are also processed by the visitor.\n *\n * Supports:\n * - Simple destructuring: `{ $count, $name }`\n * - Nested destructuring: `{ user: { $name } }`\n * - Default values: `{ $isLoading = false }`\n * - Rest elements: `{ $a, ...$rest }`\n * - Mixed patterns: `{ $x, nested: { $y }, ...$rest }`\n *\n * @param {NodePath<t.ObjectPattern>} path - Object pattern path\n *\n * @example\n * ```typescript\n * const { $count, $name } = state;\n * const { user: { $name } } = data;\n * const { $isLoading = false } = config;\n * const { $a, ...$rest } = obj;\n * ```\n */\nexport function symbolObjectPattern(path: NodePath<t.ObjectPattern>): void {\n if (!isValidPath(path)) {\n return;\n }\n\n const properties = path.node.properties;\n\n if (!Array.isArray(properties) || properties.length === 0) {\n return;\n }\n\n // Process each property\n for (const property of properties) {\n if (!property) continue;\n\n if (t.isObjectProperty(property)) {\n handleObjectProperty(property, path);\n } else if (t.isRestElement(property)) {\n handleRestElement(property, path);\n }\n }\n}\n\n/**\n * Handle a single object property within a destructuring pattern.\n *\n * Recursively processes nested patterns.\n *\n * @param {t.ObjectProperty} property - Property node\n * @param {NodePath<t.ObjectPattern>} parentPath - Parent object pattern path\n */\nfunction handleObjectProperty(\n property: t.ObjectProperty,\n parentPath: NodePath<t.ObjectPattern>,\n): void {\n if (!property || !property.value) {\n return;\n }\n\n const value = property.value;\n\n // Recurse into nested patterns\n if (t.isObjectPattern(value)) {\n const mockPath = {\n node: value,\n state: parentPath.state,\n parentPath,\n } as NodePath<t.ObjectPattern>;\n symbolObjectPattern(mockPath);\n } else if (t.isArrayPattern(value)) {\n const mockPath = {\n node: value,\n state: parentPath.state,\n parentPath,\n } as NodePath<t.ArrayPattern>;\n symbolArrayPattern(mockPath);\n } else if (t.isAssignmentPattern(value)) {\n handleAssignmentPattern(value, parentPath);\n }\n}\n\n/**\n * Handle assignment patterns (default values) in destructuring.\n *\n * Recursively processes nested patterns with default values.\n *\n * @param {t.AssignmentPattern} pattern - Assignment pattern node\n * @param {NodePath<t.ObjectPattern | t.ArrayPattern>} parentPath - Parent pattern path\n */\nfunction handleAssignmentPattern(\n pattern: t.AssignmentPattern,\n parentPath: NodePath<t.ObjectPattern> | NodePath<t.ArrayPattern>,\n): void {\n const left = pattern.left;\n\n if (t.isObjectPattern(left)) {\n const mockPath = {\n node: left,\n state: parentPath.state,\n parentPath,\n } as NodePath<t.ObjectPattern>;\n symbolObjectPattern(mockPath);\n } else if (t.isArrayPattern(left)) {\n const mockPath = {\n node: left,\n state: parentPath.state,\n parentPath,\n } as NodePath<t.ArrayPattern>;\n symbolArrayPattern(mockPath);\n }\n}\n\n/**\n * Handle rest elements inside object destructuring.\n *\n * Recursively processes nested patterns in rest elements.\n *\n * @param {t.RestElement} restElement - Rest element node\n * @param {NodePath<t.ObjectPattern>} parentPath - Parent object pattern path\n */\nfunction handleRestElement(\n restElement: t.RestElement,\n parentPath: NodePath<t.ObjectPattern>,\n): void {\n if (!restElement || !restElement.argument) {\n return;\n }\n\n const argument = restElement.argument;\n\n if (t.isObjectPattern(argument)) {\n const mockPath = {\n node: argument,\n state: parentPath.state,\n parentPath,\n } as NodePath<t.ObjectPattern>;\n symbolObjectPattern(mockPath);\n } else if (t.isArrayPattern(argument)) {\n const mockPath = {\n node: argument,\n state: parentPath.state,\n parentPath,\n } as NodePath<t.ArrayPattern>;\n symbolArrayPattern(mockPath);\n }\n}\n\n/**\n * Process signal variables in array destructuring patterns.\n *\n * Recursively processes array destructuring to handle nested patterns.\n * Note: This function doesn't transform the destructuring itself, but ensures\n * nested patterns are also processed by the visitor.\n *\n * Supported patterns:\n * - Direct destructuring: `[$first, $second]`\n * - Skipping elements: `[$first, , $third]`\n * - Default values: `[$count = 0]`\n * - Nested destructuring: `[[$x, $y], $z]`\n * - Rest destructuring: `[$first, ...$rest]`\n * - Mixed patterns: `[[$x], { $y }, $z = 0, ...$rest]`\n *\n * @param {NodePath<t.ArrayPattern>} path - AST path of the array destructuring pattern node\n *\n * @example\n * ```typescript\n * const [$x, $y] = coordinates;\n * const [$first, , $third] = items;\n * const [[$count, $name], $status] = nestedData;\n * const [$head, ...$tail] = list;\n * const [$count = 0, $name = ''] = partialData;\n * ```\n */\nexport function symbolArrayPattern(path: NodePath<t.ArrayPattern>): void {\n if (!isValidPath(path)) {\n return;\n }\n\n const elements = path.node.elements;\n\n if (!Array.isArray(elements) || elements.length === 0) {\n return;\n }\n\n // Process each element\n for (const element of elements) {\n if (!element) continue; // Skip holes\n\n if (t.isAssignmentPattern(element)) {\n handleAssignmentPattern(element, path);\n } else if (t.isRestElement(element)) {\n handleArrayRestElement(element, path);\n } else if (t.isObjectPattern(element)) {\n const mockPath = {\n node: element,\n state: path.state,\n parentPath: path,\n } as NodePath<t.ObjectPattern>;\n symbolObjectPattern(mockPath);\n } else if (t.isArrayPattern(element)) {\n const mockPath = {\n node: element,\n state: path.state,\n parentPath: path,\n } as NodePath<t.ArrayPattern>;\n symbolArrayPattern(mockPath);\n }\n }\n}\n\n/**\n * Handle rest element in array destructuring.\n *\n * Recursively processes nested patterns in rest elements.\n *\n * @param {t.RestElement} restElement - Rest element node\n * @param {NodePath<t.ArrayPattern>} parentPath - Parent node path\n */\nfunction handleArrayRestElement(\n restElement: t.RestElement,\n parentPath: NodePath<t.ArrayPattern>,\n): void {\n if (!restElement || !restElement.argument) {\n return;\n }\n\n const argument = restElement.argument;\n\n if (t.isArrayPattern(argument)) {\n const mockPath = {\n node: argument,\n state: parentPath.state,\n parentPath,\n } as NodePath<t.ArrayPattern>;\n symbolArrayPattern(mockPath);\n } else if (t.isObjectPattern(argument)) {\n const mockPath = {\n node: argument,\n state: parentPath.state,\n parentPath,\n } as NodePath<t.ObjectPattern>;\n symbolObjectPattern(mockPath);\n }\n}\n","import { types as t } from '@babel/core';\nimport type {\n ArrowFunctionExpression,\n FunctionDeclaration,\n FunctionExpression,\n} from '@babel/types';\nimport type { NodePath } from '@babel/core';\n\n/**\n * Validates if a path and its node are valid\n *\n * @param path - AST node path to validate\n * @returns true if path and node are valid, false otherwise\n */\nexport function isValidPath(path: NodePath<unknown> | null | undefined): boolean {\n return !!(path && path.node);\n}\n/**\n * Checks if a node is a JSX element or fragment\n *\n * @param node - AST node to check\n * @returns true if node is JSX element or fragment, false otherwise\n */\nexport function isJSXNode(node: t.Node | null | undefined): boolean {\n return !!(node && (t.isJSXElement(node) || t.isJSXFragment(node)));\n}\n\n/**\n * Checks if an expression might return JSX\n * Handles conditional, logical, and sequence expressions recursively\n *\n * @param expr - Expression to check\n * @returns true if expression might return JSX, false otherwise\n */\nexport function mightReturnJSX(expr: t.Expression | t.Node): boolean {\n // Direct JSX check\n if (isJSXNode(expr)) {\n return true;\n }\n\n // Conditional: condition ? <A /> : <B />\n if (t.isConditionalExpression(expr)) {\n return mightReturnJSX(expr.consequent) || mightReturnJSX(expr.alternate);\n }\n\n // Logical: condition && <A /> or condition || <B />\n if (t.isLogicalExpression(expr)) {\n return mightReturnJSX(expr.left) || mightReturnJSX(expr.right);\n }\n\n // Sequence: (expr1, expr2, <JSX />)\n if (t.isSequenceExpression(expr)) {\n return expr.expressions.some(mightReturnJSX);\n }\n\n // Parenthesized: (<JSX />)\n if (t.isParenthesizedExpression(expr)) {\n return mightReturnJSX(expr.expression);\n }\n\n return false;\n}\n\n/**\n * Checks if a function returns JSX elements\n *\n * Only functions that return JSX need props transformation. This function\n * performs a comprehensive check to detect JSX returns in various scenarios.\n *\n * @param path - Function node path to analyze\n * @returns true if function returns JSX element or JSX fragment, false otherwise\n * @throws Never throws - returns false on any error\n *\n * @example\n * ```typescript\n * // Returns true\n * function Component() { return <div />; }\n * const Component = () => <div />;\n * const Component = () => { return <div />; };\n * const Component = () => condition ? <div /> : <span />;\n *\n * // Returns false\n * function helper() { return 'string'; }\n * const compute = () => 42;\n * const Component = () => { console.log('no return'); };\n * ```\n */\nexport function checkHasJSXReturn(\n path: NodePath<FunctionDeclaration | ArrowFunctionExpression | FunctionExpression>,\n): boolean {\n if (!isValidPath(path)) return false;\n\n try {\n const body = path.get('body');\n if (!isValidPath(body)) return false;\n\n // if the body is not a block statement, check if it might return JSX\n if (!t.isBlockStatement(body.node)) {\n return mightReturnJSX(body.node);\n }\n\n // check if the body has a return statement that returns JSX\n let hasJSX = false;\n body.traverse({\n 'ReturnStatement': function (returnPath) {\n if (!hasJSX && returnPath.node.argument && mightReturnJSX(returnPath.node.argument)) {\n hasJSX = true;\n returnPath.stop();\n }\n },\n 'FunctionDeclaration|FunctionExpression|ArrowFunctionExpression': nestedPath => {\n nestedPath.skip();\n },\n });\n\n return hasJSX;\n } catch {\n return false;\n }\n}\n/**\n * Checks if a member expression is accessing a specific property\n *\n * @param node - Member expression node\n * @param propertyName - Property name to check\n * @returns true if the member expression accesses the specified property\n */\nexport function isMemberAccessingProperty(node: t.MemberExpression, propertyName: string): boolean {\n if (!node.computed && t.isIdentifier(node.property) && node.property.name === propertyName) {\n return true;\n }\n\n if (node.computed && t.isStringLiteral(node.property) && node.property.value === propertyName) {\n return true;\n }\n\n return false;\n}\n","import { type NodePath, types as t } from '@babel/core';\n\nimport { isPlainObject, startsWith, warn } from '@estjs/shared';\nimport { TRANSFORM_PROPERTY_NAME } from '../constants';\nimport { addImport, importMap } from '../import';\nimport { checkHasJSXReturn } from './utils';\nimport type { PluginState } from '../types';\nimport type {\n ArrowFunctionExpression,\n FunctionDeclaration,\n ObjectProperty,\n RestElement,\n} from '@babel/types';\n\n/**\n * Recursively replaces properties in object destructuring patterns\n *\n * This is the core transformation function that handles various types of property\n * destructuring patterns while collecting default value information.\n *\n * Supported patterns:\n * 1. **Simple destructuring**: `{ name }` → `__props.name`\n * 2. **Aliasing**: `{ name: userName }` → `__props.name` (userName renamed)\n * 3. **Default values**: `{ delay = 1500 }` → `__props.delay` (default collected)\n * 4. **Nested objects**: `{ user: { name } }` → `__props.user.name`\n * 5. **Mixed patterns**: `{ a, b: { c = 1 } }` → `__props.a`, `__props.b.c`\n *\n * @param path - Function node path being transformed\n * @param properties - List of properties to process from object destructuring pattern\n * @param parentPath - Parent path prefix for building complete property paths\n * @param defaultValues - Default value collector to store extracted default values\n * @throws Never throws - handles all errors internally and continues processing\n *\n * @example\n * ```typescript\n * // Input: function Component({ name, user: { age = 18 } }) { ... }\n * // After: function Component(__props = { user: { age: 18 } }) {\n * // // name → __props.name\n * // // age → __props.user.age\n * // }\n * ```\n */\nfunction transformProperty(\n path: NodePath<FunctionDeclaration | ArrowFunctionExpression>,\n properties: ObjectProperty[],\n parentPath: string,\n defaultValues: Record<string, unknown> = {},\n): Record<string, unknown> {\n properties.forEach((property, index) => {\n try {\n // Only process object properties, skip rest elements\n if (!t.isObjectProperty(property)) {\n return;\n }\n\n // Ensure key is identifier\n if (!t.isIdentifier(property.key)) {\n // For computed property names, skip processing\n if (__DEV__) {\n warn('transformObjectProperties: Skipping computed property', { index });\n }\n return;\n }\n\n const keyName = property.key.name;\n\n if (t.isIdentifier(property.value)) {\n path.scope.rename(property.value.name, `${parentPath}.${keyName}`);\n } else if (t.isAssignmentPattern(property.value)) {\n // Case 2: Assignment pattern (with default value) - collect default value and rename\n // Example: { delay = 1500 } -> collect default value, rename to __props.delay\n if (t.isIdentifier(property.value.left)) {\n // Collect default value\n defaultValues[keyName] = property.value.right;\n // Rename identifier to use parent path\n\n path.scope.rename(property.value.left.name, `${parentPath}.${keyName}`);\n } else if (t.isObjectPattern(property.value.left)) {\n // Nested object with default: { nested: { x } = {} }\n transformProperty(\n path,\n property.value.left.properties as ObjectProperty[],\n `${parentPath}.${keyName}`,\n defaultValues,\n );\n // Store the default value for the nested object\n defaultValues[keyName] = property.value.right;\n }\n } else if (t.isObjectPattern(property.value)) {\n // Case 3: Nested object pattern - recursive processing\n // Example: { user: { name, age } } -> __props.user.name, __props.user.age\n transformProperty(\n path,\n property.value.properties as ObjectProperty[],\n `${parentPath}.${keyName}`,\n defaultValues,\n );\n }\n // Other cases (like array patterns) are not commonly used in props and are skipped\n } catch (error) {\n // Single property processing failure should not affect other properties\n warn('transformProperty', `Failed to process property at index ${index}`, {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n });\n\n return defaultValues;\n}\n\n/**\n * Rest parameter information collected during transformation\n */\ninterface RestParameterInfo {\n /** Rest parameter variable name */\n name: string;\n /** Parent path prefix (e.g., '__props.user.') */\n parentPath: string;\n /** Properties to exclude from this rest object */\n excludeProps: string[];\n}\n/**\n * Creates a variable declaration for rest parameter\n *\n * When a rest parameter exists, creates a reactive rest object that excludes\n * the explicitly destructured properties using the omit utility.\n *\n * Strategy:\n * - If no excludeProps: `const rest = __props` (direct reference)\n * - If has excludeProps: `const rest = omit(__props, ['name', 'age'])`\n * - For nested rest: `const userRest = omit(__props.user, ['name', 'age'])`\n *\n * @param state - Babel plugin state object (must contain imports.omit)\n * @param restName - Rest parameter name (e.g., 'rest', 'otherProps')\n * @param parentPath - Parent path prefix (e.g., '__props.' or '__props.user.')\n * @param excludeProps - List of property names to exclude from rest object\n * @returns Variable declaration AST node for the rest parameter\n * @throws {Error} If state is invalid or missing omit import\n * @throws {Error} If restName is invalid\n * @throws {TypeError} If excludeProps is not an array\n *\n * @example\n * ```typescript\n * // Top-level rest: { name, age, ...rest }\n * // Output: const rest = omit(__props, ['name', 'age']);\n *\n * // Nested rest: { user: { name, ...userRest } }\n * // Output: const userRest = omit(__props.user, ['name']);\n *\n * // Usage in component:\n * // <div {...rest} /> will spread all props except name and age\n * ```\n */\nfunction buildRestVariableDeclaration(\n state: PluginState,\n restName: string,\n parentPath: string,\n excludeProps: string[],\n): t.VariableDeclaration {\n // Validate restName\n // if (!restName || restName.trim() !== restName || !parentPath) {\n // return;\n // }\n\n // Validate each property name in excludeProps\n const validExcludeProps = excludeProps.filter(Boolean);\n\n let init: t.Expression;\n\n // Build the source object expression from parentPath\n // e.g., '__props.' -> __props, '__props.user.' -> __props.user\n const pathParts = parentPath.split('.').filter(part => part.length > 0);\n let sourceObject: t.Expression = t.identifier(pathParts[0] || '__props');\n\n for (let i = 1; i < pathParts.length; i++) {\n sourceObject = t.memberExpression(sourceObject, t.identifier(pathParts[i]));\n }\n\n if (validExcludeProps.length === 0) {\n // No properties to exclude, directly reference the source object\n init = sourceObject;\n } else {\n // Create: omit(sourceObject, ['name', 'age'])\n init = t.callExpression(state.imports.omitProps, [\n sourceObject,\n t.arrayExpression(validExcludeProps.map(name => t.stringLiteral(name))),\n ]);\n }\n\n return t.variableDeclaration('const', [t.variableDeclarator(t.identifier(restName), init)]);\n}\n\nfunction transformRestProperties(\n path: NodePath<FunctionDeclaration | ArrowFunctionExpression>,\n restProperties: RestElement,\n notRestNames: string[] = [],\n nestedRestParams: RestParameterInfo[] = [],\n): void {\n if (!t.isIdentifier(restProperties.argument)) {\n return;\n }\n const restName = restProperties.argument.name;\n\n if (notRestNames.length === 0 && nestedRestParams.length === 0) {\n // Only rest parameter, no other properties and no nested rest\n // Directly use rest parameter name as first parameter\n path.node.params[0] = t.identifier(restName);\n } else {\n // Has regular properties or nested rest parameters\n const restDeclarations: t.VariableDeclaration[] = [];\n\n // Process nested rest parameters first (from deepest to shallowest for correct order)\n if (nestedRestParams.length > 0) {\n for (const nestedRest of nestedRestParams) {\n const nestedRestDeclaration = buildRestVariableDeclaration(\n path.state,\n nestedRest.name,\n nestedRest.parentPath,\n nestedRest.excludeProps,\n );\n restDeclarations.push(nestedRestDeclaration);\n\n // Add omit import if there are props to exclude\n if (nestedRest.excludeProps.length > 0) {\n addImport(importMap.omitProps);\n }\n }\n }\n\n // Process top-level rest parameter if exists\n if (restProperties) {\n const restDeclaration = buildRestVariableDeclaration(\n path.state,\n restName,\n TRANSFORM_PROPERTY_NAME,\n notRestNames,\n );\n restDeclarations.push(restDeclaration);\n\n // Only add omit import if we actually need it (when there are props to exclude)\n if (notRestNames.length) {\n addImport(importMap.omitProps);\n }\n }\n\n // Insert all rest declarations at function body start\n for (const declaration of restDeclarations) {\n const body = path.node.body as t.BlockStatement;\n body.body.unshift(declaration);\n }\n }\n}\n/**\n * Creates a default value object expression with support for nested defaults\n *\n * @param defaultValues - Collected default value mapping (key → expression or nested object)\n * @returns Object expression containing default values, or empty object if input is invalid\n * @throws Never throws - returns empty object on any error\n *\n * @example\n * ```typescript\n * // Input: { count: 0, user: { age: 18, settings: { theme: 'dark' } } }\n * // Output: AST for { count: 0, user: { age: 18, settings: { theme: 'dark' } } }\n *\n * // Used as: function Component(__props = { count: 0, user: { age: 18 } })\n * ```\n */\nfunction buildDefaultValueObject(defaultValues): t.ObjectExpression {\n // Validate input type\n if (!isPlainObject(defaultValues)) {\n return t.objectExpression([]);\n }\n\n const properties: t.ObjectProperty[] = [];\n\n for (const [key, value] of Object.entries(defaultValues)) {\n if (!key) {\n continue;\n }\n\n let propertyValue: t.Expression;\n\n // Check if value is a nested DefaultValueCollector\n if (isPlainObject(value) && !t.isNode(value)) {\n // Recursively build nested object\n propertyValue = buildDefaultValueObject(value);\n } else if (t.isExpression(value)) {\n // Direct expression value\n propertyValue = value;\n } else {\n continue;\n }\n\n properties.push(t.objectProperty(t.identifier(key), propertyValue));\n }\n\n return t.objectExpression(properties);\n}\n\nfunction buildDefaultValue(\n path: NodePath<FunctionDeclaration | ArrowFunctionExpression>,\n defaultValues: Record<string, unknown>,\n): void {\n const propsParam =\n Object.keys(defaultValues).length > 0\n ? t.assignmentPattern(\n t.identifier(TRANSFORM_PROPERTY_NAME),\n buildDefaultValueObject(defaultValues),\n )\n : t.identifier(TRANSFORM_PROPERTY_NAME);\n\n path.node.params[0] = propsParam;\n}\n\n/**\n * Transforms function parameters to reactive properties\n * @param path - Function node path to transform\n * @throws Never throws - handles all errors internally and continues compilation\n *\n * Transformation flow:\n * 1. Validate function returns JSX\n * 2. Validate first parameter is object pattern\n * 3. Check prop names don't conflict with signal prefix\n * 4. Replace property references with __props.xxx\n * 5. Collect default values\n * 6. Handle rest parameters\n *\n * @example\n * ```typescript\n * // Before\n * function Component({ title, count = 0, ...rest }) {\n * return <div>{title} {count} {rest}</div>;\n * }\n *\n * // After\n * function Component(__props = { count: 0 }) {\n * const rest = omitProps(__props, ['title', 'count']);\n * return <div>{__props.title} {__props.count} {rest}</div>;\n * }\n * ```\n */\nexport function transformProps(\n path: NodePath<FunctionDeclaration | ArrowFunctionExpression>,\n): void {\n // just transform the first parameter\n const firstParam = path.node.params[0];\n\n // validate the first parameter is an object pattern and the function returns JSX\n if (!firstParam || !t.isObjectPattern(firstParam) || !checkHasJSXReturn(path)) {\n return;\n }\n\n const state: PluginState = path.state;\n const properties = firstParam.properties as ObjectProperty[];\n\n const signalPrefix = state.opts.symbol || '$';\n\n const notRestProperties = properties.filter(prop => !t.isRestElement(prop)) as ObjectProperty[];\n\n // one object just have one rest\n const restProperties = properties.find(prop => t.isRestElement(prop)) as RestElement | undefined;\n const notRestNames = notRestProperties\n .map(prop => (t.isIdentifier(prop.key) ? prop.key.name : null))\n .filter((name): name is string => name !== null);\n\n if (__DEV__) {\n // if the property names start with the signal prefix,\n if (notRestNames.some(name => startsWith(name, signalPrefix))) {\n warn(\n 'transformProps',\n 'Property names cannot start with signal prefix',\n notRestNames.filter(name => startsWith(name, signalPrefix)),\n );\n }\n }\n\n if (notRestProperties.length) {\n const defaultValues = transformProperty(path, notRestProperties, TRANSFORM_PROPERTY_NAME);\n buildDefaultValue(path, defaultValues);\n }\n if (restProperties) {\n transformRestProperties(path, restProperties, notRestNames);\n }\n}\n","import type { NodePath } from '@babel/core';\nimport type { JSXElement, PluginState } from '../types';\n\n/**\n * Transform Context Interface\n * @description Describes shared context data during the transformation process\n */\nexport interface TransformContext {\n /// State object\n state: PluginState;\n // Node path\n path: NodePath<JSXElement>;\n // Index to track operations\n operationIndex: number;\n}\n\nconst contextStack: TransformContext[] = [];\n/**\n * Get current transform context\n * @returns {TransformContext} Current context object\n */\nexport function getContext(): TransformContext {\n if (!contextStack.length) {\n throw new Error('No active context found. Ensure setContext has been called.');\n }\n return contextStack[contextStack.length - 1];\n}\n\n/**\n * Set transform context\n * @param {Partial<TransformContext>} context - The context to update\n */\nexport function setContext(context: TransformContext): void {\n contextStack.push(context);\n}\n\n/**\n * Reset transform context\n * @description Resets the context to its initial state\n */\nexport function resetContext(): void {\n contextStack.pop();\n}\n","import {\n coerceArray,\n isArray,\n isDelegatedEvent,\n isNil,\n isObject,\n isString,\n startsWith,\n warn,\n} from '@estjs/shared';\nimport { types as t } from '@babel/core';\nimport { addImport, importMap } from '../import';\nimport {\n BUILT_IN_COMPONENTS,\n CLASS_NAME,\n CREATE_COMPONENT_NAME,\n EVENT_ATTR_NAME,\n NODE_TYPE,\n REF_KEY,\n SPREAD_NAME,\n STYLE_NAME,\n UPDATE_PREFIX,\n} from './constants';\nimport {\n type DynamicContent,\n createPropsObjectExpression,\n findBeforeIndex,\n findIndexPosition,\n getSetFunctionForAttribute,\n isDynamicExpression,\n serializeAttributes,\n} from './shared';\nimport { getContext, setContext } from './context';\nimport { type TreeNode, isTreeNode } from './tree';\nimport type { NodePath } from '@babel/core';\nimport type { JSXElement, PluginState } from '../types';\n\ninterface ReactiveOperation {\n nodeIndex: number;\n attrName: string;\n attrValue: t.Expression;\n setFunction: {\n name: string;\n value: t.Identifier;\n };\n propKey: string;\n}\n\nexport function transformJSXToClient(path: NodePath<JSXElement>, node: TreeNode) {\n const state = path.state;\n\n // Handle component or fragment\n if (node.type === NODE_TYPE.COMPONENT) {\n const props = { ...node.props, children: node.children };\n return createComponentExpression(node, props);\n }\n // Generate static template\n const staticTemplate = generateStaticTemplate(node);\n\n // Collect dynamic props and children (static ones are already in template)\n const dynamicCollection = generateDynamic(node);\n\n // Generate index mapping for DOM node references\n const indexMap = generateIndexMap(dynamicCollection);\n\n // Create identifiers for root element and node mapping\n const elementId = path.scope.generateUidIdentifier('_$el');\n const nodesId = path.scope.generateUidIdentifier('_$nodes');\n\n // Initialize statements array for function body\n const statements: t.Statement[] = [];\n\n if (staticTemplate) {\n addImport(importMap.template);\n const tmplId = path.scope.generateUidIdentifier('_$tmpl');\n\n state.declarations.push(\n t.variableDeclarator(\n tmplId,\n t.callExpression(state.imports.template, coerceArray(staticTemplate).map(t.stringLiteral)),\n ),\n );\n statements.push(\n t.variableDeclaration('const', [\n t.variableDeclarator(elementId, t.callExpression(tmplId, [])),\n ]),\n );\n }\n if (\n dynamicCollection.children.length ||\n dynamicCollection.props.length ||\n dynamicCollection.operations.length\n ) {\n // Import mapNodes\n addImport(importMap.mapNodes);\n\n statements.push(\n t.variableDeclaration('const', [\n t.variableDeclarator(\n nodesId,\n t.callExpression(state.imports.mapNodes, [\n elementId,\n t.arrayExpression(indexMap.map(idx => t.numericLiteral(idx))),\n ]),\n ),\n ]),\n );\n // Process dynamic child nodes if they exist\n if (dynamicCollection.children.length) {\n generateDynamicChildrenCode(dynamicCollection.children, statements, state, nodesId, indexMap);\n }\n\n // Process dynamic properties if they exist\n if (dynamicCollection.props.length) {\n generateDynamicPropsCode(dynamicCollection.props, statements, state, nodesId, indexMap);\n }\n\n // Process reactive operations if they exist\n if (dynamicCollection.operations.length) {\n generateUnifiedMemoizedEffect(\n dynamicCollection.operations,\n statements,\n state,\n nodesId,\n indexMap,\n );\n }\n }\n\n // Add return statement\n statements.push(t.returnStatement(elementId));\n\n // Create and return IIFE expression\n return t.callExpression(t.arrowFunctionExpression([], t.blockStatement(statements)), []);\n}\n\n/**\n * Generate property key name (for state objects)\n *\n * Creates unique property keys for DOM attributes in the state object,\n * ensuring proper batching and tracking of dynamic attribute updates.\n *\n * @param attrName - The attribute name to generate a key for\n * @returns A unique property key string\n */\nfunction generatePropKey(attrName: string = 'attr'): string {\n const { operationIndex } = getContext();\n const keyMap: Record<string, string> = {\n [CLASS_NAME]: 'c',\n [STYLE_NAME]: 's',\n name: 'n',\n attr: 'a',\n };\n\n const baseKey = keyMap[attrName] || attrName.charAt(0);\n setContext({ ...getContext(), operationIndex: operationIndex + 1 });\n setContext({ ...getContext(), operationIndex: operationIndex + 1 });\n return `${baseKey}${operationIndex}`;\n}\n\n/**\n * Transform JSX element to client rendering code\n * @param path - The path of the JSX element being transformed\n * @param treeNode - The tree node representation of the JSX element\n * @returns The transformed client rendering code\n */\nfunction transformJSXClientChildren(path: NodePath<JSXElement>, treeNode: TreeNode) {\n return transformJSXToClient(path, treeNode);\n}\n\n/**\n * Creates a component expression for client rendering\n * @param node - The tree node representation of the component or fragment\n * @param componentProps - The props object for the component or fragment\n * @returns The transformed component expression\n */\nfunction createComponentExpression(node: TreeNode, componentProps: Record<string, unknown>) {\n const { state } = getContext();\n\n addImport(importMap.createComponent);\n\n // Built-in components\n const isBuiltIn = BUILT_IN_COMPONENTS.includes(node.tag!);\n if (isBuiltIn) {\n addImport(importMap[node.tag!]);\n }\n\n const argTag = isBuiltIn ? state.imports[node.tag!] : t.identifier(node.tag!);\n // Create props object expression\n const propsObj = createPropsObjectExpression(componentProps, transformJSXClientChildren);\n\n const args: t.Expression[] = [argTag, propsObj];\n\n return t.callExpression(state.imports[CREATE_COMPONENT_NAME], args);\n}\n/**\n * Generates an optimized index map for DOM node references.\n */\nfunction generateIndexMap({\n props,\n children,\n operations = [],\n}: {\n props: Array<{ props: Record<string, unknown>; parentIndex: number | null }>;\n children: Array<{ parentIndex: number | null; before: number | null }>;\n operations?: Array<{ nodeIndex: number }>;\n}) {\n const indexSet = new Set<number>();\n\n // Collect indices related to dynamic child nodes\n for (const item of children) {\n // Add parent node index\n if (!isNil(item.parentIndex)) {\n indexSet.add(item.parentIndex);\n }\n // Add reference node index (for insertBefore)\n if (!isNil(item.before)) {\n indexSet.add(item.before);\n }\n }\n\n // Collect parent node indices related to dynamic attributes\n for (const item of props) {\n if (!isNil(item.parentIndex)) {\n indexSet.add(item.parentIndex);\n }\n }\n\n // Collect node indices for reactive operations\n if (operations && operations.length > 0) {\n for (const item of operations) {\n if (!isNil(item.nodeIndex)) {\n indexSet.add(item.nodeIndex);\n }\n }\n }\n\n // Convert to sorted array for predictable ordering\n const indexMap = Array.from(indexSet).sort((a, b) => a - b);\n\n // Validation: Ensure all indices are positive integers\n if (__DEV__) {\n for (const index of indexMap) {\n if (!Number.isInteger(index) || index < 1) {\n warn(`Invalid index in index map: ${index}. All indices must be positive integers.`);\n }\n }\n }\n\n return indexMap;\n}\n\n// typeof value === \"function\" ? value(_el$) : value.value = _el$;\nexport function createRefStatement(\n nodesId: t.Identifier,\n nodeIndex: number,\n value: t.Expression,\n): t.ExpressionStatement {\n // Get the target DOM element: nodes[nodeIndex]\n const elementRef = t.memberExpression(nodesId, t.numericLiteral(nodeIndex), true);\n\n // Create: typeof value === \"function\"\n const typeofCheck = t.binaryExpression(\n '===',\n t.unaryExpression('typeof', value),\n t.stringLiteral('function'),\n );\n\n // Create: value(element) - function call\n const functionCall = t.callExpression(value, [elementRef]);\n\n // Create: value.value = element - assignment expression\n const assignmentExpr = t.assignmentExpression(\n '=',\n t.memberExpression(value, t.identifier('value')),\n elementRef,\n );\n\n // Create: typeof value === \"function\" ? value(element) : value.value = element\n const conditionalExpr = t.conditionalExpression(typeofCheck, functionCall, assignmentExpr);\n\n return t.expressionStatement(conditionalExpr);\n}\n\n/**\n * Create attribute setting statement\n\n */\nexport function createAttributeStatement(\n functionIdentifier: t.Identifier,\n nodesId: t.Identifier,\n nodeIndex: number,\n value: t.Expression,\n key?: t.Expression,\n): t.ExpressionStatement {\n // Prepare parameter array, first parameter is always the target DOM element\n const args: t.Expression[] = [t.memberExpression(nodesId, t.numericLiteral(nodeIndex), true)];\n\n // Add optional key parameter (such as attribute name, event name, etc.)\n if (key) {\n args.push(key);\n }\n\n // Add value parameter, supports array spreading\n if (value) {\n if (isArray(value)) {\n // Array value: spread all elements as independent parameters\n args.push(...value);\n } else {\n // Single value: add directly\n args.push(value);\n }\n }\n\n // Create function call expression statement\n const functionCall = t.callExpression(functionIdentifier, args);\n return t.expressionStatement(functionCall);\n}\n\n/**\n * Add event listener handling statement\n\n * @param {string} attrName - Event attribute name (e.g., 'onClick', 'onMouseOver')\n * @param {t.Expression} attrValue - Event handler function expression\n * @param {t.Identifier} nodesId - Node mapping array identifier\n * @param {number} nodeIndex - Target node index position in mapping array\n * @param {t.Statement[]} statements - Statement collection (for adding generated code)\n * @param {State} state - Plugin state (contains event registration info)\n */\nfunction addEventListenerStatement(\n attrName: string,\n attrValue: t.Expression,\n nodesId: t.Identifier,\n nodeIndex: number,\n statements: t.Statement[],\n state: PluginState,\n): void {\n // Extract event name: remove 'on' prefix and convert to lowercase\n const eventName = attrName.slice(2).toLowerCase();\n\n if (isDelegatedEvent(eventName)) {\n const activeContext = getContext();\n if (!activeContext) {\n warn('Missing active context, unable to handle delegated events');\n return;\n }\n\n // Generate delegated event code: element.$eventName = handler\n const elementRef = t.memberExpression(nodesId, t.numericLiteral(nodeIndex), true);\n const eventProperty = t.memberExpression(elementRef, t.stringLiteral(`_$${eventName}`), true);\n\n // Create assignment statement: nodes[index].$eventName = handler\n const assignmentStmt = t.expressionStatement(\n t.assignmentExpression('=', eventProperty, attrValue),\n );\n statements.push(assignmentStmt);\n\n // Register event to global event system\n state.events?.add(eventName);\n return;\n }\n\n // Direct event handling (compatibility path)\n addImport(importMap.addEventListener);\n\n // Generate direct event listener code: addEventListener(element, 'eventName', handler)\n const eventListenerStmt = createAttributeStatement(\n state.imports.addEventListener,\n nodesId,\n nodeIndex,\n attrValue,\n t.stringLiteral(eventName),\n );\n statements.push(eventListenerStmt);\n}\n/**\n * Generate specific attribute setting code based on attribute name\n * @param attributeName - Attribute name\n * @param attributeValue - Attribute value\n * @param nodesId - Node mapping identifier\n * @param nodeIndex - Node index position\n * @param statements - Statement collection\n * @param state - Plugin state\n */\nfunction generateSpecificAttributeCode(\n attributeName: string,\n attributeValue: t.Expression,\n nodesId: t.Identifier,\n nodeIndex: number,\n statements: t.Statement[],\n state: PluginState,\n): void {\n // Note: Reactive attributes are already handled uniformly in generateDynamicPropsCode\n // This only handles non-reactive static attributes\n\n switch (attributeName) {\n case CLASS_NAME:\n addImport(importMap.patchClass);\n statements.push(\n createAttributeStatement(state.imports.patchClass, nodesId, nodeIndex, attributeValue),\n );\n break;\n\n case SPREAD_NAME:\n addImport(importMap.setSpread);\n statements.push(\n createAttributeStatement(state.imports.setSpread, nodesId, nodeIndex, attributeValue),\n );\n break;\n\n case REF_KEY:\n statements.push(createRefStatement(nodesId, nodeIndex, attributeValue));\n break;\n\n case STYLE_NAME:\n addImport(importMap.patchStyle);\n statements.push(\n createAttributeStatement(state.imports.patchStyle, nodesId, nodeIndex, attributeValue),\n );\n break;\n\n default:\n if (startsWith(attributeName, `${UPDATE_PREFIX}:`)) {\n addImport(importMap.bindElement);\n const attrName = attributeName.split(':')[1];\n statements.push(\n createAttributeStatement(\n state.imports.bindElement,\n nodesId,\n nodeIndex,\n attributeValue,\n t.stringLiteral(attrName),\n ),\n );\n return;\n }\n // Process normal attributes\n addImport(importMap.patchAttr);\n statements.push(\n createAttributeStatement(\n state.imports.patchAttr,\n nodesId,\n nodeIndex,\n attributeValue,\n t.stringLiteral(attributeName),\n ),\n );\n break;\n }\n}\n\n/**\n * Process Immediately Invoked Function Expression (IIFE) optimization\n *\n * @param {t.Expression} node - Expression node to be processed\n * @returns {t.Expression} Optimized expression\n */\nexport function processIIFEExpression(node: t.Expression): t.Expression {\n // Check if it's an IIFE (Immediately Invoked Function Expression)\n if (\n t.isCallExpression(node) &&\n (t.isArrowFunctionExpression(node.callee) || t.isFunctionExpression(node.callee)) &&\n node.arguments.length === 0\n ) {\n const callee = node.callee;\n const body = callee.body;\n\n // Handle block-level function body { return value; }\n if (t.isBlockStatement(body)) {\n // Only handle simple cases with single return statement\n if (body.body.length === 1) {\n const statement = body.body[0];\n if (t.isReturnStatement(statement) && statement.argument) {\n // Directly return the return value, remove IIFE wrapper\n return statement.argument;\n }\n }\n }\n // Handle arrow function shorthand form (() => expression)\n else if (t.isExpression(body)) {\n // Directly return expression body, remove function wrapper\n return body;\n }\n }\n\n // Not IIFE or cannot be safely optimized, keep original expression\n return node;\n}\n\n/**\n * Create parameter array for DOM insertion operations\n *\n * @param {DynamicContent} dynamicContent - Dynamic content object (contains node and position info)\n * @param {t.Identifier} nodesIdentifier - Node mapping array identifier\n * @param {number[]} indexMap - Pre-calculated index mapping array\n * @returns {t.Expression[]} Parameter array for insert function call\n */\nexport function createInsertArguments(\n dynamicContent: DynamicContent,\n nodesIdentifier: t.Identifier,\n indexMap: number[] | Map<number, number>,\n): t.Expression[] {\n // Validate required parent node index\n if (isNil(dynamicContent.parentIndex)) {\n throw new Error('Dynamic content missing valid parent node index');\n }\n\n // Get parent node position in mapping array\n const parentPosition = findIndexPosition(dynamicContent.parentIndex, indexMap);\n if (parentPosition === -1) {\n throw new Error(\n `Cannot find parent node index in index mapping: ${dynamicContent.parentIndex}`,\n );\n }\n\n // Build basic parameter list\n const argExpressions: t.Expression[] = [\n // Target parent node reference: nodes[parentPosition]\n t.memberExpression(nodesIdentifier, t.numericLiteral(parentPosition), true),\n\n // CallExpression not be use call function\n // Content lazy function: () => dynamicContent (implements on-demand calculation)\n t.isCallExpression(dynamicContent.node) ||\n t.isArrowFunctionExpression(dynamicContent.node) ||\n t.isFunctionExpression(dynamicContent.node)\n ? dynamicContent.node\n : t.arrowFunctionExpression([], dynamicContent.node),\n ];\n\n // Handle insert position node (for insertBefore operation)\n if (dynamicContent.before !== null) {\n const beforePosition = findIndexPosition(dynamicContent.before, indexMap);\n if (beforePosition === -1) {\n throw new Error(`Cannot find before node index in index mapping: ${dynamicContent.before}`);\n }\n\n // Add before node reference: nodes[beforePosition]\n argExpressions.push(\n t.memberExpression(nodesIdentifier, t.numericLiteral(beforePosition), true),\n );\n }\n\n return argExpressions;\n}\n\n/**\n * Generate dynamic child node insertion code\n *\n * @param {DynamicContent[]} dynamicChildren - Dynamic child node collection\n * @param {t.Statement[]} statements - Statement collection (for adding generated code)\n * @param {State} state - Plugin state (contains import mapping)\n * @param {t.Identifier} nodesId - Node mapping array identifier\n * @param {number[]} indexMap - Index mapping array\n */\nfunction generateDynamicChildrenCode(\n dynamicChildren: DynamicContent[],\n statements: t.Statement[],\n state: PluginState,\n nodesId: t.Identifier,\n indexMap: number[],\n): void {\n // Ensure insert function is imported\n addImport(importMap.insert);\n\n // Create insertion statement for each dynamic content\n for (const dynamicContent of dynamicChildren) {\n // Special handling for IIFE expressions, optimize performance\n const processedNode = processIIFEExpression(dynamicContent.node);\n\n // Create insertion parameters\n const insertArgs = createInsertArguments(\n { ...dynamicContent, node: processedNode },\n nodesId,\n indexMap,\n );\n\n // Add insertion statement to code\n const insertCall = t.callExpression(state.imports.insert, insertArgs);\n statements.push(t.expressionStatement(insertCall));\n }\n}\n\n/**\n * Generate dynamic attribute setting code\n *\n * Redesigned as unified memoizedEffect architecture:\n * 1. Collect all reactive attributes\n * 2. Generate a unified memoizedEffect to handle all updates\n * 3. Set non-reactive attributes directly\n *\n * @param {Array<{ props: Record<string, unknown>; parentIndex: number | null }>} dynamicProps - Dynamic attribute collection\n * @param {t.Statement[]} statements - Statement collection (for adding generated code)\n * @param {State} state - Plugin state (contains import mapping and configuration)\n * @param {t.Identifier} nodesId - Node mapping array identifier\n * @param {number[]} indexMap - Index mapping array\n */\nfunction generateDynamicPropsCode(\n dynamicProps: Array<{\n props: Record<string, unknown>;\n parentIndex: number | null;\n }>,\n statements: t.Statement[],\n state: PluginState,\n nodesId: t.Identifier,\n indexMap: number[],\n): void {\n // Process each dynamic attribute item\n for (const propItem of dynamicProps) {\n const { parentIndex, props } = propItem;\n\n // Skip invalid parent node indices\n if (parentIndex === null) {\n continue;\n }\n\n // Find parent node position in index mapping\n const parentIndexPosition = indexMap.indexOf(parentIndex);\n if (parentIndexPosition === -1) {\n warn(`Cannot find parent node index: ${parentIndex}`);\n continue;\n }\n\n // Process each dynamic attribute of the node\n for (const [attrName, attrValue] of Object.entries(props)) {\n try {\n // Handle bind attributes (update:xxx) which are arrays [getter, setter]\n if (attrName.startsWith(`${UPDATE_PREFIX}:`) && Array.isArray(attrValue)) {\n // Type guard: ensure array elements are expressions\n if (\n attrValue.length === 2 &&\n t.isExpression(attrValue[0]) &&\n t.isExpression(attrValue[1])\n ) {\n generateSpecificAttributeCode(\n attrName,\n attrValue as any, // Pass array as-is, createAttributeStatement will spread it\n nodesId,\n parentIndexPosition,\n statements,\n state,\n );\n }\n continue;\n }\n\n // Process by attribute name classification\n // Type guard: attrValue must be Expression for dynamic props\n if (!t.isExpression(attrValue as t.Node)) {\n continue;\n }\n\n if (attrName.startsWith('on')) {\n // Handle event attributes (onClick, onMouseOver, etc.)\n addEventListenerStatement(\n attrName,\n attrValue as t.Expression,\n nodesId,\n parentIndexPosition,\n statements,\n state,\n );\n } else {\n // Non-reactive attributes, set directly\n generateSpecificAttributeCode(\n attrName,\n attrValue as t.Expression,\n nodesId,\n parentIndexPosition,\n statements,\n state,\n );\n }\n } catch (error) {\n // When single attribute processing fails, log error but continue processing other attributes\n warn(`Attribute processing failed (${attrName}): ${error}`);\n }\n }\n }\n\n // Reactive operations have been added to global collector, not processed here\n}\n\n/**\n * Generates a unified memoized effect to handle all reactive operations.\n * This function takes in an array of reactive operations, and a statement array\n * to which the generated code will be appended.\n * The generated code will create a memoized effect that will be called with the initial state\n * object, and will return the final state object.\n *\n * @param reactiveOperations An array of reactive operations to be processed.\n * @param statements The statement array to which the generated code will be appended.\n * @param state The plugin state.\n * @param nodesId The identifier of the nodes mapping.\n */\nfunction generateUnifiedMemoizedEffect(\n reactiveOperations: ReactiveOperation[],\n statements: t.Statement[],\n state: PluginState,\n nodesId: t.Identifier,\n indexMap: number[],\n): void {\n addImport(importMap.memoEffect);\n\n // Create variable declarations\n const variableDeclarations = reactiveOperations.map((op, index) => {\n const attrValue = op.attrValue;\n return t.variableDeclarator(t.identifier(`_v$${index}`), attrValue);\n });\n\n // Create update statements\n const updateStatements = reactiveOperations.map((op, index) => {\n // Get parent node position in mapping array\n const parentPosition = findIndexPosition(op.nodeIndex, indexMap);\n if (parentPosition === -1) {\n throw new Error(`Cannot find parent node index in index mapping: ${op.nodeIndex}`);\n }\n\n const varName = t.identifier(`_v$${index}`);\n const elementRef = t.memberExpression(nodesId, t.numericLiteral(parentPosition), true);\n\n let domOperationCall: t.CallExpression;\n\n // Handle attribute operations\n if (op.setFunction.name === 'patchAttr') {\n domOperationCall = t.callExpression(op.setFunction.value, [\n elementRef,\n t.stringLiteral(op.attrName),\n t.memberExpression(t.identifier('_p$'), t.identifier(op.propKey)),\n t.assignmentExpression(\n '=',\n t.memberExpression(t.identifier('_p$'), t.identifier(op.propKey)),\n varName,\n ),\n ]);\n } else {\n domOperationCall = t.callExpression(op.setFunction.value, [\n elementRef,\n t.memberExpression(t.identifier('_p$'), t.identifier(op.propKey)),\n t.assignmentExpression(\n '=',\n t.memberExpression(t.identifier('_p$'), t.identifier(op.propKey)),\n varName,\n ),\n ]);\n }\n\n // _v$0 !== _p$.c0 && (_p$.c0 = _v$0, _$patchClass(_el$, _v$0));\n return t.expressionStatement(\n t.logicalExpression(\n '&&',\n t.binaryExpression(\n '!==',\n varName,\n t.memberExpression(t.identifier('_p$'), t.identifier(op.propKey)),\n ),\n domOperationCall,\n ),\n );\n });\n\n // Create effect function body\n const effectBody = t.blockStatement([\n // var _v$0 = expr1, _v$1 = expr2, ...;\n t.variableDeclaration('var', variableDeclarations),\n // All update statements\n ...updateStatements,\n // return _p$;\n t.returnStatement(t.identifier('_p$')),\n ]);\n\n // Create effect function\n const effectFunction = t.arrowFunctionExpression([t.identifier('_p$')], effectBody);\n\n // Create initial state object\n const initialStateProperties = reactiveOperations.map(op =>\n t.objectProperty(t.identifier(op.propKey), t.identifier('undefined')),\n );\n const initialState = t.objectExpression(initialStateProperties);\n\n // Create memoizedEffect call\n const memoizedEffectCall = t.callExpression(state.imports.memoEffect, [\n effectFunction,\n initialState,\n ]);\n\n statements.push(t.expressionStatement(memoizedEffectCall));\n}\n\n/**\n * Recursively generates a static HTML template from a given TreeNode.\n *\n * This function is the main entry point for static template generation.\n * It handles all node types and delegates to specialized functions for\n * complex cases like normal elements and children processing.\n *\n * **Processing Rules:**\n * - Component/Fragment nodes: Return empty string (handled dynamically)\n * - Text nodes: Concatenate all text content\n * - Comment nodes: Generate HTML comment placeholder `<!>`\n * - Normal/SVG nodes: Delegate to gstForNormal for full element generation\n * - Other nodes: Delegate to gstForChildren for children-only generation\n *\n * @param {TreeNode} node - The TreeNode to generate the template from\n * @returns {string} The generated static HTML template string\n *\n * @example\n * ```typescript\n * // <div class=\"container\">Hello</div>\n * generateStaticTemplate(node)\n * // Returns: '<div class=\"container\">Hello</div>'\n * ```\n */\nfunction generateStaticTemplate(node: TreeNode): string {\n if (!node || node.type === NODE_TYPE.COMPONENT) {\n return '';\n }\n\n switch (node.type) {\n case NODE_TYPE.TEXT:\n // Text node: directly concatenate all child content\n return Array.isArray(node.children) ? node.children.join('') : '';\n\n case NODE_TYPE.COMMENT:\n // Comment node: generate HTML comment placeholder\n return '<!>';\n\n case NODE_TYPE.NORMAL:\n case NODE_TYPE.SVG:\n return gstForNormal(node);\n\n default:\n return gstForChildren(node);\n }\n}\n\n/**\n * Generates a static HTML template for a normal HTML element.\n *\n * This function handles the complete generation of HTML elements including:\n * - Opening tag with attributes\n * - Children content (recursively generated)\n * - Closing tag (or self-closing syntax)\n *\n * **Processing Steps:**\n * 1. Validate node has a tag name\n * 2. Serialize static attributes to HTML string\n * 3. Generate opening tag with attributes\n * 4. Handle self-closing tags (e.g., `<img />`, `<br />`)\n * 5. Recursively generate children content\n * 6. Generate closing tag\n *\n * @param {TreeNode} node - The TreeNode representing a normal HTML element\n * @returns {string} The generated static HTML template string\n *\n * @example\n * ```typescript\n * // <div class=\"container\"><span>Hello</span></div>\n * gstForNormal(node)\n * // Returns: '<div class=\"container\"><span>Hello</span></div>'\n * ```\n *\n * @example\n * ```typescript\n * // <img src=\"logo.png\" />\n * gstForNormal(node)\n * // Returns: '<img src=\"logo.png\"/>'\n * ```\n */\nfunction gstForNormal(node: TreeNode): string {\n if (!node.tag) {\n return gstForChildren(node);\n }\n\n const attributes = serializeAttributes(node.props);\n const startTag = `<${node.tag}${attributes ? ` ${attributes}` : ''}`;\n\n if (node.selfClosing) {\n return `${startTag}/>`;\n }\n\n return `${startTag}>${gstForChildren(node)}</${node.tag}>`;\n}\n/**\n * Recursively generates static HTML template for children nodes.\n *\n * This function processes all children of a TreeNode and concatenates their\n * static HTML representations. It handles both TreeNode children and string\n * literals, skipping dynamic content (which is handled separately).\n *\n * **Processing Rules:**\n * - TreeNode children: Recursively call generateStaticTemplate\n * - String children: Include directly in output\n * - Other types: Skip (dynamic content handled elsewhere)\n *\n * @param {TreeNode} node - The TreeNode whose children to process\n * @returns {string} The concatenated static HTML template of all children\n *\n * @example\n * ```typescript\n * // <div>Hello <span>World</span></div>\n * gstForChildren(divNode)\n * // Returns: 'Hello <span>World</span>'\n * ```\n */\nfunction gstForChildren(node: TreeNode): string {\n if (!node.children || !node.children.length) {\n return '';\n }\n\n const childTemplates: string[] = [];\n\n for (const child of node.children) {\n if (isObject(child)) {\n const childTemplate = generateStaticTemplate(child as TreeNode);\n childTemplates.push(childTemplate);\n } else if (isString(child)) {\n childTemplates.push(child);\n }\n }\n\n return childTemplates.join('');\n}\n\n/**\n * Collects all dynamic content from a TreeNode for client-side rendering.\n *\n * This function performs a depth-first traversal of the tree to identify and\n * collect all dynamic content that needs runtime processing. It separates\n * dynamic content into three categories:\n *\n * **Collection Categories:**\n * 1. **props**: Dynamic attributes that need one-time setting\n * 2. **children**: Dynamic child nodes (expressions, components, fragments)\n * 3. **operations**: Reactive attributes that need memoized updates\n *\n * **Processing Strategy:**\n * - Static content is already in the template (handled by generateStaticTemplate)\n * - Dynamic content is collected here for runtime code generation\n * - Reactive attributes are identified and added to operations for memoEffect\n *\n * @param {TreeNode} node - The root TreeNode to start collection from\n * @returns {DynamicCollection} Object containing all collected dynamic content\n *\n * @example\n * ```typescript\n * // <div class={cls}>{message}<button onClick={handler}>Click</button></div>\n * const dynamic = generateDynamic(node);\n * // dynamic.operations: [{ nodeIndex: 1, attrName: 'class', ... }]\n * // dynamic.children: [{ node: message, parentIndex: 1, ... }]\n * // dynamic.props: [{ props: { onClick: handler }, parentIndex: 2 }]\n * ```\n */\nfunction generateDynamic(node: TreeNode) {\n const dynamicCollection = {\n props: [],\n children: [],\n operations: [],\n };\n\n function walk(node: TreeNode, parentNode?: TreeNode) {\n processNodeDynamic(dynamicCollection, node, parentNode);\n\n // Skip recursive child processing for Fragment nodes\n // Fragment children are already included in the component expression\n // created by processNodeDynamic, so walking them again would cause duplicates\n if (node.type === NODE_TYPE.COMPONENT || node.type === NODE_TYPE.FRAGMENT) {\n return; // Skip processing component children in parent context\n }\n\n if (node.children && node.children.length) {\n node.children.forEach(child => {\n if (isTreeNode(child)) {\n walk(child as TreeNode, node);\n }\n });\n }\n }\n\n walk(node);\n\n return dynamicCollection;\n}\n\n/**\n * Processes a single TreeNode to extract dynamic content.\n *\n * This function is the core of dynamic content collection. It examines each node\n * and categorizes its dynamic aspects into the appropriate collection:\n *\n * **Node Type Processing:**\n * - **COMPONENT/FRAGMENT**: Create component expression and add to children\n * - **EXPRESSION**: Extract expression and add to children\n * - **TEXT**: Skip (already in static template)\n * - **NORMAL/SVG**: Process dynamic attributes\n *\n * **Attribute Classification:**\n * - **Reactive attributes**: Dynamic values that need memoized updates (class, style, etc.)\n * - **Event handlers**: onClick, onInput, etc. (added to props)\n * - **Bind directives**: update:xxx (added to props)\n * - **Static attributes**: Already in template (skipped)\n *\n * @param {DynamicCollection} dynamicCollection - The collection to populate\n * @param {TreeNode} node - The current node to process\n * @param {TreeNode} [parentNode] - The parent node (for context)\n *\n * @example\n * ```typescript\n * // <div class={cls}>{message}</div>\n * processNodeDynamic(collection, divNode, null);\n * // collection.operations: [{ attrName: 'class', attrValue: cls, ... }]\n * // collection.children: [{ node: message, ... }]\n * ```\n */\nfunction processNodeDynamic(dynamicCollection, node: TreeNode, parentNode?: TreeNode): void {\n const { children, props, operations } = dynamicCollection;\n\n switch (node.type) {\n case NODE_TYPE.COMPONENT: {\n // Prepare component attributes\n const componentProps = { ...node.props, children: node.children };\n\n // Create component call expression\n const componentExpr = createComponentExpression(node, componentProps);\n\n // Add to dynamic content list\n children.push({\n index: node.index,\n node: componentExpr,\n before: findBeforeIndex(node, parentNode as TreeNode),\n parentIndex: parentNode?.index ?? null,\n });\n break;\n }\n\n case NODE_TYPE.EXPRESSION:\n // Ensure child node array is not empty and first element is an expression\n if (node.children && node.children.length > 0) {\n const firstChild = node.children[0];\n // Handle JavaScript expression nodes\n if (isObject(firstChild) && t.isNode(firstChild) && t.isExpression(firstChild)) {\n // TODO: maybe support map\n // if (isMapCall(firstChild)) {\n // const mapCall = firstChild as t.CallExpression;\n // const list = (mapCall.callee as t.MemberExpression).object;\n // const callback = mapCall.arguments[0];\n\n // addImport(importMap.For);\n\n // let childrenProp = callback;\n // // Wrap callback if it uses index to unwrap the getter\n // if (\n // (t.isArrowFunctionExpression(callback) || t.isFunctionExpression(callback)) &&\n // callback.params.length > 1 &&\n // checkHasJSXReturn(callback)\n // ) {\n // const itemParam = path.scope.generateUidIdentifier('item');\n // const indexParam = path.scope.generateUidIdentifier('index');\n // childrenProp = t.arrowFunctionExpression(\n // [itemParam, indexParam],\n // t.callExpression(callback as t.Expression, [\n // itemParam,\n // t.callExpression(indexParam, []),\n // ]),\n // );\n // }\n // // 特殊处理,默认tree不处理map,所有这里要添加一个tag\n // node.tag = 'For';\n // children.push({\n // index: node.index,\n // node: createComponentExpression(node, {\n // each: list,\n // children: childrenProp,\n // }),\n // before: findBeforeIndex(node, parentNode as TreeNode),\n // parentIndex: parentNode?.index ?? null,\n // });\n // } else {\n children.push({\n index: node.index,\n node: t.arrowFunctionExpression([], firstChild),\n before: findBeforeIndex(node, parentNode as TreeNode),\n parentIndex: parentNode?.index ?? null,\n });\n // }\n }\n // Handle JSX elements/fragments in expression containers\n else if (isObject(firstChild) && t.isNode(firstChild) && t.isJSXElement(firstChild)) {\n // Treat JSX elements in expression containers as components\n // This usually occurs in: {<SomeComponent />} or {<></>}\n children.push({\n index: node.index,\n node: createComponentExpression(node, { children: [firstChild] }),\n before: findBeforeIndex(node, parentNode as TreeNode),\n parentIndex: parentNode?.index ?? null,\n });\n }\n }\n break;\n\n // Text nodes don't need dynamic processing (already handled in template stage)\n case NODE_TYPE.TEXT:\n break;\n\n default:\n // Handle regular HTML nodes with dynamic attributes\n // Dynamic attributes include: event handlers, conditional rendering attributes, dynamic styles, etc.\n if (node.props && Object.keys(node.props).length > 0) {\n const currentProps = {};\n\n for (const [attrName, attrValue] of Object.entries(node.props)) {\n // Type guard: check if attrValue is a Node before checking if it's dynamic\n const isReactive =\n t.isNode(attrValue) &&\n isDynamicExpression(attrValue) &&\n !startsWith(attrName, `${UPDATE_PREFIX}:`) &&\n !startsWith(attrName, EVENT_ATTR_NAME) &&\n attrName !== REF_KEY;\n\n // support bind:value\n if (startsWith(attrName, `${UPDATE_PREFIX}:`)) {\n const name = attrName.split(':')[1];\n const setFunction = getSetFunctionForAttribute();\n addImport(importMap[setFunction.name as keyof typeof importMap]);\n\n operations.push({\n nodeIndex: node?.index,\n attrName: name,\n attrValue: (attrValue as any)[0],\n setFunction,\n propKey: generatePropKey(),\n });\n }\n if (isReactive && t.isExpression(attrValue)) {\n // Collect reactive attributes for unified processing later\n const setFunction = getSetFunctionForAttribute(attrName);\n addImport(importMap[setFunction.name as keyof typeof importMap]);\n\n operations.push({\n nodeIndex: node?.index,\n attrName,\n attrValue,\n setFunction,\n propKey: generatePropKey(attrName),\n });\n } else {\n currentProps[attrName] = attrValue;\n }\n }\n\n if (Object.keys(currentProps).length > 0) {\n props.push({\n props: currentProps,\n parentIndex: node?.index ?? null,\n });\n }\n }\n break;\n }\n}\n","/**\n * Node Type Enum\n * @description Defines the types of different nodes in the JSX tree, used for internal processing and optimization.\n */\nexport enum NODE_TYPE {\n // normal\n NORMAL = 0,\n // component\n COMPONENT = 1,\n // text\n TEXT = 2,\n // fragment\n FRAGMENT = 3,\n // expression\n EXPRESSION = 4,\n // svg\n SVG = 5,\n // comment\n COMMENT = 6,\n // spread\n SPREAD = 7,\n}\n\n/**\n * Element Flags Enum\n * @description Defines special flags for HTML elements, used for rendering optimization.\n */\nexport enum ELEMENT_FLAGS {\n // Self-closing tag (e.g. <img />)\n SELF_CLOSING = 0,\n // Within SVG scope (e.g. <svg><path/></svg>)\n IN_SVG_SCOPE = 1,\n}\n\n/**\n * Key name for the CSS class attribute\n */\nexport const CLASS_NAME = 'class';\n\n/**\n * Key name for the Style attribute\n */\nexport const STYLE_NAME = 'style';\n\n/**\n * Prefix for event attributes\n */\nexport const EVENT_ATTR_NAME = 'on';\n\n/**\n * Prefix for update attributes\n */\nexport const UPDATE_PREFIX = 'update';\n\n/**\n * Tag name for Fragment components\n */\nexport const FRAGMENT_NAME = 'Fragment';\n\n/**\n * Key name for the Children attribute\n */\nexport const CHILDREN_NAME = 'children';\n\nexport const REF_KEY = 'ref';\n/**\n * Key name for the Spread attribute\n */\nexport const SPREAD_NAME = '_$spread$';\n\n/**\n * Key name for the Create Component attribute\n */\nexport const CREATE_COMPONENT_NAME = 'createComponent';\n\n/**\n * data-idx regex for hydration\n */\nexport const DATA_IDX_REGEX = /^\\d+-\\d+$/;\n\n/**\n * Bind regex for bind attributes\n */\nexport const BIND_REG = /^bind:.+/;\nexport const BUILT_IN_COMPONENTS = ['Fragment', 'Portal', 'Suspense', 'For'];\n","import { type NodePath, types as t } from '@babel/core';\nimport {\n isArray,\n isBoolean,\n isMap,\n isNull,\n isNumber,\n isObject,\n isString,\n isUndefined,\n} from '@estjs/shared';\n\nimport {\n CHILDREN_NAME,\n CLASS_NAME,\n FRAGMENT_NAME,\n NODE_TYPE,\n SPREAD_NAME,\n STYLE_NAME,\n} from './constants';\nimport { createTree, isTreeNode } from './tree';\nimport { getContext } from './context';\nimport type { Expression } from '@babel/types';\nimport type { TreeNode } from './tree';\nimport type { JSXChild, JSXElement } from '../types';\n\n/**\n * Dynamic Content Interface\n * @description Represents JSX content that needs dynamic processing, such as components, expressions, etc.\n */\nexport interface DynamicContent {\n /** Dynamic content type identifier */\n type?: string;\n /** Node index */\n index: number;\n /** AST node expression */\n node: t.Expression;\n /** Previous node index, used to determine insertion position */\n before: number | null;\n /** Template index */\n templateIndex?: number;\n /** Parent node index */\n parentIndex?: number | null;\n /** Attribute name, used for dynamic attributes */\n attrName?: string;\n}\n\n/**\n * Dynamic Content Collection Interface\n * @description Used to type-strengthen dynamic content collection results\n */\nexport interface DynamicCollection {\n /** Dynamic child node list */\n children: DynamicContent[];\n /** Dynamic attribute list */\n props: Array<{\n /** Attribute object */\n props: Record<string, unknown>;\n /** Parent node index */\n parentIndex: number | null;\n }>;\n /** Reactive operations list */\n operations: Array<{\n nodeIndex: number;\n attrName: string;\n attrValue: any;\n setFunction: {\n name: string;\n value: any;\n };\n propKey: string;\n }>;\n}\n\n/**\n * Determine whether a string is a component name\n *\n * Identifies custom components by checking naming conventions:\n * - First letter capitalized (e.g., MyComponent)\n * - Contains dot notation (e.g., SomeLibrary.Component)\n * - Starts with non-alphabetic character (e.g., _Component)\n *\n\n * @param {string} tagName - The tag name to check\n * @returns {boolean} `true` if the tag represents a component, `false` otherwise\n */\nexport function isComponentName(tagName: string): boolean {\n if (!tagName) {\n return false;\n }\n\n const firstCharCode = tagName.charCodeAt(0);\n\n // 65-90 are uppercase A-Z, 97-122 are lowercase a-z\n if (firstCharCode >= 65 && firstCharCode <= 90) {\n return true; // Uppercase letter\n }\n\n // Check for dot or colon notation\n const dotIndex = tagName.indexOf('.');\n const colonIndex = tagName.indexOf(':');\n\n if (dotIndex !== -1 || colonIndex !== -1) {\n // Split and check segments\n const segments = tagName.split(/[:.]/);\n const len = segments.length;\n for (let i = 0; i < len; i++) {\n const segment = segments[i];\n if (segment.length > 0) {\n const segmentCharCode = segment.charCodeAt(0);\n if (segmentCharCode >= 65 && segmentCharCode <= 90) {\n return true;\n }\n }\n }\n }\n\n // Check for non-alphabetic first character (like _Component)\n return !(firstCharCode >= 97 && firstCharCode <= 122); // Not lowercase letter\n}\n\n/**\n * Get tag name from JSX element node\n *\n * Extracts the tag name from JSX elements and fragments, handling both\n * regular HTML elements and custom components.\n *\n * @param {t.JSXElement | t.JSXFragment} node - AST node of JSX element or fragment\n * @returns {string} Tag name string (e.g., 'div', 'MyComponent', 'Fragment')\n */\nexport const getTagName = (node: t.JSXElement | t.JSXFragment): string => {\n // Handle JSX Fragment (<>...</> or <Fragment>...</Fragment>) case\n if (t.isJSXFragment(node)) {\n return FRAGMENT_NAME;\n }\n\n // Handle regular JSX elements (like <div>, <MyComponent.Nested/>)\n const tag = node.openingElement.name;\n return jsxElementNameToString(tag);\n};\n\n/**\n * Convert JSX element name to string representation\n * @description Supports JSXIdentifier (e.g., MyComponent), JSXMemberExpression (e.g., SomeLibrary.SomeComponent)\n * and JSXNamespacedName (e.g., namespace:ComponentName) forms.\n * @param {t.JSXMemberExpression | t.JSXIdentifier | t.JSXNamespacedName} node - AST node of JSX element name.\n * @returns {string} String representation of JSX element name.\n */\nexport function jsxElementNameToString(\n node: t.JSXMemberExpression | t.JSXIdentifier | t.JSXNamespacedName | t.MemberExpression,\n): string {\n if (t.isJSXMemberExpression(node)) {\n // Process member expression, recursively join (e.g., SomeLibrary.SomeComponent)\n return `${jsxElementNameToString(node.object)}.${jsxElementNameToString(node.property)}`;\n }\n\n if (t.isMemberExpression(node)) {\n const objectName = jsxElementNameToString(\n node.object as unknown as t.JSXIdentifier | t.JSXMemberExpression,\n );\n const propertyName = jsxElementNameToString(\n node.property as unknown as t.JSXIdentifier | t.JSXMemberExpression,\n );\n return `${objectName}.${propertyName}`;\n }\n\n if (t.isJSXIdentifier(node) || t.isIdentifier(node)) {\n // Process identifier (e.g., MyComponent)\n return node.name;\n }\n\n // Process namespace expression (e.g., namespace:ComponentName)\n const namespace = node.namespace?.name ?? '';\n const name = node.name?.name ?? '';\n if (!namespace) {\n return name;\n }\n if (!name) {\n return namespace;\n }\n return `${namespace}:${name}`;\n}\n\n/**\n * Determine if the given path represents a text child node in JSX expression\n * @description Check if the node is of type JSXText, StringLiteral, or NumericLiteral.\n * @param {NodePath<JSXChild>} path - AST path of potential text child node.\n * @returns {boolean} `true` if the path represents a text child node, `false` otherwise.\n */\nexport function isTextChild(path: NodePath<JSXChild>): boolean {\n if (path.isJSXExpressionContainer && path.isJSXExpressionContainer()) {\n const expression = path.get('expression');\n if (expression.isJSXText() || expression.isStringLiteral() || expression.isNumericLiteral()) {\n return true;\n }\n }\n if (path.isJSXText && path.isJSXText()) {\n return true;\n }\n if (path.isStringLiteral && path.isStringLiteral()) {\n return true;\n }\n if (path.isNullLiteral && path.isNullLiteral()) {\n return true;\n }\n return false;\n}\n\n/**\n * Trim text content of JSXText node\n * @description Remove excess whitespace and line breaks, merge multiple spaces into a single space.\n *\n\n * @param {t.JSXText} node - JSXText AST node.\n * @returns {string} Trimmed text content.\n */\nexport function textTrim(node: t.JSXText): string {\n if (!node || !node.value) return '';\n\n return node.value.trim();\n}\n\n/**\n * Determine if a JSX child node is valid\n * @description Ignore text nodes that contain only whitespace.\n * @param {NodePath<JSXChild>} path - AST path of JSX child node.\n * @returns {boolean} `true` if the node is valid, `false` otherwise.\n */\nexport function isValidChild(path: NodePath<JSXChild>): boolean {\n const regex = /^\\s*$/;\n if (t.isStringLiteral(path.node)) {\n return !regex.test((path.node as t.StringLiteral).value);\n }\n if (t.isJSXText(path.node)) {\n return !regex.test((path.node as t.JSXText).value);\n }\n return Object.keys(path.node).length > 0; // For other types of nodes, consider valid if they have content\n}\n\n/**\n * Get raw text content of a node without trimming\n * @description Extract raw text from JSXText or JSXExpressionContainer without trimming whitespace.\n * @param {NodePath<JSXChild>} path - AST path of JSX child node.\n * @returns {string} Raw text content of the node, or empty string if not a text node.\n */\nexport function getRawNodeText(path: NodePath<JSXChild>): string {\n if (path.isJSXText()) {\n return path.node.value || '';\n }\n if (path.isJSXExpressionContainer()) {\n const expression = path.get('expression');\n if (expression.isStringLiteral() || expression.isNumericLiteral()) {\n return String(expression.node.value);\n }\n }\n return '';\n}\n\n/**\n * Get text content of a node\n * @description Extract text from JSXText or JSXExpressionContainer containing StringLiteral/NumericLiteral.\n * @param {NodePath<JSXChild>} path - AST path of JSX child node.\n * @returns {string} Text content of the node, or empty string if not a text node.\n */\nexport function getNodeText(path: NodePath<JSXChild>): string {\n if (path.isJSXText()) {\n return textTrim(path.node);\n }\n if (path.isJSXExpressionContainer()) {\n const expression = path.get('expression');\n if (expression.isStringLiteral() || expression.isNumericLiteral()) {\n return String(expression.node.value);\n }\n }\n return '';\n}\n\n/**\n * Set text content of JSX child node\n * @description Update value of JSXText or StringLiteral/NumericLiteral in JSXExpressionContainer.\n * @param {NodePath<JSXChild>} path - AST path of JSX child node.\n * @param {string} text - Text content to set.\n */\nexport function setNodeText(path: NodePath<JSXChild>, text: string): void {\n if (path.isJSXText()) {\n path.node.value = text;\n }\n if (path.isJSXExpressionContainer()) {\n const expression = path.get('expression');\n if (expression.isStringLiteral() || expression.isNumericLiteral()) {\n expression.replaceWith(t.stringLiteral(text));\n }\n }\n}\n\n/**\n * Optimize child node list, merge adjacent text nodes\n * @description Traverse child node list, merge consecutive text nodes into one, reduce number of generated AST nodes, improve rendering performance.\n * @param {NodePath<JSXChild>[]} children - Original array of child node paths.\n * @returns {NodePath<JSXChild>[]} Optimized array of child node paths.\n */\nexport function optimizeChildNodes(children: NodePath<JSXChild>[]): NodePath<JSXChild>[] {\n const mergedWithExpression = new WeakSet<NodePath<JSXChild>>();\n\n return children.reduce<NodePath<JSXChild>[]>((acc, cur) => {\n if (isValidChild(cur)) {\n const lastChild = acc.at(-1);\n if (!lastChild) {\n acc.push(cur as NodePath<JSXChild>);\n return acc;\n }\n\n const lastIsPlainText = lastChild.isJSXText?.() ?? false;\n const currentIsPlainText = cur.isJSXText?.() ?? false;\n\n if (\n lastIsPlainText &&\n t.isJSXExpressionContainer(cur.node) &&\n (cur.get('expression').isStringLiteral() || cur.get('expression').isNumericLiteral()) &&\n !mergedWithExpression.has(lastChild)\n ) {\n const mergedText = getRawNodeText(lastChild) + getRawNodeText(cur);\n setNodeText(lastChild, mergedText);\n mergedWithExpression.add(lastChild);\n return acc;\n }\n\n if (lastIsPlainText && currentIsPlainText && !mergedWithExpression.has(lastChild)) {\n const mergedText = getRawNodeText(lastChild) + getRawNodeText(cur);\n setNodeText(lastChild, mergedText);\n return acc;\n }\n\n acc.push(cur as NodePath<JSXChild>);\n }\n return acc;\n }, []);\n}\n\n/**\n * Deep check if property in ObjectExpression contains dynamic values\n * Recursively examines object expressions to detect dynamic attributes\n *\n * @example\n * // dynamic attribute\n * <div class={{'a': a}} />\n *\n * // dynamic object dynamic attribute\n * <div class={{'a': {b: c}}} />\n *\n * // conditional expression\n * <div class={a ? 'a' : 'b'} />\n *\n * // deep conditional expression\n * <div class={a:{b:{c:c ? 'c' : 'd'}}} />\n *\n * // string expression\n * <div class={{with:`${a}px`}} />\n *\n * // string dynamic object expression\n * <div class={{with:`${a ? '1' : '2'}px`}} />\n *\n * @param {ObjectExpression} node\n * @return {boolean}\n */\nexport function deepCheckObjectDynamic(node: t.ObjectExpression): boolean {\n if (!t.isObjectExpression(node)) return false;\n\n let dynamic = false;\n\n // Recursive traversal\n function walk(current) {\n if (dynamic) return; // Already hit, early pruning\n\n // 1. Common 'dynamic' nodes: directly set to true\n if (\n t.isIdentifier(current) ||\n t.isCallExpression(current) ||\n t.isMemberExpression(current) ||\n t.isConditionalExpression(current) ||\n t.isTemplateLiteral(current) ||\n t.isBinaryExpression(current) ||\n t.isUpdateExpression(current) ||\n t.isUnaryExpression(current) ||\n t.isAwaitExpression(current) ||\n t.isYieldExpression(current) ||\n t.isTaggedTemplateExpression(current)\n ) {\n dynamic = true;\n return;\n }\n\n // 2. Object / Array expressions continue searching downward\n if (t.isObjectExpression(current)) {\n current.properties.forEach(prop => {\n if (t.isObjectProperty(prop)) walk(prop.value);\n if (t.isSpreadElement(prop)) walk(prop.argument);\n });\n return;\n }\n\n if (t.isArrayExpression(current)) {\n current.elements.forEach(el => el && walk(el));\n return;\n }\n\n // 3. Other nodes (Literal, RegExpLiteral...) are considered static, no processing needed\n }\n\n walk(node);\n return dynamic;\n}\n\n/**\n * Processes object expressions in JSX attributes, handling both conditional expressions\n * and static class/style attribute extraction (when isCt=true)\n *\n * @param propName - Current property name being processed (e.g., \"class\" or \"style\")\n * @param objectExpr - The object expression AST node to process\n * @param propsCollection - Collection of component props to modify\n * @param isClassOrStyleAttr - Flag indicating if processing class/style attribute (special handling)\n * @returns Generated class/style string when processing class/style attributes\n */\nexport function processObjectExpression(\n propName: string,\n objectExpr: t.ObjectExpression,\n propsCollection: Record<string, unknown>,\n isClassOrStyleAttr = false,\n): string {\n let classStyleString = '';\n\n // Handle conditional properties - let unified architecture handle\n if (deepCheckObjectDynamic(objectExpr)) {\n // Directly store object expression, let unified memoizedEffect architecture handle\n propsCollection[propName] = objectExpr;\n }\n // Special handling for static class/style attributes\n else if (isClassOrStyleAttr) {\n classStyleString = objectExpr.properties\n .filter((property): property is t.ObjectProperty => t.isObjectProperty(property))\n .reduce((acc, property) => {\n const key = t.isIdentifier(property.key)\n ? property.key.name\n : t.isStringLiteral(property.key)\n ? property.key.value\n : String(property.key);\n\n // Ensure value is static string literal\n if (t.isStringLiteral(property.value)) {\n return `${acc}${key}:${property.value.value};`;\n }\n return acc;\n }, '');\n\n // Remove original prop as we've converted it to string\n delete propsCollection[propName];\n }\n\n return classStyleString;\n}\n\n/**\n * Get the name of JSX attribute\n * @description Extract string name from JSXAttribute node.\n * @param {t.JSXAttribute} attribute - AST node of JSX attribute.\n * @returns {string} Name of the attribute.\n * @throws {Error} If attribute type is not supported.\n */\nexport function getAttrName(attribute: t.JSXAttribute): string {\n if (t.isJSXIdentifier(attribute.name)) {\n return attribute.name.name;\n }\n if (t.isJSXNamespacedName(attribute.name)) {\n return `${attribute.name.namespace.name}:${attribute.name.name.name}`;\n }\n\n return '';\n}\n\n/**\n * Serialize HTML element attributes to string\n * @description Serialize JSX attribute object to HTML attribute string\n * @param {Record<string, unknown>|undefined} attributes - Attribute object\n * @return {string} Serialized HTML attribute string\n */\nexport function serializeAttributes(attributes: Record<string, unknown> | undefined): string {\n if (!attributes || !isObject(attributes)) {\n return '';\n }\n\n let attributesString = '';\n let classNames = '';\n let styleString = '';\n\n // Process all attributes\n for (const [attrName, attrValue] of Object.entries(attributes)) {\n // Process class attribute\n if (attrName === CLASS_NAME && isString(attrValue)) {\n classNames += ` ${attrValue}`;\n delete attributes[attrName];\n }\n // Process style attribute\n else if (attrName === STYLE_NAME && isString(attrValue)) {\n styleString += `${attrValue}${attrValue.at(-1) === ';' ? '' : ';'}`;\n delete attributes[attrName];\n }\n // Process boolean attributes\n else if (attrValue === true) {\n attributesString += ` ${attrName}`;\n delete attributes[attrName];\n }\n // Ignore false attributes\n else if (attrValue === false) {\n delete attributes[attrName];\n }\n // Process string and number attributes\n else if (isString(attrValue) || isNumber(attrValue)) {\n attributesString += ` ${attrName}=\"${attrValue}\"`;\n delete attributes[attrName];\n }\n // Process conditional expressions - let unified architecture handle\n else if (t.isConditionalExpression(attrValue as t.Node)) {\n // Store conditional expressions directly, let unified memoizedEffect architecture handle\n // This way all reactive attributes will be handled uniformly in generateDynamicPropsCode\n attributes[attrName] = attrValue;\n }\n // Process object expressions\n else if (t.isObjectExpression(attrValue as t.ObjectExpression)) {\n const result = processObjectExpression(\n attrName,\n attrValue as t.ObjectExpression,\n attributes,\n attrName === CLASS_NAME || attrName === STYLE_NAME,\n );\n\n if (result) {\n if (attrName === CLASS_NAME) {\n classNames += ` ${result}`;\n }\n if (attrName === STYLE_NAME) {\n styleString += `${result}${result.at(-1) === ';' ? '' : ';'}`;\n }\n }\n }\n }\n\n // Add class and style attributes\n if (classNames.trim()) {\n attributesString += ` ${CLASS_NAME}=\"${classNames.trim()}\"`;\n }\n if (styleString.trim()) {\n attributesString += ` ${STYLE_NAME}=\"${styleString.trim()}\"`;\n }\n\n return attributesString;\n}\n\n/**\n * Find the marker node index where dynamic content should be inserted\n * @description Used to determine the insertion position of dynamic nodes within a parent node, handling two main scenarios:\n * 1. Followed by static node: Use the following static node as insertion marker.\n * 2. Followed by dynamic content: Need to create a comment node `<!>` as insertion marker.\n *\n * Typical use case analysis table:\n * +---------------------+-------------------------------+---------------------------+-----------------------+\n * | Template Structure | Compiled Structure | Insertion Logic | Return Value |\n * +---------------------+-------------------------------+---------------------------+-----------------------+\n * | `<div>{v}</div>` | `<div></div>` | Append to end | `null` (no following node) |\n * | `<div>A{v}B</div>` | `<div>A<!>B</div>` | Insert before `<!>` | Comment node index |\n * | `<div>{v}<span/></div>` | `<div><span/></div>` | Insert before `span` | `span` node index |\n * | `<div>{v}{v}</div>` | `<div><!></div>` | Insert in order before `<!>` | Comment node index |\n * | `<div><p/>{v}</div>` | `<div><p/></div>` | Append to end | `null` |\n * | `<div>{v}<!></div>` | `<div><!></div>` | Insert before existing `<!>` | Comment node index |\n * | `<div>{v1}{v2}<br/></div>` | `<div><br/></div>` | Insert `v2` before `br`, then insert `v1` | `br` node index |\n * | `<div>{v}<!-- --></div>` | `<div><!-- --></div>` | Insert before comment node | Comment node index |\n * | `<div>{v}<Component/></div>` | `<div><Component/></div>` | Insert before component | Component node index |\n * +---------------------+-------------------------------+---------------------------+-----------------------+\n *\n * @param {TreeNode} currentNode - Current dynamic node (expression/fragment/component).\n * @param {TreeNode} parentNode - Parent node of the current node.\n * @returns {number | null} Index of the target marker node, or `null` if no suitable position.\n */\nexport function findBeforeIndex(currentNode: TreeNode, parentNode: TreeNode): number | null {\n // Boundary condition check: If parent node has no children, or current node is the last child, no need for prefix marker\n if (!parentNode?.children?.length || currentNode.isLastChild) {\n return null;\n }\n\n const children = parentNode.children;\n const childrenLength = children.length;\n\n // Find current node index\n let nodeIndex = -1;\n for (let i = 0; i < childrenLength; i++) {\n if (children[i] === currentNode) {\n nodeIndex = i;\n break;\n }\n }\n\n // If node not found or is last child, return null\n if (nodeIndex === -1 || nodeIndex === childrenLength - 1) {\n return null;\n }\n\n // Search forward for the nearest non-dynamic sibling node as insertion marker\n for (let searchIndex = nodeIndex + 1; searchIndex < childrenLength; searchIndex++) {\n const siblingNode = children[searchIndex] as TreeNode;\n const siblingType = siblingNode.type;\n\n // Check if node is static (not dynamic)\n if (\n siblingType !== NODE_TYPE.EXPRESSION &&\n siblingType !== NODE_TYPE.FRAGMENT &&\n siblingType !== NODE_TYPE.COMPONENT\n ) {\n return siblingNode.index; // Found static node, return its index\n }\n }\n\n return null; // If all following nodes are dynamic or there are no nodes, append to the end (return null)\n}\n\n/**\n * Collect DOM node indices that need to be mapped\n * @description Extract DOM node indices that need to be referenced on the client side from dynamic children and dynamic attributes.\n *\n * @param {DynamicContent[]} dynamicChildren - Dynamic children collection.\n * @param {Array<{props: Record<string, unknown>; parentIndex: number | null}>} dynamicProps - Dynamic attribute collection.\n * @returns {number[]} De-duplicated and sorted index list, representing DOM nodes that need to be mapped.\n */\nexport function collectNodeIndexMap(\n dynamicChildren: DynamicContent[],\n dynamicProps: Array<{\n props: Record<string, unknown>;\n parentIndex: number | null;\n }>,\n extraIndices: number[] = [],\n): number[] {\n // Use Set for automatic de-duplication\n const indexSet = new Set<number>(extraIndices);\n\n const childrenLength = dynamicChildren.length;\n for (let i = 0; i < childrenLength; i++) {\n const item = dynamicChildren[i];\n const parentIndex = item.parentIndex;\n const beforeIndex = item.before;\n\n // Add parent index if valid (not null/undefined)\n if (parentIndex !== null && parentIndex) {\n indexSet.add(parentIndex);\n }\n // Add before index if valid (not null/undefined)\n if (beforeIndex !== null && beforeIndex) {\n indexSet.add(beforeIndex);\n }\n }\n\n // Collect parent node indices of dynamic attributes\n const propsLength = dynamicProps.length;\n for (let i = 0; i < propsLength; i++) {\n const parentIndex = dynamicProps[i].parentIndex;\n if (parentIndex !== null && parentIndex) {\n indexSet.add(parentIndex);\n }\n }\n\n // Convert Set to sorted array\n return Array.from(indexSet).sort((a, b) => a - b);\n}\n\n/**\n * Find the position of an index in the mapping array\n * @description In a pre-generated DOM node index mapping array, find the actual position of a specific target index.\n * Used at client runtime to quickly locate DOM nodes by index.\n * @param {number} targetIndex - Original index of the target node (TreeNode.index).\n * @param {number[]} indexMap - Pre-collected and sorted DOM node index mapping array.\n * @returns {number} Position of the target index in the `indexMap` array (0-based index), returns `-1` if not found.\n *\n * Use case examples:\n * 1. `targetIndex=1`, `indexMap=[1,2,3]` => returns `0`\n * 2. `targetIndex=2`, `indexMap=[1,2,3]` => returns `1`\n * 3. `targetIndex=3`, `indexMap=[1,2,3]` => returns `2`\n * 4. `targetIndex=4`, `indexMap=[1,2,3]` => returns `-1` (not found)\n */\nexport function findIndexPosition(\n targetIndex: number,\n indexMap: number[] | Map<number, number>,\n): number {\n if (isArray(indexMap)) {\n return indexMap.indexOf(targetIndex);\n }\n if (isMap(indexMap)) {\n const position = indexMap.get(targetIndex);\n return isNumber(position) ? position : -1;\n }\n return -1;\n}\n\n/**\n * Insert comment nodes (type: COMMENT) into TreeNode.children where needed\n * @param {TreeNode} node - Current TreeNode to process.\n */\nexport function processTextElementAddComment(node: TreeNode): void {\n if (!node.children || node.children.length === 0) {\n return;\n }\n\n const children = node.children as TreeNode[];\n const childrenLength = children.length;\n\n // Recursively process all child nodes first\n for (let i = 0; i < childrenLength; i++) {\n const child = children[i];\n // Only recursively process when child is TreeNode type\n if (isTreeNode(child)) {\n processTextElementAddComment(child);\n }\n }\n\n // Check if comments need to be inserted\n let needsComments = false;\n for (let i = 0; i < childrenLength - 1; i++) {\n if (shouldInsertComment(children as TreeNode[], i)) {\n needsComments = true;\n break;\n }\n }\n\n // If no comments needed, skip array reconstruction\n if (!needsComments) {\n return;\n }\n\n // Build new children array with comments inserted\n const newChildren: (TreeNode | string | JSXChild)[] = [];\n for (let i = 0; i < childrenLength; i++) {\n newChildren.push(children[i]);\n\n // Check if comment should be inserted after current node\n if (shouldInsertComment(children as TreeNode[], i)) {\n newChildren.push({\n type: NODE_TYPE.COMMENT,\n isComment: true,\n children: [],\n index: -1,\n parentIndex: node.index,\n } as TreeNode);\n }\n }\n\n // Replace children array\n node.children = newChildren;\n}\n\n/**\n * Determine if comment node should be inserted\n * @description Assists the `processTextElementAddComment` function, determines if comment node should be inserted at given position.\n * Rule: Current node is an expression, and is immediately followed by non-HTML/SVG element (i.e., another dynamic content or text node).\n * @param {(TreeNode | string)[]} children - Array of child nodes of parent node.\n * @param {number} idx - Index of current child node to check in the array.\n * @returns {boolean} `true` if comment node needs to be inserted, `false` otherwise.\n */\nfunction shouldInsertComment(children: (TreeNode | string | JSXChild)[], idx: number): boolean {\n const cur = children[idx];\n const next = children[idx + 1];\n\n // Only process expression nodes, because comment nodes are used to separate adjacent dynamic content\n if (!cur || !isObject(cur) || cur.type !== NODE_TYPE.EXPRESSION) {\n return false;\n }\n\n // If it's the last node, or is immediately followed by HTML/SVG element, comment node is not needed\n if (\n !next ||\n (isObject(next) && (next.type === NODE_TYPE.NORMAL || next.type === NODE_TYPE.SVG))\n ) {\n return false;\n }\n\n // Other cases (expression followed by text, another expression, Fragment or Component), comment node should be inserted\n return true;\n}\n\n/**\n * Normalize JSX props into a single flat record.\n * 1. Multiple occurrences of `class` / `className` / `style` are merged into a single string (static) or array (dynamic).\n * 2. Collect multiple object spreads as unified `SPREAD_NAME` record to avoid extra traversal.\n */\nexport function normalizeProps(raw: Record<string, unknown>): Record<string, unknown> {\n const normalized: Record<string, unknown> = {};\n\n const classBuffer: string[] = [];\n const styleBuffer: string[] = [];\n\n for (const [key, value] of Object.entries(raw)) {\n // Handle both 'class' and 'className' (React compatibility)\n if (key === CLASS_NAME || key === 'className') {\n if (isString(value)) classBuffer.push(value);\n else {\n // If there's already a dynamic class expression, keep the last one\n normalized[CLASS_NAME] = value; // Keep dynamic expressions as-is\n }\n continue;\n }\n\n if (key === STYLE_NAME) {\n if (isString(value)) styleBuffer.push(value);\n else normalized[STYLE_NAME] = value;\n continue;\n }\n\n if (key === SPREAD_NAME) {\n // If spread already exists, merge directly as array\n if (!normalized[SPREAD_NAME]) normalized[SPREAD_NAME] = [];\n (normalized[SPREAD_NAME] as unknown[]).push(value);\n continue;\n }\n\n normalized[key] = value;\n }\n\n if (classBuffer.length) normalized[CLASS_NAME] = classBuffer.join(' ').trim();\n if (styleBuffer.length) {\n const s = styleBuffer.map(str => (str.endsWith(';') ? str : `${str};`)).join('');\n normalized[STYLE_NAME] = s;\n }\n\n return normalized;\n}\n/**\n * Check if node is a map call expression\n * @param node - The node to check\n * @returns `true` if node is a map call expression, `false` otherwise\n */\nexport function isMapCall(node: t.Node): boolean {\n return (\n t.isCallExpression(node) &&\n t.isMemberExpression(node.callee) &&\n t.isIdentifier(node.callee.property) &&\n node.callee.property.name === 'map' &&\n node.arguments.length === 1\n );\n}\n\n/**\n * Create props object expression\n * @description Convert attribute record to AST object expression\n * @param {Record<string, unknown>} propsData - Attribute data\n * @param {Function} transformJSX - JSX conversion function\n * @return {t.ObjectExpression} Generated object expression\n */\nexport function createPropsObjectExpression(\n propsData: Record<string, unknown>,\n transformJSX: (path: NodePath<JSXElement>, tree: TreeNode) => t.Expression,\n): t.ObjectExpression {\n const objectProperties: (t.ObjectProperty | t.SpreadElement | t.ObjectMethod)[] = [];\n\n const propsToProcess = normalizeProps(propsData);\n\n for (const propName in propsToProcess) {\n const propValue = propsToProcess[propName];\n // Skip empty children\n if (propName === CHILDREN_NAME && (!propValue || (isArray(propValue) && !propValue.length))) {\n continue;\n }\n const astValue = convertValueToASTNode(propValue as any, transformJSX);\n\n // Process spread attribute\n if (propName === SPREAD_NAME) {\n objectProperties.push(t.spreadElement(astValue));\n } else {\n // Check if dynamic and not a function\n // if (isDynamicExpression(astValue) && !t.isFunction(astValue)) {\n // objectProperties.push(\n // t.objectMethod(\n // 'get',\n // t.identifier(propName),\n // [],\n // t.blockStatement([t.returnStatement(astValue)]),\n // ),\n // );\n // } else {\n objectProperties.push(t.objectProperty(t.stringLiteral(propName), astValue));\n // }\n }\n }\n\n return t.objectExpression(objectProperties);\n}\n\n/**\n * Convert JavaScript value to corresponding AST node\n * @description Convert value to corresponding AST expression node based on value type\n * @param {unknown} value - Value to convert\n * @param {Function} transformJSX - JSX conversion function\n * @return {t.Expression} Corresponding AST node\n */\nexport function convertValueToASTNode(\n value: JSXChild | TreeNode | Expression,\n transformJSX: (path: NodePath<JSXElement>, tree: TreeNode) => t.Expression,\n): Expression {\n // If it's already an AST node, return directly\n if (t.isExpression(value as Expression)) {\n return value as Expression;\n }\n\n if (isArray(value)) {\n return t.arrayExpression(value.map(item => convertValueToASTNode(item, transformJSX)));\n }\n\n if (isObject(value)) {\n if (isTreeNode(value) && hasPureStringChildren(value)) {\n const stringContent = extractStringChildren(value);\n return t.stringLiteral(stringContent);\n }\n\n if (\n value.type === NODE_TYPE.COMPONENT ||\n value.type === NODE_TYPE.NORMAL ||\n value.type === NODE_TYPE.TEXT ||\n value.type === NODE_TYPE.SVG\n ) {\n const { path } = getContext();\n return transformJSX(path, value);\n }\n\n if (\n value.type === NODE_TYPE.EXPRESSION &&\n value.children &&\n isArray(value.children) &&\n value.children.length > 0\n ) {\n return convertValueToASTNode(value.children[0] as JSXChild, transformJSX);\n }\n\n if (\n t.isJSXElement(value as unknown as JSXElement) ||\n t.isJSXFragment(value as unknown as JSXElement)\n ) {\n const { path } = getContext();\n const mockNodePath = {\n node: value,\n parentPath: path, // Keep parent path reference\n scope: path.scope, // Keep scope reference\n } as unknown as NodePath<JSXElement>;\n const tree = createTree(mockNodePath);\n return transformJSX(path, tree);\n }\n\n return createPropsObjectExpression(value, transformJSX);\n }\n if (isString(value)) {\n return t.stringLiteral(value);\n }\n if (isNumber(value)) {\n return t.numericLiteral(value);\n }\n if (isBoolean(value)) {\n return t.booleanLiteral(value);\n }\n if (isUndefined(value)) {\n return t.identifier('undefined');\n }\n if (isNull(value)) {\n return t.nullLiteral();\n }\n\n return value as Expression;\n}\n/**\n * Get the setting function corresponding to the attribute\n */\nexport function getSetFunctionForAttribute(attrName?: string): {\n name: string;\n value: t.Identifier;\n} {\n const { state } = getContext();\n switch (attrName) {\n case CLASS_NAME:\n return {\n name: 'patchClass',\n value: state.imports.patchClass,\n };\n case STYLE_NAME:\n return { name: 'patchStyle', value: state.imports.patchStyle };\n default:\n return { name: 'patchAttr', value: state.imports.patchAttr };\n }\n}\n\n/**\n * Determine if an AST node should be considered dynamic for attribute evaluation.\n * Covers common JS expression types beyond Identifier, including member/call/conditional/template, etc.\n */\nexport function isDynamicExpression(node: t.Node | null | undefined): boolean {\n if (!node) return false;\n\n // Direct expression types that are dynamic\n if (\n t.isIdentifier(node) ||\n t.isMemberExpression(node) ||\n t.isOptionalMemberExpression(node) ||\n t.isCallExpression(node) ||\n t.isOptionalCallExpression(node) ||\n t.isConditionalExpression(node) ||\n t.isLogicalExpression(node) ||\n t.isTemplateLiteral(node) ||\n t.isTaggedTemplateExpression(node) ||\n t.isBinaryExpression(node) ||\n t.isUnaryExpression(node) ||\n t.isUpdateExpression(node) ||\n t.isAwaitExpression(node) ||\n t.isYieldExpression(node) ||\n t.isAssignmentExpression(node) ||\n t.isSequenceExpression(node) ||\n t.isArrowFunctionExpression(node) ||\n t.isFunctionExpression(node)\n ) {\n return true;\n }\n\n // Object/Array: deep check\n if (t.isObjectExpression(node)) {\n return deepCheckObjectDynamic(node);\n }\n if (t.isArrayExpression(node)) {\n return node.elements.some(el => el != null && t.isNode(el) && isDynamicExpression(el));\n }\n\n // Literals/null are static\n if (\n t.isStringLiteral(node) ||\n t.isNumericLiteral(node) ||\n t.isBooleanLiteral(node) ||\n t.isNullLiteral(node) ||\n t.isRegExpLiteral(node)\n ) {\n return false;\n }\n\n // Fallback: if it is some other Expression, treat as dynamic; otherwise static\n return t.isExpression(node);\n}\n\n/**\n * Detect if all children are static strings and can be output directly\n *\n * @param node - TreeNode to check\n * @returns true if all children are static strings\n */\nexport function hasPureStringChildren(node: TreeNode): boolean {\n if (!node.children || node.children.length === 0) {\n return false;\n }\n\n return node.children.every(child => {\n if (isString(child)) {\n return true;\n }\n if (isTreeNode(child) && child.type === NODE_TYPE.TEXT) {\n return true;\n }\n return false;\n });\n}\n\n/**\n * Concatenates all string children into a single string\n *\n * @param node - TreeNode with string children\n * @returns Concatenated string\n */\nexport function extractStringChildren(node: TreeNode): string {\n if (!node.children || node.children.length === 0) {\n return '';\n }\n\n return node.children\n .map(child => {\n if (isString(child)) {\n return child;\n }\n if (isTreeNode(child) && child.type === NODE_TYPE.TEXT && child.children) {\n return child.children.join('');\n }\n return '';\n })\n .join('');\n}\n","import { type NodePath, types as t } from '@babel/core';\nimport { isSVGTag, isSelfClosingTag, warn } from '@estjs/shared';\nimport { BIND_REG, NODE_TYPE, SPREAD_NAME, UPDATE_PREFIX } from './constants';\nimport { getAttrName, getTagName, isComponentName, optimizeChildNodes, textTrim } from './shared';\nimport type { JSXChild, JSXElement } from '../types';\n\n/**\n * TreeNode represents a unified abstraction of JSX elements in the compilation process.\n * It serves as the core intermediate representation between JSX AST and generated runtime code.\n *\n * @interface TreeNode\n *\n * @property {NODE_TYPE} type - The type of the node (NORMAL, TEXT, EXPRESSION, COMPONENT, FRAGMENT, SVG, COMMENT, SPREAD)\n * @property {string} [tag] - The tag name for HTML elements or component name for components\n * @property {number} index - Unique sequential index for DOM node location (starts from 1, skips components/expressions)\n * @property {number | null} [parentIndex] - Index of the parent node, used to establish parent-child relationships\n * @property {Record<string, unknown>} [props] - Collection of element attributes and properties\n * @property {Array<TreeNode | JSXChild | string | t.Expression>} children - Child nodes of this element\n * @property {boolean} [root] - Whether this is the root node of the tree\n * @property {boolean} [isLastChild] - Whether this is the last child of its parent\n * @property {boolean} [selfClosing] - Whether this is a self-closing tag (e.g., <img />, <br />)\n * @property {true} [_isTreeNode] - Internal marker to identify TreeNode objects (used by isTreeNode type guard)\n *\n * @example\n * ```typescript\n * // Example TreeNode for: <div class=\"container\">Hello</div>\n * {\n * type: NODE_TYPE.NORMAL,\n * tag: 'div',\n * index: 1,\n * props: { class: 'container' },\n * children: [\n * {\n * type: NODE_TYPE.TEXT,\n * children: ['Hello'],\n * index: 2,\n * _isTreeNode: true\n * }\n * ],\n * root: true,\n * _isTreeNode: true\n * }\n * ```\n */\nexport interface TreeNode {\n /** The type of the node */\n type: NODE_TYPE;\n /** The tag name for HTML elements or component name */\n tag?: string;\n /** Unique sequential index for DOM node location */\n index: number;\n /** Index of the parent node */\n parentIndex?: number | null;\n /** Collection of element attributes and properties */\n props?: Record<string, unknown>;\n /** Child nodes of this element */\n children: (TreeNode | JSXChild | string | t.Expression)[];\n /** Whether this is the root node */\n root?: boolean;\n /** Whether this is the last child of its parent */\n isLastChild?: boolean;\n /** Whether this is a self-closing tag */\n selfClosing?: boolean;\n /** Internal marker to identify TreeNode objects */\n _isTreeNode?: true;\n}\n/**\n * Creates a default TreeNode structure with initial configuration.\n *\n * This factory function provides a consistent base template for all tree nodes,\n * ensuring uniform structure and default values across the tree building process.\n *\n * @returns {TreeNode} A new TreeNode with default configuration:\n * - `root: true` - Marked as root node\n * - `type: NODE_TYPE.NORMAL` - Default to normal HTML element\n * - `tag: ''` - Empty tag name (to be filled by caller)\n * - `props: {}` - Empty properties object\n * - `children: []` - Empty children array\n * - `index: 1` - Default index (root nodes start at 1)\n * - `parentIndex: null` - No parent for root nodes\n * - `isLastChild: false` - Not marked as last child initially\n * - `selfClosing: false` - Not self-closing by default\n * - `_isTreeNode: true` - Internal marker for type checking\n *\n * @example\n * ```typescript\n * const node = createDefaultTree();\n * node.tag = 'div';\n * node.type = NODE_TYPE.NORMAL;\n * // node is now ready to be populated with actual data\n * ```\n *\n * @internal\n */\nexport function createDefaultTree(): TreeNode {\n return {\n root: true,\n type: NODE_TYPE.NORMAL,\n tag: '',\n props: {},\n children: [],\n index: 1,\n parentIndex: null,\n isLastChild: false,\n selfClosing: false,\n _isTreeNode: true,\n };\n}\n\n/**\n * Type guard to check if an unknown value is a TreeNode.\n *\n * This function provides runtime type checking for TreeNode objects by checking\n * for the presence of the internal `_isTreeNode` marker. This is more reliable\n * than checking for specific properties since TreeNode has many optional fields.\n *\n * @param {unknown} node - The value to check\n * @returns {boolean} `true` if the value is a TreeNode, `false` otherwise\n *\n * @example\n * ```typescript\n * const maybeNode: unknown = getSomeValue();\n * if (isTreeNode(maybeNode)) {\n * // TypeScript now knows maybeNode is TreeNode\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Filtering TreeNodes from mixed array\n * const mixed: Array<TreeNode | string | Expression> = [...];\n * const treeNodes = mixed.filter(isTreeNode);\n * // treeNodes is now TreeNode[]\n * ```\n */\nexport function isTreeNode(node: unknown): node is TreeNode {\n return !!(node && (node as TreeNode)._isTreeNode);\n}\n/**\n * Global tree node index counter.\n *\n * This counter is used to assign unique sequential indices to tree nodes for efficient\n * DOM node location and manipulation at runtime. The index system is crucial for the\n * `mapNodes()` runtime function to quickly locate specific DOM elements.\n *\n * **Index Assignment Rules:**\n * - Root node starts at index 1\n * - Each non-component, non-expression node gets an incremental index (2, 3, 4, ...)\n * - Component nodes do NOT get indices (they don't correspond to DOM elements)\n * - Fragment nodes do NOT get indices (they're virtual containers)\n * - Expression nodes do NOT get indices (they're dynamic content placeholders)\n *\n * **Index Usage:**\n * The indices are used to generate an `indexMap` array that maps logical positions\n * to actual DOM nodes, enabling O(1) node lookup at runtime.\n *\n * @example\n * ```typescript\n * // JSX: <div><span/>{expr}<p/></div>\n * // Indices: div=1, span=2, expr=2 (no increment), p=3\n * // indexMap: [1, 2, 3] -> [divNode, spanNode, pNode]\n * ```\n *\n * @internal\n */\nlet treeIndex = 1;\n\n/**\n * Creates a TreeNode from a JSX AST node path.\n *\n * This is the main entry point for building the Tree intermediate representation.\n * It recursively processes JSX elements and their children, assigning indices and\n * building the complete tree structure.\n *\n * **Processing Flow:**\n * 1. Create default tree node structure\n * 2. Assign index based on node type and parent context\n * 3. Determine node type (text, element, component, etc.)\n * 4. Process attributes and children recursively\n * 5. Return completed TreeNode\n *\n * **Index Assignment:**\n * - Root nodes: Reset counter to 1 and use it\n * - Child nodes: Increment counter for non-component/non-expression nodes\n * - Components/Fragments: Skip index increment (don't correspond to DOM)\n *\n * @param {NodePath<JSXElement>} path - Babel AST path to the JSX element\n * @param {TreeNode} [parentNode] - Parent TreeNode (undefined for root nodes)\n * @returns {TreeNode} The constructed TreeNode with all children processed\n *\n * @example\n * ```typescript\n * // Building a tree from JSX\n * const jsxPath = getJSXPath(); // from Babel visitor\n * const tree = createTree(jsxPath);\n * // tree now contains the complete TreeNode structure\n * ```\n *\n * @example\n * ```typescript\n * // Recursive child processing\n * const parentTree = createTree(parentPath);\n * const childTree = createTree(childPath, parentTree);\n * // childTree.parentIndex === parentTree.index\n * ```\n */\nexport function createTree(path: NodePath<JSXElement>, parentNode?: TreeNode): TreeNode {\n const treeNode = createDefaultTree();\n const tagName = getTagName(path.node);\n\n treeNode.tag = tagName;\n treeNode.type = determineNodeType(tagName);\n treeNode.selfClosing = isSelfClosingTag(tagName);\n if (parentNode) {\n const parentIsComponent = parentNode.type === NODE_TYPE.COMPONENT;\n if (parentIsComponent) {\n treeIndex = 1;\n treeNode.index = treeIndex;\n } else if (treeNode.type !== NODE_TYPE.COMPONENT) {\n treeNode.index = ++treeIndex;\n }\n\n treeNode.parentIndex = treeIndex;\n } else {\n // Root node processing: mark as root node and reset counter\n treeNode.root = true;\n treeIndex = 1;\n }\n\n // Handle text node\n if (t.isJSXText(path.node)) {\n return processJSXText(path as unknown as NodePath<t.JSXText>, treeNode);\n }\n\n // Handle JSX (including fragment)\n if (t.isJSXElement(path.node) || t.isJSXFragment(path.node)) {\n return processJSXElement(path as NodePath<JSXElement>, treeNode);\n }\n\n return treeNode;\n}\n\n/**\n * Processes a JSX element node and populates the TreeNode with element-specific data.\n *\n * This function handles the core transformation of JSX elements into TreeNode structure,\n * including tag name extraction, type determination, attribute processing, and recursive\n * child processing.\n *\n * **Processing Steps:**\n * 1. Extract tag name from JSX element\n * 2. Determine node type (NORMAL, COMPONENT, FRAGMENT, SVG)\n * 3. Check if element is self-closing\n * 4. Process all attributes and properties\n * 5. Recursively process children (if not self-closing)\n *\n * @param {NodePath<JSXElement>} path - Babel AST path to the JSX element\n * @param {TreeNode} treeNode - The TreeNode to populate with element data\n * @returns {TreeNode} The populated TreeNode with all element data\n *\n * @example\n * ```typescript\n * // Processing: <div class=\"container\"><span>Hello</span></div>\n * const node = createDefaultTree();\n * processJSXElement(path, node);\n * // node.tag === 'div'\n * // node.type === NODE_TYPE.NORMAL\n * // node.props === { class: 'container' }\n * // node.children.length === 1\n * ```\n *\n * @internal\n */\nfunction processJSXElement(path: NodePath<JSXElement>, treeNode: TreeNode): TreeNode {\n // Process JSX attributes and properties,fragment not have props\n if (!path.isJSXFragment()) {\n treeNode.props = processProps(path);\n }\n\n // Self-closing tags don't need to process children\n if (!treeNode.selfClosing) {\n // Process child elements recursively\n processChildren(path, treeNode);\n }\n\n return treeNode;\n}\n\n/**\n * Processes JSX attributes and converts them into a props object.\n *\n * This function handles all types of JSX attributes including:\n * - Boolean attributes: `<div disabled />` → `{ disabled: true }`\n * - String literals: `<div class=\"foo\" />` → `{ class: 'foo' }`\n * - Expression containers: `<div class={expr} />` → `{ class: expr }`\n * - JSX elements as props: `<div icon={<Icon />} />` → `{ icon: <Icon /> }`\n * - Spread attributes: `<div {...props} />` → `{ [SPREAD_NAME]: props }`\n * - Bind attributes: `<input bind:value={val} />` → `{ 'update:value': [val, setter] }`\n *\n * **Attribute Processing Rules:**\n * - Boolean attributes (no value) are set to `true`\n * - String/number literals are extracted as primitive values\n * - Expressions are stored as AST nodes for later code generation\n * - Spread attributes are stored under the special `SPREAD_NAME` key\n * - Bind attributes are transformed into update handlers\n *\n * @param {NodePath<JSXElement>} path - Babel AST path to the JSX element\n * @returns {Record<string, unknown>} Object mapping attribute names to their values\n *\n * @example\n * ```typescript\n * // <div class=\"container\" id={dynamicId} disabled />\n * const props = processProps(path);\n * // props = {\n * // class: 'container',\n * // id: <Identifier: dynamicId>,\n * // disabled: true\n * // }\n * ```\n *\n * @internal\n */\nfunction processProps(path: NodePath<JSXElement>): Record<string, unknown> {\n const props = {};\n const attributes = path.get('openingElement.attributes') as NodePath<\n t.JSXAttribute | t.JSXSpreadAttribute\n >[];\n\n if (!attributes.length) {\n return props;\n }\n\n attributes.forEach(attribute => {\n if (t.isJSXAttribute(attribute.node)) {\n const name = getAttrName(attribute.node);\n const value = attribute.get('value');\n\n // Boolean attribute: <div a>\n if (!value.node) {\n props[name] = true;\n } else if (value) {\n // Expression container: <div a={expr}>\n if (value.isJSXExpressionContainer()) {\n const expression = value.get('expression');\n // Literal values: <div a={1}>\n if (expression.isStringLiteral() || expression.isNumericLiteral()) {\n props[name] = expression.node.value;\n // JSX as prop: <div a={<div />}>\n } else if (expression.isJSXElement() || expression.isJSXFragment()) {\n props[name] = expression.node;\n // Other expressions: <div a={variable}>\n } else if (expression.isExpression()) {\n processPropsExpression(expression, name, props, path);\n }\n // Direct literal: <div a=\"value\">\n } else if (value.isStringLiteral() || value.isNumericLiteral()) {\n props[name] = value.node.value;\n // Direct JSX: <div a=<div />>\n } else if (value.isJSXElement() || value.isJSXFragment()) {\n props[name] = value.node;\n // Direct expression\n } else if (value.isExpression()) {\n processPropsExpression(value, name, props, path);\n }\n }\n } else if (t.isJSXSpreadAttribute(attribute.node)) {\n // Spread attribute: <div {...props}>\n props[SPREAD_NAME] = attribute.get('argument').node;\n }\n });\n\n return props;\n}\n\n/**\n * Processes a JSX attribute expression and stores it in the props object.\n *\n * This function handles special attribute types like `bind:` directives and\n * regular dynamic attributes. It determines the appropriate processing based\n * on the attribute name pattern.\n *\n * **Attribute Types:**\n * - `bind:xxx` attributes: Two-way binding directives (e.g., `bind:value`)\n * - Regular attributes: Event handlers, refs, keys, and other dynamic props\n *\n * @param {NodePath<t.Expression>} expression - The attribute value expression\n * @param {string} name - The attribute name\n * @param {Record<string, unknown>} props - The props object to populate\n * @param {NodePath<JSXElement>} path - The JSX element path (for scope access)\n *\n * @example\n * ```typescript\n * // <input bind:value={inputValue} />\n * processPropsExpression(valueExpr, 'bind:value', props, path);\n * // props['update:value'] = [inputValue, (value) => inputValue = value]\n * ```\n *\n * @internal\n */\nfunction processPropsExpression(\n expression: NodePath<t.Expression>,\n name: string,\n props: Record<string, unknown>,\n path: NodePath<JSXElement>,\n): void {\n if (BIND_REG.test(name)) {\n processPropsBind(name, expression, props, path);\n } else {\n // Normal attribute: key/ref/on*/className/etc.\n props[name] = expression.node;\n }\n}\n\n/**\n * Processes a `bind:` directive and converts it into an update handler.\n *\n * Two-way binding directives like `bind:value={variable}` are transformed into\n * a tuple containing:\n * 1. The bound expression (for reading the value)\n * 2. A setter function (for updating the value)\n *\n * This enables bidirectional data flow between the DOM and the reactive state.\n *\n * **Transformation:**\n * ```\n * bind:value={inputValue}\n * ↓\n * update:value = [\n * inputValue, // getter\n * (value) => inputValue = value // setter\n * ]\n * ```\n *\n * @param {string} name - The bind attribute name (e.g., 'bind:value')\n * @param {NodePath<t.Expression>} expression - The bound variable expression\n * @param {Record<string, unknown>} props - The props object to populate\n * @param {NodePath<JSXElement>} path - The JSX element path (for scope access)\n *\n * @example\n * ```typescript\n * // <input bind:value={inputValue} />\n * processPropsBind('bind:value', valueExpr, props, path);\n * // props['update:value'] = [\n * // <Identifier: inputValue>,\n * // (value) => inputValue = value\n * // ]\n * ```\n *\n * @internal\n */\nfunction processPropsBind(\n name: string,\n expression: NodePath<t.Expression>,\n props: Record<string, unknown>,\n path: NodePath<JSXElement>,\n): void {\n const value = path.scope.generateUidIdentifier('value');\n const bindName = name.slice(5).toLowerCase(); // Remove 'bind:' prefix\n\n // Create update handler: [getter, setter]\n props[`${UPDATE_PREFIX}:${bindName}`] = [\n expression.node, // Getter: the bound variable\n t.arrowFunctionExpression(\n [value],\n // Type guard: expression.node must be LVal for bind directive\n t.isLVal(expression.node)\n ? t.assignmentExpression('=', expression.node, value) // Setter: variable = value\n : t.assignmentExpression('=', t.identifier('_'), value), // Fallback for invalid LVal\n ),\n ];\n}\n\n/**\n * Process all child nodes of JSX element\n *\n * @param {NodePath<JSXElement>} path - AST path of JSX element node\n * @param {TreeNode} treeNode - Tree node object of parent node\n */\nfunction processChildren(path: NodePath<JSXElement>, treeNode: TreeNode): void {\n const children = path.node.children as JSXChild[];\n // Boundary check: check if child nodes exist\n if (!children || !children.length) {\n return;\n }\n const optimizedChildren = optimizeChildNodes(path.get('children'));\n\n optimizedChildren.forEach(child => {\n processChild(child, treeNode, optimizedChildren.length === 1);\n });\n}\n\nfunction processChild(child: NodePath<JSXChild>, treeNode: TreeNode, isLastChild: boolean): void {\n // jsx\n if (t.isJSXElement(child.node) || t.isJSXFragment(child.node)) {\n const childNode = createTree(child as NodePath<JSXElement>, treeNode);\n childNode.isLastChild = isLastChild;\n treeNode.children.push(childNode);\n return;\n }\n // expression\n if (t.isJSXExpressionContainer(child.node)) {\n processChildExpressionContainer(\n child as NodePath<t.JSXExpressionContainer>,\n treeNode,\n isLastChild,\n );\n return;\n }\n // text\n if (t.isJSXText(child.node)) {\n processJSXChildText(child as NodePath<t.JSXText>, treeNode, isLastChild);\n return;\n }\n // spread\n if (t.isJSXSpreadChild(child.node)) {\n processChildSpread(child as NodePath<t.JSXSpreadChild>, treeNode, isLastChild);\n return;\n }\n}\n\nfunction processChildExpressionContainer(\n child: NodePath<t.JSXExpressionContainer>,\n treeNode: TreeNode,\n isLastChild: boolean,\n): void {\n const expression = child.get('expression');\n // string literal or numeric literal\n if (expression.isStringLiteral() || expression.isNumericLiteral()) {\n treeNode.children.push({\n type: NODE_TYPE.TEXT,\n children: [String(expression.node.value)],\n index: ++treeIndex, // Static text increments index\n parentIndex: treeNode.index,\n isLastChild,\n _isTreeNode: true,\n });\n }\n // jsx element or jsx fragment\n else if (expression.isJSXElement() || expression.isJSXFragment()) {\n const childNode = createTree(child as unknown as NodePath<JSXElement>, treeNode);\n childNode.isLastChild = isLastChild;\n treeNode.children.push(childNode);\n }\n // expression\n else if (expression.isExpression()) {\n treeNode.children.push({\n type: NODE_TYPE.EXPRESSION,\n index: treeIndex, // Expression doesn't update index because it's dynamic content\n isLastChild,\n // Type guard: expression.node is Expression in JSXExpressionContainer\n children: t.isExpression(expression.node) ? [expression.node] : [],\n parentIndex: treeNode.index,\n _isTreeNode: true,\n });\n }\n}\n/**\n * Determine whether to insert comment separator\n *\n * @param {number} childrenLength - Current number of child nodes\n * @param {TreeNode | undefined} previousNode - Previous child node\n * @returns {boolean} Whether to insert comment separator\n */\nfunction shouldInsertComment(childrenLength: number, previousNode: TreeNode | undefined): boolean {\n return !!(\n childrenLength >= 2 && // At least two child nodes\n previousNode && // Previous node exists\n previousNode.type !== NODE_TYPE.COMMENT && // Previous node is not a comment\n // Previous node is dynamic content\n (previousNode.type === NODE_TYPE.EXPRESSION || previousNode.type === NODE_TYPE.COMPONENT)\n );\n}\n\nfunction processJSXChildText(\n child: NodePath<t.JSXText>,\n treeNode: TreeNode,\n isLastChild: boolean,\n): void {\n const text = textTrim(child.node);\n\n // Ignore empty text nodes\n if (!text) {\n return;\n }\n\n const childrenLength = treeNode.children.length;\n const previousNode = treeNode.children[childrenLength - 1] as TreeNode | undefined;\n\n // Check if comment node needs to be inserted as separator\n if (shouldInsertComment(childrenLength, previousNode)) {\n const commentNode: TreeNode = {\n type: NODE_TYPE.COMMENT,\n children: [],\n index: ++treeIndex,\n _isTreeNode: true,\n };\n treeNode.children.push(commentNode);\n }\n\n // Create text node\n const textNode: TreeNode = {\n type: NODE_TYPE.TEXT,\n children: [text],\n index: ++treeIndex,\n isLastChild,\n _isTreeNode: true,\n };\n treeNode.children.push(textNode);\n}\n/**\n * Handle as array children\n * @param child\n * @param treeNode\n * @param isLastChild\n */\nfunction processChildSpread(\n child: NodePath<JSXChild>,\n treeNode: TreeNode,\n isLastChild: boolean,\n): void {\n const spreadExpression = child.get('expression');\n\n treeNode.children.push({\n type: NODE_TYPE.SPREAD,\n // Type guard: spreadExpression.node is Expression in JSXSpreadChild\n children: t.isExpression(spreadExpression.node) ? [spreadExpression.node] : [],\n index: treeIndex, // Note: doesn't increment here because this is dynamic content\n parentIndex: treeNode.index,\n isLastChild,\n _isTreeNode: true,\n });\n}\n\n/**\n * Determine JSX node type\n *\n * Type judgment priority (high to low):\n * 1. **COMPONENT**: Custom component (first letter capitalized or contains dot)\n * 3. **SVG**: SVG-related tags (svg, path, circle, etc.)\n * 4. **NORMAL**: Regular HTML elements (div, span, p, etc.)\n *\n * @param {NodePath<JSXElement>} path - JSX element path\n * @param {string} tagName - Tag name\n * @returns {NODE_TYPE} Node type enum value\n */\nfunction determineNodeType(tagName: string): NODE_TYPE {\n const isComponent = isComponentName(tagName);\n\n if (isComponent) {\n return NODE_TYPE.COMPONENT;\n }\n\n if (isSVGTag(tagName)) {\n return NODE_TYPE.SVG;\n }\n\n return NODE_TYPE.NORMAL;\n}\n\n/**\n * Process JSX text node and populate tree node information\n *\n * This function converts text content in JSX to tree node structure. It handles\n * text cleaning and normalization, ensuring the final generated HTML has no\n * excess whitespace and line breaks.\n *\n * Text processing logic:\n * 1. **Whitespace handling**: Use textTrim function to clean excess whitespace\n * 2. **Empty content check**: Empty text won't create child nodes\n * 3. **Type marking**: Set node type to TEXT\n * 4. **Content storage**: Store cleaned text in children array\n *\n * @param {NodePath<t.JSXText>} path - AST path of JSX text node\n * @param {TreeNode} treeNode - Tree node object to be populated\n * @returns {TreeNode} Completed tree node object\n *\n * @example\n * ```typescript\n * // JSX: <div> Hello World </div>\n * // After processing: node.children = ['Hello World']\n *\n * // JSX: <div> </div>\n * // After processing: node.children = [] (empty array)\n * ```\n */\nfunction processJSXText(path: NodePath<t.JSXText>, treeNode: TreeNode): TreeNode {\n treeNode.type = NODE_TYPE.TEXT;\n\n try {\n const textValue = textTrim(path.node);\n // Only create child nodes when valid text exists\n treeNode.children = textValue ? [textValue] : [];\n } catch (error) {\n // Error handling when text processing fails\n warn(`Text node processing failed: ${error}`);\n treeNode.children = [];\n }\n\n return treeNode;\n}\n","import { type NodePath, types as t } from '@babel/core';\nimport { isObject, isPrimitive, isString, isSymbol } from '@estjs/shared';\nimport { addImport, importMap } from '../import';\nimport { EVENT_ATTR_NAME, FRAGMENT_NAME, NODE_TYPE, UPDATE_PREFIX } from './constants';\nimport { getContext } from './context';\nimport { createPropsObjectExpression } from './shared';\nimport { type TreeNode, isTreeNode } from './tree';\nimport type { JSXElement } from '../types';\n\n/**\n * SSG Processing Result Interface\n * @description Stores template and dynamic content information in SSG mode\n */\nexport interface transformResult {\n /** Template string array */\n templates: string[];\n /** Dynamic content array */\n dynamics: Array<{\n /** Content type: text or attribute */\n type: 'text' | 'attr';\n /** Expression node */\n node: t.Expression;\n /** Attribute name (only for attr type) */\n attrName?: string;\n }>;\n}\n\nexport function transformJSXToSSG(path: NodePath<JSXElement>, treeNode: TreeNode) {\n const { state } = getContext();\n\n const result = transformTemplate(treeNode);\n const { templates, dynamics } = result;\n\n // Handle root component case\n if (treeNode.type === NODE_TYPE.COMPONENT || treeNode.type === NODE_TYPE.FRAGMENT) {\n const componentProps = { ...treeNode.props, children: treeNode.children };\n\n addImport(importMap.createComponent);\n return t.callExpression(state.imports.createComponent, [\n t.identifier(treeNode.tag as string),\n createPropsObjectExpression(componentProps, transformJSXToSSG),\n ]);\n }\n\n // Create render arguments\n const args: t.Expression[] = [];\n\n // Add template if exists\n if (templates && templates.length > 0) {\n addImport(importMap.template);\n const tmplId = path.scope.generateUidIdentifier('_tmpl$');\n\n // create template string array expression\n const templateNode = t.arrayExpression(templates.map(str => t.stringLiteral(str)));\n state.declarations.push(t.variableDeclarator(tmplId, templateNode));\n\n args.push(tmplId);\n }\n\n // Create render call parameters\n args.push(t.callExpression(state.imports.getHydrationKey, []));\n // Add necessary imports\n addImport(importMap.render);\n addImport(importMap.getHydrationKey);\n\n // Attributes should be placed before text content\n const textDynamics = dynamics.filter(d => d.type === 'text');\n const attrDynamics = dynamics.filter(d => d.type === 'attr');\n\n // Add attribute dynamic content\n attrDynamics.forEach(dynamic => {\n args.push(dynamic.node);\n });\n\n // Add text dynamic content\n textDynamics.forEach(dynamic => {\n args.push(dynamic.node);\n });\n\n // Create render call\n return t.callExpression(state.imports.render, args);\n}\n\nfunction transformTemplate(treeNode: TreeNode) {\n const result: transformResult = {\n templates: [],\n dynamics: [],\n };\n\n // Recursively process nodes\n walkTreeNode(treeNode, result);\n\n return result;\n}\n\nfunction walkTreeNode(treeNode: TreeNode, result: transformResult) {\n if (!treeNode) {\n return;\n }\n\n switch (treeNode.type) {\n case NODE_TYPE.COMPONENT:\n case NODE_TYPE.FRAGMENT:\n handleComponent(treeNode, result);\n break;\n\n case NODE_TYPE.EXPRESSION:\n handleExpression(treeNode, result);\n break;\n\n case NODE_TYPE.TEXT:\n handleText(treeNode, result);\n break;\n\n case NODE_TYPE.NORMAL:\n case NODE_TYPE.SVG:\n handleElement(treeNode, result);\n break;\n\n case NODE_TYPE.COMMENT:\n addTemplate(result, '<!>', true);\n break;\n\n default:\n // Handle unknown node types gracefully\n if (treeNode.children && treeNode.children.length > 0) {\n processChildren(treeNode.children as TreeNode[], result);\n }\n break;\n }\n}\n/**\n * Add content to template\n */\nexport const addTemplate = (\n result: transformResult,\n content: string,\n join: boolean = false,\n): void => {\n if (result.templates.length === 0) {\n result.templates.push(content);\n } else {\n if (join) {\n result.templates[result.templates.length - 1] += content;\n } else {\n result.templates.push(content);\n }\n }\n};\n/**\n * Handle component for SSG\n */\nconst handleComponent = (node: TreeNode, result: transformResult): void => {\n // Add placeholder for component\n result.templates.push('');\n\n const { state } = getContext();\n\n // Create component props\n const componentProps = { ...node.props };\n if (node.children.length) {\n componentProps.children = node.children;\n }\n\n addImport(importMap.createComponent);\n\n // Create component expression\n const componentExpr = t.callExpression(state.imports.createComponent, [\n t.identifier(node.tag as string),\n createPropsObjectExpression(componentProps, transformJSXToSSG),\n ]);\n\n // Add to dynamic content\n result.dynamics.push({\n type: 'text',\n node: componentExpr,\n });\n};\n\n/**\n * Handle expression for SSG\n */\nconst handleExpression = (node: TreeNode, result: transformResult): void => {\n if (!node.children || node.children.length === 0) {\n return;\n }\n\n const firstChild = node.children[0];\n\n // Break template at expression location\n result.templates.push('');\n\n // Process various types of expressions\n if (isPrimitive(firstChild)) {\n // Primitive value processing\n const { state } = getContext();\n addImport(importMap.escapeHTML);\n\n result.dynamics.push({\n type: 'text',\n node: t.callExpression(state.imports.escapeHTML, [t.valueToNode(firstChild)]),\n });\n // TODO: need fix type\n } else if (isObject(firstChild)) {\n // AST expression node processing\n const exprNode = firstChild as t.Expression;\n\n // Process special case for map function calls\n if (\n t.isCallExpression(exprNode) &&\n t.isMemberExpression(exprNode.callee) &&\n exprNode.arguments.length > 0\n ) {\n const mapCallback = exprNode.arguments[0];\n\n if (\n (t.isArrowFunctionExpression(mapCallback) || t.isFunctionExpression(mapCallback)) &&\n mapCallback.body\n ) {\n // Check if it returns JSX element\n let jsxElement: t.JSXElement | undefined = undefined;\n\n if (t.isJSXElement(mapCallback.body)) {\n jsxElement = mapCallback.body;\n } else if (t.isBlockStatement(mapCallback.body)) {\n const returnStmt = mapCallback.body.body.find(stmt => t.isReturnStatement(stmt));\n if (\n returnStmt &&\n t.isReturnStatement(returnStmt) &&\n returnStmt.argument &&\n t.isJSXElement(returnStmt.argument)\n ) {\n jsxElement = returnStmt.argument;\n }\n } else if (\n t.isParenthesizedExpression(mapCallback.body) &&\n t.isJSXElement(mapCallback.body.expression)\n ) {\n jsxElement = mapCallback.body.expression;\n }\n\n // Process JSX element\n if (jsxElement) {\n const { state } = getContext();\n const tagName =\n jsxElement.openingElement.name.type === 'JSXIdentifier'\n ? jsxElement.openingElement.name.name\n : '';\n\n // Extract props\n const props: Record<string, any> = {};\n jsxElement.openingElement.attributes.forEach(attr => {\n if (t.isJSXAttribute(attr)) {\n const name = attr.name.name as string;\n if (t.isJSXExpressionContainer(attr.value)) {\n props[name] = attr.value.expression;\n } else if (t.isStringLiteral(attr.value)) {\n props[name] = attr.value.value;\n } else if (attr.value === null) {\n props[name] = true;\n }\n } else if (t.isJSXSpreadAttribute(attr)) {\n props._$spread$ = attr.argument;\n }\n });\n\n if (tagName === FRAGMENT_NAME) {\n addImport(importMap.Fragment);\n const newCallback = t.arrowFunctionExpression(\n mapCallback.params,\n t.callExpression(state.imports.Fragment, [\n createPropsObjectExpression(props, transformJSXToSSG),\n ]),\n );\n exprNode.arguments[0] = newCallback;\n } else if (tagName && tagName[0] === tagName[0].toUpperCase()) {\n addImport(importMap.createComponent);\n const newCallback = t.arrowFunctionExpression(\n mapCallback.params,\n t.callExpression(state.imports.createComponent, [\n t.identifier(tagName),\n createPropsObjectExpression(props, transformJSXToSSG),\n ]),\n );\n exprNode.arguments[0] = newCallback;\n }\n }\n }\n }\n\n // Add to dynamic content\n result.dynamics.push({\n type: 'text',\n node: exprNode,\n });\n }\n};\n\n/**\n * Handle text for SSG\n */\nconst handleText = (node: TreeNode, result: transformResult): void => {\n if (node.children && node.children.length > 0) {\n addTemplate(result, node.children.join(''), true);\n }\n};\n\n/**\n * Handle element for SSG\n */\nconst handleElement = (node: TreeNode, result: transformResult): void => {\n // Build start tag\n let openTag = `<${node.tag} data-idx=\"${node.index}\"`;\n\n // Process attributes\n const { staticAttrs, dynamicAttrs } = processAttributes(node.props || {});\n openTag += staticAttrs;\n\n addTemplate(result, openTag, true);\n addTemplate(result, node.selfClosing ? '/>' : '>', dynamicAttrs.length === 0);\n\n // Process children\n if (!node.selfClosing && node.children && node.children.length > 0) {\n processChildren(node.children as TreeNode[], result);\n }\n\n // Add end tag\n if (!node.selfClosing) {\n addTemplate(result, `</${node.tag}>`, true);\n }\n\n // Process dynamic attributes\n processDynamicAttributes(dynamicAttrs, result);\n};\n\n/**\n * Process children for SSG\n */\nconst processChildren = (children: (TreeNode | string)[], result: transformResult): void => {\n children.forEach(child => {\n if (isTreeNode(child)) {\n walkTreeNode(child, result);\n } else if (isString(child)) {\n addTemplate(result, child, true);\n }\n });\n};\n/**\n * Process SSG attributes\n */\nexport function processAttributes(props: Record<string, any>): {\n staticAttrs: string;\n dynamicAttrs: Array<{ name: string; value: t.Expression }>;\n} {\n let staticAttrs = '';\n const dynamicAttrs: Array<{ name: string; value: t.Expression }> = [];\n\n for (const [prop, value] of Object.entries(props)) {\n // Skip event handlers and update functions\n if (prop.startsWith(EVENT_ATTR_NAME) || prop.startsWith(UPDATE_PREFIX)) {\n continue;\n }\n\n // Process static attributes\n if (isPrimitive(value)) {\n if (value === true) {\n staticAttrs += ` ${prop}`;\n } else if (isSymbol(value)) {\n staticAttrs += ` ${prop}=\"${value.toString()}\"`;\n } else if (value !== false) {\n staticAttrs += ` ${prop}=\"${value}\"`;\n }\n }\n // Process dynamic attributes\n else if (t.isExpression(value)) {\n dynamicAttrs.push({ name: prop, value });\n }\n }\n\n return { staticAttrs, dynamicAttrs };\n}\n\n/**\n * Process dynamic attributes for SSG\n */\nconst processDynamicAttributes = (\n dynamicAttrs: Array<{ name: string; value: t.Expression }>,\n result: transformResult,\n): void => {\n dynamicAttrs.forEach(attr => {\n const { state } = getContext();\n addImport(importMap.patchAttr);\n addImport(importMap.escapeHTML);\n\n result.dynamics.push({\n type: 'attr',\n node: t.callExpression(state.imports.patchAttr, [\n t.stringLiteral(attr.name),\n t.callExpression(state.imports.escapeHTML, [attr.value]),\n t.booleanLiteral(false),\n ]),\n attrName: attr.name,\n });\n });\n};\n","import { RENDER_MODE } from '../constants';\nimport { resetContext, setContext } from './context';\nimport { transformJSXToClient } from './client';\nimport { transformJSXToSSG } from './ssg';\nimport { createTree } from './tree';\nimport type { JSXElement, RenderMode } from '../types';\nimport type { NodePath } from '@babel/core';\n\nconst transformStrategies = {\n [RENDER_MODE.CLIENT]: transformJSXToClient,\n [RENDER_MODE.SSR]: transformJSXToClient,\n [RENDER_MODE.SSG]: transformJSXToSSG,\n} as const;\n\n/**\n * Retrieves the appropriate transformation strategy for a given render mode.\n *\n * @param {RenderMode} mode - The target rendering mode\n * @returns {Function} The transformation function for the specified mode\n * @throws {Error} When an unsupported render mode is provided\n */\nconst getRenderingStrategy = (mode: RenderMode) => {\n const strategy = transformStrategies[mode];\n\n if (!strategy) {\n throw new Error(`Unsupported render mode: ${mode}`);\n }\n\n return strategy;\n};\n/**\n * Main JSX transformation function that converts JSX elements and fragments\n * into optimized runtime calls based on the configured render mode.\n *\n * @param {NodePath<JSXElement>} path - Babel AST path containing the JSX element\n * @throws {Error} When JSX transformation fails due to invalid syntax or unsupported features\n */\nexport function transformJSX(path: NodePath<JSXElement>): void {\n try {\n const mode = (path.state?.opts?.mode || RENDER_MODE.CLIENT) as RenderMode;\n\n // Get the appropriate transformation strategy for the render mode\n const strategy = getRenderingStrategy(mode);\n\n // Build a normalized tree representation of the JSX structure\n const tree = createTree(path);\n\n // Initialize transformation context with current state and path\n setContext({ state: path.state, path, operationIndex: 0 });\n\n // Apply the transformation strategy to generate optimized code\n const result = strategy(path, tree);\n\n // Replace the original JSX node with the transformed result\n path.replaceWith(result!);\n\n // Clean up transformation context to prevent memory leaks\n resetContext();\n } catch (error_) {\n // In test environment, log error but allow graceful continuation\n console.warn('JSX transformation failed in test:', { error_ });\n // Clean up context even on error\n resetContext();\n\n throw error_;\n }\n}\n","import { transformProgram } from './program';\nimport { transformProps } from './signals/props';\nimport { transformJSX } from './jsx';\nimport type { PluginObj } from '@babel/core';\n\nexport default function (): PluginObj {\n return {\n name: 'babel-plugin-essor',\n\n manipulateOptions(_, parserOpts) {\n parserOpts.plugins.push('jsx');\n },\n\n visitor: {\n Program: transformProgram,\n // props\n FunctionDeclaration: transformProps,\n ArrowFunctionExpression: transformProps,\n // JSX\n JSXElement: transformJSX,\n JSXFragment: transformJSX,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAwB,SAASA,UAAS;;;ACA1C,SAAwB,SAAS,SAAS;;;ACOnC,IAAMC,IAAYC,OACvBA,MAAQ,QAAQ,OAAOA,KAAQ;AAgB1B,IAAMC,IAAU,MAAM;AAOtB,SAASC,EAASC,GAA6B;AACpD,SAAO,OAAOA,KAAQ;AACxB;AAOO,SAASC,EAASD,GAA6B;AACpD,SAAO,OAAOA,KAAQ;AACxB;AAMO,SAASE,EAAOF,GAA2B;AAChD,SAAOA,MAAQ;AACjB;AAOO,SAASG,EAASH,GAA6B;AACpD,SAAO,OAAOA,KAAQ;AACxB;AAkCO,SAASI,EAAMC,GAA4C;AAChE,SAAOC,EAAU,KAAKD,CAAG,MAAM;AACjC;AAOO,SAASE,EAAMF,GAAuC;AAC3D,SAAOA,KAAQ;AACjB;AAuBO,IAAMG,IACXC,OAEA,CAAC,UAAU,UAAU,WAAW,UAAU,WAAW,EAAE,SAAS,OAAOA,CAAG,KAAKC,EAAOD,CAAG;AAgBpF,IAAME,IAAiBC,OAC5BC,EAAU,KAAKD,CAAG,MAAM;AAyBnB,SAASE,EAAYC,GAAgC;AAC1D,SAAO,OAAOA,KAAQ;AACxB;AAOO,SAASC,EAAUD,GAA8B;AACtD,SAAO,OAAOA,KAAQ;AACxB;AAIA,ICrLaE,IAAY,OAAO,UAAU;AAwBnC,SAASC,EAAeC,GAAoB;AACjD,SAAOC,EAAQD,CAAI,IAAIA,IAAO,CAACA,CAAI;AACrC;AAQO,IAOME,IAAO,SAAS;AAWtB,SAASC,EAAWC,GAAaC,KAA+B;AACrE,SAAKC,EAASF,CAAG,IAGVA,EAAI,QAAQC,GAAY,MAAM,IAF5B;AAG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zB,YAAY;AAAA,MACZ,aAAa;AAAA,IACf;AAAA,EACF;AACF;","names":["t","isObject","val","isArray","isString","val","isNumber","isNull","isSymbol","isMap","val","_toString","isNil","isPrimitive","val","isNull","isPlainObject","val","_toString","isUndefined","val","isBoolean","_toString","coerceArray","data","isArray","noop","startsWith","str","searchString","isString","cacheStringFunction","fn","cache","str","EMPTY_OBJ","EMPTY_ARR","hyphenateRE","kebabCase","cacheStringFunction","str","camelizeRE","camelCase","_","c","capitalize","warn","msg","args","error","msg","args","makeMap","str","map","key","val","specialBooleanAttrs","isSpecialBooleanAttr","isBooleanAttr","isKnownHtmlAttr","makeMap","isKnownSvgAttr","HTML_TAGS","SVG_TAGS","MATH_TAGS","DELEGATED_EVENTS","VOID_TAGS","SELFCLOSING_TAGS","isHTMLTag","makeMap","isSVGTag","isMathMLTag","isVoidTag","isSelfClosingTag","isDelegatedEvent","t","t","t","t","t","t","t","t","t","t","t","t","t","transformJSX","t","t","a","node","t","t","d","processChildren","_"]}
1
+ {"version":3,"sources":["../src/program.ts","../src/import.ts","../../shared/src/is.ts","../../shared/src/base.ts","../../shared/src/string.ts","../../shared/src/logger.ts","../../shared/src/escape.ts","../../shared/src/dom.ts","../src/constants.ts","../src/signals/symbol.ts","../src/signals/utils.ts","../src/signals/props.ts","../src/jsx/context.ts","../src/jsx/client.ts","../src/jsx/constants.ts","../src/jsx/shared.ts","../src/jsx/tree.ts","../src/jsx/ssg.ts","../src/jsx/index.ts","../src/index.ts"],"sourcesContent":["import { type NodePath, types as t } from '@babel/core';\nimport { addImport, clearImport, createImport, createImportIdentifiers, importMap } from './import';\nimport { DEFAULT_OPTIONS } from './constants';\nimport {\n replaceSymbol,\n symbolArrayPattern,\n symbolAssignment,\n symbolIdentifier,\n symbolObjectPattern,\n symbolUpdate,\n} from './signals/symbol';\nimport type { PluginState } from './types';\n\n// ============================================\n// Virtual module path - unified use of virtual:essor-hmr\n// ============================================\nfunction getHmrModulePath(): string {\n return '/@essor-refresh';\n}\n// ============================================\n// Create import identifier\n// ============================================\nexport function createImportIdentifier(path: babel.NodePath, importName: string): t.Identifier {\n const source = getHmrModulePath();\n const program = path.scope.getProgramParent().path as babel.NodePath<t.Program>;\n\n // Check if already imported\n let importId: t.Identifier | undefined;\n\n program.traverse({\n ImportDeclaration(importPath) {\n if (importPath.node.source.value === source) {\n const specifier = importPath.node.specifiers.find(\n spec =>\n t.isImportSpecifier(spec) &&\n t.isIdentifier(spec.imported) &&\n spec.imported.name === importName,\n );\n if (specifier && t.isImportSpecifier(specifier)) {\n importId = specifier.local;\n }\n }\n },\n });\n\n if (!importId) {\n // Create new import\n importId = path.scope.generateUidIdentifier(importName);\n const importDecl = t.importDeclaration(\n [t.importSpecifier(importId, t.identifier(importName))],\n t.stringLiteral(source),\n );\n\n // Insert import at the top of program\n program.unshiftContainer('body', importDecl);\n }\n\n return importId;\n}\n\n/**\n * Helper function to automatically set state for visitor paths.\n * This ensures that paths created by traverse() inherit the parent state.\n */\nfunction withState<T>(visitor: (path: NodePath<T>) => void, parentState: any) {\n return (path: NodePath<T>) => {\n path.state = parentState;\n visitor(path);\n };\n}\n\nexport const transformProgram = {\n enter: (path: NodePath<t.Program>, state) => {\n const opts = { ...DEFAULT_OPTIONS, ...state.opts };\n const imports = createImportIdentifiers(path);\n\n // Clear any previous import state to ensure clean transformation\n clearImport();\n\n // Extend path state with plugin-specific data\n path.state = {\n ...state,\n opts,\n imports,\n declarations: [], // Collect template declarations during transformation\n filename: state.filename,\n events: new Set(), // Track delegated events for optimization\n };\n\n // Transform signals BEFORE JSX transformation\n // This ensures that when JSX transformer extracts expression.node,\n // signal variables have already been transformed to access .value\n const parentState = path.state;\n\n path.traverse({\n VariableDeclarator: withState(replaceSymbol, parentState), // let $x = 0 → let $x = signal(0)\n Identifier: withState(symbolIdentifier, parentState), // $x → $x.value\n AssignmentExpression: withState(symbolAssignment, parentState), // $x = 1 → $x.value = 1\n UpdateExpression: withState(symbolUpdate, parentState), // $x++ → $x.value++\n ObjectPattern: withState(symbolObjectPattern, parentState), // { $x } → handle nested patterns\n ArrayPattern: withState(symbolArrayPattern, parentState), // [$x] → handle nested patterns\n });\n },\n\n // eslint-disable-next-line unused-imports/no-unused-vars\n exit: (path: NodePath<t.Program>, state) => {\n const pluginState: PluginState = path.state as PluginState;\n const { imports, declarations, events } = pluginState;\n // const mode = (opts?.mode || RENDER_MODE.CLIENT) as RENDER_MODE;\n\n // Find optimal insertion point after imports but before other code\n const insertIndex = path.node.body.findIndex(node => !t.isImportDeclaration(node));\n\n // Insert template declarations for reactive components\n if (declarations?.length) {\n const templateDeclaration = t.variableDeclaration('const', declarations);\n\n // Insert at the appropriate location to maintain code organization\n if (insertIndex !== -1) {\n path.node.body.splice(insertIndex, 0, templateDeclaration);\n } else {\n path.node.body.push(templateDeclaration);\n }\n }\n\n // Setup event delegation for performance optimization\n if (events && events.size > 0) {\n const eventsDeclaration = t.expressionStatement(\n t.callExpression(imports.delegateEvents, [\n t.arrayExpression(Array.from(events).map(event => t.stringLiteral(event))),\n ]),\n );\n addImport(importMap.delegateEvents);\n path.node.body.push(eventsDeclaration);\n }\n\n // Generate and insert required import statements\n createImport(path, imports, 'essor');\n },\n};\n","import { type NodePath, types as t } from '@babel/core';\nimport { error } from '@estjs/shared';\nimport { IMPORTS_MAPS, RENDER_MODE, SSG_IMPORTS_MAPS, SSR_IMPORTS_MAPS } from './constants';\nimport type { PluginState } from './types';\n\nexport type IMPORT_MAP_NAMES = (typeof IMPORTS_MAPS)[number];\n/**\n * Generates a set of unique import identifiers for a given program path.\n\n * @param path - The program path used to generate unique identifiers.\n * @returns A record mapping import names to their corresponding unique identifiers.\n * @throws Will throw an error if identifier generation fails for any import.\n */\nexport function createImportIdentifiers(path: NodePath<t.Program>) {\n // Initialize all required identifiers\n const identifiers = IMPORTS_MAPS.reduce<Record<string, t.Identifier>>((acc, name) => {\n // Generate unique identifier\n const identifier = path.scope?.generateUidIdentifier(`${name}$`) ?? t.identifier(`${name}$`);\n\n // Ensure identifier is valid\n if (!identifier) {\n throw new Error(`Failed to generate identifier for ${name}`);\n }\n acc[name] = identifier;\n return acc;\n }, {});\n\n return identifiers;\n}\nexport const importMap = IMPORTS_MAPS.reduce(\n (acc, name) => ({ ...acc, [name]: name }),\n {},\n) as Record<IMPORT_MAP_NAMES, IMPORT_MAP_NAMES>;\n\n// imported sets\nexport const importedSets = new Set<IMPORT_MAP_NAMES>();\n\n/**\n * Adds the given import name to the set of imported names.\n *\n * @param name The name of the import to add.\n */\nexport function addImport(name: IMPORT_MAP_NAMES): void {\n importedSets.add(name);\n}\n\n/**\n * Clears the set of imported names.\n *\n * This function is useful when the state of the imported names needs to be reset.\n * It will be called when the babel plugin is finished processing the current\n * file.\n */\nexport function clearImport(): void {\n importedSets.clear();\n}\n/**\n * Creates an import declaration for given program path.\n *\n * @param {NodePath<t.Program>} path The program path\n * @param {Record<string, t.Identifier>} imports Imported identifiers\n * @param {string} from The module path to import\n */\nexport function createImport(\n path: NodePath<t.Program>,\n imports: Record<string, t.Identifier>,\n from: string,\n): void {\n const state = path.state as PluginState;\n\n const mode = state.opts.mode;\n\n // Return early if no functions to import\n if (!importedSets.size) {\n return;\n }\n try {\n // Create import specifiers\n const importSpecifiers = Array.from(importedSets).map(name => {\n const importIdentifier = imports[name];\n if (!importIdentifier) {\n throw new Error(`Import identifier not found for: ${name}`);\n }\n const local = t.identifier(importIdentifier.name);\n if (mode === RENDER_MODE.SSG) {\n name = SSG_IMPORTS_MAPS[name] || name;\n }\n if (mode === RENDER_MODE.SSR) {\n name = SSR_IMPORTS_MAPS[name] || name;\n }\n const imported = t.identifier(name);\n return t.importSpecifier(local, imported);\n });\n\n // Create and insert import declaration at program start\n const importDeclaration = t.importDeclaration(importSpecifiers, t.stringLiteral(from));\n\n path.node.body.unshift(importDeclaration);\n } catch (error_) {\n error('Failed to create import declaration:', error);\n throw error_;\n }\n}\n","import { _toString } from './base';\n\n/**\n * Checks if a value is an object\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is an object, false otherwise\n */\nexport const isObject = (val: unknown): val is Record<any, unknown> =>\n val !== null && typeof val === 'object';\n\n/**\n * Checks if a value is a Promise\n * @template T - The type of the Promise's resolved value\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a Promise, false otherwise\n */\nexport function isPromise<T = unknown>(val: unknown): val is Promise<T> {\n return _toString.call(val) === '[object Promise]';\n}\n\n/**\n * Checks if a value is an Array\n * @type {(arg: unknown ) => arg is unknown []}\n */\nexport const isArray = Array.isArray;\n\n/**\n * Checks if a value is a string\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a string, false otherwise\n */\nexport function isString(val: unknown): val is string {\n return typeof val === 'string';\n}\n\n/**\n * Checks if a value is a number\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a number, false otherwise\n */\nexport function isNumber(val: unknown): val is number {\n return typeof val === 'number';\n}\n/**\n * Checks if a value is null\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is null, false otherwise\n */\nexport function isNull(val: unknown): val is null {\n return val === null;\n}\n\n/**\n * Checks if a value is a Symbol\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a Symbol, false otherwise\n */\nexport function isSymbol(val: unknown): val is symbol {\n return typeof val === 'symbol';\n}\n\n/**\n * Checks if a value is a Set\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a Set, false otherwise\n */\nexport function isSet(val: unknown): val is Set<unknown> {\n return _toString.call(val) === '[object Set]';\n}\n\n/**\n * Checks if a value is a WeakMap\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a WeakMap, false otherwise\n */\nexport function isWeakMap(val: unknown): val is WeakMap<any, unknown> {\n return _toString.call(val) === '[object WeakMap]';\n}\n\n/**\n * Checks if a value is a WeakSet\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a WeakSet, false otherwise\n */\nexport function isWeakSet(val: unknown): val is WeakSet<any> {\n return _toString.call(val) === '[object WeakSet]';\n}\n\n/**\n * Checks if a value is a Map\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a Map, false otherwise\n */\nexport function isMap(val: unknown): val is Map<unknown, unknown> {\n return _toString.call(val) === '[object Map]';\n}\n\n/**\n * Checks if a value is null or undefined\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is null or undefined, false otherwise\n */\nexport function isNil(val: unknown): val is null | undefined {\n return val === null || val === undefined;\n}\n\n/**\n * Checks if a value is a function\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a function, false otherwise\n */\nexport const isFunction = (val: unknown): val is Function => typeof val === 'function';\n\n/**\n * Checks if a value is falsy (false, null, or undefined)\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is falsy, false otherwise\n */\nexport function isFalsy(val: unknown): val is false | null | undefined {\n return val === false || val === null || val === undefined;\n}\n\n/**\n * Checks if a value is a primitive type (string, number, boolean, symbol, null, or undefined)\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a primitive type, false otherwise\n */\nexport const isPrimitive = (\n val: unknown,\n): val is string | number | boolean | symbol | null | undefined =>\n ['string', 'number', 'boolean', 'symbol', 'undefined'].includes(typeof val) || isNull(val);\n\n/**\n * Checks if a value is an HTMLElement\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is an HTMLElement, false otherwise\n */\nexport function isHTMLElement(val: unknown): val is HTMLElement {\n return val instanceof HTMLElement;\n}\n\n/**\n * Checks if a value is a plain object (created using Object constructor)\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a plain object, false otherwise\n */\nexport const isPlainObject = (val: unknown): val is object =>\n _toString.call(val) === '[object Object]';\n\n/**\n * String representation of a number\n * @typedef {`${number}`} StringNumber\n */\nexport type StringNumber = `${number}`;\n\n/**\n * Checks if a value is a string representation of a number\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a string number, false otherwise\n */\nexport function isStringNumber(val: unknown): val is StringNumber {\n if (!isString(val) || val === '') {\n return false;\n }\n return !Number.isNaN(Number(val));\n}\n\n/**\n * Checks if a value is undefined\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is undefined, false otherwise\n */\nexport function isUndefined(val: unknown): val is undefined {\n return typeof val === 'undefined';\n}\n\n/**\n * Checks if a value is a boolean\n * @param {unknown} val - The value to check\n * @returns {boolean} - Returns true if the value is a boolean, false otherwise\n */\nexport function isBoolean(val: unknown): val is boolean {\n return typeof val === 'boolean';\n}\n\nexport function isNaN(val: unknown): val is number {\n return Number.isNaN(val);\n}\n","import { isArray, isFunction, isString } from './is';\n\n/**\n * Reference to Object.prototype.toString\n * @type {Function}\n */\nexport const _toString = Object.prototype.toString;\nconst hasOwnProperty = Object.prototype.hasOwnProperty;\n\n/**\n * Reference to Object.assign\n * @type {Function}\n */\nexport const extend = Object.assign;\n\n/**\n * Checks if an object has a specific property\n * @template T\n * @param {object} val - The target object to check\n * @param {string | symbol} key - The property name to check for\n * @returns {key is keyof T} - Returns true if the object has the property, false otherwise\n */\nexport const hasOwn = (val: object, key: string | symbol): key is keyof typeof val =>\n hasOwnProperty.call(val, key);\n/**\n * Forces a value to be an array\n * @template T - The type of array elements\n * @param {T | T[]} data - The data to convert, can be a single element or an array\n * @returns {T[]} - The resulting array\n */\nexport function coerceArray<T>(data: T | T[]): T[] {\n return isArray(data) ? data : [data];\n}\n\n/**\n * Checks if a value has changed\n * @param {unknown } value - The new value\n * @param {unknown } oldValue - The old value\n * @returns {boolean} - Returns true if the value has changed, false otherwise\n */\nexport const hasChanged = (value: unknown, oldValue: unknown): boolean =>\n !Object.is(value, oldValue);\n\n/**\n * Empty function, used for defaults and placeholders\n * @type {Function}\n */\nexport const noop = Function.prototype as () => void;\n\n/**\n * Checks if a string starts with a specified substring\n *\n * Uses indexOf for better performance in most cases\n * @see https://www.measurethat.net/Benchmarks/Show/12350/0/startswith-vs-test-vs-match-vs-indexof#latest_results_block\n * @param {string} str - The string to check\n * @param {string} searchString - The substring to search for\n * @returns {boolean} - Returns true if the string starts with the substring, false otherwise\n */\nexport function startsWith(str: string, searchString: string): boolean {\n if (!isString(str)) {\n return false;\n }\n return str.indexOf(searchString) === 0;\n}\n\n/**\n * Generates an 8-character random string as a unique identifier\n *\n * Note: Uses Math.random() which is not cryptographically secure.\n * For security-sensitive use cases, consider using crypto.getRandomValues()\n * @returns {string} - The generated unique identifier\n */\nexport function generateUniqueId(): string {\n const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n let result = '';\n const charactersLength = characters.length;\n for (let i = 0; i < 8; i++) {\n result += characters.charAt(Math.floor(Math.random() * charactersLength));\n }\n return result;\n}\n\n/**\n * Checks if the current environment is a browser\n * @returns {boolean} - Returns true if in a browser environment, false otherwise\n */\nexport function isBrowser(): boolean {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\n/**\n * Creates a cached version of a string processing function\n * @template T - The function type\n * @param {T} fn - The string processing function to cache\n * @returns {T} - The cached function\n */\nexport const cacheStringFunction = <T extends (str: string) => string>(fn: T): T => {\n const cache: Record<string, string> = Object.create(null);\n return ((str: string) => {\n const hit = cache[str];\n return hit || (cache[str] = fn(str));\n }) as T;\n};\n\n/**\n * Read-only empty object\n * @type {Readonly<Record<string, unknown >>}\n */\nexport const EMPTY_OBJ: { readonly [key: string]: unknown } = Object.freeze({});\n\n/**\n * Read-only empty array\n * @type {readonly never[]}\n */\nexport const EMPTY_ARR: readonly never[] = Object.freeze([]);\n\n/**\n * Checks if a property name is an event handler (starts with 'on' followed by uppercase letter)\n *\n * Matches patterns like: onClick, onChange, onKeyDown (but not 'onclick' or 'on123')\n * @param {string} key - The property name to check\n * @returns {boolean} - Returns true if the property is an event handler, false otherwise\n */\nexport const isOn = (key: string): boolean =>\n key.charCodeAt(0) === 111 /* o */ &&\n key.charCodeAt(1) === 110 /* n */ &&\n key.charCodeAt(2) >= 65 && // uppercase letter A-Z\n key.charCodeAt(2) <= 90;\n\ndeclare let global: {};\n\nlet _globalThis: unknown;\n/**\n * Gets the global object for the current environment\n * @returns {unknown } - The global object for the current environment\n */\nexport const getGlobalThis = (): unknown => {\n return (\n _globalThis ||\n (_globalThis =\n typeof globalThis !== 'undefined'\n ? globalThis\n : typeof self !== 'undefined'\n ? self\n : typeof window !== 'undefined'\n ? window\n : typeof global !== 'undefined'\n ? global\n : {})\n );\n};\n\nexport type ExcludeType = ((key: string | symbol) => boolean) | (string | symbol)[];\n\n/**\n * Checks if a key should be excluded\n * @param {string | symbol} key - The key to check\n * @param {ExcludeType} [exclude] - The exclusion condition, can be a function or array\n * @returns {boolean} - Returns true if the key should be excluded, false otherwise\n */\nexport function isExclude(key: string | symbol, exclude?: ExcludeType): boolean {\n if (!exclude) {\n return false;\n }\n return isArray(exclude) ? exclude.includes(key) : isFunction(exclude) ? exclude(key) : false;\n}\n","import { cacheStringFunction } from './base';\n\n/**\n * Regular expression for converting camelCase to kebab-case\n * @type {RegExp}\n */\nconst hyphenateRE = /\\B([A-Z])/g;\n\n/**\n * Converts a camelCase string to kebab-case\n * Example: myFunction -> my-function\n * @param {string} str - The camelCase string to convert\n * @returns {string} - The kebab-case string\n */\nexport const kebabCase: (str: string) => string = cacheStringFunction((str: string) =>\n str.replaceAll(hyphenateRE, '-$1').toLowerCase(),\n);\n\n/**\n * Regular expression for converting kebab-case or snake_case to camelCase\n * @type {RegExp}\n */\nconst camelizeRE = /[_-](\\w)/g;\n\n/**\n * Converts a kebab-case or snake_case string to camelCase\n * Example: my-function or my_function -> myFunction\n * @param {string} str - The kebab-case or snake_case string to convert\n * @returns {string} - The camelCase string\n */\nexport const camelCase: (str: string) => string = cacheStringFunction((str: string): string => {\n // Remove leading and trailing hyphens or underscores\n str = str.replaceAll(/^[_-]+|[_-]+$/g, '');\n // Replace consecutive hyphens or underscores with a single hyphen\n str = str.replaceAll(/[_-]+/g, '-');\n // Convert to camelCase\n return str.replaceAll(camelizeRE, (_, c) => c.toUpperCase());\n});\n\n/**\n * Capitalizes the first letter of a string\n * Example: hello -> Hello\n * @template T - The input string type\n * @param {T} str - The string to capitalize\n * @returns {Capitalize<T>} - The capitalized string\n */\nexport const capitalize: <T extends string>(str: T) => Capitalize<T> = cacheStringFunction(\n <T extends string>(str: T) => {\n return (str.charAt(0).toUpperCase() + str.slice(1)) as Capitalize<T>;\n },\n);\n","/**\n * Outputs a warning level log message\n * @param {string} msg - The warning message\n * @param {...unknown } args - Additional arguments to log\n */\nexport function warn(msg: string, ...args: unknown[]): void {\n console.warn(`[Essor warn]: ${msg}`, ...args);\n}\n\n/**\n * Outputs an info level log message\n * @param {string} msg - The info message\n * @param {...unknown } args - Additional arguments to log\n */\nexport function info(msg: string, ...args: unknown[]): void {\n // eslint-disable-next-line no-console\n console.info(`[Essor info]: ${msg}`, ...args);\n}\n\n/**\n * Outputs an error level log message\n * @param {string} msg - The error message\n * @param {...unknown } args - Additional arguments to log\n */\nexport function error(msg: string, ...args: unknown[]): void {\n console.error(`[Essor error]: ${msg}`, ...args);\n}\n","/**\n * Regular expression for matching HTML special characters\n * @type {RegExp}\n */\nconst escapeRE = /[\"&'<>]/;\n\n/**\n * Escapes HTML special characters in a string to their corresponding entity references\n * @param {unknown} string - The string to escapeHTML\n * @returns {string} - The escaped string\n */\nexport function escapeHTML(string: unknown): string {\n const str = `${string}`;\n const match = escapeRE.exec(str);\n\n if (!match) {\n return str;\n }\n\n let html = '';\n let escaped: string;\n let index: number;\n let lastIndex = 0;\n for (index = match.index; index < str.length; index++) {\n switch (str.charCodeAt(index)) {\n case 34: // \"\n escaped = '&quot;';\n break;\n case 38: // &\n escaped = '&amp;';\n break;\n case 39: // '\n escaped = '&#39;';\n break;\n case 60: // <\n escaped = '&lt;';\n break;\n case 62: // >\n escaped = '&gt;';\n break;\n default:\n continue;\n }\n\n if (lastIndex !== index) {\n html += str.slice(lastIndex, index);\n }\n\n lastIndex = index + 1;\n html += escaped;\n }\n\n return lastIndex !== index ? html + str.slice(lastIndex, index) : html;\n}\n\n/**\n * Regular expression for stripping HTML comment markers\n * Reference: https://www.w3.org/TR/html52/syntax.html#comments\n * @type {RegExp}\n */\nconst commentStripRE = /^-?>|<!--|-->|--!>|<!-$/g;\n\n/**\n * Strips special characters from HTML comments\n * @param {string} src - The source string\n * @returns {string} - The cleaned string\n */\nexport function escapeHTMLComment(src: string): string {\n return src.replaceAll(commentStripRE, '');\n}\n\n/**\n * Regular expression for matching special characters in CSS variable names\n * @type {RegExp}\n */\nexport const cssVarNameEscapeSymbolsRE = /[ !\"#$%&'()*+,./:;<=>?@[\\\\\\]^`{|}~]/g;\n\n/**\n * Escapes special characters in CSS variable names\n * @param {string} key - The CSS variable name\n * @param {boolean} doubleEscape - Whether to apply double escaping\n * @returns {string} - The escaped CSS variable name\n */\nexport function getEscapedCssVarName(key: string, doubleEscape: boolean): string {\n return key.replaceAll(cssVarNameEscapeSymbolsRE, s =>\n doubleEscape ? (s === '\"' ? '\\\\\\\\\\\\\"' : `\\\\\\\\${s}`) : `\\\\${s}`,\n );\n}\n","/**\n * Make a map and return a function for checking if a key\n * is in that map.\n * IMPORTANT: all calls of this function must be prefixed with\n * \\/\\*#\\_\\_PURE\\_\\_\\*\\/\n * So that rollup can tree-shake them if necessary.\n */\n\n/*! #__NO_SIDE_EFFECTS__ */\n\nimport { hasOwn } from './base';\nimport { error } from './logger';\n\nexport function makeMap(str: string): (key: string) => boolean {\n const map = Object.create(null);\n for (const key of str.split(',')) {\n map[key] = 1;\n }\n return val => val in map;\n}\n\n/**\n * On the client we only need to offer special cases for boolean attributes that\n * have different names from their corresponding dom properties:\n * - itemscope -> N/A\n * - allowfullscreen -> allowFullscreen\n * - formnovalidate -> formNoValidate\n * - ismap -> isMap\n * - nomodule -> noModule\n * - novalidate -> noValidate\n * - readonly -> readOnly\n */\nconst specialBooleanAttrs =\n 'itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly';\nexport const isSpecialBooleanAttr: (key: string) => boolean =\n /*@__PURE__*/ makeMap(specialBooleanAttrs);\n\n/**\n * The full list is needed during SSR to produce the correct initial markup.\n */\nexport const isBooleanAttr: (key: string) => boolean = /*@__PURE__*/ makeMap(\n `${specialBooleanAttrs},async,autofocus,autoplay,controls,default,defer,disabled,hidden,inert,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected`,\n);\n\n/**\n * Boolean attributes should be included if the value is truthy or ''.\n * e.g. `<select multiple>` compiles to `{ multiple: '' }`\n */\nexport function includeBooleanAttr(value: unknown): boolean {\n return !!value || value === '';\n}\n\nconst unsafeAttrCharRE = /[\\t\\n\\f \"'/=>]/;\nconst attrValidationCache: Record<string, boolean> = {};\n\nexport function isSSRSafeAttrName(name: string): boolean {\n if (hasOwn(attrValidationCache, name)) {\n return attrValidationCache[name];\n }\n const isUnsafe = unsafeAttrCharRE.test(name);\n if (isUnsafe) {\n if (__DEV__) {\n error(`unsafe attribute name: ${name}`);\n }\n }\n return (attrValidationCache[name] = !isUnsafe);\n}\n\nexport const propsToAttrMap: Record<string, string | undefined> = {\n acceptCharset: 'accept-charset',\n className: 'class',\n htmlFor: 'for',\n httpEquiv: 'http-equiv',\n};\n\n/**\n * Known attributes, this is used for stringification of runtime static nodes\n * so that we don't stringify bindings that cannot be set from HTML.\n * Don't also forget to allow `data-*` and `aria-*`!\n * Generated from https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes\n */\nexport const isKnownHtmlAttr: (key: string) => boolean = /*@__PURE__*/ makeMap(\n 'accept,accept-charset,accesskey,action,align,allow,alt,async,' +\n 'autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,' +\n 'border,buffered,capture,challenge,charset,checked,cite,class,code,' +\n 'codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,' +\n 'coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,' +\n 'disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,' +\n 'formaction,formenctype,formmethod,formnovalidate,formtarget,headers,' +\n 'height,hidden,high,href,hreflang,http-equiv,icon,id,importance,inert,integrity,' +\n 'ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,' +\n 'manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,' +\n 'open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,' +\n 'referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,' +\n 'selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,' +\n 'start,step,style,summary,tabindex,target,title,translate,type,usemap,' +\n 'value,width,wrap',\n);\n\n/**\n * Generated from https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute\n */\nexport const isKnownSvgAttr: (key: string) => boolean = /*@__PURE__*/ makeMap(\n 'xmlns,accent-height,accumulate,additive,alignment-baseline,alphabetic,amplitude,' +\n 'arabic-form,ascent,attributeName,attributeType,azimuth,baseFrequency,' +\n 'baseline-shift,baseProfile,bbox,begin,bias,by,calcMode,cap-height,class,' +\n 'clip,clipPathUnits,clip-path,clip-rule,color,color-interpolation,' +\n 'color-interpolation-filters,color-profile,color-rendering,' +\n 'contentScriptType,contentStyleType,crossorigin,cursor,cx,cy,d,decelerate,' +\n 'descent,diffuseConstant,direction,display,divisor,dominant-baseline,dur,dx,' +\n 'dy,edgeMode,elevation,enable-background,end,exponent,fill,fill-opacity,' +\n 'fill-rule,filter,filterRes,filterUnits,flood-color,flood-opacity,' +\n 'font-family,font-size,font-size-adjust,font-stretch,font-style,' +\n 'font-variant,font-weight,format,from,fr,fx,fy,g1,g2,glyph-name,' +\n 'glyph-orientation-horizontal,glyph-orientation-vertical,glyphRef,' +\n 'gradientTransform,gradientUnits,hanging,height,href,hreflang,horiz-adv-x,' +\n 'horiz-origin-x,id,ideographic,image-rendering,in,in2,intercept,k,k1,k2,k3,' +\n 'k4,kernelMatrix,kernelUnitLength,kerning,keyPoints,keySplines,keyTimes,' +\n 'lang,lengthAdjust,letter-spacing,lighting-color,limitingConeAngle,local,' +\n 'marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,' +\n 'mask,maskContentUnits,maskUnits,mathematical,max,media,method,min,mode,' +\n 'name,numOctaves,offset,opacity,operator,order,orient,orientation,origin,' +\n 'overflow,overline-position,overline-thickness,panose-1,paint-order,path,' +\n 'pathLength,patternContentUnits,patternTransform,patternUnits,ping,' +\n 'pointer-events,points,pointsAtX,pointsAtY,pointsAtZ,preserveAlpha,' +\n 'preserveAspectRatio,primitiveUnits,r,radius,referrerPolicy,refX,refY,rel,' +\n 'rendering-intent,repeatCount,repeatDur,requiredExtensions,requiredFeatures,' +\n 'restart,result,rotate,rx,ry,scale,seed,shape-rendering,slope,spacing,' +\n 'specularConstant,specularExponent,speed,spreadMethod,startOffset,' +\n 'stdDeviation,stemh,stemv,stitchTiles,stop-color,stop-opacity,' +\n 'strikethrough-position,strikethrough-thickness,string,stroke,' +\n 'stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,' +\n 'stroke-miterlimit,stroke-opacity,stroke-width,style,surfaceScale,' +\n 'systemLanguage,tabindex,tableValues,target,targetX,targetY,text-anchor,' +\n 'text-decoration,text-rendering,textLength,to,transform,transform-origin,' +\n 'type,u1,u2,underline-position,underline-thickness,unicode,unicode-bidi,' +\n 'unicode-range,units-per-em,v-alphabetic,v-hanging,v-ideographic,' +\n 'v-mathematical,values,vector-effect,version,vert-adv-y,vert-origin-x,' +\n 'vert-origin-y,viewBox,viewTarget,visibility,width,widths,word-spacing,' +\n 'writing-mode,x,x-height,x1,x2,xChannelSelector,xlink:actuate,xlink:arcrole,' +\n 'xlink:href,xlink:role,xlink:show,xlink:title,xlink:type,xmlns:xlink,xml:base,xml:lang,' +\n 'xml:space,y,y1,y2,yChannelSelector,z,zoomAndPan',\n);\n\n/**\n * Shared between server-renderer and runtime-core hydration logic\n */\nexport function isRenderAbleAttrValue(value: unknown): boolean {\n if (value == null) {\n return false;\n }\n const type = typeof value;\n return type === 'string' || type === 'number' || type === 'boolean';\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/HTML/Element\nconst HTML_TAGS =\n 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +\n 'header,hgroup,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,' +\n 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +\n 'data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,' +\n 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +\n 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +\n 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +\n 'option,output,progress,select,textarea,details,dialog,menu,' +\n 'summary,template,blockquote,iframe,tfoot';\n\n// https://developer.mozilla.org/en-US/docs/Web/SVG/Element\nconst SVG_TAGS =\n 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +\n 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +\n 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +\n 'feDistantLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +\n 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +\n 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +\n 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +\n 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +\n 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +\n 'text,textPath,title,tspan,unknown,use,view';\n\n// https://www.w3.org/TR/mathml4/ (content elements excluded)\nconst MATH_TAGS =\n 'annotation,annotation-xml,maction,maligngroup,malignmark,math,menclose,' +\n 'merror,mfenced,mfrac,mfraction,mglyph,mi,mlabeledtr,mlongdiv,' +\n 'mmultiscripts,mn,mo,mover,mpadded,mphantom,mprescripts,mroot,mrow,ms,' +\n 'mscarries,mscarry,msgroup,msline,mspace,msqrt,msrow,mstack,mstyle,msub,' +\n 'msubsup,msup,mtable,mtd,mtext,mtr,munder,munderover,none,semantics';\n\nconst DELEGATED_EVENTS =\n 'beforeinput,click,dblclick,contextmenu,focusin,focusout,input,keydown,' +\n 'keyup,mousedown,mousemove,mouseout,mouseover,mouseup,pointerdown,' +\n 'pointermove,pointerout,pointerover,pointerup,touchend,touchmove,touchstart';\n\nconst VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';\n\nconst SELFCLOSING_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';\n\nexport const isHTMLTag: (key: string) => boolean = /*@__PURE__*/ makeMap(HTML_TAGS);\n\nexport const isSVGTag: (key: string) => boolean = /*@__PURE__*/ makeMap(SVG_TAGS);\n\nexport const isMathMLTag: (key: string) => boolean = /*@__PURE__*/ makeMap(MATH_TAGS);\n\nexport const isVoidTag: (key: string) => boolean = /*@__PURE__*/ makeMap(VOID_TAGS);\n\nexport const isSelfClosingTag: (key: string) => boolean = /*@__PURE__*/ makeMap(SELFCLOSING_TAGS);\n\nexport const isDelegatedEvent: (key: string) => boolean = /*@__PURE__*/ makeMap(DELEGATED_EVENTS);\n","import type { PluginOptions } from './types';\n\n// default options\nexport const DEFAULT_OPTIONS: PluginOptions = {\n mode: 'client',\n symbol: '$',\n props: true,\n hmr: false,\n styled: false,\n};\n\n// Rendering mode\nexport enum RENDER_MODE {\n CLIENT = 'client',\n SSR = 'ssr',\n SSG = 'ssg',\n}\n\nexport const IMPORTS_MAPS = [\n // Reactive API\n 'signal',\n 'computed',\n 'reactive',\n 'memoEffect',\n 'omitProps',\n\n // component\n 'createComponent',\n 'Fragment',\n 'For',\n 'Suspense',\n 'Portal',\n\n // Template related\n 'mapNodes',\n 'template',\n 'delegateEvents',\n // styled\n 'styled',\n // binding related\n 'insert',\n 'patchStyle',\n 'patchClass',\n 'patchAttr',\n 'bindElement',\n 'setSpread',\n 'addEventListener',\n // rendering related\n 'render',\n 'escapeHTML',\n 'getHydrationKey',\n] as const;\n\n// Static Site Generation API\nexport const SSG_IMPORTS_MAPS = {\n createComponent: 'createSSGComponent',\n patchAttr: 'setSSGAttr',\n} as const;\n\n// Server-side Rendering API\nexport const SSR_IMPORTS_MAPS = {\n mapNodes: 'mapSSRNodes',\n template: 'getElement',\n} as const;\n\n// transform property name\nexport const TRANSFORM_PROPERTY_NAME = '__props';\n","/**\n * Signal Symbol Transformer\n *\n * This module provides AST transformation functions for signal variables in the Babel plugin.\n * It handles the detection and transformation of signal variables based on naming convention.\n *\n * Key responsibilities:\n * - Signal variable detection (pure prefix-based, no global registry)\n * - AST transformations for signal reads, writes, and updates\n * - Destructuring pattern processing (object and array patterns)\n * - Signal declaration transformation (signal() and computed() wrappers)\n *\n * Design philosophy:\n * - Pure naming convention: variables starting with '$' are signals\n * - No global state or cross-file tracking needed\n * - Works automatically across module boundaries\n * - Simple and predictable behavior\n *\n * @module signal/symbol\n */\n\nimport { types as t } from '@babel/core';\nimport { addImport } from '../import';\nimport { isMemberAccessingProperty, isValidPath } from './utils';\nimport type { PluginState } from '../types';\nimport type { VariableDeclarator } from '@babel/types';\nimport type { NodePath } from '@babel/core';\n\n/**\n * Check whether a variable is a signal based on naming convention.\n *\n * Simple rule: any variable starting with '$' is treated as a signal.\n * This works across file boundaries without any global state.\n *\n * @param {string} name - Variable name to check\n * @returns {boolean} True if the variable is a signal\n *\n * @example\n * ```typescript\n * isSignal('$count'); // true\n * isSignal('$value'); // true\n * isSignal('count'); // false\n * isSignal('_private'); // false\n * ```\n */\nexport function isSignal(name: string): boolean {\n return !!name && name.startsWith('$');\n}\n\n/**\n * Rewrite signal variable declarations to `signal()` or `computed()` calls.\n *\n * Transformation rules:\n * 1. **Plain values** → `signal(value)`\n * - Example: `let $count = 0` → `let $count = signal(0)`\n *\n * 2. **Function expressions** → `computed(fn)`\n * - Example: `const $fullName = () => first + last`\n * → `const $fullName = computed(() => first + last)`\n *\n * 3. **Already wrapped** → skip\n * - Detects existing `signal()` / `computed()` calls\n *\n * 4. **Uninitialized** → `signal()`\n * - Example: `let $count;` → `let $count = signal();`\n *\n * @param {NodePath<VariableDeclarator>} path - AST path for the variable declarator\n *\n * @example\n * ```typescript\n * let $count = 0; // → let $count = signal(0);\n * const $fullName = () => first + last; // → const $fullName = computed(() => first + last);\n * let $existing = signal(42); // → unchanged\n * let $uninitialized; // → let $uninitialized = signal();\n * ```\n */\nexport function replaceSymbol(path: NodePath<VariableDeclarator>): void {\n const { init, id } = path.node;\n\n // Only process identifier declarators\n if (!t.isIdentifier(id)) {\n return;\n }\n\n const variableName = id.name;\n\n // Skip non-signal variables\n if (!isSignal(variableName)) {\n return;\n }\n\n // Skip if already wrapped with signal/computed\n if (isAlreadySignalCall(init)) {\n return;\n }\n\n // Use `computed` only when the initializer is a function on a `const`\n const isComputed =\n init &&\n (t.isFunctionExpression(init) || t.isArrowFunctionExpression(init)) &&\n (path.parent as t.VariableDeclaration).kind === 'const';\n\n const importName = isComputed ? 'computed' : 'signal';\n\n // Get plugin state\n const state = path.state as PluginState;\n\n // Build the wrapper call\n const args = init ? [init] : [];\n const newInit = t.callExpression(t.identifier(state.imports[importName].name), args);\n\n addImport(importName as any);\n\n // Update the AST\n path.node.init = newInit;\n}\n\n/**\n * Check whether the initializer already invokes a signal factory.\n *\n * @param {t.Expression | null} init - Initializer expression\n * @returns {boolean} True when the expression already calls a signal helper\n */\nfunction isAlreadySignalCall(init: t.Expression | null | undefined): boolean {\n if (!init || !t.isCallExpression(init) || !t.isIdentifier(init.callee)) {\n return false;\n }\n\n const calleeName = init.callee.name;\n return (\n calleeName === 'signal' ||\n calleeName === 'computed' ||\n calleeName.includes('signal') ||\n calleeName.includes('computed')\n );\n}\n\n/**\n * Rewrite signal references to access the `.value` property.\n *\n * Transforms signal variable reads to access their underlying value.\n *\n * Conversion rules:\n * - `$count` → `$count.value`\n * - `console.log($name)` → `console.log($name.value)`\n *\n * Smart skipping:\n * - Non-signal variables\n * - Already transformed (`.value` already present)\n * - Declaration contexts (variable declarations, imports, etc.)\n * - Object property keys\n *\n * @param {NodePath<t.Identifier>} path - AST path for the identifier node\n *\n * @example\n * ```typescript\n * const result = $count + 1; // → const result = $count.value + 1;\n * console.log($name); // → console.log($name.value);\n *\n * // Skipped contexts\n * let $count = 0; // declaration - not transformed\n * obj.$count = 1; // property key - not transformed\n * $count.value; // already transformed - not transformed\n * ```\n */\nexport function symbolIdentifier(path: NodePath<t.Identifier>): void {\n if (!isValidPath(path)) {\n return;\n }\n\n const name = path.node.name;\n\n // Skip non-signal variables\n if (!isSignal(name)) {\n return;\n }\n\n // Skip if context should not be transformed\n if (!shouldProcessIdentifier(path, path.parentPath)) {\n return;\n }\n\n // Skip if already accessing .value\n if (isAlreadyValueAccess(path)) {\n return;\n }\n\n // This prevents transforming cases like `__props.$value` into `__props.$value.value`\n // which would create an invalid nested structure\n const parent = path.parent;\n if (t.isMemberExpression(parent) && parent.property === path.node) {\n return;\n }\n\n // Transform: $count → $count.value\n path.replaceWith(t.memberExpression(t.identifier(name), t.identifier('value')));\n}\n\n/**\n * Decide whether an identifier should be transformed as a signal reference.\n *\n * Provides fine-grained context checks to avoid incorrect rewrites and maintain\n * program correctness.\n *\n * Contexts to skip:\n * 1. Variable declarations (e.g. `let $count = 1`)\n * 2. Import specifiers (e.g. `import { $value } from 'module'`)\n * 3. Object property keys (e.g. `obj.$prop` as the key)\n * 4. Destructuring patterns (e.g. `const { $x } = obj`)\n * 5. Function parameters and names\n * 6. Labels (e.g. `break $label`)\n * 7. Class names (e.g. `class $Class`)\n * 8. Method names\n *\n * Safe to transform when used inside expressions, as call arguments, in return\n * statements, or on the right-hand side of assignments.\n *\n * @param {NodePath<t.Identifier>} path - Identifier node path\n * @param {NodePath<t.Node> | null} parentPath - Parent AST path\n * @returns {boolean} True when the identifier should be transformed\n *\n * @example\n * ```typescript\n * // Skip\n * let $count = 1;\n * import { $value } from '';\n * obj.$prop = 1;\n *\n * // Transform\n * console.log($count);\n * return $value + 1;\n * ```\n */\nfunction shouldProcessIdentifier(\n path: NodePath<t.Identifier>,\n parentPath: NodePath<t.Node> | null,\n): boolean {\n // Validate parent path exists\n if (!parentPath) {\n return false;\n }\n\n const parent = parentPath.node;\n const currentNode = path.node;\n\n // Group 1: Declaration contexts - skip identifiers that define names\n if (t.isVariableDeclarator(parent) || t.isArrayPattern(parent) || t.isObjectPattern(parent)) {\n return false;\n }\n\n // Group 2: Import/Export contexts - skip module-level identifiers\n if (\n t.isImportSpecifier(parent) ||\n t.isImportDefaultSpecifier(parent) ||\n t.isImportNamespaceSpecifier(parent)\n ) {\n return false;\n }\n\n // Group 3: Function contexts - skip function names and parameters\n if (\n t.isFunctionDeclaration(parent) ||\n t.isFunctionExpression(parent) ||\n t.isArrowFunctionExpression(parent)\n ) {\n return false;\n }\n\n // Group 4: Class contexts - skip class and method names\n if (t.isClassDeclaration(parent) && parent.id === currentNode) {\n return false;\n }\n\n if (t.isObjectMethod(parent) || t.isClassMethod(parent)) {\n return false;\n }\n\n // Group 5: Object property keys - skip keys but allow values\n if (t.isObjectProperty(parent) && parent.key === currentNode) {\n return false;\n }\n\n // Group 6: Label contexts - skip labels in labeled statements\n if (t.isLabeledStatement(parent) && parent.label === currentNode) {\n return false;\n }\n if (\n (t.isBreakStatement(parent) || t.isContinueStatement(parent)) &&\n parent.label === currentNode\n ) {\n return false;\n }\n\n // Otherwise allow the transformation\n return true;\n}\n\n/**\n * Determine whether an identifier is already accessing `.value`.\n *\n * Prevents reprocessing identifiers that have already been rewritten, covering\n * a variety of member-access patterns.\n *\n * Detection patterns:\n * 1. Direct access – `$count.value`\n * 2. Chained access – `$count.value.toString()`\n * 3. Computed access – `$count['value']`\n * 4. Wrapped expressions – `($count).value`\n *\n * @param {NodePath<t.Identifier>} path - Identifier node path\n * @returns {boolean} True when `.value` access is already present\n *\n * @example\n * ```typescript\n * $count.value; // true\n * $count.value.toString(); // true\n * $count; // false\n * $count.other; // false\n * ```\n */\nfunction isAlreadyValueAccess(path: NodePath<t.Identifier>): boolean {\n const parent = path.parent;\n\n // Direct member access `$count.value` or computed `$count['value']`\n // This is the most common case, so check it first\n if (t.isMemberExpression(parent) && parent.object === path.node) {\n return isMemberAccessingProperty(parent, 'value');\n }\n\n if (\n !t.isParenthesizedExpression(parent) &&\n !t.isTSAsExpression(parent) &&\n !t.isTSNonNullExpression(parent)\n ) {\n return false;\n }\n\n // Traverse ancestors for nested member expressions such as ($count).value\n // Only needed for rare cases with parentheses or type assertions\n const ancestorCheck = path.findParent(p => {\n if (!p.isMemberExpression()) {\n return false;\n }\n\n const memberExpr = p.node as t.MemberExpression;\n\n // Confirm the member expression targets the current identifier\n return memberExpr.object === path.node && isMemberAccessingProperty(memberExpr, 'value');\n });\n\n return !!ancestorCheck;\n}\n\n/**\n * Rewrite signal assignments to target `.value`.\n *\n * Transforms signal variable assignments to update their underlying value.\n *\n * Conversion rules:\n * - `$count = 42` → `$count.value = 42`\n * - `$count += 1` → `$count.value += 1`\n *\n * Supported operators: `=`, `+=`, `-=`, `*=`, `/=`, `%=`, `**=`, `&=`, `|=`, `^=`, `<<=`, `>>=`, `>>>=`, `&&=`, `||=`, `??=`\n *\n * @param {NodePath<t.AssignmentExpression>} path - Assignment expression path\n *\n * @example\n * ```typescript\n * $count = 42; // → $count.value = 42;\n * $count += 1; // → $count.value += 1;\n * $name ||= 'default'; // → $name.value ||= 'default';\n *\n * // Skipped\n * obj.prop = 1; // not an identifier\n * $count.value = 1; // already .value\n * regularVar = 1; // not a signal\n * ```\n */\nexport function symbolAssignment(path: NodePath<t.AssignmentExpression>): void {\n if (!isValidPath(path)) {\n return;\n }\n\n const { left } = path.node;\n\n // Only process identifier assignments\n if (!t.isIdentifier(left)) {\n return;\n }\n\n const name = left.name;\n\n // Skip non-signal variables\n if (!isSignal(name)) {\n return;\n }\n\n // Skip if already accessing .value\n if (isAlreadyValueAssignment(left)) {\n return;\n }\n\n // Transform: $count = 1 → $count.value = 1\n path.node.left = t.memberExpression(t.identifier(name), t.identifier('value'));\n}\n\n/**\n * Check whether the assignment already targets the `.value` property.\n *\n * @param {t.LVal} left - Assignment left-hand side\n * @returns {boolean} True when `.value` is already being assigned\n */\nfunction isAlreadyValueAssignment(left: t.LVal): boolean {\n return t.isMemberExpression(left) && isMemberAccessingProperty(left, 'value');\n}\n\n/**\n * Transform signal variable update expressions to .value property updates.\n *\n * Handles increment and decrement operations on signal variables.\n *\n * Transformation rules:\n * - `$count++` → `$count.value++`\n * - `++$index` → `++$index.value`\n * - `$value--` → `$value.value--`\n * - `--$counter` → `--$counter.value`\n *\n * @param {NodePath<t.UpdateExpression>} path - AST path of the update expression node\n *\n * @example\n * ```typescript\n * $count++; // → $count.value++;\n * ++$index; // → ++$index.value;\n * $value--; // → $value.value--;\n * --$counter; // → --$counter.value;\n *\n * // Skipped\n * obj.prop++; // not an identifier\n * $count.value++; // already .value\n * regularVar++; // not a signal\n * ```\n */\nexport function symbolUpdate(path: NodePath<t.UpdateExpression>): void {\n if (!isValidPath(path)) {\n return;\n }\n\n const { argument } = path.node;\n\n // Only process identifier updates\n if (!t.isIdentifier(argument)) {\n return;\n }\n\n const name = argument.name;\n\n // Skip non-signal variables\n if (!isSignal(name)) {\n return;\n }\n\n // Skip if already accessing .value\n if (isAlreadyValueUpdate(argument)) {\n return;\n }\n\n // Transform: $count++ → $count.value++\n path.node.argument = t.memberExpression(t.identifier(name), t.identifier('value'));\n}\n\n/**\n * Check if the update expression argument is already a .value property access\n *\n * @param {t.Expression} argument - The update expression argument\n * @returns {boolean} Returns true if it's already a .value update\n */\nfunction isAlreadyValueUpdate(argument: t.Expression): boolean {\n return t.isMemberExpression(argument) && isMemberAccessingProperty(argument, 'value');\n}\n\n/**\n * Process signal-aware object destructuring patterns.\n *\n * Recursively processes object destructuring to handle nested patterns.\n * Note: This function doesn't transform the destructuring itself, but ensures\n * nested patterns are also processed by the visitor.\n *\n * Supports:\n * - Simple destructuring: `{ $count, $name }`\n * - Nested destructuring: `{ user: { $name } }`\n * - Default values: `{ $isLoading = false }`\n * - Rest elements: `{ $a, ...$rest }`\n * - Mixed patterns: `{ $x, nested: { $y }, ...$rest }`\n *\n * @param {NodePath<t.ObjectPattern>} path - Object pattern path\n *\n * @example\n * ```typescript\n * const { $count, $name } = state;\n * const { user: { $name } } = data;\n * const { $isLoading = false } = config;\n * const { $a, ...$rest } = obj;\n * ```\n */\nexport function symbolObjectPattern(path: NodePath<t.ObjectPattern>): void {\n if (!isValidPath(path)) {\n return;\n }\n\n const properties = path.node.properties;\n\n if (!Array.isArray(properties) || properties.length === 0) {\n return;\n }\n\n // Process each property\n for (const property of properties) {\n if (!property) continue;\n\n if (t.isObjectProperty(property)) {\n handleObjectProperty(property, path);\n } else if (t.isRestElement(property)) {\n handleRestElement(property, path);\n }\n }\n}\n\n/**\n * Handle a single object property within a destructuring pattern.\n *\n * Recursively processes nested patterns.\n *\n * @param {t.ObjectProperty} property - Property node\n * @param {NodePath<t.ObjectPattern>} parentPath - Parent object pattern path\n */\nfunction handleObjectProperty(\n property: t.ObjectProperty,\n parentPath: NodePath<t.ObjectPattern>,\n): void {\n if (!property || !property.value) {\n return;\n }\n\n const value = property.value;\n\n // Recurse into nested patterns\n if (t.isObjectPattern(value)) {\n const mockPath = {\n node: value,\n state: parentPath.state,\n parentPath,\n } as NodePath<t.ObjectPattern>;\n symbolObjectPattern(mockPath);\n } else if (t.isArrayPattern(value)) {\n const mockPath = {\n node: value,\n state: parentPath.state,\n parentPath,\n } as NodePath<t.ArrayPattern>;\n symbolArrayPattern(mockPath);\n } else if (t.isAssignmentPattern(value)) {\n handleAssignmentPattern(value, parentPath);\n }\n}\n\n/**\n * Handle assignment patterns (default values) in destructuring.\n *\n * Recursively processes nested patterns with default values.\n *\n * @param {t.AssignmentPattern} pattern - Assignment pattern node\n * @param {NodePath<t.ObjectPattern | t.ArrayPattern>} parentPath - Parent pattern path\n */\nfunction handleAssignmentPattern(\n pattern: t.AssignmentPattern,\n parentPath: NodePath<t.ObjectPattern> | NodePath<t.ArrayPattern>,\n): void {\n const left = pattern.left;\n\n if (t.isObjectPattern(left)) {\n const mockPath = {\n node: left,\n state: parentPath.state,\n parentPath,\n } as NodePath<t.ObjectPattern>;\n symbolObjectPattern(mockPath);\n } else if (t.isArrayPattern(left)) {\n const mockPath = {\n node: left,\n state: parentPath.state,\n parentPath,\n } as NodePath<t.ArrayPattern>;\n symbolArrayPattern(mockPath);\n }\n}\n\n/**\n * Handle rest elements inside object destructuring.\n *\n * Recursively processes nested patterns in rest elements.\n *\n * @param {t.RestElement} restElement - Rest element node\n * @param {NodePath<t.ObjectPattern>} parentPath - Parent object pattern path\n */\nfunction handleRestElement(\n restElement: t.RestElement,\n parentPath: NodePath<t.ObjectPattern>,\n): void {\n if (!restElement || !restElement.argument) {\n return;\n }\n\n const argument = restElement.argument;\n\n if (t.isObjectPattern(argument)) {\n const mockPath = {\n node: argument,\n state: parentPath.state,\n parentPath,\n } as NodePath<t.ObjectPattern>;\n symbolObjectPattern(mockPath);\n } else if (t.isArrayPattern(argument)) {\n const mockPath = {\n node: argument,\n state: parentPath.state,\n parentPath,\n } as NodePath<t.ArrayPattern>;\n symbolArrayPattern(mockPath);\n }\n}\n\n/**\n * Process signal variables in array destructuring patterns.\n *\n * Recursively processes array destructuring to handle nested patterns.\n * Note: This function doesn't transform the destructuring itself, but ensures\n * nested patterns are also processed by the visitor.\n *\n * Supported patterns:\n * - Direct destructuring: `[$first, $second]`\n * - Skipping elements: `[$first, , $third]`\n * - Default values: `[$count = 0]`\n * - Nested destructuring: `[[$x, $y], $z]`\n * - Rest destructuring: `[$first, ...$rest]`\n * - Mixed patterns: `[[$x], { $y }, $z = 0, ...$rest]`\n *\n * @param {NodePath<t.ArrayPattern>} path - AST path of the array destructuring pattern node\n *\n * @example\n * ```typescript\n * const [$x, $y] = coordinates;\n * const [$first, , $third] = items;\n * const [[$count, $name], $status] = nestedData;\n * const [$head, ...$tail] = list;\n * const [$count = 0, $name = ''] = partialData;\n * ```\n */\nexport function symbolArrayPattern(path: NodePath<t.ArrayPattern>): void {\n if (!isValidPath(path)) {\n return;\n }\n\n const elements = path.node.elements;\n\n if (!Array.isArray(elements) || elements.length === 0) {\n return;\n }\n\n // Process each element\n for (const element of elements) {\n if (!element) continue; // Skip holes\n\n if (t.isAssignmentPattern(element)) {\n handleAssignmentPattern(element, path);\n } else if (t.isRestElement(element)) {\n handleArrayRestElement(element, path);\n } else if (t.isObjectPattern(element)) {\n const mockPath = {\n node: element,\n state: path.state,\n parentPath: path,\n } as NodePath<t.ObjectPattern>;\n symbolObjectPattern(mockPath);\n } else if (t.isArrayPattern(element)) {\n const mockPath = {\n node: element,\n state: path.state,\n parentPath: path,\n } as NodePath<t.ArrayPattern>;\n symbolArrayPattern(mockPath);\n }\n }\n}\n\n/**\n * Handle rest element in array destructuring.\n *\n * Recursively processes nested patterns in rest elements.\n *\n * @param {t.RestElement} restElement - Rest element node\n * @param {NodePath<t.ArrayPattern>} parentPath - Parent node path\n */\nfunction handleArrayRestElement(\n restElement: t.RestElement,\n parentPath: NodePath<t.ArrayPattern>,\n): void {\n if (!restElement || !restElement.argument) {\n return;\n }\n\n const argument = restElement.argument;\n\n if (t.isArrayPattern(argument)) {\n const mockPath = {\n node: argument,\n state: parentPath.state,\n parentPath,\n } as NodePath<t.ArrayPattern>;\n symbolArrayPattern(mockPath);\n } else if (t.isObjectPattern(argument)) {\n const mockPath = {\n node: argument,\n state: parentPath.state,\n parentPath,\n } as NodePath<t.ObjectPattern>;\n symbolObjectPattern(mockPath);\n }\n}\n","import { types as t } from '@babel/core';\nimport type {\n ArrowFunctionExpression,\n FunctionDeclaration,\n FunctionExpression,\n} from '@babel/types';\nimport type { NodePath } from '@babel/core';\n\n/**\n * Validates if a path and its node are valid\n *\n * @param path - AST node path to validate\n * @returns true if path and node are valid, false otherwise\n */\nexport function isValidPath(path: NodePath<unknown> | null | undefined): boolean {\n return !!(path && path.node);\n}\n/**\n * Checks if a node is a JSX element or fragment\n *\n * @param node - AST node to check\n * @returns true if node is JSX element or fragment, false otherwise\n */\nexport function isJSXNode(node: t.Node | null | undefined): boolean {\n return !!(node && (t.isJSXElement(node) || t.isJSXFragment(node)));\n}\n\n/**\n * Checks if an expression might return JSX\n * Handles conditional, logical, and sequence expressions recursively\n *\n * @param expr - Expression to check\n * @returns true if expression might return JSX, false otherwise\n */\nexport function mightReturnJSX(expr: t.Expression | t.Node): boolean {\n // Direct JSX check\n if (isJSXNode(expr)) {\n return true;\n }\n\n // Conditional: condition ? <A /> : <B />\n if (t.isConditionalExpression(expr)) {\n return mightReturnJSX(expr.consequent) || mightReturnJSX(expr.alternate);\n }\n\n // Logical: condition && <A /> or condition || <B />\n if (t.isLogicalExpression(expr)) {\n return mightReturnJSX(expr.left) || mightReturnJSX(expr.right);\n }\n\n // Sequence: (expr1, expr2, <JSX />)\n if (t.isSequenceExpression(expr)) {\n return expr.expressions.some(mightReturnJSX);\n }\n\n // Parenthesized: (<JSX />)\n if (t.isParenthesizedExpression(expr)) {\n return mightReturnJSX(expr.expression);\n }\n\n return false;\n}\n\n/**\n * Checks if a function returns JSX elements\n *\n * Only functions that return JSX need props transformation. This function\n * performs a comprehensive check to detect JSX returns in various scenarios.\n *\n * @param path - Function node path to analyze\n * @returns true if function returns JSX element or JSX fragment, false otherwise\n * @throws Never throws - returns false on any error\n *\n * @example\n * ```typescript\n * // Returns true\n * function Component() { return <div />; }\n * const Component = () => <div />;\n * const Component = () => { return <div />; };\n * const Component = () => condition ? <div /> : <span />;\n *\n * // Returns false\n * function helper() { return 'string'; }\n * const compute = () => 42;\n * const Component = () => { console.log('no return'); };\n * ```\n */\nexport function checkHasJSXReturn(\n path: NodePath<FunctionDeclaration | ArrowFunctionExpression | FunctionExpression>,\n): boolean {\n if (!isValidPath(path)) return false;\n\n try {\n const body = path.get('body');\n if (!isValidPath(body)) return false;\n\n // if the body is not a block statement, check if it might return JSX\n if (!t.isBlockStatement(body.node)) {\n return mightReturnJSX(body.node);\n }\n\n // check if the body has a return statement that returns JSX\n let hasJSX = false;\n body.traverse({\n 'ReturnStatement': function (returnPath) {\n if (!hasJSX && returnPath.node.argument && mightReturnJSX(returnPath.node.argument)) {\n hasJSX = true;\n returnPath.stop();\n }\n },\n 'FunctionDeclaration|FunctionExpression|ArrowFunctionExpression': nestedPath => {\n nestedPath.skip();\n },\n });\n\n return hasJSX;\n } catch {\n return false;\n }\n}\n/**\n * Checks if a member expression is accessing a specific property\n *\n * @param node - Member expression node\n * @param propertyName - Property name to check\n * @returns true if the member expression accesses the specified property\n */\nexport function isMemberAccessingProperty(node: t.MemberExpression, propertyName: string): boolean {\n if (!node.computed && t.isIdentifier(node.property) && node.property.name === propertyName) {\n return true;\n }\n\n if (node.computed && t.isStringLiteral(node.property) && node.property.value === propertyName) {\n return true;\n }\n\n return false;\n}\n","import { type NodePath, types as t } from '@babel/core';\n\nimport { isPlainObject, startsWith, warn } from '@estjs/shared';\nimport { TRANSFORM_PROPERTY_NAME } from '../constants';\nimport { addImport, importMap } from '../import';\nimport { checkHasJSXReturn } from './utils';\nimport type { PluginState } from '../types';\nimport type {\n ArrowFunctionExpression,\n FunctionDeclaration,\n ObjectProperty,\n RestElement,\n} from '@babel/types';\n\n/**\n * Recursively replaces properties in object destructuring patterns\n *\n * This is the core transformation function that handles various types of property\n * destructuring patterns while collecting default value information.\n *\n * Supported patterns:\n * 1. **Simple destructuring**: `{ name }` → `__props.name`\n * 2. **Aliasing**: `{ name: userName }` → `__props.name` (userName renamed)\n * 3. **Default values**: `{ delay = 1500 }` → `__props.delay` (default collected)\n * 4. **Nested objects**: `{ user: { name } }` → `__props.user.name`\n * 5. **Mixed patterns**: `{ a, b: { c = 1 } }` → `__props.a`, `__props.b.c`\n *\n * @param path - Function node path being transformed\n * @param properties - List of properties to process from object destructuring pattern\n * @param parentPath - Parent path prefix for building complete property paths\n * @param defaultValues - Default value collector to store extracted default values\n * @throws Never throws - handles all errors internally and continues processing\n *\n * @example\n * ```typescript\n * // Input: function Component({ name, user: { age = 18 } }) { ... }\n * // After: function Component(__props = { user: { age: 18 } }) {\n * // // name → __props.name\n * // // age → __props.user.age\n * // }\n * ```\n */\nfunction transformProperty(\n path: NodePath<FunctionDeclaration | ArrowFunctionExpression>,\n properties: ObjectProperty[],\n parentPath: string,\n defaultValues: Record<string, unknown> = {},\n): Record<string, unknown> {\n properties.forEach((property, index) => {\n try {\n // Only process object properties, skip rest elements\n if (!t.isObjectProperty(property)) {\n return;\n }\n\n // Ensure key is identifier\n if (!t.isIdentifier(property.key)) {\n // For computed property names, skip processing\n if (__DEV__) {\n warn('transformObjectProperties: Skipping computed property', { index });\n }\n return;\n }\n\n const keyName = property.key.name;\n\n if (t.isIdentifier(property.value)) {\n path.scope.rename(property.value.name, `${parentPath}.${keyName}`);\n } else if (t.isAssignmentPattern(property.value)) {\n // Case 2: Assignment pattern (with default value) - collect default value and rename\n // Example: { delay = 1500 } -> collect default value, rename to __props.delay\n if (t.isIdentifier(property.value.left)) {\n // Collect default value\n defaultValues[keyName] = property.value.right;\n // Rename identifier to use parent path\n\n path.scope.rename(property.value.left.name, `${parentPath}.${keyName}`);\n } else if (t.isObjectPattern(property.value.left)) {\n // Nested object with default: { nested: { x } = {} }\n transformProperty(\n path,\n property.value.left.properties as ObjectProperty[],\n `${parentPath}.${keyName}`,\n defaultValues,\n );\n // Store the default value for the nested object\n defaultValues[keyName] = property.value.right;\n }\n } else if (t.isObjectPattern(property.value)) {\n // Case 3: Nested object pattern - recursive processing\n // Example: { user: { name, age } } -> __props.user.name, __props.user.age\n transformProperty(\n path,\n property.value.properties as ObjectProperty[],\n `${parentPath}.${keyName}`,\n defaultValues,\n );\n }\n // Other cases (like array patterns) are not commonly used in props and are skipped\n } catch (error) {\n // Single property processing failure should not affect other properties\n warn('transformProperty', `Failed to process property at index ${index}`, {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n });\n\n return defaultValues;\n}\n\n/**\n * Rest parameter information collected during transformation\n */\ninterface RestParameterInfo {\n /** Rest parameter variable name */\n name: string;\n /** Parent path prefix (e.g., '__props.user.') */\n parentPath: string;\n /** Properties to exclude from this rest object */\n excludeProps: string[];\n}\n/**\n * Creates a variable declaration for rest parameter\n *\n * When a rest parameter exists, creates a reactive rest object that excludes\n * the explicitly destructured properties using the omit utility.\n *\n * Strategy:\n * - If no excludeProps: `const rest = __props` (direct reference)\n * - If has excludeProps: `const rest = omit(__props, ['name', 'age'])`\n * - For nested rest: `const userRest = omit(__props.user, ['name', 'age'])`\n *\n * @param state - Babel plugin state object (must contain imports.omit)\n * @param restName - Rest parameter name (e.g., 'rest', 'otherProps')\n * @param parentPath - Parent path prefix (e.g., '__props.' or '__props.user.')\n * @param excludeProps - List of property names to exclude from rest object\n * @returns Variable declaration AST node for the rest parameter\n * @throws {Error} If state is invalid or missing omit import\n * @throws {Error} If restName is invalid\n * @throws {TypeError} If excludeProps is not an array\n *\n * @example\n * ```typescript\n * // Top-level rest: { name, age, ...rest }\n * // Output: const rest = omit(__props, ['name', 'age']);\n *\n * // Nested rest: { user: { name, ...userRest } }\n * // Output: const userRest = omit(__props.user, ['name']);\n *\n * // Usage in component:\n * // <div {...rest} /> will spread all props except name and age\n * ```\n */\nfunction buildRestVariableDeclaration(\n state: PluginState,\n restName: string,\n parentPath: string,\n excludeProps: string[],\n): t.VariableDeclaration {\n // Validate restName\n // if (!restName || restName.trim() !== restName || !parentPath) {\n // return;\n // }\n\n // Validate each property name in excludeProps\n const validExcludeProps = excludeProps.filter(Boolean);\n\n let init: t.Expression;\n\n // Build the source object expression from parentPath\n // e.g., '__props.' -> __props, '__props.user.' -> __props.user\n const pathParts = parentPath.split('.').filter(part => part.length > 0);\n let sourceObject: t.Expression = t.identifier(pathParts[0] || '__props');\n\n for (let i = 1; i < pathParts.length; i++) {\n sourceObject = t.memberExpression(sourceObject, t.identifier(pathParts[i]));\n }\n\n if (validExcludeProps.length === 0) {\n // No properties to exclude, directly reference the source object\n init = sourceObject;\n } else {\n // Create: omit(sourceObject, ['name', 'age'])\n init = t.callExpression(state.imports.omitProps, [\n sourceObject,\n t.arrayExpression(validExcludeProps.map(name => t.stringLiteral(name))),\n ]);\n }\n\n return t.variableDeclaration('const', [t.variableDeclarator(t.identifier(restName), init)]);\n}\n\nfunction transformRestProperties(\n path: NodePath<FunctionDeclaration | ArrowFunctionExpression>,\n restProperties: RestElement,\n notRestNames: string[] = [],\n nestedRestParams: RestParameterInfo[] = [],\n): void {\n if (!t.isIdentifier(restProperties.argument)) {\n return;\n }\n const restName = restProperties.argument.name;\n\n if (notRestNames.length === 0 && nestedRestParams.length === 0) {\n // Only rest parameter, no other properties and no nested rest\n // Directly use rest parameter name as first parameter\n path.node.params[0] = t.identifier(restName);\n } else {\n // Has regular properties or nested rest parameters\n const restDeclarations: t.VariableDeclaration[] = [];\n\n // Process nested rest parameters first (from deepest to shallowest for correct order)\n if (nestedRestParams.length > 0) {\n for (const nestedRest of nestedRestParams) {\n const nestedRestDeclaration = buildRestVariableDeclaration(\n path.state,\n nestedRest.name,\n nestedRest.parentPath,\n nestedRest.excludeProps,\n );\n restDeclarations.push(nestedRestDeclaration);\n\n // Add omit import if there are props to exclude\n if (nestedRest.excludeProps.length > 0) {\n addImport(importMap.omitProps);\n }\n }\n }\n\n // Process top-level rest parameter if exists\n if (restProperties) {\n const restDeclaration = buildRestVariableDeclaration(\n path.state,\n restName,\n TRANSFORM_PROPERTY_NAME,\n notRestNames,\n );\n restDeclarations.push(restDeclaration);\n\n // Only add omit import if we actually need it (when there are props to exclude)\n if (notRestNames.length) {\n addImport(importMap.omitProps);\n }\n }\n\n // Insert all rest declarations at function body start\n for (const declaration of restDeclarations) {\n const body = path.node.body as t.BlockStatement;\n body.body.unshift(declaration);\n }\n }\n}\n/**\n * Creates a default value object expression with support for nested defaults\n *\n * @param defaultValues - Collected default value mapping (key → expression or nested object)\n * @returns Object expression containing default values, or empty object if input is invalid\n * @throws Never throws - returns empty object on any error\n *\n * @example\n * ```typescript\n * // Input: { count: 0, user: { age: 18, settings: { theme: 'dark' } } }\n * // Output: AST for { count: 0, user: { age: 18, settings: { theme: 'dark' } } }\n *\n * // Used as: function Component(__props = { count: 0, user: { age: 18 } })\n * ```\n */\nfunction buildDefaultValueObject(defaultValues): t.ObjectExpression {\n // Validate input type\n if (!isPlainObject(defaultValues)) {\n return t.objectExpression([]);\n }\n\n const properties: t.ObjectProperty[] = [];\n\n for (const [key, value] of Object.entries(defaultValues)) {\n if (!key) {\n continue;\n }\n\n let propertyValue: t.Expression;\n\n // Check if value is a nested DefaultValueCollector\n if (isPlainObject(value) && !t.isNode(value)) {\n // Recursively build nested object\n propertyValue = buildDefaultValueObject(value);\n } else if (t.isExpression(value)) {\n // Direct expression value\n propertyValue = value;\n } else {\n continue;\n }\n\n properties.push(t.objectProperty(t.identifier(key), propertyValue));\n }\n\n return t.objectExpression(properties);\n}\n\nfunction buildDefaultValue(\n path: NodePath<FunctionDeclaration | ArrowFunctionExpression>,\n defaultValues: Record<string, unknown>,\n): void {\n const propsParam =\n Object.keys(defaultValues).length > 0\n ? t.assignmentPattern(\n t.identifier(TRANSFORM_PROPERTY_NAME),\n buildDefaultValueObject(defaultValues),\n )\n : t.identifier(TRANSFORM_PROPERTY_NAME);\n\n path.node.params[0] = propsParam;\n}\n\n/**\n * Transforms function parameters to reactive properties\n * @param path - Function node path to transform\n * @throws Never throws - handles all errors internally and continues compilation\n *\n * Transformation flow:\n * 1. Validate function returns JSX\n * 2. Validate first parameter is object pattern\n * 3. Check prop names don't conflict with signal prefix\n * 4. Replace property references with __props.xxx\n * 5. Collect default values\n * 6. Handle rest parameters\n *\n * @example\n * ```typescript\n * // Before\n * function Component({ title, count = 0, ...rest }) {\n * return <div>{title} {count} {rest}</div>;\n * }\n *\n * // After\n * function Component(__props = { count: 0 }) {\n * const rest = omitProps(__props, ['title', 'count']);\n * return <div>{__props.title} {__props.count} {rest}</div>;\n * }\n * ```\n */\nexport function transformProps(\n path: NodePath<FunctionDeclaration | ArrowFunctionExpression>,\n): void {\n // just transform the first parameter\n const firstParam = path.node.params[0];\n\n // validate the first parameter is an object pattern and the function returns JSX\n if (!firstParam || !t.isObjectPattern(firstParam) || !checkHasJSXReturn(path)) {\n return;\n }\n\n const state: PluginState = path.state;\n const properties = firstParam.properties as ObjectProperty[];\n\n const signalPrefix = state.opts.symbol || '$';\n\n const notRestProperties = properties.filter(prop => !t.isRestElement(prop)) as ObjectProperty[];\n\n // one object just have one rest\n const restProperties = properties.find(prop => t.isRestElement(prop)) as RestElement | undefined;\n const notRestNames = notRestProperties\n .map(prop => (t.isIdentifier(prop.key) ? prop.key.name : null))\n .filter((name): name is string => name !== null);\n\n if (__DEV__) {\n // if the property names start with the signal prefix,\n if (notRestNames.some(name => startsWith(name, signalPrefix))) {\n warn(\n 'transformProps',\n 'Property names cannot start with signal prefix',\n notRestNames.filter(name => startsWith(name, signalPrefix)),\n );\n }\n }\n\n if (notRestProperties.length) {\n const defaultValues = transformProperty(path, notRestProperties, TRANSFORM_PROPERTY_NAME);\n buildDefaultValue(path, defaultValues);\n }\n if (restProperties) {\n transformRestProperties(path, restProperties, notRestNames);\n }\n}\n","import type { NodePath } from '@babel/core';\nimport type { JSXElement, PluginState } from '../types';\n\n/**\n * Transform Context Interface\n * @description Describes shared context data during the transformation process\n */\nexport interface TransformContext {\n /// State object\n state: PluginState;\n // Node path\n path: NodePath<JSXElement>;\n // Index to track operations\n operationIndex: number;\n}\n\nconst contextStack: TransformContext[] = [];\n/**\n * Get current transform context\n * @returns {TransformContext} Current context object\n */\nexport function getContext(): TransformContext {\n if (!contextStack.length) {\n throw new Error('No active context found. Ensure setContext has been called.');\n }\n return contextStack[contextStack.length - 1];\n}\n\n/**\n * Set transform context\n * @param {Partial<TransformContext>} context - The context to update\n */\nexport function setContext(context: TransformContext): void {\n contextStack.push(context);\n}\n\n/**\n * Reset transform context\n * @description Resets the context to its initial state\n */\nexport function resetContext(): void {\n contextStack.pop();\n}\n","import {\n coerceArray,\n isArray,\n isDelegatedEvent,\n isNil,\n isObject,\n isString,\n startsWith,\n warn,\n} from '@estjs/shared';\nimport { types as t } from '@babel/core';\nimport { addImport, importMap } from '../import';\nimport {\n BUILT_IN_COMPONENTS,\n CLASS_NAME,\n CREATE_COMPONENT_NAME,\n EVENT_ATTR_NAME,\n NODE_TYPE,\n REF_KEY,\n SPREAD_NAME,\n STYLE_NAME,\n UPDATE_PREFIX,\n} from './constants';\nimport {\n type DynamicContent,\n createPropsObjectExpression,\n findBeforeIndex,\n findIndexPosition,\n getSetFunctionForAttribute,\n isDynamicExpression,\n serializeAttributes,\n} from './shared';\nimport { getContext, setContext } from './context';\nimport { type TreeNode, isTreeNode } from './tree';\nimport type { NodePath } from '@babel/core';\nimport type { JSXElement, PluginState } from '../types';\n\ninterface ReactiveOperation {\n nodeIndex: number;\n attrName: string;\n attrValue: t.Expression;\n setFunction: {\n name: string;\n value: t.Identifier;\n };\n propKey: string;\n}\n\nexport function transformJSXToClient(path: NodePath<JSXElement>, node: TreeNode) {\n const state = path.state;\n\n // Handle component or fragment\n if (node.type === NODE_TYPE.COMPONENT) {\n const props = { ...node.props, children: node.children };\n return createComponentExpression(node, props);\n }\n // Generate static template\n const staticTemplate = generateStaticTemplate(node);\n\n // Collect dynamic props and children (static ones are already in template)\n const dynamicCollection = generateDynamic(node);\n\n // Generate index mapping for DOM node references\n const indexMap = generateIndexMap(dynamicCollection);\n\n // Create identifiers for root element and node mapping\n const elementId = path.scope.generateUidIdentifier('_$el');\n const nodesId = path.scope.generateUidIdentifier('_$nodes');\n\n // Initialize statements array for function body\n const statements: t.Statement[] = [];\n\n if (staticTemplate) {\n addImport(importMap.template);\n const tmplId = path.scope.generateUidIdentifier('_$tmpl');\n\n state.declarations.push(\n t.variableDeclarator(\n tmplId,\n t.callExpression(state.imports.template, coerceArray(staticTemplate).map(t.stringLiteral)),\n ),\n );\n statements.push(\n t.variableDeclaration('const', [\n t.variableDeclarator(elementId, t.callExpression(tmplId, [])),\n ]),\n );\n }\n if (\n dynamicCollection.children.length ||\n dynamicCollection.props.length ||\n dynamicCollection.operations.length\n ) {\n // Import mapNodes\n addImport(importMap.mapNodes);\n\n statements.push(\n t.variableDeclaration('const', [\n t.variableDeclarator(\n nodesId,\n t.callExpression(state.imports.mapNodes, [\n elementId,\n t.arrayExpression(indexMap.map(idx => t.numericLiteral(idx))),\n ]),\n ),\n ]),\n );\n // Process dynamic child nodes if they exist\n if (dynamicCollection.children.length) {\n generateDynamicChildrenCode(dynamicCollection.children, statements, state, nodesId, indexMap);\n }\n\n // Process dynamic properties if they exist\n if (dynamicCollection.props.length) {\n generateDynamicPropsCode(dynamicCollection.props, statements, state, nodesId, indexMap);\n }\n\n // Process reactive operations if they exist\n if (dynamicCollection.operations.length) {\n generateUnifiedMemoizedEffect(\n dynamicCollection.operations,\n statements,\n state,\n nodesId,\n indexMap,\n );\n }\n }\n\n // Add return statement\n statements.push(t.returnStatement(elementId));\n\n // Create and return IIFE expression\n return t.callExpression(t.arrowFunctionExpression([], t.blockStatement(statements)), []);\n}\n\n/**\n * Generate property key name (for state objects)\n *\n * Creates unique property keys for DOM attributes in the state object,\n * ensuring proper batching and tracking of dynamic attribute updates.\n *\n * @param attrName - The attribute name to generate a key for\n * @returns A unique property key string\n */\nfunction generatePropKey(attrName: string = 'attr'): string {\n const { operationIndex } = getContext();\n const keyMap: Record<string, string> = {\n [CLASS_NAME]: 'c',\n [STYLE_NAME]: 's',\n name: 'n',\n attr: 'a',\n };\n\n const baseKey = keyMap[attrName] || attrName.charAt(0);\n setContext({ ...getContext(), operationIndex: operationIndex + 1 });\n setContext({ ...getContext(), operationIndex: operationIndex + 1 });\n return `${baseKey}${operationIndex}`;\n}\n\n/**\n * Transform JSX element to client rendering code\n * @param path - The path of the JSX element being transformed\n * @param treeNode - The tree node representation of the JSX element\n * @returns The transformed client rendering code\n */\nfunction transformJSXClientChildren(path: NodePath<JSXElement>, treeNode: TreeNode) {\n return transformJSXToClient(path, treeNode);\n}\n\n/**\n * Creates a component expression for client rendering\n * @param node - The tree node representation of the component or fragment\n * @param componentProps - The props object for the component or fragment\n * @returns The transformed component expression\n */\nfunction createComponentExpression(node: TreeNode, componentProps: Record<string, unknown>) {\n const { state } = getContext();\n\n addImport(importMap.createComponent);\n\n // Built-in components\n const isBuiltIn = BUILT_IN_COMPONENTS.includes(node.tag!);\n if (isBuiltIn) {\n addImport(importMap[node.tag!]);\n }\n\n const argTag = isBuiltIn ? state.imports[node.tag!] : t.identifier(node.tag!);\n // Create props object expression\n const propsObj = createPropsObjectExpression(componentProps, transformJSXClientChildren);\n\n const args: t.Expression[] = [argTag, propsObj];\n\n return t.callExpression(state.imports[CREATE_COMPONENT_NAME], args);\n}\n/**\n * Generates an optimized index map for DOM node references.\n */\nfunction generateIndexMap({\n props,\n children,\n operations = [],\n}: {\n props: Array<{ props: Record<string, unknown>; parentIndex: number | null }>;\n children: Array<{ parentIndex: number | null; before: number | null }>;\n operations?: Array<{ nodeIndex: number }>;\n}) {\n const indexSet = new Set<number>();\n\n // Collect indices related to dynamic child nodes\n for (const item of children) {\n // Add parent node index\n if (!isNil(item.parentIndex)) {\n indexSet.add(item.parentIndex);\n }\n // Add reference node index (for insertBefore)\n if (!isNil(item.before)) {\n indexSet.add(item.before);\n }\n }\n\n // Collect parent node indices related to dynamic attributes\n for (const item of props) {\n if (!isNil(item.parentIndex)) {\n indexSet.add(item.parentIndex);\n }\n }\n\n // Collect node indices for reactive operations\n if (operations && operations.length > 0) {\n for (const item of operations) {\n if (!isNil(item.nodeIndex)) {\n indexSet.add(item.nodeIndex);\n }\n }\n }\n\n // Convert to sorted array for predictable ordering\n const indexMap = Array.from(indexSet).sort((a, b) => a - b);\n\n // Validation: Ensure all indices are positive integers\n if (__DEV__) {\n for (const index of indexMap) {\n if (!Number.isInteger(index) || index < 1) {\n warn(`Invalid index in index map: ${index}. All indices must be positive integers.`);\n }\n }\n }\n\n return indexMap;\n}\n\n// typeof value === \"function\" ? value(_el$) : value.value = _el$;\nexport function createRefStatement(\n nodesId: t.Identifier,\n nodeIndex: number,\n value: t.Expression,\n): t.ExpressionStatement {\n // Get the target DOM element: nodes[nodeIndex]\n const elementRef = t.memberExpression(nodesId, t.numericLiteral(nodeIndex), true);\n\n // Create: typeof value === \"function\"\n const typeofCheck = t.binaryExpression(\n '===',\n t.unaryExpression('typeof', value),\n t.stringLiteral('function'),\n );\n\n // Create: value(element) - function call\n const functionCall = t.callExpression(value, [elementRef]);\n\n // Create: value.value = element - assignment expression\n const assignmentExpr = t.assignmentExpression(\n '=',\n t.memberExpression(value, t.identifier('value')),\n elementRef,\n );\n\n // Create: typeof value === \"function\" ? value(element) : value.value = element\n const conditionalExpr = t.conditionalExpression(typeofCheck, functionCall, assignmentExpr);\n\n return t.expressionStatement(conditionalExpr);\n}\n\n/**\n * Create attribute setting statement\n\n */\nexport function createAttributeStatement(\n functionIdentifier: t.Identifier,\n nodesId: t.Identifier,\n nodeIndex: number,\n value: t.Expression,\n key?: t.Expression,\n): t.ExpressionStatement {\n // Prepare parameter array, first parameter is always the target DOM element\n const args: t.Expression[] = [t.memberExpression(nodesId, t.numericLiteral(nodeIndex), true)];\n\n // Add optional key parameter (such as attribute name, event name, etc.)\n if (key) {\n args.push(key);\n }\n\n // Add value parameter, supports array spreading\n if (value) {\n if (isArray(value)) {\n // Array value: spread all elements as independent parameters\n args.push(...value);\n } else {\n // Single value: add directly\n args.push(value);\n }\n }\n\n // Create function call expression statement\n const functionCall = t.callExpression(functionIdentifier, args);\n return t.expressionStatement(functionCall);\n}\n\n/**\n * Add event listener handling statement\n\n * @param {string} attrName - Event attribute name (e.g., 'onClick', 'onMouseOver')\n * @param {t.Expression} attrValue - Event handler function expression\n * @param {t.Identifier} nodesId - Node mapping array identifier\n * @param {number} nodeIndex - Target node index position in mapping array\n * @param {t.Statement[]} statements - Statement collection (for adding generated code)\n * @param {State} state - Plugin state (contains event registration info)\n */\nfunction addEventListenerStatement(\n attrName: string,\n attrValue: t.Expression,\n nodesId: t.Identifier,\n nodeIndex: number,\n statements: t.Statement[],\n state: PluginState,\n): void {\n // Extract event name: remove 'on' prefix and convert to lowercase\n const eventName = attrName.slice(2).toLowerCase();\n\n if (isDelegatedEvent(eventName)) {\n const activeContext = getContext();\n if (!activeContext) {\n warn('Missing active context, unable to handle delegated events');\n return;\n }\n\n // Generate delegated event code: element.$eventName = handler\n const elementRef = t.memberExpression(nodesId, t.numericLiteral(nodeIndex), true);\n const eventProperty = t.memberExpression(elementRef, t.stringLiteral(`_$${eventName}`), true);\n\n // Create assignment statement: nodes[index].$eventName = handler\n const assignmentStmt = t.expressionStatement(\n t.assignmentExpression('=', eventProperty, attrValue),\n );\n statements.push(assignmentStmt);\n\n // Register event to global event system\n state.events?.add(eventName);\n return;\n }\n\n // Direct event handling (compatibility path)\n addImport(importMap.addEventListener);\n\n // Generate direct event listener code: addEventListener(element, 'eventName', handler)\n const eventListenerStmt = createAttributeStatement(\n state.imports.addEventListener,\n nodesId,\n nodeIndex,\n attrValue,\n t.stringLiteral(eventName),\n );\n statements.push(eventListenerStmt);\n}\n/**\n * Generate specific attribute setting code based on attribute name\n * @param attributeName - Attribute name\n * @param attributeValue - Attribute value\n * @param nodesId - Node mapping identifier\n * @param nodeIndex - Node index position\n * @param statements - Statement collection\n * @param state - Plugin state\n */\nfunction generateSpecificAttributeCode(\n attributeName: string,\n attributeValue: t.Expression,\n nodesId: t.Identifier,\n nodeIndex: number,\n statements: t.Statement[],\n state: PluginState,\n): void {\n // Note: Reactive attributes are already handled uniformly in generateDynamicPropsCode\n // This only handles non-reactive static attributes\n\n switch (attributeName) {\n case CLASS_NAME:\n addImport(importMap.patchClass);\n statements.push(\n createAttributeStatement(state.imports.patchClass, nodesId, nodeIndex, attributeValue),\n );\n break;\n\n case SPREAD_NAME:\n addImport(importMap.setSpread);\n statements.push(\n createAttributeStatement(state.imports.setSpread, nodesId, nodeIndex, attributeValue),\n );\n break;\n\n case REF_KEY:\n statements.push(createRefStatement(nodesId, nodeIndex, attributeValue));\n break;\n\n case STYLE_NAME:\n addImport(importMap.patchStyle);\n statements.push(\n createAttributeStatement(state.imports.patchStyle, nodesId, nodeIndex, attributeValue),\n );\n break;\n\n default:\n if (startsWith(attributeName, `${UPDATE_PREFIX}:`)) {\n addImport(importMap.bindElement);\n const attrName = attributeName.split(':')[1];\n statements.push(\n createAttributeStatement(\n state.imports.bindElement,\n nodesId,\n nodeIndex,\n attributeValue,\n t.stringLiteral(attrName),\n ),\n );\n return;\n }\n // Process normal attributes\n addImport(importMap.patchAttr);\n statements.push(\n createAttributeStatement(\n state.imports.patchAttr,\n nodesId,\n nodeIndex,\n attributeValue,\n t.stringLiteral(attributeName),\n ),\n );\n break;\n }\n}\n\n/**\n * Process Immediately Invoked Function Expression (IIFE) optimization\n *\n * @param {t.Expression} node - Expression node to be processed\n * @returns {t.Expression} Optimized expression\n */\nexport function processIIFEExpression(node: t.Expression): t.Expression {\n // Check if it's an IIFE (Immediately Invoked Function Expression)\n if (\n t.isCallExpression(node) &&\n (t.isArrowFunctionExpression(node.callee) || t.isFunctionExpression(node.callee)) &&\n node.arguments.length === 0\n ) {\n const callee = node.callee;\n const body = callee.body;\n\n // Handle block-level function body { return value; }\n if (t.isBlockStatement(body)) {\n // Only handle simple cases with single return statement\n if (body.body.length === 1) {\n const statement = body.body[0];\n if (t.isReturnStatement(statement) && statement.argument) {\n // Directly return the return value, remove IIFE wrapper\n return statement.argument;\n }\n }\n }\n // Handle arrow function shorthand form (() => expression)\n else if (t.isExpression(body)) {\n // Directly return expression body, remove function wrapper\n return body;\n }\n }\n\n // Not IIFE or cannot be safely optimized, keep original expression\n return node;\n}\n\n/**\n * Create parameter array for DOM insertion operations\n *\n * @param {DynamicContent} dynamicContent - Dynamic content object (contains node and position info)\n * @param {t.Identifier} nodesIdentifier - Node mapping array identifier\n * @param {number[]} indexMap - Pre-calculated index mapping array\n * @returns {t.Expression[]} Parameter array for insert function call\n */\nexport function createInsertArguments(\n dynamicContent: DynamicContent,\n nodesIdentifier: t.Identifier,\n indexMap: number[] | Map<number, number>,\n): t.Expression[] {\n // Validate required parent node index\n if (isNil(dynamicContent.parentIndex)) {\n throw new Error('Dynamic content missing valid parent node index');\n }\n\n // Get parent node position in mapping array\n const parentPosition = findIndexPosition(dynamicContent.parentIndex, indexMap);\n if (parentPosition === -1) {\n throw new Error(\n `Cannot find parent node index in index mapping: ${dynamicContent.parentIndex}`,\n );\n }\n\n // Build basic parameter list\n const argExpressions: t.Expression[] = [\n // Target parent node reference: nodes[parentPosition]\n t.memberExpression(nodesIdentifier, t.numericLiteral(parentPosition), true),\n\n // CallExpression not be use call function\n // Content lazy function: () => dynamicContent (implements on-demand calculation)\n t.isCallExpression(dynamicContent.node) ||\n t.isArrowFunctionExpression(dynamicContent.node) ||\n t.isFunctionExpression(dynamicContent.node)\n ? dynamicContent.node\n : t.arrowFunctionExpression([], dynamicContent.node),\n ];\n\n // Handle insert position node (for insertBefore operation)\n if (dynamicContent.before !== null) {\n const beforePosition = findIndexPosition(dynamicContent.before, indexMap);\n if (beforePosition === -1) {\n throw new Error(`Cannot find before node index in index mapping: ${dynamicContent.before}`);\n }\n\n // Add before node reference: nodes[beforePosition]\n argExpressions.push(\n t.memberExpression(nodesIdentifier, t.numericLiteral(beforePosition), true),\n );\n }\n\n return argExpressions;\n}\n\n/**\n * Generate dynamic child node insertion code\n *\n * @param {DynamicContent[]} dynamicChildren - Dynamic child node collection\n * @param {t.Statement[]} statements - Statement collection (for adding generated code)\n * @param {State} state - Plugin state (contains import mapping)\n * @param {t.Identifier} nodesId - Node mapping array identifier\n * @param {number[]} indexMap - Index mapping array\n */\nfunction generateDynamicChildrenCode(\n dynamicChildren: DynamicContent[],\n statements: t.Statement[],\n state: PluginState,\n nodesId: t.Identifier,\n indexMap: number[],\n): void {\n // Ensure insert function is imported\n addImport(importMap.insert);\n\n // Create insertion statement for each dynamic content\n for (const dynamicContent of dynamicChildren) {\n // Special handling for IIFE expressions, optimize performance\n const processedNode = processIIFEExpression(dynamicContent.node);\n\n // Create insertion parameters\n const insertArgs = createInsertArguments(\n { ...dynamicContent, node: processedNode },\n nodesId,\n indexMap,\n );\n\n // Add insertion statement to code\n const insertCall = t.callExpression(state.imports.insert, insertArgs);\n statements.push(t.expressionStatement(insertCall));\n }\n}\n\n/**\n * Generate dynamic attribute setting code\n *\n * Redesigned as unified memoizedEffect architecture:\n * 1. Collect all reactive attributes\n * 2. Generate a unified memoizedEffect to handle all updates\n * 3. Set non-reactive attributes directly\n *\n * @param {Array<{ props: Record<string, unknown>; parentIndex: number | null }>} dynamicProps - Dynamic attribute collection\n * @param {t.Statement[]} statements - Statement collection (for adding generated code)\n * @param {State} state - Plugin state (contains import mapping and configuration)\n * @param {t.Identifier} nodesId - Node mapping array identifier\n * @param {number[]} indexMap - Index mapping array\n */\nfunction generateDynamicPropsCode(\n dynamicProps: Array<{\n props: Record<string, unknown>;\n parentIndex: number | null;\n }>,\n statements: t.Statement[],\n state: PluginState,\n nodesId: t.Identifier,\n indexMap: number[],\n): void {\n // Process each dynamic attribute item\n for (const propItem of dynamicProps) {\n const { parentIndex, props } = propItem;\n\n // Skip invalid parent node indices\n if (parentIndex === null) {\n continue;\n }\n\n // Find parent node position in index mapping\n const parentIndexPosition = indexMap.indexOf(parentIndex);\n if (parentIndexPosition === -1) {\n warn(`Cannot find parent node index: ${parentIndex}`);\n continue;\n }\n\n // Process each dynamic attribute of the node\n for (const [attrName, attrValue] of Object.entries(props)) {\n try {\n // Handle bind attributes (update:xxx) which are arrays [getter, setter]\n if (attrName.startsWith(`${UPDATE_PREFIX}:`) && Array.isArray(attrValue)) {\n // Type guard: ensure array elements are expressions\n if (\n attrValue.length === 2 &&\n t.isExpression(attrValue[0]) &&\n t.isExpression(attrValue[1])\n ) {\n generateSpecificAttributeCode(\n attrName,\n attrValue as any, // Pass array as-is, createAttributeStatement will spread it\n nodesId,\n parentIndexPosition,\n statements,\n state,\n );\n }\n continue;\n }\n\n // Process by attribute name classification\n // Type guard: attrValue must be Expression for dynamic props\n if (!t.isExpression(attrValue as t.Node)) {\n continue;\n }\n\n if (attrName.startsWith('on')) {\n // Handle event attributes (onClick, onMouseOver, etc.)\n addEventListenerStatement(\n attrName,\n attrValue as t.Expression,\n nodesId,\n parentIndexPosition,\n statements,\n state,\n );\n } else {\n // Non-reactive attributes, set directly\n generateSpecificAttributeCode(\n attrName,\n attrValue as t.Expression,\n nodesId,\n parentIndexPosition,\n statements,\n state,\n );\n }\n } catch (error) {\n // When single attribute processing fails, log error but continue processing other attributes\n warn(`Attribute processing failed (${attrName}): ${error}`);\n }\n }\n }\n\n // Reactive operations have been added to global collector, not processed here\n}\n\n/**\n * Generates a unified memoized effect to handle all reactive operations.\n * This function takes in an array of reactive operations, and a statement array\n * to which the generated code will be appended.\n * The generated code will create a memoized effect that will be called with the initial state\n * object, and will return the final state object.\n *\n * @param reactiveOperations An array of reactive operations to be processed.\n * @param statements The statement array to which the generated code will be appended.\n * @param state The plugin state.\n * @param nodesId The identifier of the nodes mapping.\n */\nfunction generateUnifiedMemoizedEffect(\n reactiveOperations: ReactiveOperation[],\n statements: t.Statement[],\n state: PluginState,\n nodesId: t.Identifier,\n indexMap: number[],\n): void {\n addImport(importMap.memoEffect);\n\n // Create variable declarations\n const variableDeclarations = reactiveOperations.map((op, index) => {\n const attrValue = op.attrValue;\n return t.variableDeclarator(t.identifier(`_v$${index}`), attrValue);\n });\n\n // Create update statements\n const updateStatements = reactiveOperations.map((op, index) => {\n // Get parent node position in mapping array\n const parentPosition = findIndexPosition(op.nodeIndex, indexMap);\n if (parentPosition === -1) {\n throw new Error(`Cannot find parent node index in index mapping: ${op.nodeIndex}`);\n }\n\n const varName = t.identifier(`_v$${index}`);\n const elementRef = t.memberExpression(nodesId, t.numericLiteral(parentPosition), true);\n\n let domOperationCall: t.CallExpression;\n\n // Handle attribute operations\n if (op.setFunction.name === 'patchAttr') {\n domOperationCall = t.callExpression(op.setFunction.value, [\n elementRef,\n t.stringLiteral(op.attrName),\n t.memberExpression(t.identifier('_p$'), t.identifier(op.propKey)),\n t.assignmentExpression(\n '=',\n t.memberExpression(t.identifier('_p$'), t.identifier(op.propKey)),\n varName,\n ),\n ]);\n } else {\n domOperationCall = t.callExpression(op.setFunction.value, [\n elementRef,\n t.memberExpression(t.identifier('_p$'), t.identifier(op.propKey)),\n t.assignmentExpression(\n '=',\n t.memberExpression(t.identifier('_p$'), t.identifier(op.propKey)),\n varName,\n ),\n ]);\n }\n\n // _v$0 !== _p$.c0 && (_p$.c0 = _v$0, _$patchClass(_el$, _v$0));\n return t.expressionStatement(\n t.logicalExpression(\n '&&',\n t.binaryExpression(\n '!==',\n varName,\n t.memberExpression(t.identifier('_p$'), t.identifier(op.propKey)),\n ),\n domOperationCall,\n ),\n );\n });\n\n // Create effect function body\n const effectBody = t.blockStatement([\n // var _v$0 = expr1, _v$1 = expr2, ...;\n t.variableDeclaration('var', variableDeclarations),\n // All update statements\n ...updateStatements,\n // return _p$;\n t.returnStatement(t.identifier('_p$')),\n ]);\n\n // Create effect function\n const effectFunction = t.arrowFunctionExpression([t.identifier('_p$')], effectBody);\n\n // Create initial state object\n const initialStateProperties = reactiveOperations.map(op =>\n t.objectProperty(t.identifier(op.propKey), t.identifier('undefined')),\n );\n const initialState = t.objectExpression(initialStateProperties);\n\n // Create memoizedEffect call\n const memoizedEffectCall = t.callExpression(state.imports.memoEffect, [\n effectFunction,\n initialState,\n ]);\n\n statements.push(t.expressionStatement(memoizedEffectCall));\n}\n\n/**\n * Recursively generates a static HTML template from a given TreeNode.\n *\n * This function is the main entry point for static template generation.\n * It handles all node types and delegates to specialized functions for\n * complex cases like normal elements and children processing.\n *\n * **Processing Rules:**\n * - Component/Fragment nodes: Return empty string (handled dynamically)\n * - Text nodes: Concatenate all text content\n * - Comment nodes: Generate HTML comment placeholder `<!>`\n * - Normal/SVG nodes: Delegate to gstForNormal for full element generation\n * - Other nodes: Delegate to gstForChildren for children-only generation\n *\n * @param {TreeNode} node - The TreeNode to generate the template from\n * @returns {string} The generated static HTML template string\n *\n * @example\n * ```typescript\n * // <div class=\"container\">Hello</div>\n * generateStaticTemplate(node)\n * // Returns: '<div class=\"container\">Hello</div>'\n * ```\n */\nfunction generateStaticTemplate(node: TreeNode): string {\n if (!node || node.type === NODE_TYPE.COMPONENT) {\n return '';\n }\n\n switch (node.type) {\n case NODE_TYPE.TEXT:\n // Text node: directly concatenate all child content\n return Array.isArray(node.children) ? node.children.join('') : '';\n\n case NODE_TYPE.COMMENT:\n // Comment node: generate HTML comment placeholder\n return '<!>';\n\n case NODE_TYPE.NORMAL:\n case NODE_TYPE.SVG:\n return gstForNormal(node);\n\n default:\n return gstForChildren(node);\n }\n}\n\n/**\n * Generates a static HTML template for a normal HTML element.\n *\n * This function handles the complete generation of HTML elements including:\n * - Opening tag with attributes\n * - Children content (recursively generated)\n * - Closing tag (or self-closing syntax)\n *\n * **Processing Steps:**\n * 1. Validate node has a tag name\n * 2. Serialize static attributes to HTML string\n * 3. Generate opening tag with attributes\n * 4. Handle self-closing tags (e.g., `<img />`, `<br />`)\n * 5. Recursively generate children content\n * 6. Generate closing tag\n *\n * @param {TreeNode} node - The TreeNode representing a normal HTML element\n * @returns {string} The generated static HTML template string\n *\n * @example\n * ```typescript\n * // <div class=\"container\"><span>Hello</span></div>\n * gstForNormal(node)\n * // Returns: '<div class=\"container\"><span>Hello</span></div>'\n * ```\n *\n * @example\n * ```typescript\n * // <img src=\"logo.png\" />\n * gstForNormal(node)\n * // Returns: '<img src=\"logo.png\"/>'\n * ```\n */\nfunction gstForNormal(node: TreeNode): string {\n if (!node.tag) {\n return gstForChildren(node);\n }\n\n const attributes = serializeAttributes(node.props);\n const startTag = `<${node.tag}${attributes ? ` ${attributes}` : ''}`;\n\n if (node.selfClosing) {\n return `${startTag}/>`;\n }\n\n return `${startTag}>${gstForChildren(node)}</${node.tag}>`;\n}\n/**\n * Recursively generates static HTML template for children nodes.\n *\n * This function processes all children of a TreeNode and concatenates their\n * static HTML representations. It handles both TreeNode children and string\n * literals, skipping dynamic content (which is handled separately).\n *\n * **Processing Rules:**\n * - TreeNode children: Recursively call generateStaticTemplate\n * - String children: Include directly in output\n * - Other types: Skip (dynamic content handled elsewhere)\n *\n * @param {TreeNode} node - The TreeNode whose children to process\n * @returns {string} The concatenated static HTML template of all children\n *\n * @example\n * ```typescript\n * // <div>Hello <span>World</span></div>\n * gstForChildren(divNode)\n * // Returns: 'Hello <span>World</span>'\n * ```\n */\nfunction gstForChildren(node: TreeNode): string {\n if (!node.children || !node.children.length) {\n return '';\n }\n\n const childTemplates: string[] = [];\n\n for (const child of node.children) {\n if (isObject(child)) {\n const childTemplate = generateStaticTemplate(child as TreeNode);\n childTemplates.push(childTemplate);\n } else if (isString(child)) {\n childTemplates.push(child);\n }\n }\n\n return childTemplates.join('');\n}\n\n/**\n * Collects all dynamic content from a TreeNode for client-side rendering.\n *\n * This function performs a depth-first traversal of the tree to identify and\n * collect all dynamic content that needs runtime processing. It separates\n * dynamic content into three categories:\n *\n * **Collection Categories:**\n * 1. **props**: Dynamic attributes that need one-time setting\n * 2. **children**: Dynamic child nodes (expressions, components, fragments)\n * 3. **operations**: Reactive attributes that need memoized updates\n *\n * **Processing Strategy:**\n * - Static content is already in the template (handled by generateStaticTemplate)\n * - Dynamic content is collected here for runtime code generation\n * - Reactive attributes are identified and added to operations for memoEffect\n *\n * @param {TreeNode} node - The root TreeNode to start collection from\n * @returns {DynamicCollection} Object containing all collected dynamic content\n *\n * @example\n * ```typescript\n * // <div class={cls}>{message}<button onClick={handler}>Click</button></div>\n * const dynamic = generateDynamic(node);\n * // dynamic.operations: [{ nodeIndex: 1, attrName: 'class', ... }]\n * // dynamic.children: [{ node: message, parentIndex: 1, ... }]\n * // dynamic.props: [{ props: { onClick: handler }, parentIndex: 2 }]\n * ```\n */\nfunction generateDynamic(node: TreeNode) {\n const dynamicCollection = {\n props: [],\n children: [],\n operations: [],\n };\n\n function walk(node: TreeNode, parentNode?: TreeNode) {\n processNodeDynamic(dynamicCollection, node, parentNode);\n\n // Skip recursive child processing for Fragment nodes\n // Fragment children are already included in the component expression\n // created by processNodeDynamic, so walking them again would cause duplicates\n if (node.type === NODE_TYPE.COMPONENT || node.type === NODE_TYPE.FRAGMENT) {\n return; // Skip processing component children in parent context\n }\n\n if (node.children && node.children.length) {\n node.children.forEach(child => {\n if (isTreeNode(child)) {\n walk(child as TreeNode, node);\n }\n });\n }\n }\n\n walk(node);\n\n return dynamicCollection;\n}\n\n/**\n * Processes a single TreeNode to extract dynamic content.\n *\n * This function is the core of dynamic content collection. It examines each node\n * and categorizes its dynamic aspects into the appropriate collection:\n *\n * **Node Type Processing:**\n * - **COMPONENT/FRAGMENT**: Create component expression and add to children\n * - **EXPRESSION**: Extract expression and add to children\n * - **TEXT**: Skip (already in static template)\n * - **NORMAL/SVG**: Process dynamic attributes\n *\n * **Attribute Classification:**\n * - **Reactive attributes**: Dynamic values that need memoized updates (class, style, etc.)\n * - **Event handlers**: onClick, onInput, etc. (added to props)\n * - **Bind directives**: update:xxx (added to props)\n * - **Static attributes**: Already in template (skipped)\n *\n * @param {DynamicCollection} dynamicCollection - The collection to populate\n * @param {TreeNode} node - The current node to process\n * @param {TreeNode} [parentNode] - The parent node (for context)\n *\n * @example\n * ```typescript\n * // <div class={cls}>{message}</div>\n * processNodeDynamic(collection, divNode, null);\n * // collection.operations: [{ attrName: 'class', attrValue: cls, ... }]\n * // collection.children: [{ node: message, ... }]\n * ```\n */\nfunction processNodeDynamic(dynamicCollection, node: TreeNode, parentNode?: TreeNode): void {\n const { children, props, operations } = dynamicCollection;\n\n switch (node.type) {\n case NODE_TYPE.COMPONENT: {\n // Prepare component attributes\n const componentProps = { ...node.props, children: node.children };\n\n // Create component call expression\n const componentExpr = createComponentExpression(node, componentProps);\n\n // Add to dynamic content list\n children.push({\n index: node.index,\n node: componentExpr,\n before: findBeforeIndex(node, parentNode as TreeNode),\n parentIndex: parentNode?.index ?? null,\n });\n break;\n }\n\n case NODE_TYPE.EXPRESSION:\n // Ensure child node array is not empty and first element is an expression\n if (node.children && node.children.length > 0) {\n const firstChild = node.children[0];\n // Handle JavaScript expression nodes\n if (isObject(firstChild) && t.isNode(firstChild) && t.isExpression(firstChild)) {\n // TODO: maybe support map\n // if (isMapCall(firstChild)) {\n // const mapCall = firstChild as t.CallExpression;\n // const list = (mapCall.callee as t.MemberExpression).object;\n // const callback = mapCall.arguments[0];\n\n // addImport(importMap.For);\n\n // let childrenProp = callback;\n // // Wrap callback if it uses index to unwrap the getter\n // if (\n // (t.isArrowFunctionExpression(callback) || t.isFunctionExpression(callback)) &&\n // callback.params.length > 1 &&\n // checkHasJSXReturn(callback)\n // ) {\n // const itemParam = path.scope.generateUidIdentifier('item');\n // const indexParam = path.scope.generateUidIdentifier('index');\n // childrenProp = t.arrowFunctionExpression(\n // [itemParam, indexParam],\n // t.callExpression(callback as t.Expression, [\n // itemParam,\n // t.callExpression(indexParam, []),\n // ]),\n // );\n // }\n // // 特殊处理,默认tree不处理map,所有这里要添加一个tag\n // node.tag = 'For';\n // children.push({\n // index: node.index,\n // node: createComponentExpression(node, {\n // each: list,\n // children: childrenProp,\n // }),\n // before: findBeforeIndex(node, parentNode as TreeNode),\n // parentIndex: parentNode?.index ?? null,\n // });\n // } else {\n children.push({\n index: node.index,\n node: t.arrowFunctionExpression([], firstChild),\n before: findBeforeIndex(node, parentNode as TreeNode),\n parentIndex: parentNode?.index ?? null,\n });\n // }\n }\n // Handle JSX elements/fragments in expression containers\n else if (isObject(firstChild) && t.isNode(firstChild) && t.isJSXElement(firstChild)) {\n // Treat JSX elements in expression containers as components\n // This usually occurs in: {<SomeComponent />} or {<></>}\n children.push({\n index: node.index,\n node: createComponentExpression(node, { children: [firstChild] }),\n before: findBeforeIndex(node, parentNode as TreeNode),\n parentIndex: parentNode?.index ?? null,\n });\n }\n }\n break;\n\n // Text nodes don't need dynamic processing (already handled in template stage)\n case NODE_TYPE.TEXT:\n break;\n\n default:\n // Handle regular HTML nodes with dynamic attributes\n // Dynamic attributes include: event handlers, conditional rendering attributes, dynamic styles, etc.\n if (node.props && Object.keys(node.props).length > 0) {\n const currentProps = {};\n\n for (const [attrName, attrValue] of Object.entries(node.props)) {\n // Type guard: check if attrValue is a Node before checking if it's dynamic\n const isReactive =\n t.isNode(attrValue) &&\n isDynamicExpression(attrValue) &&\n !startsWith(attrName, `${UPDATE_PREFIX}:`) &&\n !startsWith(attrName, EVENT_ATTR_NAME) &&\n attrName !== REF_KEY;\n\n // support bind:value\n if (startsWith(attrName, `${UPDATE_PREFIX}:`)) {\n const name = attrName.split(':')[1];\n const setFunction = getSetFunctionForAttribute();\n addImport(importMap[setFunction.name as keyof typeof importMap]);\n\n operations.push({\n nodeIndex: node?.index,\n attrName: name,\n attrValue: (attrValue as any)[0],\n setFunction,\n propKey: generatePropKey(),\n });\n }\n if (isReactive && t.isExpression(attrValue)) {\n // Collect reactive attributes for unified processing later\n const setFunction = getSetFunctionForAttribute(attrName);\n addImport(importMap[setFunction.name as keyof typeof importMap]);\n\n operations.push({\n nodeIndex: node?.index,\n attrName,\n attrValue,\n setFunction,\n propKey: generatePropKey(attrName),\n });\n } else {\n currentProps[attrName] = attrValue;\n }\n }\n\n if (Object.keys(currentProps).length > 0) {\n props.push({\n props: currentProps,\n parentIndex: node?.index ?? null,\n });\n }\n }\n break;\n }\n}\n","/**\n * Node Type Enum\n * @description Defines the types of different nodes in the JSX tree, used for internal processing and optimization.\n */\nexport enum NODE_TYPE {\n // normal\n NORMAL = 0,\n // component\n COMPONENT = 1,\n // text\n TEXT = 2,\n // fragment\n FRAGMENT = 3,\n // expression\n EXPRESSION = 4,\n // svg\n SVG = 5,\n // comment\n COMMENT = 6,\n // spread\n SPREAD = 7,\n}\n\n/**\n * Element Flags Enum\n * @description Defines special flags for HTML elements, used for rendering optimization.\n */\nexport enum ELEMENT_FLAGS {\n // Self-closing tag (e.g. <img />)\n SELF_CLOSING = 0,\n // Within SVG scope (e.g. <svg><path/></svg>)\n IN_SVG_SCOPE = 1,\n}\n\n/**\n * Key name for the CSS class attribute\n */\nexport const CLASS_NAME = 'class';\n\n/**\n * Key name for the Style attribute\n */\nexport const STYLE_NAME = 'style';\n\n/**\n * Prefix for event attributes\n */\nexport const EVENT_ATTR_NAME = 'on';\n\n/**\n * Prefix for update attributes\n */\nexport const UPDATE_PREFIX = 'update';\n\n/**\n * Tag name for Fragment components\n */\nexport const FRAGMENT_NAME = 'Fragment';\n\n/**\n * Key name for the Children attribute\n */\nexport const CHILDREN_NAME = 'children';\n\nexport const REF_KEY = 'ref';\n/**\n * Key name for the Spread attribute\n */\nexport const SPREAD_NAME = '_$spread$';\n\n/**\n * Key name for the Create Component attribute\n */\nexport const CREATE_COMPONENT_NAME = 'createComponent';\n\n/**\n * data-idx regex for hydration\n */\nexport const DATA_IDX_REGEX = /^\\d+-\\d+$/;\n\n/**\n * Bind regex for bind attributes\n */\nexport const BIND_REG = /^bind:.+/;\nexport const BUILT_IN_COMPONENTS = ['Fragment', 'Portal', 'Suspense', 'For'];\n","import { type NodePath, types as t } from '@babel/core';\nimport {\n isArray,\n isBoolean,\n isMap,\n isNull,\n isNumber,\n isObject,\n isString,\n isUndefined,\n} from '@estjs/shared';\n\nimport {\n CHILDREN_NAME,\n CLASS_NAME,\n FRAGMENT_NAME,\n NODE_TYPE,\n SPREAD_NAME,\n STYLE_NAME,\n} from './constants';\nimport { createTree, isTreeNode } from './tree';\nimport { getContext } from './context';\nimport type { Expression } from '@babel/types';\nimport type { TreeNode } from './tree';\nimport type { JSXChild, JSXElement } from '../types';\n\n/**\n * Dynamic Content Interface\n * @description Represents JSX content that needs dynamic processing, such as components, expressions, etc.\n */\nexport interface DynamicContent {\n /** Dynamic content type identifier */\n type?: string;\n /** Node index */\n index: number;\n /** AST node expression */\n node: t.Expression;\n /** Previous node index, used to determine insertion position */\n before: number | null;\n /** Template index */\n templateIndex?: number;\n /** Parent node index */\n parentIndex?: number | null;\n /** Attribute name, used for dynamic attributes */\n attrName?: string;\n}\n\n/**\n * Dynamic Content Collection Interface\n * @description Used to type-strengthen dynamic content collection results\n */\nexport interface DynamicCollection {\n /** Dynamic child node list */\n children: DynamicContent[];\n /** Dynamic attribute list */\n props: Array<{\n /** Attribute object */\n props: Record<string, unknown>;\n /** Parent node index */\n parentIndex: number | null;\n }>;\n /** Reactive operations list */\n operations: Array<{\n nodeIndex: number;\n attrName: string;\n attrValue: any;\n setFunction: {\n name: string;\n value: any;\n };\n propKey: string;\n }>;\n}\n\n/**\n * Determine whether a string is a component name\n *\n * Identifies custom components by checking naming conventions:\n * - First letter capitalized (e.g., MyComponent)\n * - Contains dot notation (e.g., SomeLibrary.Component)\n * - Starts with non-alphabetic character (e.g., _Component)\n *\n\n * @param {string} tagName - The tag name to check\n * @returns {boolean} `true` if the tag represents a component, `false` otherwise\n */\nexport function isComponentName(tagName: string): boolean {\n if (!tagName) {\n return false;\n }\n\n const firstCharCode = tagName.charCodeAt(0);\n\n // 65-90 are uppercase A-Z, 97-122 are lowercase a-z\n if (firstCharCode >= 65 && firstCharCode <= 90) {\n return true; // Uppercase letter\n }\n\n // Check for dot or colon notation\n const dotIndex = tagName.indexOf('.');\n const colonIndex = tagName.indexOf(':');\n\n if (dotIndex !== -1 || colonIndex !== -1) {\n // Split and check segments\n const segments = tagName.split(/[:.]/);\n const len = segments.length;\n for (let i = 0; i < len; i++) {\n const segment = segments[i];\n if (segment.length > 0) {\n const segmentCharCode = segment.charCodeAt(0);\n if (segmentCharCode >= 65 && segmentCharCode <= 90) {\n return true;\n }\n }\n }\n }\n\n // Check for non-alphabetic first character (like _Component)\n return !(firstCharCode >= 97 && firstCharCode <= 122); // Not lowercase letter\n}\n\n/**\n * Get tag name from JSX element node\n *\n * Extracts the tag name from JSX elements and fragments, handling both\n * regular HTML elements and custom components.\n *\n * @param {t.JSXElement | t.JSXFragment} node - AST node of JSX element or fragment\n * @returns {string} Tag name string (e.g., 'div', 'MyComponent', 'Fragment')\n */\nexport const getTagName = (node: t.JSXElement | t.JSXFragment): string => {\n // Handle JSX Fragment (<>...</> or <Fragment>...</Fragment>) case\n if (t.isJSXFragment(node)) {\n return FRAGMENT_NAME;\n }\n\n // Handle regular JSX elements (like <div>, <MyComponent.Nested/>)\n const tag = node.openingElement.name;\n return jsxElementNameToString(tag);\n};\n\n/**\n * Convert JSX element name to string representation\n * @description Supports JSXIdentifier (e.g., MyComponent), JSXMemberExpression (e.g., SomeLibrary.SomeComponent)\n * and JSXNamespacedName (e.g., namespace:ComponentName) forms.\n * @param {t.JSXMemberExpression | t.JSXIdentifier | t.JSXNamespacedName} node - AST node of JSX element name.\n * @returns {string} String representation of JSX element name.\n */\nexport function jsxElementNameToString(\n node: t.JSXMemberExpression | t.JSXIdentifier | t.JSXNamespacedName | t.MemberExpression,\n): string {\n if (t.isJSXMemberExpression(node)) {\n // Process member expression, recursively join (e.g., SomeLibrary.SomeComponent)\n return `${jsxElementNameToString(node.object)}.${jsxElementNameToString(node.property)}`;\n }\n\n if (t.isMemberExpression(node)) {\n const objectName = jsxElementNameToString(\n node.object as unknown as t.JSXIdentifier | t.JSXMemberExpression,\n );\n const propertyName = jsxElementNameToString(\n node.property as unknown as t.JSXIdentifier | t.JSXMemberExpression,\n );\n return `${objectName}.${propertyName}`;\n }\n\n if (t.isJSXIdentifier(node) || t.isIdentifier(node)) {\n // Process identifier (e.g., MyComponent)\n return node.name;\n }\n\n // Process namespace expression (e.g., namespace:ComponentName)\n const namespace = node.namespace?.name ?? '';\n const name = node.name?.name ?? '';\n if (!namespace) {\n return name;\n }\n if (!name) {\n return namespace;\n }\n return `${namespace}:${name}`;\n}\n\n/**\n * Determine if the given path represents a text child node in JSX expression\n * @description Check if the node is of type JSXText, StringLiteral, or NumericLiteral.\n * @param {NodePath<JSXChild>} path - AST path of potential text child node.\n * @returns {boolean} `true` if the path represents a text child node, `false` otherwise.\n */\nexport function isTextChild(path: NodePath<JSXChild>): boolean {\n if (path.isJSXExpressionContainer && path.isJSXExpressionContainer()) {\n const expression = path.get('expression');\n if (expression.isJSXText() || expression.isStringLiteral() || expression.isNumericLiteral()) {\n return true;\n }\n }\n if (path.isJSXText && path.isJSXText()) {\n return true;\n }\n if (path.isStringLiteral && path.isStringLiteral()) {\n return true;\n }\n if (path.isNullLiteral && path.isNullLiteral()) {\n return true;\n }\n return false;\n}\n\n/**\n * Trim text content of JSXText node\n * @description Remove excess whitespace and line breaks, merge multiple spaces into a single space.\n *\n\n * @param {t.JSXText} node - JSXText AST node.\n * @returns {string} Trimmed text content.\n */\nexport function textTrim(node: t.JSXText): string {\n if (!node || !node.value) return '';\n\n return node.value.trim();\n}\n\n/**\n * Determine if a JSX child node is valid\n * @description Ignore text nodes that contain only whitespace.\n * @param {NodePath<JSXChild>} path - AST path of JSX child node.\n * @returns {boolean} `true` if the node is valid, `false` otherwise.\n */\nexport function isValidChild(path: NodePath<JSXChild>): boolean {\n const regex = /^\\s*$/;\n if (t.isStringLiteral(path.node)) {\n return !regex.test((path.node as t.StringLiteral).value);\n }\n if (t.isJSXText(path.node)) {\n return !regex.test((path.node as t.JSXText).value);\n }\n return Object.keys(path.node).length > 0; // For other types of nodes, consider valid if they have content\n}\n\n/**\n * Get raw text content of a node without trimming\n * @description Extract raw text from JSXText or JSXExpressionContainer without trimming whitespace.\n * @param {NodePath<JSXChild>} path - AST path of JSX child node.\n * @returns {string} Raw text content of the node, or empty string if not a text node.\n */\nexport function getRawNodeText(path: NodePath<JSXChild>): string {\n if (path.isJSXText()) {\n return path.node.value || '';\n }\n if (path.isJSXExpressionContainer()) {\n const expression = path.get('expression');\n if (expression.isStringLiteral() || expression.isNumericLiteral()) {\n return String(expression.node.value);\n }\n }\n return '';\n}\n\n/**\n * Get text content of a node\n * @description Extract text from JSXText or JSXExpressionContainer containing StringLiteral/NumericLiteral.\n * @param {NodePath<JSXChild>} path - AST path of JSX child node.\n * @returns {string} Text content of the node, or empty string if not a text node.\n */\nexport function getNodeText(path: NodePath<JSXChild>): string {\n if (path.isJSXText()) {\n return textTrim(path.node);\n }\n if (path.isJSXExpressionContainer()) {\n const expression = path.get('expression');\n if (expression.isStringLiteral() || expression.isNumericLiteral()) {\n return String(expression.node.value);\n }\n }\n return '';\n}\n\n/**\n * Set text content of JSX child node\n * @description Update value of JSXText or StringLiteral/NumericLiteral in JSXExpressionContainer.\n * @param {NodePath<JSXChild>} path - AST path of JSX child node.\n * @param {string} text - Text content to set.\n */\nexport function setNodeText(path: NodePath<JSXChild>, text: string): void {\n if (path.isJSXText()) {\n path.node.value = text;\n }\n if (path.isJSXExpressionContainer()) {\n const expression = path.get('expression');\n if (expression.isStringLiteral() || expression.isNumericLiteral()) {\n expression.replaceWith(t.stringLiteral(text));\n }\n }\n}\n\n/**\n * Optimize child node list, merge adjacent text nodes\n * @description Traverse child node list, merge consecutive text nodes into one, reduce number of generated AST nodes, improve rendering performance.\n * @param {NodePath<JSXChild>[]} children - Original array of child node paths.\n * @returns {NodePath<JSXChild>[]} Optimized array of child node paths.\n */\nexport function optimizeChildNodes(children: NodePath<JSXChild>[]): NodePath<JSXChild>[] {\n const mergedWithExpression = new WeakSet<NodePath<JSXChild>>();\n\n return children.reduce<NodePath<JSXChild>[]>((acc, cur) => {\n if (isValidChild(cur)) {\n const lastChild = acc.at(-1);\n if (!lastChild) {\n acc.push(cur as NodePath<JSXChild>);\n return acc;\n }\n\n const lastIsPlainText = lastChild.isJSXText?.() ?? false;\n const currentIsPlainText = cur.isJSXText?.() ?? false;\n\n if (\n lastIsPlainText &&\n t.isJSXExpressionContainer(cur.node) &&\n (cur.get('expression').isStringLiteral() || cur.get('expression').isNumericLiteral()) &&\n !mergedWithExpression.has(lastChild)\n ) {\n const mergedText = getRawNodeText(lastChild) + getRawNodeText(cur);\n setNodeText(lastChild, mergedText);\n mergedWithExpression.add(lastChild);\n return acc;\n }\n\n if (lastIsPlainText && currentIsPlainText && !mergedWithExpression.has(lastChild)) {\n const mergedText = getRawNodeText(lastChild) + getRawNodeText(cur);\n setNodeText(lastChild, mergedText);\n return acc;\n }\n\n acc.push(cur as NodePath<JSXChild>);\n }\n return acc;\n }, []);\n}\n\n/**\n * Deep check if property in ObjectExpression contains dynamic values\n * Recursively examines object expressions to detect dynamic attributes\n *\n * @example\n * // dynamic attribute\n * <div class={{'a': a}} />\n *\n * // dynamic object dynamic attribute\n * <div class={{'a': {b: c}}} />\n *\n * // conditional expression\n * <div class={a ? 'a' : 'b'} />\n *\n * // deep conditional expression\n * <div class={a:{b:{c:c ? 'c' : 'd'}}} />\n *\n * // string expression\n * <div class={{with:`${a}px`}} />\n *\n * // string dynamic object expression\n * <div class={{with:`${a ? '1' : '2'}px`}} />\n *\n * @param {ObjectExpression} node\n * @return {boolean}\n */\nexport function deepCheckObjectDynamic(node: t.ObjectExpression): boolean {\n if (!t.isObjectExpression(node)) return false;\n\n let dynamic = false;\n\n // Recursive traversal\n function walk(current) {\n if (dynamic) return; // Already hit, early pruning\n\n // 1. Common 'dynamic' nodes: directly set to true\n if (\n t.isIdentifier(current) ||\n t.isCallExpression(current) ||\n t.isMemberExpression(current) ||\n t.isConditionalExpression(current) ||\n t.isTemplateLiteral(current) ||\n t.isBinaryExpression(current) ||\n t.isUpdateExpression(current) ||\n t.isUnaryExpression(current) ||\n t.isAwaitExpression(current) ||\n t.isYieldExpression(current) ||\n t.isTaggedTemplateExpression(current)\n ) {\n dynamic = true;\n return;\n }\n\n // 2. Object / Array expressions continue searching downward\n if (t.isObjectExpression(current)) {\n current.properties.forEach(prop => {\n if (t.isObjectProperty(prop)) walk(prop.value);\n if (t.isSpreadElement(prop)) walk(prop.argument);\n });\n return;\n }\n\n if (t.isArrayExpression(current)) {\n current.elements.forEach(el => el && walk(el));\n return;\n }\n\n // 3. Other nodes (Literal, RegExpLiteral...) are considered static, no processing needed\n }\n\n walk(node);\n return dynamic;\n}\n\n/**\n * Processes object expressions in JSX attributes, handling both conditional expressions\n * and static class/style attribute extraction (when isCt=true)\n *\n * @param propName - Current property name being processed (e.g., \"class\" or \"style\")\n * @param objectExpr - The object expression AST node to process\n * @param propsCollection - Collection of component props to modify\n * @param isClassOrStyleAttr - Flag indicating if processing class/style attribute (special handling)\n * @returns Generated class/style string when processing class/style attributes\n */\nexport function processObjectExpression(\n propName: string,\n objectExpr: t.ObjectExpression,\n propsCollection: Record<string, unknown>,\n isClassOrStyleAttr = false,\n): string {\n let classStyleString = '';\n\n // Handle conditional properties - let unified architecture handle\n if (deepCheckObjectDynamic(objectExpr)) {\n // Directly store object expression, let unified memoizedEffect architecture handle\n propsCollection[propName] = objectExpr;\n }\n // Special handling for static class/style attributes\n else if (isClassOrStyleAttr) {\n classStyleString = objectExpr.properties\n .filter((property): property is t.ObjectProperty => t.isObjectProperty(property))\n .reduce((acc, property) => {\n const key = t.isIdentifier(property.key)\n ? property.key.name\n : t.isStringLiteral(property.key)\n ? property.key.value\n : String(property.key);\n\n // Ensure value is static string literal\n if (t.isStringLiteral(property.value)) {\n return `${acc}${key}:${property.value.value};`;\n }\n return acc;\n }, '');\n\n // Remove original prop as we've converted it to string\n delete propsCollection[propName];\n }\n\n return classStyleString;\n}\n\n/**\n * Get the name of JSX attribute\n * @description Extract string name from JSXAttribute node.\n * @param {t.JSXAttribute} attribute - AST node of JSX attribute.\n * @returns {string} Name of the attribute.\n * @throws {Error} If attribute type is not supported.\n */\nexport function getAttrName(attribute: t.JSXAttribute): string {\n if (t.isJSXIdentifier(attribute.name)) {\n return attribute.name.name;\n }\n if (t.isJSXNamespacedName(attribute.name)) {\n return `${attribute.name.namespace.name}:${attribute.name.name.name}`;\n }\n\n return '';\n}\n\n/**\n * Serialize HTML element attributes to string\n * @description Serialize JSX attribute object to HTML attribute string\n * @param {Record<string, unknown>|undefined} attributes - Attribute object\n * @return {string} Serialized HTML attribute string\n */\nexport function serializeAttributes(attributes: Record<string, unknown> | undefined): string {\n if (!attributes || !isObject(attributes)) {\n return '';\n }\n\n let attributesString = '';\n let classNames = '';\n let styleString = '';\n\n // Process all attributes\n for (const [attrName, attrValue] of Object.entries(attributes)) {\n // Process class attribute\n if (attrName === CLASS_NAME && isString(attrValue)) {\n classNames += ` ${attrValue}`;\n delete attributes[attrName];\n }\n // Process style attribute\n else if (attrName === STYLE_NAME && isString(attrValue)) {\n styleString += `${attrValue}${attrValue.at(-1) === ';' ? '' : ';'}`;\n delete attributes[attrName];\n }\n // Process boolean attributes\n else if (attrValue === true) {\n attributesString += ` ${attrName}`;\n delete attributes[attrName];\n }\n // Ignore false attributes\n else if (attrValue === false) {\n delete attributes[attrName];\n }\n // Process string and number attributes\n else if (isString(attrValue) || isNumber(attrValue)) {\n attributesString += ` ${attrName}=\"${attrValue}\"`;\n delete attributes[attrName];\n }\n // Process conditional expressions - let unified architecture handle\n else if (t.isConditionalExpression(attrValue as t.Node)) {\n // Store conditional expressions directly, let unified memoizedEffect architecture handle\n // This way all reactive attributes will be handled uniformly in generateDynamicPropsCode\n attributes[attrName] = attrValue;\n }\n // Process object expressions\n else if (t.isObjectExpression(attrValue as t.ObjectExpression)) {\n const result = processObjectExpression(\n attrName,\n attrValue as t.ObjectExpression,\n attributes,\n attrName === CLASS_NAME || attrName === STYLE_NAME,\n );\n\n if (result) {\n if (attrName === CLASS_NAME) {\n classNames += ` ${result}`;\n }\n if (attrName === STYLE_NAME) {\n styleString += `${result}${result.at(-1) === ';' ? '' : ';'}`;\n }\n }\n }\n }\n\n // Add class and style attributes\n if (classNames.trim()) {\n attributesString += ` ${CLASS_NAME}=\"${classNames.trim()}\"`;\n }\n if (styleString.trim()) {\n attributesString += ` ${STYLE_NAME}=\"${styleString.trim()}\"`;\n }\n\n return attributesString;\n}\n\n/**\n * Find the marker node index where dynamic content should be inserted\n * @description Used to determine the insertion position of dynamic nodes within a parent node, handling two main scenarios:\n * 1. Followed by static node: Use the following static node as insertion marker.\n * 2. Followed by dynamic content: Need to create a comment node `<!>` as insertion marker.\n *\n * Typical use case analysis table:\n * +---------------------+-------------------------------+---------------------------+-----------------------+\n * | Template Structure | Compiled Structure | Insertion Logic | Return Value |\n * +---------------------+-------------------------------+---------------------------+-----------------------+\n * | `<div>{v}</div>` | `<div></div>` | Append to end | `null` (no following node) |\n * | `<div>A{v}B</div>` | `<div>A<!>B</div>` | Insert before `<!>` | Comment node index |\n * | `<div>{v}<span/></div>` | `<div><span/></div>` | Insert before `span` | `span` node index |\n * | `<div>{v}{v}</div>` | `<div><!></div>` | Insert in order before `<!>` | Comment node index |\n * | `<div><p/>{v}</div>` | `<div><p/></div>` | Append to end | `null` |\n * | `<div>{v}<!></div>` | `<div><!></div>` | Insert before existing `<!>` | Comment node index |\n * | `<div>{v1}{v2}<br/></div>` | `<div><br/></div>` | Insert `v2` before `br`, then insert `v1` | `br` node index |\n * | `<div>{v}<!-- --></div>` | `<div><!-- --></div>` | Insert before comment node | Comment node index |\n * | `<div>{v}<Component/></div>` | `<div><Component/></div>` | Insert before component | Component node index |\n * +---------------------+-------------------------------+---------------------------+-----------------------+\n *\n * @param {TreeNode} currentNode - Current dynamic node (expression/fragment/component).\n * @param {TreeNode} parentNode - Parent node of the current node.\n * @returns {number | null} Index of the target marker node, or `null` if no suitable position.\n */\nexport function findBeforeIndex(currentNode: TreeNode, parentNode: TreeNode): number | null {\n // Boundary condition check: If parent node has no children, or current node is the last child, no need for prefix marker\n if (!parentNode?.children?.length || currentNode.isLastChild) {\n return null;\n }\n\n const children = parentNode.children;\n const childrenLength = children.length;\n\n // Find current node index\n let nodeIndex = -1;\n for (let i = 0; i < childrenLength; i++) {\n if (children[i] === currentNode) {\n nodeIndex = i;\n break;\n }\n }\n\n // If node not found or is last child, return null\n if (nodeIndex === -1 || nodeIndex === childrenLength - 1) {\n return null;\n }\n\n // Search forward for the nearest non-dynamic sibling node as insertion marker\n for (let searchIndex = nodeIndex + 1; searchIndex < childrenLength; searchIndex++) {\n const siblingNode = children[searchIndex] as TreeNode;\n const siblingType = siblingNode.type;\n\n // Check if node is static (not dynamic)\n if (\n siblingType !== NODE_TYPE.EXPRESSION &&\n siblingType !== NODE_TYPE.FRAGMENT &&\n siblingType !== NODE_TYPE.COMPONENT\n ) {\n return siblingNode.index; // Found static node, return its index\n }\n }\n\n return null; // If all following nodes are dynamic or there are no nodes, append to the end (return null)\n}\n\n/**\n * Collect DOM node indices that need to be mapped\n * @description Extract DOM node indices that need to be referenced on the client side from dynamic children and dynamic attributes.\n *\n * @param {DynamicContent[]} dynamicChildren - Dynamic children collection.\n * @param {Array<{props: Record<string, unknown>; parentIndex: number | null}>} dynamicProps - Dynamic attribute collection.\n * @returns {number[]} De-duplicated and sorted index list, representing DOM nodes that need to be mapped.\n */\nexport function collectNodeIndexMap(\n dynamicChildren: DynamicContent[],\n dynamicProps: Array<{\n props: Record<string, unknown>;\n parentIndex: number | null;\n }>,\n extraIndices: number[] = [],\n): number[] {\n // Use Set for automatic de-duplication\n const indexSet = new Set<number>(extraIndices);\n\n const childrenLength = dynamicChildren.length;\n for (let i = 0; i < childrenLength; i++) {\n const item = dynamicChildren[i];\n const parentIndex = item.parentIndex;\n const beforeIndex = item.before;\n\n // Add parent index if valid (not null/undefined)\n if (parentIndex !== null && parentIndex) {\n indexSet.add(parentIndex);\n }\n // Add before index if valid (not null/undefined)\n if (beforeIndex !== null && beforeIndex) {\n indexSet.add(beforeIndex);\n }\n }\n\n // Collect parent node indices of dynamic attributes\n const propsLength = dynamicProps.length;\n for (let i = 0; i < propsLength; i++) {\n const parentIndex = dynamicProps[i].parentIndex;\n if (parentIndex !== null && parentIndex) {\n indexSet.add(parentIndex);\n }\n }\n\n // Convert Set to sorted array\n return Array.from(indexSet).sort((a, b) => a - b);\n}\n\n/**\n * Find the position of an index in the mapping array\n * @description In a pre-generated DOM node index mapping array, find the actual position of a specific target index.\n * Used at client runtime to quickly locate DOM nodes by index.\n * @param {number} targetIndex - Original index of the target node (TreeNode.index).\n * @param {number[]} indexMap - Pre-collected and sorted DOM node index mapping array.\n * @returns {number} Position of the target index in the `indexMap` array (0-based index), returns `-1` if not found.\n *\n * Use case examples:\n * 1. `targetIndex=1`, `indexMap=[1,2,3]` => returns `0`\n * 2. `targetIndex=2`, `indexMap=[1,2,3]` => returns `1`\n * 3. `targetIndex=3`, `indexMap=[1,2,3]` => returns `2`\n * 4. `targetIndex=4`, `indexMap=[1,2,3]` => returns `-1` (not found)\n */\nexport function findIndexPosition(\n targetIndex: number,\n indexMap: number[] | Map<number, number>,\n): number {\n if (isArray(indexMap)) {\n return indexMap.indexOf(targetIndex);\n }\n if (isMap(indexMap)) {\n const position = indexMap.get(targetIndex);\n return isNumber(position) ? position : -1;\n }\n return -1;\n}\n\n/**\n * Insert comment nodes (type: COMMENT) into TreeNode.children where needed\n * @param {TreeNode} node - Current TreeNode to process.\n */\nexport function processTextElementAddComment(node: TreeNode): void {\n if (!node.children || node.children.length === 0) {\n return;\n }\n\n const children = node.children as TreeNode[];\n const childrenLength = children.length;\n\n // Recursively process all child nodes first\n for (let i = 0; i < childrenLength; i++) {\n const child = children[i];\n // Only recursively process when child is TreeNode type\n if (isTreeNode(child)) {\n processTextElementAddComment(child);\n }\n }\n\n // Check if comments need to be inserted\n let needsComments = false;\n for (let i = 0; i < childrenLength - 1; i++) {\n if (shouldInsertComment(children as TreeNode[], i)) {\n needsComments = true;\n break;\n }\n }\n\n // If no comments needed, skip array reconstruction\n if (!needsComments) {\n return;\n }\n\n // Build new children array with comments inserted\n const newChildren: (TreeNode | string | JSXChild)[] = [];\n for (let i = 0; i < childrenLength; i++) {\n newChildren.push(children[i]);\n\n // Check if comment should be inserted after current node\n if (shouldInsertComment(children as TreeNode[], i)) {\n newChildren.push({\n type: NODE_TYPE.COMMENT,\n isComment: true,\n children: [],\n index: -1,\n parentIndex: node.index,\n } as TreeNode);\n }\n }\n\n // Replace children array\n node.children = newChildren;\n}\n\n/**\n * Determine if comment node should be inserted\n * @description Assists the `processTextElementAddComment` function, determines if comment node should be inserted at given position.\n * Rule: Current node is an expression, and is immediately followed by non-HTML/SVG element (i.e., another dynamic content or text node).\n * @param {(TreeNode | string)[]} children - Array of child nodes of parent node.\n * @param {number} idx - Index of current child node to check in the array.\n * @returns {boolean} `true` if comment node needs to be inserted, `false` otherwise.\n */\nfunction shouldInsertComment(children: (TreeNode | string | JSXChild)[], idx: number): boolean {\n const cur = children[idx];\n const next = children[idx + 1];\n\n // Only process expression nodes, because comment nodes are used to separate adjacent dynamic content\n if (!cur || !isObject(cur) || cur.type !== NODE_TYPE.EXPRESSION) {\n return false;\n }\n\n // If it's the last node, or is immediately followed by HTML/SVG element, comment node is not needed\n if (\n !next ||\n (isObject(next) && (next.type === NODE_TYPE.NORMAL || next.type === NODE_TYPE.SVG))\n ) {\n return false;\n }\n\n // Other cases (expression followed by text, another expression, Fragment or Component), comment node should be inserted\n return true;\n}\n\n/**\n * Normalize JSX props into a single flat record.\n * 1. Multiple occurrences of `class` / `className` / `style` are merged into a single string (static) or array (dynamic).\n * 2. Collect multiple object spreads as unified `SPREAD_NAME` record to avoid extra traversal.\n */\nexport function normalizeProps(raw: Record<string, unknown>): Record<string, unknown> {\n const normalized: Record<string, unknown> = {};\n\n const classBuffer: string[] = [];\n const styleBuffer: string[] = [];\n\n for (const [key, value] of Object.entries(raw)) {\n // Handle both 'class' and 'className' (React compatibility)\n if (key === CLASS_NAME || key === 'className') {\n if (isString(value)) classBuffer.push(value);\n else {\n // If there's already a dynamic class expression, keep the last one\n normalized[CLASS_NAME] = value; // Keep dynamic expressions as-is\n }\n continue;\n }\n\n if (key === STYLE_NAME) {\n if (isString(value)) styleBuffer.push(value);\n else normalized[STYLE_NAME] = value;\n continue;\n }\n\n if (key === SPREAD_NAME) {\n // If spread already exists, merge directly as array\n if (!normalized[SPREAD_NAME]) normalized[SPREAD_NAME] = [];\n (normalized[SPREAD_NAME] as unknown[]).push(value);\n continue;\n }\n\n normalized[key] = value;\n }\n\n if (classBuffer.length) normalized[CLASS_NAME] = classBuffer.join(' ').trim();\n if (styleBuffer.length) {\n const s = styleBuffer.map(str => (str.endsWith(';') ? str : `${str};`)).join('');\n normalized[STYLE_NAME] = s;\n }\n\n return normalized;\n}\n/**\n * Check if node is a map call expression\n * @param node - The node to check\n * @returns `true` if node is a map call expression, `false` otherwise\n */\nexport function isMapCall(node: t.Node): boolean {\n return (\n t.isCallExpression(node) &&\n t.isMemberExpression(node.callee) &&\n t.isIdentifier(node.callee.property) &&\n node.callee.property.name === 'map' &&\n node.arguments.length === 1\n );\n}\n\n/**\n * Create props object expression\n * @description Convert attribute record to AST object expression\n * @param {Record<string, unknown>} propsData - Attribute data\n * @param {Function} transformJSX - JSX conversion function\n * @return {t.ObjectExpression} Generated object expression\n */\nexport function createPropsObjectExpression(\n propsData: Record<string, unknown>,\n transformJSX: (path: NodePath<JSXElement>, tree: TreeNode) => t.Expression,\n): t.ObjectExpression {\n const objectProperties: (t.ObjectProperty | t.SpreadElement | t.ObjectMethod)[] = [];\n\n const propsToProcess = normalizeProps(propsData);\n\n for (const propName in propsToProcess) {\n const propValue = propsToProcess[propName];\n // Skip empty children\n if (propName === CHILDREN_NAME && (!propValue || (isArray(propValue) && !propValue.length))) {\n continue;\n }\n const astValue = convertValueToASTNode(propValue as any, transformJSX);\n\n // Process spread attribute\n if (propName === SPREAD_NAME) {\n objectProperties.push(t.spreadElement(astValue));\n } else {\n // Check if dynamic and not a function\n // if (isDynamicExpression(astValue) && !t.isFunction(astValue)) {\n // objectProperties.push(\n // t.objectMethod(\n // 'get',\n // t.identifier(propName),\n // [],\n // t.blockStatement([t.returnStatement(astValue)]),\n // ),\n // );\n // } else {\n objectProperties.push(t.objectProperty(t.stringLiteral(propName), astValue));\n // }\n }\n }\n\n return t.objectExpression(objectProperties);\n}\n\n/**\n * Convert JavaScript value to corresponding AST node\n * @description Convert value to corresponding AST expression node based on value type\n * @param {unknown} value - Value to convert\n * @param {Function} transformJSX - JSX conversion function\n * @return {t.Expression} Corresponding AST node\n */\nexport function convertValueToASTNode(\n value: JSXChild | TreeNode | Expression,\n transformJSX: (path: NodePath<JSXElement>, tree: TreeNode) => t.Expression,\n): Expression {\n // If it's already an AST node, return directly\n if (t.isExpression(value as Expression)) {\n return value as Expression;\n }\n\n if (isArray(value)) {\n return t.arrayExpression(value.map(item => convertValueToASTNode(item, transformJSX)));\n }\n\n if (isObject(value)) {\n if (isTreeNode(value) && hasPureStringChildren(value)) {\n const stringContent = extractStringChildren(value);\n return t.stringLiteral(stringContent);\n }\n\n if (\n value.type === NODE_TYPE.COMPONENT ||\n value.type === NODE_TYPE.NORMAL ||\n value.type === NODE_TYPE.TEXT ||\n value.type === NODE_TYPE.SVG\n ) {\n const { path } = getContext();\n return transformJSX(path, value);\n }\n\n if (\n value.type === NODE_TYPE.EXPRESSION &&\n value.children &&\n isArray(value.children) &&\n value.children.length > 0\n ) {\n return convertValueToASTNode(value.children[0] as JSXChild, transformJSX);\n }\n\n if (\n t.isJSXElement(value as unknown as JSXElement) ||\n t.isJSXFragment(value as unknown as JSXElement)\n ) {\n const { path } = getContext();\n const mockNodePath = {\n node: value,\n parentPath: path, // Keep parent path reference\n scope: path.scope, // Keep scope reference\n } as unknown as NodePath<JSXElement>;\n const tree = createTree(mockNodePath);\n return transformJSX(path, tree);\n }\n\n return createPropsObjectExpression(value, transformJSX);\n }\n if (isString(value)) {\n return t.stringLiteral(value);\n }\n if (isNumber(value)) {\n return t.numericLiteral(value);\n }\n if (isBoolean(value)) {\n return t.booleanLiteral(value);\n }\n if (isUndefined(value)) {\n return t.identifier('undefined');\n }\n if (isNull(value)) {\n return t.nullLiteral();\n }\n\n return value as Expression;\n}\n/**\n * Get the setting function corresponding to the attribute\n */\nexport function getSetFunctionForAttribute(attrName?: string): {\n name: string;\n value: t.Identifier;\n} {\n const { state } = getContext();\n switch (attrName) {\n case CLASS_NAME:\n return {\n name: 'patchClass',\n value: state.imports.patchClass,\n };\n case STYLE_NAME:\n return { name: 'patchStyle', value: state.imports.patchStyle };\n default:\n return { name: 'patchAttr', value: state.imports.patchAttr };\n }\n}\n\n/**\n * Determine if an AST node should be considered dynamic for attribute evaluation.\n * Covers common JS expression types beyond Identifier, including member/call/conditional/template, etc.\n */\nexport function isDynamicExpression(node: t.Node | null | undefined): boolean {\n if (!node) return false;\n\n // Direct expression types that are dynamic\n if (\n t.isIdentifier(node) ||\n t.isMemberExpression(node) ||\n t.isOptionalMemberExpression(node) ||\n t.isCallExpression(node) ||\n t.isOptionalCallExpression(node) ||\n t.isConditionalExpression(node) ||\n t.isLogicalExpression(node) ||\n t.isTemplateLiteral(node) ||\n t.isTaggedTemplateExpression(node) ||\n t.isBinaryExpression(node) ||\n t.isUnaryExpression(node) ||\n t.isUpdateExpression(node) ||\n t.isAwaitExpression(node) ||\n t.isYieldExpression(node) ||\n t.isAssignmentExpression(node) ||\n t.isSequenceExpression(node) ||\n t.isArrowFunctionExpression(node) ||\n t.isFunctionExpression(node)\n ) {\n return true;\n }\n\n // Object/Array: deep check\n if (t.isObjectExpression(node)) {\n return deepCheckObjectDynamic(node);\n }\n if (t.isArrayExpression(node)) {\n return node.elements.some(el => el != null && t.isNode(el) && isDynamicExpression(el));\n }\n\n // Literals/null are static\n if (\n t.isStringLiteral(node) ||\n t.isNumericLiteral(node) ||\n t.isBooleanLiteral(node) ||\n t.isNullLiteral(node) ||\n t.isRegExpLiteral(node)\n ) {\n return false;\n }\n\n // Fallback: if it is some other Expression, treat as dynamic; otherwise static\n return t.isExpression(node);\n}\n\n/**\n * Detect if all children are static strings and can be output directly\n *\n * @param node - TreeNode to check\n * @returns true if all children are static strings\n */\nexport function hasPureStringChildren(node: TreeNode): boolean {\n if (!node.children || node.children.length === 0) {\n return false;\n }\n\n return node.children.every(child => {\n if (isString(child)) {\n return true;\n }\n if (isTreeNode(child) && child.type === NODE_TYPE.TEXT) {\n return true;\n }\n return false;\n });\n}\n\n/**\n * Concatenates all string children into a single string\n *\n * @param node - TreeNode with string children\n * @returns Concatenated string\n */\nexport function extractStringChildren(node: TreeNode): string {\n if (!node.children || node.children.length === 0) {\n return '';\n }\n\n return node.children\n .map(child => {\n if (isString(child)) {\n return child;\n }\n if (isTreeNode(child) && child.type === NODE_TYPE.TEXT && child.children) {\n return child.children.join('');\n }\n return '';\n })\n .join('');\n}\n","import { type NodePath, types as t } from '@babel/core';\nimport { isSVGTag, isSelfClosingTag, warn } from '@estjs/shared';\nimport { BIND_REG, NODE_TYPE, SPREAD_NAME, UPDATE_PREFIX } from './constants';\nimport { getAttrName, getTagName, isComponentName, optimizeChildNodes, textTrim } from './shared';\nimport type { JSXChild, JSXElement } from '../types';\n\n/**\n * TreeNode represents a unified abstraction of JSX elements in the compilation process.\n * It serves as the core intermediate representation between JSX AST and generated runtime code.\n *\n * @interface TreeNode\n *\n * @property {NODE_TYPE} type - The type of the node (NORMAL, TEXT, EXPRESSION, COMPONENT, FRAGMENT, SVG, COMMENT, SPREAD)\n * @property {string} [tag] - The tag name for HTML elements or component name for components\n * @property {number} index - Unique sequential index for DOM node location (starts from 1, skips components/expressions)\n * @property {number | null} [parentIndex] - Index of the parent node, used to establish parent-child relationships\n * @property {Record<string, unknown>} [props] - Collection of element attributes and properties\n * @property {Array<TreeNode | JSXChild | string | t.Expression>} children - Child nodes of this element\n * @property {boolean} [root] - Whether this is the root node of the tree\n * @property {boolean} [isLastChild] - Whether this is the last child of its parent\n * @property {boolean} [selfClosing] - Whether this is a self-closing tag (e.g., <img />, <br />)\n * @property {true} [_isTreeNode] - Internal marker to identify TreeNode objects (used by isTreeNode type guard)\n *\n * @example\n * ```typescript\n * // Example TreeNode for: <div class=\"container\">Hello</div>\n * {\n * type: NODE_TYPE.NORMAL,\n * tag: 'div',\n * index: 1,\n * props: { class: 'container' },\n * children: [\n * {\n * type: NODE_TYPE.TEXT,\n * children: ['Hello'],\n * index: 2,\n * _isTreeNode: true\n * }\n * ],\n * root: true,\n * _isTreeNode: true\n * }\n * ```\n */\nexport interface TreeNode {\n /** The type of the node */\n type: NODE_TYPE;\n /** The tag name for HTML elements or component name */\n tag?: string;\n /** Unique sequential index for DOM node location */\n index: number;\n /** Index of the parent node */\n parentIndex?: number | null;\n /** Collection of element attributes and properties */\n props?: Record<string, unknown>;\n /** Child nodes of this element */\n children: (TreeNode | JSXChild | string | t.Expression)[];\n /** Whether this is the root node */\n root?: boolean;\n /** Whether this is the last child of its parent */\n isLastChild?: boolean;\n /** Whether this is a self-closing tag */\n selfClosing?: boolean;\n /** Internal marker to identify TreeNode objects */\n _isTreeNode?: true;\n}\n/**\n * Creates a default TreeNode structure with initial configuration.\n *\n * This factory function provides a consistent base template for all tree nodes,\n * ensuring uniform structure and default values across the tree building process.\n *\n * @returns {TreeNode} A new TreeNode with default configuration:\n * - `root: true` - Marked as root node\n * - `type: NODE_TYPE.NORMAL` - Default to normal HTML element\n * - `tag: ''` - Empty tag name (to be filled by caller)\n * - `props: {}` - Empty properties object\n * - `children: []` - Empty children array\n * - `index: 1` - Default index (root nodes start at 1)\n * - `parentIndex: null` - No parent for root nodes\n * - `isLastChild: false` - Not marked as last child initially\n * - `selfClosing: false` - Not self-closing by default\n * - `_isTreeNode: true` - Internal marker for type checking\n *\n * @example\n * ```typescript\n * const node = createDefaultTree();\n * node.tag = 'div';\n * node.type = NODE_TYPE.NORMAL;\n * // node is now ready to be populated with actual data\n * ```\n *\n * @internal\n */\nexport function createDefaultTree(): TreeNode {\n return {\n root: true,\n type: NODE_TYPE.NORMAL,\n tag: '',\n props: {},\n children: [],\n index: 1,\n parentIndex: null,\n isLastChild: false,\n selfClosing: false,\n _isTreeNode: true,\n };\n}\n\n/**\n * Type guard to check if an unknown value is a TreeNode.\n *\n * This function provides runtime type checking for TreeNode objects by checking\n * for the presence of the internal `_isTreeNode` marker. This is more reliable\n * than checking for specific properties since TreeNode has many optional fields.\n *\n * @param {unknown} node - The value to check\n * @returns {boolean} `true` if the value is a TreeNode, `false` otherwise\n *\n * @example\n * ```typescript\n * const maybeNode: unknown = getSomeValue();\n * if (isTreeNode(maybeNode)) {\n * // TypeScript now knows maybeNode is TreeNode\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Filtering TreeNodes from mixed array\n * const mixed: Array<TreeNode | string | Expression> = [...];\n * const treeNodes = mixed.filter(isTreeNode);\n * // treeNodes is now TreeNode[]\n * ```\n */\nexport function isTreeNode(node: unknown): node is TreeNode {\n return !!(node && (node as TreeNode)._isTreeNode);\n}\n/**\n * Global tree node index counter.\n *\n * This counter is used to assign unique sequential indices to tree nodes for efficient\n * DOM node location and manipulation at runtime. The index system is crucial for the\n * `mapNodes()` runtime function to quickly locate specific DOM elements.\n *\n * **Index Assignment Rules:**\n * - Root node starts at index 1\n * - Each non-component, non-expression node gets an incremental index (2, 3, 4, ...)\n * - Component nodes do NOT get indices (they don't correspond to DOM elements)\n * - Fragment nodes do NOT get indices (they're virtual containers)\n * - Expression nodes do NOT get indices (they're dynamic content placeholders)\n *\n * **Index Usage:**\n * The indices are used to generate an `indexMap` array that maps logical positions\n * to actual DOM nodes, enabling O(1) node lookup at runtime.\n *\n * @example\n * ```typescript\n * // JSX: <div><span/>{expr}<p/></div>\n * // Indices: div=1, span=2, expr=2 (no increment), p=3\n * // indexMap: [1, 2, 3] -> [divNode, spanNode, pNode]\n * ```\n *\n * @internal\n */\nlet treeIndex = 1;\n\n/**\n * Creates a TreeNode from a JSX AST node path.\n *\n * This is the main entry point for building the Tree intermediate representation.\n * It recursively processes JSX elements and their children, assigning indices and\n * building the complete tree structure.\n *\n * **Processing Flow:**\n * 1. Create default tree node structure\n * 2. Assign index based on node type and parent context\n * 3. Determine node type (text, element, component, etc.)\n * 4. Process attributes and children recursively\n * 5. Return completed TreeNode\n *\n * **Index Assignment:**\n * - Root nodes: Reset counter to 1 and use it\n * - Child nodes: Increment counter for non-component/non-expression nodes\n * - Components/Fragments: Skip index increment (don't correspond to DOM)\n *\n * @param {NodePath<JSXElement>} path - Babel AST path to the JSX element\n * @param {TreeNode} [parentNode] - Parent TreeNode (undefined for root nodes)\n * @returns {TreeNode} The constructed TreeNode with all children processed\n *\n * @example\n * ```typescript\n * // Building a tree from JSX\n * const jsxPath = getJSXPath(); // from Babel visitor\n * const tree = createTree(jsxPath);\n * // tree now contains the complete TreeNode structure\n * ```\n *\n * @example\n * ```typescript\n * // Recursive child processing\n * const parentTree = createTree(parentPath);\n * const childTree = createTree(childPath, parentTree);\n * // childTree.parentIndex === parentTree.index\n * ```\n */\nexport function createTree(path: NodePath<JSXElement>, parentNode?: TreeNode): TreeNode {\n const treeNode = createDefaultTree();\n const tagName = getTagName(path.node);\n\n treeNode.tag = tagName;\n treeNode.type = determineNodeType(tagName);\n treeNode.selfClosing = isSelfClosingTag(tagName);\n if (parentNode) {\n const parentIsComponent = parentNode.type === NODE_TYPE.COMPONENT;\n if (parentIsComponent) {\n treeIndex = 1;\n treeNode.index = treeIndex;\n } else if (treeNode.type !== NODE_TYPE.COMPONENT) {\n treeNode.index = ++treeIndex;\n }\n\n treeNode.parentIndex = treeIndex;\n } else {\n // Root node processing: mark as root node and reset counter\n treeNode.root = true;\n treeIndex = 1;\n }\n\n // Handle text node\n if (t.isJSXText(path.node)) {\n return processJSXText(path as unknown as NodePath<t.JSXText>, treeNode);\n }\n\n // Handle JSX (including fragment)\n if (t.isJSXElement(path.node) || t.isJSXFragment(path.node)) {\n return processJSXElement(path as NodePath<JSXElement>, treeNode);\n }\n\n return treeNode;\n}\n\n/**\n * Processes a JSX element node and populates the TreeNode with element-specific data.\n *\n * This function handles the core transformation of JSX elements into TreeNode structure,\n * including tag name extraction, type determination, attribute processing, and recursive\n * child processing.\n *\n * **Processing Steps:**\n * 1. Extract tag name from JSX element\n * 2. Determine node type (NORMAL, COMPONENT, FRAGMENT, SVG)\n * 3. Check if element is self-closing\n * 4. Process all attributes and properties\n * 5. Recursively process children (if not self-closing)\n *\n * @param {NodePath<JSXElement>} path - Babel AST path to the JSX element\n * @param {TreeNode} treeNode - The TreeNode to populate with element data\n * @returns {TreeNode} The populated TreeNode with all element data\n *\n * @example\n * ```typescript\n * // Processing: <div class=\"container\"><span>Hello</span></div>\n * const node = createDefaultTree();\n * processJSXElement(path, node);\n * // node.tag === 'div'\n * // node.type === NODE_TYPE.NORMAL\n * // node.props === { class: 'container' }\n * // node.children.length === 1\n * ```\n *\n * @internal\n */\nfunction processJSXElement(path: NodePath<JSXElement>, treeNode: TreeNode): TreeNode {\n // Process JSX attributes and properties,fragment not have props\n if (!path.isJSXFragment()) {\n treeNode.props = processProps(path);\n }\n\n // Self-closing tags don't need to process children\n if (!treeNode.selfClosing) {\n // Process child elements recursively\n processChildren(path, treeNode);\n }\n\n return treeNode;\n}\n\n/**\n * Processes JSX attributes and converts them into a props object.\n *\n * This function handles all types of JSX attributes including:\n * - Boolean attributes: `<div disabled />` → `{ disabled: true }`\n * - String literals: `<div class=\"foo\" />` → `{ class: 'foo' }`\n * - Expression containers: `<div class={expr} />` → `{ class: expr }`\n * - JSX elements as props: `<div icon={<Icon />} />` → `{ icon: <Icon /> }`\n * - Spread attributes: `<div {...props} />` → `{ [SPREAD_NAME]: props }`\n * - Bind attributes: `<input bind:value={val} />` → `{ 'update:value': [val, setter] }`\n *\n * **Attribute Processing Rules:**\n * - Boolean attributes (no value) are set to `true`\n * - String/number literals are extracted as primitive values\n * - Expressions are stored as AST nodes for later code generation\n * - Spread attributes are stored under the special `SPREAD_NAME` key\n * - Bind attributes are transformed into update handlers\n *\n * @param {NodePath<JSXElement>} path - Babel AST path to the JSX element\n * @returns {Record<string, unknown>} Object mapping attribute names to their values\n *\n * @example\n * ```typescript\n * // <div class=\"container\" id={dynamicId} disabled />\n * const props = processProps(path);\n * // props = {\n * // class: 'container',\n * // id: <Identifier: dynamicId>,\n * // disabled: true\n * // }\n * ```\n *\n * @internal\n */\nfunction processProps(path: NodePath<JSXElement>): Record<string, unknown> {\n const props = {};\n const attributes = path.get('openingElement.attributes') as NodePath<\n t.JSXAttribute | t.JSXSpreadAttribute\n >[];\n\n if (!attributes.length) {\n return props;\n }\n\n attributes.forEach(attribute => {\n if (t.isJSXAttribute(attribute.node)) {\n const name = getAttrName(attribute.node);\n const value = attribute.get('value');\n\n // Boolean attribute: <div a>\n if (!value.node) {\n props[name] = true;\n } else if (value) {\n // Expression container: <div a={expr}>\n if (value.isJSXExpressionContainer()) {\n const expression = value.get('expression');\n // Literal values: <div a={1}>\n if (expression.isStringLiteral() || expression.isNumericLiteral()) {\n props[name] = expression.node.value;\n // JSX as prop: <div a={<div />}>\n } else if (expression.isJSXElement() || expression.isJSXFragment()) {\n props[name] = expression.node;\n // Other expressions: <div a={variable}>\n } else if (expression.isExpression()) {\n processPropsExpression(expression, name, props, path);\n }\n // Direct literal: <div a=\"value\">\n } else if (value.isStringLiteral() || value.isNumericLiteral()) {\n props[name] = value.node.value;\n // Direct JSX: <div a=<div />>\n } else if (value.isJSXElement() || value.isJSXFragment()) {\n props[name] = value.node;\n // Direct expression\n } else if (value.isExpression()) {\n processPropsExpression(value, name, props, path);\n }\n }\n } else if (t.isJSXSpreadAttribute(attribute.node)) {\n // Spread attribute: <div {...props}>\n props[SPREAD_NAME] = attribute.get('argument').node;\n }\n });\n\n return props;\n}\n\n/**\n * Processes a JSX attribute expression and stores it in the props object.\n *\n * This function handles special attribute types like `bind:` directives and\n * regular dynamic attributes. It determines the appropriate processing based\n * on the attribute name pattern.\n *\n * **Attribute Types:**\n * - `bind:xxx` attributes: Two-way binding directives (e.g., `bind:value`)\n * - Regular attributes: Event handlers, refs, keys, and other dynamic props\n *\n * @param {NodePath<t.Expression>} expression - The attribute value expression\n * @param {string} name - The attribute name\n * @param {Record<string, unknown>} props - The props object to populate\n * @param {NodePath<JSXElement>} path - The JSX element path (for scope access)\n *\n * @example\n * ```typescript\n * // <input bind:value={inputValue} />\n * processPropsExpression(valueExpr, 'bind:value', props, path);\n * // props['update:value'] = [inputValue, (value) => inputValue = value]\n * ```\n *\n * @internal\n */\nfunction processPropsExpression(\n expression: NodePath<t.Expression>,\n name: string,\n props: Record<string, unknown>,\n path: NodePath<JSXElement>,\n): void {\n if (BIND_REG.test(name)) {\n processPropsBind(name, expression, props, path);\n } else {\n // Normal attribute: key/ref/on*/className/etc.\n props[name] = expression.node;\n }\n}\n\n/**\n * Processes a `bind:` directive and converts it into an update handler.\n *\n * Two-way binding directives like `bind:value={variable}` are transformed into\n * a tuple containing:\n * 1. The bound expression (for reading the value)\n * 2. A setter function (for updating the value)\n *\n * This enables bidirectional data flow between the DOM and the reactive state.\n *\n * **Transformation:**\n * ```\n * bind:value={inputValue}\n * ↓\n * update:value = [\n * inputValue, // getter\n * (value) => inputValue = value // setter\n * ]\n * ```\n *\n * @param {string} name - The bind attribute name (e.g., 'bind:value')\n * @param {NodePath<t.Expression>} expression - The bound variable expression\n * @param {Record<string, unknown>} props - The props object to populate\n * @param {NodePath<JSXElement>} path - The JSX element path (for scope access)\n *\n * @example\n * ```typescript\n * // <input bind:value={inputValue} />\n * processPropsBind('bind:value', valueExpr, props, path);\n * // props['update:value'] = [\n * // <Identifier: inputValue>,\n * // (value) => inputValue = value\n * // ]\n * ```\n *\n * @internal\n */\nfunction processPropsBind(\n name: string,\n expression: NodePath<t.Expression>,\n props: Record<string, unknown>,\n path: NodePath<JSXElement>,\n): void {\n const value = path.scope.generateUidIdentifier('value');\n const bindName = name.slice(5).toLowerCase(); // Remove 'bind:' prefix\n\n // Create update handler: [getter, setter]\n props[`${UPDATE_PREFIX}:${bindName}`] = [\n expression.node, // Getter: the bound variable\n t.arrowFunctionExpression(\n [value],\n // Type guard: expression.node must be LVal for bind directive\n t.isLVal(expression.node)\n ? t.assignmentExpression('=', expression.node, value) // Setter: variable = value\n : t.assignmentExpression('=', t.identifier('_'), value), // Fallback for invalid LVal\n ),\n ];\n}\n\n/**\n * Process all child nodes of JSX element\n *\n * @param {NodePath<JSXElement>} path - AST path of JSX element node\n * @param {TreeNode} treeNode - Tree node object of parent node\n */\nfunction processChildren(path: NodePath<JSXElement>, treeNode: TreeNode): void {\n const children = path.node.children as JSXChild[];\n // Boundary check: check if child nodes exist\n if (!children || !children.length) {\n return;\n }\n const optimizedChildren = optimizeChildNodes(path.get('children'));\n\n optimizedChildren.forEach(child => {\n processChild(child, treeNode, optimizedChildren.length === 1);\n });\n}\n\nfunction processChild(child: NodePath<JSXChild>, treeNode: TreeNode, isLastChild: boolean): void {\n // jsx\n if (t.isJSXElement(child.node) || t.isJSXFragment(child.node)) {\n const childNode = createTree(child as NodePath<JSXElement>, treeNode);\n childNode.isLastChild = isLastChild;\n treeNode.children.push(childNode);\n return;\n }\n // expression\n if (t.isJSXExpressionContainer(child.node)) {\n processChildExpressionContainer(\n child as NodePath<t.JSXExpressionContainer>,\n treeNode,\n isLastChild,\n );\n return;\n }\n // text\n if (t.isJSXText(child.node)) {\n processJSXChildText(child as NodePath<t.JSXText>, treeNode, isLastChild);\n return;\n }\n // spread\n if (t.isJSXSpreadChild(child.node)) {\n processChildSpread(child as NodePath<t.JSXSpreadChild>, treeNode, isLastChild);\n return;\n }\n}\n\nfunction processChildExpressionContainer(\n child: NodePath<t.JSXExpressionContainer>,\n treeNode: TreeNode,\n isLastChild: boolean,\n): void {\n const expression = child.get('expression');\n // string literal or numeric literal\n if (expression.isStringLiteral() || expression.isNumericLiteral()) {\n treeNode.children.push({\n type: NODE_TYPE.TEXT,\n children: [String(expression.node.value)],\n index: ++treeIndex, // Static text increments index\n parentIndex: treeNode.index,\n isLastChild,\n _isTreeNode: true,\n });\n }\n // jsx element or jsx fragment\n else if (expression.isJSXElement() || expression.isJSXFragment()) {\n const childNode = createTree(child as unknown as NodePath<JSXElement>, treeNode);\n childNode.isLastChild = isLastChild;\n treeNode.children.push(childNode);\n }\n // expression\n else if (expression.isExpression()) {\n treeNode.children.push({\n type: NODE_TYPE.EXPRESSION,\n index: treeIndex, // Expression doesn't update index because it's dynamic content\n isLastChild,\n // Type guard: expression.node is Expression in JSXExpressionContainer\n children: t.isExpression(expression.node) ? [expression.node] : [],\n parentIndex: treeNode.index,\n _isTreeNode: true,\n });\n }\n}\n/**\n * Determine whether to insert comment separator\n *\n * @param {number} childrenLength - Current number of child nodes\n * @param {TreeNode | undefined} previousNode - Previous child node\n * @returns {boolean} Whether to insert comment separator\n */\nfunction shouldInsertComment(childrenLength: number, previousNode: TreeNode | undefined): boolean {\n return !!(\n childrenLength >= 2 && // At least two child nodes\n previousNode && // Previous node exists\n previousNode.type !== NODE_TYPE.COMMENT && // Previous node is not a comment\n // Previous node is dynamic content\n (previousNode.type === NODE_TYPE.EXPRESSION || previousNode.type === NODE_TYPE.COMPONENT)\n );\n}\n\nfunction processJSXChildText(\n child: NodePath<t.JSXText>,\n treeNode: TreeNode,\n isLastChild: boolean,\n): void {\n const text = textTrim(child.node);\n\n // Ignore empty text nodes\n if (!text) {\n return;\n }\n\n const childrenLength = treeNode.children.length;\n const previousNode = treeNode.children[childrenLength - 1] as TreeNode | undefined;\n\n // Check if comment node needs to be inserted as separator\n if (shouldInsertComment(childrenLength, previousNode)) {\n const commentNode: TreeNode = {\n type: NODE_TYPE.COMMENT,\n children: [],\n index: ++treeIndex,\n _isTreeNode: true,\n };\n treeNode.children.push(commentNode);\n }\n\n // Create text node\n const textNode: TreeNode = {\n type: NODE_TYPE.TEXT,\n children: [text],\n index: ++treeIndex,\n isLastChild,\n _isTreeNode: true,\n };\n treeNode.children.push(textNode);\n}\n/**\n * Handle as array children\n * @param child\n * @param treeNode\n * @param isLastChild\n */\nfunction processChildSpread(\n child: NodePath<JSXChild>,\n treeNode: TreeNode,\n isLastChild: boolean,\n): void {\n const spreadExpression = child.get('expression');\n\n treeNode.children.push({\n type: NODE_TYPE.SPREAD,\n // Type guard: spreadExpression.node is Expression in JSXSpreadChild\n children: t.isExpression(spreadExpression.node) ? [spreadExpression.node] : [],\n index: treeIndex, // Note: doesn't increment here because this is dynamic content\n parentIndex: treeNode.index,\n isLastChild,\n _isTreeNode: true,\n });\n}\n\n/**\n * Determine JSX node type\n *\n * Type judgment priority (high to low):\n * 1. **COMPONENT**: Custom component (first letter capitalized or contains dot)\n * 3. **SVG**: SVG-related tags (svg, path, circle, etc.)\n * 4. **NORMAL**: Regular HTML elements (div, span, p, etc.)\n *\n * @param {NodePath<JSXElement>} path - JSX element path\n * @param {string} tagName - Tag name\n * @returns {NODE_TYPE} Node type enum value\n */\nfunction determineNodeType(tagName: string): NODE_TYPE {\n const isComponent = isComponentName(tagName);\n\n if (isComponent) {\n return NODE_TYPE.COMPONENT;\n }\n\n if (isSVGTag(tagName)) {\n return NODE_TYPE.SVG;\n }\n\n return NODE_TYPE.NORMAL;\n}\n\n/**\n * Process JSX text node and populate tree node information\n *\n * This function converts text content in JSX to tree node structure. It handles\n * text cleaning and normalization, ensuring the final generated HTML has no\n * excess whitespace and line breaks.\n *\n * Text processing logic:\n * 1. **Whitespace handling**: Use textTrim function to clean excess whitespace\n * 2. **Empty content check**: Empty text won't create child nodes\n * 3. **Type marking**: Set node type to TEXT\n * 4. **Content storage**: Store cleaned text in children array\n *\n * @param {NodePath<t.JSXText>} path - AST path of JSX text node\n * @param {TreeNode} treeNode - Tree node object to be populated\n * @returns {TreeNode} Completed tree node object\n *\n * @example\n * ```typescript\n * // JSX: <div> Hello World </div>\n * // After processing: node.children = ['Hello World']\n *\n * // JSX: <div> </div>\n * // After processing: node.children = [] (empty array)\n * ```\n */\nfunction processJSXText(path: NodePath<t.JSXText>, treeNode: TreeNode): TreeNode {\n treeNode.type = NODE_TYPE.TEXT;\n\n try {\n const textValue = textTrim(path.node);\n // Only create child nodes when valid text exists\n treeNode.children = textValue ? [textValue] : [];\n } catch (error) {\n // Error handling when text processing fails\n warn(`Text node processing failed: ${error}`);\n treeNode.children = [];\n }\n\n return treeNode;\n}\n","import { type NodePath, types as t } from '@babel/core';\nimport { isObject, isPrimitive, isString, isSymbol } from '@estjs/shared';\nimport { addImport, importMap } from '../import';\nimport { EVENT_ATTR_NAME, FRAGMENT_NAME, NODE_TYPE, UPDATE_PREFIX } from './constants';\nimport { getContext } from './context';\nimport { createPropsObjectExpression } from './shared';\nimport { type TreeNode, isTreeNode } from './tree';\nimport type { JSXElement } from '../types';\n\n/**\n * SSG Processing Result Interface\n * @description Stores template and dynamic content information in SSG mode\n */\nexport interface transformResult {\n /** Template string array */\n templates: string[];\n /** Dynamic content array */\n dynamics: Array<{\n /** Content type: text or attribute */\n type: 'text' | 'attr';\n /** Expression node */\n node: t.Expression;\n /** Attribute name (only for attr type) */\n attrName?: string;\n }>;\n}\n\nexport function transformJSXToSSG(path: NodePath<JSXElement>, treeNode: TreeNode) {\n const { state } = getContext();\n\n const result = transformTemplate(treeNode);\n const { templates, dynamics } = result;\n\n // Handle root component case\n if (treeNode.type === NODE_TYPE.COMPONENT || treeNode.type === NODE_TYPE.FRAGMENT) {\n const componentProps = { ...treeNode.props, children: treeNode.children };\n\n addImport(importMap.createComponent);\n return t.callExpression(state.imports.createComponent, [\n t.identifier(treeNode.tag as string),\n createPropsObjectExpression(componentProps, transformJSXToSSG),\n ]);\n }\n\n // Create render arguments\n const args: t.Expression[] = [];\n\n // Add template if exists\n if (templates && templates.length > 0) {\n addImport(importMap.template);\n const tmplId = path.scope.generateUidIdentifier('_tmpl$');\n\n // create template string array expression\n const templateNode = t.arrayExpression(templates.map(str => t.stringLiteral(str)));\n state.declarations.push(t.variableDeclarator(tmplId, templateNode));\n\n args.push(tmplId);\n }\n\n // Create render call parameters\n args.push(t.callExpression(state.imports.getHydrationKey, []));\n // Add necessary imports\n addImport(importMap.render);\n addImport(importMap.getHydrationKey);\n\n // Attributes should be placed before text content\n const textDynamics = dynamics.filter(d => d.type === 'text');\n const attrDynamics = dynamics.filter(d => d.type === 'attr');\n\n // Add attribute dynamic content\n attrDynamics.forEach(dynamic => {\n args.push(dynamic.node);\n });\n\n // Add text dynamic content\n textDynamics.forEach(dynamic => {\n args.push(dynamic.node);\n });\n\n // Create render call\n return t.callExpression(state.imports.render, args);\n}\n\nfunction transformTemplate(treeNode: TreeNode) {\n const result: transformResult = {\n templates: [],\n dynamics: [],\n };\n\n // Recursively process nodes\n walkTreeNode(treeNode, result);\n\n return result;\n}\n\nfunction walkTreeNode(treeNode: TreeNode, result: transformResult) {\n if (!treeNode) {\n return;\n }\n\n switch (treeNode.type) {\n case NODE_TYPE.COMPONENT:\n case NODE_TYPE.FRAGMENT:\n handleComponent(treeNode, result);\n break;\n\n case NODE_TYPE.EXPRESSION:\n handleExpression(treeNode, result);\n break;\n\n case NODE_TYPE.TEXT:\n handleText(treeNode, result);\n break;\n\n case NODE_TYPE.NORMAL:\n case NODE_TYPE.SVG:\n handleElement(treeNode, result);\n break;\n\n case NODE_TYPE.COMMENT:\n addTemplate(result, '<!>', true);\n break;\n\n default:\n // Handle unknown node types gracefully\n if (treeNode.children && treeNode.children.length > 0) {\n processChildren(treeNode.children as TreeNode[], result);\n }\n break;\n }\n}\n/**\n * Add content to template\n */\nexport const addTemplate = (\n result: transformResult,\n content: string,\n join: boolean = false,\n): void => {\n if (result.templates.length === 0) {\n result.templates.push(content);\n } else {\n if (join) {\n result.templates[result.templates.length - 1] += content;\n } else {\n result.templates.push(content);\n }\n }\n};\n/**\n * Handle component for SSG\n */\nconst handleComponent = (node: TreeNode, result: transformResult): void => {\n // Add placeholder for component\n result.templates.push('');\n\n const { state } = getContext();\n\n // Create component props\n const componentProps = { ...node.props };\n if (node.children.length) {\n componentProps.children = node.children;\n }\n\n addImport(importMap.createComponent);\n\n // Create component expression\n const componentExpr = t.callExpression(state.imports.createComponent, [\n t.identifier(node.tag as string),\n createPropsObjectExpression(componentProps, transformJSXToSSG),\n ]);\n\n // Add to dynamic content\n result.dynamics.push({\n type: 'text',\n node: componentExpr,\n });\n};\n\n/**\n * Handle expression for SSG\n */\nconst handleExpression = (node: TreeNode, result: transformResult): void => {\n if (!node.children || node.children.length === 0) {\n return;\n }\n\n const firstChild = node.children[0];\n\n // Break template at expression location\n result.templates.push('');\n\n // Process various types of expressions\n if (isPrimitive(firstChild)) {\n // Primitive value processing\n const { state } = getContext();\n addImport(importMap.escapeHTML);\n\n result.dynamics.push({\n type: 'text',\n node: t.callExpression(state.imports.escapeHTML, [t.valueToNode(firstChild)]),\n });\n // TODO: need fix type\n } else if (isObject(firstChild)) {\n // AST expression node processing\n const exprNode = firstChild as t.Expression;\n\n // Process special case for map function calls\n if (\n t.isCallExpression(exprNode) &&\n t.isMemberExpression(exprNode.callee) &&\n exprNode.arguments.length > 0\n ) {\n const mapCallback = exprNode.arguments[0];\n\n if (\n (t.isArrowFunctionExpression(mapCallback) || t.isFunctionExpression(mapCallback)) &&\n mapCallback.body\n ) {\n // Check if it returns JSX element\n let jsxElement: t.JSXElement | undefined = undefined;\n\n if (t.isJSXElement(mapCallback.body)) {\n jsxElement = mapCallback.body;\n } else if (t.isBlockStatement(mapCallback.body)) {\n const returnStmt = mapCallback.body.body.find(stmt => t.isReturnStatement(stmt));\n if (\n returnStmt &&\n t.isReturnStatement(returnStmt) &&\n returnStmt.argument &&\n t.isJSXElement(returnStmt.argument)\n ) {\n jsxElement = returnStmt.argument;\n }\n } else if (\n t.isParenthesizedExpression(mapCallback.body) &&\n t.isJSXElement(mapCallback.body.expression)\n ) {\n jsxElement = mapCallback.body.expression;\n }\n\n // Process JSX element\n if (jsxElement) {\n const { state } = getContext();\n const tagName =\n jsxElement.openingElement.name.type === 'JSXIdentifier'\n ? jsxElement.openingElement.name.name\n : '';\n\n // Extract props\n const props: Record<string, any> = {};\n jsxElement.openingElement.attributes.forEach(attr => {\n if (t.isJSXAttribute(attr)) {\n const name = attr.name.name as string;\n if (t.isJSXExpressionContainer(attr.value)) {\n props[name] = attr.value.expression;\n } else if (t.isStringLiteral(attr.value)) {\n props[name] = attr.value.value;\n } else if (attr.value === null) {\n props[name] = true;\n }\n } else if (t.isJSXSpreadAttribute(attr)) {\n props._$spread$ = attr.argument;\n }\n });\n\n if (tagName === FRAGMENT_NAME) {\n addImport(importMap.Fragment);\n const newCallback = t.arrowFunctionExpression(\n mapCallback.params,\n t.callExpression(state.imports.Fragment, [\n createPropsObjectExpression(props, transformJSXToSSG),\n ]),\n );\n exprNode.arguments[0] = newCallback;\n } else if (tagName && tagName[0] === tagName[0].toUpperCase()) {\n addImport(importMap.createComponent);\n const newCallback = t.arrowFunctionExpression(\n mapCallback.params,\n t.callExpression(state.imports.createComponent, [\n t.identifier(tagName),\n createPropsObjectExpression(props, transformJSXToSSG),\n ]),\n );\n exprNode.arguments[0] = newCallback;\n }\n }\n }\n }\n\n // Add to dynamic content\n result.dynamics.push({\n type: 'text',\n node: exprNode,\n });\n }\n};\n\n/**\n * Handle text for SSG\n */\nconst handleText = (node: TreeNode, result: transformResult): void => {\n if (node.children && node.children.length > 0) {\n addTemplate(result, node.children.join(''), true);\n }\n};\n\n/**\n * Handle element for SSG\n */\nconst handleElement = (node: TreeNode, result: transformResult): void => {\n // Build start tag\n let openTag = `<${node.tag} data-idx=\"${node.index}\"`;\n\n // Process attributes\n const { staticAttrs, dynamicAttrs } = processAttributes(node.props || {});\n openTag += staticAttrs;\n\n addTemplate(result, openTag, true);\n addTemplate(result, node.selfClosing ? '/>' : '>', dynamicAttrs.length === 0);\n\n // Process children\n if (!node.selfClosing && node.children && node.children.length > 0) {\n processChildren(node.children as TreeNode[], result);\n }\n\n // Add end tag\n if (!node.selfClosing) {\n addTemplate(result, `</${node.tag}>`, true);\n }\n\n // Process dynamic attributes\n processDynamicAttributes(dynamicAttrs, result);\n};\n\n/**\n * Process children for SSG\n */\nconst processChildren = (children: (TreeNode | string)[], result: transformResult): void => {\n children.forEach(child => {\n if (isTreeNode(child)) {\n walkTreeNode(child, result);\n } else if (isString(child)) {\n addTemplate(result, child, true);\n }\n });\n};\n/**\n * Process SSG attributes\n */\nexport function processAttributes(props: Record<string, any>): {\n staticAttrs: string;\n dynamicAttrs: Array<{ name: string; value: t.Expression }>;\n} {\n let staticAttrs = '';\n const dynamicAttrs: Array<{ name: string; value: t.Expression }> = [];\n\n for (const [prop, value] of Object.entries(props)) {\n // Skip event handlers and update functions\n if (prop.startsWith(EVENT_ATTR_NAME) || prop.startsWith(UPDATE_PREFIX)) {\n continue;\n }\n\n // Process static attributes\n if (isPrimitive(value)) {\n if (value === true) {\n staticAttrs += ` ${prop}`;\n } else if (isSymbol(value)) {\n staticAttrs += ` ${prop}=\"${value.toString()}\"`;\n } else if (value !== false) {\n staticAttrs += ` ${prop}=\"${value}\"`;\n }\n }\n // Process dynamic attributes\n else if (t.isExpression(value)) {\n dynamicAttrs.push({ name: prop, value });\n }\n }\n\n return { staticAttrs, dynamicAttrs };\n}\n\n/**\n * Process dynamic attributes for SSG\n */\nconst processDynamicAttributes = (\n dynamicAttrs: Array<{ name: string; value: t.Expression }>,\n result: transformResult,\n): void => {\n dynamicAttrs.forEach(attr => {\n const { state } = getContext();\n addImport(importMap.patchAttr);\n addImport(importMap.escapeHTML);\n\n result.dynamics.push({\n type: 'attr',\n node: t.callExpression(state.imports.patchAttr, [\n t.stringLiteral(attr.name),\n t.callExpression(state.imports.escapeHTML, [attr.value]),\n t.booleanLiteral(false),\n ]),\n attrName: attr.name,\n });\n });\n};\n","import { RENDER_MODE } from '../constants';\nimport { resetContext, setContext } from './context';\nimport { transformJSXToClient } from './client';\nimport { transformJSXToSSG } from './ssg';\nimport { createTree } from './tree';\nimport type { JSXElement, RenderMode } from '../types';\nimport type { NodePath } from '@babel/core';\n\nconst transformStrategies = {\n [RENDER_MODE.CLIENT]: transformJSXToClient,\n [RENDER_MODE.SSR]: transformJSXToClient,\n [RENDER_MODE.SSG]: transformJSXToSSG,\n} as const;\n\n/**\n * Retrieves the appropriate transformation strategy for a given render mode.\n *\n * @param {RenderMode} mode - The target rendering mode\n * @returns {Function} The transformation function for the specified mode\n * @throws {Error} When an unsupported render mode is provided\n */\nconst getRenderingStrategy = (mode: RenderMode) => {\n const strategy = transformStrategies[mode];\n\n if (!strategy) {\n throw new Error(`Unsupported render mode: ${mode}`);\n }\n\n return strategy;\n};\n/**\n * Main JSX transformation function that converts JSX elements and fragments\n * into optimized runtime calls based on the configured render mode.\n *\n * @param {NodePath<JSXElement>} path - Babel AST path containing the JSX element\n * @throws {Error} When JSX transformation fails due to invalid syntax or unsupported features\n */\nexport function transformJSX(path: NodePath<JSXElement>): void {\n try {\n const mode = (path.state?.opts?.mode || RENDER_MODE.CLIENT) as RenderMode;\n\n // Get the appropriate transformation strategy for the render mode\n const strategy = getRenderingStrategy(mode);\n\n // Build a normalized tree representation of the JSX structure\n const tree = createTree(path);\n\n // Initialize transformation context with current state and path\n setContext({ state: path.state, path, operationIndex: 0 });\n\n // Apply the transformation strategy to generate optimized code\n const result = strategy(path, tree);\n\n // Replace the original JSX node with the transformed result\n path.replaceWith(result!);\n\n // Clean up transformation context to prevent memory leaks\n resetContext();\n } catch (error_) {\n // In test environment, log error but allow graceful continuation\n console.warn('JSX transformation failed in test:', { error_ });\n // Clean up context even on error\n resetContext();\n\n throw error_;\n }\n}\n","import { transformProgram } from './program';\nimport { transformProps } from './signals/props';\nimport { transformJSX } from './jsx';\nimport type { PluginObj } from '@babel/core';\n\nexport default function (): PluginObj {\n return {\n name: 'babel-plugin-essor',\n\n manipulateOptions(_, parserOpts) {\n parserOpts.plugins.push('jsx');\n },\n\n visitor: {\n Program: transformProgram,\n // props\n FunctionDeclaration: transformProps,\n ArrowFunctionExpression: transformProps,\n // JSX\n JSXElement: transformJSX,\n JSXFragment: transformJSX,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAwB,SAASA,UAAS;;;ACA1C,SAAwB,SAAS,SAAS;;;ACOnC,IAAMC,IAAYC,OACvBA,MAAQ,QAAQ,OAAOA,KAAQ;AAgB1B,IAAMC,IAAU,MAAM;AAOtB,SAASC,EAASC,GAA6B;AACpD,SAAO,OAAOA,KAAQ;AACxB;AAOO,SAASC,EAASD,GAA6B;AACpD,SAAO,OAAOA,KAAQ;AACxB;AAMO,SAASE,EAAOF,GAA2B;AAChD,SAAOA,MAAQ;AACjB;AAOO,SAASG,EAASH,GAA6B;AACpD,SAAO,OAAOA,KAAQ;AACxB;AAkCO,SAASI,EAAMC,GAA4C;AAChE,SAAOC,EAAU,KAAKD,CAAG,MAAM;AACjC;AAOO,SAASE,EAAMF,GAAuC;AAC3D,SAAOA,KAAQ;AACjB;AAuBO,IAAMG,IACXC,OAEA,CAAC,UAAU,UAAU,WAAW,UAAU,WAAW,EAAE,SAAS,OAAOA,CAAG,KAAKC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AS,MAAM,IAAI;AAGlC,SAAK,YAAY,MAAO;AAGxB,iBAAa;AAAA,EACf,SAAS,QAAQ;AAEf,YAAQ,KAAK,sCAAsC,EAAE,OAAO,CAAC;AAE7D,iBAAa;AAEb,UAAM;AAAA,EACR;AACF;;;AC7De,SAAR,gBAA+B;AACpC,SAAO;AAAA,IACL,MAAM;AAAA,IAEN,kBAAkBG,IAAG,YAAY;AAC/B,iBAAW,QAAQ,KAAK,KAAK;AAAA,IAC/B;AAAA,IAEA,SAAS;AAAA,MACP,SAAS;AAAA;AAAA,MAET,qBAAqB;AAAA,MACrB,yBAAyB;AAAA;AAAA,MAEzB,YAAY;AAAA,MACZ,aAAa;AAAA,IACf;AAAA,EACF;AACF;","names":["t","isObject","val","isArray","isString","val","isNumber","isNull","isSymbol","isMap","val","_toString","isNil","isPrimitive","val","isNull","isPlainObject","val","_toString","isUndefined","val","isBoolean","_toString","coerceArray","data","isArray","noop","startsWith","str","searchString","isString","cacheStringFunction","fn","cache","str","EMPTY_OBJ","EMPTY_ARR","hyphenateRE","kebabCase","cacheStringFunction","str","camelizeRE","camelCase","_","c","capitalize","warn","msg","args","error","msg","args","makeMap","str","map","key","val","specialBooleanAttrs","isSpecialBooleanAttr","isBooleanAttr","isKnownHtmlAttr","makeMap","isKnownSvgAttr","HTML_TAGS","SVG_TAGS","MATH_TAGS","DELEGATED_EVENTS","VOID_TAGS","SELFCLOSING_TAGS","isHTMLTag","makeMap","isSVGTag","isMathMLTag","isVoidTag","isSelfClosingTag","isDelegatedEvent","t","t","t","t","t","t","t","t","t","t","t","t","t","transformJSX","t","t","a","node","t","t","d","processChildren","_"]}