@wevu/compiler 7.12.2-dev.20261124.1 → 7.13.0-dev.20261127.1

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.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import{ROOT_PORTAL_ENABLE_MIN_SDK_VERSION,ROOT_PORTAL_MIN_SDK_VERSION,ROOT_PORTAL_TOP_LEVEL_TARGETS,WEAPP_I18N_RUNTIME_MARKER,WEAPP_VITE_RUNTIME_REACTIVITY_VIRTUAL_ID,WEAPP_VITE_RUNTIME_TEMPLATE_VIRTUAL_ID,WEAPP_VITE_RUNTIME_VIRTUAL_ID,WEVU_BINDING_MANIFEST_KEY,WEVU_CLASS_STYLE_RUNTIME_FILE,WEVU_CLASS_STYLE_RUNTIME_MODULE,WEVU_CSS_MODULES_KEY,WEVU_CSS_VARS_STYLE_KEY,WEVU_DEFINE_PAGE_MACRO,WEVU_DEFINE_PAGE_META_MACRO,WEVU_EXPRESSION_ERROR_IDENTIFIER,WEVU_FUNCTION_PROP_PATHS_KEY,WEVU_INLINE_HANDLER,WEVU_INLINE_MAP_KEY,WEVU_IS_PAGE_KEY,WEVU_JSX_ISLAND_DATA_KEY,WEVU_JSX_ISLAND_HANDLER,WEVU_JSX_ISLAND_TEMPLATE_NAME,WEVU_LAYOUT_BIND_PREFIX,WEVU_LAYOUT_HOSTS_KEY,WEVU_LAYOUT_HOST_ID_PREFIX,WEVU_LAYOUT_HOST_REF_PREFIX,WEVU_LEGACY_RENDERER_KEY,WEVU_MODEL_HANDLER,WEVU_NATIVE_DECLARATION_ADDRESS_PROP,WEVU_NATIVE_DECLARATION_EVENT,WEVU_NATIVE_DECLARATION_METHOD,WEVU_NATIVE_DOM_MODULE_ID,WEVU_NATIVE_SLOT_CONTEXT_KEY,WEVU_NATIVE_SLOT_PARENT_DATASET_ATTR,WEVU_NATIVE_SLOT_PARENT_EVENT,WEVU_NATIVE_SLOT_PARENT_METHOD,WEVU_OWNER_HANDLER,WEVU_PAGE_LAYOUT_NAME_KEY,WEVU_PAGE_LAYOUT_PROPS_KEY,WEVU_PROPS_ALIASES_KEY,WEVU_PROPS_DERIVED_KEYS_KEY,WEVU_PROPS_KEY,WEVU_ROUTER_MODULE_ID,WEVU_SCOPED_SLOT_CREATOR_KEY,WEVU_SCOPED_SLOT_OWNER_REQUIRED_KEY,WEVU_SETUP_READY_KEY,WEVU_SLOT_FALLBACK_VIRTUAL_HOST_BASE,WEVU_SLOT_FALLBACK_VIRTUAL_HOST_TAG_NAME,WEVU_SLOT_FUNCTION_TOKEN,WEVU_SLOT_NAMES_ATTR,WEVU_SLOT_NAMES_PROP,WEVU_SLOT_OWNER_ID_ATTR,WEVU_SLOT_OWNER_ID_KEY,WEVU_SLOT_OWNER_ID_PROP,WEVU_SLOT_OWNER_KEY,WEVU_SLOT_OWNER_PROXY_KEY,WEVU_SLOT_PROPS_ATTR,WEVU_SLOT_PROPS_DATA_KEY,WEVU_SLOT_PROPS_KEY,WEVU_SLOT_SCOPE_ATTR,WEVU_SLOT_SCOPE_KEY,WEVU_TEMPLATE_REFS_KEY,WEVU_TEMPLATE_REF_CLASS_PREFIX}from"@weapp-core/constants";import{TraceMap,originalPositionFor}from"@jridgewell/trace-mapping";import{ConstantTypes,ErrorCodes,NodeTypes,advancePositionWithClone,baseParse,createSimpleExpression,transformModel}from"@vue/compiler-core";import*as compilerDom from"@vue/compiler-dom";import{compile,parse}from"@vue/compiler-dom";import{LRUCache}from"lru-cache";import MagicString,{Bundle}from"magic-string";import{compileScript,compileStyleAsync,parse as parse$1}from"vue/compiler-sfc";import remapping from"@jridgewell/remapping";import{findScriptClosingTag}from"@weapp-vite/wxml/core";import{presets}from"@weapp-vite/wxml/presets";import{access,mkdir,readFile as readFile$1,rm,stat,writeFile}from"node:fs/promises";import path from"pathe";import{fileURLToPath}from"node:url";import*as t from"@weapp-vite/ast/babelTypes";import{BABEL_TS_MODULE_PARSER_OPTIONS,BABEL_TS_MODULE_PLUGINS,generate,parse as parse$3,parseJsLike,traverse}from"@weapp-vite/ast/babel";import path$1 from"node:path";import{escapeWxmlAttribute,escapeWxmlText,getMiniProgramRuntimeGlobalKeys,getMiniProgramScriptModuleOptions,getMiniProgramTemplatePreset,removeExtensionDeep,resolveMiniProgramPlatform}from"@weapp-core/shared";import{createHash}from"node:crypto";import{recursive}from"merge";import{bundleRequire}from"rolldown-require";import fs,{readFileSync}from"node:fs";import os from"node:os";import process from"node:process";import{analyzeCompilerScriptsWithNative,collectJsxImportedComponentsAndDefaultExportFromBabelAst,collectJsxTemplateTagsFromBabelExpression,collectScriptCallStringLiterals,collectScriptStringLiterals,getObjectPropertyByKey,getRenderPropertyFromComponentOptions,mayContainScriptCallOrModuleSyntax,parseJsLikeWithEngine,resolveRenderExpressionFromComponentOptions,toStaticObjectKey,unwrapTypeScriptExpression}from"@weapp-vite/ast";import postcss from"postcss";import selectorParser from"postcss-selector-parser";import{parse as parse$2}from"comment-json";import vm from"node:vm";const components=[`wxs`,`template`,`block`,`import`,`include`,`cover-image`,`cover-view`,`match-media`,`movable-area`,`movable-view`,`page-container`,`root-portal`,`scroll-view`,`swiper`,`swiper-item`,`view`,`icon`,`progress`,`rich-text`,`selection`,`text`,`button`,`checkbox`,`checkbox-group`,`editor`,`editor-portal`,`form`,`input`,`keyboard-accessory`,`label`,`picker`,`picker-view`,`picker-view-column`,`radio`,`radio-group`,`slider`,`switch`,`textarea`,`double-tap-gesture-handler`,`force-press-gesture-handler`,`horizontal-drag-gesture-handler`,`long-press-gesture-handler`,`pan-gesture-handler`,`scale-gesture-handler`,`tap-gesture-handler`,`vertical-drag-gesture-handler`,`draggable-sheet`,`grid-builder`,`grid-view`,`large-image`,`list-builder`,`list-view`,`nested-scroll-body`,`nested-scroll-header`,`open-container`,`open-data-item`,`open-data-list`,`share-element`,`snapshot`,`span`,`sticky-header`,`sticky-section`,`functional-page-navigator`,`navigator`,`audio`,`camera`,`channel-live`,`channel-video`,`image`,`live-player`,`live-pusher`,`video`,`voip-room`,`map`,`canvas`,`ad`,`ad-custom`,`official-account`,`official-account-publish`,`open-data`,`reward`,`store-coupon`,`store-gift`,`store-home`,`store-product`,`web-view`,`native-component`,`aria-component`,`navigation-bar`,`page-meta`];const builtinComponentsSet=new Set(components);function isBuiltinComponent(tag){return builtinComponentsSet.has(tag)}function createRuntimeBindingManifest(manifest,mode=`compact`){const bindings=manifest.bindings.map(binding=>({id:binding.id,outputPath:binding.outputPath,...mode===`diagnostic`&&binding.sourceFile?{sourceFile:binding.sourceFile}:{},...binding.updateMode===`exact-path`?{}:{updateMode:binding.updateMode},...binding.updateMode===`snapshot-fallback`&&binding.sourceRoots.length?{sourceRoots:binding.sourceRoots}:{},...mode===`diagnostic`&&binding.sourceLocation?{sourceLocation:binding.sourceLocation}:{}}));const features={};if(manifest.features.scopedSlots)features.scopedSlots=true;return{version:1,sourceFile:manifest.sourceFile,bindings,...Object.keys(features).length?{features}:{}}}const WE_VU_PAGE_HOOK_TO_FEATURE={onPageScroll:`enableOnPageScroll`,usePageScrollRestoration:`enableOnPageScroll`,onPullDownRefresh:`enableOnPullDownRefresh`,onReachBottom:`enableOnReachBottom`,onRouteDone:`enableOnRouteDone`,onTabItemTap:`enableOnTabItemTap`,onResize:`enableOnResize`,onShareAppMessage:`enableOnShareAppMessage`,onShareTimeline:`enableOnShareTimeline`,onAddToFavorites:`enableOnAddToFavorites`,onSaveExitState:`enableOnSaveExitState`};const WE_VU_MODULE_ID=`wevu`;const WE_VU_INTERNAL_RUNTIME_MODULE_ID=`wevu/internal-runtime`;const WE_VU_INTERNAL_REACTIVITY_MODULE_ID=`wevu/internal-reactivity`;const WE_VU_INTERNAL_TEMPLATE_MODULE_ID=`wevu/internal-template`;const WE_VU_COMPILER_RUNTIME_MODULE_ID=WEAPP_VITE_RUNTIME_VIRTUAL_ID;const WE_VU_COMPILER_REACTIVITY_MODULE_ID=WEAPP_VITE_RUNTIME_REACTIVITY_VIRTUAL_ID;const WE_VU_COMPILER_TEMPLATE_MODULE_ID=WEAPP_VITE_RUNTIME_TEMPLATE_VIRTUAL_ID;const WE_VU_RUNTIME_MODULE_IDS=[WE_VU_MODULE_ID,WE_VU_INTERNAL_RUNTIME_MODULE_ID,WE_VU_COMPILER_RUNTIME_MODULE_ID,WE_VU_COMPILER_REACTIVITY_MODULE_ID,WE_VU_COMPILER_TEMPLATE_MODULE_ID];function isWevuRuntimeModuleId(moduleId){return WE_VU_RUNTIME_MODULE_IDS.includes(moduleId)}function isWevuPageFeatureModuleId(moduleId){return isWevuRuntimeModuleId(moduleId)||moduleId===`wevu/router`||moduleId===`wevu/dev/router`}const WE_VU_RUNTIME_APIS={createApp:`createApp`,createWevuComponent:`createWevuComponent`,createWevuScopedSlotComponent:`createWevuScopedSlotComponent`,defineAppSetup:`defineAppSetup`,defineComponent:`defineComponent`,setWevuDefaults:`setWevuDefaults`};const WE_VU_INTERNAL_REACTIVITY_APIS=[`addMutationRecorder`,`batch`,`computed`,`customRef`,`effect`,`effectScope`,`endBatch`,`getCurrentScope`,`getDeepWatchStrategy`,`getReactiveVersion`,`isProxy`,`isRaw`,`isReactive`,`isReadonly`,`isRef`,`isShallowReactive`,`isShallowRef`,`markRaw`,`nextTick`,`onScopeDispose`,`prelinkReactiveTree`,`reactive`,`readonly`,`ref`,`removeMutationRecorder`,`setDeepWatchStrategy`,`shallowReactive`,`shallowReadonly`,`shallowRef`,`startBatch`,`stop`,`toRaw`,`toRef`,`toRefs`,`toValue`,`touchReactive`,`traverse`,`triggerRef`,`unref`,`useAsyncDerivation`,`watch`,`watchEffect`,`watchPostEffect`,`watchSyncEffect`];const WE_VU_INTERNAL_TEMPLATE_APIS=[`normalizeClass`,`normalizeStyle`,`resolvePropValue`];const WE_VU_INTERNAL_REACTIVITY_API_SET=new Set(WE_VU_INTERNAL_REACTIVITY_APIS);const WE_VU_INTERNAL_TEMPLATE_API_SET=new Set(WE_VU_INTERNAL_TEMPLATE_APIS);function resolveWevuInternalImportModuleId(apiName){if(WE_VU_INTERNAL_REACTIVITY_API_SET.has(apiName))return WE_VU_COMPILER_REACTIVITY_MODULE_ID;if(WE_VU_INTERNAL_TEMPLATE_API_SET.has(apiName))return WE_VU_COMPILER_TEMPLATE_MODULE_ID;return WE_VU_COMPILER_RUNTIME_MODULE_ID}var CompilerDiagnosticError=class extends Error{code;severity;filename;source;loc;constructor(diagnostic,options){super(diagnostic.message,options);this.name=`CompilerDiagnosticError`;this.code=diagnostic.code;this.severity=diagnostic.severity;this.filename=diagnostic.filename;this.source=diagnostic.source;this.loc=diagnostic.loc}};function getReadFileCheckMtime(config){return Boolean(config?.isDev)}function isEncodedSourceMapLike(value){return Boolean(value&&typeof value===`object`&&`version`in value&&`mappings`in value&&`names`in value&&`sources`in value)}function composeSourceMaps(transformedMap,originalMap){if(isEncodedSourceMapLike(transformedMap)&&isEncodedSourceMapLike(originalMap))return remapping([transformedMap,originalMap],()=>null);if(isEncodedSourceMapLike(transformedMap))return transformedMap;if(isEncodedSourceMapLike(originalMap))return originalMap;return null}function composeSourceMapForSource(transformedMap,originalMap,sourceFile){if(!isEncodedSourceMapLike(transformedMap))return null;if(!isEncodedSourceMapLike(originalMap))return transformedMap;const transformedMapInput=transformedMap;const sourceIndex=transformedMap.sources.indexOf(sourceFile);if(sourceIndex<0)return transformedMap;const resolvedSourceFile=new TraceMap(transformedMapInput).resolvedSources[sourceIndex];return remapping(transformedMapInput,(file,context)=>{if(context.depth!==1||file!==resolvedSourceFile)return null;context.source=``;return originalMap})}const allRawTags=new Set(presets.flatMap(preset=>preset.dialect.rawTags));const rawTagCandidate=new RegExp(`<(?:${[...allRawTags].join(`|`)})(?:\\s|>)`,`i`);function scriptTags(platform){return platform?new Set(presets.find(preset=>preset.id===platform)?.dialect.rawTags??[`wxs`]):allRawTags}function scriptBodyStart(source,start){let quote=0;for(let offset=start;offset<source.length;offset++){const code=source.charCodeAt(offset);if(quote){if(code===quote)quote=0}else if(code===34||code===39)quote=code;else if(code===62)return offset+1}return 0}function collectRawElements(root,rawTags){const elements=[];const visit=nodes=>{for(const node of nodes){if(node.type!==NodeTypes.ELEMENT)continue;const scriptFilter=node.tag!==`filter`||node.props.some(prop=>prop.type===NodeTypes.ATTRIBUTE&&[`module`,`src`].includes(prop.name));if(rawTags.has(node.tag.toLowerCase())&&scriptFilter&&!node.isSelfClosing)elements.push(node);visit(node.children)}};visit(root.children);return elements.sort((left,right)=>left.loc.start.offset-right.loc.start.offset)}function parseTemplateWithScriptModules(source,options,platform,parser=parse){const byStart=/* @__PURE__ */ new Map;const scripts={byStart,restore(output){for(const script of byStart.values())output=output.replaceAll(script.placeholder,()=>script.source);return output}};if(!rawTagCandidate.test(source))return{ast:parser(source,options),scripts};let placeholderPrefix=`wevu:raw-script:`;while(source.includes(placeholderPrefix))placeholderPrefix+=`:`;const rawTags=scriptTags(platform);let view=source;let ast;while(true){const errors=[];ast=parser(view,{...options,onError:error=>errors.push(error)});let changed=false;let cursor=0;for(const node of collectRawElements(ast,rawTags)){const start=node.loc.start.offset;if(start<cursor)continue;const existing=byStart.get(start);if(existing){cursor=existing.end;continue}const bodyStart=scriptBodyStart(source,start+node.tag.length+1);const closing=findScriptClosingTag(source,bodyStart,node.tag);if(!bodyStart||!closing)throw new Error(`脚本标签 <${node.tag}> 缺少可确认的结束边界`);byStart.set(start,{start,bodyStart,bodyEnd:closing.start,end:closing.end,placeholder:`<!--${placeholderPrefix}${byStart.size}-->`,source:source.slice(start,closing.end)});cursor=closing.end;changed=true}if(!changed){for(const error of errors){if(!options.onError)throw error;options.onError(error)}break}const chunks=[];cursor=0;for(const script of[...byStart.values()].sort((left,right)=>left.start-right.start)){chunks.push(source.slice(cursor,script.bodyStart),source.slice(script.bodyStart,script.bodyEnd).replace(/[^\r\n]/g,` `));cursor=script.bodyEnd}chunks.push(source.slice(cursor));view=chunks.join(``)}if(!byStart.size)return{ast,scripts};ast.loc.source=source;const restoreLocations=nodes=>{for(const node of nodes){node.loc.source=source.slice(node.loc.start.offset,node.loc.end.offset);if(node.type!==NodeTypes.ELEMENT)continue;if(node.innerLoc)node.innerLoc.source=source.slice(node.innerLoc.start.offset,node.innerLoc.end.offset);const script=byStart.get(node.loc.start.offset);if(script){const content=source.slice(script.bodyStart,script.bodyEnd);const start=advancePositionWithClone(node.loc.start,source.slice(script.start,script.bodyStart));node.children=[{type:NodeTypes.TEXT,content,loc:{start,end:advancePositionWithClone(start,content),source:content}}]}else restoreLocations(node.children)}};restoreLocations(ast.children);return{ast,scripts}}const CRLF_RE=/\r\n?/g;const HYPHENATE_RE=/\B([A-Z])/g;function hyphenate(value){return value.replace(HYPHENATE_RE,`-$1`).toLowerCase()}function normalizeComponentHostName(value){return value.startsWith(`__wv`)?value:hyphenate(value)}function normalizeLineEndings(source){if(!source.includes(`\r`))return source;return source.replace(CRLF_RE,`
1
+ import{ROOT_PORTAL_ENABLE_MIN_SDK_VERSION,ROOT_PORTAL_MIN_SDK_VERSION,ROOT_PORTAL_TOP_LEVEL_TARGETS,WEAPP_I18N_RUNTIME_MARKER,WEAPP_VITE_RUNTIME_REACTIVITY_VIRTUAL_ID,WEAPP_VITE_RUNTIME_TEMPLATE_VIRTUAL_ID,WEAPP_VITE_RUNTIME_VIRTUAL_ID,WEVU_BINDING_MANIFEST_KEY,WEVU_CLASS_STYLE_RUNTIME_FILE,WEVU_CLASS_STYLE_RUNTIME_MODULE,WEVU_CSS_MODULES_KEY,WEVU_CSS_VARS_STYLE_KEY,WEVU_DEFINE_PAGE_MACRO,WEVU_DEFINE_PAGE_META_MACRO,WEVU_EXPRESSION_ERROR_IDENTIFIER,WEVU_FUNCTION_PROP_PATHS_KEY,WEVU_INLINE_HANDLER,WEVU_INLINE_MAP_KEY,WEVU_IS_PAGE_KEY,WEVU_JSX_ISLAND_DATA_KEY,WEVU_JSX_ISLAND_HANDLER,WEVU_JSX_ISLAND_TEMPLATE_NAME,WEVU_LAYOUT_BIND_PREFIX,WEVU_LAYOUT_HOSTS_KEY,WEVU_LAYOUT_HOST_ID_PREFIX,WEVU_LAYOUT_HOST_REF_PREFIX,WEVU_LEGACY_RENDERER_KEY,WEVU_MODEL_HANDLER,WEVU_NATIVE_DECLARATION_ADDRESS_PROP,WEVU_NATIVE_DECLARATION_EVENT,WEVU_NATIVE_DECLARATION_METHOD,WEVU_NATIVE_DOM_MODULE_ID,WEVU_NATIVE_SLOT_CONTEXT_KEY,WEVU_NATIVE_SLOT_PARENT_DATASET_ATTR,WEVU_NATIVE_SLOT_PARENT_EVENT,WEVU_NATIVE_SLOT_PARENT_METHOD,WEVU_OWNER_HANDLER,WEVU_PAGE_LAYOUT_NAME_KEY,WEVU_PAGE_LAYOUT_PROPS_KEY,WEVU_PROPS_ALIASES_KEY,WEVU_PROPS_DERIVED_KEYS_KEY,WEVU_PROPS_KEY,WEVU_ROUTER_MODULE_ID,WEVU_SCOPED_SLOT_CREATOR_KEY,WEVU_SCOPED_SLOT_OWNER_REQUIRED_KEY,WEVU_SETUP_READY_KEY,WEVU_SLOT_FALLBACK_VIRTUAL_HOST_BASE,WEVU_SLOT_FALLBACK_VIRTUAL_HOST_TAG_NAME,WEVU_SLOT_FUNCTION_TOKEN,WEVU_SLOT_NAMES_ATTR,WEVU_SLOT_NAMES_PROP,WEVU_SLOT_OWNER_ID_ATTR,WEVU_SLOT_OWNER_ID_KEY,WEVU_SLOT_OWNER_ID_PROP,WEVU_SLOT_OWNER_KEY,WEVU_SLOT_OWNER_PROXY_KEY,WEVU_SLOT_PROPS_ATTR,WEVU_SLOT_PROPS_DATA_KEY,WEVU_SLOT_PROPS_KEY,WEVU_SLOT_SCOPE_ATTR,WEVU_SLOT_SCOPE_KEY,WEVU_TEMPLATE_REFS_KEY,WEVU_TEMPLATE_REF_CLASS_PREFIX}from"@weapp-core/constants";import{TraceMap,originalPositionFor}from"@jridgewell/trace-mapping";import{ConstantTypes,ErrorCodes,NodeTypes,advancePositionWithClone,baseParse,createSimpleExpression,transformModel}from"@vue/compiler-core";import*as compilerDom from"@vue/compiler-dom";import{compile,parse}from"@vue/compiler-dom";import{LRUCache}from"lru-cache";import MagicString,{Bundle}from"magic-string";import{compileScript,compileStyleAsync,parse as parse$1}from"vue/compiler-sfc";import remapping from"@jridgewell/remapping";import{findScriptClosingTag}from"@weapp-vite/wxml/core";import{presets}from"@weapp-vite/wxml/presets";import{access,mkdir,readFile as readFile$1,rm,stat,writeFile}from"node:fs/promises";import path from"pathe";import{fileURLToPath}from"node:url";import*as t from"@weapp-vite/ast/babelTypes";import{BABEL_TS_MODULE_PARSER_OPTIONS,BABEL_TS_MODULE_PLUGINS,generate,parse as parse$3,parseJsLike,traverse}from"@weapp-vite/ast/babel";import path$1 from"node:path";import{escapeWxmlAttribute,escapeWxmlText,getMiniProgramRuntimeGlobalKeys,getMiniProgramScriptModuleOptions,getMiniProgramTemplatePreset,removeExtensionDeep,resolveMiniProgramPlatform}from"@weapp-core/shared";import{createHash}from"node:crypto";import{recursive}from"merge";import{bundleRequire}from"rolldown-require";import fs,{readFileSync}from"node:fs";import os from"node:os";import process from"node:process";import{analyzeCompilerScriptsWithNative,collectJsxImportedComponentsAndDefaultExportFromBabelAst,collectJsxTemplateTagsFromBabelExpression,collectScriptCallStringLiterals,collectScriptStringLiterals,getObjectPropertyByKey,getRenderPropertyFromComponentOptions,mayContainScriptCallOrModuleSyntax,parseJsLikeWithEngine,resolveRenderExpressionFromComponentOptions,toStaticObjectKey,unwrapTypeScriptExpression}from"@weapp-vite/ast";import postcss from"postcss";import selectorParser from"postcss-selector-parser";import{parse as parse$2}from"comment-json";import vm from"node:vm";import{performance}from"node:perf_hooks";const components=[`wxs`,`template`,`block`,`import`,`include`,`cover-image`,`cover-view`,`match-media`,`movable-area`,`movable-view`,`page-container`,`root-portal`,`scroll-view`,`swiper`,`swiper-item`,`view`,`icon`,`progress`,`rich-text`,`selection`,`text`,`button`,`checkbox`,`checkbox-group`,`editor`,`editor-portal`,`form`,`input`,`keyboard-accessory`,`label`,`picker`,`picker-view`,`picker-view-column`,`radio`,`radio-group`,`slider`,`switch`,`textarea`,`double-tap-gesture-handler`,`force-press-gesture-handler`,`horizontal-drag-gesture-handler`,`long-press-gesture-handler`,`pan-gesture-handler`,`scale-gesture-handler`,`tap-gesture-handler`,`vertical-drag-gesture-handler`,`draggable-sheet`,`grid-builder`,`grid-view`,`large-image`,`list-builder`,`list-view`,`nested-scroll-body`,`nested-scroll-header`,`open-container`,`open-data-item`,`open-data-list`,`share-element`,`snapshot`,`span`,`sticky-header`,`sticky-section`,`functional-page-navigator`,`navigator`,`audio`,`camera`,`channel-live`,`channel-video`,`image`,`live-player`,`live-pusher`,`video`,`voip-room`,`map`,`canvas`,`ad`,`ad-custom`,`official-account`,`official-account-publish`,`open-data`,`reward`,`store-coupon`,`store-gift`,`store-home`,`store-product`,`web-view`,`native-component`,`aria-component`,`navigation-bar`,`page-meta`];const builtinComponentsSet=new Set(components);function isBuiltinComponent(tag){return builtinComponentsSet.has(tag)}function createRuntimeBindingManifest(manifest,mode=`compact`){const bindings=manifest.bindings.map(binding=>({id:binding.id,outputPath:binding.outputPath,...mode===`diagnostic`&&binding.sourceFile?{sourceFile:binding.sourceFile}:{},...binding.updateMode===`exact-path`?{}:{updateMode:binding.updateMode},...binding.updateMode===`snapshot-fallback`&&binding.sourceRoots.length?{sourceRoots:binding.sourceRoots}:{},...mode===`diagnostic`&&binding.sourceLocation?{sourceLocation:binding.sourceLocation}:{}}));const features={};if(manifest.features.scopedSlots)features.scopedSlots=true;return{version:1,sourceFile:manifest.sourceFile,bindings,...Object.keys(features).length?{features}:{}}}const WE_VU_PAGE_HOOK_TO_FEATURE={onPageScroll:`enableOnPageScroll`,usePageScrollRestoration:`enableOnPageScroll`,onPullDownRefresh:`enableOnPullDownRefresh`,onReachBottom:`enableOnReachBottom`,onRouteDone:`enableOnRouteDone`,onTabItemTap:`enableOnTabItemTap`,onResize:`enableOnResize`,onShareAppMessage:`enableOnShareAppMessage`,onShareTimeline:`enableOnShareTimeline`,onAddToFavorites:`enableOnAddToFavorites`,onSaveExitState:`enableOnSaveExitState`};const WE_VU_MODULE_ID=`wevu`;const WE_VU_INTERNAL_RUNTIME_MODULE_ID=`wevu/internal-runtime`;const WE_VU_INTERNAL_REACTIVITY_MODULE_ID=`wevu/internal-reactivity`;const WE_VU_INTERNAL_TEMPLATE_MODULE_ID=`wevu/internal-template`;const WE_VU_COMPILER_RUNTIME_MODULE_ID=WEAPP_VITE_RUNTIME_VIRTUAL_ID;const WE_VU_COMPILER_REACTIVITY_MODULE_ID=WEAPP_VITE_RUNTIME_REACTIVITY_VIRTUAL_ID;const WE_VU_COMPILER_TEMPLATE_MODULE_ID=WEAPP_VITE_RUNTIME_TEMPLATE_VIRTUAL_ID;const WE_VU_RUNTIME_MODULE_IDS=[WE_VU_MODULE_ID,WE_VU_INTERNAL_RUNTIME_MODULE_ID,WE_VU_COMPILER_RUNTIME_MODULE_ID,WE_VU_COMPILER_REACTIVITY_MODULE_ID,WE_VU_COMPILER_TEMPLATE_MODULE_ID];function isWevuRuntimeModuleId(moduleId){return WE_VU_RUNTIME_MODULE_IDS.includes(moduleId)}function isWevuPageFeatureModuleId(moduleId){return isWevuRuntimeModuleId(moduleId)||moduleId===`wevu/router`||moduleId===`wevu/dev/router`}const WE_VU_RUNTIME_APIS={createApp:`createApp`,createWevuComponent:`createWevuComponent`,createWevuScopedSlotComponent:`createWevuScopedSlotComponent`,defineAppSetup:`defineAppSetup`,defineComponent:`defineComponent`,setWevuDefaults:`setWevuDefaults`};const WE_VU_INTERNAL_REACTIVITY_APIS=[`addMutationRecorder`,`batch`,`computed`,`customRef`,`effect`,`effectScope`,`endBatch`,`getCurrentScope`,`getDeepWatchStrategy`,`getReactiveVersion`,`isProxy`,`isRaw`,`isReactive`,`isReadonly`,`isRef`,`isShallowReactive`,`isShallowRef`,`markRaw`,`nextTick`,`onScopeDispose`,`prelinkReactiveTree`,`reactive`,`readonly`,`ref`,`removeMutationRecorder`,`setDeepWatchStrategy`,`shallowReactive`,`shallowReadonly`,`shallowRef`,`startBatch`,`stop`,`toRaw`,`toRef`,`toRefs`,`toValue`,`touchReactive`,`traverse`,`triggerRef`,`unref`,`useAsyncDerivation`,`watch`,`watchEffect`,`watchPostEffect`,`watchSyncEffect`];const WE_VU_INTERNAL_TEMPLATE_APIS=[`normalizeClass`,`normalizeStyle`,`resolvePropValue`];const WE_VU_INTERNAL_REACTIVITY_API_SET=new Set(WE_VU_INTERNAL_REACTIVITY_APIS);const WE_VU_INTERNAL_TEMPLATE_API_SET=new Set(WE_VU_INTERNAL_TEMPLATE_APIS);function resolveWevuInternalImportModuleId(apiName){if(WE_VU_INTERNAL_REACTIVITY_API_SET.has(apiName))return WE_VU_COMPILER_REACTIVITY_MODULE_ID;if(WE_VU_INTERNAL_TEMPLATE_API_SET.has(apiName))return WE_VU_COMPILER_TEMPLATE_MODULE_ID;return WE_VU_COMPILER_RUNTIME_MODULE_ID}var CompilerDiagnosticError=class extends Error{code;severity;filename;source;loc;constructor(diagnostic,options){super(diagnostic.message,options);this.name=`CompilerDiagnosticError`;this.code=diagnostic.code;this.severity=diagnostic.severity;this.filename=diagnostic.filename;this.source=diagnostic.source;this.loc=diagnostic.loc}};function getReadFileCheckMtime(config){return Boolean(config?.isDev)}function isEncodedSourceMapLike(value){return Boolean(value&&typeof value===`object`&&`version`in value&&`mappings`in value&&`names`in value&&`sources`in value)}function composeSourceMaps(transformedMap,originalMap){if(isEncodedSourceMapLike(transformedMap)&&isEncodedSourceMapLike(originalMap))return remapping([transformedMap,originalMap],()=>null);if(isEncodedSourceMapLike(transformedMap))return transformedMap;if(isEncodedSourceMapLike(originalMap))return originalMap;return null}function composeSourceMapForSource(transformedMap,originalMap,sourceFile){if(!isEncodedSourceMapLike(transformedMap))return null;if(!isEncodedSourceMapLike(originalMap))return transformedMap;const transformedMapInput=transformedMap;const sourceIndex=transformedMap.sources.indexOf(sourceFile);if(sourceIndex<0)return transformedMap;const resolvedSourceFile=new TraceMap(transformedMapInput).resolvedSources[sourceIndex];return remapping(transformedMapInput,(file,context)=>{if(context.depth!==1||file!==resolvedSourceFile)return null;context.source=``;return originalMap})}const allRawTags=new Set(presets.flatMap(preset=>preset.dialect.rawTags));const rawTagCandidate=new RegExp(`<(?:${[...allRawTags].join(`|`)})(?:\\s|>)`,`i`);function scriptTags(platform){return platform?new Set(presets.find(preset=>preset.id===platform)?.dialect.rawTags??[`wxs`]):allRawTags}function scriptBodyStart(source,start){let quote=0;for(let offset=start;offset<source.length;offset++){const code=source.charCodeAt(offset);if(quote){if(code===quote)quote=0}else if(code===34||code===39)quote=code;else if(code===62)return offset+1}return 0}function collectRawElements(root,rawTags){const elements=[];const visit=nodes=>{for(const node of nodes){if(node.type!==NodeTypes.ELEMENT)continue;const scriptFilter=node.tag!==`filter`||node.props.some(prop=>prop.type===NodeTypes.ATTRIBUTE&&[`module`,`src`].includes(prop.name));if(rawTags.has(node.tag.toLowerCase())&&scriptFilter&&!node.isSelfClosing)elements.push(node);visit(node.children)}};visit(root.children);return elements.sort((left,right)=>left.loc.start.offset-right.loc.start.offset)}function parseTemplateWithScriptModules(source,options,platform,parser=parse){const byStart=/* @__PURE__ */ new Map;const scripts={byStart,restore(output){for(const script of byStart.values())output=output.replaceAll(script.placeholder,()=>script.source);return output}};if(!rawTagCandidate.test(source))return{ast:parser(source,options),scripts};let placeholderPrefix=`wevu:raw-script:`;while(source.includes(placeholderPrefix))placeholderPrefix+=`:`;const rawTags=scriptTags(platform);let view=source;let ast;while(true){const errors=[];ast=parser(view,{...options,onError:error=>errors.push(error)});let changed=false;let cursor=0;for(const node of collectRawElements(ast,rawTags)){const start=node.loc.start.offset;if(start<cursor)continue;const existing=byStart.get(start);if(existing){cursor=existing.end;continue}const bodyStart=scriptBodyStart(source,start+node.tag.length+1);const closing=findScriptClosingTag(source,bodyStart,node.tag);if(!bodyStart||!closing)throw new Error(`脚本标签 <${node.tag}> 缺少可确认的结束边界`);byStart.set(start,{start,bodyStart,bodyEnd:closing.start,end:closing.end,placeholder:`<!--${placeholderPrefix}${byStart.size}-->`,source:source.slice(start,closing.end)});cursor=closing.end;changed=true}if(!changed){for(const error of errors){if(!options.onError)throw error;options.onError(error)}break}const chunks=[];cursor=0;for(const script of[...byStart.values()].sort((left,right)=>left.start-right.start)){chunks.push(source.slice(cursor,script.bodyStart),source.slice(script.bodyStart,script.bodyEnd).replace(/[^\r\n]/g,` `));cursor=script.bodyEnd}chunks.push(source.slice(cursor));view=chunks.join(``)}if(!byStart.size)return{ast,scripts};ast.loc.source=source;const restoreLocations=nodes=>{for(const node of nodes){node.loc.source=source.slice(node.loc.start.offset,node.loc.end.offset);if(node.type!==NodeTypes.ELEMENT)continue;if(node.innerLoc)node.innerLoc.source=source.slice(node.innerLoc.start.offset,node.innerLoc.end.offset);const script=byStart.get(node.loc.start.offset);if(script){const content=source.slice(script.bodyStart,script.bodyEnd);const start=advancePositionWithClone(node.loc.start,source.slice(script.start,script.bodyStart));node.children=[{type:NodeTypes.TEXT,content,loc:{start,end:advancePositionWithClone(start,content),source:content}}]}else restoreLocations(node.children)}};restoreLocations(ast.children);return{ast,scripts}}const CRLF_RE=/\r\n?/g;const HYPHENATE_RE=/\B([A-Z])/g;function hyphenate(value){return value.replace(HYPHENATE_RE,`-$1`).toLowerCase()}function normalizeComponentHostName(value){return value.startsWith(`__wv`)?value:hyphenate(value)}function normalizeLineEndings(source){if(!source.includes(`\r`))return source;return source.replace(CRLF_RE,`
2
2
  `)}async function ensureDir(path){await mkdir(path,{recursive:true})}async function remove(path){await rm(path,{recursive:true,force:true})}async function pathExists$1(path){try{await access(path);return true}catch{return false}}const mtimeCache=/* @__PURE__ */ new Map;const loadCache=new LRUCache({max:1024});const pathExistsCache=new LRUCache({max:4096});const sourceSignatures=new LRUCache({max:1024});const pendingReads=/* @__PURE__ */ new Map;const transientRenameRetryDelays=[10,25,50];function isMissingFileError(error){return error instanceof Error&&`code`in error&&error.code===`ENOENT`}async function readFileSignature(id){const stats=await stat(id);const mtimeMs=typeof stats?.mtimeMs===`number`?stats.mtimeMs:NaN;const ctimeMs=typeof stats?.ctimeMs===`number`?stats.ctimeMs:NaN;const size=typeof stats?.size===`number`?stats.size:NaN;const ino=typeof stats?.ino===`number`?stats.ino:NaN;return[mtimeMs,ctimeMs,size,ino].every(Number.isFinite)?{mtimeMs,ctimeMs,size,ino}:void 0}function sameFileSignature(left,right){return left!==void 0&&left.mtimeMs===right.mtimeMs&&left.ctimeMs===right.ctimeMs&&left.size===right.size&&left.ino===right.ino}async function isInvalidate(id){const signature=await readFileSignature(id);if(!signature)return true;const unchanged=sameFileSignature(mtimeCache.get(id),signature);mtimeCache.set(id,signature);return!unchanged}async function readFile(id,options){const checkMtime=options?.checkMtime??true;const encoding=options?.encoding??`utf8`;if(!checkMtime){const cached=loadCache.get(id);if(cached!==void 0)return cached}const token={};pendingReads.set(id,token);try{for(let attempt=0;;attempt+=1)try{const signature=checkMtime?await readFileSignature(id):void 0;if(signature){const cached=sourceSignatures.get(id);if(cached&&sameFileSignature(cached.signature,signature)&&loadCache.get(id)===cached.source){if(pendingReads.get(id)===token)mtimeCache.set(id,signature);return cached.source}}const content=normalizeLineEndings(await readFile$1(id,encoding));if(pendingReads.get(id)===token){loadCache.set(id,content);if(signature){sourceSignatures.set(id,{source:content,signature});mtimeCache.set(id,signature)}else{sourceSignatures.delete(id);mtimeCache.delete(id)}}return content}catch(error){const retryDelay=transientRenameRetryDelays[attempt];if(!isMissingFileError(error)||retryDelay===void 0)throw error;await new Promise(resolve=>setTimeout(resolve,retryDelay))}}finally{if(pendingReads.get(id)===token)pendingReads.delete(id)}}async function pathExists(id,options){const ttlMs=options?.ttlMs;const cached=pathExistsCache.get(id);if(cached!==void 0)return cached;const exists=await pathExists$1(id);if(typeof ttlMs===`number`&&Number.isFinite(ttlMs)&&ttlMs>0)pathExistsCache.set(id,exists,{ttl:ttlMs});else pathExistsCache.set(id,exists);return exists}function invalidateFileCache(id){pendingReads.delete(id);sourceSignatures.delete(id);mtimeCache.delete(id);loadCache.delete(id);pathExistsCache.delete(id)}function clearFileCaches(){pendingReads.clear();sourceSignatures.clear();mtimeCache.clear();loadCache.clear();pathExistsCache.clear()}const VUE_VIRTUAL_MODULE_PREFIX=`\0vue:`;const BACKSLASH_RE$4=/\\/g;function normalizeViteId(id,options){const stripQuery=options?.stripQuery!==false;const fileProtocolToPathEnabled=options?.fileProtocolToPath!==false;const stripAtFsPrefix=options?.stripAtFsPrefix!==false;const stripVueVirtualPrefix=options?.stripVueVirtualPrefix===true;const stripLeadingNullByte=options?.stripLeadingNullByte===true;let clean=id;if(stripVueVirtualPrefix&&clean.startsWith(VUE_VIRTUAL_MODULE_PREFIX))clean=clean.slice(5);if(clean.includes(`\\`))clean=clean.replace(BACKSLASH_RE$4,`/`);if(stripQuery)clean=clean.split(`?`,1)[0];if(fileProtocolToPathEnabled&&clean.startsWith(`file://`))try{clean=fileURLToPath(clean)}catch{}if(stripAtFsPrefix&&clean.startsWith(`/@fs/`))clean=clean.slice(4);if(stripLeadingNullByte&&clean.startsWith(`\0`))clean=clean.slice(1);return clean}function isSkippableResolvedId(id){if(!id)return true;return id.startsWith(`\0`)||id.startsWith(`node:`)}function normalizeFsResolvedId(id,options){const normalizeOptions={stripVueVirtualPrefix:true};if(options?.normalize)Object.assign(normalizeOptions,options.normalize);if(options?.stripLeadingNullByte)normalizeOptions.stripLeadingNullByte=true;return normalizeViteId(id,normalizeOptions)}const SCRIPT_LANG_EXT=/* @__PURE__ */ new Map([[`.ts`,`ts`],[`.tsx`,`tsx`],[`.js`,`js`],[`.jsx`,`jsx`],[`.mjs`,`js`],[`.cjs`,`js`]]);const STYLE_LANG_EXT=/* @__PURE__ */ new Map([[`.css`,`css`],[`.scss`,`scss`],[`.sass`,`sass`],[`.less`,`less`],[`.styl`,`styl`],[`.stylus`,`styl`]]);const TEMPLATE_LANG_EXT=/* @__PURE__ */ new Map([[`.html`,`html`],[`.htm`,`html`],[`.pug`,`pug`],[`.jade`,`pug`]]);const CSS_VARS_CLOSE_TAG_SENTINEL_PREFIX=`__WEVU_SFC_CSS_VARS_CLOSE_`;function createCssVarsCloseTagSentinel(styles){let index=0;while(styles.some(style=>style.content.includes(`${CSS_VARS_CLOSE_TAG_SENTINEL_PREFIX}${index}_`)))index++;return`${CSS_VARS_CLOSE_TAG_SENTINEL_PREFIX}${index}_`}function resolveDescriptorCssVars(styles,filename){const sentinel=createCssVarsCloseTagSentinel(styles);const closeTagRestorations=[];let closeTagIndex=0;const styleSource=styles.map(style=>{return`<style>${style.content.replace(/<\/style/gi,source=>{const token=`${sentinel}${closeTagIndex++}__`;closeTagRestorations.push([token,source]);return token})}</style>`}).join(`
3
3
  `);const parsed=parse$1(`<template></template>\n${styleSource}`,{filename,sourceMap:false});if(parsed.errors.length){const error=parsed.errors[0];const message=error instanceof Error?error.message:String(error);throw new Error(`解析 ${filename} 失败:无法重建外部样式 CSS 变量元数据:${message}`)}const cssVars=[];for(const expression of parsed.descriptor.cssVars){let restored=expression;for(const[token,source]of closeTagRestorations)restored=restored.replaceAll(token,source);if(!cssVars.includes(restored))cssVars.push(restored)}return cssVars}function inferLangFromSrc(src,kind){const ext=path.extname(src).toLowerCase();if(!ext)return;if(kind===`style`)return STYLE_LANG_EXT.get(ext);if(kind===`template`)return TEMPLATE_LANG_EXT.get(ext);return SCRIPT_LANG_EXT.get(ext)}function getBlockLabel(kind){if(kind===`script setup`)return`script setup`;return kind}async function resolveBlockSrcPath(src,filename,options){const normalizedSrc=normalizeFsResolvedId(src);if(normalizedSrc&&isSkippableResolvedId(normalizedSrc))throw new Error(`解析 ${filename} 失败:不支持 <src> 引用虚拟模块 ${src}`);let resolvedId;if(options?.resolveId){const resolved=await options.resolveId(src,filename);if(resolved){const normalized=normalizeFsResolvedId(resolved);if(normalized&&isSkippableResolvedId(normalized))throw new Error(`解析 ${filename} 失败:不支持 <src> 引用虚拟模块 ${src}`);resolvedId=normalized||resolved}}if(resolvedId){if(!path.isAbsolute(resolvedId))resolvedId=path.resolve(path.dirname(filename),resolvedId);return resolvedId}if(normalizedSrc&&path.isAbsolute(normalizedSrc))return normalizedSrc;return path.resolve(path.dirname(filename),normalizedSrc||src)}async function readBlockContent(resolvedId,filename,kind,options){const reader=options?.readFile;const checkMtime=options?.checkMtime;if(reader)return await reader(resolvedId,{checkMtime,blockType:kind===`script setup`?`script`:kind});try{return await readFile(resolvedId,{checkMtime})}catch(error){const message=error instanceof Error?error.message:String(error);throw new Error(`解析 ${filename} 失败:读取 ${resolvedId} 失败:${message}`,{cause:error})}}async function resolveSfcBlockSrc(descriptor,filename,options){if(!options)return{descriptor,deps:[]};const deps=/* @__PURE__ */ new Set;let templateResolvedId;let scriptResolvedId;let scriptSetupResolvedId;let hasResolvedStyleSrc=false;const nextDescriptor={...descriptor,styles:descriptor.styles.slice()};const resolveBlock=async(block,kind)=>{if(!block||!block.src)return block;if(block.content.trim().length>0)throw new Error(`解析 ${filename} 失败:<${getBlockLabel(kind)}> 同时存在 src 与内联内容`);const resolvedId=await resolveBlockSrcPath(block.src,filename,options);if(kind===`template`)templateResolvedId=resolvedId;else if(kind===`script`)scriptResolvedId=resolvedId;else if(kind===`script setup`)scriptSetupResolvedId=resolvedId;const content=await readBlockContent(resolvedId,filename,kind,options);if(kind===`style`)hasResolvedStyleSrc=true;deps.add(resolvedId);const inferredLang=block.lang??inferLangFromSrc(resolvedId,kind);return{...block,content,lang:inferredLang??block.lang}};nextDescriptor.template=await resolveBlock(descriptor.template,`template`);nextDescriptor.script=await resolveBlock(descriptor.script,`script`);nextDescriptor.scriptSetup=await resolveBlock(descriptor.scriptSetup,`script setup`);if(nextDescriptor.styles.length)nextDescriptor.styles=await Promise.all(nextDescriptor.styles.map(style=>resolveBlock(style,`style`)));if(hasResolvedStyleSrc)nextDescriptor.cssVars=resolveDescriptorCssVars(nextDescriptor.styles,filename);return{descriptor:nextDescriptor,deps:[...deps],scriptResolvedId,scriptSetupResolvedId,templateResolvedId}}const sfcParseCache=new LRUCache({max:512});const SCRIPT_SETUP_SRC_ATTR=`data-weapp-vite-src`;const SCRIPT_SRC_ATTR=`data-weapp-vite-script-src`;const INTERNAL_SCRIPT_SRC_ATTR=`\0wevu-script-src`;const EXTERNAL_SCRIPT_CONTENT_SENTINEL=`\0wevu-external-script`;function createSourceLineStarts$1(source){const starts=[0];for(const match of source.matchAll(/\r\n?|\n/g))starts.push(match.index+match[0].length);return starts}function resolvePosition(source,lineStarts,line,column){const safeLine=Math.min(Math.max(line,1),lineStarts.length);const lineStart=lineStarts[safeLine-1]??0;const offset=Math.min(source.length,lineStart+Math.max(column-1,0));return{offset,line:safeLine,column:offset-lineStart+1}}function readSfcParseErrorPosition(value){if(!value||typeof value!==`object`)return;if(!(`line`in value)||typeof value.line!==`number`||!(`column`in value)||typeof value.column!==`number`)return;return{line:value.line,column:value.column}}function readSfcParseErrorLocation(error){if(!error||typeof error!==`object`||!(`loc`in error)||!error.loc||typeof error.loc!==`object`)return;const start=`start`in error.loc?readSfcParseErrorPosition(error.loc.start):void 0;const end=`end`in error.loc?readSfcParseErrorPosition(error.loc.end):void 0;return start?{start,end:end??start}:void 0}function createSfcParseError(error,options){const originalLocation=readSfcParseErrorLocation(error);const sourceLineStarts=originalLocation?createSourceLineStarts$1(options.source):[];let traceMap;if(originalLocation&&isEncodedSourceMapLike(options.sourceMap))try{traceMap=new TraceMap(options.sourceMap)}catch{traceMap=void 0}const remap=position=>{if(traceMap)try{const mapped=originalPositionFor(traceMap,{line:position.line,column:Math.max(position.column-1,0)});if(mapped.line!=null&&mapped.column!=null)return resolvePosition(options.source,sourceLineStarts,mapped.line,mapped.column+1)}catch{}return resolvePosition(options.source,sourceLineStarts,position.line,position.column)};const location=originalLocation?{start:remap(originalLocation.start),end:remap(originalLocation.end)}:void 0;const causeMessage=error instanceof Error?error.message:String(error);const diagnostic={code:`WV2003`,severity:`error`,message:options.formatMessage?.(causeMessage,location)??`解析 ${options.filename} 失败:${causeMessage}`,filename:options.filename,source:`sfc`,loc:location};return new CompilerDiagnosticError(diagnostic,{cause:error})}function parseSfcAst(source,options,onScriptSrc){const{ast}=parseTemplateWithScriptModules(source,options);for(const child of ast.children){if(child.type!==NodeTypes.ELEMENT||child.tag!==`script`)continue;let src;let setup=false;for(const attribute of child.props){if(attribute.type!==NodeTypes.ATTRIBUTE)continue;if(attribute.name===`src`)src=attribute;else if(attribute.name===`setup`)setup=true}if(src)onScriptSrc({attribute:src,node:child,setup})}return ast}function collectSfcScriptSrcAttributes(source){const attributes=[];try{parseSfcAst(source,{parseMode:`sfc`,onError(){}},owned=>attributes.push(owned))}catch{}return attributes}const sfcSrcCompiler={compile:compilerDom.compile,parse(source,options){return parseSfcAst(source,options,({attribute,node})=>{attribute.name=INTERNAL_SCRIPT_SRC_ATTR;if(node.children.every(child=>child.type===NodeTypes.TEXT&&child.content.trim()===``))node.children.push({type:NodeTypes.TEXT,content:EXTERNAL_SCRIPT_CONTENT_SENTINEL,loc:node.innerLoc??node.loc})})}};function restoreScriptBlockSrc(block,marker){if(!block||!(marker in block.attrs))return;const raw=block.attrs[marker];delete block.attrs[marker];block.attrs.src=raw;block.src=typeof raw===`string`?raw:void 0}function parseVueSfc(source,options={}){const parsed=parse$1(source,{...options,compiler:sfcSrcCompiler});restoreScriptBlockSrc(parsed.descriptor.script,INTERNAL_SCRIPT_SRC_ATTR);restoreScriptBlockSrc(parsed.descriptor.scriptSetup,INTERNAL_SCRIPT_SRC_ATTR);return parsed}function preprocessScriptSource(source,setup){if(!source.includes(`<script`)||!source.includes(`src`))return source;let transformed;const marker=setup?SCRIPT_SETUP_SRC_ATTR:SCRIPT_SRC_ATTR;for(const owned of collectSfcScriptSrcAttributes(source)){if(owned.setup!==setup)continue;transformed??=new MagicString(source);transformed.overwrite(owned.attribute.nameLoc.start.offset,owned.attribute.nameLoc.end.offset,marker)}return transformed?.toString()??source}function preprocessScriptSetupSrc(source){return preprocessScriptSource(source,true)}function preprocessScriptSrc(source){return preprocessScriptSource(source,false)}function restoreScriptSetupSrc(descriptor){restoreScriptBlockSrc(descriptor.scriptSetup,SCRIPT_SETUP_SRC_ATTR)}function restoreScriptSrc(descriptor){restoreScriptBlockSrc(descriptor.script,SCRIPT_SRC_ATTR)}async function readAndParseSfc(filename,options){const checkMtime=options?.checkMtime??true;const source=normalizeLineEndings(options?.source??await readFile(filename,{checkMtime}));const parserSource=options?.preprocessedSource??source;const ignoreEmpty=options?.ignoreEmpty??true;const cached=sfcParseCache.get(filename);if(cached){if(cached.parserSource===parserSource&&cached.ignoreEmpty===ignoreEmpty){if(options?.resolveSrc)return{source,descriptor:(await resolveSfcBlockSrc(cached.descriptor,filename,options.resolveSrc)).descriptor,errors:cached.errors};return{source,descriptor:cached.descriptor,errors:cached.errors}}}const parsed=parseVueSfc(parserSource,{filename,ignoreEmpty});sfcParseCache.set(filename,{parserSource,ignoreEmpty,descriptor:parsed.descriptor,errors:parsed.errors});if(options?.resolveSrc)return{source,descriptor:(await resolveSfcBlockSrc(parsed.descriptor,filename,options.resolveSrc)).descriptor,errors:parsed.errors};return{source,descriptor:parsed.descriptor,errors:parsed.errors}}function getSfcCheckMtime(config){return getReadFileCheckMtime(config)}function resolveSourceLocation$1(source,offset){let line=1;let lineStart=0;const end=Math.min(Math.max(offset,0),source.length);for(let index=0;index<end;index+=1){const char=source.charCodeAt(index);if(char===10||char===8232||char===8233){line+=1;lineStart=index+1}else if(char===13){line+=1;if(source.charCodeAt(index+1)===10)index+=1;lineStart=index+1}}return{line,column:end-lineStart+1}}function getAbsoluteOffset(block,node){return block.offset+(typeof node?.start===`number`?node.start:0)}function createPageDeclarationError(block,node,message){const location=resolveSourceLocation$1(block.source,getAbsoluteOffset(block,node));return/* @__PURE__ */ new Error(`${block.filename}:${location.line}:${location.column} ${message}`)}function createPageDeclarationParseError(block,error){const parseError=error instanceof Error?error:new Error(String(error));const offset=`pos`in parseError&&typeof parseError.pos===`number`?parseError.pos:0;const location=resolveSourceLocation$1(block.source,block.offset+offset);return/* @__PURE__ */ new Error(`${block.filename}:${location.line}:${location.column} 解析页面声明失败:${parseError.message}`)}const BACKSLASH_RE$3=/\\/g;const LEADING_SLASH_RE=/^[\\/]+/;const DUPLICATE_SLASH_RE=/\/{2,}/g;const TRIM_SLASH_RE=/^\/+|\/+$/g;function toPosixPath(value){return value.replace(BACKSLASH_RE$3,`/`)}function stripLeadingSlashes(value){return value.replace(LEADING_SLASH_RE,``)}function normalizeRoot(root){return toPosixPath(root).replace(DUPLICATE_SLASH_RE,`/`).replace(TRIM_SLASH_RE,``)}function rewriteRelativeImportSource(source,fromDir,tempDir){if(!source.startsWith(`.`))return source;const abs=path.resolve(fromDir,source);let next=toPosixPath(path.relative(tempDir,abs));if(!next.startsWith(`.`))next=`./${next}`;return next}function rewriteJsLikeImportsForTempDir(source,fromDir,tempDir){const ast=parseJsLike(source);const ms=new MagicString(source);let mutated=false;const rewriteLiteral=(node,originalSource)=>{if(!originalSource||!originalSource.startsWith(`.`))return;const next=rewriteRelativeImportSource(originalSource,fromDir,tempDir);const start=node?.start;const end=node?.end;if(typeof start===`number`&&typeof end===`number`){ms.overwrite(start,end,JSON.stringify(next));mutated=true}};traverse(ast,{ImportDeclaration(p){const sourceNode=p.node?.source;if(sourceNode&&t.isStringLiteral(sourceNode))rewriteLiteral(sourceNode,sourceNode.value)},ExportNamedDeclaration(p){const sourceNode=p.node?.source;if(sourceNode&&t.isStringLiteral(sourceNode))rewriteLiteral(sourceNode,sourceNode.value)},ExportAllDeclaration(p){const sourceNode=p.node?.source;if(sourceNode&&t.isStringLiteral(sourceNode))rewriteLiteral(sourceNode,sourceNode.value)},ImportExpression(p){const sourceNode=p.node?.source;if(sourceNode&&t.isStringLiteral(sourceNode))rewriteLiteral(sourceNode,sourceNode.value)},CallExpression(p){const callee=p.node?.callee;if(!callee)return;const arg0=p.node?.arguments?.[0];if(!arg0||!t.isStringLiteral(arg0))return;if(t.isImport(callee)){rewriteLiteral(arg0,arg0.value);return}if(t.isIdentifier(callee,{name:`require`}))rewriteLiteral(arg0,arg0.value)}});return mutated?ms.toString():source}function nodeStart(node){return node.start??0}function nodeEnd(node){return node.end??nodeStart(node)}function isValueBindingPath(bindingPath){const declarationPath=bindingPath.parentPath;if(`declare`in bindingPath.node&&bindingPath.node.declare===true||declarationPath?.isVariableDeclaration()&&declarationPath.node.declare===true)return false;if(!declarationPath?.isImportDeclaration())return true;if(declarationPath.node.importKind===`type`)return false;return!bindingPath.isImportSpecifier()||bindingPath.node.importKind!==`type`}function hasTypeScriptValueBinding(parsed,reference,name){for(let current=reference;current;current=current.parentPath)if(parsed.typeScriptValueBindings.get(current.node)?.has(name))return true;return false}function hasValueBinding(parsed,reference,name){const binding=reference.scope.getBinding(name);return Boolean(binding&&isValueBindingPath(binding.path))||hasTypeScriptValueBinding(parsed,reference,name)}function hasModuleVisibleValueBinding(parsedBlocks,name){return parsedBlocks.some(parsed=>{if(parsed.block.kind===`script`&&parsed.typeScriptValueBindings.get(parsed.ast.program)?.has(name))return true;const binding=parsed.programPath.scope.getBinding(name);if(!binding||!isValueBindingPath(binding.path))return false;return parsed.block.kind===`script`||binding.path.parentPath?.isImportDeclaration()===true})}function getImportRemovalEdits(macroImports){const byDeclaration=/* @__PURE__ */ new Map;for(const macroImport of macroImports){const entries=byDeclaration.get(macroImport.declaration)??[];entries.push(macroImport);byDeclaration.set(macroImport.declaration,entries)}const edits=[];for(const[declaration,entries]of byDeclaration){const block=entries[0].block;const removed=new Set(entries.map(entry=>entry.specifier));if(!declaration.specifiers.filter(specifier=>{return!t.isImportSpecifier(specifier)||!removed.has(specifier)}).length){edits.push({block,start:nodeStart(declaration),end:nodeEnd(declaration)});continue}const namedSpecifiers=declaration.specifiers.filter(t.isImportSpecifier);if(!namedSpecifiers.filter(specifier=>!removed.has(specifier)).length){edits.push({block,start:nodeStart(namedSpecifiers[0]),end:nodeEnd(namedSpecifiers[namedSpecifiers.length-1])});continue}for(let index=0;index<namedSpecifiers.length;){if(!removed.has(namedSpecifiers[index])){index+=1;continue}const firstRemoved=index;while(index<namedSpecifiers.length&&removed.has(namedSpecifiers[index]))index+=1;const lastRemoved=index-1;const nextKept=namedSpecifiers[index];const previousKept=namedSpecifiers[firstRemoved-1];edits.push(nextKept?{block,start:nodeStart(namedSpecifiers[firstRemoved]),end:nodeStart(nextKept)}:{block,start:nodeEnd(previousKept),end:nodeEnd(namedSpecifiers[lastRemoved])})}}return edits}function rebaseExternalScriptImports(parsed,targetFilename,code,parsedBlocks){const sourceDir=path.dirname(parsed.block.filename);const targetDir=path.dirname(targetFilename);if(sourceDir===targetDir)return;const rewriteSource=node=>{if(!t.isStringLiteral(node)||!node.value.startsWith(`.`))return;code.overwrite(parsed.block.offset+nodeStart(node),parsed.block.offset+nodeEnd(node),JSON.stringify(rewriteRelativeImportSource(node.value,sourceDir,targetDir)))};const hasModuleRequireBinding=hasModuleVisibleValueBinding(parsedBlocks,`require`);parsed.programPath.traverse({ImportDeclaration(path){rewriteSource(path.node.source)},ExportNamedDeclaration(path){rewriteSource(path.node.source)},ExportAllDeclaration(path){rewriteSource(path.node.source)},ImportExpression(path){rewriteSource(path.node.source)},CallExpression(path){const{callee,arguments:args}=path.node;if(t.isImport(callee)){rewriteSource(args[0]);return}if(!t.isIdentifier(callee,{name:`require`}))return;if(!hasModuleRequireBinding&&!hasValueBinding(parsed,path,`require`))rewriteSource(args[0])}})}function isRuntimeReference(path){const parent=path.parentPath;if(parent&&(parent.isTSEnumDeclaration()||parent.isTSEnumMember()||parent.isTSModuleDeclaration()||parent.isTSImportEqualsDeclaration())&&parent.node.id===path.node)return false;if(parent?.isTSQualifiedName()&&parent.node.right===path.node)return false;return!path.findParent(parent=>parent.isTSType()||parent.isTSInterfaceDeclaration()||parent.isTSTypeAliasDeclaration()||parent.isTSDeclareFunction()||(parent.isExportNamedDeclaration()||parent.isExportSpecifier())&&parent.node.exportKind===`type`)}function importedName$1(specifier){return t.isIdentifier(specifier.imported)?specifier.imported.name:specifier.imported.value}function collectMacroImports(parsed,macro){const imports=[];for(const statement of parsed.ast.program.body){if(!t.isImportDeclaration(statement)||statement.source.value!==macro.moduleId)continue;for(const specifier of statement.specifiers){if(!t.isImportSpecifier(specifier)||importedName$1(specifier)!==macro.name)continue;imports.push({binding:parsed.programPath.scope.getBinding(specifier.local.name),block:parsed.block,declaration:statement,localName:specifier.local.name,specifier,typeOnly:statement.importKind===`type`||specifier.importKind===`type`,parsed})}}return imports}function isCanonicalMacroImportBinding(bindingPath,macro){if(!bindingPath?.isImportSpecifier())return false;const declaration=bindingPath.parentPath;return declaration?.isImportDeclaration()===true&&declaration.node.source.value===macro.moduleId&&declaration.node.importKind!==`type`&&bindingPath.node.importKind!==`type`&&importedName$1(bindingPath.node)===macro.name}function resolveDirectCall(referencePath,topLevelOnly=true){const callPath=referencePath.parentPath;if(!callPath?.isCallExpression()||callPath.node.callee!==referencePath.node)return;const statementPath=callPath.parentPath;if(!statementPath?.isExpressionStatement()||topLevelOnly&&!statementPath.parentPath?.isProgram())return;return{callPath,statementPath}}function collectDirectMacroCalls(parsed,macro,options={}){const calls=[];const isGlobalMacro=(path,name)=>name===macro.name&&!hasValueBinding(parsed,path,name)&&options.hasModuleShadow?.(name)!==true;const rejectGlobalWrite=path=>{if(!options.rejectInvalidReferences)return;const identifier=t.getAssignmentIdentifiers(path.node)[macro.name];if(identifier&&isGlobalMacro(path,macro.name))throw createPageDeclarationError(parsed.block,identifier,`${macro.name} 全局宏不能被重新赋值。`)};traverse(parsed.ast,{"AssignmentExpression|UpdateExpression|ForInStatement|ForOfStatement":rejectGlobalWrite,ReferencedIdentifier(path){const canonicalImport=isCanonicalMacroImportBinding(path.scope.getBinding(path.node.name)?.path,macro);if(canonicalImport&&options.includeCanonicalImports===false)return;if(!canonicalImport&&!isGlobalMacro(path,path.node.name))return;if(!isRuntimeReference(path))return;const directCall=resolveDirectCall(path,options.topLevelOnly!==false);if(!directCall){if(options.rejectInvalidReferences)throw createPageDeclarationError(parsed.block,path.node,`${macro.name} 全局宏只能用于顶层直接调用,不能被引用、传递或嵌套调用。`);return}calls.push({block:parsed.block,call:directCall.callPath.node,statement:directCall.statementPath.node})}});return calls}function collectBoundCalls(macroImport,macro){if(!macroImport.binding)return[];const write=macroImport.binding.constantViolations.find(path=>!hasTypeScriptValueBinding(macroImport.parsed,path,macroImport.localName));if(write)throw createPageDeclarationError(macroImport.block,write.node,`${macro.name} 导入绑定不能被重新赋值。`);const calls=[];for(const referencePath of macroImport.binding.referencePaths){if(!isRuntimeReference(referencePath)||hasTypeScriptValueBinding(macroImport.parsed,referencePath,macroImport.localName))continue;const directCall=resolveDirectCall(referencePath);if(!directCall||macroImport.typeOnly)throw createPageDeclarationError(macroImport.block,referencePath.node,`${macro.name} 导入绑定只能用于顶层直接调用,不能被引用、传递或嵌套调用。`);calls.push({block:macroImport.block,call:directCall.callPath.node,statement:directCall.statementPath.node})}return calls}function getCrossBlockCandidates(path,importedFromOtherBlock,name,parsed){const candidates=importedFromOtherBlock.get(name);if(!candidates?.length)return;return hasValueBinding(parsed,path,name)?void 0:candidates}function collectCrossBlockCalls(parsedBlocks,macroImports,macro){const calls=[];for(const parsed of parsedBlocks){const importedFromOtherBlock=/* @__PURE__ */ new Map;for(const macroImport of macroImports){if(macroImport.block===parsed.block)continue;const entries=importedFromOtherBlock.get(macroImport.localName)??[];entries.push(macroImport);importedFromOtherBlock.set(macroImport.localName,entries)}if(!importedFromOtherBlock.size)continue;const rejectCrossBlockWrite=path=>{for(const[name,identifier]of Object.entries(t.getAssignmentIdentifiers(path.node))){if(!getCrossBlockCandidates(path,importedFromOtherBlock,name,parsed))continue;throw createPageDeclarationError(parsed.block,identifier,`${macro.name} 导入绑定不能被重新赋值。`)}};traverse(parsed.ast,{"AssignmentExpression|UpdateExpression|ForInStatement|ForOfStatement":rejectCrossBlockWrite,ReferencedIdentifier(path){const candidates=getCrossBlockCandidates(path,importedFromOtherBlock,path.node.name,parsed);if(!candidates||!isRuntimeReference(path))return;const directCall=resolveDirectCall(path);const runtimeCandidates=candidates.filter(candidate=>!candidate.typeOnly);if(!directCall||!runtimeCandidates.length)throw createPageDeclarationError(parsed.block,path.node,`${macro.name} 导入绑定只能用于顶层直接调用,不能被引用、传递或嵌套调用。`);if(runtimeCandidates.length>1)throw createPageDeclarationError(parsed.block,path.node,`${macro.name} 调用对应了多个导入绑定。`);calls.push({block:parsed.block,call:directCall.callPath.node,statement:directCall.statementPath.node})}})}return calls}function collectMacroCallsFromPrograms(parsedBlocks,macro){const macroImports=parsedBlocks.flatMap(parsed=>collectMacroImports(parsed,macro));return{calls:[...macroImports.flatMap(macroImport=>collectBoundCalls(macroImport,macro)),...collectCrossBlockCalls(parsedBlocks,macroImports,macro),...parsedBlocks.flatMap(parsed=>collectDirectMacroCalls(parsed,macro,{hasModuleShadow:name=>hasModuleVisibleValueBinding(parsedBlocks,name),includeCanonicalImports:false,rejectInvalidReferences:true}))],runtimeImports:macroImports.filter(macroImport=>!macroImport.typeOnly)}}function collectDirectMacroCallsForTransform(parsed,macro){return collectDirectMacroCalls(parsed,macro,{topLevelOnly:false})}function hasRuntimeCode(node){if(`declare`in node&&node.declare===true||t.isTSInterfaceDeclaration(node)||t.isTSTypeAliasDeclaration(node)||t.isTSDeclareFunction(node)||t.isEmptyStatement(node))return false;if(t.isImportDeclaration(node)||t.isTSImportEqualsDeclaration(node))return node.importKind!==`type`;if(t.isExportNamedDeclaration(node))return node.exportKind!==`type`&&(node.declaration?hasRuntimeCode(node.declaration):node.specifiers.some(specifier=>!t.isExportSpecifier(specifier)||specifier.exportKind!==`type`));if(t.isTSModuleDeclaration(node))return Boolean(node.body&&hasRuntimeCode(node.body));if(t.isTSModuleBlock(node))return node.body.some(hasRuntimeCode);return true}function createParsedBlock(ast,block){let programPath;const typeScriptValueBindings=/* @__PURE__ */ new Map;const registerTypeScriptValue=path=>{if(!t.isIdentifier(path.node.id)||!hasRuntimeCode(path.node)||path.findParent(parent=>`declare`in parent.node&&parent.node.declare===true))return;let owner=path.scope.block;for(let parent=path.parentPath;parent&&parent.node!==owner;parent=parent.parentPath)if(parent.isTSModuleBlock()||parent.isTSModuleDeclaration()){owner=parent.node;break}const names=typeScriptValueBindings.get(owner)??/* @__PURE__ */ new Set;names.add(path.node.id.name);typeScriptValueBindings.set(owner,names)};traverse(ast,{Program(path){programPath=path},TSEnumDeclaration:registerTypeScriptValue,TSModuleDeclaration:registerTypeScriptValue,TSImportEqualsDeclaration:registerTypeScriptValue});if(!programPath)throw new Error(`${block.filename}:1:1 无法读取页面声明模块。`);return{ast,block,programPath,typeScriptValueBindings}}function parsePageDeclarationBlock(block){let ast;try{ast=parse$3(block.content,{...BABEL_TS_MODULE_PARSER_OPTIONS,sourceFilename:block.filename})}catch(error){throw createPageDeclarationParseError(block,error)}return createParsedBlock(ast,block)}function createProgramBlock(ast,kind){return createParsedBlock(ast,{content:``,filename:``,kind,offset:0,order:0,source:``})}function unwrapStaticExpression(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTSTypeAssertion(node)||t.isTypeCastExpression(node)||t.isParenthesizedExpression(node))return unwrapStaticExpression(node.expression);return node}function resolveStaticString(node){const value=unwrapStaticExpression(node);if(t.isStringLiteral(value))return value.value;if(t.isTemplateLiteral(value)&&value.expressions.length===0)return value.quasis[0]?.value.cooked??value.quasis[0]?.value.raw??``}function resolveObjectKey(property){if(property.computed)return;if(t.isIdentifier(property.key))return property.key.name;if(t.isStringLiteral(property.key)||t.isNumericLiteral(property.key))return String(property.key.value)}function defineSafeProperty(target,key,value){Object.defineProperty(target,key,{configurable:true,enumerable:true,value,writable:true})}function resolveStaticRouteValue(pageCall,node){const value=unwrapStaticExpression(node);if(t.isStringLiteral(value)||t.isBooleanLiteral(value))return value.value;if(t.isNullLiteral(value))return null;if(t.isNumericLiteral(value)&&Number.isFinite(value.value))return value.value;if(t.isUnaryExpression(value)&&(value.operator===`-`||value.operator===`+`)&&t.isNumericLiteral(value.argument)){const numberValue=value.operator===`-`?-value.argument.value:value.argument.value;if(Number.isFinite(numberValue))return numberValue}if(t.isTemplateLiteral(value)&&value.expressions.length===0)return value.quasis[0]?.value.cooked??value.quasis[0]?.value.raw??``;if(t.isArrayExpression(value))return value.elements.map(element=>{if(!element||t.isSpreadElement(element)||!t.isExpression(element))throw createPageDeclarationError(pageCall.block,element??value,`${WEVU_DEFINE_PAGE_MACRO}().meta 只能包含无空项、无展开的有限 JSON 值。`);return resolveStaticRouteValue(pageCall,element)});if(t.isObjectExpression(value)){const result={};for(const property of value.properties){if(!t.isObjectProperty(property)||!t.isExpression(property.value))throw createPageDeclarationError(pageCall.block,property,`${WEVU_DEFINE_PAGE_MACRO}().meta 不支持展开、方法或访问器。`);const key=resolveObjectKey(property);if(key==null)throw createPageDeclarationError(pageCall.block,property.key,`${WEVU_DEFINE_PAGE_MACRO}().meta 不支持计算或动态属性名。`);defineSafeProperty(result,key,resolveStaticRouteValue(pageCall,property.value))}return result}throw createPageDeclarationError(pageCall.block,value,`${WEVU_DEFINE_PAGE_MACRO}().meta 只能包含静态有限 JSON 值。`)}function resolvePageDeclaration(pageCall){const call=pageCall.call;if(call.arguments.length!==1||!t.isExpression(call.arguments[0]))throw createPageDeclarationError(pageCall.block,call,`${WEVU_DEFINE_PAGE_MACRO}() 必须且只能接收一个静态对象参数。`);const declaration=unwrapStaticExpression(call.arguments[0]);if(!t.isObjectExpression(declaration))throw createPageDeclarationError(pageCall.block,call.arguments[0],`${WEVU_DEFINE_PAGE_MACRO}() 必须且只能接收一个静态对象参数。`);let name;let meta;const seen=/* @__PURE__ */ new Set;for(const property of declaration.properties){if(!t.isObjectProperty(property)||!t.isExpression(property.value))throw createPageDeclarationError(pageCall.block,property,`${WEVU_DEFINE_PAGE_MACRO}() 不支持展开、方法或访问器。`);const key=resolveObjectKey(property);if(key==null)throw createPageDeclarationError(pageCall.block,property.key,`${WEVU_DEFINE_PAGE_MACRO}() 不支持计算或动态属性名。`);if(key!==`name`&&key!==`meta`)throw createPageDeclarationError(pageCall.block,property.key,`${WEVU_DEFINE_PAGE_MACRO}() 不支持属性 "${key}";path 由页面注册位置生成。`);if(seen.has(key))throw createPageDeclarationError(pageCall.block,property.key,`${WEVU_DEFINE_PAGE_MACRO}() 的属性 "${key}" 不能重复。`);seen.add(key);if(key===`name`){const staticName=resolveStaticString(property.value);if(staticName==null||staticName.trim().length===0)throw createPageDeclarationError(pageCall.block,property.value,`${WEVU_DEFINE_PAGE_MACRO}().name 必须是非空静态字符串。`);name=staticName}else{const value=unwrapStaticExpression(property.value);if(!t.isObjectExpression(value))throw createPageDeclarationError(pageCall.block,property.value,`${WEVU_DEFINE_PAGE_MACRO}().meta 必须是静态对象。`);meta=resolveStaticRouteValue(pageCall,value)}}if(name==null)throw createPageDeclarationError(pageCall.block,declaration,`${WEVU_DEFINE_PAGE_MACRO}() 必须声明非空静态 name。`);return meta===void 0?{name}:{name,meta}}function tryResolveStaticPageMeta(pageCall){const argument=pageCall.call.arguments[0];if(pageCall.call.arguments.length!==1||!t.isExpression(argument))return;const value=unwrapStaticExpression(argument);if(!t.isObjectExpression(value))return;try{return resolveStaticRouteValue(pageCall,value)}catch{return}}const PAGE_META_MACRO={moduleId:WE_VU_MODULE_ID,name:WEVU_DEFINE_PAGE_META_MACRO};const PAGE_ROUTE_MACRO={moduleId:WEVU_ROUTER_MODULE_ID,name:WEVU_DEFINE_PAGE_MACRO};function collectPageMetaCallsForTransform(ast){return collectDirectMacroCallsForTransform(createProgramBlock(ast,`script`),PAGE_META_MACRO).map(call=>call.call)}function collectPageMetaCallsFromPrograms(programs){const parsedBlocks=[];for(const kind of[`script`,`scriptSetup`]){const ast=programs[kind];if(ast)parsedBlocks.push(createProgramBlock(ast,kind))}return collectMacroCallsFromPrograms(parsedBlocks,PAGE_META_MACRO).calls.map(call=>call.call)}function analyzePageRouteBlocks(blocks,parsedBlocks){const{calls:unsortedCalls,runtimeImports}=collectMacroCallsFromPrograms(parsedBlocks,PAGE_ROUTE_MACRO);const blockOrder=new Map(blocks.map((block,index)=>[block,index]));const calls=unsortedCalls.sort((left,right)=>{return(blockOrder.get(left.block)??0)-(blockOrder.get(right.block)??0)||getAbsoluteOffset(left.block,left.call)-getAbsoluteOffset(right.block,right.call)});const importEdits=getImportRemovalEdits(runtimeImports);if(!calls.length)return{edits:importEdits,parsedBlocks};if(calls.length>1)throw createPageDeclarationError(calls[1].block,calls[1].call,`同一个页面只能声明一次 ${WEVU_DEFINE_PAGE_MACRO}()。`);const pageCall=calls[0];return{declaration:resolvePageDeclaration(pageCall),declarationSourceFile:pageCall.block.filename,parsedBlocks,edits:[...importEdits,{block:pageCall.block,start:pageCall.statement.start??0,end:pageCall.statement.end??0}]}}function analyzePageDeclarationBlocks(blocks){return analyzePageRouteBlocks(blocks,blocks.map(parsePageDeclarationBlock))}function analyzePageCompileTimeMacroBlocks(blocks){const parsedBlocks=blocks.map(parsePageDeclarationBlock);const routeAnalysis=analyzePageRouteBlocks(blocks,parsedBlocks);const{calls,runtimeImports}=collectMacroCallsFromPrograms(parsedBlocks,PAGE_META_MACRO);return{...routeAnalysis,pageMeta:calls.length===1?tryResolveStaticPageMeta(calls[0]):void 0,edits:[...routeAnalysis.edits,...getImportRemovalEdits(runtimeImports),...calls.map(call=>({block:call.block,start:call.statement.start??0,end:call.statement.end??0}))]}}function collectSfcScriptBlocks(source,filename,descriptor,resolvedIds={}){const blocks=[];const appendBlock=(block,kind,resolvedId)=>{if(!block)return;const external=Boolean(block.src&&resolvedId);blocks.push({content:block.content,filename:external?resolvedId:filename,kind,offset:external?0:block.loc.start.offset,order:block.loc.start.offset,source:external?block.content:source})};appendBlock(descriptor.script,`script`,resolvedIds.scriptResolvedId);appendBlock(descriptor.scriptSetup,`scriptSetup`,resolvedIds.scriptSetupResolvedId);blocks.sort((left,right)=>left.order-right.order);return blocks}function createSourceTransforms(filename,source,blocks,analysis){const transforms=/* @__PURE__ */ new Map;for(const block of blocks){const current=transforms.get(block.filename);if(current&&current.source!==block.source)throw new Error(`${block.filename}:1:1 页面声明源文件内容不一致。`);if(!current)transforms.set(block.filename,{code:new MagicString(block.source),source:block.source})}for(const[sourceFile,transform]of transforms){const edits=analysis.edits.filter(edit=>edit.block.filename===sourceFile).map(edit=>({end:edit.block.offset+edit.end,start:edit.block.offset+edit.start})).sort((left,right)=>left.start-right.start);for(let index=0;index<edits.length;index+=1){const edit=edits[index];if(edit.start<0||edit.end>transform.source.length||edit.start>edit.end)throw new Error(`${sourceFile}:1:1 页面声明擦除范围无效。`);if(index>0&&edit.start<edits[index-1].end)throw new Error(`${sourceFile}:1:1 页面声明擦除范围发生重叠。`);const replacement=transform.source.slice(edit.start,edit.end).replace(/[^\r\n\u2028\u2029]/g,` `);transform.code.overwrite(edit.start,edit.end,replacement)}}if(!transforms.has(filename))transforms.set(filename,{code:new MagicString(source),source});return transforms}function updateScriptBlockSource(block,info,transform,sourceMap){if(!block||!info||!transform)return block;const content=transform.code.slice(info.offset,info.offset+info.content.length);return{...block,content,map:block.src&&sourceMap?transform.code.generateMap({hires:true,includeContent:true,source:info.filename}):block.map}}function resolveSourcePosition$1(source,offset){let line=1;let lineStart=0;for(let index=0;index<offset;index+=1){const char=source.charCodeAt(index);if(char===10||char===8232||char===8233){line+=1;lineStart=index+1}else if(char===13){line+=1;if(source.charCodeAt(index+1)===10)index+=1;lineStart=index+1}}return{column:offset-lineStart+1,line,offset}}function createDescriptorForExternalScriptCompile(descriptor,blocks,transforms,sourceMap){if(!descriptor.scriptSetup||!blocks.some(block=>block.filename!==descriptor.filename))return;const bundle=new Bundle({separator:``});let source=``;let script=null;let scriptSetup=null;for(const block of blocks){const original=block.kind===`script`?descriptor.script:descriptor.scriptSetup;const chunk=transforms.get(block.filename).code.clone().snip(block.offset,block.offset+block.content.length);const content=chunk.toString();const openingTag=`<script${block.kind===`scriptSetup`?` setup`:``}${original?.lang?` lang=${JSON.stringify(original.lang)}`:``}>\n`;bundle.append(openingTag);bundle.addSource({content:chunk,filename:block.filename});bundle.append(`<\/script>
4
4
  `);source+=openingTag;const startOffset=source.length;source+=`${content}<\/script>\n`;const attrs={...original.attrs};delete attrs.src;const nextBlock={...original,attrs,src:void 0,content,loc:{source:content,start:resolveSourcePosition$1(source,startOffset),end:resolveSourcePosition$1(source,startOffset+content.length)}};if(block.kind===`script`)script=nextBlock;else scriptSetup=nextBlock}return{descriptor:{...descriptor,source,script,scriptSetup},map:sourceMap?bundle.generateMap({hires:true,includeContent:true}):void 0}}const PAGE_DECLARATION_MACRO_HINT_RE=new RegExp(`(?:^|[^\\p{ID_Continue}$\\u200C\\u200D])${WEVU_DEFINE_PAGE_MACRO}(?![\\p{ID_Continue}$\\u200C\\u200D])`,`u`);function isOriginalVueSfc(filename){return!filename.includes(`?`)&&!filename.includes(`#`)&&/\.vue$/i.test(filename)}function parsePageDeclarationSfc(source,filename,ignoreEmpty=true){const parsed=parseVueSfc(source,{filename,ignoreEmpty,templateParseOptions:{prefixIdentifiers:false}});if(parsed.errors.length)throw createSfcParseError(parsed.errors[0],{filename,source,formatMessage:(message,location)=>`${filename}:${location?.start.line??1}:${location?.start.column??1} 解析页面声明 SFC 失败:${message}`});return parsed.descriptor}function mayContainPageDeclaration(source){return source.includes(`\\`)||PAGE_DECLARATION_MACRO_HINT_RE.test(source)}function mayContainPageMeta(source){return source.includes(`\\`)||source.includes(WEVU_DEFINE_PAGE_META_MACRO)}function stripAnalyzedPageMacrosFromSfcDescriptor(source,filename,descriptor,sourceMap,blocks,analysis){if(!analysis.edits.length&&!blocks.some(block=>block.filename!==filename))return;const transforms=createSourceTransforms(filename,source,blocks,analysis);for(const parsed of analysis.parsedBlocks)if(parsed.block.filename!==filename)rebaseExternalScriptImports(parsed,filename,transforms.get(parsed.block.filename).code,analysis.parsedBlocks);const scriptBlock=blocks.find(block=>block.kind===`script`);const scriptSetupBlock=blocks.find(block=>block.kind===`scriptSetup`);const descriptorWithStrippedScripts={...descriptor,source:transforms.get(filename).code.toString(),script:updateScriptBlockSource(descriptor.script,scriptBlock,scriptBlock?transforms.get(scriptBlock.filename):void 0,sourceMap),scriptSetup:updateScriptBlockSource(descriptor.scriptSetup,scriptSetupBlock,scriptSetupBlock?transforms.get(scriptSetupBlock.filename):void 0,sourceMap)};const externalCompile=createDescriptorForExternalScriptCompile(descriptorWithStrippedScripts,blocks,transforms,sourceMap);const mainTransform=transforms.get(filename);const hasMainEdits=analysis.edits.some(edit=>edit.block.filename===filename);return{code:mainTransform.code.toString(),descriptor:descriptorWithStrippedScripts,routeConfig:analysis.declaration,pageMeta:analysis.pageMeta,descriptorForCompile:externalCompile?.descriptor,map:sourceMap&&hasMainEdits?mainTransform.code.generateMap({hires:true,includeContent:true,source:filename}):void 0,scriptMap:externalCompile?.map}}function stripPageDeclarationFromSfcDescriptor(source,filename,descriptor,sourceMap=true,resolvedIds={}){const blocks=collectSfcScriptBlocks(source,filename,descriptor,resolvedIds);return stripAnalyzedPageMacrosFromSfcDescriptor(source,filename,descriptor,sourceMap,blocks,analyzePageDeclarationBlocks(blocks))}function prepareSfcScriptCompile(source,filename,descriptor,sourceMap=true,resolvedIds={},isPage=true){const blocks=collectSfcScriptBlocks(source,filename,descriptor,resolvedIds);return stripAnalyzedPageMacrosFromSfcDescriptor(source,filename,descriptor,sourceMap,blocks,isPage?analyzePageCompileTimeMacroBlocks(blocks):{edits:[],parsedBlocks:blocks.map(parsePageDeclarationBlock)})}async function extractPageDeclarationWithDependencies(source,filename,options){if(!isOriginalVueSfc(filename)){if(!mayContainPageDeclaration(source))return{dependencies:[]};const analysis=analyzePageDeclarationBlocks([{content:source,filename,kind:`script`,offset:0,order:0,source}]);return{declaration:analysis.declaration,declarationSourceFile:analysis.declarationSourceFile,dependencies:[]}}if(!mayContainPageDeclaration(source)&&(!source.includes(`<script`)||!source.includes(`src`)))return{dependencies:[]};const descriptor=parsePageDeclarationSfc(source,filename);const inlineBlocks=collectSfcScriptBlocks(source,filename,descriptor);if(!Boolean(descriptor.script?.src||descriptor.scriptSetup?.src)&&!inlineBlocks.some(block=>mayContainPageDeclaration(block.content)))return{dependencies:[]};const resolved=await resolveSfcBlockSrc(descriptor,filename,options??{});const resolvedIds={scriptResolvedId:resolved.scriptResolvedId,scriptSetupResolvedId:resolved.scriptSetupResolvedId};const dependencies=[...new Set([resolved.scriptResolvedId,resolved.scriptSetupResolvedId].filter(dependency=>Boolean(dependency)))];const blocks=collectSfcScriptBlocks(source,filename,resolved.descriptor,resolvedIds);if(!blocks.some(block=>mayContainPageDeclaration(block.content)))return{dependencies};const analysis=analyzePageDeclarationBlocks(blocks);return{declaration:analysis.declaration,declarationSourceFile:analysis.declarationSourceFile,dependencies}}function extractPageDeclaration(source,filename){if(isOriginalVueSfc(filename)){const descriptor=parsePageDeclarationSfc(source,filename);return analyzePageDeclarationBlocks(collectSfcScriptBlocks(source,filename,descriptor)).declaration}return analyzePageDeclarationBlocks([{content:source,filename,kind:`script`,offset:0,order:0,source}]).declaration}function stripPageDeclaration(source,filename){if(isOriginalVueSfc(filename)){const result=stripPageDeclarationFromSfcDescriptor(source,filename,parsePageDeclarationSfc(source,filename));return result?{code:result.code,map:result.map}:void 0}const block={content:source,filename,kind:`script`,offset:0,order:0,source};const analysis=analyzePageDeclarationBlocks([block]);if(!analysis.edits.length)return;const transform=createSourceTransforms(filename,source,[block],analysis).get(filename);return{code:transform.code.toString(),map:transform.code.generateMap({hires:true,includeContent:true,source:filename})}}const WE_VU_RUNTIME_CAPABILITY_ORDER=[`patchStrategy`,`templateRefs`,`inlineEvents`,`setDataHighFrequencyWarning`,`scopedSlots`,`layout`,`jsxIslands`];const WE_VU_RUNTIME_CAPABILITY_INSTALLERS={patchStrategy:`installPatchStrategy`,templateRefs:`installTemplateRefs`,inlineEvents:`installInlineEvents`,setDataHighFrequencyWarning:`installSetDataHighFrequencyWarning`,scopedSlots:`installScopedSlots`,layout:`installLayout`,jsxIslands:`installJsxIslands`};function createWevuRuntimeCapabilityMetadata(required,conservative=[]){const requiredSet=new Set(required);if(requiredSet.has(`layout`))requiredSet.add(`templateRefs`);const sortedRequired=WE_VU_RUNTIME_CAPABILITY_ORDER.filter(name=>requiredSet.has(name));if(!sortedRequired.length)return;const conservativeSet=new Set(conservative);const sortedConservative=sortedRequired.filter(name=>conservativeSet.has(name));return{required:sortedRequired,...sortedConservative.length?{conservative:sortedConservative}:{}}}function createWevuRuntimeCapabilityMetadataFromBindingManifest(manifest){const required=[];const features=manifest.features;if(features.templateRefs)required.push(`templateRefs`);if(features.inlineEvents)required.push(`inlineEvents`);if(features.scopedSlots)required.push(`scopedSlots`);if(features.layout)required.push(`layout`);if(features.jsxIslands)required.push(`jsxIslands`);return createWevuRuntimeCapabilityMetadata(required)}function mergeWevuRuntimeCapabilityMetadata(...metadata){const required=/* @__PURE__ */ new Set;const conservative=/* @__PURE__ */ new Set;for(const item of metadata){item?.required.forEach(name=>required.add(name));item?.conservative?.forEach(name=>conservative.add(name))}return createWevuRuntimeCapabilityMetadata(required,conservative)}const RESERVED_VUE_COMPONENT_TAGS=/* @__PURE__ */ new Set([`template`,`slot`,`component`,`transition`,`keep-alive`,`teleport`,`suspense`]);const VUE_COMPONENT_TAG_RE=/^[A-Z_$][\w$]*$/i;const PASCAL_CASE_TAG_RE=/^[A-Z][\w$]*$/;function isAutoImportCandidateTag(tag){return tag.includes(`-`)||PASCAL_CASE_TAG_RE.test(tag)}function analyzeVueTemplateTags(template,options){const tags=/* @__PURE__ */ new Set;try{const{ast,scripts}=parseTemplateWithScriptModules(template,{onError:()=>{}},void 0,baseParse);const visit=node=>{if(node.type===NodeTypes.ELEMENT){if(scripts.byStart.has(node.loc.start.offset))return;const tag=node.tag;const normalizedTag=tag.toLowerCase();if((!options||options.shouldCollect(tag))&&!RESERVED_VUE_COMPONENT_TAGS.has(normalizedTag)&&!isBuiltinComponent(tag))tags.add(tag);node.children.forEach(visit)}};ast.children.forEach(visit);return{tags}}catch(error){return{tags,errorMessage:error instanceof Error?error.message:String(error)}}}function warnVueTemplateTagAnalysis(errorMessage,options){if(errorMessage!==void 0){const warn=options.warn;const warnLabel=options.warnLabel||`模板标签收集`;const filename=options.filename||`<未知文件>`;warn?.(`[Vue 模板] 解析失败:${warnLabel}(${filename}):${errorMessage}`)}}function collectVueTemplateTags(template,options){const{warn,warnLabel,filename}=options;const analysis=analyzeVueTemplateTags(template,options);if(analysis.errorMessage!==void 0)warnVueTemplateTagAnalysis(analysis.errorMessage,{warn,warnLabel,filename});return analysis.tags}const BASE_LIBRARY_VERSION_PATTERN=/^\d+(?:\.\d+)*$/;function createBaseLibraryHintState(){return{reported:/* @__PURE__ */ new Set}}function createBaseLibraryCompileContext(options){return{version:options?.version,hintState:options?.hintState,reported:/* @__PURE__ */ new Set}}function parseBaseLibraryVersion(version){const normalized=version.trim().replace(/^v/i,``);if(!BASE_LIBRARY_VERSION_PATTERN.test(normalized))return;return normalized.split(`.`).map(segment=>Number(segment))}function isBaseLibraryVersionSatisfied(version,minimum){if(!version)return false;const current=parseBaseLibraryVersion(version);const required=parseBaseLibraryVersion(minimum);if(!current||!required)return false;for(let index=0;index<Math.max(current.length,required.length);index+=1){const diff=(current[index]??0)-(required[index]??0);if(diff!==0)return diff>0}return true}function consumeBaseLibraryHint(context,request){if(isBaseLibraryVersionSatisfied(context.version,request.minimum))return false;if(context.reported.has(request.topic)||context.hintState?.reported.has(request.topic))return false;context.reported.add(request.topic);context.hintState?.reported.add(request.topic);return true}const IDENTIFIER_RE$5=/^[A-Z_$][\w$]*$/i;const INLINE_GLOBALS=/* @__PURE__ */ new Set([`Math`,`Number`,`Date`,`Array`,`Object`,`Boolean`,`String`,`RegExp`,`Map`,`Set`,`JSON`,`Intl`,`Promise`,`console`,`Infinity`,`undefined`,`NaN`,`isFinite`,`isNaN`,`parseFloat`,`parseInt`,`decodeURI`,`decodeURIComponent`,`encodeURI`,`encodeURIComponent`,`require`,`arguments`,WEVU_CLASS_STYLE_RUNTIME_MODULE,`__wevuUnref`,`globalThis`,`setTimeout`,`clearTimeout`,`setInterval`,`clearInterval`,`Page`,`App`,`Component`,`requirePlugin`,`getApp`,`getCurrentPages`,...getMiniProgramRuntimeGlobalKeys()]);function createInlineExpressionParameterIdentifiers(scope,usedNames){const generatedNames=/* @__PURE__ */ new Set;const createIdentifier=name=>{let identifier=scope.generateUidIdentifier(name);while(usedNames.has(identifier.name)||generatedNames.has(identifier.name))identifier=scope.generateUidIdentifier(name);generatedNames.add(identifier.name);return identifier};return{context:createIdentifier(`ctx`),scope:createIdentifier(`scope`),event:createIdentifier(`event`)}}function createMemberAccess$2(target,prop){if(IDENTIFIER_RE$5.test(prop))return t.memberExpression(t.identifier(target),t.identifier(prop));return t.memberExpression(t.identifier(target),t.stringLiteral(prop),true)}function isTemplateContextThis(path){let childPath=path;let parentPath=path.parentPath;while(parentPath){if((parentPath.isObjectMethod()||parentPath.isClassMethod())&&(childPath.key===`key`||childPath.listKey===`decorators`)){childPath=parentPath;parentPath=parentPath.parentPath;continue}if(parentPath.isFunction()&&!parentPath.isArrowFunctionExpression())return false;if((parentPath.isClassProperty()||parentPath.isClassPrivateProperty()||parentPath.isClassAccessorProperty())&&childPath.key===`value`)return false;if(parentPath.isStaticBlock())return false;childPath=parentPath;parentPath=parentPath.parentPath}return true}function replaceIdentifierWithExpression$1(path,replacement){const parent=path.parentPath;if(parent.isObjectProperty()&&parent.node.shorthand&&parent.node.key===path.node){parent.node.shorthand=false;parent.node.value=replacement;return}path.replaceWith(replacement)}const babelExpressionCache=new LRUCache({max:1024});const inlineHandlerCache=new LRUCache({max:1024});const BABEL_GENERATE_MINI_PROGRAM_OPTIONS={compact:true,jsescOption:{quotes:`single`,minimal:true}};function stripPatternTypes(node){if(!node||typeof node!==`object`)return;if(`typeAnnotation`in node)node.typeAnnotation=null;if(`optional`in node)node.optional=false;if(node.type===`AssignmentPattern`)stripPatternTypes(node.left);else if(node.type===`RestElement`)stripPatternTypes(node.argument);else if(node.type===`ObjectPattern`)for(const property of node.properties)stripPatternTypes(property.type===`RestElement`?property.argument:property.value);else if(node.type===`ArrayPattern`)for(const element of node.elements)stripPatternTypes(element)}function stripTypeScriptExpression(ast){traverse(ast,{TSAsExpression(path){path.replaceWith(path.node.expression)},TSNonNullExpression(path){path.replaceWith(path.node.expression)},TSTypeAssertion(path){path.replaceWith(path.node.expression)},Function(path){path.node.typeParameters=null;path.node.returnType=null;for(const param of path.node.params)stripPatternTypes(param)}});return ast}function parseTypeScriptExpression(exp){return stripTypeScriptExpression(parse$3(`(${exp})`,{sourceType:`module`,plugins:[`typescript`]}))}function generateExpression(node){const{code}=generate(node,BABEL_GENERATE_MINI_PROGRAM_OPTIONS);return code}function parseBabelExpression(exp){const cached=babelExpressionCache.get(exp);if(cached!==void 0)return cached===false?null:cached;try{const stmt=parseTypeScriptExpression(exp).program.body[0];if(!stmt||!(`expression`in stmt)){babelExpressionCache.set(exp,false);return null}const expression=stmt.expression;babelExpressionCache.set(exp,expression);return expression}catch{babelExpressionCache.set(exp,false);return null}}function parseBabelExpressionFile(exp){try{const ast=parseTypeScriptExpression(exp);const stmt=ast.program.body[0];if(!stmt||!(`expression`in stmt))return null;return{ast,expression:stmt.expression}}catch{return null}}function hasOwn(source,key){return Object.prototype.hasOwnProperty.call(source,key)}function getForItemAccess(context,name){for(let index=context.forStack.length-1;index>=0;index-=1){const forInfo=context.forStack[index];if(forInfo?.item===name&&forInfo.itemAccess)return forInfo.itemAccess}return name}function rewriteForItemAccess(ast,context){const itemAccesses=/* @__PURE__ */ new Map;for(const forInfo of context.forStack)if(forInfo.item&&forInfo.itemAccess)itemAccesses.set(forInfo.item,forInfo.itemAccess);if(!itemAccesses.size)return;traverse(ast,{Identifier(path){if(!path.isReferencedIdentifier()||path.scope.hasBinding(path.node.name))return;const replacement=itemAccesses.get(path.node.name);if(!replacement)return;const parsed=replacement.split(`.`).slice(1).reduce((target,property)=>t.memberExpression(target,t.identifier(property)),t.identifier(path.node.name));replaceIdentifierWithExpression$1(path,parsed);path.skip()}})}const DIGIT_NUMERIC_SEPARATOR_RE=/\d_\d/;const NON_DECIMAL_NUMERIC_LITERAL_RE=/\b0[bxo][\da-f_]/i;const DECIMAL_BIGINT_LITERAL_RE=/\b\d[\d_]*n\b/;const NON_DECIMAL_NUMERIC_RAW_RE=/^0[bxo]/i;function hasExtendedNumericLiteralSyntax(exp){return DIGIT_NUMERIC_SEPARATOR_RE.test(exp)||NON_DECIMAL_NUMERIC_LITERAL_RE.test(exp)||DECIMAL_BIGINT_LITERAL_RE.test(exp)}function serializeBigIntForWxml(value){const asNumber=Number(value);if(!Number.isSafeInteger(asNumber))return t.stringLiteral(value.toString());return asNumber<0?t.unaryExpression(`-`,t.numericLiteral(Math.abs(asNumber))):t.numericLiteral(asNumber)}function normalizeTopLevelBigInt(expression){if(t.isBigIntLiteral(expression))return serializeBigIntForWxml(BigInt(expression.value));if(t.isUnaryExpression(expression,{operator:`-`})&&t.isBigIntLiteral(expression.argument))return serializeBigIntForWxml(-BigInt(expression.argument.value));return expression}function canonicalizeNumericLiteral(node){const raw=node.extra?.raw;if(typeof raw!==`string`||!raw.includes(`_`)&&!NON_DECIMAL_NUMERIC_RAW_RE.test(raw))return;delete node.extra?.raw;delete node.extra?.rawValue}function templateLiteralToConcat(node){const segments=[];node.quasis.forEach((quasi,index)=>{const cooked=quasi.value.cooked??quasi.value.raw??``;if(cooked)segments.push(t.stringLiteral(cooked));if(index<node.expressions.length){let inner=node.expressions[index];if(t.isTemplateLiteral(inner))inner=templateLiteralToConcat(inner);segments.push(inner)}});if(segments.length===0)return t.stringLiteral(``);if(segments.length===1)return segments[0];return segments.reduce((acc,cur)=>t.binaryExpression(`+`,acc,cur))}function isOptionalChainNode(node){return Boolean(node&&(t.isOptionalMemberExpression(node)||t.isOptionalCallExpression(node)))}function collectOptionalChain(node){const operations=[];let current=node;while(isOptionalChainNode(current)){if(t.isOptionalMemberExpression(current)){operations.push({type:`member`,optional:current.optional===true,computed:current.computed,property:t.cloneNode(current.property)});current=current.object;continue}operations.push({type:`call`,optional:current.optional===true,args:current.arguments.map(arg=>t.cloneNode(arg))});current=current.callee}if(!t.isExpression(current))return null;return{base:t.cloneNode(current),operations:operations.reverse()}}function applyOptionalChainOperation(base,operation){if(operation.type===`member`)return t.memberExpression(base,t.cloneNode(operation.property),operation.computed);return t.callExpression(base,operation.args.map(arg=>t.cloneNode(arg)))}function lowerOptionalChain(node){const chain=collectOptionalChain(node);if(!chain)return t.cloneNode(node);const segments=[chain.base];for(const operation of chain.operations){const currentBase=t.cloneNode(segments[segments.length-1]);segments.push(applyOptionalChainOperation(currentBase,operation))}let lowered=t.cloneNode(segments[segments.length-1]);for(let index=chain.operations.length-1;index>=0;index--){if(!chain.operations[index].optional)continue;lowered=t.conditionalExpression(t.binaryExpression(`==`,t.cloneNode(segments[index]),t.nullLiteral()),t.identifier(`undefined`),lowered)}return lowered}const TEMPLATE_INTERPOLATION_RE=/\$\{([^}]+)\}/g;const EMPTY_STRING_CONCAT_LEFT_RE=/'\s*\+\s*''/g;const EMPTY_STRING_CONCAT_RIGHT_RE=/''\s*\+\s*'/g;const LEADING_EMPTY_CONCAT_RE=/^\s*''\s*\+\s*/g;const TRAILING_EMPTY_CONCAT_RE=/\s*\+\s*''\s*$/g;function rewriteVueSlotsExpression(ast){traverse(ast,{MemberExpression:{exit(path){const node=path.node;if(!t.isIdentifier(node.object,{name:`$slots`}))return;const access=t.memberExpression(t.identifier(`vueSlots`),t.cloneNode(node.property),node.computed);path.replaceWith(t.logicalExpression(`&&`,t.identifier(`vueSlots`),access));path.skip()}},OptionalMemberExpression:{exit(path){const node=path.node;if(!t.isIdentifier(node.object,{name:`$slots`}))return;const access=t.memberExpression(t.identifier(`vueSlots`),t.cloneNode(node.property),node.computed);path.replaceWith(t.logicalExpression(`&&`,t.identifier(`vueSlots`),access));path.skip()}},Identifier:{exit(path){if(!path.isReferencedIdentifier()||path.node.name!==`$slots`)return;const parent=path.parentPath.node;if((t.isMemberExpression(parent)||t.isOptionalMemberExpression(parent))&&parent.object===path.node)return;path.replaceWith(t.identifier(`vueSlots`));path.skip()}}})}function normalizeWxmlExpression(exp){const hasTypeScriptSyntax=/\s(?:as|satisfies)\s/.test(exp)||/[\w$)\]]!(?=[.[\s,);:?]|$)/.test(exp)||/^\s*<[^>]+>/.test(exp);const needsVueSlotsRewrite=exp.includes(`$slots`);const needsThisRewrite=/\bthis\./.test(exp);const needsNumericLiteralRewrite=hasExtendedNumericLiteralSyntax(exp);if(!exp.includes("`")&&!exp.includes(`??`)&&!exp.includes(`?.`)&&!hasTypeScriptSyntax&&!needsVueSlotsRewrite&&!needsThisRewrite&&!needsNumericLiteralRewrite)return exp;try{const ast=parse$3(`(${exp})`,{sourceType:`module`,plugins:[`typescript`]});const stmt=ast.program.body[0];if(!stmt||!(`expression`in stmt))return exp;if(needsVueSlotsRewrite)rewriteVueSlotsExpression(ast);const expressionStatement=stmt;expressionStatement.expression=normalizeTopLevelBigInt(expressionStatement.expression);traverse(ast,{MemberExpression:{exit(path){const node=path.node;if(!t.isThisExpression(node.object)||node.computed||!t.isIdentifier(node.property))return;path.replaceWith(t.identifier(node.property.name));path.skip()}},TSAsExpression(path){path.replaceWith(path.node.expression)},TSNonNullExpression(path){path.replaceWith(path.node.expression)},TSTypeAssertion(path){path.replaceWith(path.node.expression)},NumericLiteral(path){canonicalizeNumericLiteral(path.node)},OptionalMemberExpression:{exit(path){if(isOptionalChainNode(path.parentPath.node))return;path.replaceWith(lowerOptionalChain(path.node));path.skip()}},OptionalCallExpression:{exit(path){if(isOptionalChainNode(path.parentPath.node))return;path.replaceWith(lowerOptionalChain(path.node));path.skip()}},LogicalExpression:{exit(path){if(path.node.operator!==`??`)return;const left=path.node.left;const right=path.node.right;const test=t.binaryExpression(`!=`,t.cloneNode(left),t.nullLiteral());path.replaceWith(t.conditionalExpression(test,t.cloneNode(left),t.cloneNode(right)));path.skip()}},TemplateLiteral(path){if(t.isTaggedTemplateExpression(path.parent))return;path.replaceWith(templateLiteralToConcat(path.node))}});const normalized=stmt.expression;return generateExpression(normalized)}catch{if(exp.startsWith("`")&&exp.endsWith("`")){let rewritten=`'${exp.slice(1,-1).replace(TEMPLATE_INTERPOLATION_RE,`' + ($1) + '`)}'`;rewritten=rewritten.replace(EMPTY_STRING_CONCAT_LEFT_RE,`'`).replace(EMPTY_STRING_CONCAT_RIGHT_RE,`'`);rewritten=rewritten.replace(LEADING_EMPTY_CONCAT_RE,``).replace(TRAILING_EMPTY_CONCAT_RE,``);return rewritten}return exp}}const SCOPED_SLOT_GLOBALS=/* @__PURE__ */ new Set([`Math`,`Number`,`Date`,`Array`,`Object`,`Boolean`,`String`,`RegExp`,`Map`,`Set`,`JSON`,`Intl`,`console`,`Infinity`,`undefined`,`NaN`,`isFinite`,`isNaN`,`parseFloat`,`parseInt`,`decodeURI`,`decodeURIComponent`,`encodeURI`,`encodeURIComponent`,`require`,`arguments`,`vueSlots`,WEVU_SLOT_OWNER_KEY,WEVU_SLOT_PROPS_KEY,WEVU_SLOT_PROPS_DATA_KEY,WEVU_CLASS_STYLE_RUNTIME_MODULE]);function collectScopedSlotLocals(context){const locals=/* @__PURE__ */ new Set;for(const scope of context.scopeStack)for(const name of scope)locals.add(name);return locals}function collectSlotPropMapping(context){const mapping={};for(const entry of context.slotPropStack)Object.assign(mapping,entry);return mapping}function collectForAliasMapping$2(context){const mapping={};for(const forInfo of context.forStack){if(!forInfo.itemAliases)continue;Object.assign(mapping,forInfo.itemAliases)}return mapping}function replaceIdentifierWithExpression(path,replacement){const parent=path.parentPath;if(parent.isObjectProperty()&&parent.node.shorthand&&parent.node.key===path.node){parent.node.shorthand=false;parent.node.value=replacement;return}path.replaceWith(replacement)}const IDENTIFIER_RE$4=/^[A-Z_$][\w$]*$/i;function rewriteScopedSlotExpression(exp,context){const normalized=normalizeWxmlExpression(exp);const parsed=parseBabelExpressionFile(normalized);if(!parsed)return normalized;const{ast}=parsed;const locals=collectScopedSlotLocals(context);const slotProps=collectSlotPropMapping(context);const forAliases=collectForAliasMapping$2(context);const createMemberAccess=(target,prop)=>{if(!prop)return t.identifier(target);if(IDENTIFIER_RE$4.test(prop))return t.memberExpression(t.identifier(target),t.identifier(prop));return t.memberExpression(t.identifier(target),t.stringLiteral(prop),true)};traverse(ast,{Identifier(path){if(!path.isReferencedIdentifier())return;const name=path.node.name;if(path.scope.getBinding(name))return;if(hasOwn(forAliases,name)){const aliasExp=parseBabelExpression(forAliases[name]);if(aliasExp){replaceIdentifierWithExpression(path,t.cloneNode(aliasExp,true));return}}if(locals.has(name))return;if(SCOPED_SLOT_GLOBALS.has(name))return;if(hasOwn(slotProps,name)){replaceIdentifierWithExpression(path,createMemberAccess(WEVU_SLOT_PROPS_DATA_KEY,slotProps[name]));return}replaceIdentifierWithExpression(path,createMemberAccess(WEVU_SLOT_OWNER_KEY,name))}});rewriteForItemAccess(ast,context);const stmt=ast.program.body[0];const updatedExpression=stmt&&`expression`in stmt?stmt.expression:null;return updatedExpression?generateExpression(updatedExpression):normalized}function rewriteForAliasExpression(exp,context){const normalized=normalizeWxmlExpression(exp);const forAliases=collectForAliasMapping$2(context);if(!Object.keys(forAliases).length&&!context.forStack.some(forInfo=>forInfo.itemAccess))return normalized;const parsed=parseBabelExpressionFile(normalized);if(!parsed)return normalized;const{ast}=parsed;traverse(ast,{Identifier(path){if(!path.isReferencedIdentifier())return;const name=path.node.name;if(path.scope.getBinding(name))return;if(hasOwn(forAliases,name)){const aliasExp=parseBabelExpression(forAliases[name]);if(aliasExp)replaceIdentifierWithExpression(path,t.cloneNode(aliasExp,true))}}});rewriteForItemAccess(ast,context);const stmt=ast.program.body[0];const updatedExpression=stmt&&`expression`in stmt?stmt.expression:null;return updatedExpression?generateExpression(updatedExpression):normalized}function normalizeWxmlExpressionWithContext(exp,context){if(!context)return normalizeWxmlExpression(exp);if(!context.rewriteScopedSlot)return rewriteForAliasExpression(exp,context);return rewriteScopedSlotExpression(exp,context)}const INTERNAL_GLOBALS={undefined:true,Infinity:true,NaN:true,arguments:true};const completeBindingManifests=/* @__PURE__ */ new WeakSet;function cloneSourceSpan(location){if(!location)return;return{start:{...location.start},end:{...location.end}}}function getStaticPropertyName(node){if(!node.computed&&t.isIdentifier(node.property))return node.property.name;if(node.computed&&(t.isStringLiteral(node.property)||t.isNumericLiteral(node.property)))return String(node.property.value);return null}function resolveMemberDependency(node){const segments=[];let current=node;let dynamic=false;while(t.isMemberExpression(current)||t.isOptionalMemberExpression(current)){const property=getStaticPropertyName(current);if(property===null)dynamic=true;else segments.unshift(property);if(!t.isExpression(current.object))return null;current=current.object}if(!t.isIdentifier(current)||INLINE_GLOBALS.has(current.name)||INTERNAL_GLOBALS[current.name])return null;if(dynamic)return{root:current.name,mode:`top-level`};const path=[current.name,...segments].join(`.`);return{root:current.name,path,mode:`exact-path`}}function collectDependencies(expression,context,additionalLocals){const normalized=context?normalizeWxmlExpressionWithContext(expression,context):expression;const parsed=parseBabelExpressionFile(normalized);if(!parsed)return null;const localNames=/* @__PURE__ */ new Set;for(const scope of context?.scopeStack??[])for(const name of scope)localNames.add(name);for(const name of additionalLocals??[])localNames.add(name);const dependencies=/* @__PURE__ */ new Map;let snapshotFallback=false;const addDependency=dependency=>{if(localNames.has(dependency.root)||INLINE_GLOBALS.has(dependency.root)||INTERNAL_GLOBALS[dependency.root])return;const key=`${dependency.root}:${dependency.path??``}:${dependency.mode}`;dependencies.set(key,dependency)};traverse(parsed.ast,{Identifier(path){if(!path.isReferencedIdentifier()||path.scope.hasBinding(path.node.name))return;const parent=path.parentPath;if((parent.isMemberExpression()||parent.isOptionalMemberExpression())&&parent.node.object===path.node){let outer=parent;while((outer.parentPath.isMemberExpression()||outer.parentPath.isOptionalMemberExpression())&&outer.parentPath.node.object===outer.node)outer=outer.parentPath;const dependency=resolveMemberDependency(outer.node);if(dependency)addDependency(dependency);return}if((parent.isMemberExpression()||parent.isOptionalMemberExpression())&&parent.node.property===path.node&&!parent.node.computed)return;addDependency({root:path.node.name,path:path.node.name,mode:`exact-path`})},CallExpression(path){if(t.isIdentifier(path.node.callee)&&context?.templateSafeCallNames.has(path.node.callee.name))return;snapshotFallback=true},OptionalCallExpression(){snapshotFallback=true},NewExpression(){snapshotFallback=true},Function(){snapshotFallback=true},SpreadElement(){snapshotFallback=true}});if(localNames.size&&context)for(const forInfo of context.forStack){const listExpression=forInfo.rawListExp??forInfo.listExp;if(!listExpression)continue;const outerAnalysis=collectDependencies(listExpression,{...context,scopeStack:[],forStack:[]});for(const dependency of outerAnalysis?.dependencies??[])addDependency(dependency);snapshotFallback||=outerAnalysis?.snapshotFallback??false}return{dependencies:[...dependencies.values()],snapshotFallback}}function resolveBindingDependencies(dependencies,snapshotFallback){return dependencies.map(dependency=>({root:dependency.root,...dependency.path?{path:dependency.path}:{},updateMode:snapshotFallback?`snapshot-fallback`:dependency.mode}))}function resolveBindingUpdateMode(dependencies){if(dependencies.some(dependency=>dependency.updateMode===`snapshot-fallback`))return`snapshot-fallback`;if(dependencies.some(dependency=>dependency.updateMode===`top-level`))return`top-level`;return`exact-path`}function resolveBindingScopes(context,dependencies,explicitScopes){if(explicitScopes)return explicitScopes.map(scope=>({...scope,...scope.locals?{locals:[...scope.locals]}:{}}));const scopes=[{kind:`root`,depth:0}];let forDepth=1;if(context?.rewriteScopedSlot){const roots=new Set(dependencies.map(dependency=>dependency.root));if(roots.has(WEVU_SLOT_OWNER_KEY)||roots.has(WEVU_SLOT_OWNER_PROXY_KEY)||roots.has(WEVU_SLOT_OWNER_ID_KEY)||roots.has(WEVU_SLOT_OWNER_ID_PROP)||roots.has(WEVU_SLOT_SCOPE_KEY)){scopes.push({kind:`slot-owner`,depth:1});forDepth=2}if(roots.has(WEVU_SLOT_PROPS_DATA_KEY)){scopes.push({kind:`slot-props`,depth:1});forDepth=2}}for(const[index,forInfo]of(context?.forStack??[]).entries()){const locals=[forInfo.item,forInfo.index,forInfo.key,...Object.keys(forInfo.itemAliases??{})].filter(Boolean);scopes.push({kind:`for`,depth:forDepth+index,...locals.length?{locals:[...new Set(locals)]}:{}})}return scopes}function mergeBindingScopeDependencies(analysis,scopeDependencies){const dependencies=/* @__PURE__ */ new Map;const addDependency=dependency=>{const key=`${dependency.root}:${dependency.path??``}:${dependency.mode}`;dependencies.set(key,dependency)};analysis.dependencies.forEach(addDependency);let snapshotFallback=analysis.snapshotFallback;for(const scope of scopeDependencies){const scopeAnalysis=collectDependencies(scope.expression,void 0,scope.locals);if(!scopeAnalysis){snapshotFallback=true;continue}scopeAnalysis.dependencies.forEach(addDependency);snapshotFallback||=scopeAnalysis.snapshotFallback}return{dependencies:[...dependencies.values()],snapshotFallback}}function recordBindingManifestExpression(manifest,options,context,additionalLocals){const initialAnalysis=collectDependencies(options.expression,context,additionalLocals);const analysis=initialAnalysis&&options.scopeDependencies?.length?mergeBindingScopeDependencies(initialAnalysis,options.scopeDependencies):initialAnalysis;const sourceLocation=cloneSourceSpan(options.sourceLocation);if(!analysis){manifest.bindings.push({id:`b${manifest.bindings.length}`,kind:options.kind,outputPath:options.outputPath??`*`,...options.sourceFile&&options.sourceFile!==manifest.sourceFile?{sourceFile:options.sourceFile}:{},sourceRoots:[],dependencies:[],scopes:resolveBindingScopes(context,[],options.scopes),updateMode:`snapshot-fallback`,sourceLocation});return}const{dependencies,snapshotFallback}=analysis;if(options.outputPath){const sourceRoots=[...new Set(dependencies.map(dependency=>dependency.root))];const sourcePaths=dependencies.flatMap(dependency=>dependency.path?[dependency.path]:[]);const bindingDependencies=resolveBindingDependencies(dependencies,snapshotFallback);manifest.bindings.push({id:`b${manifest.bindings.length}`,kind:options.kind,outputPath:options.outputPath,...options.sourceFile&&options.sourceFile!==manifest.sourceFile?{sourceFile:options.sourceFile}:{},sourceRoots,sourcePaths:sourcePaths.length?[...new Set(sourcePaths)]:void 0,dependencies:bindingDependencies,scopes:resolveBindingScopes(context,dependencies,options.scopes),updateMode:resolveBindingUpdateMode(bindingDependencies),sourceLocation});return}for(const dependency of dependencies){const[bindingDependency]=resolveBindingDependencies([dependency],snapshotFallback);manifest.bindings.push({id:`b${manifest.bindings.length}`,kind:options.kind,outputPath:dependency.mode===`exact-path`?dependency.path:dependency.root,...options.sourceFile&&options.sourceFile!==manifest.sourceFile?{sourceFile:options.sourceFile}:{},sourceRoots:[dependency.root],sourcePaths:dependency.path?[dependency.path]:void 0,dependencies:[bindingDependency],scopes:resolveBindingScopes(context,[dependency],options.scopes),updateMode:bindingDependency.updateMode,sourceLocation})}}function createBindingManifest(sourceFile){const manifest={version:1,sourceFile,bindings:[],features:{}};completeBindingManifests.add(manifest);return manifest}function isBindingManifestComplete(manifest){return completeBindingManifests.has(manifest)}function markBindingManifestIncomplete(manifest){completeBindingManifests.delete(manifest)}function recordBindingExpression(context,options){recordBindingManifestExpression(context.bindingManifest,options,context)}function recordSyntheticBindingExpression(manifest,options,localNames){recordBindingManifestExpression(manifest,options,void 0,localNames)}const CLASS_STYLE_WXS_MODULE=WEVU_CLASS_STYLE_RUNTIME_MODULE;const CLASS_STYLE_WXS_FILE=WEVU_CLASS_STYLE_RUNTIME_FILE;function resolveScriptModuleTag(extension){return(extension.startsWith(`.`)?extension.slice(1):extension)===`sjs`?`sjs`:`wxs`}function buildClassStyleWxsTag(extension,src,platform){const normalized=extension.startsWith(`.`)?extension.slice(1):extension;const resolvedSrc=src??`./${CLASS_STYLE_WXS_FILE}.${normalized}`;const options=getMiniProgramScriptModuleOptions(resolveMiniProgramPlatform(platform),normalized);return`<${platform?options.tag:resolveScriptModuleTag(normalized)} ${options.moduleAttribute}="${CLASS_STYLE_WXS_MODULE}" ${options.sourceAttribute}="${resolvedSrc}"/>`}function resolveClassStyleWxsLocation(options){const normalizedExt=options.extension.startsWith(`.`)?options.extension.slice(1):options.extension;const normalizedRoot=normalizeRoot(options.packageRoot??``);const fileName=normalizedRoot?`${normalizedRoot}/${CLASS_STYLE_WXS_FILE}.${normalizedExt}`:`${CLASS_STYLE_WXS_FILE}.${normalizedExt}`;const baseDir=path.posix.dirname(toPosixPath(options.relativeBase));const fromDir=baseDir===`.`?`.`:baseDir;let src=path.posix.relative(fromDir,fileName);if(!src||src===`.`)src=path.posix.basename(fileName);if(!src.startsWith(`.`)&&!src.startsWith(`/`))src=`./${src}`;return{fileName,src}}function getClassStyleWxsSource(options={}){const isSjs=(options.extension?.startsWith(`.`)?options.extension.slice(1):options.extension)===`sjs`;const isArrayFunctionLines=isSjs?[`function isArray(value) {`,` if (!toString) {`,` return false`,` }`,` return toString.call(value) === '[object Array]'`,`}`]:[`function isArray(value) {`,` if (!value) {`,` return false`,` }`,` if (typeof Array !== 'undefined' && Array.isArray && Array.isArray(value)) {`,` return true`,` }`,` if (toString && toString.call(value) === '[object Array]') {`,` return true`,` }`,` return typeof value.length === 'number' && typeof value.join === 'function'`,`}`];const hyphenateUpperCaseLine=isSjs?` res += str.charAt(i).toLowerCase()`:` res += String.fromCharCode(code + 32)`;const bodyLines=[`var objectCtor = ({}).constructor`,`var objectProto = objectCtor ? objectCtor.prototype : null`,`var hasOwn = objectProto ? objectProto.hasOwnProperty : null`,`var toString = objectProto ? objectProto.toString : null`,``,...isArrayFunctionLines,``,`function getObjectKeys(obj) {`,` if (objectCtor && objectCtor.keys) {`,` return objectCtor.keys(obj)`,` }`,` if (objectCtor && objectCtor.getOwnPropertyNames) {`,` return objectCtor.getOwnPropertyNames(obj)`,` }`,` return null`,`}`,``,`function isWordCharCode(code) {`,` return (code >= 48 && code <= 57)`,` || (code >= 65 && code <= 90)`,` || (code >= 97 && code <= 122)`,` || code === 95`,`}`,``,`function isUpperCaseCode(code) {`,` return code >= 65 && code <= 90`,`}`,``,`function hyphenate(str) {`,` if (!str) {`,` return ''`,` }`,` if (str.indexOf('--') === 0) {`,` return str`,` }`,` var res = ''`,` for (var i = 0; i < str.length; i++) {`,` var code = str.charCodeAt(i)`,` if (isUpperCaseCode(code)) {`,` if (i > 0 && isWordCharCode(str.charCodeAt(i - 1))) {`,` res += '-'`,` }`,hyphenateUpperCaseLine,` continue`,` }`,` res += str.charAt(i)`,` }`,` return res`,`}`,``,`function appendStyle(base, part) {`,` if (!part) {`,` return base || ''`,` }`,` if (!base) {`,` return part`,` }`,` if (base.charAt(base.length - 1) !== ';') {`,` base += ';'`,` }`,` if (part.charAt(0) === ';') {`,` part = part.slice(1)`,` }`,` return base + part`,`}`,``,`function stylePair(key, value) {`,` if (value == null) {`,` return ''`,` }`,` if (isArray(value)) {`,` var res = ''`,` for (var i = 0; i < value.length; i++) {`,` var item = value[i]`,` if (item == null) {`,` continue`,` }`,` res = appendStyle(res, key + ':' + item)`,` }`,` return res`,` }`,` return key + ':' + value`,`}`,``,`function normalizeClass(value) {`,` var res = ''`,` if (!value) {`,` return res`,` }`,` if (typeof value === 'string') {`,` return value`,` }`,` if (isArray(value)) {`,` for (var i = 0; i < value.length; i++) {`,` var normalized = normalizeClass(value[i])`,` if (normalized) {`,` res += normalized + ' '`,` }`,` }`,` return res.trim()`,` }`,` if (typeof value === 'object') {`,` var keys = getObjectKeys(value)`,` if (!keys) {`,` return res`,` }`,` for (var i = 0; i < keys.length; i++) {`,` var key = keys[i]`,` if ((!hasOwn || hasOwn.call(value, key)) && value[key]) {`,` res += key + ' '`,` }`,` }`,` return res.trim()`,` }`,` return res`,`}`,``,`function stringifyStyle(obj) {`,` var res = ''`,` var keys = getObjectKeys(obj)`,` if (!keys) {`,` return res`,` }`,` for (var i = 0; i < keys.length; i++) {`,` var key = keys[i]`,` if (hasOwn && !hasOwn.call(obj, key)) {`,` continue`,` }`,` var val = obj[key]`,` if (val == null) {`,` continue`,` }`,` var name = hyphenate(key)`,` if (isArray(val)) {`,` for (var j = 0; j < val.length; j++) {`,` var item = val[j]`,` if (item == null) {`,` continue`,` }`,` res = appendStyle(res, name + ':' + item)`,` }`,` }`,` else {`,` res = appendStyle(res, name + ':' + val)`,` }`,` }`,` return res`,`}`,``,`function normalizeStyle(value) {`,` if (value == null) {`,` return ''`,` }`,` if (typeof value === 'string') {`,` return value`,` }`,` if (isArray(value)) {`,` var res = ''`,` for (var i = 0; i < value.length; i++) {`,` var normalized = normalizeStyle(value[i])`,` if (normalized) {`,` res = appendStyle(res, normalized)`,` }`,` }`,` return res`,` }`,` if (typeof value === 'object') {`,` return stringifyStyle(value)`,` }`,` return ''`,`}`,``];const exportLines=(options.moduleFormat??(isSjs?`esm`:`commonjs`))===`esm`?[`export default {`,` cls: normalizeClass,`,` style: normalizeStyle,`,` stylePair: stylePair,`,`}`]:[`module.exports = {`,` cls: normalizeClass,`,` style: normalizeStyle,`,` stylePair: stylePair,`,`}`];return[...bodyLines,...exportLines,``].join(`
@@ -19,9 +19,9 @@ const __weapp_defineComponentJson = (config) => (__weapp_json_macro_values.push(
19
19
  const __weapp_defineSitemapJson = (config) => (__weapp_json_macro_values.push(config), config)
20
20
  const __weapp_defineThemeJson = (config) => (__weapp_json_macro_values.push(config), config)
21
21
  `.trimStart()+ms.toString()+`\nexport default __weapp_json_macro_values\n`;const extension=resolveScriptSetupExtension$1(lang);return await withTempDirLock(tempRoot,async()=>{await ensureDir(tempDir);const tempFile=path.join(tempDir,`${basename}.json-macro.${unique}.${extension}`);await writeFile(tempFile,evalSource,`utf8`);try{const{mod,dependencies}=await bundleRequire({filepath:tempFile,cwd:dir,tsconfig:false});const resolved=mod?.default??mod;const values=Array.isArray(resolved)?resolved:[resolved];let accumulator={};for(const raw of values){if(raw===void 0)continue;let next=raw;if(typeof next===`function`)next=next();if(next&&typeof next.then===`function`)next=await next;if(!next||typeof next!==`object`||Array.isArray(next))throw new Error(`宏的返回值必须解析为对象。`);if(hasOwn(next,`$schema`))delete next.$schema;if(options?.merge){const merged=options.merge(accumulator,next);if(merged&&typeof merged===`object`&&!Array.isArray(merged))accumulator=merged}else recursive(accumulator,next)}if(!Object.keys(accumulator).length)return{dependencies};return{config:accumulator,dependencies}}finally{try{await remove(tempDir)}catch{}}})}const JSON_MACROS=/* @__PURE__ */ new Set([`defineAppJson`,`definePageJson`,`defineComponentJson`,`defineSitemapJson`,`defineThemeJson`]);const JSON_MACRO_HINT_RE=/\bdefine(?:App|Page|Component|Sitemap|Theme)Json\s*\(/;function mayContainJsonMacro(content){return JSON_MACRO_HINT_RE.test(content)}function parseScriptSetupAst(content,filename){try{return parse$3(content,BABEL_TS_MODULE_PARSER_OPTIONS)}catch(error){const message=error instanceof Error?error.message:String(error);throw new Error(`解析 ${filename} 中的 <script setup> 失败:${message}`)}}function collectMacroCallPaths(ast,filename){const macroNames=/* @__PURE__ */ new Set;const macroStatements=[];traverse(ast,{CallExpression(path){const callee=path.node.callee;if(!t.isIdentifier(callee))return;if(!JSON_MACROS.has(callee.name))return;if(!(path.parentPath?.isExpressionStatement()&&path.parentPath.parentPath?.isProgram()))throw new Error(`${callee.name}() 必须在 <script setup> 顶层语句中使用(${filename})。`);macroNames.add(callee.name);macroStatements.push(path.parentPath)}});return{macroNames,macroStatements}}function assertSingleMacro(macroNames,filename){if(macroNames.size>1)throw new Error(`同一个 <script setup> 仅能使用 ${[...JSON_MACROS].join(`, `)} 中的一个(${filename})。`);return macroNames.values().next().value}function findProgramPath(ast){let programPath;traverse(ast,{Program(path){programPath=path;path.stop()}});return programPath}function stripScriptSetupMacroStatements(content,ast,filename,sourceMap){const ms=sourceMap?new MagicString(sourceMap.source,{offset:sourceMap.offset}):new MagicString(content);const macroStatementSources=[];const body=ast.program?.body??[];for(const statement of body){if(!t.isExpressionStatement(statement))continue;const expr=statement.expression;if(!t.isCallExpression(expr)||!t.isIdentifier(expr.callee))continue;const name=expr.callee.name;if(!JSON_MACROS.has(name))continue;if(expr.arguments.length!==1)throw new Error(`${name}() 在 ${filename} 中必须且只能传 1 个参数。`);if(typeof statement.start===`number`&&typeof statement.end===`number`)macroStatementSources.push(content.slice(statement.start,statement.end));if(typeof statement.start===`number`&&typeof statement.end===`number`)ms.remove(statement.start,statement.end)}const stripped=sourceMap?ms.slice(0,content.length):ms.toString();const result={stripped,macroStatementSources};if(!sourceMap||stripped===content)return result;const sourceFile=sourceMap.sourceFile;let map;return{...result,get map(){return map??=ms.generateMap({hires:true,includeContent:true,source:sourceFile})}}}function splitJsonMacroCallsFromCode(code,filename){let ast;try{ast=parse$3(code,BABEL_TS_MODULE_PARSER_OPTIONS)}catch(error){try{ast=parseJsLike(code)}catch(fallbackError){const message=error instanceof Error?error.message:String(error);const fallbackMessage=fallbackError instanceof Error?fallbackError.message:String(fallbackError);throw new Error(`解析 ${filename} 的编译脚本失败:${message};兜底解析失败:${fallbackMessage}`)}}const ms=new MagicString(code);const macroSources=[];traverse(ast,{ExpressionStatement(path){const expr=path.node.expression;if(!t.isCallExpression(expr)||!t.isIdentifier(expr.callee))return;if(!JSON_MACROS.has(expr.callee.name))return;const start=path.node.start;const end=path.node.end;if(typeof start===`number`&&typeof end===`number`){macroSources.push(code.slice(start,end));ms.remove(start,end)}}});return{macroSources,stripped:ms.toString()}}function stripJsonMacroCallsFromCode(code,filename){return splitJsonMacroCallsFromCode(code,filename).stripped}function unwrapTsExpression$1(node){if(t.isTSAsExpression(node)||t.isTSNonNullExpression(node)||t.isTSTypeAssertion(node))return unwrapTsExpression$1(node.expression);return node}function resolveStaticLiteralValue(node){const normalized=unwrapTsExpression$1(node);if(t.isStringLiteral(normalized)||t.isNumericLiteral(normalized)||t.isBooleanLiteral(normalized))return normalized.value;if(t.isNullLiteral(normalized))return null;if(t.isUnaryExpression(normalized)&&(normalized.operator===`-`||normalized.operator===`+`)&&t.isNumericLiteral(normalized.argument))return normalized.operator===`-`?-normalized.argument.value:normalized.argument.value;if(t.isArrayExpression(normalized)){const values=[];for(const element of normalized.elements){if(!element||t.isSpreadElement(element)||!t.isExpression(element))throw new Error(`unsupported static json macro array item`);values.push(resolveStaticLiteralValue(element))}return values}if(t.isObjectExpression(normalized)){const value={};for(const property of normalized.properties){if(!t.isObjectProperty(property)||property.computed||!t.isExpression(property.value))throw new Error(`unsupported static json macro object property`);const key=property.key;const keyName=t.isIdentifier(key)?key.name:t.isStringLiteral(key)||t.isNumericLiteral(key)?String(key.value):void 0;if(!keyName)throw new Error(`unsupported static json macro object key`);value[keyName]=resolveStaticLiteralValue(property.value)}return value}throw new Error(`unsupported static json macro value`)}function resolveStaticJsonMacroConfig(macroStatements,options){let accumulator={};for(const statementPath of macroStatements){const arg=statementPath.get(`expression`).get(`arguments.0`)?.node;if(!arg||!t.isExpression(arg))return;let next;try{next=resolveStaticLiteralValue(arg)}catch{return}if(!next||typeof next!==`object`||Array.isArray(next))return;if(hasOwn(next,`$schema`))delete next.$schema;if(options?.merge){const merged=options.merge(accumulator,next);if(merged&&typeof merged===`object`&&!Array.isArray(merged))accumulator=merged}else recursive(accumulator,next)}return accumulator}function withSourceMap(result,rewrite){if(!(`map`in rewrite))return result;return{...result,get map(){return rewrite.map}}}async function evaluateJsonMacroConfig(content,filename,lang,options){const contentForEval=options?.preambleContent?`${options.preambleContent}\n${content}`:content;const ast=parseScriptSetupAst(contentForEval,filename);const{macroNames,macroStatements}=collectMacroCallPaths(ast,filename);const macroName=assertSingleMacro(macroNames,filename);if(!macroName||!macroStatements.length)return;const programPath=findProgramPath(ast);if(!programPath)return;const{bodyPaths,keptStatementPaths}=collectKeptStatementPaths(programPath,macroStatements);return await evaluateScriptSetupJsonMacro({preambleContent:options?.preambleContent,originalContent:content,filename,lang,macroName,macroStatements,bodyPaths,keptStatementPaths,options})}async function extractJsonMacroFromScriptSetupInternal(content,filename,lang,options,sourceMap){if(!mayContainJsonMacro(content))return{stripped:content};const ast=parseScriptSetupAst(content,filename);const{macroNames,macroStatements}=collectMacroCallPaths(ast,filename);assertSingleMacro(macroNames,filename);const rewrite=stripScriptSetupMacroStatements(content,ast,filename,sourceMap);const{stripped,macroStatementSources}=rewrite;if(macroNames.size===0)return withSourceMap({stripped},rewrite);const macroHash=createHash(`sha256`).update(macroStatementSources.join(`
22
- `)).digest(`hex`).slice(0,12);const staticConfig=resolveStaticJsonMacroConfig(macroStatements,options);if(staticConfig)return withSourceMap({stripped,config:Object.keys(staticConfig).length?staticConfig:void 0,macroHash,dependencies:[],...options?.merge?{}:{isStatic:true}},rewrite);const result=await evaluateJsonMacroConfig(content,filename,lang,options);return withSourceMap(result?{stripped,config:result.config,macroHash,dependencies:result.dependencies}:{stripped,macroHash},rewrite)}async function extractJsonMacroFromScriptSetup(content,filename,lang,options){return await extractJsonMacroFromScriptSetupInternal(content,filename,lang,options)}async function extractJsonMacroFromScriptSetupWithSourceMap(content,filename,lang,options,sourceMap){return await extractJsonMacroFromScriptSetupInternal(content,filename,lang,options,sourceMap)}function toPlainRecord(value){if(!value||typeof value!==`object`||Array.isArray(value))return{};return value}function mergeJsonWithStrategy(target,source,strategy,context){const base={...toPlainRecord(target)};const incoming=toPlainRecord(source);if(typeof strategy===`function`){const maybeNext=strategy(base,incoming,context);if(maybeNext&&typeof maybeNext===`object`&&!Array.isArray(maybeNext))return maybeNext;return base}if(strategy===`replace`)return{...incoming};if(strategy===`assign`)return{...base,...incoming};const merged={...base};recursive(merged,incoming);return merged}function createJsonMerger(strategy,baseContext){return(target,source,stage)=>{return mergeJsonWithStrategy(target,source,strategy,{...baseContext,stage})}}function resolveWarnHandler(warn){return warn??(message=>{console.warn(message)})}function isStaticObjectKeyMatch$1(key,expected){if(t.isIdentifier(key))return key.name===expected;if(t.isStringLiteral(key))return key.value===expected;return false}function getObjectPropertyByKey$3(node,key){for(const prop of node.properties){if(!t.isObjectProperty(prop)||prop.computed)continue;if(isStaticObjectKeyMatch$1(prop.key,key))return prop}return null}function buildInjectedFeaturesObject(enabled){return t.objectExpression(Array.from(enabled,key=>{return t.objectProperty(t.identifier(key),t.booleanLiteral(true))}))}function getObjectMemberIndexByKey(node,key){return node.properties.findIndex(prop=>{if(t.isObjectProperty(prop)&&!prop.computed)return isStaticObjectKeyMatch$1(prop.key,key);if(t.isObjectMethod(prop)&&!prop.computed)return isStaticObjectKeyMatch$1(prop.key,key);return false})}function isTopLevel(path){return path.getFunctionParent()==null}function injectWevuShareLifecycleHooksIntoOptionsObject(_optionsObject,_enabled){return false}function collectWevuPageFeatureFlags(ast){const namedHookLocals=/* @__PURE__ */ new Map;const namespaceLocals=/* @__PURE__ */ new Set;for(const stmt of ast.program.body){if(!t.isImportDeclaration(stmt)||!isWevuPageFeatureModuleId(stmt.source.value))continue;for(const specifier of stmt.specifiers)if(t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.imported)){const importedName=specifier.imported.name;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[importedName];if(matched)namedHookLocals.set(specifier.local.name,matched)}else if(t.isImportNamespaceSpecifier(specifier))namespaceLocals.add(specifier.local.name)}if(namedHookLocals.size===0&&namespaceLocals.size===0)return/* @__PURE__ */ new Set;const enabled=/* @__PURE__ */ new Set;function consumeHookCallByName(name){const matched=namedHookLocals.get(name);if(matched)enabled.add(matched)}function consumeNamespaceHookCall(namespace,hookName){if(!namespaceLocals.has(namespace))return;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[hookName];if(matched)enabled.add(matched)}traverse(ast,{CallExpression(path){const callee=path.node.callee;if(t.isIdentifier(callee)){consumeHookCallByName(callee.name);return}if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)){const property=callee.property;if(t.isIdentifier(property))consumeNamespaceHookCall(callee.object.name,property.name)}},OptionalCallExpression(path){const callee=path.node.callee;if(t.isIdentifier(callee)){consumeHookCallByName(callee.name);return}if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)){const property=callee.property;if(t.isIdentifier(property))consumeNamespaceHookCall(callee.object.name,property.name)}}});return enabled}function injectWevuPageFeatureFlagsIntoOptionsObject(optionsObject,enabled){if(!enabled.size)return false;const expectedKeys=[...enabled];const existingFeaturesProp=getObjectPropertyByKey$3(optionsObject,`features`);let changed=false;if(!existingFeaturesProp){const featuresObject=buildInjectedFeaturesObject(enabled);const setupIndex=getObjectMemberIndexByKey(optionsObject,`setup`);const insertAt=setupIndex>=0?setupIndex:0;optionsObject.properties.splice(insertAt,0,t.objectProperty(t.identifier(`features`),featuresObject));changed=true}else if(t.isObjectExpression(existingFeaturesProp.value)){const featuresObject=existingFeaturesProp.value;const injectedProps=[];for(const key of expectedKeys){if(getObjectPropertyByKey$3(featuresObject,key))continue;injectedProps.push(t.objectProperty(t.identifier(key),t.booleanLiteral(true)))}if(injectedProps.length){featuresObject.properties.splice(0,0,...injectedProps);changed=true}}else if(t.isIdentifier(existingFeaturesProp.value)||t.isMemberExpression(existingFeaturesProp.value)){const base=t.cloneNode(existingFeaturesProp.value,true);const injected=buildInjectedFeaturesObject(enabled);injected.properties.push(t.spreadElement(base));existingFeaturesProp.value=injected;changed=true}changed=injectWevuShareLifecycleHooksIntoOptionsObject(optionsObject,enabled)||changed;return changed}function createEmptyModuleAnalysis(id,engine){return{id,engine,wevuNamedHookLocals:/* @__PURE__ */ new Map,wevuNamespaceLocals:/* @__PURE__ */ new Set,importedBindings:/* @__PURE__ */ new Map,localFunctions:/* @__PURE__ */ new Map,exports:/* @__PURE__ */ new Map}}const externalModuleAnalysisCache=new LRUCache({max:256});const moduleAnalysisCache=new LRUCache({max:512});function createExternalModuleAnalysisCacheKey(moduleId,astEngine){return`${astEngine??`babel`}::${moduleId}`}function createModuleAnalysisCacheKey(moduleId,astEngine){return`${astEngine??`babel`}::${moduleId}`}function getFunctionLikeFromExpression(node){if(!node)return null;if(t.isFunctionExpression(node)||t.isArrowFunctionExpression(node))return node;return null}function isOxcFunctionLike(node){return node?.type===`FunctionDeclaration`||node?.type===`FunctionExpression`||node?.type===`ArrowFunctionExpression`}function getImportedSpecifierName(node){if(node?.type===`Identifier`)return node.name;if((node?.type===`StringLiteral`||node?.type===`Literal`)&&typeof node.value===`string`)return node.value}function createModuleAnalysis(id,ast){const localFunctions=/* @__PURE__ */ new Map;const exports=/* @__PURE__ */ new Map;const importedBindings=/* @__PURE__ */ new Map;const wevuNamedHookLocals=/* @__PURE__ */ new Map;const wevuNamespaceLocals=/* @__PURE__ */ new Set;function registerFunctionDeclaration(node){if(!node.id||!node.id.name)return;localFunctions.set(node.id.name,node)}function registerVariableFunction(node){if(!t.isIdentifier(node.id))return;const fn=getFunctionLikeFromExpression(node.init);if(!fn)return;localFunctions.set(node.id.name,fn)}for(const stmt of ast.program.body){if(t.isFunctionDeclaration(stmt)){registerFunctionDeclaration(stmt);continue}if(t.isVariableDeclaration(stmt)){for(const decl of stmt.declarations)registerVariableFunction(decl);continue}if(t.isImportDeclaration(stmt)){const source=stmt.source.value;for(const specifier of stmt.specifiers)if(t.isImportSpecifier(specifier)){const imported=specifier.imported;if(isWevuPageFeatureModuleId(source)&&t.isIdentifier(imported)){const importedName=imported.name;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[importedName];if(matched)wevuNamedHookLocals.set(specifier.local.name,matched)}importedBindings.set(specifier.local.name,{kind:`named`,source,importedName:t.isIdentifier(imported)?imported.name:String(imported.value)})}else if(t.isImportDefaultSpecifier(specifier))importedBindings.set(specifier.local.name,{kind:`default`,source});else if(t.isImportNamespaceSpecifier(specifier)){importedBindings.set(specifier.local.name,{kind:`namespace`,source});if(isWevuPageFeatureModuleId(source))wevuNamespaceLocals.add(specifier.local.name)}continue}if(t.isExportNamedDeclaration(stmt)){if(stmt.declaration){if(t.isFunctionDeclaration(stmt.declaration)&&stmt.declaration.id){registerFunctionDeclaration(stmt.declaration);exports.set(stmt.declaration.id.name,{type:`local`,localName:stmt.declaration.id.name})}else if(t.isVariableDeclaration(stmt.declaration))for(const decl of stmt.declaration.declarations){registerVariableFunction(decl);if(t.isIdentifier(decl.id))exports.set(decl.id.name,{type:`local`,localName:decl.id.name})}continue}if(stmt.source){const source=stmt.source.value;for(const spec of stmt.specifiers){if(!t.isExportSpecifier(spec))continue;const exportedName=t.isIdentifier(spec.exported)?spec.exported.name:void 0;const importedName=t.isIdentifier(spec.local)?spec.local.name:void 0;if(!exportedName||!importedName)continue;exports.set(exportedName,{type:`reexport`,source,importedName})}}else for(const spec of stmt.specifiers){if(!t.isExportSpecifier(spec))continue;const exportedName=t.isIdentifier(spec.exported)?spec.exported.name:void 0;const localName=t.isIdentifier(spec.local)?spec.local.name:void 0;if(!exportedName||!localName)continue;exports.set(exportedName,{type:`local`,localName})}continue}if(t.isExportDefaultDeclaration(stmt)){const decl=stmt.declaration;if(t.isFunctionDeclaration(decl)){registerFunctionDeclaration(decl);if(decl.id)exports.set(`default`,{type:`local`,localName:decl.id.name});else exports.set(`default`,{type:`inline`,node:decl})}else if(t.isIdentifier(decl))exports.set(`default`,{type:`local`,localName:decl.name});else{const fn=getFunctionLikeFromExpression(decl);if(fn)exports.set(`default`,{type:`inline`,node:fn})}}}return{id,engine:`babel`,ast,wevuNamedHookLocals,wevuNamespaceLocals,importedBindings,localFunctions,exports}}function resolveOxcParseFilename(id){if(path.extname(id))return id;return`${id}.js`}function createModuleAnalysisWithOxc(id,code){const ast=parseJsLikeWithEngine(code,{engine:`oxc`,filename:resolveOxcParseFilename(id)});const localFunctions=/* @__PURE__ */ new Map;const exports=/* @__PURE__ */ new Map;const importedBindings=/* @__PURE__ */ new Map;const wevuNamedHookLocals=/* @__PURE__ */ new Map;const wevuNamespaceLocals=/* @__PURE__ */ new Set;function registerFunctionDeclaration(node){if(node?.id?.type===`Identifier`)localFunctions.set(node.id.name,node)}function registerVariableFunction(node){if(node?.id?.type!==`Identifier`||!isOxcFunctionLike(node.init))return;localFunctions.set(node.id.name,node.init)}for(const stmt of ast.body??[]){if(stmt?.type===`FunctionDeclaration`){registerFunctionDeclaration(stmt);continue}if(stmt?.type===`VariableDeclaration`){for(const decl of stmt.declarations??[])registerVariableFunction(decl);continue}if(stmt?.type===`ImportDeclaration`){const source=getImportedSpecifierName(stmt.source);if(!source)continue;for(const specifier of stmt.specifiers??[])if(specifier.type===`ImportSpecifier`&&specifier.local?.type===`Identifier`){const importedName=getImportedSpecifierName(specifier.imported);if(!importedName)continue;if(isWevuPageFeatureModuleId(source)){const matched=WE_VU_PAGE_HOOK_TO_FEATURE[importedName];if(matched)wevuNamedHookLocals.set(specifier.local.name,matched)}importedBindings.set(specifier.local.name,{kind:`named`,source,importedName})}else if(specifier.type===`ImportDefaultSpecifier`&&specifier.local?.type===`Identifier`)importedBindings.set(specifier.local.name,{kind:`default`,source});else if(specifier.type===`ImportNamespaceSpecifier`&&specifier.local?.type===`Identifier`){importedBindings.set(specifier.local.name,{kind:`namespace`,source});if(isWevuPageFeatureModuleId(source))wevuNamespaceLocals.add(specifier.local.name)}continue}if(stmt?.type===`ExportNamedDeclaration`){if(stmt.declaration?.type===`FunctionDeclaration`){registerFunctionDeclaration(stmt.declaration);if(stmt.declaration.id?.type===`Identifier`)exports.set(stmt.declaration.id.name,{type:`local`,localName:stmt.declaration.id.name});continue}if(stmt.declaration?.type===`VariableDeclaration`){for(const decl of stmt.declaration.declarations??[]){registerVariableFunction(decl);if(decl.id?.type===`Identifier`)exports.set(decl.id.name,{type:`local`,localName:decl.id.name})}continue}const source=getImportedSpecifierName(stmt.source);for(const spec of stmt.specifiers??[]){if(spec?.type!==`ExportSpecifier`)continue;const exportedName=getImportedSpecifierName(spec.exported);const localName=getImportedSpecifierName(spec.local);if(!exportedName||!localName)continue;if(source)exports.set(exportedName,{type:`reexport`,source,importedName:localName});else exports.set(exportedName,{type:`local`,localName})}continue}if(stmt?.type===`ExportDefaultDeclaration`){const decl=stmt.declaration;if(decl?.type===`FunctionDeclaration`){registerFunctionDeclaration(decl);if(decl.id?.type===`Identifier`)exports.set(`default`,{type:`local`,localName:decl.id.name});else exports.set(`default`,{type:`inline`,node:decl})}else if(decl?.type===`Identifier`)exports.set(`default`,{type:`local`,localName:decl.name});else if(isOxcFunctionLike(decl))exports.set(`default`,{type:`inline`,node:decl})}}return{id,engine:`oxc`,ast,wevuNamedHookLocals,wevuNamespaceLocals,importedBindings,localFunctions,exports}}const TS_WITHOUT_JSX_RE=/\.[cm]?ts(?:[?#].*)?$/i;function parseModuleAnalysisAst(id,code){const plugins=TS_WITHOUT_JSX_RE.test(id)?BABEL_TS_MODULE_PLUGINS.filter(plugin=>plugin!==`jsx`):BABEL_TS_MODULE_PLUGINS;return parse$3(code,{sourceType:`module`,plugins})}function createModuleAnalysisFromCode(id,code,options){const engine=options?.astEngine??`babel`;const cacheKey=createModuleAnalysisCacheKey(id,engine);const cached=moduleAnalysisCache.get(cacheKey);if(cached&&cached.code===code)return cached.analysis;let analysis;if(engine===`oxc`){if(!code.includes(`import`)&&!code.includes(`export`))analysis=createEmptyModuleAnalysis(id,`oxc`);else analysis=createModuleAnalysisWithOxc(id,code)}else{const ast=parseModuleAnalysisAst(id,code);analysis=createModuleAnalysis(id,ast)}moduleAnalysisCache.set(cacheKey,{code,analysis});return analysis}function getOrCreateExternalModuleAnalysis(moduleId,code,options){const cacheKey=createExternalModuleAnalysisCacheKey(moduleId,options?.astEngine);const cached=externalModuleAnalysisCache.get(cacheKey);if(cached&&cached.code===code)return cached.analysis;const analysis=createModuleAnalysisFromCode(moduleId,code,options);externalModuleAnalysisCache.set(cacheKey,{code,analysis});return analysis}const CALL_EXPRESSION_TEXT_RE=/\b[a-z_$][\w$]*(?:\s*<[^(){};]+>)?\s*(?:\?\.\s*)?\(/i;const WEVU_PAGE_HOOK_NAMES=Object.keys(WE_VU_PAGE_HOOK_TO_FEATURE);function mayContainWevuPageFeatureHints(code){return WE_VU_RUNTIME_MODULE_IDS.some(moduleId=>code.includes(moduleId))&&CALL_EXPRESSION_TEXT_RE.test(code)&&WEVU_PAGE_HOOK_NAMES.some(hookName=>code.includes(hookName))}function collectWithBabel(code){const ast=parseJsLike(code);return collectWevuPageFeatureFlags(ast)}function collectWithOxc(code){const enabled=/* @__PURE__ */ new Set;const module=createModuleAnalysisFromCode(`<inline>`,code,{astEngine:`oxc`});if(module.wevuNamedHookLocals.size===0&&module.wevuNamespaceLocals.size===0)return enabled;const visit=node=>{if(!node)return;if(node.type===`CallExpression`){const callee=node.callee;if(callee?.type===`Identifier`){const matched=module.wevuNamedHookLocals.get(callee.name);if(matched)enabled.add(matched)}else if(callee?.type===`MemberExpression`&&!callee.computed&&callee.object?.type===`Identifier`&&callee.property?.type===`Identifier`){if(module.wevuNamespaceLocals.has(callee.object.name)){const hook=callee.property.name;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[hook];if(matched)enabled.add(matched)}}}else if(node.type===`ChainExpression`){visit(node.expression);return}for(const value of Object.values(node)){if(!value)continue;if(Array.isArray(value)){for(const child of value)if(child&&typeof child===`object`&&typeof child.type===`string`)visit(child)}else if(typeof value===`object`&&typeof value.type===`string`)visit(value)}};visit(module.ast);return enabled}function collectWevuPageFeatureFlagsFromCode(code,options){if(!mayContainWevuPageFeatureHints(code))return/* @__PURE__ */ new Set;const engine=options?.astEngine??`babel`;try{return engine===`oxc`?collectWithOxc(code):collectWithBabel(code)}catch{return/* @__PURE__ */ new Set}}const WEVU_FACTORY_NAMES=/* @__PURE__ */ new Set([WE_VU_RUNTIME_APIS.defineComponent,WE_VU_RUNTIME_APIS.createWevuComponent]);const REGEXP_META_CHARS_RE=/[.*+?^${}()|[\]\\]/g;function escapeRegExp(value){return value.replace(REGEXP_META_CHARS_RE,`\\$&`)}function mayContainNamedFactoryCall(code,localName){return new RegExp(`\\b${escapeRegExp(localName)}\\b(?:\\s*<[^(){};]+>)?\\s*(?:\\?\\.)?\\s*\\(`,`m`).test(code)}function mayContainNamespaceFactoryCall(code,namespaceName){const factoryAlternation=Array.from(WEVU_FACTORY_NAMES,name=>escapeRegExp(name)).join(`|`);return new RegExp(`\\b${escapeRegExp(namespaceName)}\\b\\s*\\.\\s*(?:${factoryAlternation})\\b(?:\\s*<[^(){};]+>)?\\s*(?:\\?\\.)?\\s*\\(`,`m`).test(code)}function mayCallWevuFactoryByText(code,module){for(const[localName,binding]of module.importedBindings.entries()){if(!isWevuRuntimeModuleId(binding.source))continue;if(binding.kind===`named`&&WEVU_FACTORY_NAMES.has(binding.importedName)){if(mayContainNamedFactoryCall(code,localName))return true;continue}if(binding.kind===`namespace`&&mayContainNamespaceFactoryCall(code,localName))return true}return false}function unwrapTypeLikeExpression$2(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node))return unwrapTypeLikeExpression$2(node.expression);if(t.isParenthesizedExpression(node))return unwrapTypeLikeExpression$2(node.expression);return node}function resolveOptionsObjectFromExpression(node){const normalized=unwrapTypeLikeExpression$2(node);if(t.isObjectExpression(normalized))return normalized;if(t.isIdentifier(normalized))return null;if(t.isCallExpression(normalized)){const callee=normalized.callee;if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object,{name:`Object`})&&t.isIdentifier(callee.property,{name:`assign`}))for(let index=normalized.arguments.length-1;index>=0;index-=1){const argument=normalized.arguments[index];if(t.isSpreadElement(argument)||!t.isExpression(argument))continue;const candidate=resolveOptionsObjectFromExpression(argument);if(candidate)return candidate}}return null}function getOxcStaticPropertyName(node){if(node?.type===`Identifier`)return node.name;if((node?.type===`StringLiteral`||node?.type===`Literal`)&&typeof node.value===`string`)return node.value}function getSetupFunctionFromOptionsObject(options){for(const prop of options.properties)if(t.isObjectProperty(prop)&&!prop.computed&&isStaticObjectKeyMatch$1(prop.key,`setup`)){if(t.isFunctionExpression(prop.value)||t.isArrowFunctionExpression(prop.value))return prop.value}else if(t.isObjectMethod(prop)&&!prop.computed&&isStaticObjectKeyMatch$1(prop.key,`setup`))return prop;else if(prop?.type===`Property`&&!prop.computed&&getOxcStaticPropertyName(prop.key)===`setup`){if(prop.value?.type===`FunctionExpression`||prop.value?.type===`ArrowFunctionExpression`)return prop.value}return null}function collectTargetOptionsObjectsWithModule(ast,module){const optionsObjects=[];const constObjectBindings=/* @__PURE__ */ new Map;const pendingConstObjectRefs=[];traverse(ast,{VariableDeclarator(path){if(!isTopLevel(path))return;if(!t.isIdentifier(path.node.id))return;const init=path.node.init;if(t.isObjectExpression(init))constObjectBindings.set(path.node.id.name,init)},CallExpression(path){if(!isTopLevel(path))return;const node=path.node;if(t.isV8IntrinsicIdentifier(node.callee))return;const first=node.arguments[0];if(!first||!t.isExpression(first))return;const binding=t.isIdentifier(node.callee)?module.importedBindings.get(node.callee.name):void 0;if(t.isIdentifier(node.callee)){if(binding?.kind!==`named`||!isWevuRuntimeModuleId(binding.source))return;if(binding.importedName!==WE_VU_RUNTIME_APIS.defineComponent&&binding.importedName!==WE_VU_RUNTIME_APIS.createWevuComponent)return}else if(t.isMemberExpression(node.callee)&&!node.callee.computed&&t.isIdentifier(node.callee.object)&&t.isIdentifier(node.callee.property)){const objectBinding=module.importedBindings.get(node.callee.object.name);if(objectBinding?.kind!==`namespace`||!isWevuRuntimeModuleId(objectBinding.source))return;if(node.callee.property.name!==WE_VU_RUNTIME_APIS.defineComponent&&node.callee.property.name!==WE_VU_RUNTIME_APIS.createWevuComponent)return}else return;const inlineObject=resolveOptionsObjectFromExpression(first);if(inlineObject)optionsObjects.push(inlineObject);else if(t.isIdentifier(first)){const target=constObjectBindings.get(first.name);if(target)optionsObjects.push(target);else pendingConstObjectRefs.push(first.name)}},OptionalCallExpression(path){if(!isTopLevel(path))return;const node=path.node;const callee=node.callee;if(t.isV8IntrinsicIdentifier(callee))return;const first=node.arguments[0];if(!first||!t.isExpression(first))return;if(t.isIdentifier(callee)){const binding=module.importedBindings.get(callee.name);if(binding?.kind!==`named`||!isWevuRuntimeModuleId(binding.source))return;if(binding.importedName!==WE_VU_RUNTIME_APIS.defineComponent&&binding.importedName!==WE_VU_RUNTIME_APIS.createWevuComponent)return}else if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property)){const objectBinding=module.importedBindings.get(callee.object.name);if(objectBinding?.kind!==`namespace`||!isWevuRuntimeModuleId(objectBinding.source))return;if(callee.property.name!==WE_VU_RUNTIME_APIS.defineComponent&&callee.property.name!==WE_VU_RUNTIME_APIS.createWevuComponent)return}else return;const inlineObject=resolveOptionsObjectFromExpression(first);if(inlineObject)optionsObjects.push(inlineObject);else if(t.isIdentifier(first)){const target=constObjectBindings.get(first.name);if(target)optionsObjects.push(target);else pendingConstObjectRefs.push(first.name)}}});for(const name of pendingConstObjectRefs){const target=constObjectBindings.get(name);if(target)optionsObjects.push(target)}return{optionsObjects,module}}function unwrapOxcTypeLikeExpression(node){if(node?.type===`TSAsExpression`||node?.type===`TSSatisfiesExpression`||node?.type===`TSNonNullExpression`||node?.type===`TSTypeAssertion`||node?.type===`ParenthesizedExpression`)return unwrapOxcTypeLikeExpression(node.expression);return node}function getOxcCallExpression(node){if(node?.type===`ChainExpression`)return getOxcCallExpression(node.expression);if(node?.type===`CallExpression`)return node;return null}function resolveOxcOptionsObjectFromExpression(node,bindings){const normalized=unwrapOxcTypeLikeExpression(node);if(normalized?.type===`ObjectExpression`)return normalized;if(normalized?.type===`Identifier`)return bindings.get(normalized.name)??null;if(normalized?.type!==`CallExpression`)return null;const callee=unwrapOxcTypeLikeExpression(normalized.callee);if(callee?.type!==`MemberExpression`||callee.computed||callee.object?.type!==`Identifier`||callee.object.name!==`Object`||callee.property?.type!==`Identifier`||callee.property.name!==`assign`)return null;for(let index=normalized.arguments.length-1;index>=0;index-=1){const argument=normalized.arguments[index];if(argument?.type===`SpreadElement`)continue;const candidate=resolveOxcOptionsObjectFromExpression(argument,bindings);if(candidate)return candidate}return null}function isOxcWevuFactoryCall(call,module){const callee=unwrapOxcTypeLikeExpression(call.callee);if(callee?.type===`Identifier`){const binding=module.importedBindings.get(callee.name);return binding?.kind===`named`&&isWevuRuntimeModuleId(binding.source)&&WEVU_FACTORY_NAMES.has(binding.importedName)}if(callee?.type===`MemberExpression`&&!callee.computed&&callee.object?.type===`Identifier`&&callee.property?.type===`Identifier`){const binding=module.importedBindings.get(callee.object.name);return binding?.kind===`namespace`&&isWevuRuntimeModuleId(binding.source)&&WEVU_FACTORY_NAMES.has(callee.property.name)}return false}function collectTargetOptionsObjectsWithOxcModule(ast,module){const optionsObjects=[];const constObjectBindings=/* @__PURE__ */ new Map;const pendingConstObjectRefs=[];for(const stmt of ast?.body??[]){if(stmt?.type===`VariableDeclaration`){for(const decl of stmt.declarations??[])if(decl?.id?.type===`Identifier`&&decl.init?.type===`ObjectExpression`)constObjectBindings.set(decl.id.name,decl.init);continue}if(stmt?.type!==`ExpressionStatement`)continue;const call=getOxcCallExpression(stmt.expression);if(!call||!isOxcWevuFactoryCall(call,module))continue;const first=call.arguments?.[0];if(!first)continue;const inlineObject=resolveOxcOptionsObjectFromExpression(first,constObjectBindings);if(inlineObject)optionsObjects.push(inlineObject);else if(first.type===`Identifier`)pendingConstObjectRefs.push(first.name)}for(const name of pendingConstObjectRefs){const target=constObjectBindings.get(name);if(target)optionsObjects.push(target)}return{optionsObjects,module}}function collectTargetOptionsObjects(ast,moduleId){return collectTargetOptionsObjectsWithModule(ast,createModuleAnalysis(moduleId,ast))}function collectTargetOptionsObjectsFromCode(code,moduleId,options){if(options?.astEngine===`oxc`){if(!(code.includes(`wevu`)&&(code.includes(WE_VU_RUNTIME_APIS.defineComponent)||code.includes(WE_VU_RUNTIME_APIS.createWevuComponent))))return{optionsObjects:[],module:createEmptyModuleAnalysis(moduleId,`oxc`)};const module=createModuleAnalysisFromCode(moduleId,code,options);if(![...module.importedBindings.values()].some(binding=>isWevuRuntimeModuleId(binding.source)&&(binding.kind===`namespace`||binding.kind===`named`&&(binding.importedName===WE_VU_RUNTIME_APIS.defineComponent||binding.importedName===WE_VU_RUNTIME_APIS.createWevuComponent))))return{optionsObjects:[],module};if(!mayCallWevuFactoryByText(code,module))return{optionsObjects:[],module};return collectTargetOptionsObjectsWithOxcModule(module.ast,module)}const module=createModuleAnalysisFromCode(moduleId,code,options);return collectTargetOptionsObjectsWithModule(module.ast,module)}function getCallCalleeName(callee){if(t.isV8IntrinsicIdentifier(callee))return null;if(t.isIdentifier(callee))return{type:`ident`,name:callee.name};if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property))return{type:`member`,object:callee.object.name,property:callee.property.name};if(t.isOptionalMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property))return{type:`member`,object:callee.object.name,property:callee.property.name};return null}function collectCalledBindingsFromFunctionBody(fn,engine=`babel`){const called=[];if(engine===`oxc`){const visit=node=>{if(!node)return;if(node.type===`CallExpression`){const callee=node.callee;if(callee?.type===`Identifier`)called.push({type:`ident`,name:callee.name});else if(callee?.type===`MemberExpression`&&!callee.computed&&callee.object?.type===`Identifier`&&callee.property?.type===`Identifier`)called.push({type:`member`,object:callee.object.name,property:callee.property.name})}else if(node.type===`ChainExpression`){visit(node.expression);return}for(const value of Object.values(node)){if(!value)continue;if(Array.isArray(value)){for(const child of value)if(child&&typeof child===`object`&&typeof child.type===`string`)visit(child)}else if(typeof value===`object`&&typeof value.type===`string`)visit(value)}};visit(fn);return called}t.traverseFast(fn,node=>{if(t.isCallExpression(node)){const name=getCallCalleeName(node.callee);if(name)called.push(name)}else if(t.isOptionalCallExpression(node)){const name=getCallCalleeName(node.callee);if(name)called.push(name)}});return called}function getMemberHookName(callee){if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property))return{object:callee.object.name,hook:callee.property.name};if(t.isOptionalMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property))return{object:callee.object.name,hook:callee.property.name};return null}function addNamespaceHookFeature(module,callee,enabled){const memberHook=getMemberHookName(callee);if(!memberHook||!module.wevuNamespaceLocals.has(memberHook.object))return;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[memberHook.hook];if(matched)enabled.add(matched)}function collectWevuHookCallsInFunctionBody(module,fn){const enabled=/* @__PURE__ */ new Set;if(module.engine===`oxc`){const visit=node=>{if(!node)return;if(node.type===`CallExpression`){const callee=node.callee;if(callee?.type===`Identifier`){const matched=module.wevuNamedHookLocals.get(callee.name);if(matched)enabled.add(matched)}else if(callee?.type===`MemberExpression`&&!callee.computed&&callee.object?.type===`Identifier`&&callee.property?.type===`Identifier`){if(module.wevuNamespaceLocals.has(callee.object.name)){const hook=callee.property.name;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[hook];if(matched)enabled.add(matched)}}}else if(node.type===`ChainExpression`){visit(node.expression);return}for(const value of Object.values(node)){if(!value)continue;if(Array.isArray(value)){for(const child of value)if(child&&typeof child===`object`&&typeof child.type===`string`)visit(child)}else if(typeof value===`object`&&typeof value.type===`string`)visit(value)}};visit(fn);return enabled}t.traverseFast(fn,node=>{if(t.isCallExpression(node)){const callee=node.callee;if(t.isIdentifier(callee)){const matched=module.wevuNamedHookLocals.get(callee.name);if(matched)enabled.add(matched);return}addNamespaceHookFeature(module,callee,enabled)}else if(t.isOptionalCallExpression(node)){const callee=node.callee;if(t.isIdentifier(callee)){const matched=module.wevuNamedHookLocals.get(callee.name);if(matched)enabled.add(matched);return}addNamespaceHookFeature(module,callee,enabled)}});return enabled}function resolveExportedFunctionNode(module,exportName){const target=module.exports.get(exportName);if(!target)return null;if(target.type===`local`){const fn=module.localFunctions.get(target.localName);return fn?{type:`inline`,node:fn}:null}if(target.type===`reexport`)return target;if(target.type===`inline`)return target;return null}async function resolveExternalFunction(resolver,importerId,source,exportName,moduleCache,options){if(source===`wevu`)return null;const resolvedId=await resolver.resolveId(source,importerId);if(!resolvedId)return null;const code=await resolver.loadCode(resolvedId);if(!code)return null;let analysis=moduleCache.get(resolvedId);if(!analysis){analysis=getOrCreateExternalModuleAnalysis(resolvedId,code,options);moduleCache.set(resolvedId,analysis)}const target=resolveExportedFunctionNode(analysis,exportName);if(!target)return null;if(target.type===`reexport`)return{moduleId:resolvedId,reexport:{source:target.source,importedName:target.importedName}};if(target.type===`inline`)return{moduleId:resolvedId,fn:target.node,module:analysis};return null}async function walkReachableWevuFeatures(options){const{pageModule,setupFn,resolver,moduleCache}=options;const enabled=/* @__PURE__ */ new Set;const seedCalls=collectCalledBindingsFromFunctionBody(setupFn,pageModule.engine);const queue=[];const visitedLocal=/* @__PURE__ */ new Set;const visitedExternal=/* @__PURE__ */ new Set;const enqueueLocal=(moduleId,name)=>{const key=`${moduleId}::${name}`;if(visitedLocal.has(key))return;visitedLocal.add(key);queue.push({kind:`local`,moduleId,name})};const enqueueExternal=(importerId,source,exportName)=>{const key=`${importerId}::${source}::${exportName}`;if(visitedExternal.has(key))return;visitedExternal.add(key);queue.push({kind:`external`,importerId,source,exportName})};const seedFromCall=call=>{if(call.type===`ident`){const binding=pageModule.importedBindings.get(call.name);if(binding?.kind===`named`)enqueueExternal(pageModule.id,binding.source,binding.importedName);else if(binding?.kind==="default")enqueueExternal(pageModule.id,binding.source,`default`);else if(!binding&&pageModule.localFunctions.has(call.name))enqueueLocal(pageModule.id,call.name);return}const binding=pageModule.importedBindings.get(call.object);if(binding?.kind===`namespace`)enqueueExternal(pageModule.id,binding.source,call.property)};for(const call of seedCalls)seedFromCall(call);let steps=0;const MAX_STEPS=128;while(queue.length&&steps<MAX_STEPS){steps+=1;const item=queue.shift();if(item.kind===`local`){if(item.moduleId!==pageModule.id)continue;const fn=pageModule.localFunctions.get(item.name);if(!fn)continue;for(const f of collectWevuHookCallsInFunctionBody(pageModule,fn))enabled.add(f);const calls=collectCalledBindingsFromFunctionBody(fn,pageModule.engine);for(const call of calls)seedFromCall(call);continue}const resolved=await resolveExternalFunction(resolver,item.importerId,item.source,item.exportName,moduleCache,{astEngine:options.astEngine});if(!resolved)continue;if(`reexport`in resolved){enqueueExternal(resolved.moduleId,resolved.reexport.source,resolved.reexport.importedName);continue}for(const f of collectWevuHookCallsInFunctionBody(resolved.module,resolved.fn))enabled.add(f);const calls=collectCalledBindingsFromFunctionBody(resolved.fn,resolved.module.engine);for(const call of calls)if(call.type===`ident`){const binding=resolved.module.importedBindings.get(call.name);if(binding?.kind===`named`)enqueueExternal(resolved.moduleId,binding.source,binding.importedName);else if(binding?.kind==="default")enqueueExternal(resolved.moduleId,binding.source,`default`);else if(!binding&&resolved.module.localFunctions.has(call.name)){const key=`${resolved.moduleId}::${call.name}`;if(!visitedLocal.has(key)){visitedLocal.add(key);const localFn=resolved.module.localFunctions.get(call.name);if(localFn){for(const f of collectWevuHookCallsInFunctionBody(resolved.module,localFn))enabled.add(f);for(const inner of collectCalledBindingsFromFunctionBody(localFn,resolved.module.engine))if(inner.type===`ident`){const innerBinding=resolved.module.importedBindings.get(inner.name);if(innerBinding?.kind===`named`)enqueueExternal(resolved.moduleId,innerBinding.source,innerBinding.importedName);else if(innerBinding?.kind==="default")enqueueExternal(resolved.moduleId,innerBinding.source,`default`)}}}}}else{const binding=resolved.module.importedBindings.get(call.object);if(binding?.kind===`namespace`)enqueueExternal(resolved.moduleId,binding.source,call.property)}}return enabled}async function collectWevuFeaturesFromSetupReachableImports(pageModule,setupFn,resolver,moduleCache,options){return await walkReachableWevuFeatures({pageModule,setupFn,resolver,moduleCache,astEngine:options?.astEngine})}async function collectWevuFeaturesFromCodeReachableImports(code,options){const{optionsObjects,module}=collectTargetOptionsObjectsFromCode(code,options.id,{astEngine:options.astEngine});if(!optionsObjects.length)return/* @__PURE__ */ new Set;const moduleCache=/* @__PURE__ */ new Map([[options.id,module]]);const enabled=/* @__PURE__ */ new Set;for(const optionsObject of optionsObjects){const setupFn=getSetupFunctionFromOptionsObject(optionsObject);if(!setupFn)continue;const reachable=await collectWevuFeaturesFromSetupReachableImports(module,setupFn,options.resolver,moduleCache,{astEngine:options.astEngine});for(const feature of reachable)enabled.add(feature)}return enabled}function injectWevuPageFeaturesInJs(source,options){const enabled=collectWevuPageFeatureFlagsFromCode(source,options);if(!enabled.size)return{code:source,transformed:false};const ast=parseJsLike(source);const{optionsObjects}=collectTargetOptionsObjects(ast,`<inline>`);if(!optionsObjects.length)return{code:source,transformed:false};let changed=false;for(const target of optionsObjects)changed=injectWevuPageFeatureFlagsIntoOptionsObject(target,enabled)||changed;if(!changed)return{code:source,transformed:false};const sourceMap=options?.sourceMap!==false;const generated=generate(ast,{compact:options?.minify===true,minified:options?.minify===true,retainLines:options?.minify!==true,sourceMaps:sourceMap,sourceFileName:`inline.js`},source);return{code:generated.code,transformed:true,map:sourceMap?generated.map:null}}async function injectWevuPageFeaturesInJsWithResolver(source,options){const preflight=collectTargetOptionsObjectsFromCode(source,options.id,{astEngine:options.astEngine});if(!preflight.optionsObjects.length)return{code:source,transformed:false};const ast=parseJsLike(source);const{optionsObjects}=collectTargetOptionsObjects(ast,options.id);if(!optionsObjects.length)return{code:source,transformed:false};const enabled=/* @__PURE__ */ new Set;for(const flag of collectWevuPageFeatureFlagsFromCode(source,options))enabled.add(flag);const moduleCache=/* @__PURE__ */ new Map;moduleCache.set(options.id,preflight.module);for(const optionsObject of optionsObjects){const setupFn=getSetupFunctionFromOptionsObject(optionsObject);if(!setupFn)continue;const fromImports=await collectWevuFeaturesFromSetupReachableImports(preflight.module,setupFn,options.resolver,moduleCache,{astEngine:options.astEngine});for(const flag of fromImports)enabled.add(flag)}if(!enabled.size)return{code:source,transformed:false};let changed=false;for(const optionsObject of optionsObjects)changed=injectWevuPageFeatureFlagsIntoOptionsObject(optionsObject,enabled)||changed;if(!changed)return{code:source,transformed:false};const sourceMap=options?.sourceMap!==false;const generated=generate(ast,{compact:options?.minify===true,minified:options?.minify===true,retainLines:options?.minify!==true,sourceMaps:sourceMap,sourceFileName:`inline.js`},source);return{code:generated.code,transformed:true,map:sourceMap?generated.map:null}}function createPageEntryMatcher(source){let cached;const warn=resolveWarnHandler(source.warn);async function ensure(){if(cached)return cached;let entries;try{entries=await source.loadEntries()}catch(error){const message=error instanceof Error?error.message:String(error);warn(`[wevu] 解析页面入口失败:${message}`);return/* @__PURE__ */ new Set}const set=/* @__PURE__ */ new Set;for(const pageEntry of entries.pages??[]){const normalized=stripLeadingSlashes(String(pageEntry));if(!normalized)continue;set.add(path.resolve(source.srcRoot,normalized))}for(const meta of entries.subPackages??[]){const root=meta.root??``;for(const pageEntry of meta.pages??[]){const normalized=stripLeadingSlashes(String(pageEntry));if(!normalized)continue;set.add(path.resolve(source.srcRoot,root,normalized))}}for(const entry of entries.pluginPages??[]){const normalized=stripLeadingSlashes(String(entry));if(!normalized)continue;set.add(path.resolve(source.srcRoot,removeExtensionDeep(normalized)))}cached=set;return set}return{markDirty(){cached=void 0},async isPageFile(filePath){const pages=await ensure();const normalized=removeExtensionDeep(filePath);return pages.has(normalized)}}}function isDefineComponentCall(node,aliases){return t.isIdentifier(node.callee)&&aliases.has(node.callee.name)}function isObjectAssignCall$1(node){const callee=node.callee;return t.isMemberExpression(callee)&&t.isIdentifier(callee.object,{name:`Object`})&&t.isIdentifier(callee.property,{name:`assign`})}function unwrapTypeLikeExpression$1(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSTypeAssertion(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node))return unwrapTypeLikeExpression$1(node.expression);if(t.isParenthesizedExpression(node))return unwrapTypeLikeExpression$1(node.expression);return node}function resolveObjectExpressionFromAssignCall(node){if(!isObjectAssignCall$1(node))return null;for(let index=node.arguments.length-1;index>=0;index-=1){const arg=node.arguments[index];if(t.isSpreadElement(arg)||!t.isExpression(arg))continue;const normalized=unwrapTypeLikeExpression$1(arg);if(t.isObjectExpression(normalized))return normalized}return null}function unwrapDefineComponent(node,aliases){if(t.isCallExpression(node)&&isDefineComponentCall(node,aliases)){const arg=node.arguments[0];if(t.isObjectExpression(arg))return arg}return null}function resolveComponentExpression(declaration,defineComponentDecls,aliases){if(!declaration)return null;if(t.isObjectExpression(declaration))return declaration;if(t.isCallExpression(declaration)&&isDefineComponentCall(declaration,aliases)){const arg=declaration.arguments[0];if(t.isObjectExpression(arg))return arg;if(t.isIdentifier(arg)){const matched=defineComponentDecls.get(arg.name);return matched?t.cloneNode(matched,true):null}if(t.isExpression(arg))return arg;return null}if(t.isCallExpression(declaration)&&isObjectAssignCall$1(declaration))return declaration;if(t.isIdentifier(declaration)){const matched=defineComponentDecls.get(declaration.name);return matched?t.cloneNode(matched,true):null}return null}function resolveComponentOptionsObject(componentExpr){if(!componentExpr)return null;const normalized=unwrapTypeLikeExpression$1(componentExpr);if(t.isObjectExpression(normalized))return normalized;if(t.isCallExpression(normalized))return resolveObjectExpressionFromAssignCall(normalized);return null}function isScriptSetupReturnedObject(path){const parent=path.parentPath;if(parent?.isVariableDeclarator()&&t.isIdentifier(parent.node.id,{name:`__returned__`}))return true;if(parent?.isReturnStatement())return true;return false}function isTemplateReturnGetterReference(path){const objectMethod=path.findParent(parent=>parent.isObjectMethod());if(objectMethod?.isObjectMethod()&&objectMethod.node.kind===`get`&&!objectMethod.node.computed&&t.isIdentifier(objectMethod.node.key,{name:path.node.name})&&objectMethod.parentPath?.isObjectExpression()&&isScriptSetupReturnedObject(objectMethod.parentPath)){const getter=objectMethod.node.body.body.find(statement=>t.isReturnStatement(statement));return Boolean(getter&&t.isReturnStatement(getter)&&t.isIdentifier(getter.argument,{name:path.node.name}))}return false}function isTemplateReturnPropertyReference(path){const property=path.parentPath;if(!property?.isObjectProperty())return false;if(!property.parentPath?.isObjectExpression()||!isScriptSetupReturnedObject(property.parentPath)||property.node.computed)return false;const key=property.node.key;const value=property.node.value;if(!t.isIdentifier(value,{name:path.node.name}))return false;if(t.isIdentifier(key,{name:path.node.name})||t.isStringLiteral(key,{value:path.node.name}))return true;return false}function isStaticPropertyNamed(node,name){return!node.computed&&(t.isIdentifier(node.key,{name})||t.isStringLiteral(node.key,{value:name}))}function isOptionsApiComponentsObject(path){const componentsProperty=path.parentPath;if(!componentsProperty?.isObjectProperty()||!isStaticPropertyNamed(componentsProperty.node,`components`))return false;const optionsObject=componentsProperty.parentPath;if(!optionsObject?.isObjectExpression())return false;const optionsParent=optionsObject.parentPath;if(optionsParent?.isExportDefaultDeclaration())return true;return Boolean(optionsParent?.isCallExpression()&&optionsParent.node.arguments[0]===optionsObject.node&&optionsParent.parentPath?.isExportDefaultDeclaration())}function isOptionsApiComponentRegistrationReference(path){const property=path.parentPath;return Boolean(property?.isObjectProperty()&&property.node.value===path.node&&property.parentPath?.isObjectExpression()&&isOptionsApiComponentsObject(property.parentPath))}function isReferencedOutsideTemplateReturn(path){if(!path.isReferencedIdentifier())return false;if(isTemplateReturnGetterReference(path)||isTemplateReturnPropertyReference(path)||isOptionsApiComponentRegistrationReference(path))return false;return true}function collectReferencedNames(ast,candidateNames){const referencedNames=/* @__PURE__ */ new Set;traverse(ast,{Identifier(path){const name=path.node.name;if(!candidateNames.has(name))return;if(isReferencedOutsideTemplateReturn(path))referencedNames.add(name)}});return referencedNames}function removeSetupReturnProperties(ast,removableNames){if(!removableNames.size)return false;let changed=false;traverse(ast,{ObjectMethod(path){if(!path.parentPath?.isObjectExpression()||!isScriptSetupReturnedObject(path.parentPath))return;if(path.node.computed||!t.isIdentifier(path.node.key))return;const name=path.node.key.name;if(!removableNames.has(name))return;if(path.node.kind!==`get`)return;const getter=path.node.body.body.find(statement=>t.isReturnStatement(statement));if(!getter||!t.isReturnStatement(getter)||!t.isIdentifier(getter.argument,{name}))return;path.remove();changed=true},ObjectProperty(path){if(!path.parentPath?.isObjectExpression()||!isScriptSetupReturnedObject(path.parentPath))return;if(path.node.computed||!t.isIdentifier(path.node.value))return;const name=path.node.value.name;if(!removableNames.has(name))return;if(!t.isIdentifier(path.node.key,{name})&&!t.isStringLiteral(path.node.key,{value:name}))return;path.remove();changed=true}});return changed}function removeOptionsApiComponentRegistrations(ast,removableNames){if(!removableNames.size)return false;let changed=false;traverse(ast,{ObjectProperty(path){if(!path.parentPath?.isObjectExpression()||!isOptionsApiComponentsObject(path.parentPath)||!t.isIdentifier(path.node.value)||!removableNames.has(path.node.value.name))return;path.remove();changed=true}});traverse(ast,{ObjectProperty(path){if(!t.isObjectExpression(path.node.value)||!isStaticPropertyNamed(path.node,`components`)||path.node.value.properties.length>0||!path.parentPath?.isObjectExpression())return;const optionsParent=path.parentPath.parentPath;if(optionsParent?.isExportDefaultDeclaration()||optionsParent?.isCallExpression()&&optionsParent.node.arguments[0]===path.parentPath.node&&optionsParent.parentPath?.isExportDefaultDeclaration())path.remove()}});return changed}function pruneTemplateComponentMeta(ast,templateComponentMeta){if(!Object.keys(templateComponentMeta).length)return false;const candidateNames=new Set(Object.keys(templateComponentMeta));const referencedNames=collectReferencedNames(ast,candidateNames);const removableNames=new Set([...candidateNames].filter(name=>!referencedNames.has(name)));let changed=false;traverse(ast,{ImportDeclaration(path){if(!path.node.specifiers.length)return;const kept=path.node.specifiers.filter(specifier=>{if(!(`local`in specifier)||!t.isIdentifier(specifier.local))return true;const localName=specifier.local.name;return!removableNames.has(localName)});if(kept.length!==path.node.specifiers.length){changed=true;if(kept.length===0){path.remove();return}path.node.specifiers=kept}}});changed=removeSetupReturnProperties(ast,removableNames)||changed;changed=removeOptionsApiComponentRegistrations(ast,removableNames)||changed;return changed}function vueSfcTransformPlugin(){return{name:`vue-sfc-transform`,visitor:{ImportDeclaration(path){if(path.node.source.value===`vue`){const specifiers=path.node.specifiers;const filteredSpecifiers=specifiers.filter(s=>{if(s.type===`ImportSpecifier`&&t.isIdentifier(s.imported)&&s.imported.name===WE_VU_RUNTIME_APIS.defineComponent)return false;return true});if(filteredSpecifiers.length===0)path.remove();else if(filteredSpecifiers.length!==specifiers.length)path.node.specifiers=filteredSpecifiers}},ObjectExpression(path){const filtered=path.node.properties.filter(p=>{if(p.type===`ObjectProperty`){const key=p.key;if(key.type===`Identifier`&&key.name===`__name`)return false}return true});path.node.properties=filtered},CallExpression(path){if(t.isMemberExpression(path.node.callee)&&t.isIdentifier(path.node.callee.object,{name:`Object`})&&t.isIdentifier(path.node.callee.property,{name:`defineProperty`})&&t.isIdentifier(path.node.arguments[0],{name:`__returned__`})&&t.isStringLiteral(path.node.arguments[1],{value:`__isScriptSetup`})&&path.parentPath?.isExpressionStatement()){path.parentPath.remove();return}if(t.isIdentifier(path.node.callee,{name:`__expose`})&&path.parentPath?.isExpressionStatement()&&path.node.arguments.length===0)path.parentPath.remove()}}}}function createCollectVisitors(state){return{VariableDeclarator(path){if(!t.isIdentifier(path.node.id)||!path.node.init)return;if(t.isObjectExpression(path.node.init))state.defineComponentDecls.set(path.node.id.name,t.cloneNode(path.node.init,true));const unwrapped=unwrapDefineComponent(path.node.init,state.defineComponentAliases);if(unwrapped){state.defineComponentDecls.set(path.node.id.name,t.cloneNode(unwrapped,true));path.node.init=unwrapped;state.transformed=true}},ExportDefaultDeclaration(path){state.defaultExportPath=path}}}const RUNTIME_IMPORT_PATH=WE_VU_COMPILER_RUNTIME_MODULE_ID;const COMPILED_DEFINE_COMPONENT_IMPORT_RE=/^import\s+\{\s*defineComponent\s+as\s+([A-Za-z_$][\w$]*)\s*\}\s+from\s+['"]vue['"];?\n/;const EXPORT_DEFAULT_PURE_RE=/export\s+default\s+\/\*@__PURE__\*\/\s*/;const JSON_MACRO_RE=/\bdefine(?:App|Page|Component|Sitemap|Theme)Json\s*\(/;const PAGE_META_RE=/\bdefinePageMeta\s*\(/;const OPTION_CAPABILITY_RE=/\b(?:createApp|createWevuComponent|setData|setWevuDefaults)\b/;const WEVU_RUNTIME_IMPORT_RE=/\bfrom\s*['"](?:wevu(?:\/internal-runtime)?|virtual:weapp-vite\/runtime)['"]/;const DYNAMIC_OPTIONS_PROPERTY_RE=/\.\.\.|\[/;function hasMetadataInjectionOptions(source,options){const hasWevuDefaults=options?.wevuDefaults&&Object.keys(options.wevuDefaults).length>0;return Boolean(options?.isTypeScript||options?.isApp||options?.skipComponentTransform||options?.minify||options?.sourceMap!==false||options?.templateComponentMeta||hasWevuDefaults||options?.classStyleBindings?.length||options?.templateRefs?.length||options?.layoutHosts?.length||options?.inlineExpressions?.length||options?.runtimeCapabilities?.required.length||options?.functionPropPaths?.length||options?.propsAliases||options?.propsDerivedKeys?.length||options?.relaxStructuredTypeOnlyProps||options?.bindingManifest||options?.pageLayout||options?.scopedSlotHostProperties||options?.nativeSlotContext||options?.stabilizeCssVarsRuntime||/\b(?:useSlots|options|extends|mixins|definitionFilter|behaviors)\b|\\/.test(source))}function findMatchingCallEnd(source,openParenIndex){let depth=0;let quote;let escaped=false;let lineComment=false;let blockComment=false;for(let index=openParenIndex;index<source.length;index+=1){const current=source[index];const next=source[index+1];if(lineComment){if(current===`
22
+ `)).digest(`hex`).slice(0,12);const staticConfig=resolveStaticJsonMacroConfig(macroStatements,options);if(staticConfig)return withSourceMap({stripped,config:Object.keys(staticConfig).length?staticConfig:void 0,macroHash,dependencies:[],...options?.merge?{}:{isStatic:true}},rewrite);const result=await evaluateJsonMacroConfig(content,filename,lang,options);return withSourceMap(result?{stripped,config:result.config,macroHash,dependencies:result.dependencies}:{stripped,macroHash},rewrite)}async function extractJsonMacroFromScriptSetup(content,filename,lang,options){return await extractJsonMacroFromScriptSetupInternal(content,filename,lang,options)}async function extractJsonMacroFromScriptSetupWithSourceMap(content,filename,lang,options,sourceMap){return await extractJsonMacroFromScriptSetupInternal(content,filename,lang,options,sourceMap)}function toPlainRecord(value){if(!value||typeof value!==`object`||Array.isArray(value))return{};return value}function mergeJsonWithStrategy(target,source,strategy,context){const base={...toPlainRecord(target)};const incoming=toPlainRecord(source);if(typeof strategy===`function`){const maybeNext=strategy(base,incoming,context);if(maybeNext&&typeof maybeNext===`object`&&!Array.isArray(maybeNext))return maybeNext;return base}if(strategy===`replace`)return{...incoming};if(strategy===`assign`)return{...base,...incoming};const merged={...base};recursive(merged,incoming);return merged}function createJsonMerger(strategy,baseContext){return(target,source,stage)=>{return mergeJsonWithStrategy(target,source,strategy,{...baseContext,stage})}}function resolveWarnHandler(warn){return warn??(message=>{console.warn(message)})}function isStaticObjectKeyMatch$1(key,expected){if(t.isIdentifier(key))return key.name===expected;if(t.isStringLiteral(key))return key.value===expected;return false}function getObjectPropertyByKey$3(node,key){for(const prop of node.properties){if(!t.isObjectProperty(prop)||prop.computed)continue;if(isStaticObjectKeyMatch$1(prop.key,key))return prop}return null}function buildInjectedFeaturesObject(enabled){return t.objectExpression(Array.from(enabled,key=>{return t.objectProperty(t.identifier(key),t.booleanLiteral(true))}))}function getObjectMemberIndexByKey(node,key){return node.properties.findIndex(prop=>{if(t.isObjectProperty(prop)&&!prop.computed)return isStaticObjectKeyMatch$1(prop.key,key);if(t.isObjectMethod(prop)&&!prop.computed)return isStaticObjectKeyMatch$1(prop.key,key);return false})}function isTopLevel(path){return path.getFunctionParent()==null}function injectWevuShareLifecycleHooksIntoOptionsObject(_optionsObject,_enabled){return false}function collectWevuPageFeatureFlags(ast){const namedHookLocals=/* @__PURE__ */ new Map;const namespaceLocals=/* @__PURE__ */ new Set;for(const stmt of ast.program.body){if(!t.isImportDeclaration(stmt)||!isWevuPageFeatureModuleId(stmt.source.value))continue;for(const specifier of stmt.specifiers)if(t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.imported)){const importedName=specifier.imported.name;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[importedName];if(matched)namedHookLocals.set(specifier.local.name,matched)}else if(t.isImportNamespaceSpecifier(specifier))namespaceLocals.add(specifier.local.name)}if(namedHookLocals.size===0&&namespaceLocals.size===0)return/* @__PURE__ */ new Set;const enabled=/* @__PURE__ */ new Set;function consumeHookCallByName(name){const matched=namedHookLocals.get(name);if(matched)enabled.add(matched)}function consumeNamespaceHookCall(namespace,hookName){if(!namespaceLocals.has(namespace))return;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[hookName];if(matched)enabled.add(matched)}traverse(ast,{CallExpression(path){const callee=path.node.callee;if(t.isIdentifier(callee)){consumeHookCallByName(callee.name);return}if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)){const property=callee.property;if(t.isIdentifier(property))consumeNamespaceHookCall(callee.object.name,property.name)}},OptionalCallExpression(path){const callee=path.node.callee;if(t.isIdentifier(callee)){consumeHookCallByName(callee.name);return}if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)){const property=callee.property;if(t.isIdentifier(property))consumeNamespaceHookCall(callee.object.name,property.name)}}});return enabled}function injectWevuPageFeatureFlagsIntoOptionsObject(optionsObject,enabled){if(!enabled.size)return false;const expectedKeys=[...enabled];const existingFeaturesProp=getObjectPropertyByKey$3(optionsObject,`features`);let changed=false;if(!existingFeaturesProp){const featuresObject=buildInjectedFeaturesObject(enabled);const setupIndex=getObjectMemberIndexByKey(optionsObject,`setup`);const insertAt=setupIndex>=0?setupIndex:0;optionsObject.properties.splice(insertAt,0,t.objectProperty(t.identifier(`features`),featuresObject));changed=true}else if(t.isObjectExpression(existingFeaturesProp.value)){const featuresObject=existingFeaturesProp.value;const injectedProps=[];for(const key of expectedKeys){if(getObjectPropertyByKey$3(featuresObject,key))continue;injectedProps.push(t.objectProperty(t.identifier(key),t.booleanLiteral(true)))}if(injectedProps.length){featuresObject.properties.splice(0,0,...injectedProps);changed=true}}else if(t.isIdentifier(existingFeaturesProp.value)||t.isMemberExpression(existingFeaturesProp.value)){const base=t.cloneNode(existingFeaturesProp.value,true);const injected=buildInjectedFeaturesObject(enabled);injected.properties.push(t.spreadElement(base));existingFeaturesProp.value=injected;changed=true}changed=injectWevuShareLifecycleHooksIntoOptionsObject(optionsObject,enabled)||changed;return changed}function createEmptyModuleAnalysis(id,engine){return{id,engine,wevuNamedHookLocals:/* @__PURE__ */ new Map,wevuNamespaceLocals:/* @__PURE__ */ new Set,importedBindings:/* @__PURE__ */ new Map,localFunctions:/* @__PURE__ */ new Map,exports:/* @__PURE__ */ new Map}}const externalModuleAnalysisCache=new LRUCache({max:256});const moduleAnalysisCache=new LRUCache({max:512});function createExternalModuleAnalysisCacheKey(moduleId,astEngine){return`${astEngine??`babel`}::${moduleId}`}function createModuleAnalysisCacheKey(moduleId,astEngine){return`${astEngine??`babel`}::${moduleId}`}function getFunctionLikeFromExpression(node){if(!node)return null;if(t.isFunctionExpression(node)||t.isArrowFunctionExpression(node))return node;return null}function isOxcFunctionLike(node){return node?.type===`FunctionDeclaration`||node?.type===`FunctionExpression`||node?.type===`ArrowFunctionExpression`}function getImportedSpecifierName(node){if(node?.type===`Identifier`)return node.name;if((node?.type===`StringLiteral`||node?.type===`Literal`)&&typeof node.value===`string`)return node.value}function createModuleAnalysis(id,ast){const localFunctions=/* @__PURE__ */ new Map;const exports=/* @__PURE__ */ new Map;const importedBindings=/* @__PURE__ */ new Map;const wevuNamedHookLocals=/* @__PURE__ */ new Map;const wevuNamespaceLocals=/* @__PURE__ */ new Set;function registerFunctionDeclaration(node){if(!node.id||!node.id.name)return;localFunctions.set(node.id.name,node)}function registerVariableFunction(node){if(!t.isIdentifier(node.id))return;const fn=getFunctionLikeFromExpression(node.init);if(!fn)return;localFunctions.set(node.id.name,fn)}for(const stmt of ast.program.body){if(t.isFunctionDeclaration(stmt)){registerFunctionDeclaration(stmt);continue}if(t.isVariableDeclaration(stmt)){for(const decl of stmt.declarations)registerVariableFunction(decl);continue}if(t.isImportDeclaration(stmt)){const source=stmt.source.value;for(const specifier of stmt.specifiers)if(t.isImportSpecifier(specifier)){const imported=specifier.imported;if(isWevuPageFeatureModuleId(source)&&t.isIdentifier(imported)){const importedName=imported.name;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[importedName];if(matched)wevuNamedHookLocals.set(specifier.local.name,matched)}importedBindings.set(specifier.local.name,{kind:`named`,source,importedName:t.isIdentifier(imported)?imported.name:String(imported.value)})}else if(t.isImportDefaultSpecifier(specifier))importedBindings.set(specifier.local.name,{kind:`default`,source});else if(t.isImportNamespaceSpecifier(specifier)){importedBindings.set(specifier.local.name,{kind:`namespace`,source});if(isWevuPageFeatureModuleId(source))wevuNamespaceLocals.add(specifier.local.name)}continue}if(t.isExportNamedDeclaration(stmt)){if(stmt.declaration){if(t.isFunctionDeclaration(stmt.declaration)&&stmt.declaration.id){registerFunctionDeclaration(stmt.declaration);exports.set(stmt.declaration.id.name,{type:`local`,localName:stmt.declaration.id.name})}else if(t.isVariableDeclaration(stmt.declaration))for(const decl of stmt.declaration.declarations){registerVariableFunction(decl);if(t.isIdentifier(decl.id))exports.set(decl.id.name,{type:`local`,localName:decl.id.name})}continue}if(stmt.source){const source=stmt.source.value;for(const spec of stmt.specifiers){if(!t.isExportSpecifier(spec))continue;const exportedName=t.isIdentifier(spec.exported)?spec.exported.name:void 0;const importedName=t.isIdentifier(spec.local)?spec.local.name:void 0;if(!exportedName||!importedName)continue;exports.set(exportedName,{type:`reexport`,source,importedName})}}else for(const spec of stmt.specifiers){if(!t.isExportSpecifier(spec))continue;const exportedName=t.isIdentifier(spec.exported)?spec.exported.name:void 0;const localName=t.isIdentifier(spec.local)?spec.local.name:void 0;if(!exportedName||!localName)continue;exports.set(exportedName,{type:`local`,localName})}continue}if(t.isExportDefaultDeclaration(stmt)){const decl=stmt.declaration;if(t.isFunctionDeclaration(decl)){registerFunctionDeclaration(decl);if(decl.id)exports.set(`default`,{type:`local`,localName:decl.id.name});else exports.set(`default`,{type:`inline`,node:decl})}else if(t.isIdentifier(decl))exports.set(`default`,{type:`local`,localName:decl.name});else{const fn=getFunctionLikeFromExpression(decl);if(fn)exports.set(`default`,{type:`inline`,node:fn})}}}return{id,engine:`babel`,ast,wevuNamedHookLocals,wevuNamespaceLocals,importedBindings,localFunctions,exports}}function resolveOxcParseFilename(id){if(path.extname(id))return id;return`${id}.js`}function createModuleAnalysisWithOxc(id,code){const ast=parseJsLikeWithEngine(code,{engine:`oxc`,filename:resolveOxcParseFilename(id)});const localFunctions=/* @__PURE__ */ new Map;const exports=/* @__PURE__ */ new Map;const importedBindings=/* @__PURE__ */ new Map;const wevuNamedHookLocals=/* @__PURE__ */ new Map;const wevuNamespaceLocals=/* @__PURE__ */ new Set;function registerFunctionDeclaration(node){if(node?.id?.type===`Identifier`)localFunctions.set(node.id.name,node)}function registerVariableFunction(node){if(node?.id?.type!==`Identifier`||!isOxcFunctionLike(node.init))return;localFunctions.set(node.id.name,node.init)}for(const stmt of ast.body??[]){if(stmt?.type===`FunctionDeclaration`){registerFunctionDeclaration(stmt);continue}if(stmt?.type===`VariableDeclaration`){for(const decl of stmt.declarations??[])registerVariableFunction(decl);continue}if(stmt?.type===`ImportDeclaration`){const source=getImportedSpecifierName(stmt.source);if(!source)continue;for(const specifier of stmt.specifiers??[])if(specifier.type===`ImportSpecifier`&&specifier.local?.type===`Identifier`){const importedName=getImportedSpecifierName(specifier.imported);if(!importedName)continue;if(isWevuPageFeatureModuleId(source)){const matched=WE_VU_PAGE_HOOK_TO_FEATURE[importedName];if(matched)wevuNamedHookLocals.set(specifier.local.name,matched)}importedBindings.set(specifier.local.name,{kind:`named`,source,importedName})}else if(specifier.type===`ImportDefaultSpecifier`&&specifier.local?.type===`Identifier`)importedBindings.set(specifier.local.name,{kind:`default`,source});else if(specifier.type===`ImportNamespaceSpecifier`&&specifier.local?.type===`Identifier`){importedBindings.set(specifier.local.name,{kind:`namespace`,source});if(isWevuPageFeatureModuleId(source))wevuNamespaceLocals.add(specifier.local.name)}continue}if(stmt?.type===`ExportNamedDeclaration`){if(stmt.declaration?.type===`FunctionDeclaration`){registerFunctionDeclaration(stmt.declaration);if(stmt.declaration.id?.type===`Identifier`)exports.set(stmt.declaration.id.name,{type:`local`,localName:stmt.declaration.id.name});continue}if(stmt.declaration?.type===`VariableDeclaration`){for(const decl of stmt.declaration.declarations??[]){registerVariableFunction(decl);if(decl.id?.type===`Identifier`)exports.set(decl.id.name,{type:`local`,localName:decl.id.name})}continue}const source=getImportedSpecifierName(stmt.source);for(const spec of stmt.specifiers??[]){if(spec?.type!==`ExportSpecifier`)continue;const exportedName=getImportedSpecifierName(spec.exported);const localName=getImportedSpecifierName(spec.local);if(!exportedName||!localName)continue;if(source)exports.set(exportedName,{type:`reexport`,source,importedName:localName});else exports.set(exportedName,{type:`local`,localName})}continue}if(stmt?.type===`ExportDefaultDeclaration`){const decl=stmt.declaration;if(decl?.type===`FunctionDeclaration`){registerFunctionDeclaration(decl);if(decl.id?.type===`Identifier`)exports.set(`default`,{type:`local`,localName:decl.id.name});else exports.set(`default`,{type:`inline`,node:decl})}else if(decl?.type===`Identifier`)exports.set(`default`,{type:`local`,localName:decl.name});else if(isOxcFunctionLike(decl))exports.set(`default`,{type:`inline`,node:decl})}}return{id,engine:`oxc`,ast,wevuNamedHookLocals,wevuNamespaceLocals,importedBindings,localFunctions,exports}}const TS_WITHOUT_JSX_RE=/\.[cm]?ts(?:[?#].*)?$/i;function parseModuleAnalysisAst(id,code){const plugins=TS_WITHOUT_JSX_RE.test(id)?BABEL_TS_MODULE_PLUGINS.filter(plugin=>plugin!==`jsx`):BABEL_TS_MODULE_PLUGINS;return parse$3(code,{sourceType:`module`,plugins})}function createModuleAnalysisFromCode(id,code,options){const engine=options?.astEngine??`babel`;const cacheKey=createModuleAnalysisCacheKey(id,engine);const cached=moduleAnalysisCache.get(cacheKey);if(cached&&cached.code===code)return cached.analysis;let analysis;if(engine===`oxc`){if(!code.includes(`import`)&&!code.includes(`export`))analysis=createEmptyModuleAnalysis(id,`oxc`);else analysis=createModuleAnalysisWithOxc(id,code)}else{const ast=parseModuleAnalysisAst(id,code);analysis=createModuleAnalysis(id,ast)}moduleAnalysisCache.set(cacheKey,{code,analysis});return analysis}function getOrCreateExternalModuleAnalysis(moduleId,code,options){const cacheKey=createExternalModuleAnalysisCacheKey(moduleId,options?.astEngine);const cached=externalModuleAnalysisCache.get(cacheKey);if(cached&&cached.code===code)return cached.analysis;const analysis=createModuleAnalysisFromCode(moduleId,code,options);externalModuleAnalysisCache.set(cacheKey,{code,analysis});return analysis}const CALL_EXPRESSION_TEXT_RE=/\b[a-z_$][\w$]*(?:\s*<[^(){};]+>)?\s*(?:\?\.\s*)?\(/i;const WEVU_PAGE_HOOK_NAMES=Object.keys(WE_VU_PAGE_HOOK_TO_FEATURE);function mayContainWevuPageFeatureHints(code){return WE_VU_RUNTIME_MODULE_IDS.some(moduleId=>code.includes(moduleId))&&CALL_EXPRESSION_TEXT_RE.test(code)&&WEVU_PAGE_HOOK_NAMES.some(hookName=>code.includes(hookName))}function collectWithBabel(code){const ast=parseJsLike(code);return collectWevuPageFeatureFlags(ast)}function collectWithOxc(code){const enabled=/* @__PURE__ */ new Set;const module=createModuleAnalysisFromCode(`<inline>`,code,{astEngine:`oxc`});if(module.wevuNamedHookLocals.size===0&&module.wevuNamespaceLocals.size===0)return enabled;const visit=node=>{if(!node)return;if(node.type===`CallExpression`){const callee=node.callee;if(callee?.type===`Identifier`){const matched=module.wevuNamedHookLocals.get(callee.name);if(matched)enabled.add(matched)}else if(callee?.type===`MemberExpression`&&!callee.computed&&callee.object?.type===`Identifier`&&callee.property?.type===`Identifier`){if(module.wevuNamespaceLocals.has(callee.object.name)){const hook=callee.property.name;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[hook];if(matched)enabled.add(matched)}}}else if(node.type===`ChainExpression`){visit(node.expression);return}for(const value of Object.values(node)){if(!value)continue;if(Array.isArray(value)){for(const child of value)if(child&&typeof child===`object`&&typeof child.type===`string`)visit(child)}else if(typeof value===`object`&&typeof value.type===`string`)visit(value)}};visit(module.ast);return enabled}function collectWevuPageFeatureFlagsFromCode(code,options){if(!mayContainWevuPageFeatureHints(code))return/* @__PURE__ */ new Set;const engine=options?.astEngine??`babel`;try{return engine===`oxc`?collectWithOxc(code):collectWithBabel(code)}catch{return/* @__PURE__ */ new Set}}const WEVU_FACTORY_NAMES=/* @__PURE__ */ new Set([WE_VU_RUNTIME_APIS.defineComponent,WE_VU_RUNTIME_APIS.createWevuComponent]);const REGEXP_META_CHARS_RE=/[.*+?^${}()|[\]\\]/g;function escapeRegExp(value){return value.replace(REGEXP_META_CHARS_RE,`\\$&`)}function mayContainNamedFactoryCall(code,localName){return new RegExp(`\\b${escapeRegExp(localName)}\\b(?:\\s*<[^(){};]+>)?\\s*(?:\\?\\.)?\\s*\\(`,`m`).test(code)}function mayContainNamespaceFactoryCall(code,namespaceName){const factoryAlternation=Array.from(WEVU_FACTORY_NAMES,name=>escapeRegExp(name)).join(`|`);return new RegExp(`\\b${escapeRegExp(namespaceName)}\\b\\s*\\.\\s*(?:${factoryAlternation})\\b(?:\\s*<[^(){};]+>)?\\s*(?:\\?\\.)?\\s*\\(`,`m`).test(code)}function mayCallWevuFactoryByText(code,module){for(const[localName,binding]of module.importedBindings.entries()){if(!isWevuRuntimeModuleId(binding.source))continue;if(binding.kind===`named`&&WEVU_FACTORY_NAMES.has(binding.importedName)){if(mayContainNamedFactoryCall(code,localName))return true;continue}if(binding.kind===`namespace`&&mayContainNamespaceFactoryCall(code,localName))return true}return false}function unwrapTypeLikeExpression$2(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node))return unwrapTypeLikeExpression$2(node.expression);if(t.isParenthesizedExpression(node))return unwrapTypeLikeExpression$2(node.expression);return node}function resolveOptionsObjectFromExpression(node){const normalized=unwrapTypeLikeExpression$2(node);if(t.isObjectExpression(normalized))return normalized;if(t.isIdentifier(normalized))return null;if(t.isCallExpression(normalized)){const callee=normalized.callee;if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object,{name:`Object`})&&t.isIdentifier(callee.property,{name:`assign`}))for(let index=normalized.arguments.length-1;index>=0;index-=1){const argument=normalized.arguments[index];if(t.isSpreadElement(argument)||!t.isExpression(argument))continue;const candidate=resolveOptionsObjectFromExpression(argument);if(candidate)return candidate}}return null}function getOxcStaticPropertyName(node){if(node?.type===`Identifier`)return node.name;if((node?.type===`StringLiteral`||node?.type===`Literal`)&&typeof node.value===`string`)return node.value}function getSetupFunctionFromOptionsObject(options){for(const prop of options.properties)if(t.isObjectProperty(prop)&&!prop.computed&&isStaticObjectKeyMatch$1(prop.key,`setup`)){if(t.isFunctionExpression(prop.value)||t.isArrowFunctionExpression(prop.value))return prop.value}else if(t.isObjectMethod(prop)&&!prop.computed&&isStaticObjectKeyMatch$1(prop.key,`setup`))return prop;else if(prop?.type===`Property`&&!prop.computed&&getOxcStaticPropertyName(prop.key)===`setup`){if(prop.value?.type===`FunctionExpression`||prop.value?.type===`ArrowFunctionExpression`)return prop.value}return null}function collectTargetOptionsObjectsWithModule(ast,module){const optionsObjects=[];const constObjectBindings=/* @__PURE__ */ new Map;const pendingConstObjectRefs=[];traverse(ast,{VariableDeclarator(path){if(!isTopLevel(path))return;if(!t.isIdentifier(path.node.id))return;const init=path.node.init;if(t.isObjectExpression(init))constObjectBindings.set(path.node.id.name,init)},CallExpression(path){if(!isTopLevel(path))return;const node=path.node;if(t.isV8IntrinsicIdentifier(node.callee))return;const first=node.arguments[0];if(!first||!t.isExpression(first))return;const binding=t.isIdentifier(node.callee)?module.importedBindings.get(node.callee.name):void 0;if(t.isIdentifier(node.callee)){if(binding?.kind!==`named`||!isWevuRuntimeModuleId(binding.source))return;if(binding.importedName!==WE_VU_RUNTIME_APIS.defineComponent&&binding.importedName!==WE_VU_RUNTIME_APIS.createWevuComponent)return}else if(t.isMemberExpression(node.callee)&&!node.callee.computed&&t.isIdentifier(node.callee.object)&&t.isIdentifier(node.callee.property)){const objectBinding=module.importedBindings.get(node.callee.object.name);if(objectBinding?.kind!==`namespace`||!isWevuRuntimeModuleId(objectBinding.source))return;if(node.callee.property.name!==WE_VU_RUNTIME_APIS.defineComponent&&node.callee.property.name!==WE_VU_RUNTIME_APIS.createWevuComponent)return}else return;const inlineObject=resolveOptionsObjectFromExpression(first);if(inlineObject)optionsObjects.push(inlineObject);else if(t.isIdentifier(first)){const target=constObjectBindings.get(first.name);if(target)optionsObjects.push(target);else pendingConstObjectRefs.push(first.name)}},OptionalCallExpression(path){if(!isTopLevel(path))return;const node=path.node;const callee=node.callee;if(t.isV8IntrinsicIdentifier(callee))return;const first=node.arguments[0];if(!first||!t.isExpression(first))return;if(t.isIdentifier(callee)){const binding=module.importedBindings.get(callee.name);if(binding?.kind!==`named`||!isWevuRuntimeModuleId(binding.source))return;if(binding.importedName!==WE_VU_RUNTIME_APIS.defineComponent&&binding.importedName!==WE_VU_RUNTIME_APIS.createWevuComponent)return}else if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property)){const objectBinding=module.importedBindings.get(callee.object.name);if(objectBinding?.kind!==`namespace`||!isWevuRuntimeModuleId(objectBinding.source))return;if(callee.property.name!==WE_VU_RUNTIME_APIS.defineComponent&&callee.property.name!==WE_VU_RUNTIME_APIS.createWevuComponent)return}else return;const inlineObject=resolveOptionsObjectFromExpression(first);if(inlineObject)optionsObjects.push(inlineObject);else if(t.isIdentifier(first)){const target=constObjectBindings.get(first.name);if(target)optionsObjects.push(target);else pendingConstObjectRefs.push(first.name)}}});for(const name of pendingConstObjectRefs){const target=constObjectBindings.get(name);if(target)optionsObjects.push(target)}return{optionsObjects,module}}function unwrapOxcTypeLikeExpression(node){if(node?.type===`TSAsExpression`||node?.type===`TSSatisfiesExpression`||node?.type===`TSNonNullExpression`||node?.type===`TSTypeAssertion`||node?.type===`ParenthesizedExpression`)return unwrapOxcTypeLikeExpression(node.expression);return node}function getOxcCallExpression(node){if(node?.type===`ChainExpression`)return getOxcCallExpression(node.expression);if(node?.type===`CallExpression`)return node;return null}function resolveOxcOptionsObjectFromExpression(node,bindings){const normalized=unwrapOxcTypeLikeExpression(node);if(normalized?.type===`ObjectExpression`)return normalized;if(normalized?.type===`Identifier`)return bindings.get(normalized.name)??null;if(normalized?.type!==`CallExpression`)return null;const callee=unwrapOxcTypeLikeExpression(normalized.callee);if(callee?.type!==`MemberExpression`||callee.computed||callee.object?.type!==`Identifier`||callee.object.name!==`Object`||callee.property?.type!==`Identifier`||callee.property.name!==`assign`)return null;for(let index=normalized.arguments.length-1;index>=0;index-=1){const argument=normalized.arguments[index];if(argument?.type===`SpreadElement`)continue;const candidate=resolveOxcOptionsObjectFromExpression(argument,bindings);if(candidate)return candidate}return null}function isOxcWevuFactoryCall(call,module){const callee=unwrapOxcTypeLikeExpression(call.callee);if(callee?.type===`Identifier`){const binding=module.importedBindings.get(callee.name);return binding?.kind===`named`&&isWevuRuntimeModuleId(binding.source)&&WEVU_FACTORY_NAMES.has(binding.importedName)}if(callee?.type===`MemberExpression`&&!callee.computed&&callee.object?.type===`Identifier`&&callee.property?.type===`Identifier`){const binding=module.importedBindings.get(callee.object.name);return binding?.kind===`namespace`&&isWevuRuntimeModuleId(binding.source)&&WEVU_FACTORY_NAMES.has(callee.property.name)}return false}function collectTargetOptionsObjectsWithOxcModule(ast,module){const optionsObjects=[];const constObjectBindings=/* @__PURE__ */ new Map;const pendingConstObjectRefs=[];for(const stmt of ast?.body??[]){if(stmt?.type===`VariableDeclaration`){for(const decl of stmt.declarations??[])if(decl?.id?.type===`Identifier`&&decl.init?.type===`ObjectExpression`)constObjectBindings.set(decl.id.name,decl.init);continue}if(stmt?.type!==`ExpressionStatement`)continue;const call=getOxcCallExpression(stmt.expression);if(!call||!isOxcWevuFactoryCall(call,module))continue;const first=call.arguments?.[0];if(!first)continue;const inlineObject=resolveOxcOptionsObjectFromExpression(first,constObjectBindings);if(inlineObject)optionsObjects.push(inlineObject);else if(first.type===`Identifier`)pendingConstObjectRefs.push(first.name)}for(const name of pendingConstObjectRefs){const target=constObjectBindings.get(name);if(target)optionsObjects.push(target)}return{optionsObjects,module}}function collectTargetOptionsObjects(ast,moduleId){return collectTargetOptionsObjectsWithModule(ast,createModuleAnalysis(moduleId,ast))}function collectTargetOptionsObjectsFromCode(code,moduleId,options){if(options?.astEngine===`oxc`){if(!(code.includes(`wevu`)&&(code.includes(WE_VU_RUNTIME_APIS.defineComponent)||code.includes(WE_VU_RUNTIME_APIS.createWevuComponent))))return{optionsObjects:[],module:createEmptyModuleAnalysis(moduleId,`oxc`)};const module=createModuleAnalysisFromCode(moduleId,code,options);if(![...module.importedBindings.values()].some(binding=>isWevuRuntimeModuleId(binding.source)&&(binding.kind===`namespace`||binding.kind===`named`&&(binding.importedName===WE_VU_RUNTIME_APIS.defineComponent||binding.importedName===WE_VU_RUNTIME_APIS.createWevuComponent))))return{optionsObjects:[],module};if(!mayCallWevuFactoryByText(code,module))return{optionsObjects:[],module};return collectTargetOptionsObjectsWithOxcModule(module.ast,module)}const module=createModuleAnalysisFromCode(moduleId,code,options);return collectTargetOptionsObjectsWithModule(module.ast,module)}function getCallCalleeName(callee){if(t.isV8IntrinsicIdentifier(callee))return null;if(t.isIdentifier(callee))return{type:`ident`,name:callee.name};if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property))return{type:`member`,object:callee.object.name,property:callee.property.name};if(t.isOptionalMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property))return{type:`member`,object:callee.object.name,property:callee.property.name};return null}function collectCalledBindingsFromFunctionBody(fn,engine=`babel`){const called=[];if(engine===`oxc`){const visit=node=>{if(!node)return;if(node.type===`CallExpression`){const callee=node.callee;if(callee?.type===`Identifier`)called.push({type:`ident`,name:callee.name});else if(callee?.type===`MemberExpression`&&!callee.computed&&callee.object?.type===`Identifier`&&callee.property?.type===`Identifier`)called.push({type:`member`,object:callee.object.name,property:callee.property.name})}else if(node.type===`ChainExpression`){visit(node.expression);return}for(const value of Object.values(node)){if(!value)continue;if(Array.isArray(value)){for(const child of value)if(child&&typeof child===`object`&&typeof child.type===`string`)visit(child)}else if(typeof value===`object`&&typeof value.type===`string`)visit(value)}};visit(fn);return called}t.traverseFast(fn,node=>{if(t.isCallExpression(node)){const name=getCallCalleeName(node.callee);if(name)called.push(name)}else if(t.isOptionalCallExpression(node)){const name=getCallCalleeName(node.callee);if(name)called.push(name)}});return called}function getMemberHookName(callee){if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property))return{object:callee.object.name,hook:callee.property.name};if(t.isOptionalMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property))return{object:callee.object.name,hook:callee.property.name};return null}function addNamespaceHookFeature(module,callee,enabled){const memberHook=getMemberHookName(callee);if(!memberHook||!module.wevuNamespaceLocals.has(memberHook.object))return;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[memberHook.hook];if(matched)enabled.add(matched)}function collectWevuHookCallsInFunctionBody(module,fn){const enabled=/* @__PURE__ */ new Set;if(module.engine===`oxc`){const visit=node=>{if(!node)return;if(node.type===`CallExpression`){const callee=node.callee;if(callee?.type===`Identifier`){const matched=module.wevuNamedHookLocals.get(callee.name);if(matched)enabled.add(matched)}else if(callee?.type===`MemberExpression`&&!callee.computed&&callee.object?.type===`Identifier`&&callee.property?.type===`Identifier`){if(module.wevuNamespaceLocals.has(callee.object.name)){const hook=callee.property.name;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[hook];if(matched)enabled.add(matched)}}}else if(node.type===`ChainExpression`){visit(node.expression);return}for(const value of Object.values(node)){if(!value)continue;if(Array.isArray(value)){for(const child of value)if(child&&typeof child===`object`&&typeof child.type===`string`)visit(child)}else if(typeof value===`object`&&typeof value.type===`string`)visit(value)}};visit(fn);return enabled}t.traverseFast(fn,node=>{if(t.isCallExpression(node)){const callee=node.callee;if(t.isIdentifier(callee)){const matched=module.wevuNamedHookLocals.get(callee.name);if(matched)enabled.add(matched);return}addNamespaceHookFeature(module,callee,enabled)}else if(t.isOptionalCallExpression(node)){const callee=node.callee;if(t.isIdentifier(callee)){const matched=module.wevuNamedHookLocals.get(callee.name);if(matched)enabled.add(matched);return}addNamespaceHookFeature(module,callee,enabled)}});return enabled}function resolveExportedFunctionNode(module,exportName){const target=module.exports.get(exportName);if(!target)return null;if(target.type===`local`){const fn=module.localFunctions.get(target.localName);return fn?{type:`inline`,node:fn}:null}if(target.type===`reexport`)return target;if(target.type===`inline`)return target;return null}async function resolveExternalFunction(resolver,importerId,source,exportName,moduleCache,options){if(source===`wevu`)return null;const resolvedId=await resolver.resolveId(source,importerId);if(!resolvedId)return null;const code=await resolver.loadCode(resolvedId);if(!code)return null;let analysis=moduleCache.get(resolvedId);if(!analysis){analysis=getOrCreateExternalModuleAnalysis(resolvedId,code,options);moduleCache.set(resolvedId,analysis)}const target=resolveExportedFunctionNode(analysis,exportName);if(!target)return null;if(target.type===`reexport`)return{moduleId:resolvedId,reexport:{source:target.source,importedName:target.importedName}};if(target.type===`inline`)return{moduleId:resolvedId,fn:target.node,module:analysis};return null}async function walkReachableWevuFeatures(options){const{pageModule,setupFn,resolver,moduleCache}=options;const enabled=/* @__PURE__ */ new Set;const seedCalls=collectCalledBindingsFromFunctionBody(setupFn,pageModule.engine);const queue=[];const visitedLocal=/* @__PURE__ */ new Set;const visitedExternal=/* @__PURE__ */ new Set;const enqueueLocal=(moduleId,name)=>{const key=`${moduleId}::${name}`;if(visitedLocal.has(key))return;visitedLocal.add(key);queue.push({kind:`local`,moduleId,name})};const enqueueExternal=(importerId,source,exportName)=>{const key=`${importerId}::${source}::${exportName}`;if(visitedExternal.has(key))return;visitedExternal.add(key);queue.push({kind:`external`,importerId,source,exportName})};const seedFromCall=call=>{if(call.type===`ident`){const binding=pageModule.importedBindings.get(call.name);if(binding?.kind===`named`)enqueueExternal(pageModule.id,binding.source,binding.importedName);else if(binding?.kind==="default")enqueueExternal(pageModule.id,binding.source,`default`);else if(!binding&&pageModule.localFunctions.has(call.name))enqueueLocal(pageModule.id,call.name);return}const binding=pageModule.importedBindings.get(call.object);if(binding?.kind===`namespace`)enqueueExternal(pageModule.id,binding.source,call.property)};for(const call of seedCalls)seedFromCall(call);let steps=0;const MAX_STEPS=128;while(queue.length&&steps<MAX_STEPS){steps+=1;const item=queue.shift();if(item.kind===`local`){if(item.moduleId!==pageModule.id)continue;const fn=pageModule.localFunctions.get(item.name);if(!fn)continue;for(const f of collectWevuHookCallsInFunctionBody(pageModule,fn))enabled.add(f);const calls=collectCalledBindingsFromFunctionBody(fn,pageModule.engine);for(const call of calls)seedFromCall(call);continue}const resolved=await resolveExternalFunction(resolver,item.importerId,item.source,item.exportName,moduleCache,{astEngine:options.astEngine});if(!resolved)continue;if(`reexport`in resolved){enqueueExternal(resolved.moduleId,resolved.reexport.source,resolved.reexport.importedName);continue}for(const f of collectWevuHookCallsInFunctionBody(resolved.module,resolved.fn))enabled.add(f);const calls=collectCalledBindingsFromFunctionBody(resolved.fn,resolved.module.engine);for(const call of calls)if(call.type===`ident`){const binding=resolved.module.importedBindings.get(call.name);if(binding?.kind===`named`)enqueueExternal(resolved.moduleId,binding.source,binding.importedName);else if(binding?.kind==="default")enqueueExternal(resolved.moduleId,binding.source,`default`);else if(!binding&&resolved.module.localFunctions.has(call.name)){const key=`${resolved.moduleId}::${call.name}`;if(!visitedLocal.has(key)){visitedLocal.add(key);const localFn=resolved.module.localFunctions.get(call.name);if(localFn){for(const f of collectWevuHookCallsInFunctionBody(resolved.module,localFn))enabled.add(f);for(const inner of collectCalledBindingsFromFunctionBody(localFn,resolved.module.engine))if(inner.type===`ident`){const innerBinding=resolved.module.importedBindings.get(inner.name);if(innerBinding?.kind===`named`)enqueueExternal(resolved.moduleId,innerBinding.source,innerBinding.importedName);else if(innerBinding?.kind==="default")enqueueExternal(resolved.moduleId,innerBinding.source,`default`)}}}}}else{const binding=resolved.module.importedBindings.get(call.object);if(binding?.kind===`namespace`)enqueueExternal(resolved.moduleId,binding.source,call.property)}}return enabled}async function collectWevuFeaturesFromSetupReachableImports(pageModule,setupFn,resolver,moduleCache,options){return await walkReachableWevuFeatures({pageModule,setupFn,resolver,moduleCache,astEngine:options?.astEngine})}async function collectWevuFeaturesFromCodeReachableImports(code,options){const{optionsObjects,module}=collectTargetOptionsObjectsFromCode(code,options.id,{astEngine:options.astEngine});if(!optionsObjects.length)return/* @__PURE__ */ new Set;const moduleCache=/* @__PURE__ */ new Map([[options.id,module]]);const enabled=/* @__PURE__ */ new Set;for(const optionsObject of optionsObjects){const setupFn=getSetupFunctionFromOptionsObject(optionsObject);if(!setupFn)continue;const reachable=await collectWevuFeaturesFromSetupReachableImports(module,setupFn,options.resolver,moduleCache,{astEngine:options.astEngine});for(const feature of reachable)enabled.add(feature)}return enabled}function injectWevuPageFeaturesInJs(source,options){const enabled=collectWevuPageFeatureFlagsFromCode(source,options);if(!enabled.size)return{code:source,transformed:false};const ast=parseJsLike(source);const{optionsObjects}=collectTargetOptionsObjects(ast,`<inline>`);if(!optionsObjects.length)return{code:source,transformed:false};let changed=false;for(const target of optionsObjects)changed=injectWevuPageFeatureFlagsIntoOptionsObject(target,enabled)||changed;if(!changed)return{code:source,transformed:false};const sourceMap=options?.sourceMap!==false;const generated=generate(ast,{compact:options?.minify===true,minified:options?.minify===true,retainLines:options?.minify!==true,sourceMaps:sourceMap,sourceFileName:`inline.js`},source);return{code:generated.code,transformed:true,map:sourceMap?generated.map:null}}async function injectWevuPageFeaturesInJsWithResolver(source,options){const preflight=collectTargetOptionsObjectsFromCode(source,options.id,{astEngine:options.astEngine});if(!preflight.optionsObjects.length)return{code:source,transformed:false};const ast=parseJsLike(source);const{optionsObjects}=collectTargetOptionsObjects(ast,options.id);if(!optionsObjects.length)return{code:source,transformed:false};const enabled=new Set(options.pageFeatureFlags??collectWevuPageFeatureFlagsFromCode(source,options));const moduleCache=/* @__PURE__ */ new Map;moduleCache.set(options.id,preflight.module);for(const optionsObject of optionsObjects){const setupFn=getSetupFunctionFromOptionsObject(optionsObject);if(!setupFn)continue;const fromImports=await collectWevuFeaturesFromSetupReachableImports(preflight.module,setupFn,options.resolver,moduleCache,{astEngine:options.astEngine});for(const flag of fromImports)enabled.add(flag)}if(!enabled.size)return{code:source,transformed:false};let changed=false;for(const optionsObject of optionsObjects)changed=injectWevuPageFeatureFlagsIntoOptionsObject(optionsObject,enabled)||changed;if(!changed)return{code:source,transformed:false};const sourceMap=options?.sourceMap!==false;const generated=generate(ast,{compact:options?.minify===true,minified:options?.minify===true,retainLines:options?.minify!==true,sourceMaps:sourceMap,sourceFileName:`inline.js`},source);return{code:generated.code,transformed:true,map:sourceMap?generated.map:null}}function createPageEntryMatcher(source){let cached;const warn=resolveWarnHandler(source.warn);async function ensure(){if(cached)return cached;let entries;try{entries=await source.loadEntries()}catch(error){const message=error instanceof Error?error.message:String(error);warn(`[wevu] 解析页面入口失败:${message}`);return/* @__PURE__ */ new Set}const set=/* @__PURE__ */ new Set;for(const pageEntry of entries.pages??[]){const normalized=stripLeadingSlashes(String(pageEntry));if(!normalized)continue;set.add(path.resolve(source.srcRoot,normalized))}for(const meta of entries.subPackages??[]){const root=meta.root??``;for(const pageEntry of meta.pages??[]){const normalized=stripLeadingSlashes(String(pageEntry));if(!normalized)continue;set.add(path.resolve(source.srcRoot,root,normalized))}}for(const entry of entries.pluginPages??[]){const normalized=stripLeadingSlashes(String(entry));if(!normalized)continue;set.add(path.resolve(source.srcRoot,removeExtensionDeep(normalized)))}cached=set;return set}return{markDirty(){cached=void 0},async isPageFile(filePath){const pages=await ensure();const normalized=removeExtensionDeep(filePath);return pages.has(normalized)}}}function isDefineComponentCall(node,aliases){return t.isIdentifier(node.callee)&&aliases.has(node.callee.name)}function isObjectAssignCall$1(node){const callee=node.callee;return t.isMemberExpression(callee)&&t.isIdentifier(callee.object,{name:`Object`})&&t.isIdentifier(callee.property,{name:`assign`})}function unwrapTypeLikeExpression$1(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSTypeAssertion(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node))return unwrapTypeLikeExpression$1(node.expression);if(t.isParenthesizedExpression(node))return unwrapTypeLikeExpression$1(node.expression);return node}function resolveObjectExpressionFromAssignCall(node){if(!isObjectAssignCall$1(node))return null;for(let index=node.arguments.length-1;index>=0;index-=1){const arg=node.arguments[index];if(t.isSpreadElement(arg)||!t.isExpression(arg))continue;const normalized=unwrapTypeLikeExpression$1(arg);if(t.isObjectExpression(normalized))return normalized}return null}function unwrapDefineComponent(node,aliases){if(t.isCallExpression(node)&&isDefineComponentCall(node,aliases)){const arg=node.arguments[0];if(t.isObjectExpression(arg))return arg}return null}function resolveComponentExpression(declaration,defineComponentDecls,aliases){if(!declaration)return null;if(t.isObjectExpression(declaration))return declaration;if(t.isCallExpression(declaration)&&isDefineComponentCall(declaration,aliases)){const arg=declaration.arguments[0];if(t.isObjectExpression(arg))return arg;if(t.isIdentifier(arg)){const matched=defineComponentDecls.get(arg.name);return matched?t.cloneNode(matched,true):null}if(t.isExpression(arg))return arg;return null}if(t.isCallExpression(declaration)&&isObjectAssignCall$1(declaration))return declaration;if(t.isIdentifier(declaration)){const matched=defineComponentDecls.get(declaration.name);return matched?t.cloneNode(matched,true):null}return null}function resolveComponentOptionsObject(componentExpr){if(!componentExpr)return null;const normalized=unwrapTypeLikeExpression$1(componentExpr);if(t.isObjectExpression(normalized))return normalized;if(t.isCallExpression(normalized))return resolveObjectExpressionFromAssignCall(normalized);return null}function isScriptSetupReturnedObject(path){const parent=path.parentPath;if(parent?.isVariableDeclarator()&&t.isIdentifier(parent.node.id,{name:`__returned__`}))return true;if(parent?.isReturnStatement())return true;return false}function isTemplateReturnGetterReference(path){const objectMethod=path.findParent(parent=>parent.isObjectMethod());if(objectMethod?.isObjectMethod()&&objectMethod.node.kind===`get`&&!objectMethod.node.computed&&t.isIdentifier(objectMethod.node.key,{name:path.node.name})&&objectMethod.parentPath?.isObjectExpression()&&isScriptSetupReturnedObject(objectMethod.parentPath)){const getter=objectMethod.node.body.body.find(statement=>t.isReturnStatement(statement));return Boolean(getter&&t.isReturnStatement(getter)&&t.isIdentifier(getter.argument,{name:path.node.name}))}return false}function isTemplateReturnPropertyReference(path){const property=path.parentPath;if(!property?.isObjectProperty())return false;if(!property.parentPath?.isObjectExpression()||!isScriptSetupReturnedObject(property.parentPath)||property.node.computed)return false;const key=property.node.key;const value=property.node.value;if(!t.isIdentifier(value,{name:path.node.name}))return false;if(t.isIdentifier(key,{name:path.node.name})||t.isStringLiteral(key,{value:path.node.name}))return true;return false}function isStaticPropertyNamed(node,name){return!node.computed&&(t.isIdentifier(node.key,{name})||t.isStringLiteral(node.key,{value:name}))}function isOptionsApiComponentsObject(path){const componentsProperty=path.parentPath;if(!componentsProperty?.isObjectProperty()||!isStaticPropertyNamed(componentsProperty.node,`components`))return false;const optionsObject=componentsProperty.parentPath;if(!optionsObject?.isObjectExpression())return false;const optionsParent=optionsObject.parentPath;if(optionsParent?.isExportDefaultDeclaration())return true;return Boolean(optionsParent?.isCallExpression()&&optionsParent.node.arguments[0]===optionsObject.node&&optionsParent.parentPath?.isExportDefaultDeclaration())}function isOptionsApiComponentRegistrationReference(path){const property=path.parentPath;return Boolean(property?.isObjectProperty()&&property.node.value===path.node&&property.parentPath?.isObjectExpression()&&isOptionsApiComponentsObject(property.parentPath))}function isReferencedOutsideTemplateReturn(path){if(!path.isReferencedIdentifier())return false;if(isTemplateReturnGetterReference(path)||isTemplateReturnPropertyReference(path)||isOptionsApiComponentRegistrationReference(path))return false;return true}function collectReferencedNames(ast,candidateNames){const referencedNames=/* @__PURE__ */ new Set;traverse(ast,{Identifier(path){const name=path.node.name;if(!candidateNames.has(name))return;if(isReferencedOutsideTemplateReturn(path))referencedNames.add(name)}});return referencedNames}function removeSetupReturnProperties(ast,removableNames){if(!removableNames.size)return false;let changed=false;traverse(ast,{ObjectMethod(path){if(!path.parentPath?.isObjectExpression()||!isScriptSetupReturnedObject(path.parentPath))return;if(path.node.computed||!t.isIdentifier(path.node.key))return;const name=path.node.key.name;if(!removableNames.has(name))return;if(path.node.kind!==`get`)return;const getter=path.node.body.body.find(statement=>t.isReturnStatement(statement));if(!getter||!t.isReturnStatement(getter)||!t.isIdentifier(getter.argument,{name}))return;path.remove();changed=true},ObjectProperty(path){if(!path.parentPath?.isObjectExpression()||!isScriptSetupReturnedObject(path.parentPath))return;if(path.node.computed||!t.isIdentifier(path.node.value))return;const name=path.node.value.name;if(!removableNames.has(name))return;if(!t.isIdentifier(path.node.key,{name})&&!t.isStringLiteral(path.node.key,{value:name}))return;path.remove();changed=true}});return changed}function removeOptionsApiComponentRegistrations(ast,removableNames){if(!removableNames.size)return false;let changed=false;traverse(ast,{ObjectProperty(path){if(!path.parentPath?.isObjectExpression()||!isOptionsApiComponentsObject(path.parentPath)||!t.isIdentifier(path.node.value)||!removableNames.has(path.node.value.name))return;path.remove();changed=true}});traverse(ast,{ObjectProperty(path){if(!t.isObjectExpression(path.node.value)||!isStaticPropertyNamed(path.node,`components`)||path.node.value.properties.length>0||!path.parentPath?.isObjectExpression())return;const optionsParent=path.parentPath.parentPath;if(optionsParent?.isExportDefaultDeclaration()||optionsParent?.isCallExpression()&&optionsParent.node.arguments[0]===path.parentPath.node&&optionsParent.parentPath?.isExportDefaultDeclaration())path.remove()}});return changed}function pruneTemplateComponentMeta(ast,templateComponentMeta){if(!Object.keys(templateComponentMeta).length)return false;const candidateNames=new Set(Object.keys(templateComponentMeta));const referencedNames=collectReferencedNames(ast,candidateNames);const removableNames=new Set([...candidateNames].filter(name=>!referencedNames.has(name)));let changed=false;traverse(ast,{ImportDeclaration(path){if(!path.node.specifiers.length)return;const kept=path.node.specifiers.filter(specifier=>{if(!(`local`in specifier)||!t.isIdentifier(specifier.local))return true;const localName=specifier.local.name;return!removableNames.has(localName)});if(kept.length!==path.node.specifiers.length){changed=true;if(kept.length===0){path.remove();return}path.node.specifiers=kept}}});changed=removeSetupReturnProperties(ast,removableNames)||changed;changed=removeOptionsApiComponentRegistrations(ast,removableNames)||changed;return changed}function vueSfcTransformPlugin(){return{name:`vue-sfc-transform`,visitor:{ImportDeclaration(path){if(path.node.source.value===`vue`){const specifiers=path.node.specifiers;const filteredSpecifiers=specifiers.filter(s=>{if(s.type===`ImportSpecifier`&&t.isIdentifier(s.imported)&&s.imported.name===WE_VU_RUNTIME_APIS.defineComponent)return false;return true});if(filteredSpecifiers.length===0)path.remove();else if(filteredSpecifiers.length!==specifiers.length)path.node.specifiers=filteredSpecifiers}},ObjectExpression(path){const filtered=path.node.properties.filter(p=>{if(p.type===`ObjectProperty`){const key=p.key;if(key.type===`Identifier`&&key.name===`__name`)return false}return true});path.node.properties=filtered},CallExpression(path){if(t.isMemberExpression(path.node.callee)&&t.isIdentifier(path.node.callee.object,{name:`Object`})&&t.isIdentifier(path.node.callee.property,{name:`defineProperty`})&&t.isIdentifier(path.node.arguments[0],{name:`__returned__`})&&t.isStringLiteral(path.node.arguments[1],{value:`__isScriptSetup`})&&path.parentPath?.isExpressionStatement()){path.parentPath.remove();return}if(t.isIdentifier(path.node.callee,{name:`__expose`})&&path.parentPath?.isExpressionStatement()&&path.node.arguments.length===0)path.parentPath.remove()}}}}function createCollectVisitors(state){return{VariableDeclarator(path){if(!t.isIdentifier(path.node.id)||!path.node.init)return;if(t.isObjectExpression(path.node.init))state.defineComponentDecls.set(path.node.id.name,t.cloneNode(path.node.init,true));const unwrapped=unwrapDefineComponent(path.node.init,state.defineComponentAliases);if(unwrapped){state.defineComponentDecls.set(path.node.id.name,t.cloneNode(unwrapped,true));path.node.init=unwrapped;state.transformed=true}},ExportDefaultDeclaration(path){state.defaultExportPath=path}}}const RUNTIME_IMPORT_PATH=WE_VU_COMPILER_RUNTIME_MODULE_ID;const COMPILED_DEFINE_COMPONENT_IMPORT_RE=/^import\s+\{\s*defineComponent\s+as\s+([A-Za-z_$][\w$]*)\s*\}\s+from\s+['"]vue['"];?\n/;const EXPORT_DEFAULT_PURE_RE=/export\s+default\s+\/\*@__PURE__\*\/\s*/;const JSON_MACRO_RE=/\bdefine(?:App|Page|Component|Sitemap|Theme)Json\s*\(/;const PAGE_META_RE=/\bdefinePageMeta\s*\(/;const OPTION_CAPABILITY_RE=/\b(?:createApp|createWevuComponent|setData|setWevuDefaults)\b/;const WEVU_RUNTIME_IMPORT_RE=/\bfrom\s*['"](?:wevu(?:\/internal-runtime)?|virtual:weapp-vite\/runtime)['"]/;const DYNAMIC_OPTIONS_PROPERTY_RE=/\.\.\.|\[/;function hasMetadataInjectionOptions(source,options){const hasWevuDefaults=options?.wevuDefaults&&Object.keys(options.wevuDefaults).length>0;return Boolean(options?.isTypeScript||options?.isApp||options?.skipComponentTransform||options?.minify||options?.sourceMap!==false||options?.templateComponentMeta||hasWevuDefaults||options?.classStyleBindings?.length||options?.templateRefs?.length||options?.layoutHosts?.length||options?.inlineExpressions?.length||options?.runtimeCapabilities?.required.length||options?.functionPropPaths?.length||options?.propsAliases||options?.propsDerivedKeys?.length||options?.relaxStructuredTypeOnlyProps||options?.bindingManifest||options?.pageLayout||options?.scopedSlotHostProperties||options?.nativeSlotContext||options?.stabilizeCssVarsRuntime||/\b(?:useSlots|options|extends|mixins|definitionFilter|behaviors)\b|\\/.test(source))}function findMatchingCallEnd(source,openParenIndex){let depth=0;let quote;let escaped=false;let lineComment=false;let blockComment=false;for(let index=openParenIndex;index<source.length;index+=1){const current=source[index];const next=source[index+1];if(lineComment){if(current===`
23
23
  `||current===`\r`)lineComment=false;continue}if(blockComment){if(current===`*`&&next===`/`){blockComment=false;index+=1}continue}if(quote){if(escaped)escaped=false;else if(current===`\\`)escaped=true;else if(current===quote)quote=void 0;continue}if(current===`/`&&next===`/`){lineComment=true;index+=1;continue}if(current===`/`&&next===`*`){blockComment=true;index+=1;continue}if(current===`"`||current===`'`||current==="`"){quote=current;continue}if(current===`(`){depth+=1;continue}if(current===`)`){depth-=1;if(depth===0)return index}}return-1}function stripCompiledScriptSetupMarkers(optionsSource){return optionsSource.replace(/^\s*__name:\s*['"][^'"]+['"],?\n?/m,``).replace(/\{\s*expose:\s*__expose\s*\}/g,`{ expose }`).replace(/\b__expose(?=\s*\()/g,`expose`).replace(/^\s*Object\.defineProperty\(\s*__returned__\s*,\s*['"]__isScriptSetup['"]\s*,\s*\{\s*enumerable:\s*false\s*,\s*value:\s*true\s*\}\s*\);?\n?/m,``)}function tryFastTransformCompiledScriptSetup(source,options){if(hasMetadataInjectionOptions(source,options))return;if(JSON_MACRO_RE.test(source)||PAGE_META_RE.test(source))return;const importMatch=source.match(COMPILED_DEFINE_COMPONENT_IMPORT_RE);if(!importMatch)return;const defineComponentLocal=importMatch[1];const afterImport=source.slice(importMatch[0].length);if(/from\s+['"]vue['"]/.test(afterImport))return;const exportMatch=EXPORT_DEFAULT_PURE_RE.exec(afterImport);if(!exportMatch||exportMatch.index<0)return;const beforeExport=afterImport.slice(0,exportMatch.index);const callStart=exportMatch.index+exportMatch[0].length;const expectedCall=`${defineComponentLocal}(`;if(!afterImport.startsWith(expectedCall,callStart))return;const openParenIndex=callStart+defineComponentLocal.length;const callEnd=findMatchingCallEnd(afterImport,openParenIndex);if(callEnd<0)return;const trailing=afterImport.slice(callEnd+1).trim();if(trailing&&trailing!==`;`)return;const componentOptions=stripCompiledScriptSetupMarkers(afterImport.slice(openParenIndex+1,callEnd).trim());if(!componentOptions.startsWith(`{`)||!componentOptions.endsWith(`}`)||OPTION_CAPABILITY_RE.test(source)||DYNAMIC_OPTIONS_PROPERTY_RE.test(componentOptions)||WEVU_RUNTIME_IMPORT_RE.test(source))return;const pageMarker=` __wevu_isPage: ${options?.isPage===true},\n`;return{code:[`import { ${WE_VU_RUNTIME_APIS.createWevuComponent} } from "${RUNTIME_IMPORT_PATH}";`,beforeExport.trim(),`const __wevuOptions = {\n${pageMarker}${componentOptions.replace(/^\{\s*/,``).replace(/\s*\}$/,``)}\n};`,`export default __wevuOptions;`,`${WE_VU_RUNTIME_APIS.createWevuComponent}(__wevuOptions);`].filter(Boolean).join(`
24
- `),map:null,transformed:true,componentStyleOptions:{styleIsolation:{kind:`absent`},addGlobalClass:{kind:`absent`}}}}function ensureRuntimeImport(program,importedName,localName=importedName){const runtimeImportPath=resolveWevuInternalImportModuleId(importedName);let targetImport=program.body.find(node=>t.isImportDeclaration(node)&&node.importKind!==`type`&&node.source.value===runtimeImportPath);if(!targetImport){targetImport=t.importDeclaration([t.importSpecifier(t.identifier(localName),t.identifier(importedName))],t.stringLiteral(runtimeImportPath));program.body.unshift(targetImport);return}if(!targetImport.specifiers.some(spec=>{if(!t.isImportSpecifier(spec)||spec.importKind===`type`)return false;if(!t.isIdentifier(spec.imported,{name:importedName}))return false;return t.isIdentifier(spec.local,{name:localName})}))targetImport.specifiers.push(t.importSpecifier(t.identifier(localName),t.identifier(importedName)))}const INTERNAL_RUNTIME_VALUE_EXPORTS=/* @__PURE__ */ new Set([`addMutationRecorder`,`batch`,`computed`,`createTextVNode`,`createVNode`,`createApp`,`createWevuComponent`,`createWevuScopedSlotComponent`,...Object.values(WE_VU_RUNTIME_CAPABILITY_INSTALLERS),`customRef`,`defineAppSetup`,`defineComponent`,`effect`,`effectScope`,`endBatch`,`getCurrentInstance`,`getCurrentPageStackSnapshot`,`getCurrentScope`,`getCurrentSetupContext`,`getDeepWatchStrategy`,`Fragment`,`getNavigationBarMetrics`,`getReactiveVersion`,`hasInjectionContext`,`inject`,`injectGlobal`,`isNoSetData`,`isProxy`,`isRaw`,`isReactive`,`isReadonly`,`isRef`,`isShallowReactive`,`isShallowRef`,`isVNode`,`markNoSetData`,`markRaw`,`mergeModels`,`mergeProps`,`mountRuntimeInstance`,`nextTick`,`normalizeClass`,`normalizeJsxIsland`,`normalizeStyle`,`onActivated`,`onAddToFavorites`,`onAttached`,`onBeforeMount`,`onBeforeUnmount`,`onBeforeUpdate`,`onDeactivated`,`onDetached`,`onError`,`onErrorCaptured`,`onHide`,`onLaunch`,`onLoad`,`onMemoryWarning`,`onMounted`,`onMoved`,`onPageNotFound`,`onPageScroll`,`onPullDownRefresh`,`onReachBottom`,`onReady`,`onResize`,`onRouteDone`,`onSaveExitState`,`onScopeDispose`,`onServerPrefetch`,`onShareAppMessage`,`onShareTimeline`,`onShow`,`onTabItemTap`,`onThemeChange`,`onUnhandledRejection`,`onUnload`,`onUnmounted`,`onUpdated`,`prelinkReactiveTree`,`provide`,`provideGlobal`,`reactive`,`resolveDirective`,`resolveComponent`,`readonly`,`ref`,`registerApp`,`registerComponent`,`removeMutationRecorder`,`resetWevuDefaults`,`resolveLayoutBridge`,`resolveLayoutHost`,`resolvePropValue`,`resolveRuntimePageLayoutName`,`runSetupFunction`,`setCurrentInstance`,`setCurrentSetupContext`,`setDeepWatchStrategy`,`setGlobalProvidedValue`,`setPageLayout`,`setRuntimeSetDataVisibility`,`setWevuDefaults`,`shallowReactive`,`shallowReadonly`,`shallowRef`,`startBatch`,`stop`,`syncRuntimePageLayoutState`,`syncRuntimePageLayoutStateFromRuntime`,`teardownRuntimeInstance`,`toRaw`,`toRef`,`toRefs`,`toValue`,`transformOn`,`touchReactive`,`traverse`,`triggerRef`,`unref`,`useAttrs`,`useCssModule`,`useCssVars`,`useAsyncDerivation`,`useAsyncPullDownRefresh`,`useBindModel`,`useBoundingClientRect`,`useChangeModel`,`useDisposables`,`useElementIntersectionObserver`,`useIntersectionObserver`,`useLayoutBridge`,`useLayoutHosts`,`useModel`,`useNativeInstance`,`useNativePageRouter`,`useNativeRouter`,`useNavigationBarMetrics`,`usePageLayout`,`usePageScrollThrottle`,`usePageStack`,`useScrollOffset`,`useSelectorFields`,`useSelectorQuery`,`useSlots`,`useTemplateRef`,`useUpdatePerformanceListener`,`version`,`vModelCheckbox`,`vModelRadio`,`vModelSelect`,`vModelText`,`vShow`,`withDirectives`,`waitForLayoutHost`,`watch`,`watchEffect`,`watchPostEffect`,`watchSyncEffect`]);function ensureInternalRuntimeImport(program,importedName,localName=importedName){const runtimeImportPath=resolveWevuInternalImportModuleId(importedName);let targetImport=program.body.find(node=>t.isImportDeclaration(node)&&node.source.value===runtimeImportPath);if(!targetImport){targetImport=t.importDeclaration([],t.stringLiteral(runtimeImportPath));program.body.unshift(targetImport)}if(!targetImport.specifiers.some(specifier=>t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.imported,{name:importedName})&&t.isIdentifier(specifier.local,{name:localName})))targetImport.specifiers.push(t.importSpecifier(t.identifier(localName),t.identifier(importedName)))}function splitWevuNamedImportsToInternalRuntime(path,program,state){if(path.node.source.value!==`wevu`||path.node.importKind===`type`)return;const remaining=path.node.specifiers.filter(specifier=>{if(!t.isImportSpecifier(specifier)||specifier.importKind===`type`||!t.isIdentifier(specifier.imported)||!t.isIdentifier(specifier.local))return true;const importedName=specifier.imported.name;if(!INTERNAL_RUNTIME_VALUE_EXPORTS.has(importedName))return true;ensureInternalRuntimeImport(program,importedName,specifier.local.name);state.transformed=true;return false});if(remaining.length===0){path.remove();return}if(remaining.length!==path.node.specifiers.length)path.node.specifiers=remaining}function createImportVisitors(program,state){return{ImportDeclaration(path){if(path.node.source.value===`@vue/babel-helper-vue-transform-on`){const defaultImport=path.node.specifiers.find(specifier=>t.isImportDefaultSpecifier(specifier));if(defaultImport){ensureRuntimeImport(program,`transformOn`,defaultImport.local.name);state.transformed=true;path.remove();return}}if(path.node.source.value===`vue`){const movedVueRuntimeAPIs=/* @__PURE__ */ new Set([`createTextVNode`,`createVNode`,`Fragment`,`isVNode`,`mergeProps`,`resolveComponent`,`resolveDirective`,`unref`,`useAttrs`,`useCssModule`,`useCssVars`,`useSlots`,`useModel`,`mergeModels`,`useTemplateRef`,`vModelCheckbox`,`vModelRadio`,`vModelSelect`,`vModelText`,`vShow`,`withDirectives`]);const movedSpecifiers=[];const remaining=path.node.specifiers.filter(specifier=>{if(t.isImportSpecifier(specifier)&&specifier.imported.type===`Identifier`&&specifier.imported.name===WE_VU_RUNTIME_APIS.defineComponent){state.defineComponentAliases.add(specifier.local.name);state.transformed=true;return false}if(t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.imported)){const importedName=specifier.imported.name;if(movedVueRuntimeAPIs.has(importedName)&&t.isIdentifier(specifier.local)){movedSpecifiers.push({importedName,localName:specifier.local.name});state.transformed=true;return false}}return true});if(movedSpecifiers.length)for(const{importedName,localName}of movedSpecifiers)ensureRuntimeImport(program,importedName,localName);if(remaining.length===0){path.remove();return}path.node.specifiers=remaining}if(path.node.importKind===`type`){state.transformed=true;path.remove();return}const kept=path.node.specifiers.filter(specifier=>{if(`importKind`in specifier&&specifier.importKind===`type`){state.transformed=true;return false}return true});if(kept.length!==path.node.specifiers.length){if(kept.length===0){path.remove();return}path.node.specifiers=kept}splitWevuNamedImportsToInternalRuntime(path,program,state)}}}function createAppSetupVisitors(program,state){return{CallExpression(path){if(!t.isIdentifier(path.node.callee,{name:WE_VU_RUNTIME_APIS.defineAppSetup}))return;ensureRuntimeImport(program,WE_VU_RUNTIME_APIS.defineAppSetup);state.transformed=true}}}function importedName(specifier){return t.isIdentifier(specifier.imported)?specifier.imported.name:specifier.imported.value}function createPageMetaVisitors(ast,state){const macroCalls=new Set(collectPageMetaCallsForTransform(ast));return{ImportDeclaration(path){if(path.node.source.value!==`wevu`||path.node.importKind===`type`)return;const remaining=path.node.specifiers.filter(specifier=>{return!t.isImportSpecifier(specifier)||specifier.importKind===`type`||importedName(specifier)!==WEVU_DEFINE_PAGE_META_MACRO});if(remaining.length===path.node.specifiers.length)return;state.transformed=true;if(!remaining.length){path.remove();return}path.node.specifiers=remaining},CallExpression(path){if(!macroCalls.has(path.node)||!path.parentPath?.isExpressionStatement())return;path.parentPath.remove();state.transformed=true}}}function createSetupExposeVisitors(state){return{ObjectMethod(path){if(!t.isIdentifier(path.node.key,{name:`setup`})&&!t.isStringLiteral(path.node.key,{value:`setup`}))return;const params=path.node.params;if(params.length<2||!t.isObjectPattern(params[1]))return;const ctxParam=params[1];if(ctxParam.properties.some(property=>{if(!t.isObjectProperty(property))return false;return t.isIdentifier(property.key,{name:`expose`})&&t.isIdentifier(property.value,{name:`__expose`})})&&path.scope.hasBinding(`__expose`)&&!path.scope.hasBinding(`expose`)){path.scope.rename(`__expose`,`expose`);state.transformed=true;for(const property of ctxParam.properties){if(!t.isObjectProperty(property))continue;if(t.isIdentifier(property.key,{name:`expose`})&&t.isIdentifier(property.value,{name:`expose`}))property.shorthand=true}}}}}function isOptionalPatternNode(node){return t.isIdentifier(node)||t.isAssignmentPattern(node)||t.isRestElement(node)||t.isArrayPattern(node)||t.isObjectPattern(node)||t.isVoidPattern(node)}function stripOptionalFlag(node){if(node?.optional!==true)return false;node.optional=false;return true}function stripOptionalFromPattern(pattern){if(!pattern)return false;if(t.isTSParameterProperty(pattern))return stripOptionalFromPattern(pattern.parameter);let changed=false;if(t.isIdentifier(pattern)||t.isAssignmentPattern(pattern)||t.isRestElement(pattern)||t.isArrayPattern(pattern)||t.isObjectPattern(pattern))changed=stripOptionalFlag(pattern)||changed;if(t.isIdentifier(pattern)||t.isVoidPattern(pattern))return changed;if(t.isAssignmentPattern(pattern)){if(isOptionalPatternNode(pattern.left))changed=stripOptionalFromPattern(pattern.left)||changed;return changed}if(t.isRestElement(pattern)){if(isOptionalPatternNode(pattern.argument))changed=stripOptionalFromPattern(pattern.argument)||changed;return changed}if(t.isObjectPattern(pattern)){for(const prop of pattern.properties)if(t.isRestElement(prop)){if(isOptionalPatternNode(prop.argument)&&stripOptionalFromPattern(prop.argument))changed=true}else if(t.isObjectProperty(prop)){if(isOptionalPatternNode(prop.value)&&stripOptionalFromPattern(prop.value))changed=true}return changed}if(t.isArrayPattern(pattern)){for(const element of pattern.elements)if(isOptionalPatternNode(element)&&stripOptionalFromPattern(element))changed=true}return changed}function stripTypeArguments(node){let stripped=false;if(node.typeParameters){node.typeParameters=null;stripped=true}if(node.typeArguments){node.typeArguments=null;stripped=true}return stripped}function createStripTypesVisitors(state){return{ExportNamedDeclaration(path){if(path.node.exportKind===`type`){state.transformed=true;path.remove();return}if(path.node.specifiers?.length){const remaining=path.node.specifiers.filter(spec=>{if(t.isExportSpecifier(spec))return spec.exportKind!==`type`;return true});if(remaining.length!==path.node.specifiers.length){state.transformed=true;if(remaining.length===0){path.remove();return}path.node.specifiers=remaining}}},CallExpression(path){if(t.isIdentifier(path.node.callee,{name:`__expose`})&&path.parentPath?.isExpressionStatement()){if(path.node.arguments.length===0){path.parentPath.remove();state.transformed=true;return}}if(stripTypeArguments(path.node))state.transformed=true},NewExpression(path){if(stripTypeArguments(path.node))state.transformed=true},ObjectProperty(path){if(t.isIdentifier(path.node.key,{name:`__name`})||t.isStringLiteral(path.node.key,{value:`__name`})){path.remove();state.transformed=true}},TSTypeAliasDeclaration(path){path.remove();state.transformed=true},TSInterfaceDeclaration(path){path.remove();state.transformed=true},TSEnumDeclaration(path){path.remove();state.transformed=true},TSModuleDeclaration(path){path.remove();state.transformed=true},TSImportEqualsDeclaration(path){path.remove();state.transformed=true},TSAsExpression(path){path.replaceWith(path.node.expression);state.transformed=true},TSSatisfiesExpression(path){path.replaceWith(path.node.expression);state.transformed=true},TSTypeAssertion(path){path.replaceWith(path.node.expression);state.transformed=true},TSNonNullExpression(path){path.replaceWith(path.node.expression);state.transformed=true},TSTypeAnnotation(path){path.remove();state.transformed=true},TSParameterProperty(path){path.replaceWith(path.node.parameter);state.transformed=true},Function(path){if(t.isIdentifier(path.node.params[0],{name:`this`})){path.node.params.shift();state.transformed=true}if(path.node.returnType){path.node.returnType=null;state.transformed=true}if(stripTypeArguments(path.node))state.transformed=true;for(const param of path.node.params)if(stripOptionalFromPattern(param))state.transformed=true},ClassMethod(path){if(stripOptionalFlag(path.node))state.transformed=true},ClassPrivateMethod(path){if(stripOptionalFlag(path.node))state.transformed=true},ClassAccessorProperty(path){if(path.node.typeAnnotation){path.node.typeAnnotation=null;state.transformed=true}if(stripOptionalFlag(path.node))state.transformed=true},ClassProperty(path){if(path.node.typeAnnotation){path.node.typeAnnotation=null;state.transformed=true}if(stripOptionalFlag(path.node))state.transformed=true},ClassPrivateProperty(path){if(path.node.typeAnnotation){path.node.typeAnnotation=null;state.transformed=true}if(stripOptionalFlag(path.node))state.transformed=true}}}function createMacroVisitors(ast,state){const appSetupVisitors=createAppSetupVisitors(ast.program,state);const setupExposeVisitors=createSetupExposeVisitors(state);const stripTypesVisitors=createStripTypesVisitors(state);const pageMetaVisitors=createPageMetaVisitors(ast,state);const mergedVisitors={...appSetupVisitors,...setupExposeVisitors,...stripTypesVisitors,...pageMetaVisitors};mergedVisitors.CallExpression=path=>{appSetupVisitors.CallExpression?.(path);setupExposeVisitors.CallExpression?.(path);stripTypesVisitors.CallExpression?.(path);if(!path.removed)pageMetaVisitors.CallExpression?.(path)};return mergedVisitors}const absent$1={kind:`absent`};const unknown$1={kind:`unknown`};function unwrap$1(node){return t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node)||t.isParenthesizedExpression(node)?unwrap$1(node.expression):node}function isFactoryCall(path){if(!path.isCallExpression()||!t.isIdentifier(path.node.callee))return false;const binding=path.scope.getBinding(path.node.callee.name);return binding?.path.isImportSpecifier()&&t.isIdentifier(binding.path.node.imported,{name:`defineComponent`})&&binding.path.parentPath.isImportDeclaration()&&[`vue`,`wevu`,`wevu/internal-runtime`,`virtual:weapp-vite/runtime`].includes(binding.path.parentPath.node.source.value)}function isSafeReference$1(reference,visiting){let current=reference;while(current.parentPath){const parent=current.parentPath;if(parent.isExportDefaultDeclaration())return true;if(parent.isVariableDeclarator()&&t.isIdentifier(parent.node.id))return isSafeBinding(parent.scope.getBinding(parent.node.id.name),visiting);if(parent.isCallExpression()&&isFactoryCall(parent)){current=parent;continue}if(parent.isObjectProperty()&&!parent.node.computed||parent.isObjectExpression()||parent.isSpreadElement()||parent.isTSAsExpression()||parent.isTSSatisfiesExpression()||parent.isTSNonNullExpression()||parent.isParenthesizedExpression()){current=parent;continue}return false}return false}function isSafeBinding(binding,visiting=/* @__PURE__ */ new Set){if(!binding?.constant||!binding.path.isVariableDeclarator()||!binding.path.parentPath.isVariableDeclaration()||binding.path.parentPath.node.kind!==`const`||binding.path.parentPath.parentPath?.isExportNamedDeclaration())return false;if(visiting.has(binding.path.node))return false;const next=new Set(visiting).add(binding.path.node);return binding.referencePaths.every(reference=>isSafeReference$1(reference,next))}function resolve(node,scope,visited){node=unwrap$1(node);if(!t.isIdentifier(node)||node.name===`undefined`&&!scope?.getBinding(`undefined`))return{kind:`expression`,node,scope};const binding=scope?.getBinding(node.name);if(!isSafeBinding(binding)||!binding?.path.isVariableDeclarator()||visited.has(binding.path.node)||!binding.path.node.init||!t.isExpression(binding.path.node.init))return;return resolve(binding.path.node.init,binding.path.scope,new Set(visited).add(binding.path.node))}function primitive$1(node,scope){const resolved=resolve(node,scope,/* @__PURE__ */ new Set);if(!resolved)return unknown$1;const value=resolved.node;if(t.isStringLiteral(value)||t.isBooleanLiteral(value)||t.isNumericLiteral(value))return{kind:`known`,value:value.value};if(t.isNullLiteral(value))return{kind:`known`,value:null};if(t.isTemplateLiteral(value)&&value.expressions.length===0)return{kind:`known`,value:value.quasis[0]?.value.cooked??value.quasis[0]?.value.raw??``};if(t.isIdentifier(value,{name:`undefined`})&&!resolved.scope?.getBinding(`undefined`))return{kind:`known`,value:void 0};if(t.isUnaryExpression(value)&&t.isNumericLiteral(value.argument)){if(value.operator===`void`)return{kind:`known`,value:void 0};if(value.operator===`-`||value.operator===`+`)return{kind:`known`,value:value.operator===`-`?-value.argument.value:value.argument.value}}return unknown$1}function resolveStaticObjectProperty(node,key,scope,visited=/* @__PURE__ */ new Set){const resolved=resolve(node,scope,visited);if(!resolved||visited.has(resolved.node))return unknown$1;const current=resolved.node;const next=new Set(visited).add(current);if(t.isCallExpression(current)&&t.isMemberExpression(current.callee)&&!current.callee.computed&&t.isIdentifier(current.callee.object,{name:`Object`})&&!resolved.scope?.getBinding(`Object`)&&t.isIdentifier(current.callee.property,{name:`assign`})){let result=absent$1;for(const argument of current.arguments){const part=t.isExpression(argument)?resolveStaticObjectProperty(argument,key,resolved.scope,next):unknown$1;if(part.kind!==`absent`)result=part}return result}if(!t.isObjectExpression(current))return t.isNullLiteral(current)||t.isStringLiteral(current)||t.isBooleanLiteral(current)||t.isNumericLiteral(current)||t.isIdentifier(current,{name:`undefined`})&&!resolved.scope?.getBinding(`undefined`)?absent$1:unknown$1;let result=absent$1;for(const entry of current.properties){if(t.isSpreadElement(entry)){const part=resolveStaticObjectProperty(entry.argument,key,resolved.scope,next);if(part.kind!==`absent`)result=part;continue}const name=!entry.computed&&t.isIdentifier(entry.key)?{kind:`known`,value:entry.key.name}:t.isExpression(entry.key)?primitive$1(entry.key,resolved.scope):unknown$1;if(name.kind!==`known`)result=unknown$1;else if(String(name.value)===key)result=t.isObjectProperty(entry)&&t.isExpression(entry.value)?{kind:`expression`,node:entry.value,scope:resolved.scope,property:entry}:unknown$1}return result}function isSafeAssignOperand(node,scope,visited){const resolved=resolve(node,scope,visited);if(!resolved||visited.has(resolved.node)||!t.isObjectExpression(resolved.node))return false;const next=new Set(visited).add(resolved.node);return resolved.node.properties.every(entry=>{if(t.isSpreadElement(entry))return isSafeAssignOperand(entry.argument,resolved.scope,next);if(t.isObjectMethod(entry)&&entry.kind!==`method`)return false;const name=!entry.computed&&t.isIdentifier(entry.key)?{kind:`known`,value:entry.key.name}:t.isExpression(entry.key)?primitive$1(entry.key,resolved.scope):unknown$1;return name.kind===`known`&&name.value!==`__proto__`})}function hasUnsafeObjectEvaluation(node,scope,visited=/* @__PURE__ */ new Set){const resolved=resolve(node,scope,visited);if(!resolved||visited.has(resolved.node))return false;const current=resolved.node;const next=new Set(visited).add(current);if(t.isCallExpression(current)&&t.isMemberExpression(current.callee)&&!current.callee.computed&&t.isIdentifier(current.callee.object,{name:`Object`})&&t.isIdentifier(current.callee.property,{name:`assign`}))return Boolean(resolved.scope?.getBinding(`Object`))||current.arguments.some(argument=>!t.isExpression(argument)||!isSafeAssignOperand(argument,resolved.scope,/* @__PURE__ */ new Set)||hasUnsafeObjectEvaluation(argument,resolved.scope,next));if(t.isObjectExpression(current))return current.properties.some(entry=>{if(t.isSpreadElement(entry)){const operand=resolve(entry.argument,resolved.scope,next);return Boolean(operand&&t.isObjectExpression(operand.node)&&!isSafeAssignOperand(entry.argument,resolved.scope,next))||hasUnsafeObjectEvaluation(entry.argument,resolved.scope,next)}return t.isObjectProperty(entry)&&t.isExpression(entry.value)&&hasUnsafeObjectEvaluation(entry.value,resolved.scope,next)});return false}function analyzeComponentStyleOptions(node,scope){if(!node)return{styleIsolation:unknown$1,addGlobalClass:unknown$1};if(hasUnsafeObjectEvaluation(node,scope))return;const options=resolveStaticObjectProperty(node,`options`,scope);if([`definitionFilter`,`behaviors`,`extends`,`mixins`,`__proto__`].some(key=>resolveStaticObjectProperty(node,key,scope).kind!==`absent`))return;const read=key=>{const value=options.kind===`expression`?resolveStaticObjectProperty(options.node,key,options.scope):options;if(value.kind===`absent`)return absent$1;return value.kind===`expression`?primitive$1(value.node,value.scope):unknown$1};return{styleIsolation:read(`styleIsolation`),addGlobalClass:read(`addGlobalClass`)}}function isPlainRecord(value){if(!value||typeof value!==`object`||Array.isArray(value))return false;const proto=Object.getPrototypeOf(value);return proto===null||proto===Object.prototype}function isStaticObjectKeyMatch(key,expected){if(t.isIdentifier(key))return key.name===expected;if(t.isStringLiteral(key))return key.value===expected;return false}function getObjectPropertyByKey$2(node,key){for(const prop of node.properties){if(!t.isObjectProperty(prop)||prop.computed)continue;if(isStaticObjectKeyMatch(prop.key,key))return prop}return null}function createStaticObjectKey(key){return t.isValidIdentifier(key)?t.identifier(key):t.stringLiteral(key)}function mergeStableKeys(target,incoming){const seen=new Set(target);for(const key of incoming){if(!key||seen.has(key))continue;seen.add(key);target.push(key)}}function resolveOutputRoot(outputPath){return/^[A-Z_$][\w$]*/i.exec(outputPath)?.[0]}function resolveBindingManifestPickKeys(manifest,autoSetDataPick){const keys=[];if(!isBindingManifestComplete(manifest))return keys;const outputRoots=manifest.bindings.flatMap(binding=>{const root=resolveOutputRoot(binding.outputPath);return root?[root]:[]});if(manifest.bindings.some(binding=>{return binding.updateMode===`snapshot-fallback`&&!resolveOutputRoot(binding.outputPath)}))return keys;const requiresScopedSlotOwner=manifest.bindings.some(binding=>{return binding.outputPath===WEVU_SLOT_OWNER_ID_KEY||binding.outputPath===WEVU_SLOT_OWNER_ID_PROP});if(autoSetDataPick||requiresScopedSlotOwner)mergeStableKeys(keys,outputRoots);if(autoSetDataPick)mergeStableKeys(keys,[WEVU_SLOT_NAMES_PROP,WEVU_SLOT_OWNER_ID_PROP,WEVU_SLOT_SCOPE_KEY]);if(requiresScopedSlotOwner)mergeStableKeys(keys,[WEVU_SLOT_OWNER_ID_KEY,WEVU_SLOT_NAMES_PROP,WEVU_SLOT_OWNER_ID_PROP,WEVU_SLOT_SCOPE_KEY]);return keys}function mergePickArray(array,keys){const existing=/* @__PURE__ */ new Set;for(const element of array.elements)if(t.isStringLiteral(element))existing.add(element.value);let changed=false;for(const key of keys){if(existing.has(key))continue;existing.add(key);array.elements.push(t.stringLiteral(key));changed=true}return changed}function injectSetDataPick(componentOptions,keys){if(!keys.length)return false;const pickArray=()=>t.arrayExpression(keys.map(key=>t.stringLiteral(key)));const setDataProp=getObjectPropertyByKey$2(componentOptions,`setData`);if(!setDataProp){componentOptions.properties.unshift(t.objectProperty(t.identifier(`setData`),t.objectExpression([t.objectProperty(t.identifier(`pick`),pickArray())])));return true}if(t.isObjectExpression(setDataProp.value)){const pickProp=getObjectPropertyByKey$2(setDataProp.value,`pick`);if(!pickProp){setDataProp.value.properties.unshift(t.objectProperty(t.identifier(`pick`),pickArray()));return true}return t.isArrayExpression(pickProp.value)&&mergePickArray(pickProp.value,keys)}if(t.isIdentifier(setDataProp.value)||t.isMemberExpression(setDataProp.value)||t.isCallExpression(setDataProp.value)){setDataProp.value=t.objectExpression([t.objectProperty(t.identifier(`pick`),pickArray()),t.spreadElement(t.cloneNode(setDataProp.value,true))]);return true}return false}function injectManifestMetadata(componentOptions,manifest,mode){const serialized=createRuntimeBindingManifest(manifest,mode);const value=t.callExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`freeze`)),[t.valueToNode(serialized)]);const existing=getObjectPropertyByKey$2(componentOptions,WEVU_BINDING_MANIFEST_KEY);if(existing){existing.value=value;return true}componentOptions.properties.push(t.objectProperty(t.stringLiteral(WEVU_BINDING_MANIFEST_KEY),value));return true}function injectLayoutComputed(componentOptions,plan){const runtimeEntries=Object.entries(plan?.currentLayout?.props??{}).filter(entry=>{const value=entry[1];return typeof value===`object`&&value!==null&&value.kind===`expression`});if(!runtimeEntries.length)return false;const computedEntries=runtimeEntries.map(([key,value])=>{const expression=parseBabelExpression(value.expression)??t.identifier(`undefined`);return t.objectProperty(createStaticObjectKey(`${WEVU_LAYOUT_BIND_PREFIX}${key}`),t.functionExpression(null,[],t.blockStatement([t.tryStatement(t.blockStatement([t.returnStatement(t.cloneNode(expression,true))]),t.catchClause(t.identifier(WEVU_EXPRESSION_ERROR_IDENTIFIER),t.blockStatement([t.returnStatement(t.identifier(`undefined`))])))])))});const computedProp=getObjectPropertyByKey$2(componentOptions,`computed`);if(!computedProp){componentOptions.properties.unshift(t.objectProperty(t.identifier(`computed`),t.objectExpression(computedEntries)));return true}if(t.isObjectExpression(computedProp.value)){computedProp.value.properties.push(...computedEntries);return true}if(t.isIdentifier(computedProp.value)||t.isMemberExpression(computedProp.value)){computedProp.value=t.objectExpression([...computedEntries,t.spreadElement(t.cloneNode(computedProp.value,true))]);return true}return false}function injectBindingManifestContract(componentOptions,options){let changed=injectLayoutComputed(componentOptions,options.pageLayout);if(!options.manifest)return changed;changed=injectManifestMetadata(componentOptions,options.manifest,options.runtimeBindingManifest??`compact`)||changed;changed=injectSetDataPick(componentOptions,resolveBindingManifestPickKeys(options.manifest,options.autoSetDataPick===true))||changed;return changed}function injectClassStyleComputed(optionsObject,bindings,propsAliases,warn){if(!bindings.length)return false;const warnHandler=resolveWarnHandler(warn);const helpers={normalizeClass:t.identifier(`__wevuNormalizeClass`),normalizeStyle:t.identifier(`__wevuNormalizeStyle`),unref:t.identifier(`__wevuUnref`),resolvePropValue:t.identifier(`__wevuResolvePropValue`)};const entries=buildClassStyleComputedEntries(bindings,helpers,propsAliases);if(!entries.length)return false;const computedProp=getObjectPropertyByKey$2(optionsObject,`computed`);if(!computedProp){optionsObject.properties.splice(0,0,t.objectProperty(createStaticObjectKey(`computed`),t.objectExpression(entries)));return true}if(t.isObjectExpression(computedProp.value)){computedProp.value.properties.push(...entries);return true}if(t.isIdentifier(computedProp.value)||t.isMemberExpression(computedProp.value)){computedProp.value=t.objectExpression([...entries,t.spreadElement(t.cloneNode(computedProp.value,true))]);return true}warnHandler(`无法自动注入 class/style 计算属性,请手动合并 computed。`);return false}function ensureClassStyleRuntimeImports(program){ensureRuntimeImport(program,`normalizeClass`,`__wevuNormalizeClass`);ensureRuntimeImport(program,`normalizeStyle`,`__wevuNormalizeStyle`);ensureRuntimeImport(program,`unref`,`__wevuUnref`);ensureRuntimeImport(program,`resolvePropValue`,`__wevuResolvePropValue`)}function unwrapExpression$1(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node)||t.isParenthesizedExpression(node))return unwrapExpression$1(node.expression);return node}function resolveSetupFunction$1(componentOptionsObject){for(const prop of componentOptionsObject.properties){if(t.isObjectMethod(prop)&&!prop.computed&&isStaticObjectKeyMatch(prop.key,`setup`))return prop;if(!t.isObjectProperty(prop)||prop.computed||!isStaticObjectKeyMatch(prop.key,`setup`))continue;const value=unwrapExpression$1(prop.value);if(t.isFunctionExpression(value)||t.isArrowFunctionExpression(value))return value}return null}function isComponentMetaObject(node){return node.properties.some(prop=>{return t.isObjectProperty(prop)&&!prop.computed&&isStaticObjectKeyMatch(prop.key,`__weappViteUsingComponent`)&&t.isBooleanLiteral(prop.value,{value:true})})}function isSerializableSeed(node){const normalized=unwrapExpression$1(node);if(t.isStringLiteral(normalized)||t.isNumericLiteral(normalized)||t.isBooleanLiteral(normalized)||t.isNullLiteral(normalized))return true;if(t.isTemplateLiteral(normalized))return normalized.expressions.length===0;if(t.isArrayExpression(normalized))return normalized.elements.every(element=>!!element&&!t.isSpreadElement(element)&&isSerializableSeed(element));if(t.isObjectExpression(normalized)){if(isComponentMetaObject(normalized))return false;return normalized.properties.every(prop=>{return t.isObjectProperty(prop)&&!prop.computed&&!t.isPatternLike(prop.value)&&isSerializableSeed(prop.value)})}return false}function extractSeedExpression(node){const normalized=unwrapExpression$1(node);if(t.isCallExpression(normalized)&&t.isIdentifier(normalized.callee)&&[`ref`,`shallowRef`,`reactive`].includes(normalized.callee.name)){const firstArg=normalized.arguments[0];if(firstArg&&!t.isSpreadElement(firstArg)&&t.isExpression(firstArg)&&isSerializableSeed(firstArg))return t.cloneNode(unwrapExpression$1(firstArg),true);return null}if(!isSerializableSeed(normalized))return null;return t.cloneNode(normalized,true)}function collectSetupInitializers(setupBody){const initializers=/* @__PURE__ */ new Map;for(const statement of setupBody.body){if(!t.isVariableDeclaration(statement))continue;for(const declarator of statement.declarations){if(!t.isIdentifier(declarator.id)||!declarator.init||!t.isExpression(declarator.init))continue;initializers.set(declarator.id.name,declarator.init)}}return initializers}function resolveReturnedObjectExpression(setupBody,initializers){for(let index=setupBody.body.length-1;index>=0;index-=1){const statement=setupBody.body[index];if(!t.isReturnStatement(statement)||!statement.argument||!t.isExpression(statement.argument))continue;const returned=unwrapExpression$1(statement.argument);if(t.isObjectExpression(returned))return returned;if(t.isIdentifier(returned)){const initializer=initializers.get(returned.name);if(initializer){const normalized=unwrapExpression$1(initializer);if(t.isObjectExpression(normalized))return normalized}}}return null}function resolvePropertyName(node){if(t.isIdentifier(node.key)&&!node.computed)return node.key.name;if(t.isStringLiteral(node.key)&&!node.computed)return node.key.value;return null}function injectSetupInitialData(componentOptionsObject){if(getObjectPropertyByKey$2(componentOptionsObject,`data`))return false;const setupFn=resolveSetupFunction$1(componentOptionsObject);if(!setupFn||!t.isBlockStatement(setupFn.body))return false;const initializers=collectSetupInitializers(setupFn.body);const returnedObject=resolveReturnedObjectExpression(setupFn.body,initializers);if(!returnedObject)return false;const seedProperties=[];for(const prop of returnedObject.properties){if(!t.isObjectProperty(prop)||prop.computed)continue;const propertyName=resolvePropertyName(prop);if(!propertyName)continue;let sourceExpression=null;if(prop.shorthand&&t.isIdentifier(prop.value))sourceExpression=initializers.get(prop.value.name)??null;else if(t.isIdentifier(prop.value))sourceExpression=initializers.get(prop.value.name)??prop.value;else if(t.isExpression(prop.value))sourceExpression=prop.value;if(!sourceExpression)continue;const seedExpression=extractSeedExpression(sourceExpression);if(!seedExpression)continue;seedProperties.push(t.objectProperty(createStaticObjectKey(propertyName),seedExpression))}if(!seedProperties.length)return false;componentOptionsObject.properties.unshift(t.objectMethod(`method`,createStaticObjectKey(`data`),[],t.blockStatement([t.returnStatement(t.objectExpression(seedProperties))])));return true}function resolveImportedLocalName(program,source,importedName){for(const statement of program.body){if(!t.isImportDeclaration(statement)||statement.importKind===`type`||statement.source.value!==source)continue;for(const specifier of statement.specifiers)if(t.isImportSpecifier(specifier)&&specifier.importKind!==`type`&&t.isIdentifier(specifier.imported,{name:importedName}))return specifier.local.name}}function createEmptyCssVarsRegistration(useCssVarsLocalName,unrefLocalName){return t.expressionStatement(t.callExpression(t.identifier(useCssVarsLocalName),[t.arrowFunctionExpression([],t.blockStatement([t.expressionStatement(t.callExpression(t.identifier(unrefLocalName),[t.identifier(`undefined`)])),t.returnStatement(t.objectExpression([]))]))]))}function injectStableCssVarsRuntime(program,componentOptionsObject,scope){const runtimeImportPath=resolveWevuInternalImportModuleId(`useCssVars`);const reactivityImportPath=resolveWevuInternalImportModuleId(`unref`);const useCssVarsLocalName=resolveImportedLocalName(program,runtimeImportPath,`useCssVars`)??scope.generateUidIdentifier(`useCssVars`).name;const unrefLocalName=resolveImportedLocalName(program,reactivityImportPath,`unref`)??scope.generateUidIdentifier(`unref`).name;if(!resolveImportedLocalName(program,runtimeImportPath,`useCssVars`))ensureRuntimeImport(program,`useCssVars`,useCssVarsLocalName);if(!resolveImportedLocalName(program,reactivityImportPath,`unref`))ensureRuntimeImport(program,`unref`,unrefLocalName);const registration=createEmptyCssVarsRegistration(useCssVarsLocalName,unrefLocalName);const setupFn=resolveSetupFunction$1(componentOptionsObject);if(setupFn){const body=setupFn.body;if(t.isBlockStatement(body))body.body.unshift(registration);else setupFn.body=t.blockStatement([registration,t.returnStatement(body)]);return true}componentOptionsObject.properties.push(t.objectMethod(`method`,t.identifier(`setup`),[],t.blockStatement([registration,t.returnStatement(t.objectExpression([]))])));return true}function resolveDefaultsTarget(node){if(t.isObjectExpression(node))return node;if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node)||t.isParenthesizedExpression(node))return resolveDefaultsTarget(node.expression);if(t.isCallExpression(node)&&t.isMemberExpression(node.callee)&&!node.callee.computed&&t.isIdentifier(node.callee.object,{name:`Object`})&&t.isIdentifier(node.callee.property,{name:`assign`})){const first=node.arguments[0];return first&&t.isExpression(first)?resolveDefaultsTarget(first):void 0}}function applyDefaultsToExpression(expression,defaults,merge){let changed=false;const fallback=resolveDefaultsTarget(expression);for(const[key,value]of Object.entries(defaults)){const effective=resolveStaticObjectProperty(expression,key,void 0);if(effective.kind===`expression`&&effective.property){const normalized=t.objectProperty(t.stringLiteral(key),effective.property.value);changed=merge(t.objectExpression([normalized]),{[key]:value})||changed;effective.property.value=normalized.value}else if(effective.kind===`absent`&&fallback)changed=merge(fallback,{[key]:value})||changed;else if(effective.kind===`unknown`&&fallback)changed=merge(fallback,{[key]:value})||changed}return changed}function mergePlainDefaultsIntoObjectExpression(target,defaults){const entries=Object.entries(defaults);if(!entries.length)return false;let changed=false;const injectedProps=[];for(const[key,value]of entries){if(getObjectPropertyByKey$2(target,key))continue;injectedProps.push(t.objectProperty(createStaticObjectKey(key),t.valueToNode(value)))}if(!injectedProps.length)return false;target.properties.splice(0,0,...injectedProps);changed=true;return changed}function mergeNestedDefaults(optionsObject,key,defaultsValue){if(!isPlainRecord(defaultsValue)){if(defaultsValue===void 0)return false;if(getObjectPropertyByKey$2(optionsObject,key))return false;optionsObject.properties.splice(0,0,t.objectProperty(createStaticObjectKey(key),t.valueToNode(defaultsValue)));return true}const existing=getObjectPropertyByKey$2(optionsObject,key);if(!existing){optionsObject.properties.splice(0,0,t.objectProperty(createStaticObjectKey(key),t.valueToNode(defaultsValue)));return true}if(t.isObjectExpression(existing.value))return mergePlainDefaultsIntoObjectExpression(existing.value,defaultsValue);if(t.isIdentifier(existing.value)||t.isMemberExpression(existing.value)){const injected=t.valueToNode(defaultsValue);if(t.isObjectExpression(injected)){injected.properties.push(t.spreadElement(t.cloneNode(existing.value,true)));existing.value=injected;return true}}return false}function applyWevuDefaultsToOptionsObject(optionsObject,defaults){let changed=false;for(const[key,value]of Object.entries(defaults)){if(key===`setData`||key===`options`){changed=mergeNestedDefaults(optionsObject,key,value)||changed;continue}if(value===void 0||getObjectPropertyByKey$2(optionsObject,key))continue;optionsObject.properties.splice(0,0,t.objectProperty(createStaticObjectKey(key),t.valueToNode(value)));changed=true}return changed}function stripVirtualHostFromDefaults(defaults){const next={...defaults};const options=next.options;if(!isPlainRecord(options))return next;if(!hasOwn(options,`virtualHost`))return next;const copiedOptions={...options};delete copiedOptions.virtualHost;if(Object.keys(copiedOptions).length>0)next.options=copiedOptions;else delete next.options;return next}function serializeWevuDefaults(defaults,warn){const warnHandler=resolveWarnHandler(warn);const seen=/* @__PURE__ */ new Set;try{return JSON.stringify(defaults,(_key,value)=>{if(typeof value===`function`||typeof value===`symbol`||typeof value===`bigint`)throw new TypeError(`Wevu defaults 必须可被 JSON 序列化。`);if(value&&typeof value===`object`){if(seen.has(value))throw new Error(`Wevu defaults 不能包含循环引用。`);seen.add(value);if(!Array.isArray(value)&&!isPlainRecord(value))throw new Error(`Wevu defaults 只能是普通对象或数组。`)}return value})}catch(error){warnHandler(`[vue] 序列化 wevu defaults 失败:${error instanceof Error?error.message:String(error)}`);return}}function insertWevuDefaultsCall(program,serializedDefaults){const callStatement=t.expressionStatement(t.callExpression(t.identifier(WE_VU_RUNTIME_APIS.setWevuDefaults),[t.valueToNode(JSON.parse(serializedDefaults))]));let insertIndex=0;while(insertIndex<program.body.length&&t.isImportDeclaration(program.body[insertIndex]))insertIndex+=1;program.body.splice(insertIndex,0,callStatement)}function applyWevuDefaultsToComponentOptions(params){const{componentExpr,parsedWevuDefaults,options}=params;let changed=false;if(options?.isApp&&parsedWevuDefaults.app&&Object.keys(parsedWevuDefaults.app).length>0)changed=applyDefaultsToExpression(componentExpr,parsedWevuDefaults.app,applyWevuDefaultsToOptionsObject)||changed;if(!options?.isApp&&parsedWevuDefaults.component&&Object.keys(parsedWevuDefaults.component).length>0){const componentDefaults=options?.isPage?stripVirtualHostFromDefaults(parsedWevuDefaults.component):parsedWevuDefaults.component;if(Object.keys(componentDefaults).length>0)changed=applyDefaultsToExpression(componentExpr,componentDefaults,applyWevuDefaultsToOptionsObject)||changed}const componentOptionDefaults=parsedWevuDefaults.component?.options;if(options?.isPage&&isPlainRecord(componentOptionDefaults)&&componentOptionDefaults.virtualHost===true)changed=applyDefaultsToExpression(componentExpr,{options:{virtualHost:false}},applyWevuDefaultsToOptionsObject)||changed;return changed}function injectWevuDefaultsForApp(params){const{astProgram,options,serializedWevuDefaults}=params;let changed=false;if(options?.isApp&&serializedWevuDefaults){ensureRuntimeImport(astProgram,WE_VU_RUNTIME_APIS.setWevuDefaults);insertWevuDefaultsCall(astProgram,serializedWevuDefaults);changed=true}return changed}function rewriteComponentExport(params){const{ast,exportPath,componentExpr,isAppFile,skipComponentTransform}=params;const DEFAULT_OPTIONS_IDENTIFIER=`__wevuOptions`;if(isAppFile){ensureRuntimeImport(ast.program,WE_VU_RUNTIME_APIS.createApp);exportPath.replaceWith(t.expressionStatement(t.callExpression(t.identifier(WE_VU_RUNTIME_APIS.createApp),[componentExpr])));return true}if(skipComponentTransform){exportPath.replaceWith(t.exportDefaultDeclaration(componentExpr));return true}ensureRuntimeImport(ast.program,WE_VU_RUNTIME_APIS.createWevuComponent);exportPath.replaceWithMultiple([t.variableDeclaration(`const`,[t.variableDeclarator(t.identifier(DEFAULT_OPTIONS_IDENTIFIER),componentExpr)]),t.expressionStatement(t.callExpression(t.identifier(WE_VU_RUNTIME_APIS.createWevuComponent),[t.identifier(DEFAULT_OPTIONS_IDENTIFIER)])),t.exportDefaultDeclaration(t.identifier(DEFAULT_OPTIONS_IDENTIFIER))]);return true}function createUnrefImport(program){const names=/* @__PURE__ */ new Set;let scope;traverse(t.file(program),{Program(path){scope=path.scope},Identifier(path){names.add(path.node.name)}});let identifier;do identifier=scope.generateUidIdentifier(`wevuInlineUnref`);while(names.has(identifier.name));ensureRuntimeImport(program,`unref`,identifier.name);return identifier}function buildMethodsMergeFromSpreadSources(componentExpr,inlineMapExpr){const spreadSources=[];for(const prop of componentExpr.properties){if(!t.isSpreadElement(prop)||!t.isExpression(prop.argument))continue;const methodsAccess=t.optionalMemberExpression(t.cloneNode(prop.argument),t.identifier(`methods`),false,true);spreadSources.push(t.logicalExpression(`||`,methodsAccess,t.objectExpression([])))}if(!spreadSources.length)return null;return t.callExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`assign`)),[t.objectExpression([]),...spreadSources,t.objectExpression([t.objectProperty(createStaticObjectKey(WEVU_INLINE_MAP_KEY),inlineMapExpr)])])}function injectInlineExpressions(componentExpr,inlineExpressions,program){if(!inlineExpressions.length)return false;const needsUnref=inlineExpressions.some(entry=>entry.runtimeHelpers?.unref);if(needsUnref&&!program)throw new Error(`注入 maybe-ref 内联表达式需要宿主脚本 AST。`);const inlineMapExpr=buildInlineExpressionMap(inlineExpressions,needsUnref?createUnrefImport(program):void 0);const methodsProp=getObjectPropertyByKey$2(componentExpr,`methods`);if(!methodsProp){const mergedMethods=buildMethodsMergeFromSpreadSources(componentExpr,inlineMapExpr);if(mergedMethods){componentExpr.properties.push(t.objectProperty(createStaticObjectKey(`methods`),mergedMethods));return true}componentExpr.properties.push(t.objectProperty(createStaticObjectKey(`methods`),t.objectExpression([t.objectProperty(createStaticObjectKey(WEVU_INLINE_MAP_KEY),inlineMapExpr)])));return true}if(!t.isObjectExpression(methodsProp.value))return false;const mapProp=getObjectPropertyByKey$2(methodsProp.value,WEVU_INLINE_MAP_KEY);if(!mapProp){methodsProp.value.properties.push(t.objectProperty(createStaticObjectKey(WEVU_INLINE_MAP_KEY),inlineMapExpr));return true}if(t.isObjectExpression(mapProp.value)){mapProp.value.properties.push(...inlineMapExpr.properties);return true}return false}function buildLayoutHostEntry(binding){const props=[t.objectProperty(t.identifier(`key`),t.stringLiteral(binding.key))];if(binding.refName)props.push(t.objectProperty(t.identifier(`refName`),t.stringLiteral(binding.refName)));props.push(t.objectProperty(t.identifier(`selector`),t.stringLiteral(binding.selector)));if(binding.kind)props.push(t.objectProperty(t.identifier(`kind`),t.stringLiteral(binding.kind)));return t.objectExpression(props)}function injectLayoutHosts(optionsObject,bindings,warn){if(!bindings.length)return false;const warnHandler=resolveWarnHandler(warn);const entries=bindings.map(binding=>buildLayoutHostEntry(binding));const hostsArray=t.arrayExpression(entries);const key=createStaticObjectKey(WEVU_LAYOUT_HOSTS_KEY);const existing=getObjectPropertyByKey$2(optionsObject,WEVU_LAYOUT_HOSTS_KEY);if(!existing){optionsObject.properties.push(t.objectProperty(key,hostsArray));return true}if(t.isArrayExpression(existing.value)){existing.value.elements.push(...entries);return true}if(t.isIdentifier(existing.value)||t.isMemberExpression(existing.value)){existing.value=t.arrayExpression([...entries,t.spreadElement(t.cloneNode(existing.value,true))]);return true}warnHandler(`无法自动注入 layout host 元数据,请手动合并 ${WEVU_LAYOUT_HOSTS_KEY}。`);return false}function injectPropsAliases(optionsObject,propsAliases){const entries=Object.entries(propsAliases??{}).filter(([alias,propName])=>alias&&propName).map(([alias,propName])=>{return t.objectProperty(createStaticObjectKey(alias),t.stringLiteral(propName))});if(!entries.length)return false;if(getObjectPropertyByKey$2(optionsObject,WEVU_PROPS_ALIASES_KEY))return false;optionsObject.properties.push(t.objectProperty(createStaticObjectKey(WEVU_PROPS_ALIASES_KEY),t.objectExpression(entries)));return true}function injectPropsDerivedKeys(optionsObject,propsDerivedKeys){const keys=[...new Set(propsDerivedKeys??[])].filter(Boolean);if(!keys.length)return false;if(getObjectPropertyByKey$2(optionsObject,WEVU_PROPS_DERIVED_KEYS_KEY))return false;optionsObject.properties.push(t.objectProperty(createStaticObjectKey(WEVU_PROPS_DERIVED_KEYS_KEY),t.arrayExpression(keys.map(key=>t.stringLiteral(key)))));return true}function buildTemplateRefEntry(binding){const props=[t.objectProperty(t.identifier(`selector`),t.stringLiteral(binding.selector)),t.objectProperty(t.identifier(`inFor`),t.booleanLiteral(binding.inFor))];if(binding.name)props.push(t.objectProperty(t.identifier(`name`),t.stringLiteral(binding.name)));if(binding.expAst){const body=t.blockStatement([t.returnStatement(t.cloneNode(binding.expAst,true))]);props.push(t.objectProperty(t.identifier(`get`),t.functionExpression(null,[],body)))}if(binding.kind)props.push(t.objectProperty(t.identifier(`kind`),t.stringLiteral(binding.kind)));return t.objectExpression(props)}function injectTemplateRefs(optionsObject,bindings,warn){if(!bindings.length)return false;const warnHandler=resolveWarnHandler(warn);const entries=bindings.map(binding=>buildTemplateRefEntry(binding));const refsArray=t.arrayExpression(entries);const key=createStaticObjectKey(WEVU_TEMPLATE_REFS_KEY);const existing=getObjectPropertyByKey$2(optionsObject,WEVU_TEMPLATE_REFS_KEY);if(!existing){optionsObject.properties.push(t.objectProperty(key,refsArray));return true}if(t.isArrayExpression(existing.value)){existing.value.elements.push(...entries);return true}if(t.isIdentifier(existing.value)||t.isMemberExpression(existing.value)){existing.value=t.arrayExpression([...entries,t.spreadElement(t.cloneNode(existing.value,true))]);return true}warnHandler(`无法自动注入 template ref 元数据,请手动合并 ${WEVU_TEMPLATE_REFS_KEY}。`);return false}function hasStaticProperty(target,keyName){for(const prop of target.properties){if(prop.type!==`ObjectProperty`&&prop.type!==`ObjectMethod`||prop.computed)continue;const key=prop.key;if(key.type===`Identifier`&&key.name===keyName)return true;if(key.type===`StringLiteral`&&key.value===keyName)return true}return false}function injectFunctionPropPaths(componentOptionsObject,paths){const uniquePaths=[...new Set(paths)].filter(Boolean);if(!uniquePaths.length)return false;if(hasStaticProperty(componentOptionsObject,WEVU_FUNCTION_PROP_PATHS_KEY))return false;componentOptionsObject.properties.push(t.objectProperty(t.identifier(WEVU_FUNCTION_PROP_PATHS_KEY),t.arrayExpression(uniquePaths.map(path=>t.stringLiteral(path)))));return true}function createObjectLiteral(value){return t.objectExpression(Object.entries(value).map(([key,item])=>t.objectProperty(t.stringLiteral(key),item&&typeof item===`object`&&!Array.isArray(item)?createObjectLiteral(item):t.valueToNode(item))))}function injectCssModules(componentOptionsObject,modules){if(hasStaticProperty(componentOptionsObject,WEVU_CSS_MODULES_KEY))return false;componentOptionsObject.properties.push(t.objectProperty(t.stringLiteral(WEVU_CSS_MODULES_KEY),createObjectLiteral(modules)));return true}function createScopedSlotHostPropertyDefinition(typeName,value){return t.objectExpression([t.objectProperty(t.identifier(`type`),typeName===`String`?t.identifier(`String`):t.nullLiteral()),t.objectProperty(t.identifier(`value`),value===null?t.nullLiteral():t.stringLiteral(value))])}function createScopedSlotHostProperties(){return[t.objectProperty(t.identifier(WEVU_SLOT_NAMES_PROP),createScopedSlotHostPropertyDefinition(`null`,null)),t.objectProperty(t.identifier(WEVU_SLOT_OWNER_ID_PROP),createScopedSlotHostPropertyDefinition(`String`,``)),t.objectProperty(t.identifier(WEVU_SLOT_SCOPE_KEY),createScopedSlotHostPropertyDefinition(`null`,null))]}function injectScopedSlotHostProperties(componentOptionsObject){const propertiesProp=getObjectPropertyByKey$2(componentOptionsObject,`properties`);if(!propertiesProp){componentOptionsObject.properties.splice(0,0,t.objectProperty(t.identifier(`properties`),t.objectExpression(createScopedSlotHostProperties())));return true}if(!t.isObjectExpression(propertiesProp.value))return false;let changed=false;for(const prop of createScopedSlotHostProperties().reverse()){const key=t.isIdentifier(prop.key)?prop.key.name:void 0;if(!key||getObjectPropertyByKey$2(propertiesProp.value,key))continue;propertiesProp.value.properties.unshift(prop);changed=true}return changed}function injectScopedSlotOwnerRequirement(componentOptionsObject){if(hasStaticProperty(componentOptionsObject,WEVU_SCOPED_SLOT_OWNER_REQUIRED_KEY))return false;componentOptionsObject.properties.push(t.objectProperty(t.identifier(WEVU_SCOPED_SLOT_OWNER_REQUIRED_KEY),t.booleanLiteral(true)));return true}function unwrapTypeLikeExpression(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node))return unwrapTypeLikeExpression(node.expression);if(t.isParenthesizedExpression(node))return unwrapTypeLikeExpression(node.expression);return node}function isStructuredRuntimeType(node){return t.isIdentifier(node,{name:`Array`})||t.isIdentifier(node,{name:`Object`})}function shouldRelaxStructuredPropType(node){const normalized=unwrapTypeLikeExpression(node);if(isStructuredRuntimeType(normalized))return true;if(!t.isArrayExpression(normalized)||normalized.elements.length===0)return false;return normalized.elements.every(element=>{if(!element||t.isSpreadElement(element)||!t.isExpression(element))return false;return isStructuredRuntimeType(unwrapTypeLikeExpression(element))})}function relaxStructuredTypeOnlyProps(componentOptionsObject){const propsProp=getObjectPropertyByKey$2(componentOptionsObject,`props`);if(!propsProp||!t.isExpression(propsProp.value))return false;const propsValue=unwrapTypeLikeExpression(propsProp.value);if(!t.isObjectExpression(propsValue))return false;let changed=false;for(const prop of propsValue.properties){if(!t.isObjectProperty(prop)||prop.computed||!t.isExpression(prop.value))continue;const definition=unwrapTypeLikeExpression(prop.value);if(!t.isObjectExpression(definition))continue;const typeProp=getObjectPropertyByKey$2(definition,`type`);if(!typeProp||!t.isExpression(typeProp.value))continue;if(!shouldRelaxStructuredPropType(typeProp.value))continue;typeProp.value=t.nullLiteral();changed=true}return changed}function isObjectAssignCall(node){const callee=node.callee;return t.isMemberExpression(callee)&&t.isIdentifier(callee.object,{name:`Object`})&&t.isIdentifier(callee.property,{name:`assign`})}function resolveObjectExpressionFromProgram(program,name){for(let index=program.body.length-1;index>=0;index-=1){const statement=program.body[index];if(!t.isVariableDeclaration(statement))continue;for(const declarator of statement.declarations){if(!t.isIdentifier(declarator.id,{name})||!declarator.init||!t.isExpression(declarator.init))continue;const normalized=unwrapTypeLikeExpression(declarator.init);if(t.isObjectExpression(normalized))return normalized;if(t.isCallExpression(normalized)&&isObjectAssignCall(normalized)){const lastArg=normalized.arguments[normalized.arguments.length-1];if(lastArg&&!t.isSpreadElement(lastArg)&&t.isExpression(lastArg)){const lastNormalized=unwrapTypeLikeExpression(lastArg);if(t.isObjectExpression(lastNormalized))return lastNormalized}}}}return null}function hasStaticPropertyWithSpreads(target,keyName,program,visited=/* @__PURE__ */ new Set){if(hasStaticProperty(target,keyName))return true;for(const prop of target.properties){if(!t.isSpreadElement(prop))continue;const spreadArg=prop.argument;if(t.isObjectExpression(spreadArg)&&hasStaticPropertyWithSpreads(spreadArg,keyName,program,visited))return true;if(!t.isIdentifier(spreadArg)||visited.has(spreadArg.name))continue;visited.add(spreadArg.name);const resolved=resolveObjectExpressionFromProgram(program,spreadArg.name);if(resolved&&hasStaticPropertyWithSpreads(resolved,keyName,program,visited))return true}return false}function hasStaticPropertyInComponentExpression(componentExpr,keyName,program){const normalized=unwrapTypeLikeExpression(componentExpr);if(t.isObjectExpression(normalized))return hasStaticPropertyWithSpreads(normalized,keyName,program);if(!t.isCallExpression(normalized)||!isObjectAssignCall(normalized))return false;for(const arg of normalized.arguments){if(t.isSpreadElement(arg)||!t.isExpression(arg))continue;const expr=unwrapTypeLikeExpression(arg);if(t.isObjectExpression(expr)&&hasStaticPropertyWithSpreads(expr,keyName,program))return true;if(t.isIdentifier(expr)){const resolved=resolveObjectExpressionFromProgram(program,expr.name);if(resolved&&hasStaticPropertyWithSpreads(resolved,keyName,program,/* @__PURE__ */ new Set([expr.name])))return true}}return false}function rewriteDefaultExport(ast,state,options,enabledPageFeatures,serializedWevuDefaults,parsedWevuDefaults){if(!state.defaultExportPath)return false;const warn=resolveWarnHandler(options?.warn);let transformed=false;const exportPath=state.defaultExportPath;const componentExpr=resolveComponentExpression(exportPath.node.declaration,state.defineComponentDecls,state.defineComponentAliases);const componentOptionsObject=resolveComponentOptionsObject(componentExpr);const hasPageMarker=componentExpr?hasStaticPropertyInComponentExpression(componentExpr,WEVU_IS_PAGE_KEY,ast.program):false;if(componentOptionsObject&&!options?.isApp&&!hasPageMarker){componentOptionsObject.properties.splice(0,0,t.objectProperty(t.identifier(WEVU_IS_PAGE_KEY),t.booleanLiteral(options?.isPage===true)));transformed=true}if(componentOptionsObject&&enabledPageFeatures.size)transformed=injectWevuPageFeatureFlagsIntoOptionsObject(componentOptionsObject,enabledPageFeatures)||transformed;if(componentOptionsObject&&parsedWevuDefaults)transformed=applyWevuDefaultsToComponentOptions({componentExpr,parsedWevuDefaults,options})||transformed;if(componentExpr&&!options?.isApp&&!options?.skipComponentTransform)state.componentStyleOptions=analyzeComponentStyleOptions(componentExpr,exportPath.scope);if(componentOptionsObject)transformed=injectSetupInitialData(componentOptionsObject)||transformed;if(componentOptionsObject&&options?.bindingManifest?.bindings.some(binding=>binding.outputPath===WEVU_SETUP_READY_KEY)){componentOptionsObject.properties.push(t.objectProperty(t.identifier(WEVU_SETUP_READY_KEY),t.booleanLiteral(false)));transformed=true}if(componentOptionsObject&&options?.relaxStructuredTypeOnlyProps)transformed=relaxStructuredTypeOnlyProps(componentOptionsObject)||transformed;if(componentOptionsObject&&options?.runtimeCapabilities?.required.includes(`scopedSlots`))transformed=injectScopedSlotOwnerRequirement(componentOptionsObject)||transformed;if(componentOptionsObject&&options?.scopedSlotHostProperties)transformed=injectScopedSlotHostProperties(componentOptionsObject)||transformed;if(componentOptionsObject&&!options?.isApp&&options?.nativeSlotContext){componentOptionsObject.properties.push(t.objectProperty(t.identifier(WEVU_NATIVE_SLOT_CONTEXT_KEY),t.booleanLiteral(true)));transformed=true}if(componentOptionsObject&&options?.cssModules&&Object.keys(options.cssModules).length)transformed=injectCssModules(componentOptionsObject,options.cssModules)||transformed;if(componentOptionsObject&&options?.stabilizeCssVarsRuntime)transformed=injectStableCssVarsRuntime(ast.program,componentOptionsObject,exportPath.scope)||transformed;if(componentOptionsObject){transformed=injectPropsAliases(componentOptionsObject,options?.propsAliases)||transformed;transformed=injectPropsDerivedKeys(componentOptionsObject,options?.propsDerivedKeys)||transformed}if(componentOptionsObject&&!options?.isApp)transformed=injectBindingManifestContract(componentOptionsObject,{manifest:options?.bindingManifest,autoSetDataPick:options?.autoSetDataPick,pageLayout:options?.pageLayout,runtimeBindingManifest:options?.runtimeBindingManifest})||transformed;const classStyleBindings=options?.classStyleBindings??[];if(classStyleBindings.length){if(componentOptionsObject){ensureClassStyleRuntimeImports(ast.program);transformed=injectClassStyleComputed(componentOptionsObject,classStyleBindings,options?.propsAliases,warn)||transformed}else warn(`无法自动注入 class/style 计算属性:组件选项不是对象字面量。`)}const templateRefs=options?.templateRefs??[];if(templateRefs.length){if(componentOptionsObject)transformed=injectTemplateRefs(componentOptionsObject,templateRefs,warn)||transformed;else warn(`无法自动注入 template ref 元数据:组件选项不是对象字面量。`)}const layoutHosts=options?.layoutHosts??[];if(layoutHosts.length){if(componentOptionsObject)transformed=injectLayoutHosts(componentOptionsObject,layoutHosts,warn)||transformed;else warn(`无法自动注入 layout host 元数据:组件选项不是对象字面量。`)}const inlineExpressions=options?.inlineExpressions??[];if(inlineExpressions.length){if(componentOptionsObject){const injected=injectInlineExpressions(componentOptionsObject,inlineExpressions,ast.program);if(!injected)warn(`无法自动注入内联表达式元数据:methods 不是对象字面量。`);transformed=injected||transformed}else warn(`无法自动注入内联表达式元数据:组件选项不是对象字面量。`)}const functionPropPaths=options?.functionPropPaths??[];if(functionPropPaths.length){if(componentOptionsObject)transformed=injectFunctionPropPaths(componentOptionsObject,functionPropPaths)||transformed;else warn(`无法自动注入函数 prop 元数据:组件选项不是对象字面量。`)}if(componentExpr){if(options?.isApp)transformed=injectWevuDefaultsForApp({astProgram:ast.program,options,serializedWevuDefaults})||transformed;transformed=rewriteComponentExport({ast,exportPath,componentExpr,isAppFile:!!options?.isApp,skipComponentTransform:options?.skipComponentTransform})||transformed}return transformed}function createCapabilityAccumulator(){return{required:/* @__PURE__ */ new Set,conservative:/* @__PURE__ */ new Set}}function addConservativeCapabilities(accumulator,names){for(const name of names){accumulator.required.add(name);accumulator.conservative.add(name)}}function unwrapExpression(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node))return unwrapExpression(node.expression);if(t.isParenthesizedExpression(node))return unwrapExpression(node.expression);return node}function resolveStaticExpression(node,context,visited=/* @__PURE__ */ new Set){const normalized=unwrapExpression(node);if(!t.isIdentifier(normalized)||normalized.name===`undefined`)return{value:normalized,context};const binding=context.scope?.getBinding(normalized.name);if(!binding||!binding.constant||!binding.path.isVariableDeclarator()||!binding.path.parentPath?.isVariableDeclaration()||binding.path.parentPath.node.kind!==`const`||visited.has(binding.path.node))return;if(!(binding.referencePaths.length===1||binding.referencePaths.every(reference=>{return context.safeBindingReferences?.has(reference.node)||reference.parentPath.isExportDefaultDeclaration()&&reference.parentPath.node.declaration===reference.node}))||!binding.path.node.init||!t.isExpression(binding.path.node.init))return;visited.add(binding.path.node);return resolveStaticExpression(binding.path.node.init,{scope:binding.path.scope,safeBindingReferences:context.safeBindingReferences},visited)}function resolveProperty(object,key,context,initial={kind:`absent`}){let state=initial;for(const property of object.properties){if(t.isSpreadElement(property)||property.computed){state={kind:`unknown`};continue}if(!isStaticObjectKeyMatch(property.key,key))continue;if(!t.isObjectProperty(property)||!t.isExpression(property.value)){state={kind:`unknown`};continue}state={kind:`value`,value:property.value,context}}return state}function isStaticPrimitive(node){return t.isBooleanLiteral(node)||t.isNullLiteral(node)||t.isNumericLiteral(node)||t.isStringLiteral(node)||t.isTemplateLiteral(node)&&node.expressions.length===0||t.isIdentifier(node,{name:`undefined`})}function applyResolvedProperty(current,next){return next.kind===`absent`?current:next}function resolveInheritedSetData(expression,context,visited){const result=resolveStaticExpression(expression,context);if(!result)return{kind:`unknown`};const{value:resolved,context:resolvedContext}=result;if(!t.isObjectExpression(resolved))return isStaticPrimitive(resolved)||t.isFunction(resolved)?{kind:`absent`}:{kind:`unknown`};if(visited.has(resolved))return{kind:`absent`};visited.add(resolved);let state={kind:`absent`};const inherited=resolveProperty(resolved,`extends`,resolvedContext);if(inherited.kind===`unknown`)state=inherited;else if(inherited.kind===`value`)state=applyResolvedProperty(state,resolveInheritedSetData(inherited.value,inherited.context,visited));const mixins=resolveProperty(resolved,`mixins`,resolvedContext);if(mixins.kind===`unknown`)state=mixins;else if(mixins.kind===`value`){const resolvedMixins=resolveStaticExpression(mixins.value,mixins.context);if(!resolvedMixins||!t.isArrayExpression(resolvedMixins.value))state={kind:`unknown`};else for(const element of resolvedMixins.value.elements){if(!element||t.isSpreadElement(element)||!t.isExpression(element)){state={kind:`unknown`};continue}state=applyResolvedProperty(state,resolveInheritedSetData(element,resolvedMixins.context,visited))}}state=applyResolvedProperty(state,resolveProperty(resolved,`setData`,resolvedContext));visited.delete(resolved);return state}function analyzeHighFrequencyWarning(state,accumulator){if(state.kind===`unknown`){addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`]);return}if(state.kind===`absent`)return;const resolved=resolveStaticExpression(state.value,state.context);if(!resolved){addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`]);return}const{value,context}=resolved;if(t.isObjectExpression(value)){const enabled=resolveProperty(value,`enabled`,context);if(enabled.kind===`unknown`){addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`]);return}if(enabled.kind===`value`){const resolvedEnabled=resolveStaticExpression(enabled.value,enabled.context);if(!resolvedEnabled){addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`]);return}if(t.isBooleanLiteral(resolvedEnabled.value,{value:false}))return}accumulator.required.add(`setDataHighFrequencyWarning`);return}if(t.isBooleanLiteral(value,{value:true})){accumulator.required.add(`setDataHighFrequencyWarning`);return}if(!isStaticPrimitive(value)&&!t.isArrayExpression(value)&&!t.isFunction(value))addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`])}function analyzeSetData(state,accumulator,defaults){if(state.kind===`unknown`){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}if(state.kind===`absent`){if(defaults)analyzeSetData(defaults,accumulator);return}const defaultValue=defaults?.kind===`value`?resolveStaticExpression(defaults.value,defaults.context):void 0;const defaultObject=defaultValue&&t.isObjectExpression(defaultValue.value)?defaultValue.value:void 0;if(defaultObject&&(t.isIdentifier(state.value)||t.isMemberExpression(state.value))){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}const resolved=resolveStaticExpression(state.value,state.context);if(!resolved){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}const{value,context}=resolved;if(!t.isObjectExpression(value)){if(defaultObject)analyzeSetData({kind:`value`,value:defaultObject,context:defaultValue.context},accumulator);if(!isStaticPrimitive(value)&&!t.isArrayExpression(value)&&!t.isFunction(value))addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}const mergedDefaults=t.isObjectExpression(state.value)?defaultObject:void 0;const strategy=resolveProperty(value,`strategy`,context,mergedDefaults?resolveProperty(mergedDefaults,`strategy`,defaultValue.context):defaults?.kind===`unknown`?defaults:void 0);if(strategy.kind===`unknown`)addConservativeCapabilities(accumulator,[`patchStrategy`]);else if(strategy.kind===`value`){const resolvedStrategy=resolveStaticExpression(strategy.value,strategy.context)?.value;if(t.isStringLiteral(resolvedStrategy,{value:`patch`})||t.isTemplateLiteral(resolvedStrategy)&&resolvedStrategy.expressions.length===0&&resolvedStrategy.quasis[0]?.value.cooked===`patch`)accumulator.required.add(`patchStrategy`);else if(!resolvedStrategy||!isStaticPrimitive(resolvedStrategy)&&!t.isArrayExpression(resolvedStrategy)&&!t.isFunction(resolvedStrategy))addConservativeCapabilities(accumulator,[`patchStrategy`])}analyzeHighFrequencyWarning(resolveProperty(value,`highFrequencyWarning`,context,mergedDefaults?resolveProperty(mergedDefaults,`highFrequencyWarning`,defaultValue.context):defaults?.kind===`unknown`?defaults:void 0),accumulator)}function analyzeRuntimeFactoryOptions(expression,context,accumulator,defaults){const defaultSetDataNode=Boolean(defaults&&Object.prototype.hasOwnProperty.call(defaults,`setData`))?t.valueToNode(defaults?.setData):void 0;const defaultSetData=defaultSetDataNode&&t.isExpression(defaultSetDataNode)?{kind:`value`,value:defaultSetDataNode,context:{}}:void 0;if(!expression){if(defaultSetData)analyzeSetData(defaultSetData,accumulator);return}const resolved=resolveStaticExpression(expression,context);if(!resolved){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}if(!t.isObjectExpression(resolved.value)){if(!isStaticPrimitive(resolved.value)&&!t.isArrayExpression(resolved.value)&&!t.isFunction(resolved.value))addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}analyzeSetData(resolveInheritedSetData(resolved.value,resolved.context,/* @__PURE__ */ new Set),accumulator,defaultSetData)}function analyzeRuntimeDefaults(expression,context,accumulator){if(!expression)return;const resolved=resolveStaticExpression(expression,context);if(!resolved||!t.isObjectExpression(resolved.value)){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}for(const key of[`app`,`component`]){const branch=resolveProperty(resolved.value,key,resolved.context);if(branch.kind===`unknown`)addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);else if(branch.kind===`value`)analyzeRuntimeFactoryOptions(branch.value,branch.context,accumulator)}}function finishRuntimeCapabilityAnalysis(accumulator){return createWevuRuntimeCapabilityMetadata(accumulator.required,accumulator.conservative)}const INSTALLER_LOCAL_NAMES={patchStrategy:`__wevuInstallPatchStrategy`,templateRefs:`__wevuInstallTemplateRefs`,inlineEvents:`__wevuInstallInlineEvents`,setDataHighFrequencyWarning:`__wevuInstallSetDataHighFrequencyWarning`,scopedSlots:`__wevuInstallScopedSlots`,layout:`__wevuInstallLayout`,jsxIslands:`__wevuInstallJsxIslands`};const CAPABILITY_BY_INSTALLER=Object.fromEntries(WE_VU_RUNTIME_CAPABILITY_ORDER.map(name=>[WE_VU_RUNTIME_CAPABILITY_INSTALLERS[name],name]));function resolveInstallerCallCapability(statement,importedLocals,namespaceLocals){if(!t.isExpressionStatement(statement)||!t.isCallExpression(statement.expression)||statement.expression.arguments.length)return;const callee=statement.expression.callee;if(t.isIdentifier(callee))return WE_VU_RUNTIME_CAPABILITY_ORDER.find(name=>importedLocals[name]?.includes(callee.name));if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&namespaceLocals.has(callee.object.name)&&t.isIdentifier(callee.property))return CAPABILITY_BY_INSTALLER[callee.property.name]}function findLeadingImportEnd(program){let index=0;while(index<program.body.length&&t.isImportDeclaration(program.body[index]))index+=1;return index}function injectWevuRuntimeCapabilityInstallers(program,metadata){if(!metadata?.required.length)return false;const importedLocals={};const namespaceLocals=/* @__PURE__ */ new Set;for(const statement of program.body){if(!t.isImportDeclaration(statement)||statement.importKind===`type`||!isWevuRuntimeModuleId(statement.source.value))continue;for(const specifier of statement.specifiers)if(t.isImportNamespaceSpecifier(specifier))namespaceLocals.add(specifier.local.name);else if(t.isImportSpecifier(specifier)&&specifier.importKind!==`type`&&t.isIdentifier(specifier.imported)){const capability=CAPABILITY_BY_INSTALLER[specifier.imported.name];if(capability){const locals=importedLocals[capability]??[];locals.push(specifier.local.name);importedLocals[capability]=locals}}}const existingCalls={};let prefixIndex=findLeadingImportEnd(program);let previousCapabilityIndex=-1;while(prefixIndex<program.body.length){const statement=program.body[prefixIndex];const capability=resolveInstallerCallCapability(statement,importedLocals,namespaceLocals);if(!capability)break;const capabilityIndex=WE_VU_RUNTIME_CAPABILITY_ORDER.indexOf(capability);if(capabilityIndex<previousCapabilityIndex)break;if(!existingCalls[capability])existingCalls[capability]=statement;previousCapabilityIndex=capabilityIndex;prefixIndex+=1}const usedNames=new Set(Object.keys(t.getBindingIdentifiers(program)));const localByCapability={};for(const capability of metadata.required){if(existingCalls[capability])continue;const existingLocal=importedLocals[capability]?.[0];if(existingLocal){localByCapability[capability]=existingLocal;continue}const baseName=INSTALLER_LOCAL_NAMES[capability];let localName=baseName;let suffix=2;while(usedNames.has(localName)){localName=`${baseName}${suffix}`;suffix+=1}usedNames.add(localName);localByCapability[capability]=localName;ensureRuntimeImport(program,WE_VU_RUNTIME_CAPABILITY_INSTALLERS[capability],localName)}let insertIndex=findLeadingImportEnd(program);const requiredCapabilities=new Set(metadata.required);let changed=false;for(const capability of WE_VU_RUNTIME_CAPABILITY_ORDER){const existingCall=existingCalls[capability];if(existingCall){const existingIndex=program.body.indexOf(existingCall);if(existingIndex>=insertIndex)insertIndex=existingIndex+1;continue}if(!requiredCapabilities.has(capability))continue;const localName=localByCapability[capability];program.body.splice(insertIndex,0,t.expressionStatement(t.callExpression(t.identifier(localName),[])));insertIndex+=1;changed=true}return changed}const OPTION_FACTORY_APIS={createApp:true,createWevuComponent:true,defineComponent:true};function addScopedSlotCreatorCapabilities(accumulator){accumulator.required.add(`scopedSlots`);addConservativeCapabilities(accumulator,[`templateRefs`,`inlineEvents`,`layout`])}function analyzeWevuRuntimeCalls(ast){const namedBindings=/* @__PURE__ */ new Map;const namespaceSpecifiers=[];for(const statement of ast.program.body){if(!t.isImportDeclaration(statement)||statement.importKind===`type`||!isWevuRuntimeModuleId(statement.source.value))continue;for(const specifier of statement.specifiers){if(t.isImportNamespaceSpecifier(specifier)||t.isImportDefaultSpecifier(specifier)){namespaceSpecifiers.push(specifier);continue}if(!t.isImportSpecifier(specifier)||specifier.importKind===`type`||!t.isIdentifier(specifier.imported))continue;const importedName=specifier.imported.name;if(importedName===`createWevuScopedSlotComponent`||importedName===`setWevuDefaults`||Object.prototype.hasOwnProperty.call(OPTION_FACTORY_APIS,importedName))namedBindings.set(specifier.local.name,{api:importedName,specifier})}}if(!namedBindings.size&&!namespaceSpecifiers.length)return;const handledCallees=/* @__PURE__ */ new Set;const safeBindingReferences=/* @__PURE__ */ new Set;const accumulator=createCapabilityAccumulator();const calls=[];let programScope;traverse(ast,{Program(path){programScope=path.scope},CallExpression(path){if(!t.isIdentifier(path.node.callee))return;const runtimeBinding=namedBindings.get(path.node.callee.name);const binding=path.scope.getBinding(path.node.callee.name);if(!runtimeBinding||binding?.path.node!==runtimeBinding.specifier)return;handledCallees.add(path.node.callee);const firstArgument=path.node.arguments[0];const argument=firstArgument&&!t.isSpreadElement(firstArgument)&&t.isExpression(firstArgument)?firstArgument:void 0;if(t.isIdentifier(argument))safeBindingReferences.add(argument);calls.push({api:runtimeBinding.api,argument,argumentUnknown:Boolean(firstArgument&&(t.isSpreadElement(firstArgument)||!t.isExpression(firstArgument))),scope:path.scope})}});for(const{api,argument,argumentUnknown,scope}of calls){const context={scope,safeBindingReferences};if(api===`createWevuScopedSlotComponent`)addScopedSlotCreatorCapabilities(accumulator);else if(argumentUnknown)addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);else if(api===`setWevuDefaults`)analyzeRuntimeDefaults(argument,context,accumulator);else analyzeRuntimeFactoryOptions(argument,context,accumulator)}for(const{api,specifier}of namedBindings.values()){if(!(programScope?.getBinding(specifier.local.name))?.referencePaths.some(reference=>!handledCallees.has(reference.node)))continue;if(api===`createWevuScopedSlotComponent`)addScopedSlotCreatorCapabilities(accumulator);else addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`])}for(const specifier of namespaceSpecifiers){const binding=programScope?.getBinding(specifier.local.name);if(!binding?.referenced)continue;addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);if(binding.referencePaths.some(reference=>{const parent=reference.parentPath;if(!parent.isMemberExpression()||parent.node.object!==reference.node||parent.node.computed||!t.isIdentifier(parent.node.property))return true;return parent.node.property.name===WE_VU_RUNTIME_APIS.createWevuScopedSlotComponent}))addScopedSlotCreatorCapabilities(accumulator)}return finishRuntimeCapabilityAnalysis(accumulator)}function analyzeWevuComponentOptions(params){if(!params.expression)return;const accumulator=createCapabilityAccumulator();analyzeRuntimeFactoryOptions(params.expression,{scope:params.scope},accumulator,params.defaults);return finishRuntimeCapabilityAnalysis(accumulator)}function analyzeWevuDefaults(defaults){if(!defaults)return;const node=t.valueToNode(defaults);if(!t.isExpression(node))return;const accumulator=createCapabilityAccumulator();analyzeRuntimeDefaults(node,{},accumulator);return finishRuntimeCapabilityAnalysis(accumulator)}function runVisitor(visitor,path){if(typeof visitor===`function`)visitor(path)}function transformScript(source,options){const fastResult=tryFastTransformCompiledScriptSetup(source,options);if(fastResult)return fastResult;const ast=parse$3(source,BABEL_TS_MODULE_PARSER_OPTIONS);const sourceRuntimeCapabilities=analyzeWevuRuntimeCalls(ast);const warn=resolveWarnHandler(options?.warn);const state={transformed:false,defineComponentAliases:/* @__PURE__ */ new Set([WE_VU_RUNTIME_APIS.defineComponent,`_defineComponent`]),defineComponentDecls:/* @__PURE__ */ new Map,useSlotsAliases:/* @__PURE__ */ new Set,usesSlots:false,defaultExportPath:null};const enabledPageFeatures=options?.isPage?collectWevuPageFeatureFlags(ast):/* @__PURE__ */ new Set;const serializedWevuDefaults=options?.wevuDefaults&&Object.keys(options.wevuDefaults).length>0?serializeWevuDefaults(options.wevuDefaults,warn):void 0;const parsedWevuDefaults=serializedWevuDefaults?JSON.parse(serializedWevuDefaults):void 0;const vueSfcVisitors=vueSfcTransformPlugin().visitor;const macroVisitors=createMacroVisitors(ast,state);const importVisitors=createImportVisitors(ast.program,state);const collectVisitors=createCollectVisitors(state);const visitor={...vueSfcVisitors,...macroVisitors,...importVisitors,...collectVisitors,ImportDeclaration(path){runVisitor(macroVisitors.ImportDeclaration,path);if(path.removed)return;const source=path.node.source.value;const canProvideUseSlots=source===`vue`||isWevuRuntimeModuleId(source);for(const specifier of path.node.specifiers){if(canProvideUseSlots&&specifier.type===`ImportSpecifier`&&specifier.importKind!==`type`&&(specifier.imported.type===`Identifier`&&specifier.imported.name===WE_VU_RUNTIME_APIS.defineComponent||specifier.imported.type===`StringLiteral`&&specifier.imported.value===WE_VU_RUNTIME_APIS.defineComponent))state.defineComponentAliases.add(specifier.local.name);if(canProvideUseSlots&&specifier.type===`ImportSpecifier`&&(specifier.imported.type===`Identifier`&&specifier.imported.name===`useSlots`||specifier.imported.type===`StringLiteral`&&specifier.imported.value===`useSlots`))state.useSlotsAliases.add(specifier.local.name)}runVisitor(vueSfcVisitors.ImportDeclaration,path);if(!path.removed)runVisitor(importVisitors.ImportDeclaration,path)},CallExpression(path){if(path.node.callee.type===`Identifier`&&state.useSlotsAliases.has(path.node.callee.name))state.usesSlots=true;runVisitor(vueSfcVisitors.CallExpression,path);if(!path.removed)runVisitor(macroVisitors.CallExpression,path)}};traverse(ast,visitor);const templateRuntimeCapabilities=createWevuRuntimeCapabilityMetadata([...options?.templateRefs?.length||options?.layoutHosts?.length?[`templateRefs`]:[],...options?.inlineExpressions?.length?[`inlineEvents`]:[],...options?.layoutHosts?.length?[`layout`]:[]]);const componentExpression=state.defaultExportPath?resolveComponentExpression(state.defaultExportPath.node.declaration,state.defineComponentDecls,state.defineComponentAliases):null;const defaultDeclaration=state.defaultExportPath?.node.declaration;let componentCapabilityExpression=componentExpression;if(t.isIdentifier(defaultDeclaration))componentCapabilityExpression=defaultDeclaration;else if(t.isCallExpression(defaultDeclaration)&&t.isIdentifier(defaultDeclaration.callee)&&state.defineComponentAliases.has(defaultDeclaration.callee.name)){const firstArgument=defaultDeclaration.arguments[0];if(firstArgument&&!t.isSpreadElement(firstArgument)&&t.isExpression(firstArgument))componentCapabilityExpression=firstArgument}const defaultsBranch=options?.isApp?parsedWevuDefaults?.app:parsedWevuDefaults?.component;const componentRuntimeCapabilities=componentCapabilityExpression?analyzeWevuComponentOptions({expression:componentCapabilityExpression,scope:state.defaultExportPath?.scope,defaults:defaultsBranch}):void 0;const defaultsRuntimeCapabilities=options?.isApp?analyzeWevuDefaults(parsedWevuDefaults):void 0;const runtimeCapabilities=mergeWevuRuntimeCapabilityMetadata(options?.runtimeCapabilities,templateRuntimeCapabilities,sourceRuntimeCapabilities,componentRuntimeCapabilities,defaultsRuntimeCapabilities);if(options?.templateComponentMeta)state.transformed=pruneTemplateComponentMeta(ast,options.templateComponentMeta)||state.transformed;const rewriteOptions=state.usesSlots&&!options?.scopedSlotHostProperties?{...options,scopedSlotHostProperties:true}:options;state.transformed=rewriteDefaultExport(ast,state,rewriteOptions,enabledPageFeatures,serializedWevuDefaults,parsedWevuDefaults)||state.transformed;state.transformed=injectWevuRuntimeCapabilityInstallers(ast.program,runtimeCapabilities)||state.transformed;if(!state.transformed)return{code:source,transformed:false,...runtimeCapabilities?{runtimeCapabilities}:{},...state.componentStyleOptions?{componentStyleOptions:state.componentStyleOptions}:{}};const sourceMap=options?.sourceMap!==false;const generated=generate(ast,{compact:options?.minify===true,minified:options?.minify===true,retainLines:options?.minify!==true,sourceMaps:sourceMap,sourceFileName:`inline.ts`},source);return{code:generated.code,map:sourceMap?generated.map:null,transformed:state.transformed,...runtimeCapabilities?{runtimeCapabilities}:{},...state.componentStyleOptions?{componentStyleOptions:state.componentStyleOptions}:{}}}function addJsxDiagnostic(context,node,code,message,severity=`warning`){context.warningDiagnostics.set(context.warnings.length,{code,severity,message,filename:node.loc?.filename??context.filename??``,source:`jsx`,loc:node.loc&&node.start!=null&&node.end!=null?{start:{offset:node.start,line:node.loc.start.line,column:node.loc.start.column+1},end:{offset:node.end,line:node.loc.end.line,column:node.loc.end.column+1}}:void 0});context.warnings.push(message)}function createJsxDiagnostics(warnings,filename,metadata){return warnings.map((warning,index)=>{const message=warning.startsWith(`[JSX 编译]`)?warning:`[JSX 编译] ${warning}`;return{code:`WV1003`,severity:`warning`,filename,source:`jsx`,...metadata?.get(index),message}})}function reportJsxDiagnostics(diagnostics,warn){for(const diagnostic of diagnostics??[]){warn?.(diagnostic.message);if(diagnostic.severity===`error`)throw new CompilerDiagnosticError(diagnostic)}}const WXML_EXPRESSION_GENERATE_OPTIONS={compact:true,jsescOption:{quotes:`single`,minimal:true}};const escapeText=escapeWxmlText;const escapeAttr=escapeWxmlAttribute;const WHITESPACE_RE=/\s+/g;function normalizeJsxText(value){return value.replace(WHITESPACE_RE,` `)}function printExpression$1(exp){const normalized=t.cloneNode(exp,true);t.traverseFast(normalized,node=>{if(t.isStringLiteral(node))node.extra=void 0});return generate(normalized,WXML_EXPRESSION_GENERATE_OPTIONS).code}function unwrapTsExpression(exp){return unwrapTypeScriptExpression(exp)}function normalizeInterpolationExpression(exp,context){const cached=context?.interpolationCache.get(exp);if(cached!=null)return cached;let source=printExpression$1(unwrapTsExpression(exp));if(context?.setupRefBindings?.size){const expression=t.cloneNode(unwrapTsExpression(exp),true);const file=t.file(t.program([t.expressionStatement(expression)]));traverse(file,{"MemberExpression|OptionalMemberExpression":{enter(path){const member=path.node;if(!t.isMemberExpression(member)&&!t.isOptionalMemberExpression(member))return;const object=t.isExpression(member.object)?unwrapTsExpression(member.object):member.object;if(!t.isIdentifier(object)||!context.setupRefBindings?.has(object.name)||context.scopeStack.includes(object.name)||path.scope.hasBinding(object.name))return;if(member.loc?.filename&&context.filename&&member.loc.filename!==context.filename)return;if(member.computed?t.isStringLiteral(member.property,{value:`value`}):t.isIdentifier(member.property,{name:`value`}))path.replaceWith(t.cloneNode(object))}}});const statement=file.program.body[0];source=printExpression$1(statement.expression)}let normalized=normalizeWxmlExpression(source);if(context&&shouldFallbackToRuntimeBinding(source)){const name=`__wv_bind_${context.classStyleBindings.filter(item=>item.type===`bind`).length}`;context.classStyleBindings.push({name,type:`bind`,exp:source,forStack:context.forStack.map(info=>({...info}))});normalized=`${name}${context.forStack.map(info=>`[${info.index??`index`}]`).join(``)}`}context?.interpolationCache.set(exp,normalized);return normalized}function renderMustache(expression,context){return context.mustacheInterpolation===`spaced`?`{{ ${expression} }}`:`{{${expression}}}`}function pushScope(context,names,sourceExpression){const scopedNames=names.filter(Boolean);const sourceLocals=[...context.scopeStack];context.scopeStack.push(...scopedNames);if(scopedNames.length)context.bindingScopeStack.push({locals:scopedNames,sourceExpression,sourceLocals})}function popScope(context,count){for(let i=0;i<count;i+=1)context.scopeStack.pop();if(count>0)context.bindingScopeStack.pop()}function analyzeInlineExpression(exp,context){const localSet=new Set(context.scopeStack);const used=[];const usedSet=/* @__PURE__ */ new Set;const identifierNames=/* @__PURE__ */ new Set;const normalizedExpression=t.cloneNode(exp,true);const file=t.file(t.program([t.expressionStatement(normalizedExpression)]));let programScope;traverse(file,{Program(path){programScope=path.scope},Identifier(path){const name=path.node.name;identifierNames.add(name);if(!localSet.has(name)||!path.isReferencedIdentifier()||path.scope.hasBinding(name)||usedSet.has(name))return;usedSet.add(name);used.push(name)},StringLiteral(path){path.node.extra=void 0}});if(!programScope)throw new Error(`无法为 JSX 内联表达式创建程序作用域。`);return{parameterIdentifiers:createInlineExpressionParameterIdentifiers(programScope,identifierNames),normalizedExpression,scopeKeys:used}}function registerInlineExpression(exp,context){const{normalizedExpression,parameterIdentifiers,scopeKeys}=analyzeInlineExpression(exp,context);const id=createInlineExpressionId(context.inlineExpressionSeed++);context.inlineExpressions.push({id,expression:generate(normalizedExpression,WXML_EXPRESSION_GENERATE_OPTIONS).code,scopeKeys,parameterNames:{context:parameterIdentifiers.context.name,scope:parameterIdentifiers.scope.name,event:parameterIdentifiers.event.name}});return{id,scopeKeys}}function toJsxTagName(name,context){if(t.isJSXIdentifier(name))return name.name;if(t.isJSXNamespacedName(name))return`${name.namespace.name}:${name.name.name}`;context.warnings.push(`JSX 成员标签(如 <Foo.Bar />)无法映射为小程序 WXML 组件标签,已生成 dynamic island。`);return`block`}const REF_FACTORIES=/* @__PURE__ */ new Set([`ref`,`shallowRef`,`computed`,`customRef`,`toRef`,`useModel`,`useTemplateRef`]);const REF_OBJECT_FACTORIES=/* @__PURE__ */ new Set([`toRefs`,`storeToRefs`]);function resolveSetupFunction(component){const setup=getObjectPropertyByKey(component,`setup`);if(t.isObjectMethod(setup))return setup;if(t.isObjectProperty(setup)&&(t.isFunctionExpression(setup.value)||t.isArrowFunctionExpression(setup.value)))return setup.value}function collectSetupRefBindings(component,context){const setup=resolveSetupFunction(component);const refs=/* @__PURE__ */ new Set;if(!setup||!t.isBlockStatement(setup.body))return refs;const declarations=setup.body.body.flatMap(statement=>t.isVariableDeclaration(statement)?statement.declarations:[]);const stableDeclarations=new Set(setup.body.body.flatMap(statement=>t.isVariableDeclaration(statement)&&statement.kind===`const`?statement.declarations:[]));const locals=new Set(declarations.flatMap(declaration=>Object.keys(t.getBindingIdentifiers(declaration.id))));for(const statement of setup.body.body)if(t.isFunctionDeclaration(statement)&&statement.id)locals.add(statement.id.name);for(const parameter of setup.params)Object.keys(t.getBindingIdentifiers(parameter)).forEach(name=>locals.add(name));function importedApi(expression){if(t.isIdentifier(expression)&&!locals.has(expression.name)){const imported=context.importedBindings?.get(expression.name);return imported&&[`wevu`,`vue`].includes(imported.source)?imported.importedName:void 0}if(t.isMemberExpression(expression)&&!expression.computed&&t.isIdentifier(expression.object)&&t.isIdentifier(expression.property)&&!locals.has(expression.object.name)){const imported=context.importedBindings?.get(expression.object.name);return imported?.importedName===`*`&&[`wevu`,`vue`].includes(imported.source)?expression.property.name:void 0}}function isRef(expression){const value=unwrapTypeScriptExpression(expression);if(t.isIdentifier(value))return refs.has(value.name);if(!t.isCallExpression(value)||!t.isExpression(value.callee))return false;const api=importedApi(value.callee);if(api&&REF_FACTORIES.has(api))return true;const first=value.arguments[0];return(api===`readonly`||api===`shallowReadonly`)&&t.isExpression(first)&&isRef(first)}for(const declaration of declarations){if(!declaration.init||!stableDeclarations.has(declaration))continue;if(t.isIdentifier(declaration.id)&&isRef(declaration.init))refs.add(declaration.id.name);else if(t.isObjectPattern(declaration.id)&&t.isCallExpression(declaration.init)&&t.isExpression(declaration.init.callee)){const api=importedApi(declaration.init.callee);if(api&&REF_OBJECT_FACTORIES.has(api)){for(const property of declaration.id.properties)if(t.isObjectProperty(property)&&t.isIdentifier(property.value))refs.add(property.value.name)}}}return refs}function parseIslandExpression(expression){const statement=parse$3(`const __wevuIsland = (${expression})`,BABEL_TS_MODULE_PARSER_OPTIONS).program.body[0];if(!t.isVariableDeclaration(statement))return;const init=statement.declarations[0]?.init;return init&&t.isExpression(init)?init:void 0}function injectIslandComputed(optionsObject,islands){const entries=islands.flatMap(island=>{const expression=parseIslandExpression(island.expression);if(!expression)return[];const normalized=t.callExpression(t.memberExpression(t.identifier(`__wevuNormalizeJsxIsland`),t.identifier(`call`)),[t.thisExpression(),expression,t.stringLiteral(island.id),t.objectExpression([t.objectProperty(t.identifier(`normalizeClass`),t.identifier(`__wevuNormalizeClass`)),t.objectProperty(t.identifier(`normalizeStyle`),t.identifier(`__wevuNormalizeStyle`))])]);return[t.objectProperty(t.stringLiteral(island.id),normalized)]});if(!entries.length)return false;const islandGetter=t.objectMethod(`method`,t.identifier(WEVU_JSX_ISLAND_DATA_KEY),[],t.blockStatement([t.returnStatement(t.objectExpression(entries))]));const computed=optionsObject.properties.find(property=>(t.isObjectProperty(property)||t.isObjectMethod(property))&&toStaticObjectKey(property.key)===`computed`);if(computed&&t.isObjectProperty(computed)&&t.isObjectExpression(computed.value))computed.value.properties.push(islandGetter);else optionsObject.properties.unshift(t.objectProperty(t.identifier(`computed`),t.objectExpression([islandGetter])));return true}function injectDynamicIslandRuntime(source,islands){if(!islands?.length)return source;const ast=parse$3(source,BABEL_TS_MODULE_PARSER_OPTIONS);const defineComponentAliases=/* @__PURE__ */ new Set([`defineComponent`,`_defineComponent`]);const declarations=/* @__PURE__ */ new Map;let injected=false;traverse(ast,{ImportDeclaration(path){if(path.node.source.value!==`wevu`&&path.node.source.value!==`vue`)return;for(const specifier of path.node.specifiers)if(t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.imported,{name:`defineComponent`}))defineComponentAliases.add(specifier.local.name)},VariableDeclarator(path){if(!t.isIdentifier(path.node.id)||!path.node.init)return;if(t.isObjectExpression(path.node.init))declarations.set(path.node.id.name,path.node.init);if(t.isCallExpression(path.node.init)&&t.isIdentifier(path.node.init.callee)&&defineComponentAliases.has(path.node.init.callee.name)){const first=path.node.init.arguments[0];if(t.isObjectExpression(first))declarations.set(path.node.id.name,first)}},ExportDefaultDeclaration(path){const declaration=path.node.declaration;let optionsObject;if(t.isObjectExpression(declaration))optionsObject=declaration;else if(t.isCallExpression(declaration)&&t.isIdentifier(declaration.callee)&&defineComponentAliases.has(declaration.callee.name)){const first=declaration.arguments[0];if(t.isObjectExpression(first))optionsObject=first}else if(t.isIdentifier(declaration))optionsObject=declarations.get(declaration.name);if(optionsObject)injected=injectIslandComputed(optionsObject,islands)||injected}});if(!injected)return source;ensureRuntimeImport(ast.program,`normalizeJsxIsland`,`__wevuNormalizeJsxIsland`);ensureRuntimeImport(ast.program,`normalizeClass`,`__wevuNormalizeClass`);ensureRuntimeImport(ast.program,`normalizeStyle`,`__wevuNormalizeStyle`);return generate(ast).code}function removeRenderOptionFromObjectExpression(node){const nextProps=node.properties.filter(prop=>{if(t.isObjectMethod(prop))return toStaticObjectKey(prop.key)!==`render`;if(t.isObjectProperty(prop)&&!prop.computed)return toStaticObjectKey(prop.key)!==`render`;return true});const removed=nextProps.length!==node.properties.length;if(removed)node.properties=nextProps;return removed}function resolveReturnedJsxClosureExpression(expression){if(!t.isArrowFunctionExpression(expression)&&!t.isFunctionExpression(expression))return;if(t.isJSXElement(expression.body)||t.isJSXFragment(expression.body))return expression.body;if(!t.isBlockStatement(expression.body))return;const returned=expression.body.body.find(statement=>t.isReturnStatement(statement)&&statement.argument);if(!returned||!t.isReturnStatement(returned))return;return returned.argument&&(t.isJSXElement(returned.argument)||t.isJSXFragment(returned.argument))?returned.argument:void 0}function rewriteSetupRenderClosure(node){const setup=resolveSetupFunction(node);if(!setup||!t.isBlockStatement(setup.body))return false;const localNames=/* @__PURE__ */ new Set;for(const param of setup.params)Object.keys(t.getBindingIdentifiers(param)).forEach(name=>localNames.add(name));for(const statement of setup.body.body)if(t.isVariableDeclaration(statement))for(const declaration of statement.declarations)Object.keys(t.getBindingIdentifiers(declaration.id)).forEach(name=>localNames.add(name));else if(t.isFunctionDeclaration(statement)&&statement.id)localNames.add(statement.id.name);for(const statement of setup.body.body){if(!t.isReturnStatement(statement)||!statement.argument||!t.isExpression(statement.argument))continue;const jsx=resolveReturnedJsxClosureExpression(statement.argument);if(!jsx)continue;const captures=/* @__PURE__ */ new Set;const file=t.file(t.program([t.expressionStatement(t.cloneNode(jsx,true))]));traverse(file,{ReferencedIdentifier(path){if(localNames.has(path.node.name))captures.add(path.node.name)}});statement.argument=t.objectExpression([...captures].map(name=>t.objectProperty(t.identifier(name),t.identifier(name),false,true)));return true}return false}function stripRenderOptionFromScript(source,filename,warnings){let ast;try{ast=parse$3(source,BABEL_TS_MODULE_PARSER_OPTIONS)}catch{return source}const defineComponentAliases=/* @__PURE__ */ new Set([`defineComponent`,`_defineComponent`]);const defineComponentDecls=/* @__PURE__ */ new Map;let hasDefaultExport=false;let removedRender=false;let removedJsonMacroImport=false;traverse(ast,{ImportDeclaration(path){const importSource=path.node.source.value;if(importSource===`wevu`||importSource===`vue`)for(const specifier of path.node.specifiers){if(!t.isImportSpecifier(specifier))continue;if(!t.isIdentifier(specifier.imported,{name:`defineComponent`}))continue;defineComponentAliases.add(specifier.local.name)}if(importSource!==`weapp-vite`)return;const retained=path.node.specifiers.filter(specifier=>{if(!t.isImportSpecifier(specifier))return true;const importedName=t.isIdentifier(specifier.imported)?specifier.imported.name:t.isStringLiteral(specifier.imported)?specifier.imported.value:``;return!JSON_MACROS.has(importedName)});if(retained.length===path.node.specifiers.length)return;removedJsonMacroImport=true;if(retained.length===0)path.remove();else path.node.specifiers=retained},VariableDeclarator(path){if(!t.isIdentifier(path.node.id)||!path.node.init)return;if(t.isObjectExpression(path.node.init)){defineComponentDecls.set(path.node.id.name,path.node.init);return}if(!t.isCallExpression(path.node.init))return;const callee=path.node.init.callee;if(!t.isIdentifier(callee)||!defineComponentAliases.has(callee.name))return;const first=path.node.init.arguments[0];if(t.isObjectExpression(first))defineComponentDecls.set(path.node.id.name,first)},ExportDefaultDeclaration(path){hasDefaultExport=true;const declaration=path.node.declaration;if(t.isDeclaration(declaration))return;if(t.isObjectExpression(declaration)){removedRender=removeRenderOptionFromObjectExpression(declaration)||rewriteSetupRenderClosure(declaration)||removedRender;return}if(t.isCallExpression(declaration)){const callee=declaration.callee;if(!t.isIdentifier(callee)||!defineComponentAliases.has(callee.name))return;const first=declaration.arguments[0];if(t.isObjectExpression(first))removedRender=removeRenderOptionFromObjectExpression(first)||rewriteSetupRenderClosure(first)||removedRender;return}if(t.isIdentifier(declaration)){const target=defineComponentDecls.get(declaration.name);if(target)removedRender=removeRenderOptionFromObjectExpression(target)||rewriteSetupRenderClosure(target)||removedRender}}});if(hasDefaultExport&&!removedRender)warnings?.push(`[JSX 编译] 未在 ${filename} 中移除 render 选项,输出脚本可能包含 JSX。`);if(!removedRender&&!removedJsonMacroImport)return source;return generate(ast).code}function resolveRenderExpression(componentExpr,context){if(!t.isObjectExpression(componentExpr)){context.warnings.push(`JSX 编译仅支持对象字面量组件选项。`);return null}const renderExpression=resolveRenderExpressionFromComponentOptions(componentExpr);if(renderExpression)return renderExpression;if(getRenderPropertyFromComponentOptions(componentExpr)){context.warnings.push(`render 不是可执行函数。`);return null}const setup=resolveSetupFunction(componentExpr);if(setup){const body=setup.body;if(t.isBlockStatement(body))for(const statement of body.body){if(!t.isReturnStatement(statement)||!statement.argument)continue;if(t.isArrowFunctionExpression(statement.argument)||t.isFunctionExpression(statement.argument)){context.setupRefBindings=collectSetupRefBindings(componentExpr,context);const renderBody=statement.argument.body;if(t.isExpression(renderBody))return renderBody;const returned=renderBody.body.find(item=>t.isReturnStatement(item)&&item.argument);if(returned&&t.isReturnStatement(returned)&&returned.argument)return returned.argument}}}context.warnings.push(`未找到 render() 或 setup() 返回的 render closure。`);return null}function isCollectableJsxTemplateTag(tag){if(!tag)return false;if(RESERVED_VUE_COMPONENT_TAGS.has(tag))return false;return!isBuiltinComponent(tag)}function analyzeJsxAst(ast,context){const{importedComponents,exportDefaultExpression}=collectJsxImportedComponentsAndDefaultExportFromBabelAst(ast,{isDefineComponentSource(source){return source===`wevu`||source===`vue`},resolveBabelComponentExpression:resolveComponentExpression});let renderExpression=null;let templateTags=/* @__PURE__ */ new Set;if(exportDefaultExpression){renderExpression=resolveRenderExpression(exportDefaultExpression,context);if(renderExpression)templateTags=collectJsxTemplateTagsFromBabelExpression(renderExpression,isCollectableJsxTemplateTag)}return{renderExpression,autoComponentContext:{templateTags,importedComponents}}}const EXTENSIONS=[``,`.tsx`,`.jsx`,`.ts`,`.js`];function isMissingFile(error){return Boolean(error&&typeof error===`object`&&`code`in error&&[`ENOENT`,`ENOTDIR`,`EISDIR`].includes(String(error.code)))}function resolveFile(source,importer,readSource){if(!source.startsWith(`.`))return;const base=path$1.resolve(path$1.dirname(importer),source);for(const extension of EXTENSIONS){const candidate=`${base}${extension}`;try{if(readSource(candidate)!==void 0)return candidate}catch(error){if(!isMissingFile(error))throw error}}for(const extension of EXTENSIONS){const candidate=path$1.join(base,`index${extension}`);try{if(readSource(candidate)!==void 0)return candidate}catch(error){if(!isMissingFile(error))throw error}}}function expressionFromDeclaration(node){if(!node)return;if(t.isJSXElement(node)||t.isJSXFragment(node))return{expression:node,params:[]};if(t.isArrowFunctionExpression(node)||t.isFunctionExpression(node)){let body;if(t.isBlockStatement(node.body)){const returned=node.body.body.find(statement=>t.isReturnStatement(statement)&&!!statement.argument);if(returned&&t.isReturnStatement(returned)&&returned.argument&&t.isExpression(returned.argument))body=returned.argument}else body=node.body;if(body)return{expression:body,params:node.params.filter(t.isIdentifier).map(param=>param.name)}}if(t.isFunctionDeclaration(node)){const body=node.body.body.find(statement=>t.isReturnStatement(statement)&&!!statement.argument);if(body&&t.isReturnStatement(body)&&body.argument&&t.isExpression(body.argument))return{expression:body.argument,params:node.params.filter(t.isIdentifier).map(param=>param.name)}}}function collectExports(ast){const locals=/* @__PURE__ */ new Map;const exports=/* @__PURE__ */ new Map;const reexports=/* @__PURE__ */ new Map;for(const statement of ast.program.body){if(t.isVariableDeclaration(statement)){for(const declaration of statement.declarations)if(t.isIdentifier(declaration.id)&&declaration.init&&t.isExpression(declaration.init))locals.set(declaration.id.name,declaration.init)}if(t.isFunctionDeclaration(statement)&&statement.id)locals.set(statement.id.name,statement);if(t.isExportNamedDeclaration(statement)){if(statement.declaration){if(t.isVariableDeclaration(statement.declaration)){for(const declaration of statement.declaration.declarations)if(t.isIdentifier(declaration.id)&&declaration.init&&t.isExpression(declaration.init)){locals.set(declaration.id.name,declaration.init);exports.set(declaration.id.name,declaration.id.name)}}if(t.isFunctionDeclaration(statement.declaration)&&statement.declaration.id){locals.set(statement.declaration.id.name,statement.declaration);exports.set(statement.declaration.id.name,statement.declaration.id.name)}}for(const specifier of statement.specifiers)if(t.isExportSpecifier(specifier)&&t.isIdentifier(specifier.local)&&t.isIdentifier(specifier.exported)){exports.set(specifier.exported.name,specifier.local.name);if(statement.source)reexports.set(specifier.exported.name,{source:statement.source.value,importedName:specifier.local.name})}}if(t.isExportDefaultDeclaration(statement)&&statement.declaration){if(t.isFunctionDeclaration(statement.declaration)&&statement.declaration.id)locals.set(`default`,statement.declaration);else if(t.isExpression(statement.declaration))locals.set(`default`,statement.declaration)}}return{locals,exports,reexports}}function createJsxModuleResolver(warnings,readSource=filename=>readFileSync(filename,`utf8`)){const cache=/* @__PURE__ */ new Map;const active=/* @__PURE__ */ new Set;const dependencies=/* @__PURE__ */ new Set;function read(filename){const code=readSource(filename);const cached=cache.get(filename);if(cached?.code===code)return cached.exports;const collected=collectExports(parse$3(code,{...BABEL_TS_MODULE_PARSER_OPTIONS,sourceFilename:filename}));cache.set(filename,{code,exports:collected});return collected}function resolveExport(filename,localName){if(active.has(filename)){warnings?.push(`[JSX 编译] 检测到跨文件 JSX 循环引用:${filename}`);return}active.add(filename);try{const{locals,reexports}=read(filename);const direct=expressionFromDeclaration(locals.get(localName)??null);if(direct)return direct;const forwarded=reexports.get(localName);if(!forwarded)return;const target=resolveFile(forwarded.source,filename,readSource);if(target)dependencies.add(target);return target?resolveExport(target,forwarded.importedName):void 0}finally{active.delete(filename)}}function resolveImport(filename,source,importedName){const target=resolveFile(source,filename,readSource);if(!target)return;dependencies.add(target);return resolveExport(target,importedName==="default"?`default`:importedName)}return{getDependencies:()=>[...dependencies],resolveExport,resolveImport}}function normalizeSourceFile$1(filename){return filename.replaceAll(`\\`,`/`)}function resolveBindingSourceFile(context,ownerFile){if(!ownerFile||!context.filename||path$1.resolve(ownerFile)===path$1.resolve(context.filename))return;if(!context.bindingManifest.sourceFile)return normalizeSourceFile$1(ownerFile);const relativeOwner=path$1.relative(path$1.dirname(context.filename),ownerFile);return normalizeSourceFile$1(path$1.join(path$1.dirname(context.bindingManifest.sourceFile),relativeOwner))}function recordJsxBinding(context,node,kind,outputPath){const expression=normalizeInterpolationExpression(node,context);const sourceFile=resolveBindingSourceFile(context,node.loc?.filename);const sourceLocation=node.loc&&node.start!=null&&node.end!=null?{start:{offset:node.start,line:node.loc.start.line,column:node.loc.start.column+1},end:{offset:node.end,line:node.loc.end.line,column:node.loc.end.column+1}}:void 0;const scopes=[{kind:`root`,depth:0},...context.bindingScopeStack.map((scope,index)=>({kind:`for`,depth:index+1,locals:[...scope.locals]}))];recordSyntheticBindingExpression(context.bindingManifest,{kind,expression,outputPath,sourceFile,sourceLocation,scopes,scopeDependencies:context.bindingScopeStack.map(scope=>({expression:scope.sourceExpression,locals:scope.sourceLocals}))},context.scopeStack)}const ON_EVENT_RE=/^on[A-Z]/;const CATCH_EVENT_RE=/^catch[A-Z]/;const CAPTURE_BIND_EVENT_RE=/^captureBind[A-Z]/;const CAPTURE_CATCH_EVENT_RE=/^captureCatch[A-Z]/;const MUT_BIND_EVENT_RE=/^mutBind[A-Z]/;const UPPERCASE_STYLE_RE=/[A-Z]/g;function isEventBinding(name){return ON_EVENT_RE.test(name)||CATCH_EVENT_RE.test(name)||CAPTURE_BIND_EVENT_RE.test(name)||CAPTURE_CATCH_EVENT_RE.test(name)||MUT_BIND_EVENT_RE.test(name)}function lowerFirstEventName(name){if(!name)return name;return`${name.charAt(0).toLowerCase()}${name.slice(1)}`}function resolveMappedEventName(rawName,context,isComponent){const resolveEvent=name=>{const eventName=lowerFirstEventName(name);return isComponent?eventName:context.platform.mapEventName(eventName)};if(CAPTURE_BIND_EVENT_RE.test(rawName))return resolveEvent(rawName.slice(11));if(CAPTURE_CATCH_EVENT_RE.test(rawName))return resolveEvent(rawName.slice(12));if(MUT_BIND_EVENT_RE.test(rawName))return resolveEvent(rawName.slice(7));if(CATCH_EVENT_RE.test(rawName))return resolveEvent(rawName.slice(5));return resolveEvent(rawName.slice(2))}function toEventBindingName(rawName,context,isComponent,tagName){const eventName=resolveMappedEventName(rawName,context,isComponent);if(ON_EVENT_RE.test(rawName)&&!isComponent){const sourceEventName=lowerFirstEventName(rawName.slice(2));const exactBinding=context.platform.eventBindingAlias?.(sourceEventName,tagName);if(exactBinding)return exactBinding}if(CAPTURE_BIND_EVENT_RE.test(rawName))return context.platform.eventBindingAttr(`capture-bind:${eventName}`);if(CAPTURE_CATCH_EVENT_RE.test(rawName))return context.platform.eventBindingAttr(`capture-catch:${eventName}`);if(MUT_BIND_EVENT_RE.test(rawName))return context.platform.eventBindingAttr(`mut-bind:${eventName}`);if(CATCH_EVENT_RE.test(rawName))return context.platform.eventBindingAttr(`catch:${eventName}`);return context.platform.eventBindingAttr(`bind:${eventName}`)}function readJsxAttributeExpression(value){if(!value)return t.booleanLiteral(true);if(t.isStringLiteral(value))return value;if(!t.isJSXExpressionContainer(value))return null;if(t.isJSXEmptyExpression(value.expression))return null;return unwrapTsExpression(value.expression)}function extractJsxKeyExpression(node,context){for(const attr of node.openingElement.attributes){if(!t.isJSXAttribute(attr)||!t.isJSXIdentifier(attr.name))continue;if(attr.name.name!==`key`)continue;const exp=readJsxAttributeExpression(attr.value);if(!exp)return null;if(t.isStringLiteral(exp))return exp.value;return normalizeInterpolationExpression(exp,context)}return null}function compileEventAttribute(name,value,context,isComponent,tagName){const bindAttr=toEventBindingName(name,context,isComponent,tagName);const eventName=resolveMappedEventName(name,context,isComponent);const eventSuffix=normalizeEventDatasetSuffix(eventName);const exp=readJsxAttributeExpression(value);if(!exp)return[];if(t.isStringLiteral(exp)&&exp.value)return[`${bindAttr}="${escapeAttr(exp.value)}"`];if(t.isIdentifier(exp))return[`${bindAttr}="${escapeAttr(exp.name)}"`];if(t.isMemberExpression(exp)&&!exp.computed&&t.isThisExpression(exp.object)&&t.isIdentifier(exp.property))return[`${bindAttr}="${escapeAttr(exp.property.name)}"`];context.bindingManifest.features.inlineEvents=true;const inline=registerInlineExpression(exp,context);const attrs=[`data-${`wi`}-${eventSuffix}="${inline.id}"`,`${bindAttr}="${WEVU_INLINE_HANDLER}"`];inline.scopeKeys.forEach((scopeKey,index)=>{attrs.push(`data-wv-s${index}="${renderMustache(scopeKey,context)}"`)});return attrs}function compileNormalAttribute(name,value,context,isComponent){const normalizedName=name===`className`?`class`:isComponent?normalizeComponentHostName(name):name;const exp=readJsxAttributeExpression(value);if(!exp)return null;if(t.isStringLiteral(exp))return`${normalizedName}="${escapeAttr(exp.value)}"`;if(t.isBooleanLiteral(exp))return`${normalizedName}="${renderMustache(String(exp.value),context)}"`;if(normalizedName===`class`){const value=resolveStaticClass(exp);if(value!=null)return`class="${escapeAttr(value)}"`}if(normalizedName===`style`){const value=resolveStaticStyle(exp);if(value!=null)return`style="${escapeAttr(value)}"`}recordJsxBinding(context,exp,normalizedName===`class`?`class`:normalizedName===`style`?`style`:isComponent?`component-prop`:`attribute`);if(isComponent&&(t.isArrowFunctionExpression(exp)||t.isFunctionExpression(exp)))context.bindingManifest.features.functionProps=true;const normalizedExp=normalizeInterpolationExpression(exp,context);return`${normalizedName}="${renderMustache(normalizedExp,context)}"`}function compileNamedAttribute(name,value,context,isComponent,tagName){if(name===`key`)return[];if(name===`v-html`){context.warnings.push(`小程序不支持 JSX v-html,请使用 rich-text 组件替代。`);return[]}if(name===`v-if`||name===`v-show`||name===`v-text`||name===`v-for`)return[];if(name===`v-slots`||name===`v-model`||name===`v-models`){context.warnings.push(`JSX ${name} 需要 Wevu runtime 语义,已生成确定性诊断。`);return[]}if(name.startsWith(`v-`)){context.warnings.push(`小程序不支持 JSX 自定义指令 ${name},已移除该指令。`);return[]}if(name===`innerHTML`||name.startsWith(`domProps`)){context.warnings.push(`小程序不支持 JSX DOM property ${name},已移除该属性。`);return[]}if(isEventBinding(name))return compileEventAttribute(name,value,context,isComponent,tagName);const normalAttr=compileNormalAttribute(name,value,context,isComponent);return normalAttr?[normalAttr]:[]}function compileJsxAttributes(attributes,context,options){const isComponent=options?.isComponent===true;const output=[];for(const attr of attributes){if(t.isJSXSpreadAttribute(attr)){const argument=unwrapTsExpression(attr.argument);if(t.isObjectExpression(argument))for(const property of argument.properties)if(t.isObjectProperty(property)&&!property.computed&&(t.isIdentifier(property.key)||t.isStringLiteral(property.key))){const value=property.value;if(t.isExpression(value)){const name=t.isIdentifier(property.key)?property.key.name:property.key.value;output.push(...compileNamedAttribute(name,t.jsxExpressionContainer(value),context,isComponent,options?.tagName))}}else context.warnings.push(`JSX spread attributes 包含无法静态展开的属性,已保留为 dynamic island。`);else context.warnings.push(`动态 JSX spread attributes 无法映射为静态 WXML,已生成确定性诊断。`);continue}if(t.isJSXNamespacedName(attr.name)){const namespace=attr.name.namespace.name;const name=attr.name.name.name;if(namespace.startsWith(`v-`))context.warnings.push(`小程序不支持 JSX 自定义指令 ${namespace}:${name},已移除该指令。`);else context.warnings.push(`小程序不支持 JSX 命名属性 ${namespace}:${name},已移除该属性。`);continue}if(!t.isJSXIdentifier(attr.name)){context.warnings.push(`小程序不支持 JSX 动态属性名,已移除该属性。`);continue}const name=attr.name.name;output.push(...compileNamedAttribute(name,attr.value,context,isComponent,options?.tagName))}return output}function staticObjectKey(node){if(t.isIdentifier(node))return node.name;if(t.isStringLiteral(node))return node.value}function resolveStaticClass(exp){if(t.isStringLiteral(exp)||t.isNumericLiteral(exp))return String(exp.value);if(t.isArrayExpression(exp)){const values=exp.elements.map(element=>{if(!element||!t.isExpression(element))return``;return resolveStaticClass(element)});return values.some(value=>value==null)?void 0:values.filter(Boolean).join(` `)}if(t.isObjectExpression(exp)){const values=[];for(const property of exp.properties){if(!t.isObjectProperty(property)||property.computed||!t.isBooleanLiteral(property.value))return;const key=staticObjectKey(property.key);if(key==null)return;if(property.value.value)values.push(key)}return values.join(` `)}}function resolveStaticStyle(exp){if(t.isStringLiteral(exp))return exp.value;if(t.isArrayExpression(exp)){const values=exp.elements.map(element=>{if(!element||!t.isExpression(element))return``;return resolveStaticStyle(element)});return values.some(value=>value==null)?void 0:values.filter(Boolean).join(`;`)}if(!t.isObjectExpression(exp))return;const values=[];for(const property of exp.properties){if(!t.isObjectProperty(property)||property.computed)return;const key=staticObjectKey(property.key)?.replace(UPPERCASE_STYLE_RE,char=>`-${char.toLowerCase()}`);if(!key||!t.isStringLiteral(property.value)&&!t.isNumericLiteral(property.value))return;values.push(`${key}:${property.value.value}`)}return values.join(`;`)}function isStaticClassStyleExpression(exp){return resolveStaticClass(exp)!=null||resolveStaticStyle(exp)!=null}function collectJsxDirectives(node){const directives=/* @__PURE__ */ new Map;for(const attribute of node.openingElement.attributes){if(!t.isJSXAttribute(attribute))continue;const name=t.isJSXIdentifier(attribute.name)?attribute.name.name:t.isJSXNamespacedName(attribute.name)?attribute.name.namespace.name:void 0;if(!name?.startsWith(`v-`))continue;const expression=readJsxAttributeExpression(attribute.value);if(expression)directives.set(name,expression)}return directives}const ROOT_PORTAL_TAG=`root-portal`;const TELEPORT_REMOVED_ATTRIBUTES=/* @__PURE__ */ new Set([`to`,`defer`,`disabled`,`key`]);function findJsxAttribute(node,name){return node.openingElement.attributes.find(attribute=>t.isJSXAttribute(attribute)&&t.isJSXIdentifier(attribute.name)&&attribute.name.name===name)}function resolveTeleportTarget(node){const attribute=findJsxAttribute(node,`to`);if(!attribute)return{kind:`missing`};const expression=readJsxAttributeExpression(attribute.value);if(expression&&t.isStringLiteral(expression))return{kind:`static`,value:expression.value};return{kind:`dynamic`}}function resolveTeleportEnable(node,context){const attribute=findJsxAttribute(node,`disabled`);if(!attribute)return renderMustache(`true`,context);const expression=readJsxAttributeExpression(attribute.value);if(!expression||t.isBooleanLiteral(expression)&&expression.value)return renderMustache(`false`,context);if(t.isBooleanLiteral(expression))return renderMustache(`true`,context);recordJsxBinding(context,expression,`attribute`);return renderMustache(`!(${normalizeInterpolationExpression(expression,context)})`,context)}function resolveTeleportPassthroughAttributes(node){const attributes=[];for(const attribute of node.openingElement.attributes){if(!t.isJSXAttribute(attribute)||!t.isJSXIdentifier(attribute.name))continue;const name=attribute.name.name;if(name.startsWith(`v-`)||TELEPORT_REMOVED_ATTRIBUTES.has(name))continue;attributes.push(attribute)}return attributes}function hasTeleportClassOrStyle(attributes){return attributes.some(attribute=>t.isJSXIdentifier(attribute.name)&&(attribute.name.name===`class`||attribute.name.name===`className`||attribute.name.name===`style`))}function compileJsxTeleport(node,context,compileJsxChildren,registerDynamicIsland){const directives=collectJsxDirectives(node);const wrapIf=content=>{const expression=directives.get(`v-if`);if(!expression)return content;recordJsxBinding(context,expression,`if`);return context.platform.wrapIf(normalizeInterpolationExpression(expression,context),content,value=>renderMustache(value,context))};if(!context.teleport.enabled)return wrapIf(compileJsxChildren(node.children,context));const decision=resolveTeleportDecision({supportsRootPortal:context.platform.supportsRootPortal===true,to:resolveTeleportTarget(node),spread:node.openingElement.attributes.some(attribute=>t.isJSXSpreadAttribute(attribute))});if(decision.kind===`degrade`){addJsxDiagnostic(context,node,TELEPORT_DEGRADE_CODES[decision.reason],decision.message,context.teleport.unsupported===`error`?`error`:`warning`);return wrapIf(compileJsxChildren(node.children,context))}const dynamicDirective=[`v-for`,`v-slots`,`v-model`,`v-models`].find(name=>directives.has(name));if(dynamicDirective){if(dynamicDirective===`v-model`||dynamicDirective===`v-models`)context.bindingManifest.features.model=true;context.warnings.push(`JSX ${dynamicDirective} 无法直接映射当前静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`closure`)}if(consumeBaseLibraryHint(context.baseLibrary,{topic:`root-portal`,minimum:ROOT_PORTAL_ENABLE_MIN_SDK_VERSION}))addJsxDiagnostic(context,node,`WV1010`,ROOT_PORTAL_BASE_LIBRARY_HINT_MESSAGE);const passthroughAttributes=resolveTeleportPassthroughAttributes(node);if(hasTeleportClassOrStyle(passthroughAttributes))addJsxDiagnostic(context,node,`WV1009`,`<Teleport> 的 class/style 会落在 root-portal 宿主节点上,可能无法按预期作用于内部弹层,建议把样式写在内层节点。`);const attrs=[`enable="${resolveTeleportEnable(node,context)}"`,...compileJsxAttributes(passthroughAttributes,context,{isComponent:false,tagName:ROOT_PORTAL_TAG})];const showExpression=directives.get(`v-show`);if(showExpression){recordJsxBinding(context,showExpression,`style`);attrs.push(`hidden="${renderMustache(`!(${normalizeInterpolationExpression(showExpression,context)})`,context)}"`)}const attrsSegment=attrs.length?` ${attrs.join(` `)}`:``;const content=compileJsxChildren(node.children,context);return wrapIf(content?`<${ROOT_PORTAL_TAG}${attrsSegment}>${content}</${ROOT_PORTAL_TAG}>`:`<${ROOT_PORTAL_TAG}${attrsSegment} />`)}const DYNAMIC_ISLAND_TEMPLATE_DEPTH=8;function resolveDynamicIslandTemplateName(depth){return depth===0?WEVU_JSX_ISLAND_TEMPLATE_NAME:`${WEVU_JSX_ISLAND_TEMPLATE_NAME}_${depth}`}function compileListExpression(exp,context){return normalizeInterpolationExpression(exp,context)}function registerDynamicIsland(exp,context,reason){if(context.dynamicIslandMode===`static`){context.warnings.push(`[JSX 编译] static 模式不允许 dynamic island(${reason})。`);return``}const id=`i${context.dynamicIslandSeed??0}`;context.dynamicIslandSeed=(context.dynamicIslandSeed??0)+1;context.bindingManifest.features.jsxIslands=true;recordJsxBinding(context,exp,`text`,WEVU_JSX_ISLAND_DATA_KEY);const expression=normalizeInterpolationExpression(exp);const captures=/* @__PURE__ */ new Set;const file=t.file(t.program([t.expressionStatement(t.cloneNode(exp,true))]));traverse(file,{ReferencedIdentifier(path){if(path.scope.hasBinding(path.node.name))return;if(context.importedBindings?.has(path.node.name))return;captures.add(path.node.name)},ThisExpression(){captures.add(`this`)}});context.dynamicIslands?.push({id,expression,reason,captures:[...captures]});return`<template is="${WEVU_JSX_ISLAND_TEMPLATE_NAME}" data-wv-jsx-island="${id}" data="{{node:${WEVU_JSX_ISLAND_DATA_KEY}.${id},islandId:'${id}'}}" />`}function renderDynamicIslandSupportTemplate(context){const{directives}=context.platform;const bindTap=context.platform.eventBindingAttr(`bind:tap`);const bindInput=context.platform.eventBindingAttr(`bind:input`);const bindChange=context.platform.eventBindingAttr(`bind:change`);const attrs=`id="{{node.props.id}}" class="{{node.props.class}}" style="{{node.props.style}}" hidden="{{node.props.hidden}}"`;const tapAttrs=`${attrs} data-wv-jsx-handler="{{node.events.tap}}" ${bindTap}="${WEVU_JSX_ISLAND_HANDLER}"`;return Array.from({length:DYNAMIC_ISLAND_TEMPLATE_DEPTH},(_,depth)=>{const templateName=resolveDynamicIslandTemplateName(depth);const childTemplateName=resolveDynamicIslandTemplateName(depth+1);const childTemplate=depth+1<DYNAMIC_ISLAND_TEMPLATE_DEPTH?`<block ${directives.forAttr}="{{node.children}}" ${directives.forItemAttr}="child" ${directives.keyAttr}="index"><template is="${childTemplateName}" data="{{node:child,islandId:islandId}}" /></block>`:``;return`<template name="${templateName}"><block ${directives.ifAttr}="{{node.kind=='text'}}">{{node.text}}</block><block ${directives.elifAttr}="{{node.kind=='fragment'}}">${childTemplate}</block><view ${directives.elifAttr}="{{node.tag=='view'}}" ${tapAttrs}>${childTemplate}</view><text ${directives.elifAttr}="{{node.tag=='text'}}" ${tapAttrs}>${childTemplate}</text><button ${directives.elifAttr}="{{node.tag=='button'}}" ${tapAttrs}>${childTemplate}</button><input ${directives.elifAttr}="{{node.tag=='input'}}" ${attrs} value="{{node.props.value}}" data-wv-jsx-handler="{{node.events.input||node.events.change}}" ${bindInput}="${WEVU_JSX_ISLAND_HANDLER}" ${bindChange}="${WEVU_JSX_ISLAND_HANDLER}" /><image ${directives.elifAttr}="{{node.tag=='image'}}" ${tapAttrs} src="{{node.props.src}}" /><block ${directives.elseAttr}>${childTemplate}</block></template>`}).join(``)}function resolveImportedExpression(node,context){if(!context.filename||!context.moduleResolver)return;let localName;let importedName;if(t.isIdentifier(node))localName=node.name;else if(t.isMemberExpression(node)&&!node.computed&&t.isIdentifier(node.object)&&t.isIdentifier(node.property)){localName=node.object.name;importedName=node.property.name}if(!localName)return;const binding=context.importedBindings?.get(localName);if(!binding)return;if(binding.importedName!==`*`&&importedName)return;const resolvedName=importedName??binding.importedName;const key=`${context.filename}:${localName}:${resolvedName}`;if(context.resolvingExports?.has(key)){context.warnings.push(`[JSX 编译] 跨文件 JSX 导出循环引用:${localName}`);return}context.resolvingExports?.add(key);try{return context.moduleResolver.resolveImport(context.filename,binding.source,resolvedName)}finally{context.resolvingExports?.delete(key)}}function compileImportedExpression(node,context){const resolved=resolveImportedExpression(node,context);if(!resolved||resolved.params.length>0){const importedLocal=t.isIdentifier(node)?node.name:t.isMemberExpression(node)&&t.isIdentifier(node.object)?node.object.name:``;if(context.importedBindings?.has(importedLocal)){context.warnings.push(`[JSX 编译] 无法静态展开跨文件 JSX 导出,已生成 dynamic island:${importedLocal||`unknown`}`);return registerDynamicIsland(node,context,`unsupported-import`)}return null}return compileRenderableExpression(resolved.expression,context)}function compileImportedFactoryCall(node,context){if(!t.isIdentifier(node.callee)||!context.filename||!context.moduleResolver)return null;const binding=context.importedBindings?.get(node.callee.name);if(!binding)return null;const resolved=context.moduleResolver.resolveImport(context.filename,binding.source,binding.importedName);if(!resolved||resolved.params.length===0){context.warnings.push(`[JSX 编译] 无法静态展开 JSX 工厂 ${node.callee.name},已生成 dynamic island。`);return registerDynamicIsland(node,context,`unsupported-call`)}const replacements=/* @__PURE__ */ new Map;resolved.params.forEach((param,index)=>{const argument=node.arguments[index];if(argument&&t.isExpression(argument))replacements.set(param,argument)});if(replacements.size!==resolved.params.length){context.warnings.push(`[JSX 编译] JSX 工厂 ${node.callee.name} 调用参数不足,已保留运行时表达式。`);return null}const expression=t.cloneNode(resolved.expression,true);const file=t.file(t.program([t.expressionStatement(expression)]));traverse(file,{ReferencedIdentifier(path){const replacement=replacements.get(path.node.name);if(replacement)path.replaceWith(t.cloneNode(replacement,true))}});const output=file.program.body[0];if(!t.isExpressionStatement(output))return null;let expanded=output.expression;if(t.isCallExpression(expanded)&&expanded.arguments.length===0){const callee=expanded.callee;if(t.isArrowFunctionExpression(callee)||t.isFunctionExpression(callee)){const body=callee.body;let capturesThis=false;if(t.isExpression(body)){const file=t.file(t.program([t.expressionStatement(body)]));traverse(file,{ThisExpression(){capturesThis=true}});if(!capturesThis)expanded=body}}}return compileRenderableExpression(expanded,context)}function compileMapExpression(exp,context){const callee=exp.callee;if(!t.isMemberExpression(callee)||!t.isIdentifier(callee.property,{name:`map`}))return null;const callback=exp.arguments[0];if(!callback||!(t.isArrowFunctionExpression(callback)||t.isFunctionExpression(callback))){context.warnings.push(`仅支持 map(fn) 形式的列表渲染。`);return null}recordJsxBinding(context,callee.object,`for`);const listExp=compileListExpression(callee.object,context);const renderTemplateMustache=expression=>renderMustache(expression,context);const itemParam=callback.params[0];const indexParam=callback.params[1];const item=t.isIdentifier(itemParam)?itemParam.name:`item`;const index=t.isIdentifier(indexParam)?indexParam.name:void 0;const addedScope=[item,index].filter(name=>!!name);pushScope(context,addedScope,listExp);let bodyExp=null;if(t.isBlockStatement(callback.body)){for(const statement of callback.body.body)if(t.isReturnStatement(statement)&&statement.argument){bodyExp=unwrapTsExpression(statement.argument);break}}else bodyExp=unwrapTsExpression(callback.body);const body=bodyExp?compileRenderableExpression(bodyExp,context):``;if(!body){popScope(context,addedScope.length);return``}let keyValue=context.platform.keyThisValue;if(bodyExp&&t.isJSXElement(bodyExp)){const extracted=extractJsxKeyExpression(bodyExp,context);if(extracted)keyValue=extracted;else if(index)keyValue=index}else if(index)keyValue=index;popScope(context,addedScope.length);return`<block ${[...context.platform.forAttrs(listExp,renderTemplateMustache,item,index),context.platform.keyAttr(keyValue)].join(` `)}>${body}</block>`}function compileConditionalExpression(exp,context){const renderTemplateMustache=expression=>renderMustache(expression,context);recordJsxBinding(context,exp.test,`if`);const test=normalizeInterpolationExpression(exp.test,context);const consequent=compileRenderableExpression(exp.consequent,context);const alternate=compileRenderableExpression(exp.alternate,context);if(!alternate)return context.platform.wrapIf(test,consequent,renderTemplateMustache);return`${context.platform.wrapIf(test,consequent,renderTemplateMustache)}${context.platform.wrapElse(alternate)}`}function compileLogicalExpression(exp,context){const renderTemplateMustache=expression=>renderMustache(expression,context);recordJsxBinding(context,exp.left,`if`);if(exp.operator===`&&`){const test=normalizeInterpolationExpression(exp.left,context);const content=compileRenderableExpression(exp.right,context);return context.platform.wrapIf(test,content,renderTemplateMustache)}if(exp.operator===`||`){const negated=t.unaryExpression(`!`,t.parenthesizedExpression(t.cloneNode(exp.left,true)));const test=normalizeInterpolationExpression(negated,context);const content=compileRenderableExpression(exp.right,context);return context.platform.wrapIf(test,content,renderTemplateMustache)}return renderMustache(normalizeInterpolationExpression(exp,context),context)}function compileRenderableExpression(exp,context){const node=unwrapTsExpression(exp);if(t.isJSXElement(node))return compileJsxElement(node,context);if(t.isJSXFragment(node))return compileJsxFragment(node,context);if(t.isConditionalExpression(node))return compileConditionalExpression(node,context);if(t.isLogicalExpression(node))return compileLogicalExpression(node,context);if(t.isCallExpression(node)){const importedFactory=compileImportedFactoryCall(node,context);if(importedFactory!=null)return importedFactory;const mapped=compileMapExpression(node,context);if(mapped!=null)return mapped;context.warnings.push(`无法证明 JSX 子节点函数调用返回静态文本,已生成 dynamic island。`);return registerDynamicIsland(node,context,`unsupported-call`)}if(t.isArrayExpression(node))return node.elements.map(element=>{if(!element||!t.isExpression(element))return``;return compileRenderableExpression(element,context)}).join(``);if(t.isIdentifier(node)||t.isMemberExpression(node)){const imported=compileImportedExpression(node,context);if(imported!=null)return imported}if(t.isNullLiteral(node)||t.isBooleanLiteral(node))return``;recordJsxBinding(context,node,`text`);return renderMustache(normalizeInterpolationExpression(node,context),context)}function compileExpressionContainer(node,context){const exp=node.expression;if(t.isJSXEmptyExpression(exp))return``;return compileRenderableExpression(exp,context)}function compileJsxChildren(children,context){const parts=[];for(const child of children){if(t.isJSXText(child)){const normalized=normalizeJsxText(child.value);if(!normalized.trim())continue;parts.push(escapeText(normalized));continue}if(t.isJSXExpressionContainer(child)){const chunk=compileExpressionContainer(child,context);if(chunk)parts.push(chunk);continue}if(t.isJSXElement(child)){parts.push(compileJsxElement(child,context));continue}if(t.isJSXFragment(child)){parts.push(compileJsxFragment(child,context));continue}if(t.isJSXSpreadChild(child)){parts.push(registerDynamicIsland(child.expression,context,`spread-child`));context.warnings.push(`JSX spread child 无法映射为静态 WXML,已生成 dynamic island。`)}}return parts.join(``)}function compileJsxFragment(node,context){return compileJsxChildren(node.children,context)}function compileJsxElement(node,context){if(t.isJSXMemberExpression(node.openingElement.name)){context.warnings.push(`JSX 成员标签(如 <Foo.Bar />)无法映射为小程序 WXML 组件标签,已生成 dynamic island。`);return registerDynamicIsland(node,context,`dynamic-component`)}const rawTag=toJsxTagName(node.openingElement.name,context);if(rawTag===`Teleport`)return compileJsxTeleport(node,context,compileJsxChildren,registerDynamicIsland);const dynamicSpread=node.openingElement.attributes.find(attr=>{if(!t.isJSXSpreadAttribute(attr))return false;const argument=unwrapTsExpression(attr.argument);return!t.isObjectExpression(argument)||argument.properties.some(property=>!t.isObjectProperty(property)||property.computed||!t.isIdentifier(property.key)&&!t.isStringLiteral(property.key)||!t.isExpression(property.value))});if(dynamicSpread&&t.isJSXSpreadAttribute(dynamicSpread)){context.warnings.push(`动态 JSX spread attributes 无法映射为静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`dynamic-spread`)}if(rawTag===`component`){context.warnings.push(`JSX 动态 component 无法映射为静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`dynamic-component`)}if(rawTag===`Transition`){context.warnings.push(`JSX <Transition> 需要 Web 动画运行时,当前仅渲染子节点。`);return compileJsxChildren(node.children,context)}if(rawTag===`KeepAlive`){context.warnings.push(`JSX <KeepAlive> 需要运行时缓存管理,当前仅保留标记并渲染子节点。`);return`<block data-keep-alive="true">${compileJsxChildren(node.children,context)}</block>`}const isComponent=!isBuiltinComponent(rawTag);const tag=isComponent?hyphenate(rawTag):rawTag;if(node.children.some(child=>{if(!t.isJSXExpressionContainer(child)||t.isJSXEmptyExpression(child.expression))return false;const expression=unwrapTsExpression(child.expression);return t.isObjectExpression(expression)||t.isFunctionExpression(expression)||t.isArrowFunctionExpression(expression)})){context.warnings.push(`JSX slot 函数或对象 slots 无法映射为静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`closure`)}if(node.openingElement.attributes.some(attribute=>{if(!t.isJSXAttribute(attribute)||!t.isJSXIdentifier(attribute.name))return false;if(attribute.name.name!==`class`&&attribute.name.name!==`className`&&attribute.name.name!==`style`)return false;const expression=readJsxAttributeExpression(attribute.value);return!!expression&&(t.isArrayExpression(expression)||t.isObjectExpression(expression))&&!isStaticClassStyleExpression(expression)})){context.warnings.push(`动态 JSX class/style 数组或对象需要运行时合并,已生成 dynamic island。`);return registerDynamicIsland(node,context,`closure`)}const directives=collectJsxDirectives(node);if(directives.has(`v-for`)||directives.has(`v-slots`)||directives.has(`v-model`)||directives.has(`v-models`)){const directive=[`v-for`,`v-slots`,`v-model`,`v-models`].find(name=>directives.has(name));if(directive===`v-model`||directive===`v-models`)context.bindingManifest.features.model=true;context.warnings.push(`JSX ${directive} 无法直接映射当前静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`closure`)}const attrs=compileJsxAttributes(node.openingElement.attributes,context,{isComponent,tagName:tag});const showExpression=directives.get(`v-show`);if(showExpression){recordJsxBinding(context,showExpression,`style`);attrs.push(`hidden="${renderMustache(`!(${normalizeInterpolationExpression(showExpression,context)})`,context)}"`)}const attrsSegment=attrs.length?` ${attrs.join(` `)}`:``;const textExpression=directives.get(`v-text`);if(textExpression)recordJsxBinding(context,textExpression,`text`);const content=textExpression?renderMustache(normalizeInterpolationExpression(textExpression,context),context):compileJsxChildren(node.children,context);const element=node.openingElement.selfClosing&&!textExpression?`<${tag}${attrsSegment} />`:`<${tag}${attrsSegment}>${content}</${tag}>`;const ifExpression=directives.get(`v-if`);if(ifExpression){recordJsxBinding(context,ifExpression,`if`);return context.platform.wrapIf(normalizeInterpolationExpression(ifExpression,context),element,expression=>renderMustache(expression,context))}return element}function createJsxCompileContext(options){return{platform:options?.template?.platform??getMiniProgramTemplatePlatform(),mustacheInterpolation:options?.template?.mustacheInterpolation??`compact`,formatWxml:options?.template?.formatWxml??false,warnings:[],warningDiagnostics:/* @__PURE__ */ new Map,bindingManifest:createBindingManifest(options?.bindingManifestSourceFile??``),inlineExpressions:[],classStyleBindings:[],forStack:[],interpolationCache:/* @__PURE__ */ new WeakMap,inlineExpressionSeed:0,scopeStack:[],bindingScopeStack:[],moduleResolver:void 0,importedBindings:/* @__PURE__ */ new Map,resolvingExports:/* @__PURE__ */ new Set,dynamicIslands:[],dynamicIslandSeed:0,dynamicIslandMode:`auto`,baseLibrary:createBaseLibraryCompileContext({version:options?.template?.baseLibraryVersion,hintState:options?.template?.baseLibraryHintState}),teleport:{enabled:options?.template?.teleport?.enabled??true,unsupported:options?.template?.teleport?.unsupported===`error`?`error`:`warn`}}}function collectImportedBindings(ast,context){for(const statement of ast.program.body){if(!t.isImportDeclaration(statement))continue;const source=statement.source.value;for(const specifier of statement.specifiers)if(t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.local)){const importedName=t.isIdentifier(specifier.imported)?specifier.imported.name:specifier.imported.value;context.importedBindings?.set(specifier.local.name,{source,importedName})}else if(t.isImportDefaultSpecifier(specifier)&&t.isIdentifier(specifier.local))context.importedBindings?.set(specifier.local.name,{source,importedName:`default`});else if(t.isImportNamespaceSpecifier(specifier)&&t.isIdentifier(specifier.local))context.importedBindings?.set(specifier.local.name,{source,importedName:`*`})}}function compileJsxTemplateAndCollectComponents(source,filename,options){const ast=parse$3(source,{...BABEL_TS_MODULE_PARSER_OPTIONS,sourceFilename:filename});const context=createJsxCompileContext(options);context.filename=filename;context.bindingManifest.sourceFile=options?.bindingManifestSourceFile??filename;context.moduleResolver=createJsxModuleResolver(context.warnings,options?.jsx?.readFile);collectImportedBindings(ast,context);const{renderExpression,autoComponentContext}=analyzeJsxAst(ast,context);let template;if(renderExpression){template=compileRenderableExpression(renderExpression,context);if(context.dynamicIslands?.length)template+=renderDynamicIslandSupportTemplate(context);if(context.formatWxml)template=formatWxml(template)}else context.warnings=context.warnings.map(message=>message===`未识别到默认导出组件。`?`未在 ${filename} 中识别到默认导出组件。`:message);return{template,warnings:context.warnings,warningDiagnostics:context.warningDiagnostics,bindingManifest:context.bindingManifest,inlineExpressions:context.inlineExpressions,classStyleBindings:context.classStyleBindings,autoComponentContext,dynamicIslands:context.dynamicIslands,dependencies:context.moduleResolver.getDependencies()}}function printExpression(expression){return expression&&generate(expression,{compact:true}).code}function serializeForScope(scope){const{listExpAst,rawListExpAst,projectedListExpAst,...values}=scope;return{...values,listExpression:printExpression(listExpAst),rawListExpression:printExpression(rawListExpAst),projectedListExpression:printExpression(projectedListExpAst)}}function createJsxTemplateRegistrationSignature(options){const bindings=options.classStyleBindings.map(({expAst,forStack,conditions,...binding})=>({...binding,expression:printExpression(expAst),forStack:forStack.map(serializeForScope),conditions:conditions?.map(condition=>({expression:printExpression(condition.expAst),rawExpression:printExpression(condition.rawExpAst),forDepth:condition.forDepth}))}));return createHash(`sha256`).update(JSON.stringify([options.template,options.inlineExpressions,bindings,options.dynamicIslands])).digest(`hex`)}const LEADING_DOT_RE=/^\./;const SETUP_CALL_RE$1=/\bsetup\s*\(/;function normalizeUsingComponentFrom(value){if(!value)return;return typeof value===`string`?value:value.from}function toMiniProgramComponentTag(name){return name.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).replace(/([A-Z]+)([A-Z][a-z])/g,`$1-$2`).toLowerCase()}async function compileJsxFile(source,filename,options){if(isNativeDomCompilation(options))throw new Error(`[wevu] native-dom 暂只支持带 template 的 Vue SFC,不支持 JSX/TSX 入口`);if(options?.isPage&&mayContainPageDeclaration(source))source=stripPageDeclaration(source,filename)?.code??source;const jsonKind=options?.json?.kind??(options?.isApp?`app`:options?.isPage?`page`:`component`);const jsonDefaults=options?.json?.defaults?.[jsonKind];const mergeJson=createJsonMerger(options?.json?.mergeStrategy,{filename,kind:jsonKind});let scriptSource=source;let scriptMacroConfig;let scriptMacroHash;const scriptLang=path.extname(filename).replace(LEADING_DOT_RE,``)||void 0;if(mayContainJsonMacro(source))try{const extracted=await extractJsonMacroFromScriptSetup(source,filename,scriptLang,{merge:(target,incoming)=>mergeJson(target,incoming,`macro`)});scriptSource=extracted.stripped;scriptMacroConfig=extracted.config;scriptMacroHash=extracted.macroHash}catch(error){const message=error instanceof Error?error.message:String(error);throw new Error(`解析 ${filename} 失败:${message}`)}const{template:rawTemplate,warnings:templateWarnings,warningDiagnostics,bindingManifest,inlineExpressions,classStyleBindings,autoComponentContext,dynamicIslands,dependencies}=compileJsxTemplateAndCollectComponents(source,filename,options);const autoUsingComponentsMap={};const localComponentAliases=/* @__PURE__ */ new Map;if(options?.autoUsingComponents?.resolveUsingComponentPath&&autoComponentContext.templateTags.size>0)for(const imported of autoComponentContext.importedComponents){if(!autoComponentContext.templateTags.has(imported.localName))continue;let resolved=normalizeUsingComponentFrom(await options.autoUsingComponents.resolveUsingComponentPath(imported.importSource,filename,{localName:imported.localName,importedName:imported.importedName,kind:imported.kind}));if(!resolved&&imported.importSource.startsWith(`/`))resolved=removeExtensionDeep(imported.importSource);if(!resolved)continue;const componentName=imported.importSource.startsWith(`.`)||imported.importSource.startsWith(`/`)?toMiniProgramComponentTag(imported.localName):imported.localName;autoUsingComponentsMap[componentName]=resolved;if(componentName!==imported.localName)localComponentAliases.set(imported.localName,componentName)}const autoImportTagsMap={};if(options?.autoImportTags?.resolveUsingComponent&&autoComponentContext.templateTags.size>0)for(const tag of autoComponentContext.templateTags){if(!isAutoImportCandidateTag(tag))continue;let resolved;try{resolved=await options.autoImportTags.resolveUsingComponent(tag,filename)}catch{resolved=void 0}if(!resolved?.from)continue;const resolvedName=resolved.name||tag;autoImportTagsMap[localComponentAliases.get(resolvedName)??resolvedName]=resolved.from}let compiledTemplateStr=rawTemplate;for(const[from,to]of localComponentAliases)if(compiledTemplateStr)compiledTemplateStr=compiledTemplateStr.replaceAll(`<${from}`,`<${to}`).replaceAll(`</${from}>`,`</${to}>`);if(compiledTemplateStr&&(options?.pageLayout||options?.appShell))compiledTemplateStr=applyCompilerTemplateWrappers({template:compiledTemplateStr,manifest:bindingManifest,platform:options?.template?.platform??getMiniProgramTemplatePlatform(),pageLayout:options?.pageLayout,appShell:options?.appShell});const normalizedScriptSource=injectDynamicIslandRuntime(stripRenderOptionFromScript(scriptSource,filename,templateWarnings),dynamicIslands);const{transformVueJsxScript}=await import(`./vueJsxTransform-C4lhnLbg.mjs`);const vueJsxTransformed=transformVueJsxScript(normalizedScriptSource,filename,options?.sourceMap!==false);const runtimeCapabilities=createWevuRuntimeCapabilityMetadataFromBindingManifest(bindingManifest);const transformedScript=transformScript(vueJsxTransformed.code,{skipComponentTransform:options?.skipComponentTransform??options?.isApp,isApp:options?.isApp,isPage:options?.isPage,minify:options?.minify,sourceMap:options?.sourceMap,warn:options?.warn,wevuDefaults:options?.wevuDefaults,inlineExpressions,classStyleBindings,bindingManifest:options?.isApp?void 0:bindingManifest,autoSetDataPick:!options?.isApp&&options?.autoSetDataPick,runtimeBindingManifest:options?.runtimeBindingManifest,pageLayout:options?.isApp?void 0:options?.pageLayout,runtimeCapabilities});const diagnostics=templateWarnings.length?createJsxDiagnostics(templateWarnings,filename,warningDiagnostics):void 0;reportJsxDiagnostics(diagnostics,options?.warn);let configObj;if(Object.keys(autoUsingComponentsMap).length>0||Object.keys(autoImportTagsMap).length>0){const existingRaw=configObj?.usingComponents;const usingComponents=existingRaw&&typeof existingRaw===`object`&&!Array.isArray(existingRaw)?existingRaw:{};for(const[name,from]of Object.entries(autoImportTagsMap)){if(Reflect.has(usingComponents,name)&&usingComponents[name]!==from)options?.autoImportTags?.warn?.(`[JSX 编译] usingComponents 冲突:${filename} 中 usingComponents['${name}']='${usingComponents[name]}' 将被 JSX 标签自动引入覆盖为 '${from}'`);usingComponents[name]=from}for(const[name,from]of Object.entries(autoUsingComponentsMap)){if(Reflect.has(usingComponents,name)&&usingComponents[name]!==from)options?.autoUsingComponents?.warn?.(`[JSX 编译] usingComponents 冲突:${filename} 中 usingComponents['${name}']='${usingComponents[name]}' 将被 JSX 导入组件覆盖为 '${from}'`);usingComponents[name]=from}configObj=mergeJson(configObj??{},{usingComponents},`auto-using-components`)}if(jsonDefaults&&Object.keys(jsonDefaults).length>0)configObj=mergeJson(configObj??{},jsonDefaults,`defaults`);if(scriptMacroConfig&&Object.keys(scriptMacroConfig).length>0)configObj=mergeJson(configObj??{},scriptMacroConfig,`macro`);const config=mergeCompilerLayoutUsingComponents(configObj&&Object.keys(configObj).length>0?JSON.stringify(configObj,null,2):void 0,options?.pageLayout,options?.appShell);return{script:transformedScript.code,scriptMap:transformedScript.map??vueJsxTransformed.map,template:compiledTemplateStr,diagnostics,bindingManifest,config,meta:{hasScriptSetup:false,hasSetupOption:SETUP_CALL_RE$1.test(normalizedScriptSource),jsonMacroHash:scriptMacroHash,jsxDynamicIslands:dynamicIslands,templateRegistrationSignature:createJsxTemplateRegistrationSignature({template:compiledTemplateStr,inlineExpressions,classStyleBindings,dynamicIslands}),...transformedScript.componentStyleOptions?{componentStyleOptions:transformedScript.componentStyleOptions}:{},...transformedScript.runtimeCapabilities?{runtimeCapabilities:transformedScript.runtimeCapabilities}:{},jsxDependencies:dependencies}}}const DIRECTIVE_TOKEN_RE=/\/\/\s*#(?:ifdef|ifndef|else|endif)\b[^\r\n]*|\/\*+\s*#(?:ifdef|ifndef|else|endif)\b[\s\S]*?\*\/|<!--\s*#(?:ifdef|ifndef|else|endif)\b[\s\S]*?-->/g;const SCRIPT_EXT_RE=/\.[cm]?[jt]sx?$/i;const STYLE_EXT_RE=/\.(?:css|less|sass|scss|styl|stylus)$/i;const UNI_APP_RUNTIME_MODULE=`@dcloudio/uni-app`;function resolveRuntimeImport(source){if(source===`vue`||source===UNI_APP_RUNTIME_MODULE)return`wevu`}function evaluateCondition(expression,defines,filename,line){const normalized=expression.replace(/(?:\*\/|-->)\s*$/,``).trim();const tokens=normalized.match(/[A-Z][A-Z0-9_-]*|&&|\|\||[()!]/g)??[];if(!tokens.length||tokens.join(``)!==normalized.replace(/\s/g,``))throw new Error(`[uni-app] ${filename}:${line} 包含无效的条件表达式 "${normalized}"`);let index=0;const parser={parseAnd(){let value=parser.parsePrimary();while(tokens[index]===`&&`){index+=1;const right=parser.parsePrimary();value=value&&right}return value},parseOr(){let value=parser.parseAnd();while(tokens[index]===`||`){index+=1;const right=parser.parseAnd();value=value||right}return value},parsePrimary(){const token=tokens[index];if(token===`!`){index+=1;return!parser.parsePrimary()}if(token===`(`){index+=1;const value=parser.parseOr();if(tokens[index]!==`)`)throw new Error(`[uni-app] ${filename}:${line} 包含无效的条件表达式 "${normalized}"`);index+=1;return value}if(!token||!/^[A-Z][A-Z0-9_-]*$/.test(token))throw new Error(`[uni-app] ${filename}:${line} 包含无效的条件表达式 "${normalized}"`);index+=1;return defines.has(token)}};const value=parser.parseOr();if(index!==tokens.length)throw new Error(`[uni-app] ${filename}:${line} 包含无效的条件表达式 "${normalized}"`);return value}function transformUniAppConditionalCode(source,options){const defines=new Set(options.target===`h5`?[`H5`,`VUE3`]:[`MP`,`MP-WEIXIN`,`VUE3`]);const frames=[];let active=true;let changed=false;let cursor=0;let line=1;let code=``;for(const match of source.matchAll(DIRECTIVE_TOKEN_RE)){const offset=match.index;const segment=source.slice(cursor,offset);code+=active?segment:segment.replace(/[^\r\n]/g,``);line+=segment.split(`
24
+ `),map:null,transformed:true,componentStyleOptions:{styleIsolation:{kind:`absent`},addGlobalClass:{kind:`absent`}}}}function ensureRuntimeImport(program,importedName,localName=importedName){const runtimeImportPath=resolveWevuInternalImportModuleId(importedName);let targetImport=program.body.find(node=>t.isImportDeclaration(node)&&node.importKind!==`type`&&node.source.value===runtimeImportPath);if(!targetImport){targetImport=t.importDeclaration([t.importSpecifier(t.identifier(localName),t.identifier(importedName))],t.stringLiteral(runtimeImportPath));program.body.unshift(targetImport);return}if(!targetImport.specifiers.some(spec=>{if(!t.isImportSpecifier(spec)||spec.importKind===`type`)return false;if(!t.isIdentifier(spec.imported,{name:importedName}))return false;return t.isIdentifier(spec.local,{name:localName})}))targetImport.specifiers.push(t.importSpecifier(t.identifier(localName),t.identifier(importedName)))}const INTERNAL_RUNTIME_VALUE_EXPORTS=/* @__PURE__ */ new Set([`addMutationRecorder`,`batch`,`computed`,`createTextVNode`,`createVNode`,`createApp`,`createWevuComponent`,`createWevuScopedSlotComponent`,...Object.values(WE_VU_RUNTIME_CAPABILITY_INSTALLERS),`customRef`,`defineAppSetup`,`defineComponent`,`effect`,`effectScope`,`endBatch`,`getCurrentInstance`,`getCurrentPageStackSnapshot`,`getCurrentScope`,`getCurrentSetupContext`,`getDeepWatchStrategy`,`Fragment`,`getNavigationBarMetrics`,`getReactiveVersion`,`hasInjectionContext`,`inject`,`injectGlobal`,`isNoSetData`,`isProxy`,`isRaw`,`isReactive`,`isReadonly`,`isRef`,`isShallowReactive`,`isShallowRef`,`isVNode`,`markNoSetData`,`markRaw`,`mergeModels`,`mergeProps`,`mountRuntimeInstance`,`nextTick`,`normalizeClass`,`normalizeJsxIsland`,`normalizeStyle`,`onActivated`,`onAddToFavorites`,`onAttached`,`onBeforeMount`,`onBeforeUnmount`,`onBeforeUpdate`,`onDeactivated`,`onDetached`,`onError`,`onErrorCaptured`,`onHide`,`onLaunch`,`onLoad`,`onMemoryWarning`,`onMounted`,`onMoved`,`onPageNotFound`,`onPageScroll`,`onPullDownRefresh`,`onReachBottom`,`onReady`,`onResize`,`onRouteDone`,`onSaveExitState`,`onScopeDispose`,`onServerPrefetch`,`onShareAppMessage`,`onShareTimeline`,`onShow`,`onTabItemTap`,`onThemeChange`,`onUnhandledRejection`,`onUnload`,`onUnmounted`,`onUpdated`,`prelinkReactiveTree`,`provide`,`provideGlobal`,`reactive`,`resolveDirective`,`resolveComponent`,`readonly`,`ref`,`registerApp`,`registerComponent`,`removeMutationRecorder`,`resetWevuDefaults`,`resolveLayoutBridge`,`resolveLayoutHost`,`resolvePropValue`,`resolveRuntimePageLayoutName`,`runSetupFunction`,`setCurrentInstance`,`setCurrentSetupContext`,`setDeepWatchStrategy`,`setGlobalProvidedValue`,`setPageLayout`,`setRuntimeSetDataVisibility`,`setWevuDefaults`,`shallowReactive`,`shallowReadonly`,`shallowRef`,`startBatch`,`stop`,`syncRuntimePageLayoutState`,`syncRuntimePageLayoutStateFromRuntime`,`teardownRuntimeInstance`,`toRaw`,`toRef`,`toRefs`,`toValue`,`transformOn`,`touchReactive`,`traverse`,`triggerRef`,`unref`,`useAttrs`,`useCssModule`,`useCssVars`,`useAsyncDerivation`,`useAsyncPullDownRefresh`,`useBindModel`,`useBoundingClientRect`,`useChangeModel`,`useDisposables`,`useElementIntersectionObserver`,`useIntersectionObserver`,`useLayoutBridge`,`useLayoutHosts`,`useModel`,`useNativeInstance`,`useNativePageRouter`,`useNativeRouter`,`useNavigationBarMetrics`,`usePageLayout`,`usePageScrollThrottle`,`usePageStack`,`useScrollOffset`,`useSelectorFields`,`useSelectorQuery`,`useSlots`,`useTemplateRef`,`useUpdatePerformanceListener`,`version`,`vModelCheckbox`,`vModelRadio`,`vModelSelect`,`vModelText`,`vShow`,`withDirectives`,`waitForLayoutHost`,`watch`,`watchEffect`,`watchPostEffect`,`watchSyncEffect`]);function ensureInternalRuntimeImport(program,importedName,localName=importedName){const runtimeImportPath=resolveWevuInternalImportModuleId(importedName);let targetImport=program.body.find(node=>t.isImportDeclaration(node)&&node.source.value===runtimeImportPath);if(!targetImport){targetImport=t.importDeclaration([],t.stringLiteral(runtimeImportPath));program.body.unshift(targetImport)}if(!targetImport.specifiers.some(specifier=>t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.imported,{name:importedName})&&t.isIdentifier(specifier.local,{name:localName})))targetImport.specifiers.push(t.importSpecifier(t.identifier(localName),t.identifier(importedName)))}function splitWevuNamedImportsToInternalRuntime(path,program,state){if(path.node.source.value!==`wevu`||path.node.importKind===`type`)return;const remaining=path.node.specifiers.filter(specifier=>{if(!t.isImportSpecifier(specifier)||specifier.importKind===`type`||!t.isIdentifier(specifier.imported)||!t.isIdentifier(specifier.local))return true;const importedName=specifier.imported.name;if(!INTERNAL_RUNTIME_VALUE_EXPORTS.has(importedName))return true;ensureInternalRuntimeImport(program,importedName,specifier.local.name);state.transformed=true;return false});if(remaining.length===0){path.remove();return}if(remaining.length!==path.node.specifiers.length)path.node.specifiers=remaining}function createImportVisitors(program,state){return{ImportDeclaration(path){if(path.node.source.value===`@vue/babel-helper-vue-transform-on`){const defaultImport=path.node.specifiers.find(specifier=>t.isImportDefaultSpecifier(specifier));if(defaultImport){ensureRuntimeImport(program,`transformOn`,defaultImport.local.name);state.transformed=true;path.remove();return}}if(path.node.source.value===`vue`){const movedVueRuntimeAPIs=/* @__PURE__ */ new Set([`createTextVNode`,`createVNode`,`Fragment`,`isVNode`,`mergeProps`,`resolveComponent`,`resolveDirective`,`unref`,`useAttrs`,`useCssModule`,`useCssVars`,`useSlots`,`useModel`,`mergeModels`,`useTemplateRef`,`vModelCheckbox`,`vModelRadio`,`vModelSelect`,`vModelText`,`vShow`,`withDirectives`]);const movedSpecifiers=[];const remaining=path.node.specifiers.filter(specifier=>{if(t.isImportSpecifier(specifier)&&specifier.imported.type===`Identifier`&&specifier.imported.name===WE_VU_RUNTIME_APIS.defineComponent){state.defineComponentAliases.add(specifier.local.name);state.transformed=true;return false}if(t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.imported)){const importedName=specifier.imported.name;if(movedVueRuntimeAPIs.has(importedName)&&t.isIdentifier(specifier.local)){movedSpecifiers.push({importedName,localName:specifier.local.name});state.transformed=true;return false}}return true});if(movedSpecifiers.length)for(const{importedName,localName}of movedSpecifiers)ensureRuntimeImport(program,importedName,localName);if(remaining.length===0){path.remove();return}path.node.specifiers=remaining}if(path.node.importKind===`type`){state.transformed=true;path.remove();return}const kept=path.node.specifiers.filter(specifier=>{if(`importKind`in specifier&&specifier.importKind===`type`){state.transformed=true;return false}return true});if(kept.length!==path.node.specifiers.length){if(kept.length===0){path.remove();return}path.node.specifiers=kept}splitWevuNamedImportsToInternalRuntime(path,program,state)}}}function createAppSetupVisitors(program,state){return{CallExpression(path){if(!t.isIdentifier(path.node.callee,{name:WE_VU_RUNTIME_APIS.defineAppSetup}))return;ensureRuntimeImport(program,WE_VU_RUNTIME_APIS.defineAppSetup);state.transformed=true}}}function importedName(specifier){return t.isIdentifier(specifier.imported)?specifier.imported.name:specifier.imported.value}function createPageMetaVisitors(ast,state){const macroCalls=new Set(collectPageMetaCallsForTransform(ast));return{ImportDeclaration(path){if(path.node.source.value!==`wevu`||path.node.importKind===`type`)return;const remaining=path.node.specifiers.filter(specifier=>{return!t.isImportSpecifier(specifier)||specifier.importKind===`type`||importedName(specifier)!==WEVU_DEFINE_PAGE_META_MACRO});if(remaining.length===path.node.specifiers.length)return;state.transformed=true;if(!remaining.length){path.remove();return}path.node.specifiers=remaining},CallExpression(path){if(!macroCalls.has(path.node)||!path.parentPath?.isExpressionStatement())return;path.parentPath.remove();state.transformed=true}}}function createSetupExposeVisitors(state){return{ObjectMethod(path){if(!t.isIdentifier(path.node.key,{name:`setup`})&&!t.isStringLiteral(path.node.key,{value:`setup`}))return;const params=path.node.params;if(params.length<2||!t.isObjectPattern(params[1]))return;const ctxParam=params[1];if(ctxParam.properties.some(property=>{if(!t.isObjectProperty(property))return false;return t.isIdentifier(property.key,{name:`expose`})&&t.isIdentifier(property.value,{name:`__expose`})})&&path.scope.hasBinding(`__expose`)&&!path.scope.hasBinding(`expose`)){path.scope.rename(`__expose`,`expose`);state.transformed=true;for(const property of ctxParam.properties){if(!t.isObjectProperty(property))continue;if(t.isIdentifier(property.key,{name:`expose`})&&t.isIdentifier(property.value,{name:`expose`}))property.shorthand=true}}}}}function isOptionalPatternNode(node){return t.isIdentifier(node)||t.isAssignmentPattern(node)||t.isRestElement(node)||t.isArrayPattern(node)||t.isObjectPattern(node)||t.isVoidPattern(node)}function stripOptionalFlag(node){if(node?.optional!==true)return false;node.optional=false;return true}function stripOptionalFromPattern(pattern){if(!pattern)return false;if(t.isTSParameterProperty(pattern))return stripOptionalFromPattern(pattern.parameter);let changed=false;if(t.isIdentifier(pattern)||t.isAssignmentPattern(pattern)||t.isRestElement(pattern)||t.isArrayPattern(pattern)||t.isObjectPattern(pattern))changed=stripOptionalFlag(pattern)||changed;if(t.isIdentifier(pattern)||t.isVoidPattern(pattern))return changed;if(t.isAssignmentPattern(pattern)){if(isOptionalPatternNode(pattern.left))changed=stripOptionalFromPattern(pattern.left)||changed;return changed}if(t.isRestElement(pattern)){if(isOptionalPatternNode(pattern.argument))changed=stripOptionalFromPattern(pattern.argument)||changed;return changed}if(t.isObjectPattern(pattern)){for(const prop of pattern.properties)if(t.isRestElement(prop)){if(isOptionalPatternNode(prop.argument)&&stripOptionalFromPattern(prop.argument))changed=true}else if(t.isObjectProperty(prop)){if(isOptionalPatternNode(prop.value)&&stripOptionalFromPattern(prop.value))changed=true}return changed}if(t.isArrayPattern(pattern)){for(const element of pattern.elements)if(isOptionalPatternNode(element)&&stripOptionalFromPattern(element))changed=true}return changed}function stripTypeArguments(node){let stripped=false;if(node.typeParameters){node.typeParameters=null;stripped=true}if(node.typeArguments){node.typeArguments=null;stripped=true}return stripped}function createStripTypesVisitors(state){return{ExportNamedDeclaration(path){if(path.node.exportKind===`type`){state.transformed=true;path.remove();return}if(path.node.specifiers?.length){const remaining=path.node.specifiers.filter(spec=>{if(t.isExportSpecifier(spec))return spec.exportKind!==`type`;return true});if(remaining.length!==path.node.specifiers.length){state.transformed=true;if(remaining.length===0){path.remove();return}path.node.specifiers=remaining}}},CallExpression(path){if(t.isIdentifier(path.node.callee,{name:`__expose`})&&path.parentPath?.isExpressionStatement()){if(path.node.arguments.length===0){path.parentPath.remove();state.transformed=true;return}}if(stripTypeArguments(path.node))state.transformed=true},NewExpression(path){if(stripTypeArguments(path.node))state.transformed=true},ObjectProperty(path){if(t.isIdentifier(path.node.key,{name:`__name`})||t.isStringLiteral(path.node.key,{value:`__name`})){path.remove();state.transformed=true}},TSTypeAliasDeclaration(path){path.remove();state.transformed=true},TSInterfaceDeclaration(path){path.remove();state.transformed=true},TSEnumDeclaration(path){path.remove();state.transformed=true},TSModuleDeclaration(path){path.remove();state.transformed=true},TSImportEqualsDeclaration(path){path.remove();state.transformed=true},TSAsExpression(path){path.replaceWith(path.node.expression);state.transformed=true},TSSatisfiesExpression(path){path.replaceWith(path.node.expression);state.transformed=true},TSTypeAssertion(path){path.replaceWith(path.node.expression);state.transformed=true},TSNonNullExpression(path){path.replaceWith(path.node.expression);state.transformed=true},TSTypeAnnotation(path){path.remove();state.transformed=true},TSParameterProperty(path){path.replaceWith(path.node.parameter);state.transformed=true},Function(path){if(t.isIdentifier(path.node.params[0],{name:`this`})){path.node.params.shift();state.transformed=true}if(path.node.returnType){path.node.returnType=null;state.transformed=true}if(stripTypeArguments(path.node))state.transformed=true;for(const param of path.node.params)if(stripOptionalFromPattern(param))state.transformed=true},ClassMethod(path){if(stripOptionalFlag(path.node))state.transformed=true},ClassPrivateMethod(path){if(stripOptionalFlag(path.node))state.transformed=true},ClassAccessorProperty(path){if(path.node.typeAnnotation){path.node.typeAnnotation=null;state.transformed=true}if(stripOptionalFlag(path.node))state.transformed=true},ClassProperty(path){if(path.node.typeAnnotation){path.node.typeAnnotation=null;state.transformed=true}if(stripOptionalFlag(path.node))state.transformed=true},ClassPrivateProperty(path){if(path.node.typeAnnotation){path.node.typeAnnotation=null;state.transformed=true}if(stripOptionalFlag(path.node))state.transformed=true}}}function createMacroVisitors(ast,state){const appSetupVisitors=createAppSetupVisitors(ast.program,state);const setupExposeVisitors=createSetupExposeVisitors(state);const stripTypesVisitors=createStripTypesVisitors(state);const pageMetaVisitors=createPageMetaVisitors(ast,state);const mergedVisitors={...appSetupVisitors,...setupExposeVisitors,...stripTypesVisitors,...pageMetaVisitors};mergedVisitors.CallExpression=path=>{appSetupVisitors.CallExpression?.(path);setupExposeVisitors.CallExpression?.(path);stripTypesVisitors.CallExpression?.(path);if(!path.removed)pageMetaVisitors.CallExpression?.(path)};return mergedVisitors}const absent$1={kind:`absent`};const unknown$1={kind:`unknown`};function unwrap$1(node){return t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node)||t.isParenthesizedExpression(node)?unwrap$1(node.expression):node}function isFactoryCall(path){if(!path.isCallExpression()||!t.isIdentifier(path.node.callee))return false;const binding=path.scope.getBinding(path.node.callee.name);return binding?.path.isImportSpecifier()&&t.isIdentifier(binding.path.node.imported,{name:`defineComponent`})&&binding.path.parentPath.isImportDeclaration()&&[`vue`,`wevu`,`wevu/internal-runtime`,`virtual:weapp-vite/runtime`].includes(binding.path.parentPath.node.source.value)}function isSafeReference$1(reference,visiting){let current=reference;while(current.parentPath){const parent=current.parentPath;if(parent.isExportDefaultDeclaration())return true;if(parent.isVariableDeclarator()&&t.isIdentifier(parent.node.id))return isSafeBinding(parent.scope.getBinding(parent.node.id.name),visiting);if(parent.isCallExpression()&&isFactoryCall(parent)){current=parent;continue}if(parent.isObjectProperty()&&!parent.node.computed||parent.isObjectExpression()||parent.isSpreadElement()||parent.isTSAsExpression()||parent.isTSSatisfiesExpression()||parent.isTSNonNullExpression()||parent.isParenthesizedExpression()){current=parent;continue}return false}return false}function isSafeBinding(binding,visiting=/* @__PURE__ */ new Set){if(!binding?.constant||!binding.path.isVariableDeclarator()||!binding.path.parentPath.isVariableDeclaration()||binding.path.parentPath.node.kind!==`const`||binding.path.parentPath.parentPath?.isExportNamedDeclaration())return false;if(visiting.has(binding.path.node))return false;const next=new Set(visiting).add(binding.path.node);return binding.referencePaths.every(reference=>isSafeReference$1(reference,next))}function resolve(node,scope,visited){node=unwrap$1(node);if(!t.isIdentifier(node)||node.name===`undefined`&&!scope?.getBinding(`undefined`))return{kind:`expression`,node,scope};const binding=scope?.getBinding(node.name);if(!isSafeBinding(binding)||!binding?.path.isVariableDeclarator()||visited.has(binding.path.node)||!binding.path.node.init||!t.isExpression(binding.path.node.init))return;return resolve(binding.path.node.init,binding.path.scope,new Set(visited).add(binding.path.node))}function primitive$1(node,scope){const resolved=resolve(node,scope,/* @__PURE__ */ new Set);if(!resolved)return unknown$1;const value=resolved.node;if(t.isStringLiteral(value)||t.isBooleanLiteral(value)||t.isNumericLiteral(value))return{kind:`known`,value:value.value};if(t.isNullLiteral(value))return{kind:`known`,value:null};if(t.isTemplateLiteral(value)&&value.expressions.length===0)return{kind:`known`,value:value.quasis[0]?.value.cooked??value.quasis[0]?.value.raw??``};if(t.isIdentifier(value,{name:`undefined`})&&!resolved.scope?.getBinding(`undefined`))return{kind:`known`,value:void 0};if(t.isUnaryExpression(value)&&t.isNumericLiteral(value.argument)){if(value.operator===`void`)return{kind:`known`,value:void 0};if(value.operator===`-`||value.operator===`+`)return{kind:`known`,value:value.operator===`-`?-value.argument.value:value.argument.value}}return unknown$1}function resolveStaticObjectProperty(node,key,scope,visited=/* @__PURE__ */ new Set){const resolved=resolve(node,scope,visited);if(!resolved||visited.has(resolved.node))return unknown$1;const current=resolved.node;const next=new Set(visited).add(current);if(t.isCallExpression(current)&&t.isMemberExpression(current.callee)&&!current.callee.computed&&t.isIdentifier(current.callee.object,{name:`Object`})&&!resolved.scope?.getBinding(`Object`)&&t.isIdentifier(current.callee.property,{name:`assign`})){let result=absent$1;for(const argument of current.arguments){const part=t.isExpression(argument)?resolveStaticObjectProperty(argument,key,resolved.scope,next):unknown$1;if(part.kind!==`absent`)result=part}return result}if(!t.isObjectExpression(current))return t.isNullLiteral(current)||t.isStringLiteral(current)||t.isBooleanLiteral(current)||t.isNumericLiteral(current)||t.isIdentifier(current,{name:`undefined`})&&!resolved.scope?.getBinding(`undefined`)?absent$1:unknown$1;let result=absent$1;for(const entry of current.properties){if(t.isSpreadElement(entry)){const part=resolveStaticObjectProperty(entry.argument,key,resolved.scope,next);if(part.kind!==`absent`)result=part;continue}const name=!entry.computed&&t.isIdentifier(entry.key)?{kind:`known`,value:entry.key.name}:t.isExpression(entry.key)?primitive$1(entry.key,resolved.scope):unknown$1;if(name.kind!==`known`)result=unknown$1;else if(String(name.value)===key)result=t.isObjectProperty(entry)&&t.isExpression(entry.value)?{kind:`expression`,node:entry.value,scope:resolved.scope,property:entry}:unknown$1}return result}function isSafeAssignOperand(node,scope,visited){const resolved=resolve(node,scope,visited);if(!resolved||visited.has(resolved.node)||!t.isObjectExpression(resolved.node))return false;const next=new Set(visited).add(resolved.node);return resolved.node.properties.every(entry=>{if(t.isSpreadElement(entry))return isSafeAssignOperand(entry.argument,resolved.scope,next);if(t.isObjectMethod(entry)&&entry.kind!==`method`)return false;const name=!entry.computed&&t.isIdentifier(entry.key)?{kind:`known`,value:entry.key.name}:t.isExpression(entry.key)?primitive$1(entry.key,resolved.scope):unknown$1;return name.kind===`known`&&name.value!==`__proto__`})}function hasUnsafeObjectEvaluation(node,scope,visited=/* @__PURE__ */ new Set){const resolved=resolve(node,scope,visited);if(!resolved||visited.has(resolved.node))return false;const current=resolved.node;const next=new Set(visited).add(current);if(t.isCallExpression(current)&&t.isMemberExpression(current.callee)&&!current.callee.computed&&t.isIdentifier(current.callee.object,{name:`Object`})&&t.isIdentifier(current.callee.property,{name:`assign`}))return Boolean(resolved.scope?.getBinding(`Object`))||current.arguments.some(argument=>!t.isExpression(argument)||!isSafeAssignOperand(argument,resolved.scope,/* @__PURE__ */ new Set)||hasUnsafeObjectEvaluation(argument,resolved.scope,next));if(t.isObjectExpression(current))return current.properties.some(entry=>{if(t.isSpreadElement(entry)){const operand=resolve(entry.argument,resolved.scope,next);return Boolean(operand&&t.isObjectExpression(operand.node)&&!isSafeAssignOperand(entry.argument,resolved.scope,next))||hasUnsafeObjectEvaluation(entry.argument,resolved.scope,next)}return t.isObjectProperty(entry)&&t.isExpression(entry.value)&&hasUnsafeObjectEvaluation(entry.value,resolved.scope,next)});return false}function analyzeComponentStyleOptions(node,scope){if(!node)return{styleIsolation:unknown$1,addGlobalClass:unknown$1};if(hasUnsafeObjectEvaluation(node,scope))return;const options=resolveStaticObjectProperty(node,`options`,scope);if([`definitionFilter`,`behaviors`,`extends`,`mixins`,`__proto__`].some(key=>resolveStaticObjectProperty(node,key,scope).kind!==`absent`))return;const read=key=>{const value=options.kind===`expression`?resolveStaticObjectProperty(options.node,key,options.scope):options;if(value.kind===`absent`)return absent$1;return value.kind===`expression`?primitive$1(value.node,value.scope):unknown$1};return{styleIsolation:read(`styleIsolation`),addGlobalClass:read(`addGlobalClass`)}}function isPlainRecord(value){if(!value||typeof value!==`object`||Array.isArray(value))return false;const proto=Object.getPrototypeOf(value);return proto===null||proto===Object.prototype}function isStaticObjectKeyMatch(key,expected){if(t.isIdentifier(key))return key.name===expected;if(t.isStringLiteral(key))return key.value===expected;return false}function getObjectPropertyByKey$2(node,key){for(const prop of node.properties){if(!t.isObjectProperty(prop)||prop.computed)continue;if(isStaticObjectKeyMatch(prop.key,key))return prop}return null}function createStaticObjectKey(key){return t.isValidIdentifier(key)?t.identifier(key):t.stringLiteral(key)}function mergeStableKeys(target,incoming){const seen=new Set(target);for(const key of incoming){if(!key||seen.has(key))continue;seen.add(key);target.push(key)}}function resolveOutputRoot(outputPath){return/^[A-Z_$][\w$]*/i.exec(outputPath)?.[0]}function resolveBindingManifestPickKeys(manifest,autoSetDataPick){const keys=[];if(!isBindingManifestComplete(manifest))return keys;const outputRoots=manifest.bindings.flatMap(binding=>{const root=resolveOutputRoot(binding.outputPath);return root?[root]:[]});if(manifest.bindings.some(binding=>{return binding.updateMode===`snapshot-fallback`&&!resolveOutputRoot(binding.outputPath)}))return keys;const requiresScopedSlotOwner=manifest.bindings.some(binding=>{return binding.outputPath===WEVU_SLOT_OWNER_ID_KEY||binding.outputPath===WEVU_SLOT_OWNER_ID_PROP});if(autoSetDataPick||requiresScopedSlotOwner)mergeStableKeys(keys,outputRoots);if(autoSetDataPick)mergeStableKeys(keys,[WEVU_SLOT_NAMES_PROP,WEVU_SLOT_OWNER_ID_PROP,WEVU_SLOT_SCOPE_KEY]);if(requiresScopedSlotOwner)mergeStableKeys(keys,[WEVU_SLOT_OWNER_ID_KEY,WEVU_SLOT_NAMES_PROP,WEVU_SLOT_OWNER_ID_PROP,WEVU_SLOT_SCOPE_KEY]);return keys}function mergePickArray(array,keys){const existing=/* @__PURE__ */ new Set;for(const element of array.elements)if(t.isStringLiteral(element))existing.add(element.value);let changed=false;for(const key of keys){if(existing.has(key))continue;existing.add(key);array.elements.push(t.stringLiteral(key));changed=true}return changed}function injectSetDataPick(componentOptions,keys){if(!keys.length)return false;const pickArray=()=>t.arrayExpression(keys.map(key=>t.stringLiteral(key)));const setDataProp=getObjectPropertyByKey$2(componentOptions,`setData`);if(!setDataProp){componentOptions.properties.unshift(t.objectProperty(t.identifier(`setData`),t.objectExpression([t.objectProperty(t.identifier(`pick`),pickArray())])));return true}if(t.isObjectExpression(setDataProp.value)){const pickProp=getObjectPropertyByKey$2(setDataProp.value,`pick`);if(!pickProp){setDataProp.value.properties.unshift(t.objectProperty(t.identifier(`pick`),pickArray()));return true}return t.isArrayExpression(pickProp.value)&&mergePickArray(pickProp.value,keys)}if(t.isIdentifier(setDataProp.value)||t.isMemberExpression(setDataProp.value)||t.isCallExpression(setDataProp.value)){setDataProp.value=t.objectExpression([t.objectProperty(t.identifier(`pick`),pickArray()),t.spreadElement(t.cloneNode(setDataProp.value,true))]);return true}return false}function injectManifestMetadata(componentOptions,manifest,mode){const serialized=createRuntimeBindingManifest(manifest,mode);const value=t.callExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`freeze`)),[t.valueToNode(serialized)]);const existing=getObjectPropertyByKey$2(componentOptions,WEVU_BINDING_MANIFEST_KEY);if(existing){existing.value=value;return true}componentOptions.properties.push(t.objectProperty(t.stringLiteral(WEVU_BINDING_MANIFEST_KEY),value));return true}function injectLayoutComputed(componentOptions,plan){const runtimeEntries=Object.entries(plan?.currentLayout?.props??{}).filter(entry=>{const value=entry[1];return typeof value===`object`&&value!==null&&value.kind===`expression`});if(!runtimeEntries.length)return false;const computedEntries=runtimeEntries.map(([key,value])=>{const expression=parseBabelExpression(value.expression)??t.identifier(`undefined`);return t.objectProperty(createStaticObjectKey(`${WEVU_LAYOUT_BIND_PREFIX}${key}`),t.functionExpression(null,[],t.blockStatement([t.tryStatement(t.blockStatement([t.returnStatement(t.cloneNode(expression,true))]),t.catchClause(t.identifier(WEVU_EXPRESSION_ERROR_IDENTIFIER),t.blockStatement([t.returnStatement(t.identifier(`undefined`))])))])))});const computedProp=getObjectPropertyByKey$2(componentOptions,`computed`);if(!computedProp){componentOptions.properties.unshift(t.objectProperty(t.identifier(`computed`),t.objectExpression(computedEntries)));return true}if(t.isObjectExpression(computedProp.value)){computedProp.value.properties.push(...computedEntries);return true}if(t.isIdentifier(computedProp.value)||t.isMemberExpression(computedProp.value)){computedProp.value=t.objectExpression([...computedEntries,t.spreadElement(t.cloneNode(computedProp.value,true))]);return true}return false}function injectBindingManifestContract(componentOptions,options){let changed=injectLayoutComputed(componentOptions,options.pageLayout);if(!options.manifest)return changed;changed=injectManifestMetadata(componentOptions,options.manifest,options.runtimeBindingManifest??`compact`)||changed;changed=injectSetDataPick(componentOptions,resolveBindingManifestPickKeys(options.manifest,options.autoSetDataPick===true))||changed;return changed}function injectClassStyleComputed(optionsObject,bindings,propsAliases,warn){if(!bindings.length)return false;const warnHandler=resolveWarnHandler(warn);const helpers={normalizeClass:t.identifier(`__wevuNormalizeClass`),normalizeStyle:t.identifier(`__wevuNormalizeStyle`),unref:t.identifier(`__wevuUnref`),resolvePropValue:t.identifier(`__wevuResolvePropValue`)};const entries=buildClassStyleComputedEntries(bindings,helpers,propsAliases);if(!entries.length)return false;const computedProp=getObjectPropertyByKey$2(optionsObject,`computed`);if(!computedProp){optionsObject.properties.splice(0,0,t.objectProperty(createStaticObjectKey(`computed`),t.objectExpression(entries)));return true}if(t.isObjectExpression(computedProp.value)){computedProp.value.properties.push(...entries);return true}if(t.isIdentifier(computedProp.value)||t.isMemberExpression(computedProp.value)){computedProp.value=t.objectExpression([...entries,t.spreadElement(t.cloneNode(computedProp.value,true))]);return true}warnHandler(`无法自动注入 class/style 计算属性,请手动合并 computed。`);return false}function ensureClassStyleRuntimeImports(program){ensureRuntimeImport(program,`normalizeClass`,`__wevuNormalizeClass`);ensureRuntimeImport(program,`normalizeStyle`,`__wevuNormalizeStyle`);ensureRuntimeImport(program,`unref`,`__wevuUnref`);ensureRuntimeImport(program,`resolvePropValue`,`__wevuResolvePropValue`)}function unwrapExpression$1(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node)||t.isParenthesizedExpression(node))return unwrapExpression$1(node.expression);return node}function resolveSetupFunction$1(componentOptionsObject){for(const prop of componentOptionsObject.properties){if(t.isObjectMethod(prop)&&!prop.computed&&isStaticObjectKeyMatch(prop.key,`setup`))return prop;if(!t.isObjectProperty(prop)||prop.computed||!isStaticObjectKeyMatch(prop.key,`setup`))continue;const value=unwrapExpression$1(prop.value);if(t.isFunctionExpression(value)||t.isArrowFunctionExpression(value))return value}return null}function isComponentMetaObject(node){return node.properties.some(prop=>{return t.isObjectProperty(prop)&&!prop.computed&&isStaticObjectKeyMatch(prop.key,`__weappViteUsingComponent`)&&t.isBooleanLiteral(prop.value,{value:true})})}function isSerializableSeed(node){const normalized=unwrapExpression$1(node);if(t.isStringLiteral(normalized)||t.isNumericLiteral(normalized)||t.isBooleanLiteral(normalized)||t.isNullLiteral(normalized))return true;if(t.isTemplateLiteral(normalized))return normalized.expressions.length===0;if(t.isArrayExpression(normalized))return normalized.elements.every(element=>!!element&&!t.isSpreadElement(element)&&isSerializableSeed(element));if(t.isObjectExpression(normalized)){if(isComponentMetaObject(normalized))return false;return normalized.properties.every(prop=>{return t.isObjectProperty(prop)&&!prop.computed&&!t.isPatternLike(prop.value)&&isSerializableSeed(prop.value)})}return false}function extractSeedExpression(node){const normalized=unwrapExpression$1(node);if(t.isCallExpression(normalized)&&t.isIdentifier(normalized.callee)&&[`ref`,`shallowRef`,`reactive`].includes(normalized.callee.name)){const firstArg=normalized.arguments[0];if(firstArg&&!t.isSpreadElement(firstArg)&&t.isExpression(firstArg)&&isSerializableSeed(firstArg))return t.cloneNode(unwrapExpression$1(firstArg),true);return null}if(!isSerializableSeed(normalized))return null;return t.cloneNode(normalized,true)}function collectSetupInitializers(setupBody){const initializers=/* @__PURE__ */ new Map;for(const statement of setupBody.body){if(!t.isVariableDeclaration(statement))continue;for(const declarator of statement.declarations){if(!t.isIdentifier(declarator.id)||!declarator.init||!t.isExpression(declarator.init))continue;initializers.set(declarator.id.name,declarator.init)}}return initializers}function resolveReturnedObjectExpression(setupBody,initializers){for(let index=setupBody.body.length-1;index>=0;index-=1){const statement=setupBody.body[index];if(!t.isReturnStatement(statement)||!statement.argument||!t.isExpression(statement.argument))continue;const returned=unwrapExpression$1(statement.argument);if(t.isObjectExpression(returned))return returned;if(t.isIdentifier(returned)){const initializer=initializers.get(returned.name);if(initializer){const normalized=unwrapExpression$1(initializer);if(t.isObjectExpression(normalized))return normalized}}}return null}function resolvePropertyName(node){if(t.isIdentifier(node.key)&&!node.computed)return node.key.name;if(t.isStringLiteral(node.key)&&!node.computed)return node.key.value;return null}function injectSetupInitialData(componentOptionsObject){if(getObjectPropertyByKey$2(componentOptionsObject,`data`))return false;const setupFn=resolveSetupFunction$1(componentOptionsObject);if(!setupFn||!t.isBlockStatement(setupFn.body))return false;const initializers=collectSetupInitializers(setupFn.body);const returnedObject=resolveReturnedObjectExpression(setupFn.body,initializers);if(!returnedObject)return false;const seedProperties=[];for(const prop of returnedObject.properties){if(!t.isObjectProperty(prop)||prop.computed)continue;const propertyName=resolvePropertyName(prop);if(!propertyName)continue;let sourceExpression=null;if(prop.shorthand&&t.isIdentifier(prop.value))sourceExpression=initializers.get(prop.value.name)??null;else if(t.isIdentifier(prop.value))sourceExpression=initializers.get(prop.value.name)??prop.value;else if(t.isExpression(prop.value))sourceExpression=prop.value;if(!sourceExpression)continue;const seedExpression=extractSeedExpression(sourceExpression);if(!seedExpression)continue;seedProperties.push(t.objectProperty(createStaticObjectKey(propertyName),seedExpression))}if(!seedProperties.length)return false;componentOptionsObject.properties.unshift(t.objectMethod(`method`,createStaticObjectKey(`data`),[],t.blockStatement([t.returnStatement(t.objectExpression(seedProperties))])));return true}function resolveImportedLocalName(program,source,importedName){for(const statement of program.body){if(!t.isImportDeclaration(statement)||statement.importKind===`type`||statement.source.value!==source)continue;for(const specifier of statement.specifiers)if(t.isImportSpecifier(specifier)&&specifier.importKind!==`type`&&t.isIdentifier(specifier.imported,{name:importedName}))return specifier.local.name}}function createEmptyCssVarsRegistration(useCssVarsLocalName,unrefLocalName){return t.expressionStatement(t.callExpression(t.identifier(useCssVarsLocalName),[t.arrowFunctionExpression([],t.blockStatement([t.expressionStatement(t.callExpression(t.identifier(unrefLocalName),[t.identifier(`undefined`)])),t.returnStatement(t.objectExpression([]))]))]))}function injectStableCssVarsRuntime(program,componentOptionsObject,scope){const runtimeImportPath=resolveWevuInternalImportModuleId(`useCssVars`);const reactivityImportPath=resolveWevuInternalImportModuleId(`unref`);const useCssVarsLocalName=resolveImportedLocalName(program,runtimeImportPath,`useCssVars`)??scope.generateUidIdentifier(`useCssVars`).name;const unrefLocalName=resolveImportedLocalName(program,reactivityImportPath,`unref`)??scope.generateUidIdentifier(`unref`).name;if(!resolveImportedLocalName(program,runtimeImportPath,`useCssVars`))ensureRuntimeImport(program,`useCssVars`,useCssVarsLocalName);if(!resolveImportedLocalName(program,reactivityImportPath,`unref`))ensureRuntimeImport(program,`unref`,unrefLocalName);const registration=createEmptyCssVarsRegistration(useCssVarsLocalName,unrefLocalName);const setupFn=resolveSetupFunction$1(componentOptionsObject);if(setupFn){const body=setupFn.body;if(t.isBlockStatement(body))body.body.unshift(registration);else setupFn.body=t.blockStatement([registration,t.returnStatement(body)]);return true}componentOptionsObject.properties.push(t.objectMethod(`method`,t.identifier(`setup`),[],t.blockStatement([registration,t.returnStatement(t.objectExpression([]))])));return true}function resolveDefaultsTarget(node){if(t.isObjectExpression(node))return node;if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node)||t.isParenthesizedExpression(node))return resolveDefaultsTarget(node.expression);if(t.isCallExpression(node)&&t.isMemberExpression(node.callee)&&!node.callee.computed&&t.isIdentifier(node.callee.object,{name:`Object`})&&t.isIdentifier(node.callee.property,{name:`assign`})){const first=node.arguments[0];return first&&t.isExpression(first)?resolveDefaultsTarget(first):void 0}}function applyDefaultsToExpression(expression,defaults,merge){let changed=false;const fallback=resolveDefaultsTarget(expression);for(const[key,value]of Object.entries(defaults)){const effective=resolveStaticObjectProperty(expression,key,void 0);if(effective.kind===`expression`&&effective.property){const normalized=t.objectProperty(t.stringLiteral(key),effective.property.value);changed=merge(t.objectExpression([normalized]),{[key]:value})||changed;effective.property.value=normalized.value}else if(effective.kind===`absent`&&fallback)changed=merge(fallback,{[key]:value})||changed;else if(effective.kind===`unknown`&&fallback)changed=merge(fallback,{[key]:value})||changed}return changed}function mergePlainDefaultsIntoObjectExpression(target,defaults){const entries=Object.entries(defaults);if(!entries.length)return false;let changed=false;const injectedProps=[];for(const[key,value]of entries){if(getObjectPropertyByKey$2(target,key))continue;injectedProps.push(t.objectProperty(createStaticObjectKey(key),t.valueToNode(value)))}if(!injectedProps.length)return false;target.properties.splice(0,0,...injectedProps);changed=true;return changed}function mergeNestedDefaults(optionsObject,key,defaultsValue){if(!isPlainRecord(defaultsValue)){if(defaultsValue===void 0)return false;if(getObjectPropertyByKey$2(optionsObject,key))return false;optionsObject.properties.splice(0,0,t.objectProperty(createStaticObjectKey(key),t.valueToNode(defaultsValue)));return true}const existing=getObjectPropertyByKey$2(optionsObject,key);if(!existing){optionsObject.properties.splice(0,0,t.objectProperty(createStaticObjectKey(key),t.valueToNode(defaultsValue)));return true}if(t.isObjectExpression(existing.value))return mergePlainDefaultsIntoObjectExpression(existing.value,defaultsValue);if(t.isIdentifier(existing.value)||t.isMemberExpression(existing.value)){const injected=t.valueToNode(defaultsValue);if(t.isObjectExpression(injected)){injected.properties.push(t.spreadElement(t.cloneNode(existing.value,true)));existing.value=injected;return true}}return false}function applyWevuDefaultsToOptionsObject(optionsObject,defaults){let changed=false;for(const[key,value]of Object.entries(defaults)){if(key===`setData`||key===`options`){changed=mergeNestedDefaults(optionsObject,key,value)||changed;continue}if(value===void 0||getObjectPropertyByKey$2(optionsObject,key))continue;optionsObject.properties.splice(0,0,t.objectProperty(createStaticObjectKey(key),t.valueToNode(value)));changed=true}return changed}function stripVirtualHostFromDefaults(defaults){const next={...defaults};const options=next.options;if(!isPlainRecord(options))return next;if(!hasOwn(options,`virtualHost`))return next;const copiedOptions={...options};delete copiedOptions.virtualHost;if(Object.keys(copiedOptions).length>0)next.options=copiedOptions;else delete next.options;return next}function serializeWevuDefaults(defaults,warn){const warnHandler=resolveWarnHandler(warn);const seen=/* @__PURE__ */ new Set;try{return JSON.stringify(defaults,(_key,value)=>{if(typeof value===`function`||typeof value===`symbol`||typeof value===`bigint`)throw new TypeError(`Wevu defaults 必须可被 JSON 序列化。`);if(value&&typeof value===`object`){if(seen.has(value))throw new Error(`Wevu defaults 不能包含循环引用。`);seen.add(value);if(!Array.isArray(value)&&!isPlainRecord(value))throw new Error(`Wevu defaults 只能是普通对象或数组。`)}return value})}catch(error){warnHandler(`[vue] 序列化 wevu defaults 失败:${error instanceof Error?error.message:String(error)}`);return}}function insertWevuDefaultsCall(program,serializedDefaults){const callStatement=t.expressionStatement(t.callExpression(t.identifier(WE_VU_RUNTIME_APIS.setWevuDefaults),[t.valueToNode(JSON.parse(serializedDefaults))]));let insertIndex=0;while(insertIndex<program.body.length&&t.isImportDeclaration(program.body[insertIndex]))insertIndex+=1;program.body.splice(insertIndex,0,callStatement)}function applyWevuDefaultsToComponentOptions(params){const{componentExpr,parsedWevuDefaults,options}=params;let changed=false;if(options?.isApp&&parsedWevuDefaults.app&&Object.keys(parsedWevuDefaults.app).length>0)changed=applyDefaultsToExpression(componentExpr,parsedWevuDefaults.app,applyWevuDefaultsToOptionsObject)||changed;if(!options?.isApp&&parsedWevuDefaults.component&&Object.keys(parsedWevuDefaults.component).length>0){const componentDefaults=options?.isPage?stripVirtualHostFromDefaults(parsedWevuDefaults.component):parsedWevuDefaults.component;if(Object.keys(componentDefaults).length>0)changed=applyDefaultsToExpression(componentExpr,componentDefaults,applyWevuDefaultsToOptionsObject)||changed}const componentOptionDefaults=parsedWevuDefaults.component?.options;if(options?.isPage&&isPlainRecord(componentOptionDefaults)&&componentOptionDefaults.virtualHost===true)changed=applyDefaultsToExpression(componentExpr,{options:{virtualHost:false}},applyWevuDefaultsToOptionsObject)||changed;return changed}function injectWevuDefaultsForApp(params){const{astProgram,options,serializedWevuDefaults}=params;let changed=false;if(options?.isApp&&serializedWevuDefaults){ensureRuntimeImport(astProgram,WE_VU_RUNTIME_APIS.setWevuDefaults);insertWevuDefaultsCall(astProgram,serializedWevuDefaults);changed=true}return changed}function rewriteComponentExport(params){const{ast,exportPath,componentExpr,isAppFile,skipComponentTransform}=params;const DEFAULT_OPTIONS_IDENTIFIER=`__wevuOptions`;if(isAppFile){ensureRuntimeImport(ast.program,WE_VU_RUNTIME_APIS.createApp);exportPath.replaceWith(t.expressionStatement(t.callExpression(t.identifier(WE_VU_RUNTIME_APIS.createApp),[componentExpr])));return true}if(skipComponentTransform){exportPath.replaceWith(t.exportDefaultDeclaration(componentExpr));return true}ensureRuntimeImport(ast.program,WE_VU_RUNTIME_APIS.createWevuComponent);exportPath.replaceWithMultiple([t.variableDeclaration(`const`,[t.variableDeclarator(t.identifier(DEFAULT_OPTIONS_IDENTIFIER),componentExpr)]),t.expressionStatement(t.callExpression(t.identifier(WE_VU_RUNTIME_APIS.createWevuComponent),[t.identifier(DEFAULT_OPTIONS_IDENTIFIER)])),t.exportDefaultDeclaration(t.identifier(DEFAULT_OPTIONS_IDENTIFIER))]);return true}function createUnrefImport(program){const names=/* @__PURE__ */ new Set;let scope;traverse(t.file(program),{Program(path){scope=path.scope},Identifier(path){names.add(path.node.name)}});let identifier;do identifier=scope.generateUidIdentifier(`wevuInlineUnref`);while(names.has(identifier.name));ensureRuntimeImport(program,`unref`,identifier.name);return identifier}function buildMethodsMergeFromSpreadSources(componentExpr,inlineMapExpr){const spreadSources=[];for(const prop of componentExpr.properties){if(!t.isSpreadElement(prop)||!t.isExpression(prop.argument))continue;const methodsAccess=t.optionalMemberExpression(t.cloneNode(prop.argument),t.identifier(`methods`),false,true);spreadSources.push(t.logicalExpression(`||`,methodsAccess,t.objectExpression([])))}if(!spreadSources.length)return null;return t.callExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`assign`)),[t.objectExpression([]),...spreadSources,t.objectExpression([t.objectProperty(createStaticObjectKey(WEVU_INLINE_MAP_KEY),inlineMapExpr)])])}function injectInlineExpressions(componentExpr,inlineExpressions,program){if(!inlineExpressions.length)return false;const needsUnref=inlineExpressions.some(entry=>entry.runtimeHelpers?.unref);if(needsUnref&&!program)throw new Error(`注入 maybe-ref 内联表达式需要宿主脚本 AST。`);const inlineMapExpr=buildInlineExpressionMap(inlineExpressions,needsUnref?createUnrefImport(program):void 0);const methodsProp=getObjectPropertyByKey$2(componentExpr,`methods`);if(!methodsProp){const mergedMethods=buildMethodsMergeFromSpreadSources(componentExpr,inlineMapExpr);if(mergedMethods){componentExpr.properties.push(t.objectProperty(createStaticObjectKey(`methods`),mergedMethods));return true}componentExpr.properties.push(t.objectProperty(createStaticObjectKey(`methods`),t.objectExpression([t.objectProperty(createStaticObjectKey(WEVU_INLINE_MAP_KEY),inlineMapExpr)])));return true}if(!t.isObjectExpression(methodsProp.value))return false;const mapProp=getObjectPropertyByKey$2(methodsProp.value,WEVU_INLINE_MAP_KEY);if(!mapProp){methodsProp.value.properties.push(t.objectProperty(createStaticObjectKey(WEVU_INLINE_MAP_KEY),inlineMapExpr));return true}if(t.isObjectExpression(mapProp.value)){mapProp.value.properties.push(...inlineMapExpr.properties);return true}return false}function buildLayoutHostEntry(binding){const props=[t.objectProperty(t.identifier(`key`),t.stringLiteral(binding.key))];if(binding.refName)props.push(t.objectProperty(t.identifier(`refName`),t.stringLiteral(binding.refName)));props.push(t.objectProperty(t.identifier(`selector`),t.stringLiteral(binding.selector)));if(binding.kind)props.push(t.objectProperty(t.identifier(`kind`),t.stringLiteral(binding.kind)));return t.objectExpression(props)}function injectLayoutHosts(optionsObject,bindings,warn){if(!bindings.length)return false;const warnHandler=resolveWarnHandler(warn);const entries=bindings.map(binding=>buildLayoutHostEntry(binding));const hostsArray=t.arrayExpression(entries);const key=createStaticObjectKey(WEVU_LAYOUT_HOSTS_KEY);const existing=getObjectPropertyByKey$2(optionsObject,WEVU_LAYOUT_HOSTS_KEY);if(!existing){optionsObject.properties.push(t.objectProperty(key,hostsArray));return true}if(t.isArrayExpression(existing.value)){existing.value.elements.push(...entries);return true}if(t.isIdentifier(existing.value)||t.isMemberExpression(existing.value)){existing.value=t.arrayExpression([...entries,t.spreadElement(t.cloneNode(existing.value,true))]);return true}warnHandler(`无法自动注入 layout host 元数据,请手动合并 ${WEVU_LAYOUT_HOSTS_KEY}。`);return false}function injectPropsAliases(optionsObject,propsAliases){const entries=Object.entries(propsAliases??{}).filter(([alias,propName])=>alias&&propName).map(([alias,propName])=>{return t.objectProperty(createStaticObjectKey(alias),t.stringLiteral(propName))});if(!entries.length)return false;if(getObjectPropertyByKey$2(optionsObject,WEVU_PROPS_ALIASES_KEY))return false;optionsObject.properties.push(t.objectProperty(createStaticObjectKey(WEVU_PROPS_ALIASES_KEY),t.objectExpression(entries)));return true}function injectPropsDerivedKeys(optionsObject,propsDerivedKeys){const keys=[...new Set(propsDerivedKeys??[])].filter(Boolean);if(!keys.length)return false;if(getObjectPropertyByKey$2(optionsObject,WEVU_PROPS_DERIVED_KEYS_KEY))return false;optionsObject.properties.push(t.objectProperty(createStaticObjectKey(WEVU_PROPS_DERIVED_KEYS_KEY),t.arrayExpression(keys.map(key=>t.stringLiteral(key)))));return true}function buildTemplateRefEntry(binding){const props=[t.objectProperty(t.identifier(`selector`),t.stringLiteral(binding.selector)),t.objectProperty(t.identifier(`inFor`),t.booleanLiteral(binding.inFor))];if(binding.name)props.push(t.objectProperty(t.identifier(`name`),t.stringLiteral(binding.name)));if(binding.expAst){const body=t.blockStatement([t.returnStatement(t.cloneNode(binding.expAst,true))]);props.push(t.objectProperty(t.identifier(`get`),t.functionExpression(null,[],body)))}if(binding.kind)props.push(t.objectProperty(t.identifier(`kind`),t.stringLiteral(binding.kind)));return t.objectExpression(props)}function injectTemplateRefs(optionsObject,bindings,warn){if(!bindings.length)return false;const warnHandler=resolveWarnHandler(warn);const entries=bindings.map(binding=>buildTemplateRefEntry(binding));const refsArray=t.arrayExpression(entries);const key=createStaticObjectKey(WEVU_TEMPLATE_REFS_KEY);const existing=getObjectPropertyByKey$2(optionsObject,WEVU_TEMPLATE_REFS_KEY);if(!existing){optionsObject.properties.push(t.objectProperty(key,refsArray));return true}if(t.isArrayExpression(existing.value)){existing.value.elements.push(...entries);return true}if(t.isIdentifier(existing.value)||t.isMemberExpression(existing.value)){existing.value=t.arrayExpression([...entries,t.spreadElement(t.cloneNode(existing.value,true))]);return true}warnHandler(`无法自动注入 template ref 元数据,请手动合并 ${WEVU_TEMPLATE_REFS_KEY}。`);return false}function hasStaticProperty(target,keyName){for(const prop of target.properties){if(prop.type!==`ObjectProperty`&&prop.type!==`ObjectMethod`||prop.computed)continue;const key=prop.key;if(key.type===`Identifier`&&key.name===keyName)return true;if(key.type===`StringLiteral`&&key.value===keyName)return true}return false}function injectFunctionPropPaths(componentOptionsObject,paths){const uniquePaths=[...new Set(paths)].filter(Boolean);if(!uniquePaths.length)return false;if(hasStaticProperty(componentOptionsObject,WEVU_FUNCTION_PROP_PATHS_KEY))return false;componentOptionsObject.properties.push(t.objectProperty(t.identifier(WEVU_FUNCTION_PROP_PATHS_KEY),t.arrayExpression(uniquePaths.map(path=>t.stringLiteral(path)))));return true}function createObjectLiteral(value){return t.objectExpression(Object.entries(value).map(([key,item])=>t.objectProperty(t.stringLiteral(key),item&&typeof item===`object`&&!Array.isArray(item)?createObjectLiteral(item):t.valueToNode(item))))}function injectCssModules(componentOptionsObject,modules){if(hasStaticProperty(componentOptionsObject,WEVU_CSS_MODULES_KEY))return false;componentOptionsObject.properties.push(t.objectProperty(t.stringLiteral(WEVU_CSS_MODULES_KEY),createObjectLiteral(modules)));return true}function createScopedSlotHostPropertyDefinition(typeName,value){return t.objectExpression([t.objectProperty(t.identifier(`type`),typeName===`String`?t.identifier(`String`):t.nullLiteral()),t.objectProperty(t.identifier(`value`),value===null?t.nullLiteral():t.stringLiteral(value))])}function createScopedSlotHostProperties(){return[t.objectProperty(t.identifier(WEVU_SLOT_NAMES_PROP),createScopedSlotHostPropertyDefinition(`null`,null)),t.objectProperty(t.identifier(WEVU_SLOT_OWNER_ID_PROP),createScopedSlotHostPropertyDefinition(`String`,``)),t.objectProperty(t.identifier(WEVU_SLOT_SCOPE_KEY),createScopedSlotHostPropertyDefinition(`null`,null))]}function injectScopedSlotHostProperties(componentOptionsObject){const propertiesProp=getObjectPropertyByKey$2(componentOptionsObject,`properties`);if(!propertiesProp){componentOptionsObject.properties.splice(0,0,t.objectProperty(t.identifier(`properties`),t.objectExpression(createScopedSlotHostProperties())));return true}if(!t.isObjectExpression(propertiesProp.value))return false;let changed=false;for(const prop of createScopedSlotHostProperties().reverse()){const key=t.isIdentifier(prop.key)?prop.key.name:void 0;if(!key||getObjectPropertyByKey$2(propertiesProp.value,key))continue;propertiesProp.value.properties.unshift(prop);changed=true}return changed}function injectScopedSlotOwnerRequirement(componentOptionsObject){if(hasStaticProperty(componentOptionsObject,WEVU_SCOPED_SLOT_OWNER_REQUIRED_KEY))return false;componentOptionsObject.properties.push(t.objectProperty(t.identifier(WEVU_SCOPED_SLOT_OWNER_REQUIRED_KEY),t.booleanLiteral(true)));return true}function unwrapTypeLikeExpression(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node))return unwrapTypeLikeExpression(node.expression);if(t.isParenthesizedExpression(node))return unwrapTypeLikeExpression(node.expression);return node}function isStructuredRuntimeType(node){return t.isIdentifier(node,{name:`Array`})||t.isIdentifier(node,{name:`Object`})}function shouldRelaxStructuredPropType(node){const normalized=unwrapTypeLikeExpression(node);if(isStructuredRuntimeType(normalized))return true;if(!t.isArrayExpression(normalized)||normalized.elements.length===0)return false;return normalized.elements.every(element=>{if(!element||t.isSpreadElement(element)||!t.isExpression(element))return false;return isStructuredRuntimeType(unwrapTypeLikeExpression(element))})}function relaxStructuredTypeOnlyProps(componentOptionsObject){const propsProp=getObjectPropertyByKey$2(componentOptionsObject,`props`);if(!propsProp||!t.isExpression(propsProp.value))return false;const propsValue=unwrapTypeLikeExpression(propsProp.value);if(!t.isObjectExpression(propsValue))return false;let changed=false;for(const prop of propsValue.properties){if(!t.isObjectProperty(prop)||prop.computed||!t.isExpression(prop.value))continue;const definition=unwrapTypeLikeExpression(prop.value);if(!t.isObjectExpression(definition))continue;const typeProp=getObjectPropertyByKey$2(definition,`type`);if(!typeProp||!t.isExpression(typeProp.value))continue;if(!shouldRelaxStructuredPropType(typeProp.value))continue;typeProp.value=t.nullLiteral();changed=true}return changed}function isObjectAssignCall(node){const callee=node.callee;return t.isMemberExpression(callee)&&t.isIdentifier(callee.object,{name:`Object`})&&t.isIdentifier(callee.property,{name:`assign`})}function resolveObjectExpressionFromProgram(program,name){for(let index=program.body.length-1;index>=0;index-=1){const statement=program.body[index];if(!t.isVariableDeclaration(statement))continue;for(const declarator of statement.declarations){if(!t.isIdentifier(declarator.id,{name})||!declarator.init||!t.isExpression(declarator.init))continue;const normalized=unwrapTypeLikeExpression(declarator.init);if(t.isObjectExpression(normalized))return normalized;if(t.isCallExpression(normalized)&&isObjectAssignCall(normalized)){const lastArg=normalized.arguments[normalized.arguments.length-1];if(lastArg&&!t.isSpreadElement(lastArg)&&t.isExpression(lastArg)){const lastNormalized=unwrapTypeLikeExpression(lastArg);if(t.isObjectExpression(lastNormalized))return lastNormalized}}}}return null}function hasStaticPropertyWithSpreads(target,keyName,program,visited=/* @__PURE__ */ new Set){if(hasStaticProperty(target,keyName))return true;for(const prop of target.properties){if(!t.isSpreadElement(prop))continue;const spreadArg=prop.argument;if(t.isObjectExpression(spreadArg)&&hasStaticPropertyWithSpreads(spreadArg,keyName,program,visited))return true;if(!t.isIdentifier(spreadArg)||visited.has(spreadArg.name))continue;visited.add(spreadArg.name);const resolved=resolveObjectExpressionFromProgram(program,spreadArg.name);if(resolved&&hasStaticPropertyWithSpreads(resolved,keyName,program,visited))return true}return false}function hasStaticPropertyInComponentExpression(componentExpr,keyName,program){const normalized=unwrapTypeLikeExpression(componentExpr);if(t.isObjectExpression(normalized))return hasStaticPropertyWithSpreads(normalized,keyName,program);if(!t.isCallExpression(normalized)||!isObjectAssignCall(normalized))return false;for(const arg of normalized.arguments){if(t.isSpreadElement(arg)||!t.isExpression(arg))continue;const expr=unwrapTypeLikeExpression(arg);if(t.isObjectExpression(expr)&&hasStaticPropertyWithSpreads(expr,keyName,program))return true;if(t.isIdentifier(expr)){const resolved=resolveObjectExpressionFromProgram(program,expr.name);if(resolved&&hasStaticPropertyWithSpreads(resolved,keyName,program,/* @__PURE__ */ new Set([expr.name])))return true}}return false}function rewriteDefaultExport(ast,state,options,enabledPageFeatures,serializedWevuDefaults,parsedWevuDefaults){if(!state.defaultExportPath)return false;const warn=resolveWarnHandler(options?.warn);let transformed=false;const exportPath=state.defaultExportPath;const componentExpr=resolveComponentExpression(exportPath.node.declaration,state.defineComponentDecls,state.defineComponentAliases);const componentOptionsObject=resolveComponentOptionsObject(componentExpr);const hasPageMarker=componentExpr?hasStaticPropertyInComponentExpression(componentExpr,WEVU_IS_PAGE_KEY,ast.program):false;if(componentOptionsObject&&!options?.isApp&&!hasPageMarker){componentOptionsObject.properties.splice(0,0,t.objectProperty(t.identifier(WEVU_IS_PAGE_KEY),t.booleanLiteral(options?.isPage===true)));transformed=true}if(componentOptionsObject&&enabledPageFeatures.size)transformed=injectWevuPageFeatureFlagsIntoOptionsObject(componentOptionsObject,enabledPageFeatures)||transformed;if(componentOptionsObject&&parsedWevuDefaults)transformed=applyWevuDefaultsToComponentOptions({componentExpr,parsedWevuDefaults,options})||transformed;if(componentExpr&&!options?.isApp&&!options?.skipComponentTransform)state.componentStyleOptions=analyzeComponentStyleOptions(componentExpr,exportPath.scope);if(componentOptionsObject)transformed=injectSetupInitialData(componentOptionsObject)||transformed;if(componentOptionsObject&&options?.bindingManifest?.bindings.some(binding=>binding.outputPath===WEVU_SETUP_READY_KEY)){componentOptionsObject.properties.push(t.objectProperty(t.identifier(WEVU_SETUP_READY_KEY),t.booleanLiteral(false)));transformed=true}if(componentOptionsObject&&options?.relaxStructuredTypeOnlyProps)transformed=relaxStructuredTypeOnlyProps(componentOptionsObject)||transformed;if(componentOptionsObject&&options?.runtimeCapabilities?.required.includes(`scopedSlots`))transformed=injectScopedSlotOwnerRequirement(componentOptionsObject)||transformed;if(componentOptionsObject&&options?.scopedSlotHostProperties)transformed=injectScopedSlotHostProperties(componentOptionsObject)||transformed;if(componentOptionsObject&&!options?.isApp&&options?.nativeSlotContext){componentOptionsObject.properties.push(t.objectProperty(t.identifier(WEVU_NATIVE_SLOT_CONTEXT_KEY),t.booleanLiteral(true)));transformed=true}if(componentOptionsObject&&options?.cssModules&&Object.keys(options.cssModules).length)transformed=injectCssModules(componentOptionsObject,options.cssModules)||transformed;if(componentOptionsObject&&options?.stabilizeCssVarsRuntime)transformed=injectStableCssVarsRuntime(ast.program,componentOptionsObject,exportPath.scope)||transformed;if(componentOptionsObject){transformed=injectPropsAliases(componentOptionsObject,options?.propsAliases)||transformed;transformed=injectPropsDerivedKeys(componentOptionsObject,options?.propsDerivedKeys)||transformed}if(componentOptionsObject&&!options?.isApp)transformed=injectBindingManifestContract(componentOptionsObject,{manifest:options?.bindingManifest,autoSetDataPick:options?.autoSetDataPick,pageLayout:options?.pageLayout,runtimeBindingManifest:options?.runtimeBindingManifest})||transformed;const classStyleBindings=options?.classStyleBindings??[];if(classStyleBindings.length){if(componentOptionsObject){ensureClassStyleRuntimeImports(ast.program);transformed=injectClassStyleComputed(componentOptionsObject,classStyleBindings,options?.propsAliases,warn)||transformed}else warn(`无法自动注入 class/style 计算属性:组件选项不是对象字面量。`)}const templateRefs=options?.templateRefs??[];if(templateRefs.length){if(componentOptionsObject)transformed=injectTemplateRefs(componentOptionsObject,templateRefs,warn)||transformed;else warn(`无法自动注入 template ref 元数据:组件选项不是对象字面量。`)}const layoutHosts=options?.layoutHosts??[];if(layoutHosts.length){if(componentOptionsObject)transformed=injectLayoutHosts(componentOptionsObject,layoutHosts,warn)||transformed;else warn(`无法自动注入 layout host 元数据:组件选项不是对象字面量。`)}const inlineExpressions=options?.inlineExpressions??[];if(inlineExpressions.length){if(componentOptionsObject){const injected=injectInlineExpressions(componentOptionsObject,inlineExpressions,ast.program);if(!injected)warn(`无法自动注入内联表达式元数据:methods 不是对象字面量。`);transformed=injected||transformed}else warn(`无法自动注入内联表达式元数据:组件选项不是对象字面量。`)}const functionPropPaths=options?.functionPropPaths??[];if(functionPropPaths.length){if(componentOptionsObject)transformed=injectFunctionPropPaths(componentOptionsObject,functionPropPaths)||transformed;else warn(`无法自动注入函数 prop 元数据:组件选项不是对象字面量。`)}if(componentExpr){if(options?.isApp)transformed=injectWevuDefaultsForApp({astProgram:ast.program,options,serializedWevuDefaults})||transformed;transformed=rewriteComponentExport({ast,exportPath,componentExpr,isAppFile:!!options?.isApp,skipComponentTransform:options?.skipComponentTransform})||transformed}return transformed}function createCapabilityAccumulator(){return{required:/* @__PURE__ */ new Set,conservative:/* @__PURE__ */ new Set}}function addConservativeCapabilities(accumulator,names){for(const name of names){accumulator.required.add(name);accumulator.conservative.add(name)}}function unwrapExpression(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node))return unwrapExpression(node.expression);if(t.isParenthesizedExpression(node))return unwrapExpression(node.expression);return node}function resolveStaticExpression(node,context,visited=/* @__PURE__ */ new Set){const normalized=unwrapExpression(node);if(!t.isIdentifier(normalized)||normalized.name===`undefined`)return{value:normalized,context};const binding=context.scope?.getBinding(normalized.name);if(!binding||!binding.constant||!binding.path.isVariableDeclarator()||!binding.path.parentPath?.isVariableDeclaration()||binding.path.parentPath.node.kind!==`const`||visited.has(binding.path.node))return;if(!(binding.referencePaths.length===1||binding.referencePaths.every(reference=>{return context.safeBindingReferences?.has(reference.node)||reference.parentPath.isExportDefaultDeclaration()&&reference.parentPath.node.declaration===reference.node}))||!binding.path.node.init||!t.isExpression(binding.path.node.init))return;visited.add(binding.path.node);return resolveStaticExpression(binding.path.node.init,{scope:binding.path.scope,safeBindingReferences:context.safeBindingReferences},visited)}function resolveProperty(object,key,context,initial={kind:`absent`}){let state=initial;for(const property of object.properties){if(t.isSpreadElement(property)||property.computed){state={kind:`unknown`};continue}if(!isStaticObjectKeyMatch(property.key,key))continue;if(!t.isObjectProperty(property)||!t.isExpression(property.value)){state={kind:`unknown`};continue}state={kind:`value`,value:property.value,context}}return state}function isStaticPrimitive(node){return t.isBooleanLiteral(node)||t.isNullLiteral(node)||t.isNumericLiteral(node)||t.isStringLiteral(node)||t.isTemplateLiteral(node)&&node.expressions.length===0||t.isIdentifier(node,{name:`undefined`})}function applyResolvedProperty(current,next){return next.kind===`absent`?current:next}function resolveInheritedSetData(expression,context,visited){const result=resolveStaticExpression(expression,context);if(!result)return{kind:`unknown`};const{value:resolved,context:resolvedContext}=result;if(!t.isObjectExpression(resolved))return isStaticPrimitive(resolved)||t.isFunction(resolved)?{kind:`absent`}:{kind:`unknown`};if(visited.has(resolved))return{kind:`absent`};visited.add(resolved);let state={kind:`absent`};const inherited=resolveProperty(resolved,`extends`,resolvedContext);if(inherited.kind===`unknown`)state=inherited;else if(inherited.kind===`value`)state=applyResolvedProperty(state,resolveInheritedSetData(inherited.value,inherited.context,visited));const mixins=resolveProperty(resolved,`mixins`,resolvedContext);if(mixins.kind===`unknown`)state=mixins;else if(mixins.kind===`value`){const resolvedMixins=resolveStaticExpression(mixins.value,mixins.context);if(!resolvedMixins||!t.isArrayExpression(resolvedMixins.value))state={kind:`unknown`};else for(const element of resolvedMixins.value.elements){if(!element||t.isSpreadElement(element)||!t.isExpression(element)){state={kind:`unknown`};continue}state=applyResolvedProperty(state,resolveInheritedSetData(element,resolvedMixins.context,visited))}}state=applyResolvedProperty(state,resolveProperty(resolved,`setData`,resolvedContext));visited.delete(resolved);return state}function analyzeHighFrequencyWarning(state,accumulator){if(state.kind===`unknown`){addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`]);return}if(state.kind===`absent`)return;const resolved=resolveStaticExpression(state.value,state.context);if(!resolved){addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`]);return}const{value,context}=resolved;if(t.isObjectExpression(value)){const enabled=resolveProperty(value,`enabled`,context);if(enabled.kind===`unknown`){addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`]);return}if(enabled.kind===`value`){const resolvedEnabled=resolveStaticExpression(enabled.value,enabled.context);if(!resolvedEnabled){addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`]);return}if(t.isBooleanLiteral(resolvedEnabled.value,{value:false}))return}accumulator.required.add(`setDataHighFrequencyWarning`);return}if(t.isBooleanLiteral(value,{value:true})){accumulator.required.add(`setDataHighFrequencyWarning`);return}if(!isStaticPrimitive(value)&&!t.isArrayExpression(value)&&!t.isFunction(value))addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`])}function analyzeSetData(state,accumulator,defaults){if(state.kind===`unknown`){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}if(state.kind===`absent`){if(defaults)analyzeSetData(defaults,accumulator);return}const defaultValue=defaults?.kind===`value`?resolveStaticExpression(defaults.value,defaults.context):void 0;const defaultObject=defaultValue&&t.isObjectExpression(defaultValue.value)?defaultValue.value:void 0;if(defaultObject&&(t.isIdentifier(state.value)||t.isMemberExpression(state.value))){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}const resolved=resolveStaticExpression(state.value,state.context);if(!resolved){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}const{value,context}=resolved;if(!t.isObjectExpression(value)){if(defaultObject)analyzeSetData({kind:`value`,value:defaultObject,context:defaultValue.context},accumulator);if(!isStaticPrimitive(value)&&!t.isArrayExpression(value)&&!t.isFunction(value))addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}const mergedDefaults=t.isObjectExpression(state.value)?defaultObject:void 0;const strategy=resolveProperty(value,`strategy`,context,mergedDefaults?resolveProperty(mergedDefaults,`strategy`,defaultValue.context):defaults?.kind===`unknown`?defaults:void 0);if(strategy.kind===`unknown`)addConservativeCapabilities(accumulator,[`patchStrategy`]);else if(strategy.kind===`value`){const resolvedStrategy=resolveStaticExpression(strategy.value,strategy.context)?.value;if(t.isStringLiteral(resolvedStrategy,{value:`patch`})||t.isTemplateLiteral(resolvedStrategy)&&resolvedStrategy.expressions.length===0&&resolvedStrategy.quasis[0]?.value.cooked===`patch`)accumulator.required.add(`patchStrategy`);else if(!resolvedStrategy||!isStaticPrimitive(resolvedStrategy)&&!t.isArrayExpression(resolvedStrategy)&&!t.isFunction(resolvedStrategy))addConservativeCapabilities(accumulator,[`patchStrategy`])}analyzeHighFrequencyWarning(resolveProperty(value,`highFrequencyWarning`,context,mergedDefaults?resolveProperty(mergedDefaults,`highFrequencyWarning`,defaultValue.context):defaults?.kind===`unknown`?defaults:void 0),accumulator)}function analyzeRuntimeFactoryOptions(expression,context,accumulator,defaults){const defaultSetDataNode=Boolean(defaults&&Object.prototype.hasOwnProperty.call(defaults,`setData`))?t.valueToNode(defaults?.setData):void 0;const defaultSetData=defaultSetDataNode&&t.isExpression(defaultSetDataNode)?{kind:`value`,value:defaultSetDataNode,context:{}}:void 0;if(!expression){if(defaultSetData)analyzeSetData(defaultSetData,accumulator);return}const resolved=resolveStaticExpression(expression,context);if(!resolved){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}if(!t.isObjectExpression(resolved.value)){if(!isStaticPrimitive(resolved.value)&&!t.isArrayExpression(resolved.value)&&!t.isFunction(resolved.value))addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}analyzeSetData(resolveInheritedSetData(resolved.value,resolved.context,/* @__PURE__ */ new Set),accumulator,defaultSetData)}function analyzeRuntimeDefaults(expression,context,accumulator){if(!expression)return;const resolved=resolveStaticExpression(expression,context);if(!resolved||!t.isObjectExpression(resolved.value)){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}for(const key of[`app`,`component`]){const branch=resolveProperty(resolved.value,key,resolved.context);if(branch.kind===`unknown`)addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);else if(branch.kind===`value`)analyzeRuntimeFactoryOptions(branch.value,branch.context,accumulator)}}function finishRuntimeCapabilityAnalysis(accumulator){return createWevuRuntimeCapabilityMetadata(accumulator.required,accumulator.conservative)}const INSTALLER_LOCAL_NAMES={patchStrategy:`__wevuInstallPatchStrategy`,templateRefs:`__wevuInstallTemplateRefs`,inlineEvents:`__wevuInstallInlineEvents`,setDataHighFrequencyWarning:`__wevuInstallSetDataHighFrequencyWarning`,scopedSlots:`__wevuInstallScopedSlots`,layout:`__wevuInstallLayout`,jsxIslands:`__wevuInstallJsxIslands`};const CAPABILITY_BY_INSTALLER=Object.fromEntries(WE_VU_RUNTIME_CAPABILITY_ORDER.map(name=>[WE_VU_RUNTIME_CAPABILITY_INSTALLERS[name],name]));function resolveInstallerCallCapability(statement,importedLocals,namespaceLocals){if(!t.isExpressionStatement(statement)||!t.isCallExpression(statement.expression)||statement.expression.arguments.length)return;const callee=statement.expression.callee;if(t.isIdentifier(callee))return WE_VU_RUNTIME_CAPABILITY_ORDER.find(name=>importedLocals[name]?.includes(callee.name));if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&namespaceLocals.has(callee.object.name)&&t.isIdentifier(callee.property))return CAPABILITY_BY_INSTALLER[callee.property.name]}function findLeadingImportEnd(program){let index=0;while(index<program.body.length&&t.isImportDeclaration(program.body[index]))index+=1;return index}function injectWevuRuntimeCapabilityInstallers(program,metadata){if(!metadata?.required.length)return false;const importedLocals={};const namespaceLocals=/* @__PURE__ */ new Set;for(const statement of program.body){if(!t.isImportDeclaration(statement)||statement.importKind===`type`||!isWevuRuntimeModuleId(statement.source.value))continue;for(const specifier of statement.specifiers)if(t.isImportNamespaceSpecifier(specifier))namespaceLocals.add(specifier.local.name);else if(t.isImportSpecifier(specifier)&&specifier.importKind!==`type`&&t.isIdentifier(specifier.imported)){const capability=CAPABILITY_BY_INSTALLER[specifier.imported.name];if(capability){const locals=importedLocals[capability]??[];locals.push(specifier.local.name);importedLocals[capability]=locals}}}const existingCalls={};let prefixIndex=findLeadingImportEnd(program);let previousCapabilityIndex=-1;while(prefixIndex<program.body.length){const statement=program.body[prefixIndex];const capability=resolveInstallerCallCapability(statement,importedLocals,namespaceLocals);if(!capability)break;const capabilityIndex=WE_VU_RUNTIME_CAPABILITY_ORDER.indexOf(capability);if(capabilityIndex<previousCapabilityIndex)break;if(!existingCalls[capability])existingCalls[capability]=statement;previousCapabilityIndex=capabilityIndex;prefixIndex+=1}const usedNames=new Set(Object.keys(t.getBindingIdentifiers(program)));const localByCapability={};for(const capability of metadata.required){if(existingCalls[capability])continue;const existingLocal=importedLocals[capability]?.[0];if(existingLocal){localByCapability[capability]=existingLocal;continue}const baseName=INSTALLER_LOCAL_NAMES[capability];let localName=baseName;let suffix=2;while(usedNames.has(localName)){localName=`${baseName}${suffix}`;suffix+=1}usedNames.add(localName);localByCapability[capability]=localName;ensureRuntimeImport(program,WE_VU_RUNTIME_CAPABILITY_INSTALLERS[capability],localName)}let insertIndex=findLeadingImportEnd(program);const requiredCapabilities=new Set(metadata.required);let changed=false;for(const capability of WE_VU_RUNTIME_CAPABILITY_ORDER){const existingCall=existingCalls[capability];if(existingCall){const existingIndex=program.body.indexOf(existingCall);if(existingIndex>=insertIndex)insertIndex=existingIndex+1;continue}if(!requiredCapabilities.has(capability))continue;const localName=localByCapability[capability];program.body.splice(insertIndex,0,t.expressionStatement(t.callExpression(t.identifier(localName),[])));insertIndex+=1;changed=true}return changed}const OPTION_FACTORY_APIS={createApp:true,createWevuComponent:true,defineComponent:true};function addScopedSlotCreatorCapabilities(accumulator){accumulator.required.add(`scopedSlots`);addConservativeCapabilities(accumulator,[`templateRefs`,`inlineEvents`,`layout`])}function analyzeWevuRuntimeCalls(ast){const namedBindings=/* @__PURE__ */ new Map;const namespaceSpecifiers=[];for(const statement of ast.program.body){if(!t.isImportDeclaration(statement)||statement.importKind===`type`||!isWevuRuntimeModuleId(statement.source.value))continue;for(const specifier of statement.specifiers){if(t.isImportNamespaceSpecifier(specifier)||t.isImportDefaultSpecifier(specifier)){namespaceSpecifiers.push(specifier);continue}if(!t.isImportSpecifier(specifier)||specifier.importKind===`type`||!t.isIdentifier(specifier.imported))continue;const importedName=specifier.imported.name;if(importedName===`createWevuScopedSlotComponent`||importedName===`setWevuDefaults`||Object.prototype.hasOwnProperty.call(OPTION_FACTORY_APIS,importedName))namedBindings.set(specifier.local.name,{api:importedName,specifier})}}if(!namedBindings.size&&!namespaceSpecifiers.length)return;const handledCallees=/* @__PURE__ */ new Set;const safeBindingReferences=/* @__PURE__ */ new Set;const accumulator=createCapabilityAccumulator();const calls=[];let programScope;traverse(ast,{Program(path){programScope=path.scope},CallExpression(path){if(!t.isIdentifier(path.node.callee))return;const runtimeBinding=namedBindings.get(path.node.callee.name);const binding=path.scope.getBinding(path.node.callee.name);if(!runtimeBinding||binding?.path.node!==runtimeBinding.specifier)return;handledCallees.add(path.node.callee);const firstArgument=path.node.arguments[0];const argument=firstArgument&&!t.isSpreadElement(firstArgument)&&t.isExpression(firstArgument)?firstArgument:void 0;if(t.isIdentifier(argument))safeBindingReferences.add(argument);calls.push({api:runtimeBinding.api,argument,argumentUnknown:Boolean(firstArgument&&(t.isSpreadElement(firstArgument)||!t.isExpression(firstArgument))),scope:path.scope})}});for(const{api,argument,argumentUnknown,scope}of calls){const context={scope,safeBindingReferences};if(api===`createWevuScopedSlotComponent`)addScopedSlotCreatorCapabilities(accumulator);else if(argumentUnknown)addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);else if(api===`setWevuDefaults`)analyzeRuntimeDefaults(argument,context,accumulator);else analyzeRuntimeFactoryOptions(argument,context,accumulator)}for(const{api,specifier}of namedBindings.values()){if(!(programScope?.getBinding(specifier.local.name))?.referencePaths.some(reference=>!handledCallees.has(reference.node)))continue;if(api===`createWevuScopedSlotComponent`)addScopedSlotCreatorCapabilities(accumulator);else addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`])}for(const specifier of namespaceSpecifiers){const binding=programScope?.getBinding(specifier.local.name);if(!binding?.referenced)continue;addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);if(binding.referencePaths.some(reference=>{const parent=reference.parentPath;if(!parent.isMemberExpression()||parent.node.object!==reference.node||parent.node.computed||!t.isIdentifier(parent.node.property))return true;return parent.node.property.name===WE_VU_RUNTIME_APIS.createWevuScopedSlotComponent}))addScopedSlotCreatorCapabilities(accumulator)}return finishRuntimeCapabilityAnalysis(accumulator)}function analyzeWevuComponentOptions(params){if(!params.expression)return;const accumulator=createCapabilityAccumulator();analyzeRuntimeFactoryOptions(params.expression,{scope:params.scope},accumulator,params.defaults);return finishRuntimeCapabilityAnalysis(accumulator)}function analyzeWevuDefaults(defaults){if(!defaults)return;const node=t.valueToNode(defaults);if(!t.isExpression(node))return;const accumulator=createCapabilityAccumulator();analyzeRuntimeDefaults(node,{},accumulator);return finishRuntimeCapabilityAnalysis(accumulator)}function runVisitor(visitor,path){if(typeof visitor===`function`)visitor(path)}function transformScript(source,options){const fastResult=tryFastTransformCompiledScriptSetup(source,options);if(fastResult)return fastResult;const ast=parse$3(source,BABEL_TS_MODULE_PARSER_OPTIONS);const sourceRuntimeCapabilities=analyzeWevuRuntimeCalls(ast);const warn=resolveWarnHandler(options?.warn);const state={transformed:false,defineComponentAliases:/* @__PURE__ */ new Set([WE_VU_RUNTIME_APIS.defineComponent,`_defineComponent`]),defineComponentDecls:/* @__PURE__ */ new Map,useSlotsAliases:/* @__PURE__ */ new Set,usesSlots:false,defaultExportPath:null};const enabledPageFeatures=options?.isPage?options.nativePageFeatureFlags?new Set(options.nativePageFeatureFlags):collectWevuPageFeatureFlags(ast):/* @__PURE__ */ new Set;const serializedWevuDefaults=options?.wevuDefaults&&Object.keys(options.wevuDefaults).length>0?serializeWevuDefaults(options.wevuDefaults,warn):void 0;const parsedWevuDefaults=serializedWevuDefaults?JSON.parse(serializedWevuDefaults):void 0;const vueSfcVisitors=vueSfcTransformPlugin().visitor;const macroVisitors=createMacroVisitors(ast,state);const importVisitors=createImportVisitors(ast.program,state);const collectVisitors=createCollectVisitors(state);const visitor={...vueSfcVisitors,...macroVisitors,...importVisitors,...collectVisitors,ImportDeclaration(path){runVisitor(macroVisitors.ImportDeclaration,path);if(path.removed)return;const source=path.node.source.value;const canProvideUseSlots=source===`vue`||isWevuRuntimeModuleId(source);for(const specifier of path.node.specifiers){if(canProvideUseSlots&&specifier.type===`ImportSpecifier`&&specifier.importKind!==`type`&&(specifier.imported.type===`Identifier`&&specifier.imported.name===WE_VU_RUNTIME_APIS.defineComponent||specifier.imported.type===`StringLiteral`&&specifier.imported.value===WE_VU_RUNTIME_APIS.defineComponent))state.defineComponentAliases.add(specifier.local.name);if(canProvideUseSlots&&specifier.type===`ImportSpecifier`&&(specifier.imported.type===`Identifier`&&specifier.imported.name===`useSlots`||specifier.imported.type===`StringLiteral`&&specifier.imported.value===`useSlots`))state.useSlotsAliases.add(specifier.local.name)}runVisitor(vueSfcVisitors.ImportDeclaration,path);if(!path.removed)runVisitor(importVisitors.ImportDeclaration,path)},CallExpression(path){if(path.node.callee.type===`Identifier`&&state.useSlotsAliases.has(path.node.callee.name))state.usesSlots=true;runVisitor(vueSfcVisitors.CallExpression,path);if(!path.removed)runVisitor(macroVisitors.CallExpression,path)}};traverse(ast,visitor);const templateRuntimeCapabilities=createWevuRuntimeCapabilityMetadata([...options?.templateRefs?.length||options?.layoutHosts?.length?[`templateRefs`]:[],...options?.inlineExpressions?.length?[`inlineEvents`]:[],...options?.layoutHosts?.length?[`layout`]:[]]);const componentExpression=state.defaultExportPath?resolveComponentExpression(state.defaultExportPath.node.declaration,state.defineComponentDecls,state.defineComponentAliases):null;const defaultDeclaration=state.defaultExportPath?.node.declaration;let componentCapabilityExpression=componentExpression;if(t.isIdentifier(defaultDeclaration))componentCapabilityExpression=defaultDeclaration;else if(t.isCallExpression(defaultDeclaration)&&t.isIdentifier(defaultDeclaration.callee)&&state.defineComponentAliases.has(defaultDeclaration.callee.name)){const firstArgument=defaultDeclaration.arguments[0];if(firstArgument&&!t.isSpreadElement(firstArgument)&&t.isExpression(firstArgument))componentCapabilityExpression=firstArgument}const defaultsBranch=options?.isApp?parsedWevuDefaults?.app:parsedWevuDefaults?.component;const componentRuntimeCapabilities=componentCapabilityExpression?analyzeWevuComponentOptions({expression:componentCapabilityExpression,scope:state.defaultExportPath?.scope,defaults:defaultsBranch}):void 0;const defaultsRuntimeCapabilities=options?.isApp?analyzeWevuDefaults(parsedWevuDefaults):void 0;const runtimeCapabilities=mergeWevuRuntimeCapabilityMetadata(options?.runtimeCapabilities,templateRuntimeCapabilities,sourceRuntimeCapabilities,componentRuntimeCapabilities,defaultsRuntimeCapabilities);if(options?.templateComponentMeta)state.transformed=pruneTemplateComponentMeta(ast,options.templateComponentMeta)||state.transformed;const rewriteOptions=state.usesSlots&&!options?.scopedSlotHostProperties?{...options,scopedSlotHostProperties:true}:options;state.transformed=rewriteDefaultExport(ast,state,rewriteOptions,enabledPageFeatures,serializedWevuDefaults,parsedWevuDefaults)||state.transformed;state.transformed=injectWevuRuntimeCapabilityInstallers(ast.program,runtimeCapabilities)||state.transformed;if(!state.transformed)return{code:source,transformed:false,...runtimeCapabilities?{runtimeCapabilities}:{},...state.componentStyleOptions?{componentStyleOptions:state.componentStyleOptions}:{}};const sourceMap=options?.sourceMap!==false;const generated=generate(ast,{compact:options?.minify===true,minified:options?.minify===true,retainLines:options?.minify!==true,sourceMaps:sourceMap,sourceFileName:`inline.ts`},source);return{code:generated.code,map:sourceMap?generated.map:null,transformed:state.transformed,...runtimeCapabilities?{runtimeCapabilities}:{},...state.componentStyleOptions?{componentStyleOptions:state.componentStyleOptions}:{}}}function addJsxDiagnostic(context,node,code,message,severity=`warning`){context.warningDiagnostics.set(context.warnings.length,{code,severity,message,filename:node.loc?.filename??context.filename??``,source:`jsx`,loc:node.loc&&node.start!=null&&node.end!=null?{start:{offset:node.start,line:node.loc.start.line,column:node.loc.start.column+1},end:{offset:node.end,line:node.loc.end.line,column:node.loc.end.column+1}}:void 0});context.warnings.push(message)}function createJsxDiagnostics(warnings,filename,metadata){return warnings.map((warning,index)=>{const message=warning.startsWith(`[JSX 编译]`)?warning:`[JSX 编译] ${warning}`;return{code:`WV1003`,severity:`warning`,filename,source:`jsx`,...metadata?.get(index),message}})}function reportJsxDiagnostics(diagnostics,warn){for(const diagnostic of diagnostics??[]){warn?.(diagnostic.message);if(diagnostic.severity===`error`)throw new CompilerDiagnosticError(diagnostic)}}const WXML_EXPRESSION_GENERATE_OPTIONS={compact:true,jsescOption:{quotes:`single`,minimal:true}};const escapeText=escapeWxmlText;const escapeAttr=escapeWxmlAttribute;const WHITESPACE_RE=/\s+/g;function normalizeJsxText(value){return value.replace(WHITESPACE_RE,` `)}function printExpression$1(exp){const normalized=t.cloneNode(exp,true);t.traverseFast(normalized,node=>{if(t.isStringLiteral(node))node.extra=void 0});return generate(normalized,WXML_EXPRESSION_GENERATE_OPTIONS).code}function unwrapTsExpression(exp){return unwrapTypeScriptExpression(exp)}function normalizeInterpolationExpression(exp,context){const cached=context?.interpolationCache.get(exp);if(cached!=null)return cached;let source=printExpression$1(unwrapTsExpression(exp));if(context?.setupRefBindings?.size){const expression=t.cloneNode(unwrapTsExpression(exp),true);const file=t.file(t.program([t.expressionStatement(expression)]));traverse(file,{"MemberExpression|OptionalMemberExpression":{enter(path){const member=path.node;if(!t.isMemberExpression(member)&&!t.isOptionalMemberExpression(member))return;const object=t.isExpression(member.object)?unwrapTsExpression(member.object):member.object;if(!t.isIdentifier(object)||!context.setupRefBindings?.has(object.name)||context.scopeStack.includes(object.name)||path.scope.hasBinding(object.name))return;if(member.loc?.filename&&context.filename&&member.loc.filename!==context.filename)return;if(member.computed?t.isStringLiteral(member.property,{value:`value`}):t.isIdentifier(member.property,{name:`value`}))path.replaceWith(t.cloneNode(object))}}});const statement=file.program.body[0];source=printExpression$1(statement.expression)}let normalized=normalizeWxmlExpression(source);if(context&&shouldFallbackToRuntimeBinding(source)){const name=`__wv_bind_${context.classStyleBindings.filter(item=>item.type===`bind`).length}`;context.classStyleBindings.push({name,type:`bind`,exp:source,forStack:context.forStack.map(info=>({...info}))});normalized=`${name}${context.forStack.map(info=>`[${info.index??`index`}]`).join(``)}`}context?.interpolationCache.set(exp,normalized);return normalized}function renderMustache(expression,context){return context.mustacheInterpolation===`spaced`?`{{ ${expression} }}`:`{{${expression}}}`}function pushScope(context,names,sourceExpression){const scopedNames=names.filter(Boolean);const sourceLocals=[...context.scopeStack];context.scopeStack.push(...scopedNames);if(scopedNames.length)context.bindingScopeStack.push({locals:scopedNames,sourceExpression,sourceLocals})}function popScope(context,count){for(let i=0;i<count;i+=1)context.scopeStack.pop();if(count>0)context.bindingScopeStack.pop()}function analyzeInlineExpression(exp,context){const localSet=new Set(context.scopeStack);const used=[];const usedSet=/* @__PURE__ */ new Set;const identifierNames=/* @__PURE__ */ new Set;const normalizedExpression=t.cloneNode(exp,true);const file=t.file(t.program([t.expressionStatement(normalizedExpression)]));let programScope;traverse(file,{Program(path){programScope=path.scope},Identifier(path){const name=path.node.name;identifierNames.add(name);if(!localSet.has(name)||!path.isReferencedIdentifier()||path.scope.hasBinding(name)||usedSet.has(name))return;usedSet.add(name);used.push(name)},StringLiteral(path){path.node.extra=void 0}});if(!programScope)throw new Error(`无法为 JSX 内联表达式创建程序作用域。`);return{parameterIdentifiers:createInlineExpressionParameterIdentifiers(programScope,identifierNames),normalizedExpression,scopeKeys:used}}function registerInlineExpression(exp,context){const{normalizedExpression,parameterIdentifiers,scopeKeys}=analyzeInlineExpression(exp,context);const id=createInlineExpressionId(context.inlineExpressionSeed++);context.inlineExpressions.push({id,expression:generate(normalizedExpression,WXML_EXPRESSION_GENERATE_OPTIONS).code,scopeKeys,parameterNames:{context:parameterIdentifiers.context.name,scope:parameterIdentifiers.scope.name,event:parameterIdentifiers.event.name}});return{id,scopeKeys}}function toJsxTagName(name,context){if(t.isJSXIdentifier(name))return name.name;if(t.isJSXNamespacedName(name))return`${name.namespace.name}:${name.name.name}`;context.warnings.push(`JSX 成员标签(如 <Foo.Bar />)无法映射为小程序 WXML 组件标签,已生成 dynamic island。`);return`block`}const REF_FACTORIES=/* @__PURE__ */ new Set([`ref`,`shallowRef`,`computed`,`customRef`,`toRef`,`useModel`,`useTemplateRef`]);const REF_OBJECT_FACTORIES=/* @__PURE__ */ new Set([`toRefs`,`storeToRefs`]);function resolveSetupFunction(component){const setup=getObjectPropertyByKey(component,`setup`);if(t.isObjectMethod(setup))return setup;if(t.isObjectProperty(setup)&&(t.isFunctionExpression(setup.value)||t.isArrowFunctionExpression(setup.value)))return setup.value}function collectSetupRefBindings(component,context){const setup=resolveSetupFunction(component);const refs=/* @__PURE__ */ new Set;if(!setup||!t.isBlockStatement(setup.body))return refs;const declarations=setup.body.body.flatMap(statement=>t.isVariableDeclaration(statement)?statement.declarations:[]);const stableDeclarations=new Set(setup.body.body.flatMap(statement=>t.isVariableDeclaration(statement)&&statement.kind===`const`?statement.declarations:[]));const locals=new Set(declarations.flatMap(declaration=>Object.keys(t.getBindingIdentifiers(declaration.id))));for(const statement of setup.body.body)if(t.isFunctionDeclaration(statement)&&statement.id)locals.add(statement.id.name);for(const parameter of setup.params)Object.keys(t.getBindingIdentifiers(parameter)).forEach(name=>locals.add(name));function importedApi(expression){if(t.isIdentifier(expression)&&!locals.has(expression.name)){const imported=context.importedBindings?.get(expression.name);return imported&&[`wevu`,`vue`].includes(imported.source)?imported.importedName:void 0}if(t.isMemberExpression(expression)&&!expression.computed&&t.isIdentifier(expression.object)&&t.isIdentifier(expression.property)&&!locals.has(expression.object.name)){const imported=context.importedBindings?.get(expression.object.name);return imported?.importedName===`*`&&[`wevu`,`vue`].includes(imported.source)?expression.property.name:void 0}}function isRef(expression){const value=unwrapTypeScriptExpression(expression);if(t.isIdentifier(value))return refs.has(value.name);if(!t.isCallExpression(value)||!t.isExpression(value.callee))return false;const api=importedApi(value.callee);if(api&&REF_FACTORIES.has(api))return true;const first=value.arguments[0];return(api===`readonly`||api===`shallowReadonly`)&&t.isExpression(first)&&isRef(first)}for(const declaration of declarations){if(!declaration.init||!stableDeclarations.has(declaration))continue;if(t.isIdentifier(declaration.id)&&isRef(declaration.init))refs.add(declaration.id.name);else if(t.isObjectPattern(declaration.id)&&t.isCallExpression(declaration.init)&&t.isExpression(declaration.init.callee)){const api=importedApi(declaration.init.callee);if(api&&REF_OBJECT_FACTORIES.has(api)){for(const property of declaration.id.properties)if(t.isObjectProperty(property)&&t.isIdentifier(property.value))refs.add(property.value.name)}}}return refs}function parseIslandExpression(expression){const statement=parse$3(`const __wevuIsland = (${expression})`,BABEL_TS_MODULE_PARSER_OPTIONS).program.body[0];if(!t.isVariableDeclaration(statement))return;const init=statement.declarations[0]?.init;return init&&t.isExpression(init)?init:void 0}function injectIslandComputed(optionsObject,islands){const entries=islands.flatMap(island=>{const expression=parseIslandExpression(island.expression);if(!expression)return[];const normalized=t.callExpression(t.memberExpression(t.identifier(`__wevuNormalizeJsxIsland`),t.identifier(`call`)),[t.thisExpression(),expression,t.stringLiteral(island.id),t.objectExpression([t.objectProperty(t.identifier(`normalizeClass`),t.identifier(`__wevuNormalizeClass`)),t.objectProperty(t.identifier(`normalizeStyle`),t.identifier(`__wevuNormalizeStyle`))])]);return[t.objectProperty(t.stringLiteral(island.id),normalized)]});if(!entries.length)return false;const islandGetter=t.objectMethod(`method`,t.identifier(WEVU_JSX_ISLAND_DATA_KEY),[],t.blockStatement([t.returnStatement(t.objectExpression(entries))]));const computed=optionsObject.properties.find(property=>(t.isObjectProperty(property)||t.isObjectMethod(property))&&toStaticObjectKey(property.key)===`computed`);if(computed&&t.isObjectProperty(computed)&&t.isObjectExpression(computed.value))computed.value.properties.push(islandGetter);else optionsObject.properties.unshift(t.objectProperty(t.identifier(`computed`),t.objectExpression([islandGetter])));return true}function injectDynamicIslandRuntime(source,islands){if(!islands?.length)return source;const ast=parse$3(source,BABEL_TS_MODULE_PARSER_OPTIONS);const defineComponentAliases=/* @__PURE__ */ new Set([`defineComponent`,`_defineComponent`]);const declarations=/* @__PURE__ */ new Map;let injected=false;traverse(ast,{ImportDeclaration(path){if(path.node.source.value!==`wevu`&&path.node.source.value!==`vue`)return;for(const specifier of path.node.specifiers)if(t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.imported,{name:`defineComponent`}))defineComponentAliases.add(specifier.local.name)},VariableDeclarator(path){if(!t.isIdentifier(path.node.id)||!path.node.init)return;if(t.isObjectExpression(path.node.init))declarations.set(path.node.id.name,path.node.init);if(t.isCallExpression(path.node.init)&&t.isIdentifier(path.node.init.callee)&&defineComponentAliases.has(path.node.init.callee.name)){const first=path.node.init.arguments[0];if(t.isObjectExpression(first))declarations.set(path.node.id.name,first)}},ExportDefaultDeclaration(path){const declaration=path.node.declaration;let optionsObject;if(t.isObjectExpression(declaration))optionsObject=declaration;else if(t.isCallExpression(declaration)&&t.isIdentifier(declaration.callee)&&defineComponentAliases.has(declaration.callee.name)){const first=declaration.arguments[0];if(t.isObjectExpression(first))optionsObject=first}else if(t.isIdentifier(declaration))optionsObject=declarations.get(declaration.name);if(optionsObject)injected=injectIslandComputed(optionsObject,islands)||injected}});if(!injected)return source;ensureRuntimeImport(ast.program,`normalizeJsxIsland`,`__wevuNormalizeJsxIsland`);ensureRuntimeImport(ast.program,`normalizeClass`,`__wevuNormalizeClass`);ensureRuntimeImport(ast.program,`normalizeStyle`,`__wevuNormalizeStyle`);return generate(ast).code}function removeRenderOptionFromObjectExpression(node){const nextProps=node.properties.filter(prop=>{if(t.isObjectMethod(prop))return toStaticObjectKey(prop.key)!==`render`;if(t.isObjectProperty(prop)&&!prop.computed)return toStaticObjectKey(prop.key)!==`render`;return true});const removed=nextProps.length!==node.properties.length;if(removed)node.properties=nextProps;return removed}function resolveReturnedJsxClosureExpression(expression){if(!t.isArrowFunctionExpression(expression)&&!t.isFunctionExpression(expression))return;if(t.isJSXElement(expression.body)||t.isJSXFragment(expression.body))return expression.body;if(!t.isBlockStatement(expression.body))return;const returned=expression.body.body.find(statement=>t.isReturnStatement(statement)&&statement.argument);if(!returned||!t.isReturnStatement(returned))return;return returned.argument&&(t.isJSXElement(returned.argument)||t.isJSXFragment(returned.argument))?returned.argument:void 0}function rewriteSetupRenderClosure(node){const setup=resolveSetupFunction(node);if(!setup||!t.isBlockStatement(setup.body))return false;const localNames=/* @__PURE__ */ new Set;for(const param of setup.params)Object.keys(t.getBindingIdentifiers(param)).forEach(name=>localNames.add(name));for(const statement of setup.body.body)if(t.isVariableDeclaration(statement))for(const declaration of statement.declarations)Object.keys(t.getBindingIdentifiers(declaration.id)).forEach(name=>localNames.add(name));else if(t.isFunctionDeclaration(statement)&&statement.id)localNames.add(statement.id.name);for(const statement of setup.body.body){if(!t.isReturnStatement(statement)||!statement.argument||!t.isExpression(statement.argument))continue;const jsx=resolveReturnedJsxClosureExpression(statement.argument);if(!jsx)continue;const captures=/* @__PURE__ */ new Set;const file=t.file(t.program([t.expressionStatement(t.cloneNode(jsx,true))]));traverse(file,{ReferencedIdentifier(path){if(localNames.has(path.node.name))captures.add(path.node.name)}});statement.argument=t.objectExpression([...captures].map(name=>t.objectProperty(t.identifier(name),t.identifier(name),false,true)));return true}return false}function stripRenderOptionFromScript(source,filename,warnings){let ast;try{ast=parse$3(source,BABEL_TS_MODULE_PARSER_OPTIONS)}catch{return source}const defineComponentAliases=/* @__PURE__ */ new Set([`defineComponent`,`_defineComponent`]);const defineComponentDecls=/* @__PURE__ */ new Map;let hasDefaultExport=false;let removedRender=false;let removedJsonMacroImport=false;traverse(ast,{ImportDeclaration(path){const importSource=path.node.source.value;if(importSource===`wevu`||importSource===`vue`)for(const specifier of path.node.specifiers){if(!t.isImportSpecifier(specifier))continue;if(!t.isIdentifier(specifier.imported,{name:`defineComponent`}))continue;defineComponentAliases.add(specifier.local.name)}if(importSource!==`weapp-vite`)return;const retained=path.node.specifiers.filter(specifier=>{if(!t.isImportSpecifier(specifier))return true;const importedName=t.isIdentifier(specifier.imported)?specifier.imported.name:t.isStringLiteral(specifier.imported)?specifier.imported.value:``;return!JSON_MACROS.has(importedName)});if(retained.length===path.node.specifiers.length)return;removedJsonMacroImport=true;if(retained.length===0)path.remove();else path.node.specifiers=retained},VariableDeclarator(path){if(!t.isIdentifier(path.node.id)||!path.node.init)return;if(t.isObjectExpression(path.node.init)){defineComponentDecls.set(path.node.id.name,path.node.init);return}if(!t.isCallExpression(path.node.init))return;const callee=path.node.init.callee;if(!t.isIdentifier(callee)||!defineComponentAliases.has(callee.name))return;const first=path.node.init.arguments[0];if(t.isObjectExpression(first))defineComponentDecls.set(path.node.id.name,first)},ExportDefaultDeclaration(path){hasDefaultExport=true;const declaration=path.node.declaration;if(t.isDeclaration(declaration))return;if(t.isObjectExpression(declaration)){removedRender=removeRenderOptionFromObjectExpression(declaration)||rewriteSetupRenderClosure(declaration)||removedRender;return}if(t.isCallExpression(declaration)){const callee=declaration.callee;if(!t.isIdentifier(callee)||!defineComponentAliases.has(callee.name))return;const first=declaration.arguments[0];if(t.isObjectExpression(first))removedRender=removeRenderOptionFromObjectExpression(first)||rewriteSetupRenderClosure(first)||removedRender;return}if(t.isIdentifier(declaration)){const target=defineComponentDecls.get(declaration.name);if(target)removedRender=removeRenderOptionFromObjectExpression(target)||rewriteSetupRenderClosure(target)||removedRender}}});if(hasDefaultExport&&!removedRender)warnings?.push(`[JSX 编译] 未在 ${filename} 中移除 render 选项,输出脚本可能包含 JSX。`);if(!removedRender&&!removedJsonMacroImport)return source;return generate(ast).code}function resolveRenderExpression(componentExpr,context){if(!t.isObjectExpression(componentExpr)){context.warnings.push(`JSX 编译仅支持对象字面量组件选项。`);return null}const renderExpression=resolveRenderExpressionFromComponentOptions(componentExpr);if(renderExpression)return renderExpression;if(getRenderPropertyFromComponentOptions(componentExpr)){context.warnings.push(`render 不是可执行函数。`);return null}const setup=resolveSetupFunction(componentExpr);if(setup){const body=setup.body;if(t.isBlockStatement(body))for(const statement of body.body){if(!t.isReturnStatement(statement)||!statement.argument)continue;if(t.isArrowFunctionExpression(statement.argument)||t.isFunctionExpression(statement.argument)){context.setupRefBindings=collectSetupRefBindings(componentExpr,context);const renderBody=statement.argument.body;if(t.isExpression(renderBody))return renderBody;const returned=renderBody.body.find(item=>t.isReturnStatement(item)&&item.argument);if(returned&&t.isReturnStatement(returned)&&returned.argument)return returned.argument}}}context.warnings.push(`未找到 render() 或 setup() 返回的 render closure。`);return null}function isCollectableJsxTemplateTag(tag){if(!tag)return false;if(RESERVED_VUE_COMPONENT_TAGS.has(tag))return false;return!isBuiltinComponent(tag)}function analyzeJsxAst(ast,context){const{importedComponents,exportDefaultExpression}=collectJsxImportedComponentsAndDefaultExportFromBabelAst(ast,{isDefineComponentSource(source){return source===`wevu`||source===`vue`},resolveBabelComponentExpression:resolveComponentExpression});let renderExpression=null;let templateTags=/* @__PURE__ */ new Set;if(exportDefaultExpression){renderExpression=resolveRenderExpression(exportDefaultExpression,context);if(renderExpression)templateTags=collectJsxTemplateTagsFromBabelExpression(renderExpression,isCollectableJsxTemplateTag)}return{renderExpression,autoComponentContext:{templateTags,importedComponents}}}const EXTENSIONS=[``,`.tsx`,`.jsx`,`.ts`,`.js`];function isMissingFile(error){return Boolean(error&&typeof error===`object`&&`code`in error&&[`ENOENT`,`ENOTDIR`,`EISDIR`].includes(String(error.code)))}function resolveFile(source,importer,readSource){if(!source.startsWith(`.`))return;const base=path$1.resolve(path$1.dirname(importer),source);for(const extension of EXTENSIONS){const candidate=`${base}${extension}`;try{if(readSource(candidate)!==void 0)return candidate}catch(error){if(!isMissingFile(error))throw error}}for(const extension of EXTENSIONS){const candidate=path$1.join(base,`index${extension}`);try{if(readSource(candidate)!==void 0)return candidate}catch(error){if(!isMissingFile(error))throw error}}}function expressionFromDeclaration(node){if(!node)return;if(t.isJSXElement(node)||t.isJSXFragment(node))return{expression:node,params:[]};if(t.isArrowFunctionExpression(node)||t.isFunctionExpression(node)){let body;if(t.isBlockStatement(node.body)){const returned=node.body.body.find(statement=>t.isReturnStatement(statement)&&!!statement.argument);if(returned&&t.isReturnStatement(returned)&&returned.argument&&t.isExpression(returned.argument))body=returned.argument}else body=node.body;if(body)return{expression:body,params:node.params.filter(t.isIdentifier).map(param=>param.name)}}if(t.isFunctionDeclaration(node)){const body=node.body.body.find(statement=>t.isReturnStatement(statement)&&!!statement.argument);if(body&&t.isReturnStatement(body)&&body.argument&&t.isExpression(body.argument))return{expression:body.argument,params:node.params.filter(t.isIdentifier).map(param=>param.name)}}}function collectExports(ast){const locals=/* @__PURE__ */ new Map;const exports=/* @__PURE__ */ new Map;const reexports=/* @__PURE__ */ new Map;for(const statement of ast.program.body){if(t.isVariableDeclaration(statement)){for(const declaration of statement.declarations)if(t.isIdentifier(declaration.id)&&declaration.init&&t.isExpression(declaration.init))locals.set(declaration.id.name,declaration.init)}if(t.isFunctionDeclaration(statement)&&statement.id)locals.set(statement.id.name,statement);if(t.isExportNamedDeclaration(statement)){if(statement.declaration){if(t.isVariableDeclaration(statement.declaration)){for(const declaration of statement.declaration.declarations)if(t.isIdentifier(declaration.id)&&declaration.init&&t.isExpression(declaration.init)){locals.set(declaration.id.name,declaration.init);exports.set(declaration.id.name,declaration.id.name)}}if(t.isFunctionDeclaration(statement.declaration)&&statement.declaration.id){locals.set(statement.declaration.id.name,statement.declaration);exports.set(statement.declaration.id.name,statement.declaration.id.name)}}for(const specifier of statement.specifiers)if(t.isExportSpecifier(specifier)&&t.isIdentifier(specifier.local)&&t.isIdentifier(specifier.exported)){exports.set(specifier.exported.name,specifier.local.name);if(statement.source)reexports.set(specifier.exported.name,{source:statement.source.value,importedName:specifier.local.name})}}if(t.isExportDefaultDeclaration(statement)&&statement.declaration){if(t.isFunctionDeclaration(statement.declaration)&&statement.declaration.id)locals.set(`default`,statement.declaration);else if(t.isExpression(statement.declaration))locals.set(`default`,statement.declaration)}}return{locals,exports,reexports}}function createJsxModuleResolver(warnings,readSource=filename=>readFileSync(filename,`utf8`)){const cache=/* @__PURE__ */ new Map;const active=/* @__PURE__ */ new Set;const dependencies=/* @__PURE__ */ new Set;function read(filename){const code=readSource(filename);const cached=cache.get(filename);if(cached?.code===code)return cached.exports;const collected=collectExports(parse$3(code,{...BABEL_TS_MODULE_PARSER_OPTIONS,sourceFilename:filename}));cache.set(filename,{code,exports:collected});return collected}function resolveExport(filename,localName){if(active.has(filename)){warnings?.push(`[JSX 编译] 检测到跨文件 JSX 循环引用:${filename}`);return}active.add(filename);try{const{locals,reexports}=read(filename);const direct=expressionFromDeclaration(locals.get(localName)??null);if(direct)return direct;const forwarded=reexports.get(localName);if(!forwarded)return;const target=resolveFile(forwarded.source,filename,readSource);if(target)dependencies.add(target);return target?resolveExport(target,forwarded.importedName):void 0}finally{active.delete(filename)}}function resolveImport(filename,source,importedName){const target=resolveFile(source,filename,readSource);if(!target)return;dependencies.add(target);return resolveExport(target,importedName==="default"?`default`:importedName)}return{getDependencies:()=>[...dependencies],resolveExport,resolveImport}}function normalizeSourceFile$1(filename){return filename.replaceAll(`\\`,`/`)}function resolveBindingSourceFile(context,ownerFile){if(!ownerFile||!context.filename||path$1.resolve(ownerFile)===path$1.resolve(context.filename))return;if(!context.bindingManifest.sourceFile)return normalizeSourceFile$1(ownerFile);const relativeOwner=path$1.relative(path$1.dirname(context.filename),ownerFile);return normalizeSourceFile$1(path$1.join(path$1.dirname(context.bindingManifest.sourceFile),relativeOwner))}function recordJsxBinding(context,node,kind,outputPath){const expression=normalizeInterpolationExpression(node,context);const sourceFile=resolveBindingSourceFile(context,node.loc?.filename);const sourceLocation=node.loc&&node.start!=null&&node.end!=null?{start:{offset:node.start,line:node.loc.start.line,column:node.loc.start.column+1},end:{offset:node.end,line:node.loc.end.line,column:node.loc.end.column+1}}:void 0;const scopes=[{kind:`root`,depth:0},...context.bindingScopeStack.map((scope,index)=>({kind:`for`,depth:index+1,locals:[...scope.locals]}))];recordSyntheticBindingExpression(context.bindingManifest,{kind,expression,outputPath,sourceFile,sourceLocation,scopes,scopeDependencies:context.bindingScopeStack.map(scope=>({expression:scope.sourceExpression,locals:scope.sourceLocals}))},context.scopeStack)}const ON_EVENT_RE=/^on[A-Z]/;const CATCH_EVENT_RE=/^catch[A-Z]/;const CAPTURE_BIND_EVENT_RE=/^captureBind[A-Z]/;const CAPTURE_CATCH_EVENT_RE=/^captureCatch[A-Z]/;const MUT_BIND_EVENT_RE=/^mutBind[A-Z]/;const UPPERCASE_STYLE_RE=/[A-Z]/g;function isEventBinding(name){return ON_EVENT_RE.test(name)||CATCH_EVENT_RE.test(name)||CAPTURE_BIND_EVENT_RE.test(name)||CAPTURE_CATCH_EVENT_RE.test(name)||MUT_BIND_EVENT_RE.test(name)}function lowerFirstEventName(name){if(!name)return name;return`${name.charAt(0).toLowerCase()}${name.slice(1)}`}function resolveMappedEventName(rawName,context,isComponent){const resolveEvent=name=>{const eventName=lowerFirstEventName(name);return isComponent?eventName:context.platform.mapEventName(eventName)};if(CAPTURE_BIND_EVENT_RE.test(rawName))return resolveEvent(rawName.slice(11));if(CAPTURE_CATCH_EVENT_RE.test(rawName))return resolveEvent(rawName.slice(12));if(MUT_BIND_EVENT_RE.test(rawName))return resolveEvent(rawName.slice(7));if(CATCH_EVENT_RE.test(rawName))return resolveEvent(rawName.slice(5));return resolveEvent(rawName.slice(2))}function toEventBindingName(rawName,context,isComponent,tagName){const eventName=resolveMappedEventName(rawName,context,isComponent);if(ON_EVENT_RE.test(rawName)&&!isComponent){const sourceEventName=lowerFirstEventName(rawName.slice(2));const exactBinding=context.platform.eventBindingAlias?.(sourceEventName,tagName);if(exactBinding)return exactBinding}if(CAPTURE_BIND_EVENT_RE.test(rawName))return context.platform.eventBindingAttr(`capture-bind:${eventName}`);if(CAPTURE_CATCH_EVENT_RE.test(rawName))return context.platform.eventBindingAttr(`capture-catch:${eventName}`);if(MUT_BIND_EVENT_RE.test(rawName))return context.platform.eventBindingAttr(`mut-bind:${eventName}`);if(CATCH_EVENT_RE.test(rawName))return context.platform.eventBindingAttr(`catch:${eventName}`);return context.platform.eventBindingAttr(`bind:${eventName}`)}function readJsxAttributeExpression(value){if(!value)return t.booleanLiteral(true);if(t.isStringLiteral(value))return value;if(!t.isJSXExpressionContainer(value))return null;if(t.isJSXEmptyExpression(value.expression))return null;return unwrapTsExpression(value.expression)}function extractJsxKeyExpression(node,context){for(const attr of node.openingElement.attributes){if(!t.isJSXAttribute(attr)||!t.isJSXIdentifier(attr.name))continue;if(attr.name.name!==`key`)continue;const exp=readJsxAttributeExpression(attr.value);if(!exp)return null;if(t.isStringLiteral(exp))return exp.value;return normalizeInterpolationExpression(exp,context)}return null}function compileEventAttribute(name,value,context,isComponent,tagName){const bindAttr=toEventBindingName(name,context,isComponent,tagName);const eventName=resolveMappedEventName(name,context,isComponent);const eventSuffix=normalizeEventDatasetSuffix(eventName);const exp=readJsxAttributeExpression(value);if(!exp)return[];if(t.isStringLiteral(exp)&&exp.value)return[`${bindAttr}="${escapeAttr(exp.value)}"`];if(t.isIdentifier(exp))return[`${bindAttr}="${escapeAttr(exp.name)}"`];if(t.isMemberExpression(exp)&&!exp.computed&&t.isThisExpression(exp.object)&&t.isIdentifier(exp.property))return[`${bindAttr}="${escapeAttr(exp.property.name)}"`];context.bindingManifest.features.inlineEvents=true;const inline=registerInlineExpression(exp,context);const attrs=[`data-${`wi`}-${eventSuffix}="${inline.id}"`,`${bindAttr}="${WEVU_INLINE_HANDLER}"`];inline.scopeKeys.forEach((scopeKey,index)=>{attrs.push(`data-wv-s${index}="${renderMustache(scopeKey,context)}"`)});return attrs}function compileNormalAttribute(name,value,context,isComponent){const normalizedName=name===`className`?`class`:isComponent?normalizeComponentHostName(name):name;const exp=readJsxAttributeExpression(value);if(!exp)return null;if(t.isStringLiteral(exp))return`${normalizedName}="${escapeAttr(exp.value)}"`;if(t.isBooleanLiteral(exp))return`${normalizedName}="${renderMustache(String(exp.value),context)}"`;if(normalizedName===`class`){const value=resolveStaticClass(exp);if(value!=null)return`class="${escapeAttr(value)}"`}if(normalizedName===`style`){const value=resolveStaticStyle(exp);if(value!=null)return`style="${escapeAttr(value)}"`}recordJsxBinding(context,exp,normalizedName===`class`?`class`:normalizedName===`style`?`style`:isComponent?`component-prop`:`attribute`);if(isComponent&&(t.isArrowFunctionExpression(exp)||t.isFunctionExpression(exp)))context.bindingManifest.features.functionProps=true;const normalizedExp=normalizeInterpolationExpression(exp,context);return`${normalizedName}="${renderMustache(normalizedExp,context)}"`}function compileNamedAttribute(name,value,context,isComponent,tagName){if(name===`key`)return[];if(name===`v-html`){context.warnings.push(`小程序不支持 JSX v-html,请使用 rich-text 组件替代。`);return[]}if(name===`v-if`||name===`v-show`||name===`v-text`||name===`v-for`)return[];if(name===`v-slots`||name===`v-model`||name===`v-models`){context.warnings.push(`JSX ${name} 需要 Wevu runtime 语义,已生成确定性诊断。`);return[]}if(name.startsWith(`v-`)){context.warnings.push(`小程序不支持 JSX 自定义指令 ${name},已移除该指令。`);return[]}if(name===`innerHTML`||name.startsWith(`domProps`)){context.warnings.push(`小程序不支持 JSX DOM property ${name},已移除该属性。`);return[]}if(isEventBinding(name))return compileEventAttribute(name,value,context,isComponent,tagName);const normalAttr=compileNormalAttribute(name,value,context,isComponent);return normalAttr?[normalAttr]:[]}function compileJsxAttributes(attributes,context,options){const isComponent=options?.isComponent===true;const output=[];for(const attr of attributes){if(t.isJSXSpreadAttribute(attr)){const argument=unwrapTsExpression(attr.argument);if(t.isObjectExpression(argument))for(const property of argument.properties)if(t.isObjectProperty(property)&&!property.computed&&(t.isIdentifier(property.key)||t.isStringLiteral(property.key))){const value=property.value;if(t.isExpression(value)){const name=t.isIdentifier(property.key)?property.key.name:property.key.value;output.push(...compileNamedAttribute(name,t.jsxExpressionContainer(value),context,isComponent,options?.tagName))}}else context.warnings.push(`JSX spread attributes 包含无法静态展开的属性,已保留为 dynamic island。`);else context.warnings.push(`动态 JSX spread attributes 无法映射为静态 WXML,已生成确定性诊断。`);continue}if(t.isJSXNamespacedName(attr.name)){const namespace=attr.name.namespace.name;const name=attr.name.name.name;if(namespace.startsWith(`v-`))context.warnings.push(`小程序不支持 JSX 自定义指令 ${namespace}:${name},已移除该指令。`);else context.warnings.push(`小程序不支持 JSX 命名属性 ${namespace}:${name},已移除该属性。`);continue}if(!t.isJSXIdentifier(attr.name)){context.warnings.push(`小程序不支持 JSX 动态属性名,已移除该属性。`);continue}const name=attr.name.name;output.push(...compileNamedAttribute(name,attr.value,context,isComponent,options?.tagName))}return output}function staticObjectKey(node){if(t.isIdentifier(node))return node.name;if(t.isStringLiteral(node))return node.value}function resolveStaticClass(exp){if(t.isStringLiteral(exp)||t.isNumericLiteral(exp))return String(exp.value);if(t.isArrayExpression(exp)){const values=exp.elements.map(element=>{if(!element||!t.isExpression(element))return``;return resolveStaticClass(element)});return values.some(value=>value==null)?void 0:values.filter(Boolean).join(` `)}if(t.isObjectExpression(exp)){const values=[];for(const property of exp.properties){if(!t.isObjectProperty(property)||property.computed||!t.isBooleanLiteral(property.value))return;const key=staticObjectKey(property.key);if(key==null)return;if(property.value.value)values.push(key)}return values.join(` `)}}function resolveStaticStyle(exp){if(t.isStringLiteral(exp))return exp.value;if(t.isArrayExpression(exp)){const values=exp.elements.map(element=>{if(!element||!t.isExpression(element))return``;return resolveStaticStyle(element)});return values.some(value=>value==null)?void 0:values.filter(Boolean).join(`;`)}if(!t.isObjectExpression(exp))return;const values=[];for(const property of exp.properties){if(!t.isObjectProperty(property)||property.computed)return;const key=staticObjectKey(property.key)?.replace(UPPERCASE_STYLE_RE,char=>`-${char.toLowerCase()}`);if(!key||!t.isStringLiteral(property.value)&&!t.isNumericLiteral(property.value))return;values.push(`${key}:${property.value.value}`)}return values.join(`;`)}function isStaticClassStyleExpression(exp){return resolveStaticClass(exp)!=null||resolveStaticStyle(exp)!=null}function collectJsxDirectives(node){const directives=/* @__PURE__ */ new Map;for(const attribute of node.openingElement.attributes){if(!t.isJSXAttribute(attribute))continue;const name=t.isJSXIdentifier(attribute.name)?attribute.name.name:t.isJSXNamespacedName(attribute.name)?attribute.name.namespace.name:void 0;if(!name?.startsWith(`v-`))continue;const expression=readJsxAttributeExpression(attribute.value);if(expression)directives.set(name,expression)}return directives}const ROOT_PORTAL_TAG=`root-portal`;const TELEPORT_REMOVED_ATTRIBUTES=/* @__PURE__ */ new Set([`to`,`defer`,`disabled`,`key`]);function findJsxAttribute(node,name){return node.openingElement.attributes.find(attribute=>t.isJSXAttribute(attribute)&&t.isJSXIdentifier(attribute.name)&&attribute.name.name===name)}function resolveTeleportTarget(node){const attribute=findJsxAttribute(node,`to`);if(!attribute)return{kind:`missing`};const expression=readJsxAttributeExpression(attribute.value);if(expression&&t.isStringLiteral(expression))return{kind:`static`,value:expression.value};return{kind:`dynamic`}}function resolveTeleportEnable(node,context){const attribute=findJsxAttribute(node,`disabled`);if(!attribute)return renderMustache(`true`,context);const expression=readJsxAttributeExpression(attribute.value);if(!expression||t.isBooleanLiteral(expression)&&expression.value)return renderMustache(`false`,context);if(t.isBooleanLiteral(expression))return renderMustache(`true`,context);recordJsxBinding(context,expression,`attribute`);return renderMustache(`!(${normalizeInterpolationExpression(expression,context)})`,context)}function resolveTeleportPassthroughAttributes(node){const attributes=[];for(const attribute of node.openingElement.attributes){if(!t.isJSXAttribute(attribute)||!t.isJSXIdentifier(attribute.name))continue;const name=attribute.name.name;if(name.startsWith(`v-`)||TELEPORT_REMOVED_ATTRIBUTES.has(name))continue;attributes.push(attribute)}return attributes}function hasTeleportClassOrStyle(attributes){return attributes.some(attribute=>t.isJSXIdentifier(attribute.name)&&(attribute.name.name===`class`||attribute.name.name===`className`||attribute.name.name===`style`))}function compileJsxTeleport(node,context,compileJsxChildren,registerDynamicIsland){const directives=collectJsxDirectives(node);const wrapIf=content=>{const expression=directives.get(`v-if`);if(!expression)return content;recordJsxBinding(context,expression,`if`);return context.platform.wrapIf(normalizeInterpolationExpression(expression,context),content,value=>renderMustache(value,context))};if(!context.teleport.enabled)return wrapIf(compileJsxChildren(node.children,context));const decision=resolveTeleportDecision({supportsRootPortal:context.platform.supportsRootPortal===true,to:resolveTeleportTarget(node),spread:node.openingElement.attributes.some(attribute=>t.isJSXSpreadAttribute(attribute))});if(decision.kind===`degrade`){addJsxDiagnostic(context,node,TELEPORT_DEGRADE_CODES[decision.reason],decision.message,context.teleport.unsupported===`error`?`error`:`warning`);return wrapIf(compileJsxChildren(node.children,context))}const dynamicDirective=[`v-for`,`v-slots`,`v-model`,`v-models`].find(name=>directives.has(name));if(dynamicDirective){if(dynamicDirective===`v-model`||dynamicDirective===`v-models`)context.bindingManifest.features.model=true;context.warnings.push(`JSX ${dynamicDirective} 无法直接映射当前静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`closure`)}if(consumeBaseLibraryHint(context.baseLibrary,{topic:`root-portal`,minimum:ROOT_PORTAL_ENABLE_MIN_SDK_VERSION}))addJsxDiagnostic(context,node,`WV1010`,ROOT_PORTAL_BASE_LIBRARY_HINT_MESSAGE);const passthroughAttributes=resolveTeleportPassthroughAttributes(node);if(hasTeleportClassOrStyle(passthroughAttributes))addJsxDiagnostic(context,node,`WV1009`,`<Teleport> 的 class/style 会落在 root-portal 宿主节点上,可能无法按预期作用于内部弹层,建议把样式写在内层节点。`);const attrs=[`enable="${resolveTeleportEnable(node,context)}"`,...compileJsxAttributes(passthroughAttributes,context,{isComponent:false,tagName:ROOT_PORTAL_TAG})];const showExpression=directives.get(`v-show`);if(showExpression){recordJsxBinding(context,showExpression,`style`);attrs.push(`hidden="${renderMustache(`!(${normalizeInterpolationExpression(showExpression,context)})`,context)}"`)}const attrsSegment=attrs.length?` ${attrs.join(` `)}`:``;const content=compileJsxChildren(node.children,context);return wrapIf(content?`<${ROOT_PORTAL_TAG}${attrsSegment}>${content}</${ROOT_PORTAL_TAG}>`:`<${ROOT_PORTAL_TAG}${attrsSegment} />`)}const DYNAMIC_ISLAND_TEMPLATE_DEPTH=8;function resolveDynamicIslandTemplateName(depth){return depth===0?WEVU_JSX_ISLAND_TEMPLATE_NAME:`${WEVU_JSX_ISLAND_TEMPLATE_NAME}_${depth}`}function compileListExpression(exp,context){return normalizeInterpolationExpression(exp,context)}function registerDynamicIsland(exp,context,reason){if(context.dynamicIslandMode===`static`){context.warnings.push(`[JSX 编译] static 模式不允许 dynamic island(${reason})。`);return``}const id=`i${context.dynamicIslandSeed??0}`;context.dynamicIslandSeed=(context.dynamicIslandSeed??0)+1;context.bindingManifest.features.jsxIslands=true;recordJsxBinding(context,exp,`text`,WEVU_JSX_ISLAND_DATA_KEY);const expression=normalizeInterpolationExpression(exp);const captures=/* @__PURE__ */ new Set;const file=t.file(t.program([t.expressionStatement(t.cloneNode(exp,true))]));traverse(file,{ReferencedIdentifier(path){if(path.scope.hasBinding(path.node.name))return;if(context.importedBindings?.has(path.node.name))return;captures.add(path.node.name)},ThisExpression(){captures.add(`this`)}});context.dynamicIslands?.push({id,expression,reason,captures:[...captures]});return`<template is="${WEVU_JSX_ISLAND_TEMPLATE_NAME}" data-wv-jsx-island="${id}" data="{{node:${WEVU_JSX_ISLAND_DATA_KEY}.${id},islandId:'${id}'}}" />`}function renderDynamicIslandSupportTemplate(context){const{directives}=context.platform;const bindTap=context.platform.eventBindingAttr(`bind:tap`);const bindInput=context.platform.eventBindingAttr(`bind:input`);const bindChange=context.platform.eventBindingAttr(`bind:change`);const attrs=`id="{{node.props.id}}" class="{{node.props.class}}" style="{{node.props.style}}" hidden="{{node.props.hidden}}"`;const tapAttrs=`${attrs} data-wv-jsx-handler="{{node.events.tap}}" ${bindTap}="${WEVU_JSX_ISLAND_HANDLER}"`;return Array.from({length:DYNAMIC_ISLAND_TEMPLATE_DEPTH},(_,depth)=>{const templateName=resolveDynamicIslandTemplateName(depth);const childTemplateName=resolveDynamicIslandTemplateName(depth+1);const childTemplate=depth+1<DYNAMIC_ISLAND_TEMPLATE_DEPTH?`<block ${directives.forAttr}="{{node.children}}" ${directives.forItemAttr}="child" ${directives.keyAttr}="index"><template is="${childTemplateName}" data="{{node:child,islandId:islandId}}" /></block>`:``;return`<template name="${templateName}"><block ${directives.ifAttr}="{{node.kind=='text'}}">{{node.text}}</block><block ${directives.elifAttr}="{{node.kind=='fragment'}}">${childTemplate}</block><view ${directives.elifAttr}="{{node.tag=='view'}}" ${tapAttrs}>${childTemplate}</view><text ${directives.elifAttr}="{{node.tag=='text'}}" ${tapAttrs}>${childTemplate}</text><button ${directives.elifAttr}="{{node.tag=='button'}}" ${tapAttrs}>${childTemplate}</button><input ${directives.elifAttr}="{{node.tag=='input'}}" ${attrs} value="{{node.props.value}}" data-wv-jsx-handler="{{node.events.input||node.events.change}}" ${bindInput}="${WEVU_JSX_ISLAND_HANDLER}" ${bindChange}="${WEVU_JSX_ISLAND_HANDLER}" /><image ${directives.elifAttr}="{{node.tag=='image'}}" ${tapAttrs} src="{{node.props.src}}" /><block ${directives.elseAttr}>${childTemplate}</block></template>`}).join(``)}function resolveImportedExpression(node,context){if(!context.filename||!context.moduleResolver)return;let localName;let importedName;if(t.isIdentifier(node))localName=node.name;else if(t.isMemberExpression(node)&&!node.computed&&t.isIdentifier(node.object)&&t.isIdentifier(node.property)){localName=node.object.name;importedName=node.property.name}if(!localName)return;const binding=context.importedBindings?.get(localName);if(!binding)return;if(binding.importedName!==`*`&&importedName)return;const resolvedName=importedName??binding.importedName;const key=`${context.filename}:${localName}:${resolvedName}`;if(context.resolvingExports?.has(key)){context.warnings.push(`[JSX 编译] 跨文件 JSX 导出循环引用:${localName}`);return}context.resolvingExports?.add(key);try{return context.moduleResolver.resolveImport(context.filename,binding.source,resolvedName)}finally{context.resolvingExports?.delete(key)}}function compileImportedExpression(node,context){const resolved=resolveImportedExpression(node,context);if(!resolved||resolved.params.length>0){const importedLocal=t.isIdentifier(node)?node.name:t.isMemberExpression(node)&&t.isIdentifier(node.object)?node.object.name:``;if(context.importedBindings?.has(importedLocal)){context.warnings.push(`[JSX 编译] 无法静态展开跨文件 JSX 导出,已生成 dynamic island:${importedLocal||`unknown`}`);return registerDynamicIsland(node,context,`unsupported-import`)}return null}return compileRenderableExpression(resolved.expression,context)}function compileImportedFactoryCall(node,context){if(!t.isIdentifier(node.callee)||!context.filename||!context.moduleResolver)return null;const binding=context.importedBindings?.get(node.callee.name);if(!binding)return null;const resolved=context.moduleResolver.resolveImport(context.filename,binding.source,binding.importedName);if(!resolved||resolved.params.length===0){context.warnings.push(`[JSX 编译] 无法静态展开 JSX 工厂 ${node.callee.name},已生成 dynamic island。`);return registerDynamicIsland(node,context,`unsupported-call`)}const replacements=/* @__PURE__ */ new Map;resolved.params.forEach((param,index)=>{const argument=node.arguments[index];if(argument&&t.isExpression(argument))replacements.set(param,argument)});if(replacements.size!==resolved.params.length){context.warnings.push(`[JSX 编译] JSX 工厂 ${node.callee.name} 调用参数不足,已保留运行时表达式。`);return null}const expression=t.cloneNode(resolved.expression,true);const file=t.file(t.program([t.expressionStatement(expression)]));traverse(file,{ReferencedIdentifier(path){const replacement=replacements.get(path.node.name);if(replacement)path.replaceWith(t.cloneNode(replacement,true))}});const output=file.program.body[0];if(!t.isExpressionStatement(output))return null;let expanded=output.expression;if(t.isCallExpression(expanded)&&expanded.arguments.length===0){const callee=expanded.callee;if(t.isArrowFunctionExpression(callee)||t.isFunctionExpression(callee)){const body=callee.body;let capturesThis=false;if(t.isExpression(body)){const file=t.file(t.program([t.expressionStatement(body)]));traverse(file,{ThisExpression(){capturesThis=true}});if(!capturesThis)expanded=body}}}return compileRenderableExpression(expanded,context)}function compileMapExpression(exp,context){const callee=exp.callee;if(!t.isMemberExpression(callee)||!t.isIdentifier(callee.property,{name:`map`}))return null;const callback=exp.arguments[0];if(!callback||!(t.isArrowFunctionExpression(callback)||t.isFunctionExpression(callback))){context.warnings.push(`仅支持 map(fn) 形式的列表渲染。`);return null}recordJsxBinding(context,callee.object,`for`);const listExp=compileListExpression(callee.object,context);const renderTemplateMustache=expression=>renderMustache(expression,context);const itemParam=callback.params[0];const indexParam=callback.params[1];const item=t.isIdentifier(itemParam)?itemParam.name:`item`;const index=t.isIdentifier(indexParam)?indexParam.name:void 0;const addedScope=[item,index].filter(name=>!!name);pushScope(context,addedScope,listExp);let bodyExp=null;if(t.isBlockStatement(callback.body)){for(const statement of callback.body.body)if(t.isReturnStatement(statement)&&statement.argument){bodyExp=unwrapTsExpression(statement.argument);break}}else bodyExp=unwrapTsExpression(callback.body);const body=bodyExp?compileRenderableExpression(bodyExp,context):``;if(!body){popScope(context,addedScope.length);return``}let keyValue=context.platform.keyThisValue;if(bodyExp&&t.isJSXElement(bodyExp)){const extracted=extractJsxKeyExpression(bodyExp,context);if(extracted)keyValue=extracted;else if(index)keyValue=index}else if(index)keyValue=index;popScope(context,addedScope.length);return`<block ${[...context.platform.forAttrs(listExp,renderTemplateMustache,item,index),context.platform.keyAttr(keyValue)].join(` `)}>${body}</block>`}function compileConditionalExpression(exp,context){const renderTemplateMustache=expression=>renderMustache(expression,context);recordJsxBinding(context,exp.test,`if`);const test=normalizeInterpolationExpression(exp.test,context);const consequent=compileRenderableExpression(exp.consequent,context);const alternate=compileRenderableExpression(exp.alternate,context);if(!alternate)return context.platform.wrapIf(test,consequent,renderTemplateMustache);return`${context.platform.wrapIf(test,consequent,renderTemplateMustache)}${context.platform.wrapElse(alternate)}`}function compileLogicalExpression(exp,context){const renderTemplateMustache=expression=>renderMustache(expression,context);recordJsxBinding(context,exp.left,`if`);if(exp.operator===`&&`){const test=normalizeInterpolationExpression(exp.left,context);const content=compileRenderableExpression(exp.right,context);return context.platform.wrapIf(test,content,renderTemplateMustache)}if(exp.operator===`||`){const negated=t.unaryExpression(`!`,t.parenthesizedExpression(t.cloneNode(exp.left,true)));const test=normalizeInterpolationExpression(negated,context);const content=compileRenderableExpression(exp.right,context);return context.platform.wrapIf(test,content,renderTemplateMustache)}return renderMustache(normalizeInterpolationExpression(exp,context),context)}function compileRenderableExpression(exp,context){const node=unwrapTsExpression(exp);if(t.isJSXElement(node))return compileJsxElement(node,context);if(t.isJSXFragment(node))return compileJsxFragment(node,context);if(t.isConditionalExpression(node))return compileConditionalExpression(node,context);if(t.isLogicalExpression(node))return compileLogicalExpression(node,context);if(t.isCallExpression(node)){const importedFactory=compileImportedFactoryCall(node,context);if(importedFactory!=null)return importedFactory;const mapped=compileMapExpression(node,context);if(mapped!=null)return mapped;context.warnings.push(`无法证明 JSX 子节点函数调用返回静态文本,已生成 dynamic island。`);return registerDynamicIsland(node,context,`unsupported-call`)}if(t.isArrayExpression(node))return node.elements.map(element=>{if(!element||!t.isExpression(element))return``;return compileRenderableExpression(element,context)}).join(``);if(t.isIdentifier(node)||t.isMemberExpression(node)){const imported=compileImportedExpression(node,context);if(imported!=null)return imported}if(t.isNullLiteral(node)||t.isBooleanLiteral(node))return``;recordJsxBinding(context,node,`text`);return renderMustache(normalizeInterpolationExpression(node,context),context)}function compileExpressionContainer(node,context){const exp=node.expression;if(t.isJSXEmptyExpression(exp))return``;return compileRenderableExpression(exp,context)}function compileJsxChildren(children,context){const parts=[];for(const child of children){if(t.isJSXText(child)){const normalized=normalizeJsxText(child.value);if(!normalized.trim())continue;parts.push(escapeText(normalized));continue}if(t.isJSXExpressionContainer(child)){const chunk=compileExpressionContainer(child,context);if(chunk)parts.push(chunk);continue}if(t.isJSXElement(child)){parts.push(compileJsxElement(child,context));continue}if(t.isJSXFragment(child)){parts.push(compileJsxFragment(child,context));continue}if(t.isJSXSpreadChild(child)){parts.push(registerDynamicIsland(child.expression,context,`spread-child`));context.warnings.push(`JSX spread child 无法映射为静态 WXML,已生成 dynamic island。`)}}return parts.join(``)}function compileJsxFragment(node,context){return compileJsxChildren(node.children,context)}function compileJsxElement(node,context){if(t.isJSXMemberExpression(node.openingElement.name)){context.warnings.push(`JSX 成员标签(如 <Foo.Bar />)无法映射为小程序 WXML 组件标签,已生成 dynamic island。`);return registerDynamicIsland(node,context,`dynamic-component`)}const rawTag=toJsxTagName(node.openingElement.name,context);if(rawTag===`Teleport`)return compileJsxTeleport(node,context,compileJsxChildren,registerDynamicIsland);const dynamicSpread=node.openingElement.attributes.find(attr=>{if(!t.isJSXSpreadAttribute(attr))return false;const argument=unwrapTsExpression(attr.argument);return!t.isObjectExpression(argument)||argument.properties.some(property=>!t.isObjectProperty(property)||property.computed||!t.isIdentifier(property.key)&&!t.isStringLiteral(property.key)||!t.isExpression(property.value))});if(dynamicSpread&&t.isJSXSpreadAttribute(dynamicSpread)){context.warnings.push(`动态 JSX spread attributes 无法映射为静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`dynamic-spread`)}if(rawTag===`component`){context.warnings.push(`JSX 动态 component 无法映射为静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`dynamic-component`)}if(rawTag===`Transition`){context.warnings.push(`JSX <Transition> 需要 Web 动画运行时,当前仅渲染子节点。`);return compileJsxChildren(node.children,context)}if(rawTag===`KeepAlive`){context.warnings.push(`JSX <KeepAlive> 需要运行时缓存管理,当前仅保留标记并渲染子节点。`);return`<block data-keep-alive="true">${compileJsxChildren(node.children,context)}</block>`}const isComponent=!isBuiltinComponent(rawTag);const tag=isComponent?hyphenate(rawTag):rawTag;if(node.children.some(child=>{if(!t.isJSXExpressionContainer(child)||t.isJSXEmptyExpression(child.expression))return false;const expression=unwrapTsExpression(child.expression);return t.isObjectExpression(expression)||t.isFunctionExpression(expression)||t.isArrowFunctionExpression(expression)})){context.warnings.push(`JSX slot 函数或对象 slots 无法映射为静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`closure`)}if(node.openingElement.attributes.some(attribute=>{if(!t.isJSXAttribute(attribute)||!t.isJSXIdentifier(attribute.name))return false;if(attribute.name.name!==`class`&&attribute.name.name!==`className`&&attribute.name.name!==`style`)return false;const expression=readJsxAttributeExpression(attribute.value);return!!expression&&(t.isArrayExpression(expression)||t.isObjectExpression(expression))&&!isStaticClassStyleExpression(expression)})){context.warnings.push(`动态 JSX class/style 数组或对象需要运行时合并,已生成 dynamic island。`);return registerDynamicIsland(node,context,`closure`)}const directives=collectJsxDirectives(node);if(directives.has(`v-for`)||directives.has(`v-slots`)||directives.has(`v-model`)||directives.has(`v-models`)){const directive=[`v-for`,`v-slots`,`v-model`,`v-models`].find(name=>directives.has(name));if(directive===`v-model`||directive===`v-models`)context.bindingManifest.features.model=true;context.warnings.push(`JSX ${directive} 无法直接映射当前静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`closure`)}const attrs=compileJsxAttributes(node.openingElement.attributes,context,{isComponent,tagName:tag});const showExpression=directives.get(`v-show`);if(showExpression){recordJsxBinding(context,showExpression,`style`);attrs.push(`hidden="${renderMustache(`!(${normalizeInterpolationExpression(showExpression,context)})`,context)}"`)}const attrsSegment=attrs.length?` ${attrs.join(` `)}`:``;const textExpression=directives.get(`v-text`);if(textExpression)recordJsxBinding(context,textExpression,`text`);const content=textExpression?renderMustache(normalizeInterpolationExpression(textExpression,context),context):compileJsxChildren(node.children,context);const element=node.openingElement.selfClosing&&!textExpression?`<${tag}${attrsSegment} />`:`<${tag}${attrsSegment}>${content}</${tag}>`;const ifExpression=directives.get(`v-if`);if(ifExpression){recordJsxBinding(context,ifExpression,`if`);return context.platform.wrapIf(normalizeInterpolationExpression(ifExpression,context),element,expression=>renderMustache(expression,context))}return element}function createJsxCompileContext(options){return{platform:options?.template?.platform??getMiniProgramTemplatePlatform(),mustacheInterpolation:options?.template?.mustacheInterpolation??`compact`,formatWxml:options?.template?.formatWxml??false,warnings:[],warningDiagnostics:/* @__PURE__ */ new Map,bindingManifest:createBindingManifest(options?.bindingManifestSourceFile??``),inlineExpressions:[],classStyleBindings:[],forStack:[],interpolationCache:/* @__PURE__ */ new WeakMap,inlineExpressionSeed:0,scopeStack:[],bindingScopeStack:[],moduleResolver:void 0,importedBindings:/* @__PURE__ */ new Map,resolvingExports:/* @__PURE__ */ new Set,dynamicIslands:[],dynamicIslandSeed:0,dynamicIslandMode:`auto`,baseLibrary:createBaseLibraryCompileContext({version:options?.template?.baseLibraryVersion,hintState:options?.template?.baseLibraryHintState}),teleport:{enabled:options?.template?.teleport?.enabled??true,unsupported:options?.template?.teleport?.unsupported===`error`?`error`:`warn`}}}function collectImportedBindings(ast,context){for(const statement of ast.program.body){if(!t.isImportDeclaration(statement))continue;const source=statement.source.value;for(const specifier of statement.specifiers)if(t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.local)){const importedName=t.isIdentifier(specifier.imported)?specifier.imported.name:specifier.imported.value;context.importedBindings?.set(specifier.local.name,{source,importedName})}else if(t.isImportDefaultSpecifier(specifier)&&t.isIdentifier(specifier.local))context.importedBindings?.set(specifier.local.name,{source,importedName:`default`});else if(t.isImportNamespaceSpecifier(specifier)&&t.isIdentifier(specifier.local))context.importedBindings?.set(specifier.local.name,{source,importedName:`*`})}}function compileJsxTemplateAndCollectComponents(source,filename,options){const ast=parse$3(source,{...BABEL_TS_MODULE_PARSER_OPTIONS,sourceFilename:filename});const context=createJsxCompileContext(options);context.filename=filename;context.bindingManifest.sourceFile=options?.bindingManifestSourceFile??filename;context.moduleResolver=createJsxModuleResolver(context.warnings,options?.jsx?.readFile);collectImportedBindings(ast,context);const{renderExpression,autoComponentContext}=analyzeJsxAst(ast,context);let template;if(renderExpression){template=compileRenderableExpression(renderExpression,context);if(context.dynamicIslands?.length)template+=renderDynamicIslandSupportTemplate(context);if(context.formatWxml)template=formatWxml(template)}else context.warnings=context.warnings.map(message=>message===`未识别到默认导出组件。`?`未在 ${filename} 中识别到默认导出组件。`:message);return{template,warnings:context.warnings,warningDiagnostics:context.warningDiagnostics,bindingManifest:context.bindingManifest,inlineExpressions:context.inlineExpressions,classStyleBindings:context.classStyleBindings,autoComponentContext,dynamicIslands:context.dynamicIslands,dependencies:context.moduleResolver.getDependencies()}}function printExpression(expression){return expression&&generate(expression,{compact:true}).code}function serializeForScope(scope){const{listExpAst,rawListExpAst,projectedListExpAst,...values}=scope;return{...values,listExpression:printExpression(listExpAst),rawListExpression:printExpression(rawListExpAst),projectedListExpression:printExpression(projectedListExpAst)}}function createJsxTemplateRegistrationSignature(options){const bindings=options.classStyleBindings.map(({expAst,forStack,conditions,...binding})=>({...binding,expression:printExpression(expAst),forStack:forStack.map(serializeForScope),conditions:conditions?.map(condition=>({expression:printExpression(condition.expAst),rawExpression:printExpression(condition.rawExpAst),forDepth:condition.forDepth}))}));return createHash(`sha256`).update(JSON.stringify([options.template,options.inlineExpressions,bindings,options.dynamicIslands])).digest(`hex`)}const LEADING_DOT_RE=/^\./;const SETUP_CALL_RE$1=/\bsetup\s*\(/;function normalizeUsingComponentFrom(value){if(!value)return;return typeof value===`string`?value:value.from}function toMiniProgramComponentTag(name){return name.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).replace(/([A-Z]+)([A-Z][a-z])/g,`$1-$2`).toLowerCase()}async function compileJsxFile(source,filename,options){if(isNativeDomCompilation(options))throw new Error(`[wevu] native-dom 暂只支持带 template 的 Vue SFC,不支持 JSX/TSX 入口`);if(options?.isPage&&mayContainPageDeclaration(source))source=stripPageDeclaration(source,filename)?.code??source;const jsonKind=options?.json?.kind??(options?.isApp?`app`:options?.isPage?`page`:`component`);const jsonDefaults=options?.json?.defaults?.[jsonKind];const mergeJson=createJsonMerger(options?.json?.mergeStrategy,{filename,kind:jsonKind});let scriptSource=source;let scriptMacroConfig;let scriptMacroHash;const scriptLang=path.extname(filename).replace(LEADING_DOT_RE,``)||void 0;if(mayContainJsonMacro(source))try{const extracted=await extractJsonMacroFromScriptSetup(source,filename,scriptLang,{merge:(target,incoming)=>mergeJson(target,incoming,`macro`)});scriptSource=extracted.stripped;scriptMacroConfig=extracted.config;scriptMacroHash=extracted.macroHash}catch(error){const message=error instanceof Error?error.message:String(error);throw new Error(`解析 ${filename} 失败:${message}`)}const{template:rawTemplate,warnings:templateWarnings,warningDiagnostics,bindingManifest,inlineExpressions,classStyleBindings,autoComponentContext,dynamicIslands,dependencies}=compileJsxTemplateAndCollectComponents(source,filename,options);const autoUsingComponentsMap={};const localComponentAliases=/* @__PURE__ */ new Map;if(options?.autoUsingComponents?.resolveUsingComponentPath&&autoComponentContext.templateTags.size>0)for(const imported of autoComponentContext.importedComponents){if(!autoComponentContext.templateTags.has(imported.localName))continue;let resolved=normalizeUsingComponentFrom(await options.autoUsingComponents.resolveUsingComponentPath(imported.importSource,filename,{localName:imported.localName,importedName:imported.importedName,kind:imported.kind}));if(!resolved&&imported.importSource.startsWith(`/`))resolved=removeExtensionDeep(imported.importSource);if(!resolved)continue;const componentName=imported.importSource.startsWith(`.`)||imported.importSource.startsWith(`/`)?toMiniProgramComponentTag(imported.localName):imported.localName;autoUsingComponentsMap[componentName]=resolved;if(componentName!==imported.localName)localComponentAliases.set(imported.localName,componentName)}const autoImportTagsMap={};if(options?.autoImportTags?.resolveUsingComponent&&autoComponentContext.templateTags.size>0)for(const tag of autoComponentContext.templateTags){if(!isAutoImportCandidateTag(tag))continue;let resolved;try{resolved=await options.autoImportTags.resolveUsingComponent(tag,filename)}catch{resolved=void 0}if(!resolved?.from)continue;const resolvedName=resolved.name||tag;autoImportTagsMap[localComponentAliases.get(resolvedName)??resolvedName]=resolved.from}let compiledTemplateStr=rawTemplate;for(const[from,to]of localComponentAliases)if(compiledTemplateStr)compiledTemplateStr=compiledTemplateStr.replaceAll(`<${from}`,`<${to}`).replaceAll(`</${from}>`,`</${to}>`);if(compiledTemplateStr&&(options?.pageLayout||options?.appShell))compiledTemplateStr=applyCompilerTemplateWrappers({template:compiledTemplateStr,manifest:bindingManifest,platform:options?.template?.platform??getMiniProgramTemplatePlatform(),pageLayout:options?.pageLayout,appShell:options?.appShell});const normalizedScriptSource=injectDynamicIslandRuntime(stripRenderOptionFromScript(scriptSource,filename,templateWarnings),dynamicIslands);const{transformVueJsxScript}=await import(`./vueJsxTransform-C4lhnLbg.mjs`);const vueJsxTransformed=transformVueJsxScript(normalizedScriptSource,filename,options?.sourceMap!==false);const runtimeCapabilities=createWevuRuntimeCapabilityMetadataFromBindingManifest(bindingManifest);const transformedScript=transformScript(vueJsxTransformed.code,{skipComponentTransform:options?.skipComponentTransform??options?.isApp,isApp:options?.isApp,isPage:options?.isPage,minify:options?.minify,sourceMap:options?.sourceMap,warn:options?.warn,wevuDefaults:options?.wevuDefaults,inlineExpressions,classStyleBindings,bindingManifest:options?.isApp?void 0:bindingManifest,autoSetDataPick:!options?.isApp&&options?.autoSetDataPick,runtimeBindingManifest:options?.runtimeBindingManifest,pageLayout:options?.isApp?void 0:options?.pageLayout,runtimeCapabilities});const diagnostics=templateWarnings.length?createJsxDiagnostics(templateWarnings,filename,warningDiagnostics):void 0;reportJsxDiagnostics(diagnostics,options?.warn);let configObj;if(Object.keys(autoUsingComponentsMap).length>0||Object.keys(autoImportTagsMap).length>0){const existingRaw=configObj?.usingComponents;const usingComponents=existingRaw&&typeof existingRaw===`object`&&!Array.isArray(existingRaw)?existingRaw:{};for(const[name,from]of Object.entries(autoImportTagsMap)){if(Reflect.has(usingComponents,name)&&usingComponents[name]!==from)options?.autoImportTags?.warn?.(`[JSX 编译] usingComponents 冲突:${filename} 中 usingComponents['${name}']='${usingComponents[name]}' 将被 JSX 标签自动引入覆盖为 '${from}'`);usingComponents[name]=from}for(const[name,from]of Object.entries(autoUsingComponentsMap)){if(Reflect.has(usingComponents,name)&&usingComponents[name]!==from)options?.autoUsingComponents?.warn?.(`[JSX 编译] usingComponents 冲突:${filename} 中 usingComponents['${name}']='${usingComponents[name]}' 将被 JSX 导入组件覆盖为 '${from}'`);usingComponents[name]=from}configObj=mergeJson(configObj??{},{usingComponents},`auto-using-components`)}if(jsonDefaults&&Object.keys(jsonDefaults).length>0)configObj=mergeJson(configObj??{},jsonDefaults,`defaults`);if(scriptMacroConfig&&Object.keys(scriptMacroConfig).length>0)configObj=mergeJson(configObj??{},scriptMacroConfig,`macro`);const config=mergeCompilerLayoutUsingComponents(configObj&&Object.keys(configObj).length>0?JSON.stringify(configObj,null,2):void 0,options?.pageLayout,options?.appShell);return{script:transformedScript.code,scriptMap:transformedScript.map??vueJsxTransformed.map,template:compiledTemplateStr,diagnostics,bindingManifest,config,meta:{hasScriptSetup:false,hasSetupOption:SETUP_CALL_RE$1.test(normalizedScriptSource),jsonMacroHash:scriptMacroHash,jsxDynamicIslands:dynamicIslands,templateRegistrationSignature:createJsxTemplateRegistrationSignature({template:compiledTemplateStr,inlineExpressions,classStyleBindings,dynamicIslands}),...transformedScript.componentStyleOptions?{componentStyleOptions:transformedScript.componentStyleOptions}:{},...transformedScript.runtimeCapabilities?{runtimeCapabilities:transformedScript.runtimeCapabilities}:{},jsxDependencies:dependencies}}}const DIRECTIVE_TOKEN_RE=/\/\/\s*#(?:ifdef|ifndef|else|endif)\b[^\r\n]*|\/\*+\s*#(?:ifdef|ifndef|else|endif)\b[\s\S]*?\*\/|<!--\s*#(?:ifdef|ifndef|else|endif)\b[\s\S]*?-->/g;const SCRIPT_EXT_RE=/\.[cm]?[jt]sx?$/i;const STYLE_EXT_RE=/\.(?:css|less|sass|scss|styl|stylus)$/i;const UNI_APP_RUNTIME_MODULE=`@dcloudio/uni-app`;function resolveRuntimeImport(source){if(source===`vue`||source===UNI_APP_RUNTIME_MODULE)return`wevu`}function evaluateCondition(expression,defines,filename,line){const normalized=expression.replace(/(?:\*\/|-->)\s*$/,``).trim();const tokens=normalized.match(/[A-Z][A-Z0-9_-]*|&&|\|\||[()!]/g)??[];if(!tokens.length||tokens.join(``)!==normalized.replace(/\s/g,``))throw new Error(`[uni-app] ${filename}:${line} 包含无效的条件表达式 "${normalized}"`);let index=0;const parser={parseAnd(){let value=parser.parsePrimary();while(tokens[index]===`&&`){index+=1;const right=parser.parsePrimary();value=value&&right}return value},parseOr(){let value=parser.parseAnd();while(tokens[index]===`||`){index+=1;const right=parser.parseAnd();value=value||right}return value},parsePrimary(){const token=tokens[index];if(token===`!`){index+=1;return!parser.parsePrimary()}if(token===`(`){index+=1;const value=parser.parseOr();if(tokens[index]!==`)`)throw new Error(`[uni-app] ${filename}:${line} 包含无效的条件表达式 "${normalized}"`);index+=1;return value}if(!token||!/^[A-Z][A-Z0-9_-]*$/.test(token))throw new Error(`[uni-app] ${filename}:${line} 包含无效的条件表达式 "${normalized}"`);index+=1;return defines.has(token)}};const value=parser.parseOr();if(index!==tokens.length)throw new Error(`[uni-app] ${filename}:${line} 包含无效的条件表达式 "${normalized}"`);return value}function transformUniAppConditionalCode(source,options){const defines=new Set(options.target===`h5`?[`H5`,`VUE3`]:[`MP`,`MP-WEIXIN`,`VUE3`]);const frames=[];let active=true;let changed=false;let cursor=0;let line=1;let code=``;for(const match of source.matchAll(DIRECTIVE_TOKEN_RE)){const offset=match.index;const segment=source.slice(cursor,offset);code+=active?segment:segment.replace(/[^\r\n]/g,``);line+=segment.split(`
25
25
  `).length-1;const directiveSource=match[0].slice(match[0].indexOf(`#`));const directiveMatch=directiveSource.match(/^#(ifdef|ifndef|else|endif)\b/);if(!directiveMatch)continue;changed=true;const directive=directiveMatch[1];if(directive===`ifdef`||directive===`ifndef`){const condition=evaluateCondition(directiveSource.slice(directiveMatch[0].length),defines,options.filename,line);frames.push({condition,elseSeen:false,parentActive:active});active=active&&(directive===`ifdef`?condition:!condition)}else{const frame=frames[frames.length-1];if(!frame)throw new Error(`[uni-app] ${options.filename}:${line} 存在未配对的 #${directive}`);if(directive===`else`){if(frame.elseSeen)throw new Error(`[uni-app] ${options.filename}:${line} 同一条件块不能出现多个 #else`);frame.elseSeen=true;active=frame.parentActive&&!frame.condition}else{frames.pop();active=frame.parentActive}}code+=match[0].replace(/[^\r\n]/g,``);line+=match[0].split(`
26
26
  `).length-1;cursor=offset+match[0].length}const trailing=source.slice(cursor);code+=active?trailing:trailing.replace(/[^\r\n]/g,``);if(frames.length)throw new Error(`[uni-app] ${options.filename} 存在未闭合的条件编译块`);return{changed,code}}function normalizeAuxiliaryWxsScripts(source){const wxsBlocks=[];const withoutScripts=source.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,(block,attributes,content)=>{const src=attributes.match(/\bsrc\s*=\s*["']([^"']+)["']/i)?.[1];const moduleName=attributes.match(/\bmodule\s*=\s*["']([^"']+)["']/i)?.[1];if(!(/\blang\s*=\s*["']wxs["']/i.test(attributes)||src?.endsWith(`.wxs`))||!moduleName)return block;wxsBlocks.push(src?`<wxs module="${moduleName}" src="${src}" />`:`<wxs module="${moduleName}">${content}</wxs>`);return block.replace(/[^\r\n]/g,``)});if(!wxsBlocks.length)return source;return withoutScripts.replace(/<template\b[^>]*>/i,match=>`${match}\n${wxsBlocks.join(`
27
27
  `)}`)}function analyzeScript$1(source,filename){if(!source.trim())return{source,importSources:[],importEnd:0,usesFreeUni:false,virtualHostTrueRanges:[]};const isJsx=/\.[cm]?[jt]sx$/i.test(filename);const ast=parse$3(source,{sourceType:`module`,plugins:[`typescript`,`decorators-legacy`,...isJsx?[`jsx`]:[]]});const importSources=[];let importEnd=0;let usesFreeUni=false;const virtualHostTrueRanges=[];traverse(ast,{ImportDeclaration(path){const sourceNode=path.node.source;if(typeof path.node.end===`number`)importEnd=Math.max(importEnd,path.node.end);const replacement=t.isStringLiteral(sourceNode)?resolveRuntimeImport(sourceNode.value):void 0;if(replacement)importSources.push({start:sourceNode.start,end:sourceNode.end,replacement})},ExportAllDeclaration(path){const sourceNode=path.node.source;const replacement=t.isStringLiteral(sourceNode)?resolveRuntimeImport(sourceNode.value):void 0;if(replacement)importSources.push({start:sourceNode.start,end:sourceNode.end,replacement})},ExportNamedDeclaration(path){const sourceNode=path.node.source;const replacement=t.isStringLiteral(sourceNode)?resolveRuntimeImport(sourceNode.value):void 0;if(replacement)importSources.push({start:sourceNode.start,end:sourceNode.end,replacement})},ReferencedIdentifier(path){if(path.node.name===`uni`&&!path.scope.hasBinding(`uni`))usesFreeUni=true},ObjectProperty(path){const key=path.node.key;if(!(!path.node.computed&&(t.isIdentifier(key,{name:`virtualHost`})||t.isStringLiteral(key,{value:`virtualHost`})))||!t.isBooleanLiteral(path.node.value,{value:true})||!path.parentPath?.isObjectExpression())return;const optionsProperty=path.parentPath.parentPath;if(!optionsProperty?.isObjectProperty()||optionsProperty.node.computed||!(t.isIdentifier(optionsProperty.node.key,{name:`options`})||t.isStringLiteral(optionsProperty.node.key,{value:`options`})))return;const{start,end}=path.node.value;if(typeof start===`number`&&typeof end===`number`)virtualHostTrueRanges.push({start,end})}});return{source,importSources,importEnd,usesFreeUni,virtualHostTrueRanges}}function renderScript(analysis,injectUni,disableVirtualHost){const output=new MagicString(analysis.source);for(const source of analysis.importSources)output.overwrite(source.start,source.end,JSON.stringify(source.replacement));if(injectUni){const insertion=analysis.importEnd>0?analysis.importEnd:0;output.prepend(`import { createUniAppHost as __wevuCreateUniAppHost } from 'wevu/internal-runtime'\n`);output.appendLeft(insertion,`${insertion>0?`
@@ -35,8 +35,8 @@ const __weapp_defineOptions = (value) => (__weapp_define_options_values.push(val
35
35
  `);const evalSource=`${header+ms.toString()+(scopeFooter?`\n${scopeFooter}\n`:`
36
36
  `)}export const __weapp_define_scope = __weapp_define_scope_values\n
37
37
  export const __weapp_define_options = __weapp_define_options_values
38
- `;return await withTempDirLock(tempRoot,async()=>{await ensureDir(tempDir);const tempFile=path.join(tempDir,`${basename}.define-options.${unique}.${extension}`);await writeFile(tempFile,evalSource,`utf8`);try{const{mod,dependencies}=await bundleRequire({filepath:tempFile,cwd:dir,tsconfig:false});const exported=mod?.__weapp_define_options??mod;return{values:Array.isArray(exported)?exported:[exported],dependencies,scopeValues:mod?.__weapp_define_scope??{}}}finally{try{await remove(tempDir)}catch{}}})}async function resolveDefineOptionsValue(raw){let next=raw;if(typeof next===`function`)next=next();if(next&&typeof next.then===`function`)next=await next;if(!next||typeof next!==`object`||Array.isArray(next))throw new Error(`defineOptions 的参数最终必须解析为对象。`);return next}async function inlineScriptSetupDefineOptionsArgs(content,filename,lang,sourceMap){const{statements}=collectDefineOptionsStatements(content,filename);if(!statements.length)return{code:content,dependencies:[]};let values=[];let dependencies=[];let scopeValues={};const staticValues=resolveStaticDefineOptionsValues(statements);if(staticValues)values=staticValues;else{scopeValues=collectStaticTopLevelScopeValues(content);try{const evaluated=await evaluateDefineOptionsValues({content,filename,lang,statements});values=evaluated.values;dependencies=evaluated.dependencies;scopeValues={...scopeValues,...evaluated.scopeValues}}catch(error){if(shouldFallbackToRawDefineOptions(error))return{code:content,dependencies:[]};throw error}}const ms=sourceMap?new MagicString(sourceMap.source,{offset:sourceMap.offset}):new MagicString(content);for(let index=0;index<statements.length;index+=1){const argNode=statements[index].argPath?.node;if(!argNode||typeof argNode.start!==`number`||typeof argNode.end!==`number`)continue;const value=await resolveDefineOptionsValue(values[index]);const literal=serializeStaticValueToExpression(value,/* @__PURE__ */ new WeakSet,scopeValues);ms.overwrite(argNode.start,argNode.end,literal)}const code=sourceMap?ms.slice(0,content.length):ms.toString();const result={code,dependencies:dependencies.filter(Boolean)};if(!sourceMap||code===content)return result;const sourceFile=sourceMap.sourceFile;let map;return{...result,get map(){return map??=ms.generateMap({hires:true,includeContent:true,source:sourceFile})}}}const EXPORT_DEFAULT_RE=/\bexport\s+default\b/;function mayHaveDefaultExport(scriptCode){return EXPORT_DEFAULT_RE.test(scriptCode)}function hasDefaultExport(scriptCode,nativeAnalysis){if(!mayHaveDefaultExport(scriptCode))return false;if(nativeAnalysis?.hasDefaultExport!==void 0)return nativeAnalysis.hasDefaultExport;try{const ast=parseJsLike(scriptCode);let found=false;traverse(ast,{ExportDefaultDeclaration(path){found=true;path.stop()}});return found}catch{return mayHaveDefaultExport(scriptCode)}}function mayShareNativeOptionsAnalysis(scriptCode,template){if(!template?.ast||template.src||!mayHaveDefaultExport(scriptCode))return false;const hasComponentTag=node=>{if(node.type!==NodeTypes.ELEMENT)return false;if(!RESERVED_VUE_COMPONENT_TAGS.has(node.tag)&&!isBuiltinComponent(node.tag))return true;return node.children.some(hasComponentTag)};return template.ast.children.some(hasComponentTag)}function resolveScriptFilename(filename,lang){return`${filename}.${lang===`tsx`||lang===`jsx`||lang===`js`?lang:`ts`}`}function analyzeNativeScriptBlocks(descriptor,filename,defineOptionsSource){const blocks=[[`script`,descriptor.script],[`scriptSetup`,descriptor.scriptSetup],[`defineOptions`,defineOptionsSource]].filter(entry=>Boolean(entry[1]));if(!blocks.length)return;try{const results=analyzeCompilerScriptsWithNative(blocks.map(([,block])=>({code:block.content,filename:resolveScriptFilename(filename,block.lang)})));if(!results||results.length!==blocks.length)return;const scripts={};let defineOptions;for(const[index,[key]]of blocks.entries()){const result=results[index];if(!result)continue;if(key===`defineOptions`)defineOptions=result;else scripts[key]=result}return{scripts,defineOptions}}catch{return}}const SETUP_CALL_RE=/\bsetup\s*\(/;const DEFINE_OPTIONS_CALL_RE=/\bdefineOptions\s*\(/;const APP_VUE_FILE_RE=/[\\/]app\.vue$/;const TEMPLATE_BLOCK_RE=/<template\b[\s\S]*?<\/template>/g;const TEMPLATE_IMPORT_META_RE=/\bimport\.meta\b/g;const TEMPLATE_IMPORT_META_PLACEHOLDER=`__im_meta__`;function createIdentitySourceMap(source,originalSource,filename){const sourceMap=new MagicString(source).generateMap({hires:true,includeContent:false,source:filename});sourceMap.sourcesContent=[originalSource];return sourceMap}function resolveSfcScriptLangLabel(lang){return typeof lang===`string`&&lang.length>0?lang:`(default)`}function assertMatchingSfcScriptLang(descriptor,filename){const scriptLang=descriptor.script?.lang;const scriptSetupLang=descriptor.scriptSetup?.lang;if(!descriptor.script||!descriptor.scriptSetup||scriptLang===scriptSetupLang)return;throw new Error(`解析 ${filename} 失败:同一个 SFC 中 <script> 与 <script setup> 的 lang 必须一致,当前分别为 ${resolveSfcScriptLangLabel(scriptLang)} 与 ${resolveSfcScriptLangLabel(scriptSetupLang)}`)}function resolveSourcePosition(source,offset){let line=1;let lineStart=0;for(let index=0;index<offset;index+=1){const char=source.charCodeAt(index);if(char===10||char===8232||char===8233){line+=1;lineStart=index+1}else if(char===13){line+=1;if(source.charCodeAt(index+1)===10)index+=1;lineStart=index+1}}return{column:offset-lineStart+1,line,offset}}function replaceScriptSetupContent(descriptor,content){const scriptSetup=descriptor.scriptSetup;const startOffset=scriptSetup.loc.start.offset;const endOffset=scriptSetup.loc.end.offset;const nextSource=descriptor.source.slice(0,startOffset)+content+descriptor.source.slice(endOffset);const delta=content.length-(endOffset-startOffset);const updateBlock=block=>{if(!block)return null;const isSetup=block===scriptSetup;const nextStart=isSetup?startOffset:block.loc.start.offset>=endOffset?block.loc.start.offset+delta:block.loc.start.offset;const nextEnd=isSetup?startOffset+content.length:block.loc.end.offset>=endOffset?block.loc.end.offset+delta:block.loc.end.offset;return{...block,content:isSetup?content:block.content,loc:{source:isSetup?content:block.loc.source,start:resolveSourcePosition(nextSource,nextStart),end:resolveSourcePosition(nextSource,nextEnd)}}};return{...descriptor,source:nextSource,script:updateBlock(descriptor.script),scriptSetup:updateBlock(descriptor.scriptSetup)}}function hashDefineOptionsSources(sources){if(!sources.length)return;return createHash(`sha256`).update(sources.join(`
39
- `)).digest(`hex`).slice(0,12)}function extractDefineOptionsHash(content,analysis){if(analysis)return hashDefineOptionsSources(analysis.defineOptionsStatements.map(({start,end})=>content.slice(start,end)));let ast;try{ast=parse$3(content,BABEL_TS_MODULE_PARSER_OPTIONS)}catch{return}const macroSources=[];traverse(ast,{CallExpression(path){const callee=path.node.callee;if(!t.isIdentifier(callee,{name:`defineOptions`}))return;if(!(path.parentPath?.isExpressionStatement()&&path.parentPath.parentPath?.isProgram()))return;const statement=path.parentPath?.node;if(statement&&typeof statement.start===`number`&&typeof statement.end===`number`)macroSources.push(content.slice(statement.start,statement.end))}});return hashDefineOptionsSources(macroSources)}function preprocessTemplateImportMeta(source){return source.replace(TEMPLATE_BLOCK_RE,block=>block.replace(TEMPLATE_IMPORT_META_RE,TEMPLATE_IMPORT_META_PLACEHOLDER))}function restoreTemplateImportMeta(content){return content.replace(new RegExp(TEMPLATE_IMPORT_META_PLACEHOLDER,`g`),`import.meta`)}function restoreTemplateImportMetaInDescriptor(descriptor){if(!descriptor.template?.content?.includes(TEMPLATE_IMPORT_META_PLACEHOLDER))return descriptor;return{...descriptor,template:{...descriptor.template,content:restoreTemplateImportMeta(descriptor.template.content)}}}async function parseSfc(source,filename,ignoreEmpty,preprocessedSource=preprocessTemplateImportMeta(source)){const parsed=await readAndParseSfc(filename,{source,preprocessedSource,checkMtime:false,ignoreEmpty});return{...parsed,descriptor:restoreTemplateImportMetaInDescriptor(parsed.descriptor)}}function resolvePreprocessSourceMap(sourceMap,transforms){if(transforms)for(const transform of transforms)sourceMap=composeSourceMaps(transform.map,sourceMap);return sourceMap}function hasSharedNativeAnalysis(descriptor,defineOptionsSource,isAppFile){return[descriptor.script,descriptor.scriptSetup,defineOptionsSource].filter(Boolean).length>1||process.env.WEAPP_VITE_NATIVE===`1`&&Boolean(process.env.WEAPP_VITE_NATIVE_AST_PATH?.trim())&&!isAppFile&&!descriptor.scriptSetup&&Boolean(descriptor.script&&mayShareNativeOptionsAnalysis(descriptor.script.content,descriptor.template))}async function parseVueFile(source,filename,options){const normalizedInputSource=normalizeLineEndings(source);let scriptPreprocessMap=null;let deferredPreprocessMaps;if(options?.sourceMap!==false&&normalizedInputSource!==source)scriptPreprocessMap=createIdentitySourceMap(normalizedInputSource,source,filename);const normalizedSource=normalizedInputSource;const parserSource=preprocessTemplateImportMeta(normalizedSource);if(options?.sourceMap!==false&&parserSource!==normalizedSource)scriptPreprocessMap=composeSourceMaps(createIdentitySourceMap(parserSource,normalizedSource,filename),scriptPreprocessMap);let descriptorForCompileSource=normalizedSource;const parsedSfc=await parseSfc(normalizedSource,filename,true,parserSource);const descriptor=parsedSfc.descriptor;const{errors}=parsedSfc;if(errors.length>0)throw createSfcParseError(errors[0],{filename,source,sourceMap:scriptPreprocessMap});let resolvedDescriptor=descriptor;let sfcSrcDeps;let templateResolvedId;let scriptResolvedId;let scriptSetupResolvedId;if(options?.sfcSrc){const resolved=await resolveSfcBlockSrc(descriptor,filename,options.sfcSrc);resolvedDescriptor=resolved.descriptor;templateResolvedId=resolved.templateResolvedId;scriptResolvedId=resolved.scriptResolvedId;scriptSetupResolvedId=resolved.scriptSetupResolvedId;if(resolved.deps.length)sfcSrcDeps=resolved.deps}let routeConfig;let pageMeta;let descriptorForCompile=resolvedDescriptor;let usesExternalScriptCompileSource=false;if(scriptResolvedId||scriptSetupResolvedId||options?.isPage===true&&(mayContainPageDeclaration(normalizedSource)||mayContainPageMeta(normalizedSource))){const stripped=prepareSfcScriptCompile(normalizedSource,filename,resolvedDescriptor,options?.sourceMap!==false,{scriptResolvedId,scriptSetupResolvedId},options?.isPage===true);if(stripped){routeConfig=stripped.routeConfig;pageMeta=stripped.pageMeta;const mainSourcePreprocessMap=scriptPreprocessMap;resolvedDescriptor=stripped.descriptor;usesExternalScriptCompileSource=Boolean(stripped.descriptorForCompile);descriptorForCompile=stripped.descriptorForCompile??stripped.descriptor;descriptorForCompileSource=stripped.descriptorForCompile?.source??stripped.code;const usesExternalNormalScriptCompileSource=Boolean(resolvedDescriptor.script?.src&&!resolvedDescriptor.scriptSetup);if(usesExternalScriptCompileSource)scriptPreprocessMap=composeSourceMapForSource(stripped.scriptMap,mainSourcePreprocessMap,filename);else if(usesExternalNormalScriptCompileSource)scriptPreprocessMap=null;else scriptPreprocessMap=composeSourceMaps(stripped.map,mainSourcePreprocessMap)}}assertMatchingSfcScriptLang(resolvedDescriptor,filename);const meta={routeConfig,pageMeta,hasScriptSetup:!!resolvedDescriptor.scriptSetup,hasSetupOption:!!resolvedDescriptor.script&&SETUP_CALL_RE.test(resolvedDescriptor.script.content),sfcSrcDeps,sfcSrcCompilationDeps:[templateResolvedId,scriptResolvedId,scriptSetupResolvedId].filter(id=>Boolean(id))};let scriptSetupMacroConfig;let scriptSetupMacroHash;let defineOptionsSource;const jsonKind=options?.json?.kind??(options?.isApp?`app`:options?.isPage?`page`:`component`);const jsonDefaults=options?.json?.defaults?.[jsonKind];const mergeJson=createJsonMerger(options?.json?.mergeStrategy,{filename,kind:jsonKind,routeConfig,pageMeta});const scriptSetup=resolvedDescriptor.scriptSetup;if(scriptSetup?.content){const scriptSetupForMap=usesExternalScriptCompileSource?descriptorForCompile.scriptSetup:scriptSetup;if(mayContainJsonMacro(scriptSetup.content)){const extracted=await extractJsonMacroFromScriptSetupWithSourceMap(scriptSetup.content,filename,scriptSetup.lang,{merge:(target,source)=>mergeJson(target,source,`macro`),preambleContent:resolvedDescriptor.script?.content},usesExternalScriptCompileSource||!scriptSetupForMap.src?{source:descriptorForCompileSource,sourceFile:filename,offset:scriptSetupForMap.loc.start.offset}:void 0);if(extracted.stripped!==scriptSetup.content){if(options?.sourceMap===false)(deferredPreprocessMaps??=[]).push(extracted);else scriptPreprocessMap=composeSourceMaps(extracted.map,scriptPreprocessMap);if(usesExternalScriptCompileSource){descriptorForCompile=replaceScriptSetupContent(descriptorForCompile,extracted.stripped);descriptorForCompileSource=descriptorForCompile.source}else if(scriptSetup.src)descriptorForCompile={...descriptorForCompile,scriptSetup:{...descriptorForCompile.scriptSetup,content:extracted.stripped}};else{const setupLoc=scriptSetup.loc;const startOffset=setupLoc.start.offset;const endOffset=setupLoc.end.offset;const nextSource=descriptorForCompileSource.slice(0,startOffset)+extracted.stripped+descriptorForCompileSource.slice(endOffset);const{descriptor:nextDescriptor,errors:nextErrors}=await parseSfc(nextSource,filename,false);if(nextErrors.length>0)throw createSfcParseError(nextErrors[0],{filename,source,sourceMap:resolvePreprocessSourceMap(scriptPreprocessMap,deferredPreprocessMaps)});assertMatchingSfcScriptLang(nextDescriptor,filename);if(options?.sfcSrc){const resolvedNext=await resolveSfcBlockSrc(nextDescriptor,filename,options.sfcSrc);descriptorForCompile=resolvedNext.descriptor;if(resolvedNext.deps.length){sfcSrcDeps=[.../* @__PURE__ */ new Set([...sfcSrcDeps??[],...resolvedNext.deps])];meta.sfcSrcDeps=sfcSrcDeps}}else descriptorForCompile=nextDescriptor;descriptorForCompileSource=nextSource}}scriptSetupMacroConfig=extracted.config;scriptSetupMacroHash=extracted.macroHash}if(DEFINE_OPTIONS_CALL_RE.test(scriptSetup.content))defineOptionsSource=scriptSetup}const compileScriptSetup=descriptorForCompile.scriptSetup;if(compileScriptSetup?.content&&DEFINE_OPTIONS_CALL_RE.test(compileScriptSetup.content)){const inlined=await inlineScriptSetupDefineOptionsArgs(compileScriptSetup.content,filename,compileScriptSetup.lang,usesExternalScriptCompileSource||!compileScriptSetup.src?{source:descriptorForCompileSource,sourceFile:filename,offset:compileScriptSetup.loc.start.offset}:void 0);if(inlined.code!==compileScriptSetup.content){if(options?.sourceMap===false)(deferredPreprocessMaps??=[]).push(inlined);else scriptPreprocessMap=composeSourceMaps(inlined.map,scriptPreprocessMap);if(usesExternalScriptCompileSource){descriptorForCompile=replaceScriptSetupContent(descriptorForCompile,inlined.code);descriptorForCompileSource=descriptorForCompile.source}else if(compileScriptSetup.src)descriptorForCompile={...descriptorForCompile,scriptSetup:{...compileScriptSetup,content:inlined.code}};else{const setupLoc=compileScriptSetup.loc;const startOffset=setupLoc.start.offset;const endOffset=setupLoc.end.offset;const nextSource=descriptorForCompileSource.slice(0,startOffset)+inlined.code+descriptorForCompileSource.slice(endOffset);const{descriptor:nextDescriptor,errors:nextErrors}=await parseSfc(nextSource,filename,false);if(nextErrors.length>0)throw createSfcParseError(nextErrors[0],{filename,source,sourceMap:resolvePreprocessSourceMap(scriptPreprocessMap,deferredPreprocessMaps)});assertMatchingSfcScriptLang(nextDescriptor,filename);if(options?.sfcSrc){const resolvedNext=await resolveSfcBlockSrc(nextDescriptor,filename,options.sfcSrc);descriptorForCompile=resolvedNext.descriptor;if(resolvedNext.deps.length){sfcSrcDeps=[.../* @__PURE__ */ new Set([...sfcSrcDeps??[],...resolvedNext.deps])];meta.sfcSrcDeps=sfcSrcDeps}}else descriptorForCompile=nextDescriptor;descriptorForCompileSource=nextSource}}}const isAppFile=APP_VUE_FILE_RE.test(filename);const nativeAnalysis=hasSharedNativeAnalysis(descriptorForCompile,defineOptionsSource,isAppFile)?analyzeNativeScriptBlocks(descriptorForCompile,filename,defineOptionsSource):void 0;const defineOptionsHash=defineOptionsSource?extractDefineOptionsHash(defineOptionsSource.content,nativeAnalysis?.defineOptions):void 0;return{descriptor:resolvedDescriptor,descriptorForCompile,scriptPreprocessMap,templateResolvedId,meta,scriptSetupMacroConfig,scriptSetupMacroHash,defineOptionsHash,jsonKind,jsonDefaults,mergeJson,isAppFile,nativeScriptAnalysis:nativeAnalysis?.scripts}}function createModuleFacts(id,ast){let scope;traverse(ast,{Program(path){scope=path.scope;path.stop()}});return{id,ast,scope}}function unwrap(node){return t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTSTypeAssertion(node)||t.isTypeCastExpression(node)||t.isParenthesizedExpression(node)?unwrap(node.expression):node}function staticName(node,computed=false){node=unwrap(node);if(t.isStringLiteral(node)||t.isNumericLiteral(node))return String(node.value);if(!computed&&t.isIdentifier(node))return node.name;if(t.isTemplateLiteral(node)&&!node.expressions.length)return node.quasis[0]?.value.cooked??node.quasis[0]?.value.raw}function isImportedCall(node,module,importedName,sources){if(!t.isCallExpression(node)||!t.isIdentifier(node.callee))return false;const importPath=module.scope.getBinding(node.callee.name)?.path;const declaration=importPath?.parentPath;return Boolean(importPath?.isImportSpecifier()&&importPath.node.importKind!==`type`&&t.isIdentifier(importPath.node.imported,{name:importedName})&&declaration?.isImportDeclaration()&&declaration.node.importKind!==`type`&&sources.includes(declaration.node.source.value))}function createPropsModuleResolver(reader,root){const modules=/* @__PURE__ */ new Map([[root.id,Promise.resolve(root)]]);const load=id=>{let task=modules.get(id);if(!task){task=(async()=>{const source=await reader.load(id);if(!source||source.descriptor||source.invalid)return;try{source.ast??=parseJsLike(source.source);return createModuleFacts(id,source.ast)}catch{return}})();modules.set(id,task)}return task};const resolveExport=async(source,importer,name,visiting=/* @__PURE__ */ new Set)=>{const id=await reader.resolve(source,importer);if(!id)return;const key=`${id}\0${name}`;if(visiting.has(key))return;const next=new Set(visiting).add(key);const module=await load(id);if(!module)return;for(const statement of module.ast.program.body){if(name==="default"&&t.isExportDefaultDeclaration(statement))return{node:statement.declaration,module};if(!t.isExportNamedDeclaration(statement)||statement.exportKind===`type`)continue;if(t.isVariableDeclaration(statement.declaration)){for(const declaration of statement.declaration.declarations)if(t.isIdentifier(declaration.id,{name}))return{node:declaration.id,module}}for(const specifier of statement.specifiers){if(!t.isExportSpecifier(specifier)||specifier.exportKind===`type`||staticName(specifier.exported)!==name)continue;const local=staticName(specifier.local);if(statement.source)return local?resolveExport(statement.source.value,module.id,local,next):void 0;return{node:specifier.local,module}}}};const resolveImport=async(node,module)=>{node=unwrap(node);let local;let member;if(t.isIdentifier(node))local=node.name;else if(t.isMemberExpression(node)&&t.isIdentifier(node.object)){local=node.object.name;member=staticName(node.property,node.computed);if(!member)return}const binding=local&&module.scope.getBinding(local);if(!binding||!binding.path.parentPath?.isImportDeclaration()||binding.path.parentPath.node.importKind===`type`)return;const declaration=binding.path.parentPath.node;const specifier=binding.path.node;const name=t.isImportDefaultSpecifier(specifier)&&member===void 0?`default`:t.isImportSpecifier(specifier)&&specifier.importKind!==`type`&&member===void 0?staticName(specifier.imported):t.isImportNamespaceSpecifier(specifier)?member:void 0;return name?resolveExport(declaration.source.value,module.id,name):void 0};return{resolveImport}}function isObjectCall(node,scope,name){return t.isCallExpression(node)&&t.isMemberExpression(node.callee)&&!node.callee.computed&&t.isIdentifier(node.callee.object,{name:`Object`})&&!scope.getBinding(`Object`)&&t.isIdentifier(node.callee.property,{name})}function isGeneratedSetupReturn(reference,setup){const property=reference.parentPath;const object=property?.parentPath;const declaration=object?.parentPath;return Boolean(setup&&property?.isObjectProperty()&&property.node.value===reference.node&&object?.isObjectExpression()&&declaration?.isVariableDeclarator()&&t.isIdentifier(declaration.node.id,{name:`__returned__`})&&declaration.findParent(parent=>parent.node===setup))}function isSafeReference(reference,ownership,visiting){let current=reference;while(current.parentPath&&unwrap(current.parentPath.node)===unwrap(current.node))current=current.parentPath;if(ownership.props&&unwrap(current.node)===unwrap(ownership.props)||isGeneratedSetupReturn(current,ownership.setup))return true;if(current.findParent(parent=>t.isTSType(parent.node)))return true;const parent=current.parentPath;if(parent?.isSpreadElement()&&(parent.parentPath.isObjectExpression()||parent.parentPath.isArrayExpression()))return true;if(parent?.isCallExpression())return isObjectCall(parent.node,parent.scope,`freeze`)&&parent.node.arguments.length===1||isObjectCall(parent.node,parent.scope,`assign`)&&parent.node.arguments.indexOf(current.node)>0;if(parent?.isVariableDeclarator()&&t.isIdentifier(parent.node.id)&&parent.node.init===current.node)return isSafePropsBinding(parent.scope.getBinding(parent.node.id.name),ownership,visiting);return false}function isSafePropsBinding(binding,ownership,visiting=/* @__PURE__ */ new Set){if(!binding?.constant||!binding.path.isVariableDeclarator()||!binding.path.parentPath.isVariableDeclaration()||binding.path.parentPath.node.kind!==`const`||binding.path.parentPath.parentPath?.isExportNamedDeclaration()||visiting.has(binding.path.node))return false;const next=new Set(visiting).add(binding.path.node);return binding.referencePaths.every(reference=>isSafeReference(reference,ownership,next))}const absent={kind:`absent`};const unknown={kind:`unknown`};function isSafeOptionReference(reference,allowed,visiting){let current=reference;while(current.parentPath&&unwrap(current.parentPath.node)===unwrap(current.node))current=current.parentPath;if(allowed.has(unwrap(current.node))||current.findParent(parent=>t.isTSType(parent.node)))return true;const parent=current.parentPath;if(parent?.isVariableDeclarator()&&t.isIdentifier(parent.node.id)&&parent.node.init===current.node)return isSafeOptionBinding(parent.scope.getBinding(parent.node.id.name),allowed,visiting);return false}function isSafeOptionBinding(binding,allowed,visiting=/* @__PURE__ */ new Set){if(!binding?.constant||!binding.path.isVariableDeclarator()||!binding.path.parentPath.isVariableDeclaration()||binding.path.parentPath.node.kind!==`const`||binding.path.parentPath.parentPath?.isExportNamedDeclaration()||visiting.has(binding.path.node))return false;const next=new Set(visiting).add(binding.path.node);return binding.referencePaths.every(reference=>isSafeOptionReference(reference,allowed,next))}function isComponentFactory(node,module){if(!t.isIdentifier(node.callee))return false;const binding=module.scope.getBinding(node.callee.name);return binding?.path.isImportSpecifier()&&t.isIdentifier(binding.path.node.imported,{name:`defineComponent`})&&binding.path.parentPath.isImportDeclaration()&&[`vue`,`wevu`,`wevu/internal-runtime`,`virtual:weapp-vite/runtime`].includes(binding.path.parentPath.node.source.value)}function isSafeMergeOperand(input,module,visiting){const node=unwrap(input);if(visiting.has(node))return false;const next=new Set(visiting).add(node);if(t.isIdentifier(node)){const binding=module.scope.getBinding(node.name);return isSafeOptionBinding(binding,next)&&Boolean(binding?.path.isVariableDeclarator()&&binding.path.node.init&&isSafeMergeOperand(binding.path.node.init,module,next))}if(t.isObjectExpression(node))return node.properties.every(property=>{if(t.isSpreadElement(property))return isSafeMergeOperand(property.argument,module,next);const key=staticName(property.key,property.computed);return key!==void 0&&key!==`__proto__`&&(t.isObjectProperty(property)||property.kind===`method`)});if(t.isCallExpression(node)){if(isComponentFactory(node,module)&&node.arguments.length===1&&t.isExpression(node.arguments[0]))return isSafeMergeOperand(node.arguments[0],module,next);if(isObjectCall(node,module.scope,`assign`))return node.arguments.every(argument=>t.isExpression(argument)&&isSafeMergeOperand(argument,module,next))}return false}function findCompiledOption(input,name,module,visiting=/* @__PURE__ */ new Set){const node=unwrap(input);if(visiting.has(node))return unknown;const next=new Set(visiting).add(node);if(t.isIdentifier(node)){const binding=module.scope.getBinding(node.name);return isSafeOptionBinding(binding,next)&&binding?.path.isVariableDeclarator()&&binding.path.node.init?findCompiledOption(binding.path.node.init,name,module,next):unknown}if(t.isObjectExpression(node)){for(const property of[...node.properties].reverse()){if(t.isSpreadElement(property)){const inherited=findCompiledOption(property.argument,name,module,next);if(inherited.kind!==`absent`)return inherited;continue}const key=staticName(property.key,property.computed);if(key===void 0||key===`__proto__`)return unknown;if(key===name)return t.isObjectProperty(property)||property.kind===`method`?{kind:`value`,node:t.isObjectProperty(property)?property.value:property}:unknown}return absent}if(t.isCallExpression(node)){if(isComponentFactory(node,module)&&node.arguments.length===1&&t.isExpression(node.arguments[0]))return findCompiledOption(node.arguments[0],name,module,next);if(isObjectCall(node,module.scope,`assign`)){if(!node.arguments.every(argument=>t.isExpression(argument)&&isSafeMergeOperand(argument,module,next)))return unknown;for(const argument of[...node.arguments].reverse()){const option=t.isExpression(argument)?findCompiledOption(argument,name,module,next):unknown;if(option.kind!==`absent`)return option}return absent}}return unknown}function excludePropsObjectAliases(keys,setup){if(!setup||!(t.isObjectMethod(setup)||t.isFunctionExpression(setup)||t.isArrowFunctionExpression(setup))||!t.isIdentifier(setup.params[0])||!t.isBlockStatement(setup.body))return keys;const aliases=/* @__PURE__ */ new Set;for(const statement of setup.body.body)if(t.isVariableDeclaration(statement)){for(const declaration of statement.declarations)if(t.isIdentifier(declaration.id)&&t.isIdentifier(declaration.init,{name:setup.params[0].name}))aliases.add(declaration.id.name)}return keys.filter(key=>!aliases.has(key))}function constantInitializer(node,module){if(!t.isIdentifier(node))return;const binding=module.scope.getBinding(node.name);if(!binding?.constant||!binding.path.isVariableDeclarator()||!binding.path.parentPath.isVariableDeclaration()||binding.path.parentPath.node.kind!==`const`||!binding.path.node.init)return;return{binding,node:binding.path.node.init}}function createPropsShapeAnalyzer(modules,ownership){async function primitive(input,module,visiting=/* @__PURE__ */ new Set){const node=unwrap(input);if(visiting.has(node))return;const next=new Set(visiting).add(node);if(t.isStringLiteral(node)||t.isNumericLiteral(node))return node.value;if(t.isTemplateLiteral(node)&&!node.expressions.length)return staticName(node,true);const local=constantInitializer(node,module);if(local)return primitive(local.node,module,next);const imported=await modules.resolveImport(node,module);return imported?primitive(imported.node,imported.module,next):void 0}async function analyze(input,module,visiting=/* @__PURE__ */ new Set){const node=unwrap(input);if(visiting.has(node))return;const next=new Set(visiting).add(node);const local=constantInitializer(node,module);if(local){const value=await analyze(local.node,module,next);return value&&(value.frozen||isSafePropsBinding(local.binding,ownership))?value:void 0}if(t.isIdentifier(node)||t.isMemberExpression(node)){const imported=await modules.resolveImport(node,module);const value=imported&&await analyze(imported.node,imported.module,next);return value?.frozen?value:void 0}if(t.isCallExpression(node)&&isImportedCall(node,module,`mergeModels`,[`vue`])){if(node.arguments.length!==2||!node.arguments.every(t.isExpression))return;const[left,right]=await Promise.all(node.arguments.map(argument=>analyze(argument,module,next)));if(!left||!right)return;const names=new Set(left.names);right.names.forEach(name=>names.add(name));return{kind:left.kind===`array`&&right.kind===`array`?`array`:`object`,names,frozen:false}}if(isObjectCall(node,module.scope,`freeze`)&&node.arguments.length===1&&t.isExpression(node.arguments[0])){const value=await analyze(node.arguments[0],module,next);return value&&{...value,frozen:true}}if(isObjectCall(node,module.scope,`assign`)){const first=node.arguments[0]&&unwrap(node.arguments[0]);if(!t.isObjectExpression(first)||first.properties.length)return;const names=/* @__PURE__ */ new Set;for(const argument of node.arguments.slice(1)){if(!t.isExpression(argument))return;const value=await analyze(argument,module,next);if(!value||value.kind!==`object`)return;value.names.forEach(name=>names.add(name))}return{kind:`object`,names,frozen:false}}if(t.isObjectExpression(node)){const names=/* @__PURE__ */ new Set;for(const property of node.properties){if(t.isSpreadElement(property)){const value=await analyze(property.argument,module,next);if(!value||value.kind!==`object`)return;value.names.forEach(name=>names.add(name));continue}if(!t.isObjectProperty(property))return;const key=property.computed?await primitive(property.key,module,next):staticName(property.key);if(key===void 0||key===`__proto__`)return;names.add(String(key))}return{kind:`object`,names,frozen:false}}if(t.isArrayExpression(node)){const names=/* @__PURE__ */ new Set;for(const element of node.elements){if(!element)return;if(t.isSpreadElement(element)){const value=await analyze(element.argument,module,next);if(!value||value.kind!==`array`)return;value.names.forEach(name=>names.add(name))}else{const value=await primitive(element,module,next);if(typeof value!==`string`)return;names.add(value)}}return{kind:`array`,names,frozen:false}}}return{analyze}}async function resolveSetupPropConflicts(options){const dependencies=/* @__PURE__ */ new Set;if(!/\bprops\b/.test(options.script))return{dependencies:[]};let setupKeys=Object.entries(options.bindings??{}).filter(([,kind])=>typeof kind===`string`&&(kind.startsWith(`setup-`)||kind===`literal-const`)).map(([key])=>key);if(!setupKeys.length)return{dependencies:[]};const root=createModuleFacts(normalizeSourceId(options.filename),options.getScriptAst());const exported=root.ast.program.body.find(statement=>t.isExportDefaultDeclaration(statement));if(!exported||!t.isExportDefaultDeclaration(exported))return{conflicts:setupKeys,dependencies:[]};const props=findCompiledOption(exported.declaration,`props`,root);const setup=findCompiledOption(exported.declaration,`setup`,root);const setupNode=setup.kind===`value`?setup.node:void 0;setupKeys=excludePropsObjectAliases(setupKeys,setupNode);if(props.kind!==`value`)return{conflicts:props.kind===`unknown`?setupKeys:void 0,dependencies:[]};const reader=createAnalysisSourceReader({source:options.source,trackLogicalPaths:true},dependencies);const modules=createPropsModuleResolver(reader,root);const shape=await createPropsShapeAnalyzer(modules,{props:props.node,setup:setupNode}).analyze(props.node,root);dependencies.delete(root.id);return{conflicts:shape?setupKeys.filter(key=>shape.names.has(key)):setupKeys,dependencies:[...dependencies]}}function createSourceLineStarts(source){const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);return lineStarts}function clearBindingManifestLocations(manifest){for(const binding of manifest.bindings)if(!binding.sourceFile)binding.sourceLocation=void 0}function normalizeSourceFile(filename){return filename.replaceAll(`\\`,`/`).replace(/^\.\//,``)}function sourceFilesMatch(left,right){const normalizedLeft=normalizeSourceFile(left);const normalizedRight=normalizeSourceFile(right);return normalizedLeft===normalizedRight||normalizedLeft.endsWith(`/${normalizedRight}`)||normalizedRight.endsWith(`/${normalizedLeft}`)}function resolveMappedSource(sourceMap,originalSource,fallbackSource){if(!isEncodedSourceMapLike(sourceMap))return{content:fallbackSource,sourceFile:originalSource,hasMappedContent:false};const normalizedOriginal=normalizeSourceFile(originalSource);const sourceIndex=sourceMap.sources.findIndex(candidate=>{return sourceFilesMatch(candidate,normalizedOriginal)});const sourceFile=sourceIndex>=0?sourceMap.sources[sourceIndex]:originalSource;const mappedContent=sourceIndex>=0?sourceMap.sourcesContent?.[sourceIndex]:void 0;return{content:mappedContent??fallbackSource,sourceFile,hasMappedContent:mappedContent!=null}}function remapJsxBindingManifestLocations(manifest,sourceMap,source,sourceFile,diagnostics=[]){const compiledSourceFile=manifest.sourceFile;const ownedDiagnostics=[...diagnostics].filter(item=>sourceFilesMatch(item.filename,compiledSourceFile));const clearLocations=()=>{clearBindingManifestLocations(manifest);for(const diagnostic of ownedDiagnostics)diagnostic.loc=void 0};if(sourceFile)manifest.sourceFile=sourceFile;if(!source||!sourceMap){clearLocations();return}let traceMap;try{traceMap=new TraceMap(sourceMap)}catch{clearLocations();return}const lineStartsCache=/* @__PURE__ */ new Map;const remap=(line,column)=>{let original;try{original=originalPositionFor(traceMap,{line,column:Math.max(0,column-1)})}catch{return}if(original.source==null||original.line==null||original.column==null)return;const mapped=resolveMappedSource(sourceMap,original.source,source);const ownedSourceFile=sourceFile??(sourceFilesMatch(mapped.sourceFile,manifest.sourceFile)?manifest.sourceFile:mapped.sourceFile);if(!mapped.hasMappedContent&&!sourceFilesMatch(ownedSourceFile,manifest.sourceFile))return;const content=sourceFilesMatch(ownedSourceFile,manifest.sourceFile)?source:mapped.content;let lineStarts=lineStartsCache.get(content);if(!lineStarts){lineStarts=createSourceLineStarts(content);lineStartsCache.set(content,lineStarts)}return{position:{offset:(lineStarts[original.line-1]??0)+original.column,line:original.line,column:original.column+1},sourceFile:sourceFilesMatch(ownedSourceFile,manifest.sourceFile)?void 0:normalizeSourceFile(ownedSourceFile)}};for(const binding of manifest.bindings){const location=binding.sourceLocation;if(!location)continue;if(binding.sourceFile&&!sourceFilesMatch(binding.sourceFile,manifest.sourceFile))continue;const start=remap(location.start.line,location.start.column);const end=remap(location.end.line,location.end.column);if(!start||!end||start.sourceFile!==end.sourceFile){binding.sourceLocation=void 0;continue}binding.sourceFile=start.sourceFile;binding.sourceLocation={start:start.position,end:end.position}}for(const diagnostic of ownedDiagnostics){if(!diagnostic.loc)continue;const start=remap(diagnostic.loc.start.line,diagnostic.loc.start.column);const last=remap(diagnostic.loc.end.line,Math.max(1,diagnostic.loc.end.column-1));const end=last&&{sourceFile:last.sourceFile,position:{...last.position,offset:last.position.offset+1,column:last.position.column+1}};diagnostic.loc=start&&end&&start.sourceFile===end.sourceFile?{start:start.position,end:end.position}:void 0;diagnostic.filename=start?.sourceFile??sourceFile??diagnostic.filename}}const RESERVED_SCRIPT_SETUP_PROPS=/* @__PURE__ */ new Set([`id`,`class`,`slot`]);const RESERVED_PROPS_WARNING=`defineProps 中声明 id/class/slot 可能无法在小程序 properties 中正确取值,请改用其他 prop 名称。`;function getStaticKeyName(key){if(t.isIdentifier(key))return key.name;if(t.isStringLiteral(key))return key.value}function getTypePropertyName(key){if(t.isIdentifier(key))return key.name;if(t.isStringLiteral(key))return key.value}function isReservedScriptSetupProp(name){return name!=null&&RESERVED_SCRIPT_SETUP_PROPS.has(name)}function runtimePropsContainReservedName(node){if(t.isObjectExpression(node))return node.properties.some(prop=>t.isObjectProperty(prop)&&!prop.computed&&isReservedScriptSetupProp(getStaticKeyName(prop.key)));if(t.isArrayExpression(node))return node.elements.some(element=>t.isStringLiteral(element)&&isReservedScriptSetupProp(element.value));return false}function createTypeScope(ast){const scope=/* @__PURE__ */ new Map;traverse(ast,{TSInterfaceDeclaration(path){scope.set(path.node.id.name,path.node.body)},TSTypeAliasDeclaration(path){scope.set(path.node.id.name,path.node.typeAnnotation)}});return scope}function typePropsContainReservedName(typeNode,scope,seen=/* @__PURE__ */ new Set){if(!typeNode)return false;if(t.isTSTypeLiteral(typeNode))return typeNode.members.some(member=>{return t.isTSPropertySignature(member)&&!member.computed&&isReservedScriptSetupProp(getTypePropertyName(member.key))});if(t.isTSInterfaceBody(typeNode))return typeNode.body.some(member=>{return t.isTSPropertySignature(member)&&!member.computed&&isReservedScriptSetupProp(getTypePropertyName(member.key))});if(t.isTSIntersectionType(typeNode))return typeNode.types.some(item=>typePropsContainReservedName(item,scope,seen));if(t.isTSTypeReference(typeNode)&&t.isIdentifier(typeNode.typeName)){const typeName=typeNode.typeName.name;if(seen.has(typeName))return false;const resolved=scope.get(typeName);if(!resolved)return false;seen.add(typeName);return typePropsContainReservedName(resolved,scope,seen)}return false}function getDefinePropsLocation(node){const start=node.loc?.start;if(!start)return;return{line:start.line,column:start.column}}function resolveSourceLocation(location,scriptSetupStart){if(!location)return;if(!scriptSetupStart)return location;return{line:scriptSetupStart.line+location.line-1,column:location.line===1?scriptSetupStart.column+location.column:location.column}}function createReservedPropsWarning(location,filename){if(!location||!filename)return RESERVED_PROPS_WARNING;return`${filename}:${location.line}:${location.column+1} ${RESERVED_PROPS_WARNING}`}function detectDefinePropsReservedName(scriptSetupCode){let result;try{const ast=parseJsLike(scriptSetupCode);const typeScope=createTypeScope(ast);traverse(ast,{CallExpression(path){const callee=path.node.callee;if(!t.isIdentifier(callee,{name:`defineProps`}))return;if(runtimePropsContainReservedName(path.node.arguments[0])){result={location:getDefinePropsLocation(path.node)};path.stop();return}const typeParam=(path.node.typeParameters??path.node.typeArguments)?.params?.[0];if(typePropsContainReservedName(typeParam,typeScope)){result={location:getDefinePropsLocation(path.node)};path.stop()}}})}catch{return}return result}function warnReservedScriptSetupProps(scriptSetupCode,warn,context={},diagnostic){if(!scriptSetupCode)return;const offset=diagnostic?.warningOffset;const lines=offset===void 0?void 0:scriptSetupCode.slice(0,offset).split(/\r\n|[\r\n\u2028\u2029]/);const result=diagnostic?lines&&{location:{line:lines.length,column:lines.at(-1).length}}:detectDefinePropsReservedName(scriptSetupCode);if(!result)return;const location=resolveSourceLocation(result.location,context.scriptSetupStart);warn?.(createReservedPropsWarning(location,context.filename))}const TYPE_ONLY_DEFINE_PROPS_RE=/\bdefineProps\s*</;function resolveScriptSetupPropsAliases(bindings){const aliases=bindings?.__propsAliases;if(!aliases||typeof aliases!==`object`)return;const resolved={};for(const[alias,propName]of Object.entries(aliases))if(typeof propName===`string`&&propName.length>0)resolved[alias]=propName;return Object.keys(resolved).length?resolved:void 0}function resolveScriptSetupPropsDerivedKeys(bindings){const keys=/* @__PURE__ */ new Set;for(const[key,bindingType]of Object.entries(bindings??{})){if(key.startsWith(`__`)||bindingType!==`props`&&bindingType!==`props-aliased`)continue;keys.add(key)}return keys.size?[...keys]:void 0}function bindingsMayContainProps(bindings,scriptCode){for(const[key,bindingType]of Object.entries(bindings??{}))if(key===`__propsAliases`||bindingType===`props`||bindingType===`props-aliased`)return true;return scriptCode.includes(`__props`)||scriptCode.includes(`props:`)}function hasPrecomputedScriptPhaseInfo(info,key){return Boolean(info)&&Object.prototype.hasOwnProperty.call(info,key)}function collectScriptSetupReturnInfo(getScriptAst){const keys=/* @__PURE__ */ new Set;const propsObjectAliases=/* @__PURE__ */ new Set([`__props`]);const propsRefsAliases=/* @__PURE__ */ new Set;const destructuredPropsKeys=/* @__PURE__ */ new Set;const addObjectPatternKeys=pattern=>{for(const property of pattern.properties){if(!t.isObjectProperty(property))continue;if(t.isIdentifier(property.value))destructuredPropsKeys.add(property.value.name);else if(t.isAssignmentPattern(property.value)&&t.isIdentifier(property.value.left))destructuredPropsKeys.add(property.value.left.name)}};try{const ast=getScriptAst();traverse(ast,{VariableDeclarator(path){const init=path.node.init;if(t.isIdentifier(path.node.id)&&t.isIdentifier(init)&&propsObjectAliases.has(init.name)){propsObjectAliases.add(path.node.id.name);return}if(t.isIdentifier(path.node.id)&&t.isCallExpression(init)&&t.isIdentifier(init.callee,{name:`toRefs`})&&init.arguments.length===1&&t.isIdentifier(init.arguments[0])&&propsObjectAliases.has(init.arguments[0].name)){propsRefsAliases.add(path.node.id.name);return}if(!t.isObjectPattern(path.node.id))return;if(t.isIdentifier(init)&&propsObjectAliases.has(init.name)){addObjectPatternKeys(path.node.id);return}if(t.isIdentifier(init)&&propsRefsAliases.has(init.name)){addObjectPatternKeys(path.node.id);return}if(t.isCallExpression(init)&&t.isIdentifier(init.callee,{name:`toRefs`})&&init.arguments.length===1&&t.isIdentifier(init.arguments[0])&&propsObjectAliases.has(init.arguments[0].name))addObjectPatternKeys(path.node.id)},ObjectProperty(path){const objectPath=path.parentPath;if(!objectPath.isObjectExpression()||!objectPath.parentPath.isVariableDeclarator()||!t.isIdentifier(objectPath.parentPath.node.id,{name:`__returned__`}))return;const prop=path.node;if(prop.computed)return;if(t.isIdentifier(prop.key))keys.add(prop.key.name);else if(t.isStringLiteral(prop.key))keys.add(prop.key.value)}})}catch{return{returnedKeys:keys,destructuredPropsKeys}}return{returnedKeys:keys,destructuredPropsKeys}}function resolveEffectivePropsDerivedKeys(bindings,scriptCode,getScriptAst=()=>parseJsLike(scriptCode)){if(!bindingsMayContainProps(bindings,scriptCode))return;const directKeys=resolveScriptSetupPropsDerivedKeys(bindings)??[];const{returnedKeys,destructuredPropsKeys}=collectScriptSetupReturnInfo(getScriptAst);const aliases=resolveScriptSetupPropsAliases(bindings)??{};const propsKeys=new Set(Object.entries(bindings??{}).filter(([key,bindingType])=>key&&!key.startsWith(`__`)&&bindingType===`props`).map(([key])=>key));const keys=/* @__PURE__ */ new Set;for(const key of directKeys)keys.add(key);for(const key of destructuredPropsKeys)keys.add(key);for(const[alias,propName]of Object.entries(aliases)){if(!returnedKeys.has(alias))keys.add(alias);if(propsKeys.has(propName)&&!returnedKeys.has(propName))keys.add(propName)}for(const key of propsKeys)if(!returnedKeys.has(key))keys.add(key);return keys.size?[...keys]:void 0}async function compileScriptPhase(descriptor,descriptorForCompile,filename,options,_autoUsingComponents,templateCompiled,isAppFile,componentSourceInfo,precompiledScript,precomputedScriptPhaseInfo,originalSource,scriptPreprocessMap,nativeScriptAnalysis){const nativeDom=!isAppFile&&isNativeDomCompilation(options);const autoUsingComponentsMap={...componentSourceInfo?.autoUsingComponentsMap??{}};const autoComponentMeta={...componentSourceInfo?.autoComponentMeta??{}};const relaxStructuredTypeOnlyProps=Boolean(descriptor.scriptSetup?.content&&TYPE_ONLY_DEFINE_PROPS_RE.test(descriptor.scriptSetup.content));let scriptCode;let scriptMap=null;let propsAliases=options?.template?.propsAliases;let propsDerivedKeys;let jsxDiagnostics;if(descriptor.script||descriptor.scriptSetup){const scriptCompiled=precompiledScript??compileScript(descriptorForCompile,{id:generateScopedId(filename),isProd:false});warnReservedScriptSetupProps(descriptorForCompile.scriptSetup?.content,options?.warn,{filename,scriptSetupStart:descriptorForCompile.scriptSetup?.loc.start},nativeScriptAnalysis?.scriptSetup?.reservedPropsDiagnostic);if(!propsAliases&&hasPrecomputedScriptPhaseInfo(precomputedScriptPhaseInfo,`propsAliases`))propsAliases=precomputedScriptPhaseInfo.propsAliases;propsAliases??=resolveScriptSetupPropsAliases(scriptCompiled.bindings);scriptCode=scriptCompiled.content;propsDerivedKeys=hasPrecomputedScriptPhaseInfo(precomputedScriptPhaseInfo,`propsDerivedKeys`)?precomputedScriptPhaseInfo.propsDerivedKeys:resolveEffectivePropsDerivedKeys(scriptCompiled.bindings,scriptCode);const compiledScriptMap=options?.sourceMap!==false&&scriptCompiled.map&&typeof scriptCompiled.map===`object`?scriptCompiled.map:null;scriptMap=compiledScriptMap?composeSourceMaps(compiledScriptMap,scriptPreprocessMap):null;if(scriptCode.includes(`defineAppJson`)||scriptCode.includes(`definePageJson`)||scriptCode.includes(`defineComponentJson`))scriptCode=stripJsonMacroCallsFromCode(scriptCode,filename);const defaultExportAnalysis=scriptCode===descriptorForCompile.script?.content?nativeScriptAnalysis?.script:void 0;if(!isAppFile&&!descriptor.scriptSetup&&!hasDefaultExport(scriptCode,defaultExportAnalysis))scriptCode+=`
40
- export default {}`}else scriptCode=`export default {}`;if(scriptCode){const scriptLang=descriptor.script?.lang??descriptor.scriptSetup?.lang;const isJsxScript=scriptLang===`jsx`||scriptLang===`tsx`;let jsxTemplate;if(isJsxScript){jsxTemplate=compileJsxTemplateAndCollectComponents(scriptCode,filename,options);const externalScriptBlock=descriptor.script?.src?descriptor.script:descriptor.scriptSetup?.src?descriptor.scriptSetup:void 0;remapJsxBindingManifestLocations(jsxTemplate.bindingManifest,scriptMap,externalScriptBlock?.content??originalSource,externalScriptBlock?.src,jsxTemplate.warningDiagnostics.values());if(jsxTemplate.template&&(options?.pageLayout||options?.appShell))jsxTemplate.template=applyCompilerTemplateWrappers({template:jsxTemplate.template,manifest:jsxTemplate.bindingManifest,platform:options?.template?.platform??getMiniProgramTemplatePlatform(),pageLayout:options?.pageLayout,appShell:options?.appShell});const reportJsxWarnings=!descriptor.template||Boolean(jsxTemplate.template);scriptCode=injectDynamicIslandRuntime(stripRenderOptionFromScript(scriptCode,filename,reportJsxWarnings?jsxTemplate.warnings:void 0),jsxTemplate.dynamicIslands);if(reportJsxWarnings&&jsxTemplate.warnings.length){jsxDiagnostics=createJsxDiagnostics(jsxTemplate.warnings,filename,jsxTemplate.warningDiagnostics);reportJsxDiagnostics(jsxDiagnostics,options?.warn)}}const jsxTransformed=isJsxScript?(await import(`./vueJsxTransform-C4lhnLbg.mjs`)).transformVueJsxScript(scriptCode,filename,options?.sourceMap!==false):{code:scriptCode,map:null};const bindingManifest=jsxTemplate?.template?jsxTemplate.bindingManifest:templateCompiled?.bindingManifest;const effectiveInlineExpressions=jsxTemplate?.template?jsxTemplate.inlineExpressions:templateCompiled?.inlineExpressions;const templateRuntimeCapabilities=bindingManifest?createWevuRuntimeCapabilityMetadataFromBindingManifest(bindingManifest):templateCompiled?.runtimeCapabilities;const nativeSlotContext=!isAppFile&&usesNativeDeclarationContext({platform:options?.template?.platform??getMiniProgramTemplatePlatform(),scopedSlotsRequireProps:options?.template?.scopedSlotsRequireProps??options?.template?.scopedSlotsCompiler!==`augmented`,nativeSlotContext:options?.template?.nativeSlotContext===true});const runtimeCapabilities=mergeWevuRuntimeCapabilityMetadata(templateRuntimeCapabilities,nativeSlotContext?createWevuRuntimeCapabilityMetadata([`scopedSlots`]):void 0);const transformed=transformScript(jsxTransformed.code,{isTypeScript:descriptor.script?.lang===`ts`||descriptor.script?.lang===`tsx`||descriptor.scriptSetup?.lang===`ts`||descriptor.scriptSetup?.lang===`tsx`,skipComponentTransform:nativeDom||(options?.skipComponentTransform??isAppFile),isApp:isAppFile,isPage:options?.isPage===true,minify:options?.minify,sourceMap:options?.sourceMap,warn:options?.warn,templateComponentMeta:Object.keys(autoComponentMeta).length?Object.fromEntries(Object.entries(autoComponentMeta).filter(([name])=>!nativeDom||!componentSourceInfo?.wevuComponentTags.has(name))):void 0,wevuDefaults:options?.wevuDefaults,classStyleRuntime:templateCompiled?.classStyleRuntime,classStyleBindings:templateCompiled?.classStyleBindings,templateRefs:templateCompiled?.templateRefs,layoutHosts:templateCompiled?.layoutHosts,inlineExpressions:effectiveInlineExpressions,bindingManifest:isAppFile?void 0:bindingManifest,autoSetDataPick:!isAppFile&&options?.autoSetDataPick,runtimeBindingManifest:options?.runtimeBindingManifest,pageLayout:isAppFile?void 0:options?.pageLayout,runtimeCapabilities,functionPropPaths:templateCompiled?.functionPropPaths,propsAliases,propsDerivedKeys,cssModules:precomputedScriptPhaseInfo?.cssModules,stabilizeCssVarsRuntime:options?.stabilizeCssVarsRuntime,relaxStructuredTypeOnlyProps,nativeSlotContext,scopedSlotHostProperties:!isAppFile&&options?.isPage!==true&&Boolean(templateCompiled?.hasSlotOutlet||templateCompiled?.componentGenerics&&Object.keys(templateCompiled.componentGenerics).length>0)});const nativeResult=nativeDom?attachNativeDom({script:transformed.code,filename,descriptor:descriptorForCompile,bindings:precompiledScript?.bindings,components:componentSourceInfo,templateComputedBindings:templateCompiled?.classStyleBindings?.map(binding=>binding.name),options,scopeId:descriptorForCompile.styles.some(style=>style.scoped)?`data-v-${generateScopedId(filename)}`:void 0}):void 0;return{script:nativeResult?.code??transformed.code,scriptMap:composeSourceMaps(nativeResult?.map,composeSourceMaps(transformed.map??jsxTransformed.map,scriptMap)),template:jsxTemplate?.template,diagnostics:jsxDiagnostics,bindingManifest,inlineExpressions:jsxTemplate?.inlineExpressions,runtimeCapabilities:transformed.runtimeCapabilities,componentStyleOptions:transformed.componentStyleOptions,autoUsingComponentsMap,autoComponentMeta}}return{script:scriptCode,scriptMap:null,autoUsingComponentsMap,autoComponentMeta}}async function compileStylePhase(descriptor,filename,result,options){if(descriptor.styles.length===0)return{usesSlotted:false};const scopedId=generateScopedId(filename);const compiledStyles=await Promise.all(descriptor.styles.map(async styleBlock=>{return await compileVueStyleToWxss(styleBlock,{id:scopedId,filename,scoped:styleBlock.scoped,modules:styleBlock.module,preprocessOptions:options?.preprocessOptions?.[styleBlock.lang||`css`],preserveDeepSelectors:options?.preserveDeepSelectors,transformScoped:options?.transformScoped})}));result.style=compiledStyles.map(s=>s.code.trim()).filter(Boolean).join(`
38
+ `;return await withTempDirLock(tempRoot,async()=>{await ensureDir(tempDir);const tempFile=path.join(tempDir,`${basename}.define-options.${unique}.${extension}`);await writeFile(tempFile,evalSource,`utf8`);try{const{mod,dependencies}=await bundleRequire({filepath:tempFile,cwd:dir,tsconfig:false});const exported=mod?.__weapp_define_options??mod;return{values:Array.isArray(exported)?exported:[exported],dependencies,scopeValues:mod?.__weapp_define_scope??{}}}finally{try{await remove(tempDir)}catch{}}})}async function resolveDefineOptionsValue(raw){let next=raw;if(typeof next===`function`)next=next();if(next&&typeof next.then===`function`)next=await next;if(!next||typeof next!==`object`||Array.isArray(next))throw new Error(`defineOptions 的参数最终必须解析为对象。`);return next}async function inlineScriptSetupDefineOptionsArgs(content,filename,lang,sourceMap){const{statements}=collectDefineOptionsStatements(content,filename);if(!statements.length)return{code:content,dependencies:[]};let values=[];let dependencies=[];let scopeValues={};const staticValues=resolveStaticDefineOptionsValues(statements);if(staticValues)values=staticValues;else{scopeValues=collectStaticTopLevelScopeValues(content);try{const evaluated=await evaluateDefineOptionsValues({content,filename,lang,statements});values=evaluated.values;dependencies=evaluated.dependencies;scopeValues={...scopeValues,...evaluated.scopeValues}}catch(error){if(shouldFallbackToRawDefineOptions(error))return{code:content,dependencies:[]};throw error}}const ms=sourceMap?new MagicString(sourceMap.source,{offset:sourceMap.offset}):new MagicString(content);for(let index=0;index<statements.length;index+=1){const argNode=statements[index].argPath?.node;if(!argNode||typeof argNode.start!==`number`||typeof argNode.end!==`number`)continue;const value=await resolveDefineOptionsValue(values[index]);const literal=serializeStaticValueToExpression(value,/* @__PURE__ */ new WeakSet,scopeValues);ms.overwrite(argNode.start,argNode.end,literal)}const code=sourceMap?ms.slice(0,content.length):ms.toString();const result={code,dependencies:dependencies.filter(Boolean)};if(!sourceMap||code===content)return result;const sourceFile=sourceMap.sourceFile;let map;return{...result,get map(){return map??=ms.generateMap({hires:true,includeContent:true,source:sourceFile})}}}const EXPORT_DEFAULT_RE=/\bexport\s+default\b/;function mayHaveDefaultExport(scriptCode){return EXPORT_DEFAULT_RE.test(scriptCode)}function hasDefaultExport(scriptCode,nativeAnalysis){if(!mayHaveDefaultExport(scriptCode))return false;if(nativeAnalysis?.hasDefaultExport!==void 0)return nativeAnalysis.hasDefaultExport;try{const ast=parseJsLike(scriptCode);let found=false;traverse(ast,{ExportDefaultDeclaration(path){found=true;path.stop()}});return found}catch{return mayHaveDefaultExport(scriptCode)}}function mayShareNativeOptionsAnalysis(scriptCode,template){if(!template?.ast||template.src||!mayHaveDefaultExport(scriptCode))return false;const hasComponentTag=node=>{if(node.type!==NodeTypes.ELEMENT)return false;if(!RESERVED_VUE_COMPONENT_TAGS.has(node.tag)&&!isBuiltinComponent(node.tag))return true;return node.children.some(hasComponentTag)};return template.ast.children.some(hasComponentTag)}function resolveScriptFilename(filename,lang){return`${filename}.${lang===`tsx`||lang===`jsx`||lang===`js`?lang:`ts`}`}function analyzeNativeScriptBlocks(descriptor,filename,defineOptionsSource,collectPageFeatures=false){const blocks=[[`script`,descriptor.script],[`scriptSetup`,descriptor.scriptSetup],[`defineOptions`,defineOptionsSource]].filter(entry=>Boolean(entry[1]));if(!blocks.length)return;try{const results=analyzeCompilerScriptsWithNative(blocks.map(([key,block])=>({code:block.content,filename:resolveScriptFilename(filename,block.lang),...collectPageFeatures&&key===`script`&&!descriptor.scriptSetup?{pageFeatureModules:[...WE_VU_RUNTIME_MODULE_IDS,`wevu/router`,`wevu/dev/router`],pageFeatureHookToFeatureJson:JSON.stringify(WE_VU_PAGE_HOOK_TO_FEATURE)}:{}})));if(!results||results.length!==blocks.length)return;const scripts={};let defineOptions;for(const[index,[key]]of blocks.entries()){const result=results[index];if(!result)continue;if(key===`defineOptions`)defineOptions=result;else scripts[key]=result}return{scripts,defineOptions}}catch{return}}const SETUP_CALL_RE=/\bsetup\s*\(/;const DEFINE_OPTIONS_CALL_RE=/\bdefineOptions\s*\(/;const APP_VUE_FILE_RE=/[\\/]app\.vue$/;const TEMPLATE_BLOCK_RE=/<template\b[\s\S]*?<\/template>/g;const TEMPLATE_IMPORT_META_RE=/\bimport\.meta\b/g;const TEMPLATE_IMPORT_META_PLACEHOLDER=`__im_meta__`;function createIdentitySourceMap(source,originalSource,filename){const sourceMap=new MagicString(source).generateMap({hires:true,includeContent:false,source:filename});sourceMap.sourcesContent=[originalSource];return sourceMap}function resolveSfcScriptLangLabel(lang){return typeof lang===`string`&&lang.length>0?lang:`(default)`}function assertMatchingSfcScriptLang(descriptor,filename){const scriptLang=descriptor.script?.lang;const scriptSetupLang=descriptor.scriptSetup?.lang;if(!descriptor.script||!descriptor.scriptSetup||scriptLang===scriptSetupLang)return;throw new Error(`解析 ${filename} 失败:同一个 SFC 中 <script> 与 <script setup> 的 lang 必须一致,当前分别为 ${resolveSfcScriptLangLabel(scriptLang)} 与 ${resolveSfcScriptLangLabel(scriptSetupLang)}`)}function resolveSourcePosition(source,offset){let line=1;let lineStart=0;for(let index=0;index<offset;index+=1){const char=source.charCodeAt(index);if(char===10||char===8232||char===8233){line+=1;lineStart=index+1}else if(char===13){line+=1;if(source.charCodeAt(index+1)===10)index+=1;lineStart=index+1}}return{column:offset-lineStart+1,line,offset}}function replaceScriptSetupContent(descriptor,content){const scriptSetup=descriptor.scriptSetup;const startOffset=scriptSetup.loc.start.offset;const endOffset=scriptSetup.loc.end.offset;const nextSource=descriptor.source.slice(0,startOffset)+content+descriptor.source.slice(endOffset);const delta=content.length-(endOffset-startOffset);const updateBlock=block=>{if(!block)return null;const isSetup=block===scriptSetup;const nextStart=isSetup?startOffset:block.loc.start.offset>=endOffset?block.loc.start.offset+delta:block.loc.start.offset;const nextEnd=isSetup?startOffset+content.length:block.loc.end.offset>=endOffset?block.loc.end.offset+delta:block.loc.end.offset;return{...block,content:isSetup?content:block.content,loc:{source:isSetup?content:block.loc.source,start:resolveSourcePosition(nextSource,nextStart),end:resolveSourcePosition(nextSource,nextEnd)}}};return{...descriptor,source:nextSource,script:updateBlock(descriptor.script),scriptSetup:updateBlock(descriptor.scriptSetup)}}function hashDefineOptionsSources(sources){if(!sources.length)return;return createHash(`sha256`).update(sources.join(`
39
+ `)).digest(`hex`).slice(0,12)}function extractDefineOptionsHash(content,analysis){if(analysis)return hashDefineOptionsSources(analysis.defineOptionsStatements.map(({start,end})=>content.slice(start,end)));let ast;try{ast=parse$3(content,BABEL_TS_MODULE_PARSER_OPTIONS)}catch{return}const macroSources=[];traverse(ast,{CallExpression(path){const callee=path.node.callee;if(!t.isIdentifier(callee,{name:`defineOptions`}))return;if(!(path.parentPath?.isExpressionStatement()&&path.parentPath.parentPath?.isProgram()))return;const statement=path.parentPath?.node;if(statement&&typeof statement.start===`number`&&typeof statement.end===`number`)macroSources.push(content.slice(statement.start,statement.end))}});return hashDefineOptionsSources(macroSources)}function preprocessTemplateImportMeta(source){return source.replace(TEMPLATE_BLOCK_RE,block=>block.replace(TEMPLATE_IMPORT_META_RE,TEMPLATE_IMPORT_META_PLACEHOLDER))}function restoreTemplateImportMeta(content){return content.replace(new RegExp(TEMPLATE_IMPORT_META_PLACEHOLDER,`g`),`import.meta`)}function restoreTemplateImportMetaInDescriptor(descriptor){if(!descriptor.template?.content?.includes(TEMPLATE_IMPORT_META_PLACEHOLDER))return descriptor;return{...descriptor,template:{...descriptor.template,content:restoreTemplateImportMeta(descriptor.template.content)}}}async function parseSfc(source,filename,ignoreEmpty,preprocessedSource=preprocessTemplateImportMeta(source)){const parsed=await readAndParseSfc(filename,{source,preprocessedSource,checkMtime:false,ignoreEmpty});return{...parsed,descriptor:restoreTemplateImportMetaInDescriptor(parsed.descriptor)}}function resolvePreprocessSourceMap(sourceMap,transforms){if(transforms)for(const transform of transforms)sourceMap=composeSourceMaps(transform.map,sourceMap);return sourceMap}function mayContainPageFeatureHints(code){return[...WE_VU_RUNTIME_MODULE_IDS,`wevu/router`,`wevu/dev/router`].some(moduleId=>code.includes(moduleId))&&Object.keys(WE_VU_PAGE_HOOK_TO_FEATURE).some(hook=>code.includes(hook))}function hasSharedNativeAnalysis(descriptor,defineOptionsSource,isAppFile,isPage){return[descriptor.script,descriptor.scriptSetup,defineOptionsSource].filter(Boolean).length>1||process.env.WEAPP_VITE_NATIVE===`1`&&Boolean(process.env.WEAPP_VITE_NATIVE_AST_PATH?.trim())&&!isAppFile&&!descriptor.scriptSetup&&Boolean(descriptor.script&&(mayShareNativeOptionsAnalysis(descriptor.script.content,descriptor.template)||isPage&&mayContainPageFeatureHints(descriptor.script.content)))}async function parseVueFile(source,filename,options){const normalizedInputSource=normalizeLineEndings(source);let scriptPreprocessMap=null;let deferredPreprocessMaps;if(options?.sourceMap!==false&&normalizedInputSource!==source)scriptPreprocessMap=createIdentitySourceMap(normalizedInputSource,source,filename);const normalizedSource=normalizedInputSource;const parserSource=preprocessTemplateImportMeta(normalizedSource);if(options?.sourceMap!==false&&parserSource!==normalizedSource)scriptPreprocessMap=composeSourceMaps(createIdentitySourceMap(parserSource,normalizedSource,filename),scriptPreprocessMap);let descriptorForCompileSource=normalizedSource;const parsedSfc=await parseSfc(normalizedSource,filename,true,parserSource);const descriptor=parsedSfc.descriptor;const{errors}=parsedSfc;if(errors.length>0)throw createSfcParseError(errors[0],{filename,source,sourceMap:scriptPreprocessMap});let resolvedDescriptor=descriptor;let sfcSrcDeps;let templateResolvedId;let scriptResolvedId;let scriptSetupResolvedId;if(options?.sfcSrc){const resolved=await resolveSfcBlockSrc(descriptor,filename,options.sfcSrc);resolvedDescriptor=resolved.descriptor;templateResolvedId=resolved.templateResolvedId;scriptResolvedId=resolved.scriptResolvedId;scriptSetupResolvedId=resolved.scriptSetupResolvedId;if(resolved.deps.length)sfcSrcDeps=resolved.deps}let routeConfig;let pageMeta;let descriptorForCompile=resolvedDescriptor;let usesExternalScriptCompileSource=false;if(scriptResolvedId||scriptSetupResolvedId||options?.isPage===true&&(mayContainPageDeclaration(normalizedSource)||mayContainPageMeta(normalizedSource))){const stripped=prepareSfcScriptCompile(normalizedSource,filename,resolvedDescriptor,options?.sourceMap!==false,{scriptResolvedId,scriptSetupResolvedId},options?.isPage===true);if(stripped){routeConfig=stripped.routeConfig;pageMeta=stripped.pageMeta;const mainSourcePreprocessMap=scriptPreprocessMap;resolvedDescriptor=stripped.descriptor;usesExternalScriptCompileSource=Boolean(stripped.descriptorForCompile);descriptorForCompile=stripped.descriptorForCompile??stripped.descriptor;descriptorForCompileSource=stripped.descriptorForCompile?.source??stripped.code;const usesExternalNormalScriptCompileSource=Boolean(resolvedDescriptor.script?.src&&!resolvedDescriptor.scriptSetup);if(usesExternalScriptCompileSource)scriptPreprocessMap=composeSourceMapForSource(stripped.scriptMap,mainSourcePreprocessMap,filename);else if(usesExternalNormalScriptCompileSource)scriptPreprocessMap=null;else scriptPreprocessMap=composeSourceMaps(stripped.map,mainSourcePreprocessMap)}}assertMatchingSfcScriptLang(resolvedDescriptor,filename);const meta={routeConfig,pageMeta,hasScriptSetup:!!resolvedDescriptor.scriptSetup,hasSetupOption:!!resolvedDescriptor.script&&SETUP_CALL_RE.test(resolvedDescriptor.script.content),sfcSrcDeps,sfcSrcCompilationDeps:[templateResolvedId,scriptResolvedId,scriptSetupResolvedId].filter(id=>Boolean(id))};let scriptSetupMacroConfig;let scriptSetupMacroHash;let defineOptionsSource;const jsonKind=options?.json?.kind??(options?.isApp?`app`:options?.isPage?`page`:`component`);const jsonDefaults=options?.json?.defaults?.[jsonKind];const mergeJson=createJsonMerger(options?.json?.mergeStrategy,{filename,kind:jsonKind,routeConfig,pageMeta});const scriptSetup=resolvedDescriptor.scriptSetup;if(scriptSetup?.content){const scriptSetupForMap=usesExternalScriptCompileSource?descriptorForCompile.scriptSetup:scriptSetup;if(mayContainJsonMacro(scriptSetup.content)){const extracted=await extractJsonMacroFromScriptSetupWithSourceMap(scriptSetup.content,filename,scriptSetup.lang,{merge:(target,source)=>mergeJson(target,source,`macro`),preambleContent:resolvedDescriptor.script?.content},usesExternalScriptCompileSource||!scriptSetupForMap.src?{source:descriptorForCompileSource,sourceFile:filename,offset:scriptSetupForMap.loc.start.offset}:void 0);if(extracted.stripped!==scriptSetup.content){if(options?.sourceMap===false)(deferredPreprocessMaps??=[]).push(extracted);else scriptPreprocessMap=composeSourceMaps(extracted.map,scriptPreprocessMap);if(usesExternalScriptCompileSource){descriptorForCompile=replaceScriptSetupContent(descriptorForCompile,extracted.stripped);descriptorForCompileSource=descriptorForCompile.source}else if(scriptSetup.src)descriptorForCompile={...descriptorForCompile,scriptSetup:{...descriptorForCompile.scriptSetup,content:extracted.stripped}};else{const setupLoc=scriptSetup.loc;const startOffset=setupLoc.start.offset;const endOffset=setupLoc.end.offset;const nextSource=descriptorForCompileSource.slice(0,startOffset)+extracted.stripped+descriptorForCompileSource.slice(endOffset);const{descriptor:nextDescriptor,errors:nextErrors}=await parseSfc(nextSource,filename,false);if(nextErrors.length>0)throw createSfcParseError(nextErrors[0],{filename,source,sourceMap:resolvePreprocessSourceMap(scriptPreprocessMap,deferredPreprocessMaps)});assertMatchingSfcScriptLang(nextDescriptor,filename);if(options?.sfcSrc){const resolvedNext=await resolveSfcBlockSrc(nextDescriptor,filename,options.sfcSrc);descriptorForCompile=resolvedNext.descriptor;if(resolvedNext.deps.length){sfcSrcDeps=[.../* @__PURE__ */ new Set([...sfcSrcDeps??[],...resolvedNext.deps])];meta.sfcSrcDeps=sfcSrcDeps}}else descriptorForCompile=nextDescriptor;descriptorForCompileSource=nextSource}}scriptSetupMacroConfig=extracted.config;scriptSetupMacroHash=extracted.macroHash}if(DEFINE_OPTIONS_CALL_RE.test(scriptSetup.content))defineOptionsSource=scriptSetup}const compileScriptSetup=descriptorForCompile.scriptSetup;if(compileScriptSetup?.content&&DEFINE_OPTIONS_CALL_RE.test(compileScriptSetup.content)){const inlined=await inlineScriptSetupDefineOptionsArgs(compileScriptSetup.content,filename,compileScriptSetup.lang,usesExternalScriptCompileSource||!compileScriptSetup.src?{source:descriptorForCompileSource,sourceFile:filename,offset:compileScriptSetup.loc.start.offset}:void 0);if(inlined.code!==compileScriptSetup.content){if(options?.sourceMap===false)(deferredPreprocessMaps??=[]).push(inlined);else scriptPreprocessMap=composeSourceMaps(inlined.map,scriptPreprocessMap);if(usesExternalScriptCompileSource){descriptorForCompile=replaceScriptSetupContent(descriptorForCompile,inlined.code);descriptorForCompileSource=descriptorForCompile.source}else if(compileScriptSetup.src)descriptorForCompile={...descriptorForCompile,scriptSetup:{...compileScriptSetup,content:inlined.code}};else{const setupLoc=compileScriptSetup.loc;const startOffset=setupLoc.start.offset;const endOffset=setupLoc.end.offset;const nextSource=descriptorForCompileSource.slice(0,startOffset)+inlined.code+descriptorForCompileSource.slice(endOffset);const{descriptor:nextDescriptor,errors:nextErrors}=await parseSfc(nextSource,filename,false);if(nextErrors.length>0)throw createSfcParseError(nextErrors[0],{filename,source,sourceMap:resolvePreprocessSourceMap(scriptPreprocessMap,deferredPreprocessMaps)});assertMatchingSfcScriptLang(nextDescriptor,filename);if(options?.sfcSrc){const resolvedNext=await resolveSfcBlockSrc(nextDescriptor,filename,options.sfcSrc);descriptorForCompile=resolvedNext.descriptor;if(resolvedNext.deps.length){sfcSrcDeps=[.../* @__PURE__ */ new Set([...sfcSrcDeps??[],...resolvedNext.deps])];meta.sfcSrcDeps=sfcSrcDeps}}else descriptorForCompile=nextDescriptor;descriptorForCompileSource=nextSource}}}const isAppFile=APP_VUE_FILE_RE.test(filename);const nativeAnalysis=hasSharedNativeAnalysis(descriptorForCompile,defineOptionsSource,isAppFile,options?.isPage===true)?analyzeNativeScriptBlocks(descriptorForCompile,filename,defineOptionsSource,options?.isPage===true):void 0;const defineOptionsHash=defineOptionsSource?extractDefineOptionsHash(defineOptionsSource.content,nativeAnalysis?.defineOptions):void 0;return{descriptor:resolvedDescriptor,descriptorForCompile,scriptPreprocessMap,templateResolvedId,meta,scriptSetupMacroConfig,scriptSetupMacroHash,defineOptionsHash,jsonKind,jsonDefaults,mergeJson,isAppFile,nativeScriptAnalysis:nativeAnalysis?.scripts}}const RECORDER_KEY=`__weappCompilerProfilePhaseRecorder`;function getRecorder(){const recorder=Reflect.get(globalThis,RECORDER_KEY);if(!recorder||typeof recorder!==`object`||typeof Reflect.get(recorder,`record`)!==`function`)return;return recorder}function withCompilerPhase(name,run){const recorder=getRecorder();if(!recorder)return run();const startedAt=performance.now();const finish=()=>recorder.record(name,performance.now()-startedAt);try{const result=run();if(result&&typeof result.then===`function`)return Promise.resolve(result).then(value=>{finish();return value},error=>{finish();throw error});finish();return result}catch(error){finish();throw error}}function createModuleFacts(id,ast){let scope;traverse(ast,{Program(path){scope=path.scope;path.stop()}});return{id,ast,scope}}function unwrap(node){return t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTSTypeAssertion(node)||t.isTypeCastExpression(node)||t.isParenthesizedExpression(node)?unwrap(node.expression):node}function staticName(node,computed=false){node=unwrap(node);if(t.isStringLiteral(node)||t.isNumericLiteral(node))return String(node.value);if(!computed&&t.isIdentifier(node))return node.name;if(t.isTemplateLiteral(node)&&!node.expressions.length)return node.quasis[0]?.value.cooked??node.quasis[0]?.value.raw}function isImportedCall(node,module,importedName,sources){if(!t.isCallExpression(node)||!t.isIdentifier(node.callee))return false;const importPath=module.scope.getBinding(node.callee.name)?.path;const declaration=importPath?.parentPath;return Boolean(importPath?.isImportSpecifier()&&importPath.node.importKind!==`type`&&t.isIdentifier(importPath.node.imported,{name:importedName})&&declaration?.isImportDeclaration()&&declaration.node.importKind!==`type`&&sources.includes(declaration.node.source.value))}function createPropsModuleResolver(reader,root){const modules=/* @__PURE__ */ new Map([[root.id,Promise.resolve(root)]]);const load=id=>{let task=modules.get(id);if(!task){task=(async()=>{const source=await reader.load(id);if(!source||source.descriptor||source.invalid)return;try{source.ast??=parseJsLike(source.source);return createModuleFacts(id,source.ast)}catch{return}})();modules.set(id,task)}return task};const resolveExport=async(source,importer,name,visiting=/* @__PURE__ */ new Set)=>{const id=await reader.resolve(source,importer);if(!id)return;const key=`${id}\0${name}`;if(visiting.has(key))return;const next=new Set(visiting).add(key);const module=await load(id);if(!module)return;for(const statement of module.ast.program.body){if(name==="default"&&t.isExportDefaultDeclaration(statement))return{node:statement.declaration,module};if(!t.isExportNamedDeclaration(statement)||statement.exportKind===`type`)continue;if(t.isVariableDeclaration(statement.declaration)){for(const declaration of statement.declaration.declarations)if(t.isIdentifier(declaration.id,{name}))return{node:declaration.id,module}}for(const specifier of statement.specifiers){if(!t.isExportSpecifier(specifier)||specifier.exportKind===`type`||staticName(specifier.exported)!==name)continue;const local=staticName(specifier.local);if(statement.source)return local?resolveExport(statement.source.value,module.id,local,next):void 0;return{node:specifier.local,module}}}};const resolveImport=async(node,module)=>{node=unwrap(node);let local;let member;if(t.isIdentifier(node))local=node.name;else if(t.isMemberExpression(node)&&t.isIdentifier(node.object)){local=node.object.name;member=staticName(node.property,node.computed);if(!member)return}const binding=local&&module.scope.getBinding(local);if(!binding||!binding.path.parentPath?.isImportDeclaration()||binding.path.parentPath.node.importKind===`type`)return;const declaration=binding.path.parentPath.node;const specifier=binding.path.node;const name=t.isImportDefaultSpecifier(specifier)&&member===void 0?`default`:t.isImportSpecifier(specifier)&&specifier.importKind!==`type`&&member===void 0?staticName(specifier.imported):t.isImportNamespaceSpecifier(specifier)?member:void 0;return name?resolveExport(declaration.source.value,module.id,name):void 0};return{resolveImport}}function isObjectCall(node,scope,name){return t.isCallExpression(node)&&t.isMemberExpression(node.callee)&&!node.callee.computed&&t.isIdentifier(node.callee.object,{name:`Object`})&&!scope.getBinding(`Object`)&&t.isIdentifier(node.callee.property,{name})}function isGeneratedSetupReturn(reference,setup){const property=reference.parentPath;const object=property?.parentPath;const declaration=object?.parentPath;return Boolean(setup&&property?.isObjectProperty()&&property.node.value===reference.node&&object?.isObjectExpression()&&declaration?.isVariableDeclarator()&&t.isIdentifier(declaration.node.id,{name:`__returned__`})&&declaration.findParent(parent=>parent.node===setup))}function isSafeReference(reference,ownership,visiting){let current=reference;while(current.parentPath&&unwrap(current.parentPath.node)===unwrap(current.node))current=current.parentPath;if(ownership.props&&unwrap(current.node)===unwrap(ownership.props)||isGeneratedSetupReturn(current,ownership.setup))return true;if(current.findParent(parent=>t.isTSType(parent.node)))return true;const parent=current.parentPath;if(parent?.isSpreadElement()&&(parent.parentPath.isObjectExpression()||parent.parentPath.isArrayExpression()))return true;if(parent?.isCallExpression())return isObjectCall(parent.node,parent.scope,`freeze`)&&parent.node.arguments.length===1||isObjectCall(parent.node,parent.scope,`assign`)&&parent.node.arguments.indexOf(current.node)>0;if(parent?.isVariableDeclarator()&&t.isIdentifier(parent.node.id)&&parent.node.init===current.node)return isSafePropsBinding(parent.scope.getBinding(parent.node.id.name),ownership,visiting);return false}function isSafePropsBinding(binding,ownership,visiting=/* @__PURE__ */ new Set){if(!binding?.constant||!binding.path.isVariableDeclarator()||!binding.path.parentPath.isVariableDeclaration()||binding.path.parentPath.node.kind!==`const`||binding.path.parentPath.parentPath?.isExportNamedDeclaration()||visiting.has(binding.path.node))return false;const next=new Set(visiting).add(binding.path.node);return binding.referencePaths.every(reference=>isSafeReference(reference,ownership,next))}const absent={kind:`absent`};const unknown={kind:`unknown`};function isSafeOptionReference(reference,allowed,visiting){let current=reference;while(current.parentPath&&unwrap(current.parentPath.node)===unwrap(current.node))current=current.parentPath;if(allowed.has(unwrap(current.node))||current.findParent(parent=>t.isTSType(parent.node)))return true;const parent=current.parentPath;if(parent?.isVariableDeclarator()&&t.isIdentifier(parent.node.id)&&parent.node.init===current.node)return isSafeOptionBinding(parent.scope.getBinding(parent.node.id.name),allowed,visiting);return false}function isSafeOptionBinding(binding,allowed,visiting=/* @__PURE__ */ new Set){if(!binding?.constant||!binding.path.isVariableDeclarator()||!binding.path.parentPath.isVariableDeclaration()||binding.path.parentPath.node.kind!==`const`||binding.path.parentPath.parentPath?.isExportNamedDeclaration()||visiting.has(binding.path.node))return false;const next=new Set(visiting).add(binding.path.node);return binding.referencePaths.every(reference=>isSafeOptionReference(reference,allowed,next))}function isComponentFactory(node,module){if(!t.isIdentifier(node.callee))return false;const binding=module.scope.getBinding(node.callee.name);return binding?.path.isImportSpecifier()&&t.isIdentifier(binding.path.node.imported,{name:`defineComponent`})&&binding.path.parentPath.isImportDeclaration()&&[`vue`,`wevu`,`wevu/internal-runtime`,`virtual:weapp-vite/runtime`].includes(binding.path.parentPath.node.source.value)}function isSafeMergeOperand(input,module,visiting){const node=unwrap(input);if(visiting.has(node))return false;const next=new Set(visiting).add(node);if(t.isIdentifier(node)){const binding=module.scope.getBinding(node.name);return isSafeOptionBinding(binding,next)&&Boolean(binding?.path.isVariableDeclarator()&&binding.path.node.init&&isSafeMergeOperand(binding.path.node.init,module,next))}if(t.isObjectExpression(node))return node.properties.every(property=>{if(t.isSpreadElement(property))return isSafeMergeOperand(property.argument,module,next);const key=staticName(property.key,property.computed);return key!==void 0&&key!==`__proto__`&&(t.isObjectProperty(property)||property.kind===`method`)});if(t.isCallExpression(node)){if(isComponentFactory(node,module)&&node.arguments.length===1&&t.isExpression(node.arguments[0]))return isSafeMergeOperand(node.arguments[0],module,next);if(isObjectCall(node,module.scope,`assign`))return node.arguments.every(argument=>t.isExpression(argument)&&isSafeMergeOperand(argument,module,next))}return false}function findCompiledOption(input,name,module,visiting=/* @__PURE__ */ new Set){const node=unwrap(input);if(visiting.has(node))return unknown;const next=new Set(visiting).add(node);if(t.isIdentifier(node)){const binding=module.scope.getBinding(node.name);return isSafeOptionBinding(binding,next)&&binding?.path.isVariableDeclarator()&&binding.path.node.init?findCompiledOption(binding.path.node.init,name,module,next):unknown}if(t.isObjectExpression(node)){for(const property of[...node.properties].reverse()){if(t.isSpreadElement(property)){const inherited=findCompiledOption(property.argument,name,module,next);if(inherited.kind!==`absent`)return inherited;continue}const key=staticName(property.key,property.computed);if(key===void 0||key===`__proto__`)return unknown;if(key===name)return t.isObjectProperty(property)||property.kind===`method`?{kind:`value`,node:t.isObjectProperty(property)?property.value:property}:unknown}return absent}if(t.isCallExpression(node)){if(isComponentFactory(node,module)&&node.arguments.length===1&&t.isExpression(node.arguments[0]))return findCompiledOption(node.arguments[0],name,module,next);if(isObjectCall(node,module.scope,`assign`)){if(!node.arguments.every(argument=>t.isExpression(argument)&&isSafeMergeOperand(argument,module,next)))return unknown;for(const argument of[...node.arguments].reverse()){const option=t.isExpression(argument)?findCompiledOption(argument,name,module,next):unknown;if(option.kind!==`absent`)return option}return absent}}return unknown}function excludePropsObjectAliases(keys,setup){if(!setup||!(t.isObjectMethod(setup)||t.isFunctionExpression(setup)||t.isArrowFunctionExpression(setup))||!t.isIdentifier(setup.params[0])||!t.isBlockStatement(setup.body))return keys;const aliases=/* @__PURE__ */ new Set;for(const statement of setup.body.body)if(t.isVariableDeclaration(statement)){for(const declaration of statement.declarations)if(t.isIdentifier(declaration.id)&&t.isIdentifier(declaration.init,{name:setup.params[0].name}))aliases.add(declaration.id.name)}return keys.filter(key=>!aliases.has(key))}function constantInitializer(node,module){if(!t.isIdentifier(node))return;const binding=module.scope.getBinding(node.name);if(!binding?.constant||!binding.path.isVariableDeclarator()||!binding.path.parentPath.isVariableDeclaration()||binding.path.parentPath.node.kind!==`const`||!binding.path.node.init)return;return{binding,node:binding.path.node.init}}function createPropsShapeAnalyzer(modules,ownership){async function primitive(input,module,visiting=/* @__PURE__ */ new Set){const node=unwrap(input);if(visiting.has(node))return;const next=new Set(visiting).add(node);if(t.isStringLiteral(node)||t.isNumericLiteral(node))return node.value;if(t.isTemplateLiteral(node)&&!node.expressions.length)return staticName(node,true);const local=constantInitializer(node,module);if(local)return primitive(local.node,module,next);const imported=await modules.resolveImport(node,module);return imported?primitive(imported.node,imported.module,next):void 0}async function analyze(input,module,visiting=/* @__PURE__ */ new Set){const node=unwrap(input);if(visiting.has(node))return;const next=new Set(visiting).add(node);const local=constantInitializer(node,module);if(local){const value=await analyze(local.node,module,next);return value&&(value.frozen||isSafePropsBinding(local.binding,ownership))?value:void 0}if(t.isIdentifier(node)||t.isMemberExpression(node)){const imported=await modules.resolveImport(node,module);const value=imported&&await analyze(imported.node,imported.module,next);return value?.frozen?value:void 0}if(t.isCallExpression(node)&&isImportedCall(node,module,`mergeModels`,[`vue`])){if(node.arguments.length!==2||!node.arguments.every(t.isExpression))return;const[left,right]=await Promise.all(node.arguments.map(argument=>analyze(argument,module,next)));if(!left||!right)return;const names=new Set(left.names);right.names.forEach(name=>names.add(name));return{kind:left.kind===`array`&&right.kind===`array`?`array`:`object`,names,frozen:false}}if(isObjectCall(node,module.scope,`freeze`)&&node.arguments.length===1&&t.isExpression(node.arguments[0])){const value=await analyze(node.arguments[0],module,next);return value&&{...value,frozen:true}}if(isObjectCall(node,module.scope,`assign`)){const first=node.arguments[0]&&unwrap(node.arguments[0]);if(!t.isObjectExpression(first)||first.properties.length)return;const names=/* @__PURE__ */ new Set;for(const argument of node.arguments.slice(1)){if(!t.isExpression(argument))return;const value=await analyze(argument,module,next);if(!value||value.kind!==`object`)return;value.names.forEach(name=>names.add(name))}return{kind:`object`,names,frozen:false}}if(t.isObjectExpression(node)){const names=/* @__PURE__ */ new Set;for(const property of node.properties){if(t.isSpreadElement(property)){const value=await analyze(property.argument,module,next);if(!value||value.kind!==`object`)return;value.names.forEach(name=>names.add(name));continue}if(!t.isObjectProperty(property))return;const key=property.computed?await primitive(property.key,module,next):staticName(property.key);if(key===void 0||key===`__proto__`)return;names.add(String(key))}return{kind:`object`,names,frozen:false}}if(t.isArrayExpression(node)){const names=/* @__PURE__ */ new Set;for(const element of node.elements){if(!element)return;if(t.isSpreadElement(element)){const value=await analyze(element.argument,module,next);if(!value||value.kind!==`array`)return;value.names.forEach(name=>names.add(name))}else{const value=await primitive(element,module,next);if(typeof value!==`string`)return;names.add(value)}}return{kind:`array`,names,frozen:false}}}return{analyze}}async function resolveSetupPropConflicts(options){const dependencies=/* @__PURE__ */ new Set;if(!/\bprops\b/.test(options.script))return{dependencies:[]};let setupKeys=Object.entries(options.bindings??{}).filter(([,kind])=>typeof kind===`string`&&(kind.startsWith(`setup-`)||kind===`literal-const`)).map(([key])=>key);if(!setupKeys.length)return{dependencies:[]};const root=createModuleFacts(normalizeSourceId(options.filename),options.getScriptAst());const exported=root.ast.program.body.find(statement=>t.isExportDefaultDeclaration(statement));if(!exported||!t.isExportDefaultDeclaration(exported))return{conflicts:setupKeys,dependencies:[]};const props=findCompiledOption(exported.declaration,`props`,root);const setup=findCompiledOption(exported.declaration,`setup`,root);const setupNode=setup.kind===`value`?setup.node:void 0;setupKeys=excludePropsObjectAliases(setupKeys,setupNode);if(props.kind!==`value`)return{conflicts:props.kind===`unknown`?setupKeys:void 0,dependencies:[]};const reader=createAnalysisSourceReader({source:options.source,trackLogicalPaths:true},dependencies);const modules=createPropsModuleResolver(reader,root);const shape=await createPropsShapeAnalyzer(modules,{props:props.node,setup:setupNode}).analyze(props.node,root);dependencies.delete(root.id);return{conflicts:shape?setupKeys.filter(key=>shape.names.has(key)):setupKeys,dependencies:[...dependencies]}}function createSourceLineStarts(source){const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);return lineStarts}function clearBindingManifestLocations(manifest){for(const binding of manifest.bindings)if(!binding.sourceFile)binding.sourceLocation=void 0}function normalizeSourceFile(filename){return filename.replaceAll(`\\`,`/`).replace(/^\.\//,``)}function sourceFilesMatch(left,right){const normalizedLeft=normalizeSourceFile(left);const normalizedRight=normalizeSourceFile(right);return normalizedLeft===normalizedRight||normalizedLeft.endsWith(`/${normalizedRight}`)||normalizedRight.endsWith(`/${normalizedLeft}`)}function resolveMappedSource(sourceMap,originalSource,fallbackSource){if(!isEncodedSourceMapLike(sourceMap))return{content:fallbackSource,sourceFile:originalSource,hasMappedContent:false};const normalizedOriginal=normalizeSourceFile(originalSource);const sourceIndex=sourceMap.sources.findIndex(candidate=>{return sourceFilesMatch(candidate,normalizedOriginal)});const sourceFile=sourceIndex>=0?sourceMap.sources[sourceIndex]:originalSource;const mappedContent=sourceIndex>=0?sourceMap.sourcesContent?.[sourceIndex]:void 0;return{content:mappedContent??fallbackSource,sourceFile,hasMappedContent:mappedContent!=null}}function remapJsxBindingManifestLocations(manifest,sourceMap,source,sourceFile,diagnostics=[]){const compiledSourceFile=manifest.sourceFile;const ownedDiagnostics=[...diagnostics].filter(item=>sourceFilesMatch(item.filename,compiledSourceFile));const clearLocations=()=>{clearBindingManifestLocations(manifest);for(const diagnostic of ownedDiagnostics)diagnostic.loc=void 0};if(sourceFile)manifest.sourceFile=sourceFile;if(!source||!sourceMap){clearLocations();return}let traceMap;try{traceMap=new TraceMap(sourceMap)}catch{clearLocations();return}const lineStartsCache=/* @__PURE__ */ new Map;const remap=(line,column)=>{let original;try{original=originalPositionFor(traceMap,{line,column:Math.max(0,column-1)})}catch{return}if(original.source==null||original.line==null||original.column==null)return;const mapped=resolveMappedSource(sourceMap,original.source,source);const ownedSourceFile=sourceFile??(sourceFilesMatch(mapped.sourceFile,manifest.sourceFile)?manifest.sourceFile:mapped.sourceFile);if(!mapped.hasMappedContent&&!sourceFilesMatch(ownedSourceFile,manifest.sourceFile))return;const content=sourceFilesMatch(ownedSourceFile,manifest.sourceFile)?source:mapped.content;let lineStarts=lineStartsCache.get(content);if(!lineStarts){lineStarts=createSourceLineStarts(content);lineStartsCache.set(content,lineStarts)}return{position:{offset:(lineStarts[original.line-1]??0)+original.column,line:original.line,column:original.column+1},sourceFile:sourceFilesMatch(ownedSourceFile,manifest.sourceFile)?void 0:normalizeSourceFile(ownedSourceFile)}};for(const binding of manifest.bindings){const location=binding.sourceLocation;if(!location)continue;if(binding.sourceFile&&!sourceFilesMatch(binding.sourceFile,manifest.sourceFile))continue;const start=remap(location.start.line,location.start.column);const end=remap(location.end.line,location.end.column);if(!start||!end||start.sourceFile!==end.sourceFile){binding.sourceLocation=void 0;continue}binding.sourceFile=start.sourceFile;binding.sourceLocation={start:start.position,end:end.position}}for(const diagnostic of ownedDiagnostics){if(!diagnostic.loc)continue;const start=remap(diagnostic.loc.start.line,diagnostic.loc.start.column);const last=remap(diagnostic.loc.end.line,Math.max(1,diagnostic.loc.end.column-1));const end=last&&{sourceFile:last.sourceFile,position:{...last.position,offset:last.position.offset+1,column:last.position.column+1}};diagnostic.loc=start&&end&&start.sourceFile===end.sourceFile?{start:start.position,end:end.position}:void 0;diagnostic.filename=start?.sourceFile??sourceFile??diagnostic.filename}}const RESERVED_SCRIPT_SETUP_PROPS=/* @__PURE__ */ new Set([`id`,`class`,`slot`]);const RESERVED_PROPS_WARNING=`defineProps 中声明 id/class/slot 可能无法在小程序 properties 中正确取值,请改用其他 prop 名称。`;function getStaticKeyName(key){if(t.isIdentifier(key))return key.name;if(t.isStringLiteral(key))return key.value}function getTypePropertyName(key){if(t.isIdentifier(key))return key.name;if(t.isStringLiteral(key))return key.value}function isReservedScriptSetupProp(name){return name!=null&&RESERVED_SCRIPT_SETUP_PROPS.has(name)}function runtimePropsContainReservedName(node){if(t.isObjectExpression(node))return node.properties.some(prop=>t.isObjectProperty(prop)&&!prop.computed&&isReservedScriptSetupProp(getStaticKeyName(prop.key)));if(t.isArrayExpression(node))return node.elements.some(element=>t.isStringLiteral(element)&&isReservedScriptSetupProp(element.value));return false}function createTypeScope(ast){const scope=/* @__PURE__ */ new Map;traverse(ast,{TSInterfaceDeclaration(path){scope.set(path.node.id.name,path.node.body)},TSTypeAliasDeclaration(path){scope.set(path.node.id.name,path.node.typeAnnotation)}});return scope}function typePropsContainReservedName(typeNode,scope,seen=/* @__PURE__ */ new Set){if(!typeNode)return false;if(t.isTSTypeLiteral(typeNode))return typeNode.members.some(member=>{return t.isTSPropertySignature(member)&&!member.computed&&isReservedScriptSetupProp(getTypePropertyName(member.key))});if(t.isTSInterfaceBody(typeNode))return typeNode.body.some(member=>{return t.isTSPropertySignature(member)&&!member.computed&&isReservedScriptSetupProp(getTypePropertyName(member.key))});if(t.isTSIntersectionType(typeNode))return typeNode.types.some(item=>typePropsContainReservedName(item,scope,seen));if(t.isTSTypeReference(typeNode)&&t.isIdentifier(typeNode.typeName)){const typeName=typeNode.typeName.name;if(seen.has(typeName))return false;const resolved=scope.get(typeName);if(!resolved)return false;seen.add(typeName);return typePropsContainReservedName(resolved,scope,seen)}return false}function getDefinePropsLocation(node){const start=node.loc?.start;if(!start)return;return{line:start.line,column:start.column}}function resolveSourceLocation(location,scriptSetupStart){if(!location)return;if(!scriptSetupStart)return location;return{line:scriptSetupStart.line+location.line-1,column:location.line===1?scriptSetupStart.column+location.column:location.column}}function createReservedPropsWarning(location,filename){if(!location||!filename)return RESERVED_PROPS_WARNING;return`${filename}:${location.line}:${location.column+1} ${RESERVED_PROPS_WARNING}`}function detectDefinePropsReservedName(scriptSetupCode){let result;try{const ast=parseJsLike(scriptSetupCode);const typeScope=createTypeScope(ast);traverse(ast,{CallExpression(path){const callee=path.node.callee;if(!t.isIdentifier(callee,{name:`defineProps`}))return;if(runtimePropsContainReservedName(path.node.arguments[0])){result={location:getDefinePropsLocation(path.node)};path.stop();return}const typeParam=(path.node.typeParameters??path.node.typeArguments)?.params?.[0];if(typePropsContainReservedName(typeParam,typeScope)){result={location:getDefinePropsLocation(path.node)};path.stop()}}})}catch{return}return result}function warnReservedScriptSetupProps(scriptSetupCode,warn,context={},diagnostic){if(!scriptSetupCode)return;const offset=diagnostic?.warningOffset;const lines=offset===void 0?void 0:scriptSetupCode.slice(0,offset).split(/\r\n|[\r\n\u2028\u2029]/);const result=diagnostic?lines&&{location:{line:lines.length,column:lines.at(-1).length}}:detectDefinePropsReservedName(scriptSetupCode);if(!result)return;const location=resolveSourceLocation(result.location,context.scriptSetupStart);warn?.(createReservedPropsWarning(location,context.filename))}const TYPE_ONLY_DEFINE_PROPS_RE=/\bdefineProps\s*</;function readNativePageFeatureFlags(analysis){const flags=analysis?.pageFeatureFlags;if(!flags)return;const knownFlags=new Set(Object.values(WE_VU_PAGE_HOOK_TO_FEATURE));if(!flags.every(flag=>knownFlags.has(flag)))return;return flags}function resolveScriptSetupPropsAliases(bindings){const aliases=bindings?.__propsAliases;if(!aliases||typeof aliases!==`object`)return;const resolved={};for(const[alias,propName]of Object.entries(aliases))if(typeof propName===`string`&&propName.length>0)resolved[alias]=propName;return Object.keys(resolved).length?resolved:void 0}function resolveScriptSetupPropsDerivedKeys(bindings){const keys=/* @__PURE__ */ new Set;for(const[key,bindingType]of Object.entries(bindings??{})){if(key.startsWith(`__`)||bindingType!==`props`&&bindingType!==`props-aliased`)continue;keys.add(key)}return keys.size?[...keys]:void 0}function bindingsMayContainProps(bindings,scriptCode){for(const[key,bindingType]of Object.entries(bindings??{}))if(key===`__propsAliases`||bindingType===`props`||bindingType===`props-aliased`)return true;return scriptCode.includes(`__props`)||scriptCode.includes(`props:`)}function hasPrecomputedScriptPhaseInfo(info,key){return Boolean(info)&&Object.prototype.hasOwnProperty.call(info,key)}function collectScriptSetupReturnInfo(getScriptAst){const keys=/* @__PURE__ */ new Set;const propsObjectAliases=/* @__PURE__ */ new Set([`__props`]);const propsRefsAliases=/* @__PURE__ */ new Set;const destructuredPropsKeys=/* @__PURE__ */ new Set;const addObjectPatternKeys=pattern=>{for(const property of pattern.properties){if(!t.isObjectProperty(property))continue;if(t.isIdentifier(property.value))destructuredPropsKeys.add(property.value.name);else if(t.isAssignmentPattern(property.value)&&t.isIdentifier(property.value.left))destructuredPropsKeys.add(property.value.left.name)}};try{const ast=getScriptAst();traverse(ast,{VariableDeclarator(path){const init=path.node.init;if(t.isIdentifier(path.node.id)&&t.isIdentifier(init)&&propsObjectAliases.has(init.name)){propsObjectAliases.add(path.node.id.name);return}if(t.isIdentifier(path.node.id)&&t.isCallExpression(init)&&t.isIdentifier(init.callee,{name:`toRefs`})&&init.arguments.length===1&&t.isIdentifier(init.arguments[0])&&propsObjectAliases.has(init.arguments[0].name)){propsRefsAliases.add(path.node.id.name);return}if(!t.isObjectPattern(path.node.id))return;if(t.isIdentifier(init)&&propsObjectAliases.has(init.name)){addObjectPatternKeys(path.node.id);return}if(t.isIdentifier(init)&&propsRefsAliases.has(init.name)){addObjectPatternKeys(path.node.id);return}if(t.isCallExpression(init)&&t.isIdentifier(init.callee,{name:`toRefs`})&&init.arguments.length===1&&t.isIdentifier(init.arguments[0])&&propsObjectAliases.has(init.arguments[0].name))addObjectPatternKeys(path.node.id)},ObjectProperty(path){const objectPath=path.parentPath;if(!objectPath.isObjectExpression()||!objectPath.parentPath.isVariableDeclarator()||!t.isIdentifier(objectPath.parentPath.node.id,{name:`__returned__`}))return;const prop=path.node;if(prop.computed)return;if(t.isIdentifier(prop.key))keys.add(prop.key.name);else if(t.isStringLiteral(prop.key))keys.add(prop.key.value)}})}catch{return{returnedKeys:keys,destructuredPropsKeys}}return{returnedKeys:keys,destructuredPropsKeys}}function resolveEffectivePropsDerivedKeys(bindings,scriptCode,getScriptAst=()=>parseJsLike(scriptCode)){if(!bindingsMayContainProps(bindings,scriptCode))return;const directKeys=resolveScriptSetupPropsDerivedKeys(bindings)??[];const{returnedKeys,destructuredPropsKeys}=collectScriptSetupReturnInfo(getScriptAst);const aliases=resolveScriptSetupPropsAliases(bindings)??{};const propsKeys=new Set(Object.entries(bindings??{}).filter(([key,bindingType])=>key&&!key.startsWith(`__`)&&bindingType===`props`).map(([key])=>key));const keys=/* @__PURE__ */ new Set;for(const key of directKeys)keys.add(key);for(const key of destructuredPropsKeys)keys.add(key);for(const[alias,propName]of Object.entries(aliases)){if(!returnedKeys.has(alias))keys.add(alias);if(propsKeys.has(propName)&&!returnedKeys.has(propName))keys.add(propName)}for(const key of propsKeys)if(!returnedKeys.has(key))keys.add(key);return keys.size?[...keys]:void 0}async function compileScriptPhase(descriptor,descriptorForCompile,filename,options,_autoUsingComponents,templateCompiled,isAppFile,componentSourceInfo,precompiledScript,precomputedScriptPhaseInfo,originalSource,scriptPreprocessMap,nativeScriptAnalysis){const nativeDom=!isAppFile&&isNativeDomCompilation(options);const autoUsingComponentsMap={...componentSourceInfo?.autoUsingComponentsMap??{}};const autoComponentMeta={...componentSourceInfo?.autoComponentMeta??{}};const relaxStructuredTypeOnlyProps=Boolean(descriptor.scriptSetup?.content&&TYPE_ONLY_DEFINE_PROPS_RE.test(descriptor.scriptSetup.content));let scriptCode;let scriptMap=null;let propsAliases=options?.template?.propsAliases;let propsDerivedKeys;let jsxDiagnostics;if(descriptor.script||descriptor.scriptSetup){const scriptCompiled=precompiledScript??compileScript(descriptorForCompile,{id:generateScopedId(filename),isProd:false});warnReservedScriptSetupProps(descriptorForCompile.scriptSetup?.content,options?.warn,{filename,scriptSetupStart:descriptorForCompile.scriptSetup?.loc.start},nativeScriptAnalysis?.scriptSetup?.reservedPropsDiagnostic);if(!propsAliases&&hasPrecomputedScriptPhaseInfo(precomputedScriptPhaseInfo,`propsAliases`))propsAliases=precomputedScriptPhaseInfo.propsAliases;propsAliases??=resolveScriptSetupPropsAliases(scriptCompiled.bindings);scriptCode=scriptCompiled.content;propsDerivedKeys=hasPrecomputedScriptPhaseInfo(precomputedScriptPhaseInfo,`propsDerivedKeys`)?precomputedScriptPhaseInfo.propsDerivedKeys:resolveEffectivePropsDerivedKeys(scriptCompiled.bindings,scriptCode);const compiledScriptMap=options?.sourceMap!==false&&scriptCompiled.map&&typeof scriptCompiled.map===`object`?scriptCompiled.map:null;scriptMap=compiledScriptMap?composeSourceMaps(compiledScriptMap,scriptPreprocessMap):null;if(scriptCode.includes(`defineAppJson`)||scriptCode.includes(`definePageJson`)||scriptCode.includes(`defineComponentJson`))scriptCode=stripJsonMacroCallsFromCode(scriptCode,filename);const defaultExportAnalysis=scriptCode===descriptorForCompile.script?.content?nativeScriptAnalysis?.script:void 0;if(!isAppFile&&!descriptor.scriptSetup&&!hasDefaultExport(scriptCode,defaultExportAnalysis))scriptCode+=`
40
+ export default {}`}else scriptCode=`export default {}`;if(scriptCode){const scriptLang=descriptor.script?.lang??descriptor.scriptSetup?.lang;const isJsxScript=scriptLang===`jsx`||scriptLang===`tsx`;let jsxTemplate;if(isJsxScript){jsxTemplate=compileJsxTemplateAndCollectComponents(scriptCode,filename,options);const externalScriptBlock=descriptor.script?.src?descriptor.script:descriptor.scriptSetup?.src?descriptor.scriptSetup:void 0;remapJsxBindingManifestLocations(jsxTemplate.bindingManifest,scriptMap,externalScriptBlock?.content??originalSource,externalScriptBlock?.src,jsxTemplate.warningDiagnostics.values());if(jsxTemplate.template&&(options?.pageLayout||options?.appShell))jsxTemplate.template=applyCompilerTemplateWrappers({template:jsxTemplate.template,manifest:jsxTemplate.bindingManifest,platform:options?.template?.platform??getMiniProgramTemplatePlatform(),pageLayout:options?.pageLayout,appShell:options?.appShell});const reportJsxWarnings=!descriptor.template||Boolean(jsxTemplate.template);scriptCode=injectDynamicIslandRuntime(stripRenderOptionFromScript(scriptCode,filename,reportJsxWarnings?jsxTemplate.warnings:void 0),jsxTemplate.dynamicIslands);if(reportJsxWarnings&&jsxTemplate.warnings.length){jsxDiagnostics=createJsxDiagnostics(jsxTemplate.warnings,filename,jsxTemplate.warningDiagnostics);reportJsxDiagnostics(jsxDiagnostics,options?.warn)}}const jsxTransformed=isJsxScript?(await import(`./vueJsxTransform-C4lhnLbg.mjs`)).transformVueJsxScript(scriptCode,filename,options?.sourceMap!==false):{code:scriptCode,map:null};const bindingManifest=jsxTemplate?.template?jsxTemplate.bindingManifest:templateCompiled?.bindingManifest;const effectiveInlineExpressions=jsxTemplate?.template?jsxTemplate.inlineExpressions:templateCompiled?.inlineExpressions;const templateRuntimeCapabilities=bindingManifest?createWevuRuntimeCapabilityMetadataFromBindingManifest(bindingManifest):templateCompiled?.runtimeCapabilities;const nativeSlotContext=!isAppFile&&usesNativeDeclarationContext({platform:options?.template?.platform??getMiniProgramTemplatePlatform(),scopedSlotsRequireProps:options?.template?.scopedSlotsRequireProps??options?.template?.scopedSlotsCompiler!==`augmented`,nativeSlotContext:options?.template?.nativeSlotContext===true});const runtimeCapabilities=mergeWevuRuntimeCapabilityMetadata(templateRuntimeCapabilities,nativeSlotContext?createWevuRuntimeCapabilityMetadata([`scopedSlots`]):void 0);const transformed=withCompilerPhase(`transformScript`,()=>transformScript(jsxTransformed.code,{isTypeScript:descriptor.script?.lang===`ts`||descriptor.script?.lang===`tsx`||descriptor.scriptSetup?.lang===`ts`||descriptor.scriptSetup?.lang===`tsx`,skipComponentTransform:nativeDom||(options?.skipComponentTransform??isAppFile),isApp:isAppFile,isPage:options?.isPage===true,nativePageFeatureFlags:scriptCode===descriptorForCompile.script?.content?readNativePageFeatureFlags(nativeScriptAnalysis?.script):void 0,minify:options?.minify,sourceMap:options?.sourceMap,warn:options?.warn,templateComponentMeta:Object.keys(autoComponentMeta).length?Object.fromEntries(Object.entries(autoComponentMeta).filter(([name])=>!nativeDom||!componentSourceInfo?.wevuComponentTags.has(name))):void 0,wevuDefaults:options?.wevuDefaults,classStyleRuntime:templateCompiled?.classStyleRuntime,classStyleBindings:templateCompiled?.classStyleBindings,templateRefs:templateCompiled?.templateRefs,layoutHosts:templateCompiled?.layoutHosts,inlineExpressions:effectiveInlineExpressions,bindingManifest:isAppFile?void 0:bindingManifest,autoSetDataPick:!isAppFile&&options?.autoSetDataPick,runtimeBindingManifest:options?.runtimeBindingManifest,pageLayout:isAppFile?void 0:options?.pageLayout,runtimeCapabilities,functionPropPaths:templateCompiled?.functionPropPaths,propsAliases,propsDerivedKeys,cssModules:precomputedScriptPhaseInfo?.cssModules,stabilizeCssVarsRuntime:options?.stabilizeCssVarsRuntime,relaxStructuredTypeOnlyProps,nativeSlotContext,scopedSlotHostProperties:!isAppFile&&options?.isPage!==true&&Boolean(templateCompiled?.hasSlotOutlet||templateCompiled?.componentGenerics&&Object.keys(templateCompiled.componentGenerics).length>0)}));const nativeResult=nativeDom?attachNativeDom({script:transformed.code,filename,descriptor:descriptorForCompile,bindings:precompiledScript?.bindings,components:componentSourceInfo,templateComputedBindings:templateCompiled?.classStyleBindings?.map(binding=>binding.name),options,scopeId:descriptorForCompile.styles.some(style=>style.scoped)?`data-v-${generateScopedId(filename)}`:void 0}):void 0;return{script:nativeResult?.code??transformed.code,scriptMap:composeSourceMaps(nativeResult?.map,composeSourceMaps(transformed.map??jsxTransformed.map,scriptMap)),template:jsxTemplate?.template,diagnostics:jsxDiagnostics,bindingManifest,inlineExpressions:jsxTemplate?.inlineExpressions,runtimeCapabilities:transformed.runtimeCapabilities,componentStyleOptions:transformed.componentStyleOptions,autoUsingComponentsMap,autoComponentMeta}}return{script:scriptCode,scriptMap:null,autoUsingComponentsMap,autoComponentMeta}}async function compileStylePhase(descriptor,filename,result,options){if(descriptor.styles.length===0)return{usesSlotted:false};const scopedId=generateScopedId(filename);const compiledStyles=await Promise.all(descriptor.styles.map(async styleBlock=>{return await compileVueStyleToWxss(styleBlock,{id:scopedId,filename,scoped:styleBlock.scoped,modules:styleBlock.module,preprocessOptions:options?.preprocessOptions?.[styleBlock.lang||`css`],preserveDeepSelectors:options?.preserveDeepSelectors,transformScoped:options?.transformScoped})}));result.style=compiledStyles.map(s=>s.code.trim()).filter(Boolean).join(`
41
41
 
42
- `);if(!compiledStyles.some(s=>s.modules))return{usesSlotted:compiledStyles.some(style=>style.usesSlotted)};const modulesMap={};compiledStyles.forEach(compiled=>{if(compiled.modules)Object.assign(modulesMap,compiled.modules)});result.cssModules=modulesMap;return{usesSlotted:compiledStyles.some(style=>style.usesSlotted)}}function remapTemplateDiagnostics(diagnostics,base,source){const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);const remap=position=>{const line=base.line+position.line-1;const column=position.line===1?base.column+position.column-1:position.column;return{offset:Math.min(source.length,(lineStarts[line-1]??base.offset+position.offset)+column-1),line,column}};for(const diagnostic of diagnostics)if(diagnostic.loc)diagnostic.loc={start:remap(diagnostic.loc.start),end:remap(diagnostic.loc.end)}}function ownExternalTemplateDiagnostics(diagnostics,filename,source){const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);const own=position=>{let low=0;let high=lineStarts.length;while(low+1<high){const middle=low+high>>1;if(lineStarts[middle]<=position.offset)low=middle;else high=middle}const line=low+1;return{offset:position.offset,line,column:position.offset-lineStarts[line-1]+1}};for(const diagnostic of diagnostics){diagnostic.filename=filename;if(diagnostic.loc)diagnostic.loc={start:own(diagnostic.loc.start),end:own(diagnostic.loc.end)}}}function updateTemplateBindingManifests(templateCompiled,sourceFile,remap,runtimeBindingManifest){const updateManifest=manifest=>{manifest.sourceFile=sourceFile;if(!remap)return;for(const binding of manifest.bindings)if(binding.sourceLocation)binding.sourceLocation={start:remap(binding.sourceLocation.start),end:remap(binding.sourceLocation.end)}};updateManifest(templateCompiled.bindingManifest);for(const asset of templateCompiled.scopedSlotComponents??[]){const previousManifest=JSON.stringify(createRuntimeBindingManifest(asset.bindingManifest,runtimeBindingManifest));updateManifest(asset.bindingManifest);const nextManifest=JSON.stringify(createRuntimeBindingManifest(asset.bindingManifest,runtimeBindingManifest));asset.script=asset.script.replace(previousManifest,nextManifest)}}function compileTemplatePhase(descriptor,filename,source,templateResolvedId,options,result,bindingManifestSourceFile){if(!descriptor.template)return;const templateCompiled=compileVueTemplateToWxml(descriptor.template.content,filename,options);const manifestSourceFile=descriptor.template.src||bindingManifestSourceFile||templateResolvedId||filename;const runtimeBindingManifest=options?.runtimeBindingManifest??`compact`;if(descriptor.template.src)updateTemplateBindingManifests(templateCompiled,manifestSourceFile,void 0,runtimeBindingManifest);else{const base=descriptor.template.loc.start;const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);updateTemplateBindingManifests(templateCompiled,manifestSourceFile,position=>{const line=base.line+position.line-1;const column=position.line===1?base.column+position.column-1:position.column;return{offset:Math.min(source.length,(lineStarts[line-1]??base.offset+position.offset)+column-1),line,column}},runtimeBindingManifest)}result.bindingManifest=templateCompiled.bindingManifest;result.template=templateCompiled.code;const located=[...templateCompiled.diagnostics,...templateCompiled.sourceTags??[]];if(located.length){if(descriptor.template.src){if(templateResolvedId)ownExternalTemplateDiagnostics(located,templateResolvedId,descriptor.template.content);else for(const diagnostic of located)diagnostic.loc=void 0}else remapTemplateDiagnostics(located,descriptor.template.loc.start,source)}result.meta??={};result.meta.templateTags=templateCompiled.sourceTags;if(templateCompiled.diagnostics.length)result.diagnostics=templateCompiled.diagnostics;if(templateCompiled.scopedSlotComponents?.length)result.scopedSlotComponents=templateCompiled.scopedSlotComponents;if(templateCompiled.slotFallbackWrapperComponent)result.slotFallbackWrapperComponent=templateCompiled.slotFallbackWrapperComponent;if(templateCompiled.componentGenerics&&Object.keys(templateCompiled.componentGenerics).length)result.componentGenerics=templateCompiled.componentGenerics;if(templateCompiled.classStyleWxs)result.classStyleWxs=true;return templateCompiled}function createTemplateRegistrationSignature(descriptor,compiledTemplate){const serialize=block=>block&&{attrs:Object.fromEntries(Object.entries(block.attrs).sort(([a],[b])=>a.localeCompare(b))),content:block.content,type:block.type};return createHash(`sha256`).update(JSON.stringify([serialize(descriptor.template),descriptor.customBlocks.filter(block=>block.type!==`json`&&block.type!==`config`).map(serialize),compiledTemplate])).digest(`hex`)}async function refreshVueFileJsonConfig(source,filename,cachedResult,options){const jsonConfigCache=cachedResult.meta?.jsonConfigCache;if(!jsonConfigCache)return;const parsed=await parseVueFile(source,filename,options);const meta={...cachedResult.meta,routeConfig:parsed.meta.routeConfig,pageMeta:parsed.meta.pageMeta,hasScriptSetup:parsed.meta.hasScriptSetup,hasSetupOption:parsed.meta.hasSetupOption,sfcSrcDeps:parsed.meta.sfcSrcDeps,sfcSrcCompilationDeps:parsed.meta.sfcSrcCompilationDeps};const result={...cachedResult,meta};delete result.config;await compileConfigPhase({descriptor:parsed.descriptor,filename,autoUsingComponentsMap:{...jsonConfigCache.autoUsingComponentsMap},autoImportTagsMap:jsonConfigCache.autoImportTagsMap?{...jsonConfigCache.autoImportTagsMap}:void 0,autoUsingComponents:options?.autoUsingComponents,autoImportTags:options?.autoImportTags,jsonDefaults:parsed.jsonDefaults,mergeJson:parsed.mergeJson,scriptSetupMacroConfig:parsed.scriptSetupMacroConfig,result,warn:options?.warn});if(parsed.scriptSetupMacroHash)meta.jsonMacroHash=parsed.scriptSetupMacroHash;else delete meta.jsonMacroHash;return result}async function compileVueFile(source,filename,options){const parsed=await parseVueFile(source,filename,options);const sfcId=generateScopedId(filename);const result={meta:{...parsed.meta,styleBlocks:parsed.descriptor.styles,cssVars:parsed.descriptor.cssVars}};const autoUsingComponents=options?.autoUsingComponents?.enabled&&(parsed.descriptor.scriptSetup||parsed.descriptor.script)&&parsed.descriptor.template&&options.autoUsingComponents.resolveUsingComponentPath?options.autoUsingComponents:void 0;const autoImportTags=options?.autoImportTags?.enabled&&parsed.descriptor.template&&options.autoImportTags.resolveUsingComponent?options.autoImportTags:void 0;const componentSourceInfo=await collectComponentSourceInfo({descriptor:parsed.descriptor,descriptorForCompile:parsed.descriptorForCompile,filename,compileOptions:options,autoUsingComponents,autoImportTags,nativeScriptAnalysis:parsed.nativeScriptAnalysis});if(!parsed.isAppFile&&usesNativeDeclarationContext({platform:options?.template?.platform??getMiniProgramTemplatePlatform(),scopedSlotsRequireProps:options?.template?.scopedSlotsRequireProps??options?.template?.scopedSlotsCompiler!==`augmented`,nativeSlotContext:options?.template?.nativeSlotContext===true})){const participation=await analyzeNativeSlotContext({descriptor:parsed.descriptor,filename,options,components:componentSourceInfo});options={...options,template:{...options?.template,nativeSlotContext:participation.required,nativeSlotContextTags:participation.tags}};result.meta.nativeSlotContextDeps=participation.dependencies}const scriptCompiled=parsed.descriptor.script||parsed.descriptor.scriptSetup?compileScript(parsed.descriptorForCompile,{id:sfcId,isProd:false}):void 0;let compiledScriptAst;const getCompiledScriptAst=()=>compiledScriptAst??=parseJsLike(scriptCompiled.content);const propsAliases=scriptCompiled?resolveScriptSetupPropsAliases(scriptCompiled.bindings):void 0;const propsDerivedKeys=scriptCompiled?resolveEffectivePropsDerivedKeys(scriptCompiled.bindings,scriptCompiled.content,getCompiledScriptAst):void 0;const propsAnalysis=scriptCompiled?await resolveSetupPropConflicts({script:scriptCompiled.content,bindings:scriptCompiled.bindings,getScriptAst:getCompiledScriptAst,filename,source:options?.sfcSrc}):void 0;const scriptSetupPropConflicts=propsAnalysis?.conflicts;if(propsAnalysis?.dependencies.length)result.meta.propsAnalysisDeps=propsAnalysis.dependencies;const styleCompiled=await compileStylePhase(parsed.descriptor,filename,result,options?.style);const hasCssVarsRuntime=parsed.descriptor.cssVars.length>0||options?.stabilizeCssVarsRuntime===true;const scopedId=parsed.descriptor.styles.some(style=>style.scoped)?`data-v-${sfcId}`:void 0;const baseTemplateOptions=parsed.isAppFile?{...options?.template,isPage:options?.isPage,runtimeBindingManifest:options?.runtimeBindingManifest,propsAliases,propsDerivedKeys,scriptSetupBindings:scriptCompiled?.bindings,scriptSetupPropConflicts,scopedSlotsRequireProps:true,scopeId:scopedId,slottedScopeId:scopedId&&styleCompiled.usesSlotted?`${scopedId}-s`:void 0,cssVars:hasCssVarsRuntime}:{...options?.template,isPage:options?.isPage,runtimeBindingManifest:options?.runtimeBindingManifest,propsAliases,propsDerivedKeys,scriptSetupBindings:scriptCompiled?.bindings,scriptSetupPropConflicts,scopeId:scopedId,slottedScopeId:scopedId&&styleCompiled.usesSlotted?`${scopedId}-s`:void 0,cssVars:hasCssVarsRuntime};const templateOptions=componentSourceInfo.wevuComponentTags.size?{...baseTemplateOptions,wevuComponentTags:componentSourceInfo.wevuComponentTags,componentNameMap:componentSourceInfo.componentNameMap,miniProgramComponentTags:componentSourceInfo.miniProgramComponentTags}:{...baseTemplateOptions,wevuComponentTags:[],componentNameMap:componentSourceInfo.componentNameMap,miniProgramComponentTags:componentSourceInfo.miniProgramComponentTags};const templateCompiled=compileTemplatePhase(parsed.descriptor,filename,source,parsed.templateResolvedId,templateOptions,result,options?.bindingManifestSourceFile);if(templateCompiled?.diagnostics.length){let fatalDiagnostic;for(const diagnostic of templateCompiled.diagnostics){options?.warn?.(diagnostic.message);if(diagnostic.severity===`error`)fatalDiagnostic??=diagnostic}if(fatalDiagnostic)throw new CompilerDiagnosticError(fatalDiagnostic)}if(templateCompiled&&result.template&&(options?.pageLayout||options?.appShell)){result.template=applyCompilerTemplateWrappers({template:result.template,manifest:templateCompiled.bindingManifest,platform:templateOptions.platform??getMiniProgramTemplatePlatform(),pageLayout:options.pageLayout,appShell:options.appShell});templateCompiled.code=result.template;templateCompiled.runtimeCapabilities=createWevuRuntimeCapabilityMetadataFromBindingManifest(templateCompiled.bindingManifest)}const deferInitialRender=options?.setupInitialRenderBarrier!==false&&!parsed.isAppFile&&!isNativeDomCompilation(options)&&templateCompiled&&guardInitialSetupRender(templateCompiled,scriptCompiled?.bindings);const scriptPhase=await compileScriptPhase(parsed.descriptor,parsed.descriptorForCompile,filename,options,autoUsingComponents,templateCompiled,parsed.isAppFile,componentSourceInfo,scriptCompiled,{propsAliases,propsDerivedKeys,cssModules:result.cssModules},source,parsed.scriptPreprocessMap,parsed.nativeScriptAnalysis);result.script=scriptPhase.script;result.scriptMap=scriptPhase.scriptMap;if(scriptPhase.componentStyleOptions)result.meta.componentStyleOptions=scriptPhase.componentStyleOptions;if(scriptPhase.runtimeCapabilities)result.meta.runtimeCapabilities=scriptPhase.runtimeCapabilities;if(scriptPhase.template)result.template=scriptPhase.template;if(scriptPhase.bindingManifest)result.bindingManifest=scriptPhase.bindingManifest;if(scriptPhase.diagnostics?.length)result.diagnostics=[...result.diagnostics??[],...scriptPhase.diagnostics];await compileConfigPhase({descriptor:parsed.descriptor,filename,autoUsingComponentsMap:scriptPhase.autoUsingComponentsMap,autoImportTagsMap:componentSourceInfo.autoImportTagsMap,autoUsingComponents,autoImportTags,jsonDefaults:parsed.jsonDefaults,mergeJson:parsed.mergeJson,scriptSetupMacroConfig:parsed.scriptSetupMacroConfig,result,warn:options?.warn});result.config=mergeCompilerLayoutUsingComponents(result.config,options?.pageLayout,options?.appShell);result.meta.jsonConfigCache={autoUsingComponentsMap:{...scriptPhase.autoUsingComponentsMap},autoImportTagsMap:componentSourceInfo.autoImportTagsMap?{...componentSourceInfo.autoImportTagsMap}:void 0};finalizeResult(result,{scriptSetupMacroHash:parsed.scriptSetupMacroHash,defineOptionsHash:parsed.defineOptionsHash});if(!parsed.isAppFile&&isNativeDomCompilation(options)&&options?.isPage&&result.template)result.template=`<block tt:if="{{${WEVU_LEGACY_RENDERER_KEY}}}">${result.template}</block>`;if(deferInitialRender&&result.template){const platform=templateOptions.platform??getMiniProgramTemplatePlatform();result.template=wrapInitialSetupTemplate(result.template,platform)}result.meta.templateRegistrationSignature=createTemplateRegistrationSignature(parsed.descriptor,result.template);return result}export{CLASS_STYLE_WXS_FILE,CLASS_STYLE_WXS_MODULE,CompilerDiagnosticError,RESERVED_VUE_COMPONENT_TAGS,VUE_COMPONENT_TAG_RE,VUE_SFC_BLOCK_TYPES,WE_VU_COMPILER_REACTIVITY_MODULE_ID,WE_VU_COMPILER_RUNTIME_MODULE_ID,WE_VU_COMPILER_TEMPLATE_MODULE_ID,WE_VU_INTERNAL_REACTIVITY_APIS,WE_VU_INTERNAL_REACTIVITY_MODULE_ID,WE_VU_INTERNAL_RUNTIME_MODULE_ID,WE_VU_INTERNAL_TEMPLATE_APIS,WE_VU_INTERNAL_TEMPLATE_MODULE_ID,WE_VU_MODULE_ID,WE_VU_PAGE_HOOK_TO_FEATURE,WE_VU_RUNTIME_APIS,WE_VU_RUNTIME_MODULE_IDS,alipayPlatform,buildClassStyleComputedCode,buildClassStyleWxsTag,builtinComponentsSet,classifyVueSfcBlockChanges,clearFileCaches,collectPageMetaCallsFromPrograms,collectTargetOptionsObjectsFromCode,collectVueTemplateTags,collectWevuFeaturesFromCodeReachableImports,collectWevuPageFeatureFlags,collectWevuPageFeatureFlagsFromCode,compileConfigBlocks,compileJsxFile,compileVueFile as compileSfc,compileVueFile,compileVueStyleToWxss as compileStyle,compileVueStyleToWxss,compileVueTemplateToWxml as compileTemplate,compileVueTemplateToWxml,createBaseLibraryHintState,createJsonMerger,createPageEntryMatcher,createRuntimeBindingManifest,defaultMiniProgramPlatform,defaultMiniProgramTemplatePlatform,defaultPlatform,evaluateJsLikeConfig,extractJsonMacroFromScriptSetup,extractPageDeclaration,extractPageDeclarationWithDependencies,generateScopedId,getClassStyleWxsSource,getDefaultMiniProgramPlatform,getDefaultMiniProgramTemplatePlatform,getMiniProgramTemplatePlatform,getSfcCheckMtime,injectWevuPageFeatureFlagsIntoOptionsObject,injectWevuPageFeaturesInJs,injectWevuPageFeaturesInJsWithResolver,invalidateFileCache,isAutoImportCandidateTag,isBuiltinComponent,isInvalidate,isJsonLikeLang,isUniAppCompatibilityFile,isWevuPageFeatureModuleId,isWevuRuntimeModuleId,loadCache,mayContainJsonMacro,mayContainPageDeclaration,mayContainPageMeta,mergeJsonWithStrategy,mtimeCache,normalizeConfigLang,parseVueSfc,pathExists,preprocessScriptSetupSrc,preprocessScriptSrc,readAndParseSfc,readFile,refreshVueFileJsonConfig,resolveClassStyleWxsLocation,resolveJsLikeLang,resolveSfcBlockSrc,resolveVueSfcHasTemplate,resolveVueSfcHmrSignatures,resolveVueSfcNonJsonSignature,resolveVueSfcScriptSignature,resolveVueSfcStyleIndependentSignature,resolveVueSfcTailwindContentSignature,resolveWevuInternalImportModuleId,restoreScriptSetupSrc,restoreScriptSrc,stripJsonMacroCallsFromCode,stripPageDeclaration,swanPlatform,transformNestedWxssVars,transformScript,transformScript as transformSfcScript,transformUniAppConditionalCode,transformUniAppSource,transformVueDeepSelectors,ttPlatform,wechatPlatform};
42
+ `);if(!compiledStyles.some(s=>s.modules))return{usesSlotted:compiledStyles.some(style=>style.usesSlotted)};const modulesMap={};compiledStyles.forEach(compiled=>{if(compiled.modules)Object.assign(modulesMap,compiled.modules)});result.cssModules=modulesMap;return{usesSlotted:compiledStyles.some(style=>style.usesSlotted)}}function remapTemplateDiagnostics(diagnostics,base,source){const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);const remap=position=>{const line=base.line+position.line-1;const column=position.line===1?base.column+position.column-1:position.column;return{offset:Math.min(source.length,(lineStarts[line-1]??base.offset+position.offset)+column-1),line,column}};for(const diagnostic of diagnostics)if(diagnostic.loc)diagnostic.loc={start:remap(diagnostic.loc.start),end:remap(diagnostic.loc.end)}}function ownExternalTemplateDiagnostics(diagnostics,filename,source){const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);const own=position=>{let low=0;let high=lineStarts.length;while(low+1<high){const middle=low+high>>1;if(lineStarts[middle]<=position.offset)low=middle;else high=middle}const line=low+1;return{offset:position.offset,line,column:position.offset-lineStarts[line-1]+1}};for(const diagnostic of diagnostics){diagnostic.filename=filename;if(diagnostic.loc)diagnostic.loc={start:own(diagnostic.loc.start),end:own(diagnostic.loc.end)}}}function updateTemplateBindingManifests(templateCompiled,sourceFile,remap,runtimeBindingManifest){const updateManifest=manifest=>{manifest.sourceFile=sourceFile;if(!remap)return;for(const binding of manifest.bindings)if(binding.sourceLocation)binding.sourceLocation={start:remap(binding.sourceLocation.start),end:remap(binding.sourceLocation.end)}};updateManifest(templateCompiled.bindingManifest);for(const asset of templateCompiled.scopedSlotComponents??[]){const previousManifest=JSON.stringify(createRuntimeBindingManifest(asset.bindingManifest,runtimeBindingManifest));updateManifest(asset.bindingManifest);const nextManifest=JSON.stringify(createRuntimeBindingManifest(asset.bindingManifest,runtimeBindingManifest));asset.script=asset.script.replace(previousManifest,nextManifest)}}function compileTemplatePhase(descriptor,filename,source,templateResolvedId,options,result,bindingManifestSourceFile){if(!descriptor.template)return;const templateCompiled=compileVueTemplateToWxml(descriptor.template.content,filename,options);const manifestSourceFile=descriptor.template.src||bindingManifestSourceFile||templateResolvedId||filename;const runtimeBindingManifest=options?.runtimeBindingManifest??`compact`;if(descriptor.template.src)updateTemplateBindingManifests(templateCompiled,manifestSourceFile,void 0,runtimeBindingManifest);else{const base=descriptor.template.loc.start;const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);updateTemplateBindingManifests(templateCompiled,manifestSourceFile,position=>{const line=base.line+position.line-1;const column=position.line===1?base.column+position.column-1:position.column;return{offset:Math.min(source.length,(lineStarts[line-1]??base.offset+position.offset)+column-1),line,column}},runtimeBindingManifest)}result.bindingManifest=templateCompiled.bindingManifest;result.template=templateCompiled.code;const located=[...templateCompiled.diagnostics,...templateCompiled.sourceTags??[]];if(located.length){if(descriptor.template.src){if(templateResolvedId)ownExternalTemplateDiagnostics(located,templateResolvedId,descriptor.template.content);else for(const diagnostic of located)diagnostic.loc=void 0}else remapTemplateDiagnostics(located,descriptor.template.loc.start,source)}result.meta??={};result.meta.templateTags=templateCompiled.sourceTags;if(templateCompiled.diagnostics.length)result.diagnostics=templateCompiled.diagnostics;if(templateCompiled.scopedSlotComponents?.length)result.scopedSlotComponents=templateCompiled.scopedSlotComponents;if(templateCompiled.slotFallbackWrapperComponent)result.slotFallbackWrapperComponent=templateCompiled.slotFallbackWrapperComponent;if(templateCompiled.componentGenerics&&Object.keys(templateCompiled.componentGenerics).length)result.componentGenerics=templateCompiled.componentGenerics;if(templateCompiled.classStyleWxs)result.classStyleWxs=true;return templateCompiled}function createTemplateRegistrationSignature(descriptor,compiledTemplate){const serialize=block=>block&&{attrs:Object.fromEntries(Object.entries(block.attrs).sort(([a],[b])=>a.localeCompare(b))),content:block.content,type:block.type};return createHash(`sha256`).update(JSON.stringify([serialize(descriptor.template),descriptor.customBlocks.filter(block=>block.type!==`json`&&block.type!==`config`).map(serialize),compiledTemplate])).digest(`hex`)}async function refreshVueFileJsonConfig(source,filename,cachedResult,options){const jsonConfigCache=cachedResult.meta?.jsonConfigCache;if(!jsonConfigCache)return;const parsed=await parseVueFile(source,filename,options);const meta={...cachedResult.meta,routeConfig:parsed.meta.routeConfig,pageMeta:parsed.meta.pageMeta,hasScriptSetup:parsed.meta.hasScriptSetup,hasSetupOption:parsed.meta.hasSetupOption,sfcSrcDeps:parsed.meta.sfcSrcDeps,sfcSrcCompilationDeps:parsed.meta.sfcSrcCompilationDeps};const result={...cachedResult,meta};delete result.config;await compileConfigPhase({descriptor:parsed.descriptor,filename,autoUsingComponentsMap:{...jsonConfigCache.autoUsingComponentsMap},autoImportTagsMap:jsonConfigCache.autoImportTagsMap?{...jsonConfigCache.autoImportTagsMap}:void 0,autoUsingComponents:options?.autoUsingComponents,autoImportTags:options?.autoImportTags,jsonDefaults:parsed.jsonDefaults,mergeJson:parsed.mergeJson,scriptSetupMacroConfig:parsed.scriptSetupMacroConfig,result,warn:options?.warn});if(parsed.scriptSetupMacroHash)meta.jsonMacroHash=parsed.scriptSetupMacroHash;else delete meta.jsonMacroHash;return result}async function compileVueFile(source,filename,options){const parsed=await withCompilerPhase(`parse`,()=>parseVueFile(source,filename,options));const sfcId=generateScopedId(filename);const result={meta:{...parsed.meta,styleBlocks:parsed.descriptor.styles,cssVars:parsed.descriptor.cssVars}};const autoUsingComponents=options?.autoUsingComponents?.enabled&&(parsed.descriptor.scriptSetup||parsed.descriptor.script)&&parsed.descriptor.template&&options.autoUsingComponents.resolveUsingComponentPath?options.autoUsingComponents:void 0;const autoImportTags=options?.autoImportTags?.enabled&&parsed.descriptor.template&&options.autoImportTags.resolveUsingComponent?options.autoImportTags:void 0;const componentSourceInfo=await withCompilerPhase(`componentSource`,()=>collectComponentSourceInfo({descriptor:parsed.descriptor,descriptorForCompile:parsed.descriptorForCompile,filename,compileOptions:options,autoUsingComponents,autoImportTags,nativeScriptAnalysis:parsed.nativeScriptAnalysis}));if(!parsed.isAppFile&&usesNativeDeclarationContext({platform:options?.template?.platform??getMiniProgramTemplatePlatform(),scopedSlotsRequireProps:options?.template?.scopedSlotsRequireProps??options?.template?.scopedSlotsCompiler!==`augmented`,nativeSlotContext:options?.template?.nativeSlotContext===true})){const participation=await withCompilerPhase(`nativeSlotContext`,()=>analyzeNativeSlotContext({descriptor:parsed.descriptor,filename,options,components:componentSourceInfo}));options={...options,template:{...options?.template,nativeSlotContext:participation.required,nativeSlotContextTags:participation.tags}};result.meta.nativeSlotContextDeps=participation.dependencies}const scriptCompiled=parsed.descriptor.script||parsed.descriptor.scriptSetup?withCompilerPhase(`compileScriptSfc`,()=>compileScript(parsed.descriptorForCompile,{id:sfcId,isProd:false})):void 0;let compiledScriptAst;const getCompiledScriptAst=()=>compiledScriptAst??=parseJsLike(scriptCompiled.content);const propsAliases=scriptCompiled?resolveScriptSetupPropsAliases(scriptCompiled.bindings):void 0;const propsDerivedKeys=scriptCompiled?resolveEffectivePropsDerivedKeys(scriptCompiled.bindings,scriptCompiled.content,getCompiledScriptAst):void 0;const propsAnalysis=scriptCompiled?await withCompilerPhase(`scriptPreparation`,()=>resolveSetupPropConflicts({script:scriptCompiled.content,bindings:scriptCompiled.bindings,getScriptAst:getCompiledScriptAst,filename,source:options?.sfcSrc})):void 0;const scriptSetupPropConflicts=propsAnalysis?.conflicts;if(propsAnalysis?.dependencies.length)result.meta.propsAnalysisDeps=propsAnalysis.dependencies;const styleCompiled=await withCompilerPhase(`style`,()=>compileStylePhase(parsed.descriptor,filename,result,options?.style));const hasCssVarsRuntime=parsed.descriptor.cssVars.length>0||options?.stabilizeCssVarsRuntime===true;const scopedId=parsed.descriptor.styles.some(style=>style.scoped)?`data-v-${sfcId}`:void 0;const baseTemplateOptions=parsed.isAppFile?{...options?.template,isPage:options?.isPage,runtimeBindingManifest:options?.runtimeBindingManifest,propsAliases,propsDerivedKeys,scriptSetupBindings:scriptCompiled?.bindings,scriptSetupPropConflicts,scopedSlotsRequireProps:true,scopeId:scopedId,slottedScopeId:scopedId&&styleCompiled.usesSlotted?`${scopedId}-s`:void 0,cssVars:hasCssVarsRuntime}:{...options?.template,isPage:options?.isPage,runtimeBindingManifest:options?.runtimeBindingManifest,propsAliases,propsDerivedKeys,scriptSetupBindings:scriptCompiled?.bindings,scriptSetupPropConflicts,scopeId:scopedId,slottedScopeId:scopedId&&styleCompiled.usesSlotted?`${scopedId}-s`:void 0,cssVars:hasCssVarsRuntime};const templateOptions=componentSourceInfo.wevuComponentTags.size?{...baseTemplateOptions,wevuComponentTags:componentSourceInfo.wevuComponentTags,componentNameMap:componentSourceInfo.componentNameMap,miniProgramComponentTags:componentSourceInfo.miniProgramComponentTags}:{...baseTemplateOptions,wevuComponentTags:[],componentNameMap:componentSourceInfo.componentNameMap,miniProgramComponentTags:componentSourceInfo.miniProgramComponentTags};const templateCompiled=withCompilerPhase(`template`,()=>compileTemplatePhase(parsed.descriptor,filename,source,parsed.templateResolvedId,templateOptions,result,options?.bindingManifestSourceFile));if(templateCompiled?.diagnostics.length){let fatalDiagnostic;for(const diagnostic of templateCompiled.diagnostics){options?.warn?.(diagnostic.message);if(diagnostic.severity===`error`)fatalDiagnostic??=diagnostic}if(fatalDiagnostic)throw new CompilerDiagnosticError(fatalDiagnostic)}if(templateCompiled&&result.template&&(options?.pageLayout||options?.appShell)){result.template=applyCompilerTemplateWrappers({template:result.template,manifest:templateCompiled.bindingManifest,platform:templateOptions.platform??getMiniProgramTemplatePlatform(),pageLayout:options.pageLayout,appShell:options.appShell});templateCompiled.code=result.template;templateCompiled.runtimeCapabilities=createWevuRuntimeCapabilityMetadataFromBindingManifest(templateCompiled.bindingManifest)}const deferInitialRender=options?.setupInitialRenderBarrier!==false&&!parsed.isAppFile&&!isNativeDomCompilation(options)&&templateCompiled&&guardInitialSetupRender(templateCompiled,scriptCompiled?.bindings);const scriptPhase=await withCompilerPhase(`script`,()=>compileScriptPhase(parsed.descriptor,parsed.descriptorForCompile,filename,options,autoUsingComponents,templateCompiled,parsed.isAppFile,componentSourceInfo,scriptCompiled,{propsAliases,propsDerivedKeys,cssModules:result.cssModules},source,parsed.scriptPreprocessMap,parsed.nativeScriptAnalysis));result.script=scriptPhase.script;result.scriptMap=scriptPhase.scriptMap;if(scriptPhase.componentStyleOptions)result.meta.componentStyleOptions=scriptPhase.componentStyleOptions;if(scriptPhase.runtimeCapabilities)result.meta.runtimeCapabilities=scriptPhase.runtimeCapabilities;if(scriptPhase.template)result.template=scriptPhase.template;if(scriptPhase.bindingManifest)result.bindingManifest=scriptPhase.bindingManifest;if(scriptPhase.diagnostics?.length)result.diagnostics=[...result.diagnostics??[],...scriptPhase.diagnostics];await withCompilerPhase(`config`,()=>compileConfigPhase({descriptor:parsed.descriptor,filename,autoUsingComponentsMap:scriptPhase.autoUsingComponentsMap,autoImportTagsMap:componentSourceInfo.autoImportTagsMap,autoUsingComponents,autoImportTags,jsonDefaults:parsed.jsonDefaults,mergeJson:parsed.mergeJson,scriptSetupMacroConfig:parsed.scriptSetupMacroConfig,result,warn:options?.warn}));result.config=mergeCompilerLayoutUsingComponents(result.config,options?.pageLayout,options?.appShell);result.meta.jsonConfigCache={autoUsingComponentsMap:{...scriptPhase.autoUsingComponentsMap},autoImportTagsMap:componentSourceInfo.autoImportTagsMap?{...componentSourceInfo.autoImportTagsMap}:void 0};withCompilerPhase(`finalize`,()=>finalizeResult(result,{scriptSetupMacroHash:parsed.scriptSetupMacroHash,defineOptionsHash:parsed.defineOptionsHash}));if(!parsed.isAppFile&&isNativeDomCompilation(options)&&options?.isPage&&result.template)result.template=`<block tt:if="{{${WEVU_LEGACY_RENDERER_KEY}}}">${result.template}</block>`;if(deferInitialRender&&result.template){const platform=templateOptions.platform??getMiniProgramTemplatePlatform();result.template=wrapInitialSetupTemplate(result.template,platform)}result.meta.templateRegistrationSignature=createTemplateRegistrationSignature(parsed.descriptor,result.template);return result}export{CLASS_STYLE_WXS_FILE,CLASS_STYLE_WXS_MODULE,CompilerDiagnosticError,RESERVED_VUE_COMPONENT_TAGS,VUE_COMPONENT_TAG_RE,VUE_SFC_BLOCK_TYPES,WE_VU_COMPILER_REACTIVITY_MODULE_ID,WE_VU_COMPILER_RUNTIME_MODULE_ID,WE_VU_COMPILER_TEMPLATE_MODULE_ID,WE_VU_INTERNAL_REACTIVITY_APIS,WE_VU_INTERNAL_REACTIVITY_MODULE_ID,WE_VU_INTERNAL_RUNTIME_MODULE_ID,WE_VU_INTERNAL_TEMPLATE_APIS,WE_VU_INTERNAL_TEMPLATE_MODULE_ID,WE_VU_MODULE_ID,WE_VU_PAGE_HOOK_TO_FEATURE,WE_VU_RUNTIME_APIS,WE_VU_RUNTIME_MODULE_IDS,alipayPlatform,buildClassStyleComputedCode,buildClassStyleWxsTag,builtinComponentsSet,classifyVueSfcBlockChanges,clearFileCaches,collectPageMetaCallsFromPrograms,collectTargetOptionsObjectsFromCode,collectVueTemplateTags,collectWevuFeaturesFromCodeReachableImports,collectWevuPageFeatureFlags,collectWevuPageFeatureFlagsFromCode,compileConfigBlocks,compileJsxFile,compileVueFile as compileSfc,compileVueFile,compileVueStyleToWxss as compileStyle,compileVueStyleToWxss,compileVueTemplateToWxml as compileTemplate,compileVueTemplateToWxml,createBaseLibraryHintState,createJsonMerger,createPageEntryMatcher,createRuntimeBindingManifest,defaultMiniProgramPlatform,defaultMiniProgramTemplatePlatform,defaultPlatform,evaluateJsLikeConfig,extractJsonMacroFromScriptSetup,extractPageDeclaration,extractPageDeclarationWithDependencies,generateScopedId,getClassStyleWxsSource,getDefaultMiniProgramPlatform,getDefaultMiniProgramTemplatePlatform,getMiniProgramTemplatePlatform,getSfcCheckMtime,injectWevuPageFeatureFlagsIntoOptionsObject,injectWevuPageFeaturesInJs,injectWevuPageFeaturesInJsWithResolver,invalidateFileCache,isAutoImportCandidateTag,isBuiltinComponent,isInvalidate,isJsonLikeLang,isUniAppCompatibilityFile,isWevuPageFeatureModuleId,isWevuRuntimeModuleId,loadCache,mayContainJsonMacro,mayContainPageDeclaration,mayContainPageMeta,mergeJsonWithStrategy,mtimeCache,normalizeConfigLang,parseVueSfc,pathExists,preprocessScriptSetupSrc,preprocessScriptSrc,readAndParseSfc,readFile,refreshVueFileJsonConfig,resolveClassStyleWxsLocation,resolveJsLikeLang,resolveSfcBlockSrc,resolveVueSfcHasTemplate,resolveVueSfcHmrSignatures,resolveVueSfcNonJsonSignature,resolveVueSfcScriptSignature,resolveVueSfcStyleIndependentSignature,resolveVueSfcTailwindContentSignature,resolveWevuInternalImportModuleId,restoreScriptSetupSrc,restoreScriptSrc,stripJsonMacroCallsFromCode,stripPageDeclaration,swanPlatform,transformNestedWxssVars,transformScript,transformScript as transformSfcScript,transformUniAppConditionalCode,transformUniAppSource,transformVueDeepSelectors,ttPlatform,wechatPlatform};