@djvlc/runtime-web 1.0.3 → 1.0.5

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.
@@ -1 +1 @@
1
- var DJVRuntime=function(e){"use strict";var t=(e=>(e[e.UNKNOWN=1e3]="UNKNOWN",e[e.INVALID_REQUEST=1001]="INVALID_REQUEST",e[e.UNAUTHORIZED=1002]="UNAUTHORIZED",e[e.FORBIDDEN=1003]="FORBIDDEN",e[e.NOT_FOUND=1004]="NOT_FOUND",e[e.RATE_LIMITED=1005]="RATE_LIMITED",e[e.VALIDATION_ERROR=1006]="VALIDATION_ERROR",e[e.INTERNAL_ERROR=1007]="INTERNAL_ERROR",e[e.SERVICE_UNAVAILABLE=1008]="SERVICE_UNAVAILABLE",e[e.TIMEOUT=1009]="TIMEOUT",e[e.ACTION_NOT_FOUND=2001]="ACTION_NOT_FOUND",e[e.ACTION_INVALID_PARAMS=2002]="ACTION_INVALID_PARAMS",e[e.ACTION_EXECUTION_FAILED=2003]="ACTION_EXECUTION_FAILED",e[e.ACTION_IDEMPOTENCY_CONFLICT=2004]="ACTION_IDEMPOTENCY_CONFLICT",e[e.ACTION_BLOCKED=2005]="ACTION_BLOCKED",e[e.ACTION_RISK_REJECTED=2006]="ACTION_RISK_REJECTED",e[e.ACTION_EXPIRED=2007]="ACTION_EXPIRED",e[e.ACTION_QUOTA_EXCEEDED=2008]="ACTION_QUOTA_EXCEEDED",e[e.QUERY_NOT_FOUND=3001]="QUERY_NOT_FOUND",e[e.QUERY_INVALID_PARAMS=3002]="QUERY_INVALID_PARAMS",e[e.QUERY_EXECUTION_FAILED=3003]="QUERY_EXECUTION_FAILED",e[e.QUERY_FIELD_NOT_ALLOWED=3004]="QUERY_FIELD_NOT_ALLOWED",e[e.QUERY_TIMEOUT=3005]="QUERY_TIMEOUT",e[e.QUERY_DISABLED=3006]="QUERY_DISABLED",e[e.COMPONENT_NOT_FOUND=4001]="COMPONENT_NOT_FOUND",e[e.COMPONENT_VERSION_NOT_FOUND=4002]="COMPONENT_VERSION_NOT_FOUND",e[e.COMPONENT_BLOCKED=4003]="COMPONENT_BLOCKED",e[e.COMPONENT_INTEGRITY_MISMATCH=4004]="COMPONENT_INTEGRITY_MISMATCH",e[e.COMPONENT_INCOMPATIBLE=4005]="COMPONENT_INCOMPATIBLE",e[e.COMPONENT_LOAD_FAILED=4006]="COMPONENT_LOAD_FAILED",e[e.COMPONENT_RENDER_ERROR=4007]="COMPONENT_RENDER_ERROR",e[e.PAGE_NOT_FOUND=5001]="PAGE_NOT_FOUND",e[e.PAGE_VERSION_NOT_FOUND=5002]="PAGE_VERSION_NOT_FOUND",e[e.PAGE_SCHEMA_INVALID=5003]="PAGE_SCHEMA_INVALID",e[e.PAGE_MANIFEST_INVALID=5004]="PAGE_MANIFEST_INVALID",e[e.PAGE_PUBLISH_FAILED=5005]="PAGE_PUBLISH_FAILED",e[e.PAGE_ROLLBACK_FAILED=5006]="PAGE_ROLLBACK_FAILED",e[e.ACTIVITY_NOT_FOUND=6001]="ACTIVITY_NOT_FOUND",e[e.ACTIVITY_NOT_STARTED=6002]="ACTIVITY_NOT_STARTED",e[e.ACTIVITY_ENDED=6003]="ACTIVITY_ENDED",e[e.ACTIVITY_ALREADY_CLAIMED=6004]="ACTIVITY_ALREADY_CLAIMED",e[e.ACTIVITY_ALREADY_SIGNED=6005]="ACTIVITY_ALREADY_SIGNED",e[e.ACTIVITY_LIMIT_EXCEEDED=6006]="ACTIVITY_LIMIT_EXCEEDED",e[e.ACTIVITY_DISABLED=6007]="ACTIVITY_DISABLED",e[e.EXPRESSION_SYNTAX_ERROR=7001]="EXPRESSION_SYNTAX_ERROR",e[e.EXPRESSION_UNKNOWN_FUNCTION=7002]="EXPRESSION_UNKNOWN_FUNCTION",e[e.EXPRESSION_INVALID_ARGUMENT=7003]="EXPRESSION_INVALID_ARGUMENT",e[e.EXPRESSION_UNKNOWN_VARIABLE=7004]="EXPRESSION_UNKNOWN_VARIABLE",e[e.EXPRESSION_TYPE_MISMATCH=7005]="EXPRESSION_TYPE_MISMATCH",e[e.EXPRESSION_ACCESS_DENIED=7006]="EXPRESSION_ACCESS_DENIED",e[e.SCHEMA_VERSION_MISMATCH=8001]="SCHEMA_VERSION_MISMATCH",e[e.MIGRATION_FAILED=8002]="MIGRATION_FAILED",e[e.MIGRATION_NOT_FOUND=8003]="MIGRATION_NOT_FOUND",e[e.VERSION_INCOMPATIBLE=8004]="VERSION_INCOMPATIBLE",e))(t||{}),r={1e3:"未知错误",1001:"请求参数无效",1002:"未授权访问",1003:"禁止访问",1004:"资源不存在",1005:"请求频率超限",1006:"数据校验失败",1007:"服务内部错误",1008:"服务暂不可用",1009:"请求超时",2001:"动作不存在",2002:"动作参数无效",2003:"动作执行失败",2004:"重复请求",2005:"动作已被禁用",2006:"风控拒绝",2007:"动作已过期",2008:"配额已用尽",3001:"查询不存在",3002:"查询参数无效",3003:"查询执行失败",3004:"字段访问被拒绝",3005:"查询超时",3006:"查询已禁用",4001:"组件不存在",4002:"组件版本不存在",4003:"组件已被禁用",4004:"组件完整性校验失败",4005:"组件版本不兼容",4006:"组件加载失败",4007:"组件渲染错误",5001:"页面不存在",5002:"页面版本不存在",5003:"页面 Schema 无效",5004:"页面 Manifest 无效",5005:"页面发布失败",5006:"页面回滚失败",6001:"活动不存在",6002:"活动未开始",6003:"活动已结束",6004:"已领取过",6005:"今日已签到",6006:"超出领取限制",6007:"活动已禁用",7001:"表达式语法错误",7002:"未知函数",7003:"无效参数",7004:"未知变量",7005:"类型不匹配",7006:"访问被拒绝",8001:"Schema 版本不匹配",8002:"迁移失败",8003:"迁移脚本不存在",8004:"版本不兼容"},s=new Set([{name:"len",description:"获取字符串或数组长度",params:[{name:"value",type:"any",required:!0}],returnType:"number",examples:['len("hello")',"len([1,2,3])"]},{name:"trim",description:"去除字符串首尾空格",params:[{name:"str",type:"string",required:!0}],returnType:"string",examples:['trim(" hello ")']},{name:"upper",description:"转为大写",params:[{name:"str",type:"string",required:!0}],returnType:"string",examples:['upper("hello")']},{name:"lower",description:"转为小写",params:[{name:"str",type:"string",required:!0}],returnType:"string",examples:['lower("HELLO")']},{name:"substr",description:"截取子字符串",params:[{name:"str",type:"string",required:!0},{name:"start",type:"number",required:!0},{name:"length",type:"number",required:!1}],returnType:"string",examples:['substr("hello", 0, 2)']},{name:"concat",description:"连接字符串",params:[{name:"values",type:"any",required:!0,description:"可变参数"}],returnType:"string",examples:['concat("a", "b", "c")']},{name:"replace",description:"替换字符串",params:[{name:"str",type:"string",required:!0},{name:"search",type:"string",required:!0},{name:"replacement",type:"string",required:!0}],returnType:"string",examples:['replace("hello", "l", "x")']},{name:"split",description:"分割字符串",params:[{name:"str",type:"string",required:!0},{name:"separator",type:"string",required:!0}],returnType:"array",examples:['split("a,b,c", ",")']},{name:"join",description:"连接数组为字符串",params:[{name:"arr",type:"array",required:!0},{name:"separator",type:"string",required:!1,defaultValue:","}],returnType:"string",examples:['join(["a","b","c"], "-")']},{name:"toNumber",description:"转为数字",params:[{name:"value",type:"any",required:!0}],returnType:"number",examples:['toNumber("123")']},{name:"toString",description:"转为字符串",params:[{name:"value",type:"any",required:!0}],returnType:"string",examples:["toString(123)"]},{name:"round",description:"四舍五入",params:[{name:"value",type:"number",required:!0},{name:"decimals",type:"number",required:!1,defaultValue:0}],returnType:"number",examples:["round(3.14159, 2)"]},{name:"floor",description:"向下取整",params:[{name:"value",type:"number",required:!0}],returnType:"number",examples:["floor(3.7)"]},{name:"ceil",description:"向上取整",params:[{name:"value",type:"number",required:!0}],returnType:"number",examples:["ceil(3.2)"]},{name:"abs",description:"绝对值",params:[{name:"value",type:"number",required:!0}],returnType:"number",examples:["abs(-5)"]},{name:"min",description:"最小值",params:[{name:"values",type:"number",required:!0,description:"可变参数"}],returnType:"number",examples:["min(1, 2, 3)"]},{name:"max",description:"最大值",params:[{name:"values",type:"number",required:!0,description:"可变参数"}],returnType:"number",examples:["max(1, 2, 3)"]},{name:"now",description:"当前时间戳(毫秒)",params:[],returnType:"number",examples:["now()"]},{name:"dateFormat",description:"格式化日期",params:[{name:"timestamp",type:"number",required:!0},{name:"format",type:"string",required:!1,defaultValue:"YYYY-MM-DD"}],returnType:"string",examples:['dateFormat(now(), "YYYY-MM-DD HH:mm:ss")']},{name:"dateParse",description:"解析日期字符串",params:[{name:"dateStr",type:"string",required:!0},{name:"format",type:"string",required:!1}],returnType:"number",examples:['dateParse("2024-01-01")']},{name:"first",description:"获取数组第一个元素",params:[{name:"arr",type:"array",required:!0}],returnType:"any",examples:["first([1,2,3])"]},{name:"last",description:"获取数组最后一个元素",params:[{name:"arr",type:"array",required:!0}],returnType:"any",examples:["last([1,2,3])"]},{name:"includes",description:"检查数组是否包含元素",params:[{name:"arr",type:"array",required:!0},{name:"value",type:"any",required:!0}],returnType:"boolean",examples:["includes([1,2,3], 2)"]},{name:"slice",description:"截取数组",params:[{name:"arr",type:"array",required:!0},{name:"start",type:"number",required:!0},{name:"end",type:"number",required:!1}],returnType:"array",examples:["slice([1,2,3,4], 1, 3)"]},{name:"default",description:"提供默认值",params:[{name:"value",type:"any",required:!0},{name:"defaultValue",type:"any",required:!0}],returnType:"any",examples:['default(null, "fallback")']},{name:"ifElse",description:"条件判断",params:[{name:"condition",type:"boolean",required:!0},{name:"trueValue",type:"any",required:!0},{name:"falseValue",type:"any",required:!0}],returnType:"any",examples:['ifElse(age > 18, "成年", "未成年")']},{name:"isEmpty",description:"检查是否为空",params:[{name:"value",type:"any",required:!0}],returnType:"boolean",examples:['isEmpty("")',"isEmpty([])"]},{name:"isNull",description:"检查是否为 null 或 undefined",params:[{name:"value",type:"any",required:!0}],returnType:"boolean",examples:["isNull(null)"]},{name:"jsonParse",description:"解析 JSON 字符串",params:[{name:"str",type:"string",required:!0}],returnType:"any",examples:["jsonParse('{\"a\":1}')"]},{name:"jsonStringify",description:"序列化为 JSON",params:[{name:"value",type:"any",required:!0}],returnType:"string",examples:["jsonStringify({a:1})"]}].map(e=>e.name));function n(e){return null!==e&&"object"==typeof e&&!0===e.__isExpression&&"string"==typeof e.expression}var o=[];function a(e){if(o.some(t=>t.from===e.from&&t.to===e.to))throw new Error(`Migration from ${e.from} to ${e.to} already exists`);o.push(e)}a({from:"1.0.0",to:"1.1.0",description:"添加 Definition 版本绑定字段",migrate:e=>({...e,actionDefVersionIds:e.actionDefVersionIds||[],dataQueryVersionIds:e.dataQueryVersionIds||[]})}),a({from:"1.1.0",to:"2.0.0",description:"重构组件事件结构",breaking:!0,migrate:e=>({...e,components:e.components.map(e=>{var t;return{...e,events:null==(t=e.events)?void 0:t.map(e=>({...e,enabled:e.enabled??!0}))}})})});var i=class extends Error{constructor(e,t,s,n){super(t||r[e]||"Unknown error"),this.name="DjvlcRuntimeError",this.code=e,this.details=s,this.traceId=n,this.timestamp=Date.now()}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,traceId:this.traceId,timestamp:this.timestamp}}},c=class extends i{constructor(e,r,s){super(t.PAGE_NOT_FOUND,e,r,s),this.name="PageLoadError"}},l=class extends i{constructor(e,r,s,n=t.COMPONENT_NOT_FOUND,o){super(n,s,{...o,componentName:e,componentVersion:r}),this.name="ComponentLoadError",this.componentName=e,this.componentVersion=r}},p=class extends i{constructor(e,r,s,n){super(t.COMPONENT_INTEGRITY_MISMATCH,`Integrity check failed for ${e}@${r}`,{expectedHash:s,actualHash:n}),this.name="IntegrityError",this.componentName=e,this.componentVersion=r,this.expectedHash=s,this.actualHash=n}},d=class extends i{constructor(e,r,s){super(t.COMPONENT_BLOCKED,`Component ${e}@${r} is blocked`,{componentName:e,componentVersion:r,reason:s}),this.name="ComponentBlockedError",this.componentName=e,this.componentVersion=r,this.reason=s}},h=class extends i{constructor(e,r,s,n){super(t.UNKNOWN,r,{...n,expression:e,position:s}),this.name="ExpressionError",this.expression=e,this.position=s}},u=class{constructor(e){this.cache=new Map,this.options={channel:"prod",cache:{enabled:!0,maxAge:300},...e}}async resolve(e,t){var r,s;const n=this.getCacheKey(e,t);if(null==(r=this.options.cache)?void 0:r.enabled){const t=this.cache.get(n);if(t&&this.isCacheValid(t.timestamp))return this.log("debug",`Page ${e} loaded from cache`),t.data}const o=performance.now();try{const r=this.buildResolveUrl(e,t),a=await fetch(r,{method:"GET",headers:this.buildHeaders()});if(!a.ok)throw new c(`Failed to resolve page: ${a.status} ${a.statusText}`,{pageUid:e,status:a.status});const i=await a.json();if(!this.isValidPageResolveResult(i))throw new c("Invalid page resolve response",{pageUid:e});const l=i.data;(null==(s=this.options.cache)?void 0:s.enabled)&&this.cache.set(n,{data:l,timestamp:Date.now()});const p=performance.now()-o;return this.log("info",`Page ${e} resolved in ${p.toFixed(2)}ms`),l}catch(a){if(a instanceof c)throw a;throw new c(`Failed to resolve page: ${a instanceof Error?a.message:"Unknown error"}`,{pageUid:e})}}preconnect(){const e=document.createElement("link");e.rel="preconnect",e.href=this.options.apiBaseUrl,document.head.appendChild(e)}clearCache(e){if(e)for(const t of this.cache.keys())t.startsWith(e)&&this.cache.delete(t);else this.cache.clear()}buildResolveUrl(e,t){const r=new URL(`${this.options.apiBaseUrl}/page/resolve`);return r.searchParams.set("pageUid",e),this.options.channel&&r.searchParams.set("channel",this.options.channel),this.options.previewToken&&r.searchParams.set("previewToken",this.options.previewToken),(null==t?void 0:t.uid)&&r.searchParams.set("uid",t.uid),(null==t?void 0:t.deviceId)&&r.searchParams.set("deviceId",t.deviceId),r.toString()}buildHeaders(){const e={"Content-Type":"application/json",...this.options.headers};return this.options.authToken&&(e.Authorization=`Bearer ${this.options.authToken}`),e}getCacheKey(e,t){const r=[e,this.options.channel];return(null==t?void 0:t.uid)&&r.push(t.uid),(null==t?void 0:t.deviceId)&&r.push(t.deviceId),r.join(":")}isCacheValid(e){var t;const r=1e3*((null==(t=this.options.cache)?void 0:t.maxAge)??300);return Date.now()-e<r}isValidPageResolveResult(e){if(!e||"object"!=typeof e)return!1;const t=e;if(!t.data||"object"!=typeof t.data)return!1;const r=t.data;return"string"==typeof r.pageUid&&"string"==typeof r.pageVersionId&&void 0!==r.pageJson&&void 0!==r.manifest}log(e,t){this.options.logger&&this.options.logger[e](t)}},m=class{constructor(e){this.loadedComponents=new Map,this.loadingPromises=new Map,this.options={enableSRI:!0,concurrency:4,timeout:3e4,blockedComponents:[],...e},this.blockedSet=new Set(this.options.blockedComponents)}async load(e){const t=this.getComponentKey(e.name,e.version);if(this.isBlocked(e.name,e.version))throw new d(e.name,e.version,"Component is blocked");const r=this.loadedComponents.get(t);if(r)return r;const s=this.loadingPromises.get(t);if(s)return s;const n=this.loadComponent(e);this.loadingPromises.set(t,n);try{const e=await n;return this.loadedComponents.set(t,e),e}finally{this.loadingPromises.delete(t)}}async loadAll(e){const t=new Map,{concurrency:r=4}=this.options,s=e.components;for(let n=0;n<s.length;n+=r){const e=s.slice(n,n+r).map(async e=>{const r=this.getComponentKey(e.name,e.version),s=performance.now();try{const n=await this.load(e);t.set(r,{name:e.name,version:e.version,status:"loaded",component:n.Component,loadTime:performance.now()-s})}catch(n){const o=n instanceof d?"blocked":"failed";if(t.set(r,{name:e.name,version:e.version,status:o,error:n instanceof Error?n.message:"Unknown error",loadTime:performance.now()-s}),e.critical)throw n}});await Promise.all(e)}return t}preload(e){e.forEach(e=>{const t=document.createElement("link");t.rel="preload",t.as="script",t.href=this.resolveUrl(e.entryUrl),this.options.enableSRI&&e.integrity&&(t.integrity=e.integrity,t.crossOrigin="anonymous"),document.head.appendChild(t)})}isLoaded(e,t){return this.loadedComponents.has(this.getComponentKey(e,t))}get(e,t){return this.loadedComponents.get(this.getComponentKey(e,t))}isBlocked(e,t){return this.blockedSet.has(`${e}@${t}`)||this.blockedSet.has(e)}updateBlockedList(e){this.blockedSet=new Set(e)}async loadComponent(e){const t=performance.now(),r=this.resolveUrl(e.entryUrl);this.log("debug",`Loading component ${e.name}@${e.version}`);try{const s=await this.fetchWithTimeout(r);if(!s.ok)throw new l(e.name,e.version,`Failed to fetch component: ${s.status} ${s.statusText}`);const n=await s.text();this.options.enableSRI&&e.integrity&&await this.validateIntegrity(e,n);const o=await this.executeScript(n,e),a=performance.now()-t;return this.log("info",`Component ${e.name}@${e.version} loaded in ${a.toFixed(2)}ms`),{name:e.name,version:e.version,Component:o,loadTime:a}}catch(s){if(s instanceof l||s instanceof p||s instanceof d)throw s;throw new l(e.name,e.version,`Failed to load component: ${s instanceof Error?s.message:"Unknown error"}`)}}async fetchWithTimeout(e){const t=new AbortController,r=setTimeout(()=>t.abort(),this.options.timeout);try{return await fetch(e,{signal:t.signal,credentials:"omit"})}finally{clearTimeout(r)}}async validateIntegrity(e,t){if(!e.integrity)return;const[r,s]=e.integrity.split("-");if(!r||!s)throw new p(e.name,e.version,e.integrity,"Invalid format");const n=await crypto.subtle.digest(r.toUpperCase(),(new TextEncoder).encode(t)),o=Array.from(new Uint8Array(n)),a=btoa(String.fromCharCode(...o));if(a!==s)throw new p(e.name,e.version,s,a)}async executeScript(e,t){const r=new Blob([e],{type:"application/javascript"}),s=URL.createObjectURL(r);try{const e=await import(s),r=e.default||e[t.name]||e.Component;if(!r)throw new l(t.name,t.version,"Component module does not export a valid component");return r}finally{URL.revokeObjectURL(s)}}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")?e:`${this.options.cdnBaseUrl}/${e.replace(/^\//,"")}`}getComponentKey(e,t){return`${e}@${t}`}log(e,t){this.options.logger&&this.options.logger[e](t)}},g=class{constructor(e){this.preconnectedHosts=new Set,this.preloadedAssets=new Set,this.options=e}preconnectAll(){[...this.options.cdnHosts,...this.options.apiHosts].forEach(e=>this.preconnect(e))}preconnect(e){if(this.preconnectedHosts.has(e))return;const t=document.createElement("link");t.rel="preconnect",t.href=e.startsWith("http")?e:`https://${e}`,t.crossOrigin="anonymous",document.head.appendChild(t),this.preconnectedHosts.add(e)}dnsPrefetch(e){const t=document.createElement("link");t.rel="dns-prefetch",t.href=e.startsWith("http")?e:`https://${e}`,document.head.appendChild(t)}preloadScript(e,t){if(this.preloadedAssets.has(e))return;const r=document.createElement("link");r.rel="preload",r.as="script",r.href=e,t&&(r.integrity=t,r.crossOrigin="anonymous"),document.head.appendChild(r),this.preloadedAssets.add(e)}preloadStyle(e,t){if(this.preloadedAssets.has(e))return;const r=document.createElement("link");r.rel="preload",r.as="style",r.href=e,t&&(r.integrity=t,r.crossOrigin="anonymous"),document.head.appendChild(r),this.preloadedAssets.add(e)}preloadImage(e){if(this.preloadedAssets.has(e))return;const t=document.createElement("link");t.rel="preload",t.as="image",t.href=e,document.head.appendChild(t),this.preloadedAssets.add(e)}prefetch(e,t){const r=document.createElement("link");r.rel="prefetch",r.href=e,t&&(r.as=t),document.head.appendChild(r)}loadStylesheet(e,t){return new Promise((r,s)=>{const n=document.createElement("link");n.rel="stylesheet",n.href=e,t&&(n.integrity=t,n.crossOrigin="anonymous"),n.onload=()=>r(),n.onerror=()=>s(new Error(`Failed to load stylesheet: ${e}`)),document.head.appendChild(n)})}loadScript(e,t){return new Promise((r,s)=>{const n=document.createElement("script");n.src=e,n.async=!0,t&&(n.integrity=t,n.crossOrigin="anonymous"),n.onload=()=>r(),n.onerror=()=>s(new Error(`Failed to load script: ${e}`)),document.body.appendChild(n)})}},y=class{constructor(){this.listeners=new Set,this.state=this.createInitialState()}getState(){return this.state}getPhase(){return this.state.phase}setPhase(e){this.setState({phase:e})}setPage(e){this.setState({page:e,variables:e.pageJson.page.variables||{}})}setError(e){this.setState({phase:"error",error:e})}getVariable(e){return this.state.variables[e]}setVariable(e,t){this.setState({variables:{...this.state.variables,[e]:t}})}setVariables(e){this.setState({variables:{...this.state.variables,...e}})}getQuery(e){return this.state.queries[e]}setQuery(e,t){this.setState({queries:{...this.state.queries,[e]:t}})}setComponentStatus(e,t){const r=new Map(this.state.components);r.set(e,t),this.setState({components:r})}setDestroyed(){this.setState({destroyed:!0})}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}reset(){this.state=this.createInitialState(),this.notifyListeners()}setState(e){this.state={...this.state,...e},this.notifyListeners()}notifyListeners(){this.listeners.forEach(e=>{try{e(this.state)}catch(t){}})}createInitialState(){return{phase:"idle",page:null,variables:{},queries:{},components:new Map,error:null,destroyed:!1}}},f=class{constructor(e={}){this.handlers=new Map,this.options={debug:!1,maxListeners:100,...e}}emit(e){this.options.debug&&this.log("debug",`Event emitted: ${e.type}`,e);const t=this.handlers.get(e.type);t&&t.forEach(t=>{try{t(e)}catch(r){this.log("error",`Error in event handler for ${e.type}:`,r)}})}on(e,t){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.size>=(this.options.maxListeners??100)&&this.log("warn",`Max listeners (${this.options.maxListeners}) reached for event: ${e}`),r.add(t),()=>{null==r||r.delete(t),0===(null==r?void 0:r.size)&&this.handlers.delete(e)}}off(e,t){const r=this.handlers.get(e);r&&(r.delete(t),0===r.size&&this.handlers.delete(e))}once(e,t){const r=this.on(e,e=>{r(),t(e)});return r}clear(e){e?this.handlers.delete(e):this.handlers.clear()}listenerCount(e){var t;return(null==(t=this.handlers.get(e))?void 0:t.size)??0}static createEvent(e,t,r){return{type:e,data:t,timestamp:Date.now(),traceId:r}}log(e,t,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}},E=class{constructor(e){this.pos=0,this.tokens=[],this.input=e}tokenize(){for(this.pos=0,this.tokens=[];this.pos<this.input.length&&(this.skipWhitespace(),!(this.pos>=this.input.length));){const e=this.readToken();e&&this.tokens.push(e)}return this.tokens.push({type:"EOF",value:null,start:this.input.length,end:this.input.length}),this.tokens}readToken(){const e=this.input[this.pos],t=this.pos;if(this.isDigit(e)||"-"===e&&this.isDigit(this.peek(1)))return this.readNumber();if('"'===e||"'"===e)return this.readString(e);if(this.isIdentifierStart(e))return this.readIdentifier();const r=this.readOperator();if(r)return r;switch(e){case".":return this.pos++,{type:"DOT",value:".",start:t,end:this.pos};case"[":return this.pos++,{type:"LBRACKET",value:"[",start:t,end:this.pos};case"]":return this.pos++,{type:"RBRACKET",value:"]",start:t,end:this.pos};case"(":return this.pos++,{type:"LPAREN",value:"(",start:t,end:this.pos};case")":return this.pos++,{type:"RPAREN",value:")",start:t,end:this.pos};case",":return this.pos++,{type:"COMMA",value:",",start:t,end:this.pos};case"?":return this.pos++,{type:"QUESTION",value:"?",start:t,end:this.pos};case":":return this.pos++,{type:"COLON",value:":",start:t,end:this.pos}}throw new Error(`Unexpected character '${e}' at position ${this.pos}`)}readNumber(){const e=this.pos;let t="";for("-"===this.input[this.pos]&&(t+="-",this.pos++);this.isDigit(this.input[this.pos]);)t+=this.input[this.pos],this.pos++;if("."===this.input[this.pos]&&this.isDigit(this.peek(1)))for(t+=".",this.pos++;this.isDigit(this.input[this.pos]);)t+=this.input[this.pos],this.pos++;return{type:"NUMBER",value:parseFloat(t),start:e,end:this.pos}}readString(e){const t=this.pos;this.pos++;let r="";for(;this.pos<this.input.length&&this.input[this.pos]!==e;){if("\\"===this.input[this.pos]){this.pos++;const e=this.input[this.pos];switch(e){case"n":r+="\n";break;case"t":r+="\t";break;case"r":r+="\r";break;case"\\":r+="\\";break;case'"':r+='"';break;case"'":r+="'";break;default:r+=e}}else r+=this.input[this.pos];this.pos++}if(this.input[this.pos]!==e)throw new Error(`Unterminated string at position ${t}`);return this.pos++,{type:"STRING",value:r,start:t,end:this.pos}}readIdentifier(){const e=this.pos;let t="";for(;this.pos<this.input.length&&this.isIdentifierChar(this.input[this.pos]);)t+=this.input[this.pos],this.pos++;return"true"===t?{type:"BOOLEAN",value:!0,start:e,end:this.pos}:"false"===t?{type:"BOOLEAN",value:!1,start:e,end:this.pos}:"null"===t?{type:"NULL",value:null,start:e,end:this.pos}:{type:"IDENTIFIER",value:t,start:e,end:this.pos}}readOperator(){const e=this.pos,t=this.input.slice(this.pos,this.pos+2),r=this.input[this.pos];if(["==","!=",">=","<=","&&","||","??"].includes(t))return this.pos+=2,{type:"OPERATOR",value:t,start:e,end:this.pos};return["+","-","*","/","%",">","<","!"].includes(r)?(this.pos++,{type:"OPERATOR",value:r,start:e,end:this.pos}):null}skipWhitespace(){for(;this.pos<this.input.length&&/\s/.test(this.input[this.pos]);)this.pos++}isDigit(e){return/[0-9]/.test(e)}isIdentifierStart(e){return/[a-zA-Z_$]/.test(e)}isIdentifierChar(e){return/[a-zA-Z0-9_$]/.test(e)}peek(e=1){return this.input[this.pos+e]||""}},v={"||":1,"??":1,"&&":2,"==":3,"!=":3,"<":4,">":4,"<=":4,">=":4,"+":5,"-":5,"*":6,"/":6,"%":6},b=class{constructor(e){this.pos=0,this.tokens=e}parse(){const e=this.parseExpression();if("EOF"!==this.current().type)throw new Error(`Unexpected token '${this.current().value}' at position ${this.current().start}`);return e}parseExpression(){return this.parseTernary()}parseTernary(){const e=this.parseBinary(0);if("QUESTION"===this.current().type){this.advance();const t=this.parseExpression();this.expect("COLON");return{type:"conditional",test:e,consequent:t,alternate:this.parseExpression(),raw:void 0}}return e}parseBinary(e){let t=this.parseUnary();for(;;){const r=this.current();if("OPERATOR"!==r.type)break;const s=v[r.value];if(void 0===s||s<e)break;this.advance();const n=this.parseBinary(s+1);t={type:"binary",operator:r.value,left:t,right:n,raw:void 0}}return t}parseUnary(){const e=this.current();if("OPERATOR"===e.type&&("!"===e.value||"-"===e.value)){this.advance();const t=this.parseUnary();return{type:"unary",operator:e.value,argument:t,raw:void 0}}return this.parsePostfix()}parsePostfix(){let e=this.parsePrimary();for(;;){const t=this.current();if("DOT"===t.type){this.advance();e={type:"member",object:e,property:this.expect("IDENTIFIER").value,computed:!1,raw:void 0}}else if("LBRACKET"===t.type){this.advance();const t=this.parseExpression();this.expect("RBRACKET"),e={type:"member",object:e,property:t,computed:!0,raw:void 0}}else{if("LPAREN"!==t.type||"identifier"!==e.type)break;{const r=e.name;if(!s.has(r))throw new Error(`Unknown function '${r}' at position ${t.start}`);this.advance();const n=this.parseArguments();this.expect("RPAREN"),e={type:"call",callee:r,arguments:n,raw:void 0}}}}return e}parsePrimary(){const e=this.current();if("NUMBER"===e.type||"STRING"===e.type||"BOOLEAN"===e.type||"NULL"===e.type)return this.advance(),{type:"literal",value:e.value,start:e.start,end:e.end,raw:void 0};if("IDENTIFIER"===e.type)return this.advance(),{type:"identifier",name:e.value,start:e.start,end:e.end,raw:void 0};if("LBRACKET"===e.type)return this.parseArray();if("LPAREN"===e.type){this.advance();const e=this.parseExpression();return this.expect("RPAREN"),e}throw new Error(`Unexpected token '${e.value}' at position ${e.start}`)}parseArray(){const e=this.current().start;this.advance();const t=[];for(;"RBRACKET"!==this.current().type&&(t.push(this.parseExpression()),"COMMA"===this.current().type);)this.advance();const r=this.current().end;return this.expect("RBRACKET"),{type:"array",elements:t,start:e,end:r,raw:void 0}}parseArguments(){const e=[];if("RPAREN"!==this.current().type)for(e.push(this.parseExpression());"COMMA"===this.current().type;)this.advance(),e.push(this.parseExpression());return e}current(){return this.tokens[this.pos]}advance(){return this.tokens[this.pos++]}expect(e){const t=this.current();if(t.type!==e)throw new Error(`Expected '${e}' but got '${t.type}' at position ${t.start}`);return this.advance()}},I={len:e=>"string"==typeof e||Array.isArray(e)?e.length:0,trim:e=>String(e??"").trim(),upper:e=>String(e??"").toUpperCase(),lower:e=>String(e??"").toLowerCase(),substr:(e,t,r)=>{const s=String(e??""),n=Number(t)||0,o=void 0!==r?Number(r):void 0;return s.substring(n,void 0!==o?n+o:void 0)},concat:(...e)=>e.map(e=>String(e??"")).join(""),replace:(e,t,r)=>String(e??"").split(String(t)).join(String(r)),split:(e,t)=>String(e??"").split(String(t)),join:(e,t)=>Array.isArray(e)?e.join(void 0!==t?String(t):","):"",startsWith:(e,t)=>String(e??"").startsWith(String(t)),endsWith:(e,t)=>String(e??"").endsWith(String(t)),contains:(e,t)=>String(e??"").includes(String(t)),toNumber:e=>{const t=Number(e);return isNaN(t)?0:t},toString:e=>String(e??""),toInt:e=>Math.trunc(Number(e)||0),toFloat:e=>parseFloat(String(e))||0,round:(e,t)=>{const r=Number(e)||0,s=Number(t)||0,n=Math.pow(10,s);return Math.round(r*n)/n},floor:e=>Math.floor(Number(e)||0),ceil:e=>Math.ceil(Number(e)||0),abs:e=>Math.abs(Number(e)||0),min:(...e)=>{const t=e.map(e=>Number(e)).filter(e=>!isNaN(e));return t.length>0?Math.min(...t):0},max:(...e)=>{const t=e.map(e=>Number(e)).filter(e=>!isNaN(e));return t.length>0?Math.max(...t):0},sum:e=>Array.isArray(e)?e.reduce((e,t)=>e+(Number(t)||0),0):0,avg:e=>{if(!Array.isArray(e)||0===e.length)return 0;return e.reduce((e,t)=>e+(Number(t)||0),0)/e.length},random:()=>Math.random(),randomInt:(e,t)=>{const r=Math.ceil(Number(e)||0),s=Math.floor(Number(t)||100);return Math.floor(Math.random()*(s-r+1))+r},now:()=>Date.now(),today:()=>(new Date).toISOString().split("T")[0],dateFormat:(e,t)=>{const r=new Date(Number(e)||Date.now()),s=e=>e.toString().padStart(2,"0");return String(t||"YYYY-MM-DD").replace("YYYY",r.getFullYear().toString()).replace("MM",s(r.getMonth()+1)).replace("DD",s(r.getDate())).replace("HH",s(r.getHours())).replace("mm",s(r.getMinutes())).replace("ss",s(r.getSeconds()))},dateParse:e=>new Date(String(e)).getTime(),year:e=>new Date(Number(e)||Date.now()).getFullYear(),month:e=>new Date(Number(e)||Date.now()).getMonth()+1,day:e=>new Date(Number(e)||Date.now()).getDate(),addDays:(e,t)=>{const r=new Date(Number(e)||Date.now());return r.setDate(r.getDate()+(Number(t)||0)),r.getTime()},diffDays:(e,t)=>{const r=new Date(Number(e)||Date.now()),s=new Date(Number(t)||Date.now()),n=Math.abs(s.getTime()-r.getTime());return Math.floor(n/864e5)},isNull:e=>null==e,isUndefined:e=>void 0===e,isEmpty:e=>null==e||("string"==typeof e||Array.isArray(e)?0===e.length:"object"==typeof e&&0===Object.keys(e).length),isArray:e=>Array.isArray(e),isObject:e=>null!==e&&"object"==typeof e&&!Array.isArray(e),isString:e=>"string"==typeof e,isNumber:e=>"number"==typeof e&&!isNaN(e),isBoolean:e=>"boolean"==typeof e,typeOf:e=>null===e?"null":Array.isArray(e)?"array":typeof e,default:(e,t)=>e??t,coalesce:(...e)=>{for(const t of e)if(null!=t)return t;return null},ifElse:(e,t,r)=>e?t:r,first:e=>{if(Array.isArray(e))return e[0]},last:e=>{if(Array.isArray(e))return e[e.length-1]},at:(e,t)=>{if(Array.isArray(e))return e[Number(t)||0]},slice:(e,t,r)=>Array.isArray(e)?e.slice(Number(t)||0,void 0!==r?Number(r):void 0):[],includes:(e,t)=>!!Array.isArray(e)&&e.includes(t),indexOf:(e,t)=>Array.isArray(e)?e.indexOf(t):-1,reverse:e=>Array.isArray(e)?[...e].reverse():[],sort:e=>Array.isArray(e)?[...e].sort():[],unique:e=>Array.isArray(e)?[...new Set(e)]:[],flatten:e=>Array.isArray(e)?e.flat():[],count:e=>Array.isArray(e)?e.length:0,get:(e,t,r)=>{if(null==e)return r;const s=String(t).split(".");let n=e;for(const o of s){if(null==n)return r;n=n[o]}return n??r},keys:e=>"object"!=typeof e||null===e?[]:Object.keys(e),values:e=>"object"!=typeof e||null===e?[]:Object.values(e),entries:e=>"object"!=typeof e||null===e?[]:Object.entries(e),has:(e,t)=>"object"==typeof e&&null!==e&&String(t)in e,merge:(...e)=>{const t={};for(const r of e)"object"==typeof r&&null!==r&&Object.assign(t,r);return t},and:(...e)=>e.every(e=>Boolean(e)),or:(...e)=>e.some(e=>Boolean(e)),not:e=>!e,eq:(e,t)=>e===t,ne:(e,t)=>e!==t,gt:(e,t)=>Number(e)>Number(t),gte:(e,t)=>Number(e)>=Number(t),lt:(e,t)=>Number(e)<Number(t),lte:(e,t)=>Number(e)<=Number(t),between:(e,t,r)=>{const s=Number(e);return s>=Number(t)&&s<=Number(r)},formatNumber:(e,t)=>{const r=Number(e)||0,s=Number(t)??0;return r.toLocaleString(void 0,{minimumFractionDigits:s,maximumFractionDigits:s})},formatCurrency:(e,t)=>{const r=Number(e)||0,s=String(t||"CNY");return r.toLocaleString("zh-CN",{style:"currency",currency:s})},formatPercent:(e,t)=>{const r=Number(e)||0,s=Number(t)??0;return(100*r).toFixed(s)+"%"},jsonParse:e=>{try{return JSON.parse(String(e))}catch{return null}},jsonStringify:e=>JSON.stringify(e)},N=class{constructor(e={}){this.depth=0,this.startTime=0,this.options={maxDepth:100,timeout:1e3,debug:!1,...e}}evaluate(e,t){this.depth=0,this.startTime=Date.now();try{return{value:this.evaluateNode(e,t)}}catch(r){return{value:void 0,error:r instanceof Error?r:new Error(String(r))}}}evaluateNode(e,t){switch(this.checkLimits(),e.type){case"literal":return this.evaluateLiteral(e);case"identifier":return this.evaluateIdentifier(e,t);case"member":return this.evaluateMember(e,t);case"call":return this.evaluateCall(e,t);case"binary":return this.evaluateBinary(e,t);case"unary":return this.evaluateUnary(e,t);case"conditional":return this.evaluateConditional(e,t);case"array":return this.evaluateArray(e,t);default:throw new h("",`Unknown node type: ${e.type}`)}}evaluateLiteral(e){return e.value}evaluateIdentifier(e,t){const r=e.name;switch(r){case"state":return t.state;case"query":return t.query;case"context":return t.context;case"event":return t.event;case"item":return t.item;case"index":return t.index;default:throw new h("",`Unknown variable '${r}'`,void 0!==e.start&&void 0!==e.end?{start:e.start,end:e.end}:void 0)}}evaluateMember(e,t){const r=this.evaluateNode(e.object,t);if(null==r)return;let s;if(e.computed){s=this.evaluateNode(e.property,t)}else s=e.property;return"object"==typeof r&&null!==r?r[s]:void 0}evaluateCall(e,t){const r=I[e.callee];if(!r)throw new h("",`Unknown function '${e.callee}'`);return r(...e.arguments.map(e=>this.evaluateNode(e,t)))}evaluateBinary(e,t){const r=e.operator;if("&&"===r){const r=this.evaluateNode(e.left,t);return r?this.evaluateNode(e.right,t):r}if("||"===r){const r=this.evaluateNode(e.left,t);return r||this.evaluateNode(e.right,t)}if("??"===r){const r=this.evaluateNode(e.left,t);return null!=r?r:this.evaluateNode(e.right,t)}const s=this.evaluateNode(e.left,t),n=this.evaluateNode(e.right,t);switch(r){case"+":return"string"==typeof s||"string"==typeof n?String(s)+String(n):s+n;case"-":return s-n;case"*":return s*n;case"/":return s/n;case"%":return s%n;case"==":return s===n;case"!=":return s!==n;case"<":return s<n;case">":return s>n;case"<=":return s<=n;case">=":return s>=n;default:throw new h("",`Unknown operator '${r}'`)}}evaluateUnary(e,t){const r=this.evaluateNode(e.argument,t);switch(e.operator){case"!":return!r;case"-":return-r;default:throw new h("",`Unknown unary operator '${e.operator}'`)}}evaluateConditional(e,t){return this.evaluateNode(e.test,t)?this.evaluateNode(e.consequent,t):this.evaluateNode(e.alternate,t)}evaluateArray(e,t){return e.elements.map(e=>this.evaluateNode(e,t))}checkLimits(){if(this.depth++,this.depth>(this.options.maxDepth??100))throw new h("","Maximum recursion depth exceeded");if(Date.now()-this.startTime>(this.options.timeout??1e3))throw new h("","Expression evaluation timeout")}},T=class{constructor(e={}){this.astCache=new Map,this.options={cacheAST:!0,maxCacheSize:1e3,...e},this.evaluator=new N(e)}evaluate(e,t){try{const r=this.parse(e);return this.evaluator.evaluate(r,t)}catch(r){return{value:void 0,error:r instanceof Error?r:new Error(String(r))}}}evaluateWithFallback(e,t,r){const s=this.evaluate(e,t);return s.error?(this.log("warn",`Expression evaluation failed: ${s.error.message}`,e),r):s.value}evaluateTemplate(e,t){return e.replace(/\$\{([^}]+)\}/g,(e,r)=>{const s=this.evaluate(r.trim(),t);return s.error?(this.log("warn",`Template expression failed: ${s.error.message}`,r),""):String(s.value??"")})}parse(e){if(this.options.cacheAST){const t=this.astCache.get(e);if(t)return t}try{const t=new E(e).tokenize(),r=new b(t).parse();if(this.options.cacheAST){if(this.astCache.size>=(this.options.maxCacheSize??1e3)){Array.from(this.astCache.keys()).slice(0,Math.floor(this.astCache.size/2)).forEach(e=>this.astCache.delete(e))}this.astCache.set(e,r)}return r}catch(t){throw new h(e,t instanceof Error?t.message:"Parse error")}}validate(e){const t=[],r=[],s=[],n=[];try{const t=this.parse(e);return this.collectReferences(t,s,n),{valid:!0,errors:[],warnings:r,referencedPaths:s,calledFunctions:n}}catch(o){return t.push({type:"SYNTAX_ERROR",message:o instanceof Error?o.message:"Parse error"}),{valid:!1,errors:t,warnings:r,referencedPaths:s,calledFunctions:n}}}clearCache(){this.astCache.clear()}collectReferences(e,t,r){switch(e.type){case"identifier":t.push(e.name);break;case"member":{const r=this.buildMemberPath(e);r&&t.push(r);break}case"call":r.push(e.callee),e.arguments.forEach(e=>this.collectReferences(e,t,r));break;case"binary":this.collectReferences(e.left,t,r),this.collectReferences(e.right,t,r);break;case"unary":this.collectReferences(e.argument,t,r);break;case"conditional":this.collectReferences(e.test,t,r),this.collectReferences(e.consequent,t,r),this.collectReferences(e.alternate,t,r);break;case"array":e.elements.forEach(e=>this.collectReferences(e,t,r))}}buildMemberPath(e){if("identifier"===e.type)return e.name;if("member"===e.type&&!e.computed){const t=this.buildMemberPath(e.object);if(t)return`${t}.${e.property}`}return null}log(e,t,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}},w=class{constructor(e){this.storage={get:(e,t)=>{const r=this.getStorageKey(e,null==t?void 0:t.namespace),s=localStorage.getItem(r);if(s)try{const e=JSON.parse(s);return e.expires&&Date.now()>e.expires?void localStorage.removeItem(r):e.value}catch{return}},set:(e,t,r)=>{const s=this.getStorageKey(e,null==r?void 0:r.namespace),n={value:t,expires:(null==r?void 0:r.ttl)?Date.now()+1e3*r.ttl:void 0};localStorage.setItem(s,JSON.stringify(n))},remove:(e,t)=>{const r=this.getStorageKey(e,null==t?void 0:t.namespace);localStorage.removeItem(r)}},this.options=e,this.storageNamespace=`djvlc:${e.context.pageUid}`}async requestData(e,t){this.log("debug",`Requesting data: ${e}`,t);const r=performance.now(),s=this.options.context;try{const n=await fetch(`${this.options.apiBaseUrl}/data/query`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify({queryVersionId:e,params:t||{},context:{pageVersionId:s.pageVersionId,uid:s.userId}})}),o=await n.json(),a=performance.now()-r;return this.log("debug",`Data query completed in ${a.toFixed(2)}ms`),o.success&&o.data&&this.options.stateManager.setQuery(e,o.data),o}catch(n){return this.log("error",`Data query failed: ${e}`,n),{success:!1,message:n instanceof Error?n.message:"Query failed"}}}async executeAction(e,t){this.log("debug",`Executing action: ${e}`,t);const r=performance.now(),s=this.options.context;try{const n=await fetch(`${this.options.apiBaseUrl}/actions/execute`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify({actionType:e,params:t||{},context:{pageVersionId:s.pageVersionId,uid:s.userId,deviceId:s.deviceId,channel:s.channel},idempotencyKey:this.generateIdempotencyKey(e,t)})}),o=await n.json(),a=performance.now()-r;return this.log("debug",`Action completed in ${a.toFixed(2)}ms`),o}catch(n){return this.log("error",`Action failed: ${e}`,n),{success:!1,message:n instanceof Error?n.message:"Action failed"}}}navigate(e){this.log("debug","Navigate:",e),this.track({eventName:"navigate",params:{url:e.url,newTab:e.newTab}});let t=e.url;if(e.params){const r=new URLSearchParams(e.params);t+=(t.includes("?")?"&":"?")+r.toString()}e.newTab?window.open(t,"_blank"):e.replace?window.location.replace(t):window.location.href=t}goBack(){this.log("debug","Navigate back"),window.history.back()}refresh(){this.log("debug","Refresh page"),window.location.reload()}async openDialog(e){switch(this.log("debug","Open dialog:",e),e.type){case"alert":return window.alert(e.content||e.title),!0;case"confirm":return window.confirm(e.content||e.title);case"prompt":return window.prompt(e.content||e.title)||"";case"custom":return this.log("warn","Custom dialog not implemented"),!1;default:return!1}}closeDialog(){this.log("debug","Close dialog")}showToast(e){this.log("debug","Show toast:",e);const t=document.createElement("div");t.className=`djvlc-toast djvlc-toast-${e.type||"info"} djvlc-toast-${e.position||"top"}`,t.textContent=e.message,Object.assign(t.style,{position:"fixed",left:"50%",transform:"translateX(-50%)",padding:"12px 24px",borderRadius:"8px",color:"#fff",fontSize:"14px",zIndex:"10000",animation:"djvlc-toast-fade-in 0.3s ease"});t.style.backgroundColor={success:"#52c41a",error:"#ff4d4f",warning:"#faad14",info:"#1890ff"}[e.type||"info"];Object.assign(t.style,{top:{top:"20px"},center:{top:"50%",transform:"translate(-50%, -50%)"},bottom:{bottom:"20px"}}[e.position||"top"]),document.body.appendChild(t),setTimeout(()=>{t.style.animation="djvlc-toast-fade-out 0.3s ease",setTimeout(()=>t.remove(),300)},e.duration||3e3)}track(e){this.log("debug","Track event:",e);const t=this.options.context;fetch(`${this.options.apiBaseUrl}/track`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify({eventName:e.eventName,params:e.params,timestamp:e.timestamp||Date.now(),context:{pageVersionId:t.pageVersionId,runtimeVersion:t.runtimeVersion,userId:t.userId,deviceId:t.deviceId,channel:t.channel}}),keepalive:!0}).catch(e=>{this.log("warn","Track failed:",e)})}async copyToClipboard(e){try{return await navigator.clipboard.writeText(e),{success:!0,content:e}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Copy failed"}}}async readFromClipboard(){try{return{success:!0,content:await navigator.clipboard.readText()}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Read failed"}}}getState(e){return this.options.stateManager.getVariable(e)}setState(e,t){this.options.stateManager.setVariable(e,t)}getVariable(e){return this.options.stateManager.getVariable(e)}postMessage(e,t){this.log("debug",`Post message to ${e}:`,t);const r=new CustomEvent(`djvlc:message:${e}`,{detail:{message:t,from:this.options.context.pageUid}});document.dispatchEvent(r)}broadcast(e,t){this.log("debug",`Broadcast to ${e}:`,t);const r=new CustomEvent(`djvlc:broadcast:${e}`,{detail:{message:t,from:this.options.context.pageUid}});document.dispatchEvent(r)}getContext(){return{...this.options.context}}buildHeaders(){const e={"Content-Type":"application/json",...this.options.headers};return this.options.authToken&&(e.Authorization=`Bearer ${this.options.authToken}`),e}getStorageKey(e,t){return`${t||this.storageNamespace}:${e}`}generateIdempotencyKey(e,t){const r=Date.now(),s=JSON.stringify(t||{});return`${e}:${r}:${this.simpleHash(s)}`}simpleHash(e){let t=0;for(let r=0;r<e.length;r++){t=(t<<5)-t+e.charCodeAt(r),t&=t}return Math.abs(t).toString(36)}log(e,t,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}},A=class{constructor(e={}){this.blockedComponentsMap=new Map,this.blockedActionsSet=new Set,this.options={enableSRI:!0,cdnDomains:[],apiDomains:[],blockedComponents:[],blockedActions:[],...e},this.updateBlockedList(e.blockedComponents||[],e.blockedActions||[])}updateBlockedList(e,t){this.blockedComponentsMap.clear(),e.forEach(e=>{this.blockedComponentsMap.set(`${e.name}@${e.version}`,e)}),this.blockedActionsSet=new Set(t)}isComponentBlocked(e,t){return this.blockedComponentsMap.has(`${e}@${t}`)}getBlockedInfo(e,t){return this.blockedComponentsMap.get(`${e}@${t}`)}isActionBlocked(e){return this.blockedActionsSet.has(e)}async validateComponent(e,t,r,s){if(!this.options.enableSRI)return;const[n,o]=s.split("-");if(!n||!o)throw new p(e,t,s,"Invalid format");const a=await this.computeHash(r,n);if(a!==o)throw new p(e,t,o,a)}isAllowedUrl(e,t){const r="cdn"===t?this.options.cdnDomains:this.options.apiDomains;if(!r||0===r.length)return!0;try{const t=new URL(e);return r.some(e=>{if(e.startsWith("*.")){const r=e.slice(2);return t.hostname.endsWith(r)}return t.hostname===e})}catch{return!1}}generateCSPPolicy(){const e=this.options.cdnDomains||[],t=this.options.apiDomains||[],r=["'self'",...e].join(" "),s=["'self'",...t].join(" ");return["default-src 'self'",`script-src ${r}`,`style-src ${["'self'","'unsafe-inline'",...e].join(" ")}`,`img-src ${["'self'","data:","blob:",...e].join(" ")}`,`connect-src ${s}`,`font-src 'self' data: ${e.join(" ")}`,"frame-ancestors 'self'","base-uri 'self'","form-action 'self'"].join("; ")}applyCSP(){const e=document.createElement("meta");e.httpEquiv="Content-Security-Policy",e.content=this.generateCSPPolicy(),document.head.appendChild(e)}assertNotBlocked(e,t){const r=this.getBlockedInfo(e,t);if(r)throw new d(e,t,r.reason)}async computeHash(e,t){const r=(new TextEncoder).encode(e),s=await crypto.subtle.digest(t.toUpperCase(),r),n=Array.from(new Uint8Array(s));return btoa(String.fromCharCode(...n))}_log(e,t){this.options.logger&&this.options.logger[e](t)}get log(){return this._log.bind(this)}},S=class{constructor(e){this.spans=new Map,this.metrics=[],this.errors=[],this.options={enabled:!0,sampleRate:1,...e},this.traceId=this.generateId(),this.shouldSample=Math.random()<(this.options.sampleRate??1)}getTraceId(){return this.traceId}getTraceparent(){return`00-${this.traceId}-${this.generateId().slice(0,16)}-01`}startSpan(e,t,r){const s={spanId:this.generateId().slice(0,16),traceId:this.traceId,parentSpanId:t,name:e,startTime:performance.now(),attributes:r};return this.spans.set(s.spanId,s),this.log("debug",`Span started: ${e} (${s.spanId})`),s}endSpan(e,t="ok"){const r=this.spans.get(e);r&&(r.endTime=performance.now(),r.status=t,this.log("debug",`Span ended: ${r.name} (${e}) - ${r.endTime-r.startTime}ms`))}recordMetric(e,t,r,s){const n={type:e,name:t,duration:r,startTime:performance.now()-r,extra:s};this.metrics.push(n),this.log("debug",`Metric: ${e} - ${t} - ${r}ms`),this.options.onMetric&&this.options.onMetric(n)}recordError(e,t){const r={type:"LOAD_ERROR",message:e.message,stack:e instanceof Error?e.stack:void 0,timestamp:Date.now(),traceId:this.traceId,...t};this.errors.push(r),this.log("error",`Error recorded: ${e.message}`),this.shouldSample&&this.options.enabled&&this.reportError(r)}recordPageLoad(e,t){this.recordMetric("page_resolve","page_load",e,{pageVersionId:this.options.pageVersionId,...t})}recordComponentLoad(e,t,r,s){this.recordMetric("component_load",`${e}@${t}`,r,{success:s})}recordFirstRender(e){this.recordMetric("first_render","first_render",e,{pageVersionId:this.options.pageVersionId})}recordActionExecute(e,t,r){this.recordMetric("action_execute",e,t,{success:r})}recordQueryExecute(e,t,r,s){this.recordMetric("query_execute",e,t,{success:r,fromCache:s})}getMetrics(){return[...this.metrics]}getSpans(){return Array.from(this.spans.values())}clear(){this.spans.clear(),this.metrics=[],this.errors=[]}async flush(){if(!this.shouldSample||!this.options.enabled||!this.options.endpoint)return;const e={traceId:this.traceId,pageVersionId:this.options.pageVersionId,appId:this.options.appId,spans:this.getSpans(),metrics:this.metrics,errors:this.errors,timestamp:Date.now()};try{await fetch(this.options.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0})}catch(t){this.log("warn","Failed to flush telemetry:",t)}}reportError(e){this.options.endpoint&&fetch(`${this.options.endpoint}/errors`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0}).catch(()=>{})}generateId(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,e=>e.toString(16).padStart(2,"0")).join("")}log(e,t,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}},O=class{constructor(e){this.container=null,this.renderedElements=new Map,this.expressionContext={state:{},query:{},context:{}},this.options=e}init(){this.log("debug","Renderer initialized")}render(e,t){this.container=t,this.log("debug","Rendering page",e.page.id),t.innerHTML="",this.applyPageStyles(e.page.canvas);const r=document.createDocumentFragment();for(const s of e.components){const e=this.renderComponent(s);e&&r.appendChild(e)}t.appendChild(r),this.log("info",`Rendered ${e.components.length} components`)}updateComponent(e,t){const r=this.renderedElements.get(e);r?this.applyProps(r,t):this.log("warn",`Component not found: ${e}`)}updateContext(e){this.expressionContext={...this.expressionContext,...e}}destroy(){this.renderedElements.forEach(e=>{e.remove()}),this.renderedElements.clear(),this.container&&(this.container.innerHTML=""),this.log("debug","Renderer destroyed")}renderComponent(e){const{id:t,type:r,props:s,style:n,children:o,visible:a}=e;if(!1===a)return null;try{const e=this.options.components.get(r);let a;e&&customElements.get(r)?a=document.createElement(r):(a=document.createElement("div"),a.className=`djvlc-component djvlc-${r}`,e||(this.log("warn",`Component not loaded: ${r}`),a.textContent=`[Component: ${r}]`)),a.setAttribute("data-component-id",t),a.setAttribute("data-component-type",r);const i=this.resolveProps(s);if(this.applyProps(a,i),n&&this.applyStyles(a,n),this.options.injectHostApi(a,t),o&&o.length>0)for(const t of o){const e=this.renderComponent(t);e&&a.appendChild(e)}return this.renderedElements.set(t,a),a}catch(i){if(this.log("error",`Failed to render component: ${t}`,i),this.options.onRenderError)return this.options.onRenderError(t,i);const e=document.createElement("div");return e.className="djvlc-error-boundary",e.textContent=`Error rendering component: ${r}`,e}}resolveProps(e){const t={};for(const[r,s]of Object.entries(e))if(n(s)){const e=this.options.expressionEngine.evaluateWithFallback(s.expression,this.expressionContext,s.fallback);t[r]=e}else"object"!=typeof s||null===s||Array.isArray(s)?t[r]=s:t[r]=this.resolveProps(s);return t}applyProps(e,t){for(const[r,s]of Object.entries(t))null!=s&&(e.tagName.includes("-")?e[r]=s:"boolean"==typeof s?s?e.setAttribute(r,""):e.removeAttribute(r):"object"==typeof s?e.setAttribute(r,JSON.stringify(s)):e.setAttribute(r,String(s)))}applyStyles(e,t){for(const[r,s]of Object.entries(t)){if(null==s)continue;let t;if("number"==typeof s){t=["zIndex","opacity","flex","fontWeight"].includes(r)?String(s):`${s}px`}else t=String(s);const n=r.replace(/([A-Z])/g,"-$1").toLowerCase();e.style.setProperty(n,t)}}applyPageStyles(e){this.container&&(this.container.style.width=`${e.width}px`,e.height&&(this.container.style.minHeight=`${e.height}px`),e.background&&(this.container.style.background=e.background),this.container.classList.add("djvlc-page",`djvlc-canvas-${e.type}`))}log(e,t,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}};function C(e){return new R(e)}var R=class{constructor(e){this.container=null,this.options={channel:"prod",debug:!1,enableSRI:!0,...e},this.logger=this.createLogger(),this.stateManager=new y,this.eventBus=new f({debug:e.debug,logger:this.logger}),this.expressionEngine=new T({debug:e.debug,logger:this.logger}),this.pageLoader=new u({apiBaseUrl:e.apiBaseUrl,channel:e.channel,authToken:e.authToken,previewToken:e.previewToken,headers:e.headers,logger:this.logger}),this.componentLoader=new m({cdnBaseUrl:e.cdnBaseUrl,enableSRI:e.enableSRI,logger:this.logger}),this.assetLoader=new g({cdnHosts:[new URL(e.cdnBaseUrl).host],apiHosts:[new URL(e.apiBaseUrl).host]}),this.securityManager=new A({enableSRI:e.enableSRI,cdnDomains:[new URL(e.cdnBaseUrl).host],apiDomains:[new URL(e.apiBaseUrl).host],logger:this.logger}),this.log("info","Runtime created")}async init(){this.log("info","Initializing runtime");const e=performance.now();try{this.container=this.resolveContainer(),this.assetLoader.preconnectAll(),this.pageLoader.preconnect(),customElements.get("djvlc-fallback")||customElements.define("djvlc-fallback",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).innerHTML='\n <style>\n :host {\n display: block;\n padding: 16px;\n background: #fff2f0;\n border: 1px solid #ffccc7;\n border-radius: 4px;\n color: #ff4d4f;\n font-size: 14px;\n }\n .title {\n font-weight: 600;\n margin-bottom: 8px;\n }\n .message {\n color: #666;\n }\n </style>\n <div class="title">组件加载失败</div>\n <div class="message"><slot>请刷新页面重试</slot></div>\n '}static get observedAttributes(){return["message","component-name"]}attributeChangedCallback(e,t,r){if("message"===e&&this.shadowRoot){const e=this.shadowRoot.querySelector(".message");e&&(e.textContent=r)}if("component-name"===e&&this.shadowRoot){const e=this.shadowRoot.querySelector(".title");e&&(e.textContent=`组件 ${r} 加载失败`)}}}),customElements.get("djvlc-blocked")||customElements.define("djvlc-blocked",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).innerHTML='\n <style>\n :host {\n display: block;\n padding: 16px;\n background: #fffbe6;\n border: 1px solid #ffe58f;\n border-radius: 4px;\n color: #faad14;\n font-size: 14px;\n }\n .icon {\n margin-right: 8px;\n }\n </style>\n <span class="icon">⚠️</span>\n <span>此组件已被暂停使用</span>\n '}}),customElements.get("djvlc-error-boundary")||customElements.define("djvlc-error-boundary",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).innerHTML="\n <style>\n :host {\n display: block;\n padding: 16px;\n background: #f5f5f5;\n border: 1px dashed #d9d9d9;\n border-radius: 4px;\n color: #999;\n font-size: 14px;\n text-align: center;\n }\n </style>\n <slot>渲染出错</slot>\n "}}),this.stateManager.setPhase("resolving");const t=performance.now()-e;this.log("info",`Runtime initialized in ${t.toFixed(2)}ms`)}catch(t){throw this.handleError(t),t}}async load(){var e;this.log("info","Loading page:",this.options.pageUid);const t=performance.now();try{this.stateManager.setPhase("resolving");const r=await this.pageLoader.resolve(this.options.pageUid,{uid:this.options.userId,deviceId:this.options.deviceId});this.stateManager.setPage(r),this.telemetryManager=new S({pageVersionId:r.pageVersionId,debug:this.options.debug,logger:this.logger,onMetric:this.options.onMetric}),r.runtimeConfig&&(this.securityManager.updateBlockedList(r.runtimeConfig.blockedComponents||[],r.runtimeConfig.killSwitches||[]),this.componentLoader.updateBlockedList((null==(e=r.runtimeConfig.blockedComponents)?void 0:e.map(e=>`${e.name}@${e.version}`))||[])),this.stateManager.setPhase("loading"),this.componentLoader.preload(r.manifest.components);(await this.componentLoader.loadAll(r.manifest)).forEach((e,t)=>{this.stateManager.setComponentStatus(t,e),this.telemetryManager.recordComponentLoad(e.name,e.version,e.loadTime||0,"loaded"===e.status)}),this.initHostApi(r),this.initRenderer();const s=performance.now()-t;return this.telemetryManager.recordPageLoad(s),this.log("info",`Page loaded in ${s.toFixed(2)}ms`),this.emitEvent("page:loaded",{page:r,loadTime:s}),r}catch(r){throw this.stateManager.setPhase("error"),this.handleError(r),r}}async render(){const e=this.stateManager.getState();if(!e.page||!this.container)throw new c("Page not loaded");this.log("info","Rendering page");const t=performance.now();try{this.stateManager.setPhase("rendering"),this.renderer.updateContext({state:e.variables,query:e.queries,context:{userId:this.options.userId,deviceId:this.options.deviceId,channel:this.options.channel,pageVersionId:e.page.pageVersionId}}),this.renderer.render(e.page.pageJson,this.container),this.stateManager.setPhase("ready");const r=performance.now()-t;this.telemetryManager.recordFirstRender(r),this.log("info",`Page rendered in ${r.toFixed(2)}ms`)}catch(r){throw this.stateManager.setPhase("error"),this.handleError(r),r}}getHostApi(){return this.hostApi}getState(){return this.stateManager.getState()}onStateChange(e){return this.stateManager.subscribe(e)}on(e,t){return this.eventBus.on(e,t)}updateComponent(e,t){this.renderer.updateComponent(e,t)}setVariable(e,t){this.stateManager.setVariable(e,t);const r=this.stateManager.getState();r.page&&this.container&&this.renderer.updateContext({state:r.variables})}async refreshData(e){const t=await this.hostApi.requestData(e);if(t.success){this.stateManager.setQuery(e,t.data);const r=this.stateManager.getState();this.renderer.updateContext({query:r.queries})}}destroy(){var e,t;this.log("info","Destroying runtime"),null==(e=this.telemetryManager)||e.flush(),null==(t=this.renderer)||t.destroy(),this.eventBus.clear(),this.stateManager.setDestroyed(),this.container&&(this.container.innerHTML=""),this.log("info","Runtime destroyed")}resolveContainer(){const{container:e}=this.options;if("string"==typeof e){const t=document.querySelector(e);if(!t)throw new Error(`Container not found: ${e}`);return t}return e}initHostApi(e){const t={pageUid:e.pageUid,pageVersionId:e.pageVersionId,runtimeVersion:"0.1.0",userId:this.options.userId,deviceId:this.options.deviceId,channel:this.options.channel,isEditMode:!1,isPreviewMode:e.isPreview||!1};this.hostApi=new w({apiBaseUrl:this.options.apiBaseUrl,authToken:this.options.authToken,headers:this.options.headers,stateManager:this.stateManager,eventBus:this.eventBus,expressionEngine:this.expressionEngine,context:t,debug:this.options.debug,logger:this.logger})}initRenderer(){const e=new Map;this.stateManager.getState().components.forEach((t,r)=>{if("loaded"===t.status&&t.component){const[s,n]=r.split("@");e.set(s,{name:s,version:n,Component:t.component,loadTime:t.loadTime||0})}}),this.renderer=new O({expressionEngine:this.expressionEngine,components:e,injectHostApi:(e,t)=>{e.hostApi=this.hostApi,e.componentId=t},debug:this.options.debug,logger:this.logger,onRenderError:(e,t)=>(this.log("error",`Render error in ${e}:`,t),this.emitEvent("component:error",{componentId:e,error:t.message}),function(e,t){const r=document.createElement("djvlc-error-boundary");return t&&r.setAttribute("message",t),r}(0,t.message))}),this.renderer.init()}handleError(e){var t;const r=e instanceof i?e:{type:"LOAD_ERROR",message:e.message,timestamp:Date.now()};this.stateManager.setError(r),null==(t=this.telemetryManager)||t.recordError(e),this.emitEvent("page:error",{error:e.message}),this.options.onError&&this.options.onError(r)}emitEvent(e,t){var r;const s=f.createEvent(e,t,null==(r=this.telemetryManager)?void 0:r.getTraceId());this.eventBus.emit(s),this.options.onEvent&&this.options.onEvent(s)}createLogger(){return{debug:(...e)=>{this.options.debug},info:(...e)=>{},warn:(...e)=>{},error:(...e)=>{}}}log(e,t,...r){this.logger[e](t,...r)}};const _="1.0.2";async function M(e,t){var r,s;const n=C({container:e,pageUid:t.pageUid,apiBaseUrl:t.apiBaseUrl,cdnBaseUrl:t.cdnBaseUrl,channel:t.channel,userId:t.userId,deviceId:t.deviceId,authToken:t.authToken,previewToken:t.previewToken,debug:t.debug,enableSRI:t.enableSRI,headers:t.headers,onError:t.onError?e=>{var r;return null==(r=t.onError)?void 0:r.call(t,new Error(e.message))}:void 0,onMetric:t.onMetric});try{await n.init(),await n.load(),await n.render(),null==(r=t.onLoad)||r.call(t,n.getState())}catch(o){const e=o instanceof Error?o:new Error(String(o));throw null==(s=t.onError)||s.call(t,e),e}return{runtime:n,destroy:()=>n.destroy()}}function D(e){e.forEach(e=>{const t=document.createElement("link");t.rel="preconnect",t.href=e.startsWith("http")?e:`https://${e}`,t.crossOrigin="anonymous",document.head.appendChild(t)})}function x(e,t=_){[`${e}/runtime/${t}/runtime.esm.js`,`${e}/runtime/${t}/runtime.css`].forEach(e=>{const t=document.createElement("link");t.rel="preload",t.href=e,t.as=e.endsWith(".js")?"script":"style",e.endsWith(".js")&&(t.crossOrigin="anonymous"),document.head.appendChild(t)})}function k(){const e="djv_device_id";let t=localStorage.getItem(e);if(!t){t=`${Date.now()}-${Math.random().toString(36).substring(2,11)}`;try{localStorage.setItem(e,t)}catch{}}return t}function L(){return e=32,Array.from({length:e},()=>Math.floor(16*Math.random()).toString(16)).join("");var e}function U(){return e=16,Array.from({length:e},()=>Math.floor(16*Math.random()).toString(16)).join("");var e}function P(){return`00-${L()}-${U()}-01`}const $={mount:M,preconnect:D,preloadAssets:x,getDeviceId:k,generateTraceId:L,generateSpanId:U,generateTraceparent:P,createRuntime:C,RUNTIME_VERSION:_};return e.RUNTIME_VERSION=_,e.createRuntime=C,e.default=$,e.generateSpanId=U,e.generateTraceId=L,e.generateTraceparent=P,e.getDeviceId=k,e.mount=M,e.preconnect=D,e.preloadAssets=x,Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),e}({});
1
+ var e=function(e){"use strict";const t="1.0.4";var r,n,i=Object.create,s=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,c=Object.getPrototypeOf,u=Object.prototype.hasOwnProperty,l=(e,t,r)=>(r=null!=e?i(c(e)):{},((e,t,r,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of o(t))u.call(e,i)||undefined===i||s(e,i,{get:()=>t[i],enumerable:!(n=a(t,i))||n.enumerable});return e})(s(r,"default",{value:e,enumerable:!0}),e)),h=(r={"../../node_modules/.pnpm/@djvlc+contracts-types@1.8.3/node_modules/@djvlc/contracts-types/dist/index.js"(e){var t=(e=>(e.SYSTEM="SYSTEM",e.AUTH="AUTH",e.PERMISSION="PERMISSION",e.RESOURCE="RESOURCE",e.VALIDATION="VALIDATION",e.BUSINESS="BUSINESS",e.RISK="RISK",e))(t||{}),r=(e=>(e.SYSTEM_INTERNAL_ERROR="SYSTEM_INTERNAL_ERROR",e.SYSTEM_SERVICE_UNAVAILABLE="SYSTEM_SERVICE_UNAVAILABLE",e.SYSTEM_TIMEOUT="SYSTEM_TIMEOUT",e.SYSTEM_DATABASE_ERROR="SYSTEM_DATABASE_ERROR",e.SYSTEM_REDIS_ERROR="SYSTEM_REDIS_ERROR",e.AUTH_TOKEN_MISSING="AUTH_TOKEN_MISSING",e.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",e.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",e.AUTH_SIGNATURE_INVALID="AUTH_SIGNATURE_INVALID",e.AUTH_SESSION_EXPIRED="AUTH_SESSION_EXPIRED",e.PERMISSION_DENIED="PERMISSION_DENIED",e.PERMISSION_RESOURCE_FORBIDDEN="PERMISSION_RESOURCE_FORBIDDEN",e.PERMISSION_ACTION_FORBIDDEN="PERMISSION_ACTION_FORBIDDEN",e.RESOURCE_NOT_FOUND="RESOURCE_NOT_FOUND",e.RESOURCE_PAGE_NOT_FOUND="RESOURCE_PAGE_NOT_FOUND",e.RESOURCE_COMPONENT_NOT_FOUND="RESOURCE_COMPONENT_NOT_FOUND",e.RESOURCE_ACTION_NOT_FOUND="RESOURCE_ACTION_NOT_FOUND",e.RESOURCE_VERSION_NOT_FOUND="RESOURCE_VERSION_NOT_FOUND",e.VALIDATION_INVALID_PARAMS="VALIDATION_INVALID_PARAMS",e.VALIDATION_SCHEMA_MISMATCH="VALIDATION_SCHEMA_MISMATCH",e.VALIDATION_EXPRESSION_ERROR="VALIDATION_EXPRESSION_ERROR",e.VALIDATION_FIELD_REQUIRED="VALIDATION_FIELD_REQUIRED",e.VALIDATION_FIELD_TYPE_ERROR="VALIDATION_FIELD_TYPE_ERROR",e.BUSINESS_ACTIVITY_NOT_STARTED="BUSINESS_ACTIVITY_NOT_STARTED",e.BUSINESS_ACTIVITY_ENDED="BUSINESS_ACTIVITY_ENDED",e.BUSINESS_ALREADY_CLAIMED="BUSINESS_ALREADY_CLAIMED",e.BUSINESS_ALREADY_SIGNED="BUSINESS_ALREADY_SIGNED",e.BUSINESS_STOCK_EXHAUSTED="BUSINESS_STOCK_EXHAUSTED",e.BUSINESS_QUOTA_EXCEEDED="BUSINESS_QUOTA_EXCEEDED",e.BUSINESS_PREREQUISITE_NOT_MET="BUSINESS_PREREQUISITE_NOT_MET",e.RISK_RATE_LIMITED="RISK_RATE_LIMITED",e.RISK_BLOCKED="RISK_BLOCKED",e.RISK_CAPTCHA_REQUIRED="RISK_CAPTCHA_REQUIRED",e.RISK_DEVICE_ABNORMAL="RISK_DEVICE_ABNORMAL",e.RISK_IDEMPOTENCY_CONFLICT="RISK_IDEMPOTENCY_CONFLICT",e.COMPONENT_LOAD_FAILED="COMPONENT_LOAD_FAILED",e.COMPONENT_INTEGRITY_MISMATCH="COMPONENT_INTEGRITY_MISMATCH",e.COMPONENT_BLOCKED="COMPONENT_BLOCKED",e.COMPONENT_DEPRECATED="COMPONENT_DEPRECATED",e.COMPONENT_INCOMPATIBLE="COMPONENT_INCOMPATIBLE",e.PUBLISH_VERSION_CONFLICT="PUBLISH_VERSION_CONFLICT",e.PUBLISH_VALIDATION_FAILED="PUBLISH_VALIDATION_FAILED",e.PUBLISH_ROLLBACK_FAILED="PUBLISH_ROLLBACK_FAILED",e))(r||{}),n={SYSTEM_INTERNAL_ERROR:500,SYSTEM_SERVICE_UNAVAILABLE:503,SYSTEM_TIMEOUT:504,SYSTEM_DATABASE_ERROR:500,SYSTEM_REDIS_ERROR:500,AUTH_TOKEN_MISSING:401,AUTH_TOKEN_INVALID:401,AUTH_TOKEN_EXPIRED:401,AUTH_SIGNATURE_INVALID:401,AUTH_SESSION_EXPIRED:401,PERMISSION_DENIED:403,PERMISSION_RESOURCE_FORBIDDEN:403,PERMISSION_ACTION_FORBIDDEN:403,RESOURCE_NOT_FOUND:404,RESOURCE_PAGE_NOT_FOUND:404,RESOURCE_COMPONENT_NOT_FOUND:404,RESOURCE_ACTION_NOT_FOUND:404,RESOURCE_VERSION_NOT_FOUND:404,VALIDATION_INVALID_PARAMS:400,VALIDATION_SCHEMA_MISMATCH:400,VALIDATION_EXPRESSION_ERROR:400,VALIDATION_FIELD_REQUIRED:400,VALIDATION_FIELD_TYPE_ERROR:400,BUSINESS_ACTIVITY_NOT_STARTED:422,BUSINESS_ACTIVITY_ENDED:422,BUSINESS_ALREADY_CLAIMED:422,BUSINESS_ALREADY_SIGNED:422,BUSINESS_STOCK_EXHAUSTED:422,BUSINESS_QUOTA_EXCEEDED:422,BUSINESS_PREREQUISITE_NOT_MET:422,RISK_RATE_LIMITED:429,RISK_BLOCKED:403,RISK_CAPTCHA_REQUIRED:428,RISK_DEVICE_ABNORMAL:403,RISK_IDEMPOTENCY_CONFLICT:409,COMPONENT_LOAD_FAILED:500,COMPONENT_INTEGRITY_MISMATCH:500,COMPONENT_BLOCKED:503,COMPONENT_DEPRECATED:410,COMPONENT_INCOMPATIBLE:500,PUBLISH_VERSION_CONFLICT:409,PUBLISH_VALIDATION_FAILED:400,PUBLISH_ROLLBACK_FAILED:500},i={SYSTEM_INTERNAL_ERROR:"系统内部错误",SYSTEM_SERVICE_UNAVAILABLE:"服务暂时不可用",SYSTEM_TIMEOUT:"请求超时",SYSTEM_DATABASE_ERROR:"数据库错误",SYSTEM_REDIS_ERROR:"缓存服务错误",AUTH_TOKEN_MISSING:"缺少认证令牌",AUTH_TOKEN_INVALID:"认证令牌无效",AUTH_TOKEN_EXPIRED:"认证令牌已过期",AUTH_SIGNATURE_INVALID:"签名无效",AUTH_SESSION_EXPIRED:"会话已过期",PERMISSION_DENIED:"权限不足",PERMISSION_RESOURCE_FORBIDDEN:"无权访问该资源",PERMISSION_ACTION_FORBIDDEN:"无权执行该操作",RESOURCE_NOT_FOUND:"资源不存在",RESOURCE_PAGE_NOT_FOUND:"页面不存在",RESOURCE_COMPONENT_NOT_FOUND:"组件不存在",RESOURCE_ACTION_NOT_FOUND:"动作不存在",RESOURCE_VERSION_NOT_FOUND:"版本不存在",VALIDATION_INVALID_PARAMS:"参数无效",VALIDATION_SCHEMA_MISMATCH:"Schema 不匹配",VALIDATION_EXPRESSION_ERROR:"表达式错误",VALIDATION_FIELD_REQUIRED:"必填字段缺失",VALIDATION_FIELD_TYPE_ERROR:"字段类型错误",BUSINESS_ACTIVITY_NOT_STARTED:"活动未开始",BUSINESS_ACTIVITY_ENDED:"活动已结束",BUSINESS_ALREADY_CLAIMED:"已经领取过",BUSINESS_ALREADY_SIGNED:"今日已签到",BUSINESS_STOCK_EXHAUSTED:"库存不足",BUSINESS_QUOTA_EXCEEDED:"超出配额限制",BUSINESS_PREREQUISITE_NOT_MET:"前置条件未满足",RISK_RATE_LIMITED:"请求过于频繁",RISK_BLOCKED:"请求被阻断",RISK_CAPTCHA_REQUIRED:"需要验证码验证",RISK_DEVICE_ABNORMAL:"设备异常",RISK_IDEMPOTENCY_CONFLICT:"重复请求",COMPONENT_LOAD_FAILED:"组件加载失败",COMPONENT_INTEGRITY_MISMATCH:"组件完整性校验失败",COMPONENT_BLOCKED:"组件已被阻断",COMPONENT_DEPRECATED:"组件已废弃",COMPONENT_INCOMPATIBLE:"组件版本不兼容",PUBLISH_VERSION_CONFLICT:"版本冲突",PUBLISH_VALIDATION_FAILED:"发布校验失败",PUBLISH_ROLLBACK_FAILED:"回滚失败"},s=(e=>(e.DRAFT="draft",e.STABLE="stable",e.DEPRECATED="deprecated",e.BLOCKED="blocked",e))(s||{}),a=(e=>(e.DRAFT="draft",e.PUBLISHED="published",e.ARCHIVED="archived",e))(a||{}),o=(e=>(e.PREVIEW="preview",e.GRAY="gray",e.PROD="prod",e))(o||{}),c=(e=>(e.PENDING="pending",e.PROCESSING="processing",e.SUCCESS="success",e.FAILED="failed",e.ROLLBACK="rollback",e))(c||{}),u=(e=>(e.PAGE_CREATE="page.create",e.PAGE_UPDATE="page.update",e.PAGE_DELETE="page.delete",e.PAGE_PUBLISH="page.publish",e.PAGE_ROLLBACK="page.rollback",e.COMPONENT_PUBLISH="component.publish",e.COMPONENT_BLOCK="component.block",e.COMPONENT_UNBLOCK="component.unblock",e.ACTION_EXECUTE="action.execute",e.DEFINITION_CREATE="definition.create",e.DEFINITION_UPDATE="definition.update",e.DEFINITION_PUBLISH="definition.publish",e.SYSTEM_KILL_SWITCH="system.kill_switch",e))(u||{}),l=[{name:"len",category:"string",description:"获取字符串长度",params:[{name:"str",type:"string",required:!0,description:"输入字符串"}],returnType:"number",pure:!0,examples:['len("hello") // 5',"len(state.name) // 动态获取"]},{name:"trim",category:"string",description:"去除首尾空白",params:[{name:"str",type:"string",required:!0,description:"输入字符串"}],returnType:"string",pure:!0,examples:['trim(" hello ") // "hello"']},{name:"upper",category:"string",description:"转换为大写",params:[{name:"str",type:"string",required:!0,description:"输入字符串"}],returnType:"string",pure:!0,examples:['upper("hello") // "HELLO"']},{name:"lower",category:"string",description:"转换为小写",params:[{name:"str",type:"string",required:!0,description:"输入字符串"}],returnType:"string",pure:!0,examples:['lower("HELLO") // "hello"']},{name:"substring",category:"string",description:"截取子字符串",params:[{name:"str",type:"string",required:!0,description:"输入字符串"},{name:"start",type:"number",required:!0,description:"起始位置"},{name:"end",type:"number",required:!1,description:"结束位置"}],returnType:"string",pure:!0,examples:['substring("hello", 0, 2) // "he"']},{name:"replace",category:"string",description:"替换字符串",params:[{name:"str",type:"string",required:!0,description:"输入字符串"},{name:"search",type:"string",required:!0,description:"搜索内容"},{name:"replacement",type:"string",required:!0,description:"替换内容"}],returnType:"string",pure:!0,examples:['replace("hello", "l", "x") // "hexxo"']},{name:"split",category:"string",description:"分割字符串为数组",params:[{name:"str",type:"string",required:!0,description:"输入字符串"},{name:"separator",type:"string",required:!0,description:"分隔符"}],returnType:"array",pure:!0,examples:['split("a,b,c", ",") // ["a", "b", "c"]']},{name:"join",category:"string",description:"合并数组为字符串",params:[{name:"arr",type:"array",required:!0,description:"输入数组"},{name:"separator",type:"string",required:!1,defaultValue:",",description:"分隔符"}],returnType:"string",pure:!0,examples:['join(["a", "b", "c"], "-") // "a-b-c"']},{name:"contains",category:"string",description:"检查是否包含子字符串",params:[{name:"str",type:"string",required:!0,description:"输入字符串"},{name:"search",type:"string",required:!0,description:"搜索内容"}],returnType:"boolean",pure:!0,examples:['contains("hello", "ell") // true']},{name:"startsWith",category:"string",description:"检查是否以指定前缀开始",params:[{name:"str",type:"string",required:!0,description:"输入字符串"},{name:"prefix",type:"string",required:!0,description:"前缀"}],returnType:"boolean",pure:!0,examples:['startsWith("hello", "he") // true']},{name:"endsWith",category:"string",description:"检查是否以指定后缀结束",params:[{name:"str",type:"string",required:!0,description:"输入字符串"},{name:"suffix",type:"string",required:!0,description:"后缀"}],returnType:"boolean",pure:!0,examples:['endsWith("hello", "lo") // true']}],h=[{name:"toNumber",category:"number",description:"转换为数字",params:[{name:"value",type:"any",required:!0,description:"输入值"},{name:"defaultValue",type:"number",required:!1,defaultValue:0,description:"默认值"}],returnType:"number",pure:!0,examples:['toNumber("123") // 123','toNumber("abc", 0) // 0']},{name:"round",category:"number",description:"四舍五入",params:[{name:"value",type:"number",required:!0,description:"输入数字"},{name:"decimals",type:"number",required:!1,defaultValue:0,description:"小数位数"}],returnType:"number",pure:!0,examples:["round(3.14159, 2) // 3.14"]},{name:"floor",category:"number",description:"向下取整",params:[{name:"value",type:"number",required:!0,description:"输入数字"}],returnType:"number",pure:!0,examples:["floor(3.7) // 3"]},{name:"ceil",category:"number",description:"向上取整",params:[{name:"value",type:"number",required:!0,description:"输入数字"}],returnType:"number",pure:!0,examples:["ceil(3.2) // 4"]},{name:"abs",category:"number",description:"绝对值",params:[{name:"value",type:"number",required:!0,description:"输入数字"}],returnType:"number",pure:!0,examples:["abs(-5) // 5"]},{name:"min",category:"number",description:"最小值",params:[{name:"values",type:"number",required:!0,variadic:!0,description:"数字列表"}],returnType:"number",pure:!0,examples:["min(1, 2, 3) // 1"]},{name:"max",category:"number",description:"最大值",params:[{name:"values",type:"number",required:!0,variadic:!0,description:"数字列表"}],returnType:"number",pure:!0,examples:["max(1, 2, 3) // 3"]},{name:"clamp",category:"number",description:"限制范围",params:[{name:"value",type:"number",required:!0,description:"输入数字"},{name:"min",type:"number",required:!0,description:"最小值"},{name:"max",type:"number",required:!0,description:"最大值"}],returnType:"number",pure:!0,examples:["clamp(5, 0, 3) // 3"]}],d=[{name:"length",category:"array",description:"获取数组长度",params:[{name:"arr",type:"array",required:!0,description:"输入数组"}],returnType:"number",pure:!0,examples:["length([1, 2, 3]) // 3"]},{name:"first",category:"array",description:"获取第一个元素",params:[{name:"arr",type:"array",required:!0,description:"输入数组"}],returnType:"any",pure:!0,examples:["first([1, 2, 3]) // 1"]},{name:"last",category:"array",description:"获取最后一个元素",params:[{name:"arr",type:"array",required:!0,description:"输入数组"}],returnType:"any",pure:!0,examples:["last([1, 2, 3]) // 3"]},{name:"at",category:"array",description:"获取指定索引的元素",params:[{name:"arr",type:"array",required:!0,description:"输入数组"},{name:"index",type:"number",required:!0,description:"索引"}],returnType:"any",pure:!0,examples:["at([1, 2, 3], 1) // 2"]},{name:"includes",category:"array",description:"检查是否包含元素",params:[{name:"arr",type:"array",required:!0,description:"输入数组"},{name:"value",type:"any",required:!0,description:"搜索值"}],returnType:"boolean",pure:!0,examples:["includes([1, 2, 3], 2) // true"]},{name:"slice",category:"array",description:"截取数组",params:[{name:"arr",type:"array",required:!0,description:"输入数组"},{name:"start",type:"number",required:!0,description:"起始位置"},{name:"end",type:"number",required:!1,description:"结束位置"}],returnType:"array",pure:!0,examples:["slice([1, 2, 3, 4], 1, 3) // [2, 3]"]},{name:"concat",category:"array",description:"合并数组",params:[{name:"arrays",type:"array",required:!0,variadic:!0,description:"数组列表"}],returnType:"array",pure:!0,examples:["concat([1, 2], [3, 4]) // [1, 2, 3, 4]"]},{name:"unique",category:"array",description:"去重",params:[{name:"arr",type:"array",required:!0,description:"输入数组"}],returnType:"array",pure:!0,examples:["unique([1, 2, 2, 3]) // [1, 2, 3]"]},{name:"reverse",category:"array",description:"反转数组",params:[{name:"arr",type:"array",required:!0,description:"输入数组"}],returnType:"array",pure:!0,examples:["reverse([1, 2, 3]) // [3, 2, 1]"]},{name:"sum",category:"array",description:"求和",params:[{name:"arr",type:"array",required:!0,description:"数字数组"}],returnType:"number",pure:!0,examples:["sum([1, 2, 3]) // 6"]},{name:"average",category:"array",description:"平均值",params:[{name:"arr",type:"array",required:!0,description:"数字数组"}],returnType:"number",pure:!0,examples:["average([1, 2, 3]) // 2"]}],p=[{name:"now",category:"date",description:"当前时间戳",params:[],returnType:"number",pure:!1,examples:["now() // 1704067200000"]},{name:"today",category:"date",description:"今天日期(YYYY-MM-DD)",params:[],returnType:"string",pure:!1,examples:['today() // "2024-01-01"']},{name:"dateFormat",category:"date",description:"格式化日期",params:[{name:"date",type:"any",required:!0,description:"日期(时间戳或字符串)"},{name:"format",type:"string",required:!0,description:"格式模板"}],returnType:"string",pure:!0,examples:['dateFormat(now(), "YYYY-MM-DD") // "2024-01-01"']},{name:"dateParse",category:"date",description:"解析日期字符串",params:[{name:"str",type:"string",required:!0,description:"日期字符串"},{name:"format",type:"string",required:!1,description:"格式模板"}],returnType:"number",pure:!0,examples:['dateParse("2024-01-01") // 1704067200000']},{name:"dateAdd",category:"date",description:"日期加减",params:[{name:"date",type:"any",required:!0,description:"日期"},{name:"amount",type:"number",required:!0,description:"数量"},{name:"unit",type:"string",required:!0,description:"单位(day/week/month/year)"}],returnType:"number",pure:!0,examples:['dateAdd(now(), 7, "day") // 一周后']},{name:"dateDiff",category:"date",description:"日期差",params:[{name:"date1",type:"any",required:!0,description:"日期1"},{name:"date2",type:"any",required:!0,description:"日期2"},{name:"unit",type:"string",required:!1,defaultValue:"day",description:"单位"}],returnType:"number",pure:!0,examples:['dateDiff("2024-01-10", "2024-01-01", "day") // 9']}],m=[{name:"if",category:"logic",description:"条件判断",params:[{name:"condition",type:"boolean",required:!0,description:"条件"},{name:"trueValue",type:"any",required:!0,description:"条件为真时的值"},{name:"falseValue",type:"any",required:!0,description:"条件为假时的值"}],returnType:"any",pure:!0,examples:['if(state.count > 0, "有", "无")']},{name:"and",category:"logic",description:"逻辑与",params:[{name:"values",type:"boolean",required:!0,variadic:!0,description:"布尔值列表"}],returnType:"boolean",pure:!0,examples:["and(true, true, false) // false"]},{name:"or",category:"logic",description:"逻辑或",params:[{name:"values",type:"boolean",required:!0,variadic:!0,description:"布尔值列表"}],returnType:"boolean",pure:!0,examples:["or(true, false) // true"]},{name:"not",category:"logic",description:"逻辑非",params:[{name:"value",type:"boolean",required:!0,description:"布尔值"}],returnType:"boolean",pure:!0,examples:["not(true) // false"]},{name:"eq",category:"logic",description:"相等判断",params:[{name:"a",type:"any",required:!0,description:"值1"},{name:"b",type:"any",required:!0,description:"值2"}],returnType:"boolean",pure:!0,examples:["eq(1, 1) // true"]},{name:"ne",category:"logic",description:"不相等判断",params:[{name:"a",type:"any",required:!0,description:"值1"},{name:"b",type:"any",required:!0,description:"值2"}],returnType:"boolean",pure:!0,examples:["ne(1, 2) // true"]},{name:"gt",category:"logic",description:"大于",params:[{name:"a",type:"number",required:!0,description:"值1"},{name:"b",type:"number",required:!0,description:"值2"}],returnType:"boolean",pure:!0,examples:["gt(2, 1) // true"]},{name:"gte",category:"logic",description:"大于等于",params:[{name:"a",type:"number",required:!0,description:"值1"},{name:"b",type:"number",required:!0,description:"值2"}],returnType:"boolean",pure:!0,examples:["gte(2, 2) // true"]},{name:"lt",category:"logic",description:"小于",params:[{name:"a",type:"number",required:!0,description:"值1"},{name:"b",type:"number",required:!0,description:"值2"}],returnType:"boolean",pure:!0,examples:["lt(1, 2) // true"]},{name:"lte",category:"logic",description:"小于等于",params:[{name:"a",type:"number",required:!0,description:"值1"},{name:"b",type:"number",required:!0,description:"值2"}],returnType:"boolean",pure:!0,examples:["lte(2, 2) // true"]}],f=[{name:"default",category:"utility",description:"默认值",params:[{name:"value",type:"any",required:!0,description:"输入值"},{name:"defaultValue",type:"any",required:!0,description:"默认值"}],returnType:"any",pure:!0,examples:['default(state.name, "未知")']},{name:"coalesce",category:"utility",description:"返回第一个非空值",params:[{name:"values",type:"any",required:!0,variadic:!0,description:"值列表"}],returnType:"any",pure:!0,examples:['coalesce(null, undefined, "value") // "value"']},{name:"isEmpty",category:"utility",description:"检查是否为空",params:[{name:"value",type:"any",required:!0,description:"输入值"}],returnType:"boolean",pure:!0,examples:['isEmpty("") // true',"isEmpty([]) // true"]},{name:"isNull",category:"utility",description:"检查是否为 null/undefined",params:[{name:"value",type:"any",required:!0,description:"输入值"}],returnType:"boolean",pure:!0,examples:["isNull(null) // true"]},{name:"type",category:"utility",description:"获取值类型",params:[{name:"value",type:"any",required:!0,description:"输入值"}],returnType:"string",pure:!0,examples:['type([]) // "array"','type({}) // "object"']},{name:"toString",category:"type",description:"转换为字符串",params:[{name:"value",type:"any",required:!0,description:"输入值"}],returnType:"string",pure:!0,examples:['toString(123) // "123"']},{name:"toBoolean",category:"type",description:"转换为布尔值",params:[{name:"value",type:"any",required:!0,description:"输入值"}],returnType:"boolean",pure:!0,examples:['toBoolean("true") // true',"toBoolean(1) // true"]},{name:"toJSON",category:"utility",description:"转换为 JSON 字符串",params:[{name:"value",type:"any",required:!0,description:"输入值"}],returnType:"string",pure:!0,examples:['toJSON({a: 1}) // "{\\"a\\":1}"']},{name:"fromJSON",category:"utility",description:"解析 JSON 字符串",params:[{name:"str",type:"string",required:!0,description:"JSON 字符串"}],returnType:"any",pure:!0,examples:['fromJSON("{\\"a\\":1}") // {a: 1}']},{name:"get",category:"object",description:"获取嵌套属性",params:[{name:"obj",type:"object",required:!0,description:"输入对象"},{name:"path",type:"string",required:!0,description:"属性路径(点分隔)"},{name:"defaultValue",type:"any",required:!1,description:"默认值"}],returnType:"any",pure:!0,examples:['get(state, "user.name", "未知")']}],y=[{name:"currency",category:"format",description:"格式化货币",params:[{name:"value",type:"number",required:!0,description:"金额"},{name:"symbol",type:"string",required:!1,defaultValue:"¥",description:"货币符号"},{name:"decimals",type:"number",required:!1,defaultValue:2,description:"小数位数"}],returnType:"string",pure:!0,examples:['currency(1234.5) // "¥1,234.50"']},{name:"percent",category:"format",description:"格式化百分比",params:[{name:"value",type:"number",required:!0,description:"数值(0-1)"},{name:"decimals",type:"number",required:!1,defaultValue:0,description:"小数位数"}],returnType:"string",pure:!0,examples:['percent(0.1234) // "12%"']},{name:"number",category:"format",description:"格式化数字(千分位)",params:[{name:"value",type:"number",required:!0,description:"数值"},{name:"decimals",type:"number",required:!1,defaultValue:0,description:"小数位数"}],returnType:"string",pure:!0,examples:['number(1234567) // "1,234,567"']},{name:"pluralize",category:"format",description:"复数形式",params:[{name:"count",type:"number",required:!0,description:"数量"},{name:"singular",type:"string",required:!0,description:"单数形式"},{name:"plural",type:"string",required:!0,description:"复数形式"}],returnType:"string",pure:!0,examples:['pluralize(1, "item", "items") // "1 item"']},{name:"mask",category:"format",description:"掩码处理",params:[{name:"str",type:"string",required:!0,description:"输入字符串"},{name:"keepPrefix",type:"number",required:!1,defaultValue:3,description:"保留前缀"},{name:"keepSuffix",type:"number",required:!1,defaultValue:4,description:"保留后缀"},{name:"maskChar",type:"string",required:!1,defaultValue:"*",description:"掩码字符"}],returnType:"string",pure:!0,examples:['mask("13812345678", 3, 4) // "138****5678"']}],g=[...l,...h,...d,...p,...m,...f,...y],b=g.map(e=>e.name),v={allowedContextPaths:["state","binding","local","props","event"],allowedFunctions:b,maxDepth:10,maxLength:1e3,allowTemplate:!0,allowChaining:!0},w={STATE:"state",BINDING:"binding",LOCAL:"local",PROPS:"props",EVENT:"event"};function E(e,t){return`${e}.${t}`}var S=/^[A-Za-z_][A-Za-z0-9_-]*$/,I=/\b(state|binding|local|props|event)\.[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\.\d+|\[\d+\])*/g,T=/\b[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\.\d+|\[\d+\])*\b/g,N=new Set(["true","false","null","undefined","NaN","Infinity","typeof","instanceof","new","void","delete","Math","Date","JSON","Array","Object","String","Number","Boolean"]),A=["state","binding","local","props","event"];function O(e){const t=new Set;for(const r of e.matchAll(I))t.add(r[0]);return[...t]}function R(e){const t=new Set;for(const r of e.matchAll(T)){const e=r[0];N.has(e)||A.some(t=>e.startsWith(`${t}.`))||A.includes(e)||t.add(e)}return[...t]}var _=class extends Error{constructor(e,t,r){super(e),this.bareVariables=t,this.expression=r,this.name="TemplateParseError"}},$=(e=>(e.CLAIM="claim",e.SIGNIN="signin",e.LOTTERY="lottery",e.RESERVE="reserve",e.BIND="bind",e.TASK_COMPLETE="task_complete",e.VOTE="vote",e.SHARE="share",e.FORM_SUBMIT="form_submit",e.CUSTOM="custom",e))($||{});e.ALLOWED_FUNCTION_NAMES=b,e.ALL_BUILTIN_FUNCTIONS=g,e.ARRAY_FUNCTIONS=d,e.ActionType=$,e.AuditAction=u,e.CURRENT_ACTION_SPEC_VERSION="1.0.0",e.CURRENT_COMPONENT_META_VERSION="1.0.0",e.CURRENT_DATA_QUERY_SPEC_VERSION="1.0.0",e.CURRENT_SCHEMA_VERSION="1.0.0",e.DATE_FUNCTIONS=p,e.DEFAULT_EXPRESSION_VALIDATION_CONFIG=v,e.DEPENDENCY_PREFIX=w,e.ErrorCategory=t,e.ErrorCode=r,e.ErrorCodeToHttpStatus=n,e.ErrorMessages=i,e.FORMAT_FUNCTIONS=y,e.LOGIC_FUNCTIONS=m,e.NUMBER_FUNCTIONS=h,e.PROTOCOL_VERSION="1.0.0",e.PageStatus=a,e.PublishChannel=o,e.PublishStatus=c,e.STRING_FUNCTIONS=l,e.TemplateParseError=_,e.UTILITY_FUNCTIONS=f,e.VERSION="1.0.0",e.VersionStatus=s,e.bindingRef=function(e,t,r){if(!S.test(e))throw new Error(`Invalid bindingId: "${e}". Must match pattern [A-Za-z_][A-Za-z0-9_-]* (no dots allowed).`);return{type:"binding",value:`${e}.${t}`,fallback:r,meta:{dependencies:[E(w.BINDING,`${e}.${t}`)]}}},e.createDjvlcError=function(e,t,r){const s=n[e]||500,a=new Error(t||i[e]||"未知错误");return a.name="DjvlcError",a.code=e,a.httpStatus=s,a.details=r,a},e.createExpressionContext=function(e){return{state:{},binding:{},local:{},...e}},e.createLoopLocal=function(e,t,r){return{...r,item:e,index:t}},e.dep=E,e.isDjvlcError=function(e){return e instanceof Error&&"code"in e&&"httpStatus"in e&&"DjvlcError"===e.name},e.localRef=function(e,t){return{type:"local",value:e,fallback:t,meta:{dependencies:[E(w.LOCAL,e)]}}},e.stateRef=function(e,t){return{type:"state",value:e,fallback:t,meta:{dependencies:[E(w.STATE,e)]}}},e.template=function(e,t){const r=function(e,t="strict"){const r=new Set,n=/\$\{([^}]+)\}/g;for(const i of e.matchAll(n)){const e=(i[1]??"").trim();if(!e)continue;const n=O(e);for(const t of n)r.add(t);if("strict"===t){const t=R(e);if(t.length>0)throw new _(`Template variable must use prefix (state./binding./local./props./event.). Found bare variables: ${t.join(", ")} in \${${e}}`,t,e)}}return[...r]}(e,"strict");return{type:"template",value:e,fallback:t,meta:{dependencies:r}}}}},function(){return n||(0,r[o(r)[0]])((n={exports:{}}).exports,n),n.exports}),d=l(h()),p=l(h()),m=class extends Error{constructor(e,t,r,n){super(t||p.ErrorMessages[e]||"Unknown error"),this.name="DjvlcRuntimeError",this.code=e,this.details=r,this.traceId=n,this.timestamp=Date.now()}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,traceId:this.traceId,timestamp:this.timestamp}}},f=class extends m{constructor(e,t,r){super(p.ErrorCode.RESOURCE_PAGE_NOT_FOUND,e,t,r),this.name="PageLoadError"}},y=class extends m{constructor(e,t,r,n=p.ErrorCode.COMPONENT_LOAD_FAILED,i){super(n,r,{...i,componentName:e,componentVersion:t}),this.name="ComponentLoadError",this.componentName=e,this.componentVersion=t}},g=class extends m{constructor(e,t,r,n){super(p.ErrorCode.COMPONENT_INTEGRITY_MISMATCH,`Integrity check failed for ${e}@${t}`,{expectedHash:r,actualHash:n}),this.name="IntegrityError",this.componentName=e,this.componentVersion=t,this.expectedHash=r,this.actualHash=n}},b=class extends m{constructor(e,t,r){super(p.ErrorCode.COMPONENT_BLOCKED,`Component ${e}@${t} is blocked`,{componentName:e,componentVersion:t,reason:r}),this.name="ComponentBlockedError",this.componentName=e,this.componentVersion=t,this.reason=r}},v=class extends m{constructor(e,t,r,n){super(p.ErrorCode.VALIDATION_EXPRESSION_ERROR,t,{...n,expression:e,position:r}),this.name="ExpressionError",this.expression=e,this.position=r}},w=class extends m{constructor(e,t,r=p.ErrorCode.SYSTEM_INTERNAL_ERROR,n,i){super(r,t,{...i,actionType:e,actionId:n}),this.name="ActionError",this.actionType=e,this.actionId=n}},E=class extends m{constructor(e,t,r=p.ErrorCode.SYSTEM_INTERNAL_ERROR,n){super(r,t,{...n,queryId:e}),this.name="QueryError",this.queryId=e}},S=class{constructor(e){this.cache=new Map,this.options={channel:"prod",cache:{enabled:!0,maxAge:300},...e}}async resolve(e,t){var r,n;const i=this.getCacheKey(e,t);if(null==(r=this.options.cache)?void 0:r.enabled){const t=this.cache.get(i);if(t&&this.isCacheValid(t.timestamp))return this.log("debug",`Page ${e} loaded from cache`),t.data}const s=performance.now();try{const r=this.buildResolveUrl(e,t),a=await fetch(r,{method:"GET",headers:this.buildHeaders()});if(!a.ok)throw new f(`Failed to resolve page: ${a.status} ${a.statusText}`,{pageUid:e,status:a.status});const o=await a.json();if(!this.isValidPageResolveResult(o))throw new f("Invalid page resolve response",{pageUid:e});const c=o.data;(null==(n=this.options.cache)?void 0:n.enabled)&&this.cache.set(i,{data:c,timestamp:Date.now()});const u=performance.now()-s;return this.log("info",`Page ${e} resolved in ${u.toFixed(2)}ms`),c}catch(a){if(a instanceof f)throw a;throw new f(`Failed to resolve page: ${a instanceof Error?a.message:"Unknown error"}`,{pageUid:e})}}preconnect(){const e=document.createElement("link");e.rel="preconnect",e.href=this.options.apiBaseUrl,document.head.appendChild(e)}clearCache(e){if(e)for(const t of this.cache.keys())t.startsWith(e)&&this.cache.delete(t);else this.cache.clear()}buildResolveUrl(e,t){const r=new URL(`${this.options.apiBaseUrl}/page/resolve`);return r.searchParams.set("pageUid",e),this.options.channel&&r.searchParams.set("channel",this.options.channel),this.options.previewToken&&r.searchParams.set("previewToken",this.options.previewToken),(null==t?void 0:t.uid)&&r.searchParams.set("uid",t.uid),(null==t?void 0:t.deviceId)&&r.searchParams.set("deviceId",t.deviceId),r.toString()}buildHeaders(){const e={"Content-Type":"application/json",...this.options.headers};return this.options.authToken&&(e.Authorization=`Bearer ${this.options.authToken}`),e}getCacheKey(e,t){const r=[e,this.options.channel];return(null==t?void 0:t.uid)&&r.push(t.uid),(null==t?void 0:t.deviceId)&&r.push(t.deviceId),r.join(":")}isCacheValid(e){var t;const r=1e3*((null==(t=this.options.cache)?void 0:t.maxAge)??300);return Date.now()-e<r}isValidPageResolveResult(e){if(!e||"object"!=typeof e)return!1;const t=e;if(!t.data||"object"!=typeof t.data)return!1;const r=t.data;return"string"==typeof r.pageUid&&"string"==typeof r.pageVersionId&&void 0!==r.pageJson&&void 0!==r.manifest}log(e,t){this.options.logger&&this.options.logger[e](t)}},I=class{constructor(e){this.loadedComponents=new Map,this.loadingPromises=new Map,this.options={enableSRI:!0,concurrency:4,timeout:3e4,blockedComponents:[],...e},this.blockedSet=new Set(this.options.blockedComponents)}async load(e){const t=this.getComponentKey(e.name,e.version);if(this.isBlocked(e.name,e.version))throw new b(e.name,e.version,"Component is blocked");const r=this.loadedComponents.get(t);if(r)return r;const n=this.loadingPromises.get(t);if(n)return n;const i=this.loadComponent(e);this.loadingPromises.set(t,i);try{const e=await i;return this.loadedComponents.set(t,e),e}finally{this.loadingPromises.delete(t)}}async loadAll(e){const t=new Map,{concurrency:r=4}=this.options,n=e.components;for(let i=0;i<n.length;i+=r){const e=n.slice(i,i+r).map(async e=>{const r=this.getComponentKey(e.name,e.version),n=performance.now();try{const i=await this.load(e);t.set(r,{name:e.name,version:e.version,status:"loaded",component:i.Component,loadTime:performance.now()-n})}catch(i){const s=i instanceof b?"blocked":"failed";if(t.set(r,{name:e.name,version:e.version,status:s,error:i instanceof Error?i.message:"Unknown error",loadTime:performance.now()-n}),"critical"===e.priority)throw i}});await Promise.all(e)}return t}preload(e){e.forEach(e=>{const t=document.createElement("link");t.rel="preload",t.as="script",t.href=this.resolveUrl(e.entry),this.options.enableSRI&&e.integrity&&(t.integrity=e.integrity,t.crossOrigin="anonymous"),document.head.appendChild(t)})}isLoaded(e,t){return this.loadedComponents.has(this.getComponentKey(e,t))}get(e,t){return this.loadedComponents.get(this.getComponentKey(e,t))}isBlocked(e,t){return this.blockedSet.has(`${e}@${t}`)||this.blockedSet.has(e)}updateBlockedList(e){this.blockedSet=new Set(e)}async loadComponent(e){const t=performance.now(),r=this.resolveUrl(e.entry);this.log("debug",`Loading component ${e.name}@${e.version}`);try{const n=await this.fetchWithTimeout(r);if(!n.ok)throw new y(e.name,e.version,`Failed to fetch component: ${n.status} ${n.statusText}`);const i=await n.text();this.options.enableSRI&&e.integrity&&await this.validateIntegrity(e,i);const s=await this.executeScript(i,e),a=performance.now()-t;return this.log("info",`Component ${e.name}@${e.version} loaded in ${a.toFixed(2)}ms`),{name:e.name,version:e.version,Component:s,loadTime:a}}catch(n){if(n instanceof y||n instanceof g||n instanceof b)throw n;throw new y(e.name,e.version,`Failed to load component: ${n instanceof Error?n.message:"Unknown error"}`)}}async fetchWithTimeout(e){const t=new AbortController,r=setTimeout(()=>t.abort(),this.options.timeout);try{return await fetch(e,{signal:t.signal,credentials:"omit"})}finally{clearTimeout(r)}}async validateIntegrity(e,t){if(!e.integrity)return;const[r,n]=e.integrity.split("-");if(!r||!n)throw new g(e.name,e.version,e.integrity,"Invalid format");const i=await crypto.subtle.digest(r.toUpperCase(),(new TextEncoder).encode(t)),s=Array.from(new Uint8Array(i)),a=btoa(String.fromCharCode(...s));if(a!==n)throw new g(e.name,e.version,n,a)}async executeScript(e,t){const r=new Blob([e],{type:"application/javascript"}),n=URL.createObjectURL(r);try{const e=await import(n),r=e.default||e[t.name]||e.Component;if(!r)throw new y(t.name,t.version,"Component module does not export a valid component");return r}finally{URL.revokeObjectURL(n)}}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")?e:`${this.options.cdnBaseUrl}/${e.replace(/^\//,"")}`}getComponentKey(e,t){return`${e}@${t}`}log(e,t){this.options.logger&&this.options.logger[e](t)}},T=class{constructor(e){this.preconnectedHosts=new Set,this.preloadedAssets=new Set,this.options=e}preconnectAll(){[...this.options.cdnHosts,...this.options.apiHosts].forEach(e=>this.preconnect(e))}preconnect(e){if(this.preconnectedHosts.has(e))return;const t=document.createElement("link");t.rel="preconnect",t.href=e.startsWith("http")?e:`https://${e}`,t.crossOrigin="anonymous",document.head.appendChild(t),this.preconnectedHosts.add(e)}dnsPrefetch(e){const t=document.createElement("link");t.rel="dns-prefetch",t.href=e.startsWith("http")?e:`https://${e}`,document.head.appendChild(t)}preloadScript(e,t){if(this.preloadedAssets.has(e))return;const r=document.createElement("link");r.rel="preload",r.as="script",r.href=e,t&&(r.integrity=t,r.crossOrigin="anonymous"),document.head.appendChild(r),this.preloadedAssets.add(e)}preloadStyle(e,t){if(this.preloadedAssets.has(e))return;const r=document.createElement("link");r.rel="preload",r.as="style",r.href=e,t&&(r.integrity=t,r.crossOrigin="anonymous"),document.head.appendChild(r),this.preloadedAssets.add(e)}preloadImage(e){if(this.preloadedAssets.has(e))return;const t=document.createElement("link");t.rel="preload",t.as="image",t.href=e,document.head.appendChild(t),this.preloadedAssets.add(e)}prefetch(e,t){const r=document.createElement("link");r.rel="prefetch",r.href=e,t&&(r.as=t),document.head.appendChild(r)}loadStylesheet(e,t){return new Promise((r,n)=>{const i=document.createElement("link");i.rel="stylesheet",i.href=e,t&&(i.integrity=t,i.crossOrigin="anonymous"),i.onload=()=>r(),i.onerror=()=>n(new Error(`Failed to load stylesheet: ${e}`)),document.head.appendChild(i)})}loadScript(e,t){return new Promise((r,n)=>{const i=document.createElement("script");i.src=e,i.async=!0,t&&(i.integrity=t,i.crossOrigin="anonymous"),i.onload=()=>r(),i.onerror=()=>n(new Error(`Failed to load script: ${e}`)),document.body.appendChild(i)})}},N=class{constructor(){this.listeners=new Set,this.changeCallbacks=new Set,this.state=this.createInitialState()}getState(){return this.state}getPhase(){return this.state.phase}setPhase(e){this.setState({phase:e})}setPage(e){const t=e.pageJson,r=this.initializePageState(t);e.preloadedData&&Object.assign(r,e.preloadedData),this.setState({page:e,variables:r})}initializePageState(e){const t={};if(e.state&&e.state.fields)for(const[r,n]of Object.entries(e.state.fields))if(n&&"object"==typeof n){const e=n;t[r]=e.initialValue}return t}setError(e){this.setState({phase:"error",error:e})}clearError(){this.state.error&&this.setState({error:null})}getVariable(e){return e.includes(".")?this.getNestedValue(this.state.variables,e):this.state.variables[e]}setVariable(e,t){const r=this.getVariable(e);if(e.includes(".")){const r={...this.state.variables};this.setNestedValue(r,e,t),this.setState({variables:r})}else this.setState({variables:{...this.state.variables,[e]:t}});this.notifyChange({key:e,oldValue:r,newValue:t})}setVariables(e){const t=[];for(const[r,n]of Object.entries(e)){const e=this.getVariable(r);t.push({key:r,oldValue:e,newValue:n})}this.setState({variables:{...this.state.variables,...e}}),t.forEach(e=>this.notifyChange(e))}getQuery(e){return this.state.queries[e]}setQuery(e,t){this.setState({queries:{...this.state.queries,[e]:t}})}clearQuery(e){const{[e]:t,...r}=this.state.queries;this.setState({queries:r})}setComponentStatus(e,t){const r=new Map(this.state.components);r.set(e,t),this.setState({components:r})}getComponentStatus(e){return this.state.components.get(e)}setDestroyed(){this.setState({phase:"destroyed",destroyed:!0})}isDestroyed(){return this.state.destroyed}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}onStateChange(e){return this.changeCallbacks.add(e),()=>{this.changeCallbacks.delete(e)}}reset(){this.state=this.createInitialState(),this.notifyListeners()}getExpressionContext(){var e,t;return{state:this.state.variables,binding:this.state.queries,local:{},context:{pageVersionId:null==(e=this.state.page)?void 0:e.pageVersionId,pageUid:null==(t=this.state.page)?void 0:t.pageUid,phase:this.state.phase,$now:Date.now()}}}setState(e){this.state={...this.state,...e},this.notifyListeners()}notifyListeners(){this.listeners.forEach(e=>{try{e(this.state)}catch(t){}})}notifyChange(e){this.changeCallbacks.forEach(t=>{try{t(e)}catch(r){}})}getNestedValue(e,t){const r=t.split(".");let n=e;for(const i of r){if(null==n)return;n=n[i]}return n}setNestedValue(e,t,r){const n=t.split(".");let i=e;for(let s=0;s<n.length-1;s++){const e=n[s];void 0!==i[e]&&null!==i[e]||(i[e]={}),i=i[e]}i[n[n.length-1]]=r}createInitialState(){return{phase:"idle",page:null,variables:{},queries:{},components:new Map,error:null,destroyed:!1}}},A=class{constructor(e){this.bindings=new Map,this.dependencyGraph=new Map,this.bindingDependencies=new Map,this.options=e}registerBindings(e){for(const t of e)this.registerBinding(t)}registerBinding(e){if(this.bindings.set(e.id,{binding:e,loading:!1,retryCount:0}),e.dependencies)for(const t of e.dependencies)this.dependencyGraph.has(t)||this.dependencyGraph.set(t,new Set),this.dependencyGraph.get(t).add(e.id);this.updateBindingDependencies(e),this.log("debug",`Registered data binding: ${e.id}`)}updateBindingDependencies(e){var t;for(const[r,n]of this.bindings)r!==e.id&&(null==(t=n.binding.dependencies)?void 0:t.includes(e.targetState))&&(this.bindingDependencies.has(e.id)||this.bindingDependencies.set(e.id,new Set),this.bindingDependencies.get(e.id).add(r));if(e.dependencies)for(const r of e.dependencies)for(const[t,n]of this.bindings)t!==e.id&&n.binding.targetState===r&&(this.bindingDependencies.has(t)||this.bindingDependencies.set(t,new Set),this.bindingDependencies.get(t).add(e.id))}async initializeBindings(e){var t,r;const n=[];for(const a of this.bindings.values())"eager"===a.binding.loadStrategy&&n.push(a.binding);const i=this.topologicalSort(n),s=this.createLoadBatches(i);for(const a of s){const n=await Promise.allSettled(a.map(t=>this.loadBinding(t.id,e))),i=new Map;n.forEach((e,t)=>{const r=a[t].id;"fulfilled"===e.status?i.set(r,{success:!0,data:e.value}):i.set(r,{success:!1,error:e.reason})}),null==(r=(t=this.options).onBatchComplete)||r.call(t,i)}}topologicalSort(e){const t=new Map(e.map(e=>[e.id,e])),r=new Set,n=[],i=e=>{if(!r.has(e.id)){if(r.add(e.id),e.dependencies)for(const n of e.dependencies)for(const[e,s]of t)s.targetState!==n||r.has(e)||i(s);n.push(e)}};for(const s of e)i(s);return n}createLoadBatches(e){const t=[],r=new Set;for(;r.size<e.length;){const n=[];for(const t of e){if(r.has(t.id))continue;let i=!0;if(t.dependencies)for(const n of t.dependencies){for(const t of e)if(t.targetState===n&&!r.has(t.id)){i=!1;break}if(!i)break}i&&n.push(t)}if(0===n.length)for(const t of e)if(!r.has(t.id)){n.push(t),this.log("warn",`Possible circular dependency detected at binding: ${t.id}`);break}n.forEach(e=>r.add(e.id)),n.length>0&&t.push(n)}return t}async loadBinding(e,t,r=!1){var n,i,s;const a=this.bindings.get(e);if(!a)throw new E(e,`Data binding not found: ${e}`);const{binding:o}=a;if(!o.condition||this.evaluateCondition(o.condition,t)){if(!r&&this.isCacheValid(a))return this.log("debug",`Binding ${e} returned from cache`),a.cachedData;if(a.loading)this.log("debug",`Binding ${e} is already loading`);else{a.loading=!0;try{const r=this.resolveParams(o.params||{},t),c=await this.executeWithRetry(o,r),u=o.transform?this.applyTransform(c,o.transform,t):c;return a.cachedData=u,a.lastLoadTime=Date.now(),(null==(n=o.cache)?void 0:n.ttl)&&(a.cacheExpireTime=Date.now()+1e3*o.cache.ttl),a.retryCount=0,this.options.stateSetter.setVariable(o.targetState,u),this.setupAutoRefresh(a,t),null==(s=(i=this.options).onDataLoaded)||s.call(i,e,u),this.log("info",`Binding ${e} loaded successfully`),u}catch(c){throw await this.handleLoadError(a,c,t),c}finally{a.loading=!1}}}else this.log("debug",`Binding ${e} skipped by condition`)}async refreshBinding(e,t){await this.loadBinding(e,t,!0)}async refreshAll(e){const t=Array.from(this.bindings.keys()).map(t=>this.loadBinding(t,e,!0));await Promise.allSettled(t)}async onStateChange(e,t){const r=this.dependencyGraph.get(e);if(!r||0===r.size)return;this.log("debug",`State ${e} changed, refreshing dependent bindings`);const n=Array.from(r).map(e=>this.loadBinding(e,t,!0));await Promise.allSettled(n)}async triggerManualLoad(e,t){const r=this.bindings.get(e);if(!r)throw new E(e,`Data binding not found: ${e}`);return"manual"!==r.binding.loadStrategy&&this.log("warn",`Binding ${e} is not manual strategy`),this.loadBinding(e,t,!0)}checkVisibility(e,t,r){const n=this.bindings.get(e);n&&"lazy"===n.binding.loadStrategy&&t&&!n.lastLoadTime&&this.loadBinding(e,r).catch(t=>{this.log("error",`Lazy binding ${e} failed to load`,t)})}destroy(){for(const e of this.bindings.values())e.refreshTimer&&clearInterval(e.refreshTimer);this.bindings.clear(),this.dependencyGraph.clear(),this.log("debug","DataBindingManager destroyed")}async executeWithRetry(e,t){var r,n,i,s,a,o;const c=(null==(n=null==(r=e.onError)?void 0:r.retry)?void 0:n.maxRetries)??0,u=(null==(s=null==(i=e.onError)?void 0:i.retry)?void 0:s.backoffMs)??1e3,l=(null==(o=null==(a=e.onError)?void 0:a.retry)?void 0:o.backoff)??"fixed";let h;for(let p=0;p<=c;p++)try{const r=await this.options.requester.requestData(e.queryVersionId,t);if(!r.success)throw new E(e.queryVersionId,r.message||"Query failed",void 0,{params:t});return r.data}catch(d){if(h=d,this.log("warn",`Query attempt ${p+1}/${c+1} failed:`,d),p<c){const e="exponential"===l?u*Math.pow(2,p):u;await this.delay(e)}}throw h||new Error("Query failed after all retries")}async handleLoadError(e,t,r){var n,i;const{binding:s}=e,a=s.onError;e.retryCount++,void 0!==(null==a?void 0:a.fallbackValue)&&this.options.stateSetter.setVariable(s.targetState,a.fallbackValue),(null==a?void 0:a.showError)&&(null==(i=(n=this.options).onDataError)||i.call(n,s.id,t)),this.log("error",`Binding ${s.id} load failed:`,t)}setupAutoRefresh(e,t){e.refreshTimer&&(clearInterval(e.refreshTimer),e.refreshTimer=void 0);const r=e.binding.refreshInterval;!r||r<=0||(e.refreshTimer=setInterval(()=>{this.loadBinding(e.binding.id,t,!0).catch(t=>{this.log("error",`Auto refresh for ${e.binding.id} failed:`,t)})},1e3*r))}isCacheValid(e){return!(!e.cachedData||!e.lastLoadTime||e.cacheExpireTime&&Date.now()>e.cacheExpireTime)}resolveParams(e,t){const r={};for(const[n,i]of Object.entries(e))r[n]=this.resolveValue(i,t);return r}resolveValue(e,t){if(null==e)return e;if("object"==typeof e&&!Array.isArray(e)){const r=e;if("expression"===r.type||"binding"===r.type)return this.options.expressionEngine.evaluateWithFallback(r.expression,t,r.fallback);const n={};for(const[e,i]of Object.entries(r))n[e]=this.resolveValue(i,t);return n}return"string"==typeof e&&e.includes("${")?this.options.expressionEngine.evaluateTemplate(e,t):e}evaluateCondition(e,t){const r=void 0===e.fallback||e.fallback,n=this.options.expressionEngine.evaluateWithFallback(e.value,t,r);return Boolean(n)}applyTransform(e,t,r){const n={...r,local:{...r.local||{},$data:e,$response:e}},i=void 0!==t.fallback?t.fallback:e;return this.options.expressionEngine.evaluateWithFallback(t.value,n,i)}delay(e){return new Promise(t=>setTimeout(t,e))}log(e,t,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}},O=class{constructor(e={}){this.handlers=new Map,this.options={debug:!1,maxListeners:100,...e}}emit(e){this.options.debug&&this.log("debug",`Event emitted: ${e.type}`,e);const t=this.handlers.get(e.type);t&&t.forEach(t=>{try{t(e)}catch(r){this.log("error",`Error in event handler for ${e.type}:`,r)}})}on(e,t){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.size>=(this.options.maxListeners??100)&&this.log("warn",`Max listeners (${this.options.maxListeners}) reached for event: ${e}`),r.add(t),()=>{null==r||r.delete(t),0===(null==r?void 0:r.size)&&this.handlers.delete(e)}}off(e,t){const r=this.handlers.get(e);r&&(r.delete(t),0===r.size&&this.handlers.delete(e))}once(e,t){const r=this.on(e,e=>{r(),t(e)});return r}clear(e){e?this.handlers.delete(e):this.handlers.clear()}listenerCount(e){var t;return(null==(t=this.handlers.get(e))?void 0:t.size)??0}static createEvent(e,t,r){return{type:e,data:t,timestamp:Date.now(),traceId:r}}log(e,t,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}},R=class e{constructor(e){this.debounceTimers=new Map,this.throttleTimers=new Map,this.options=e}async handleEvent(e,t,r){if(e.condition&&!this.evaluateCondition(e.condition,r,t))return void this.log("debug",`Handler ${e.id} skipped by condition`);if(e.throttle&&e.throttle>0&&!this.throttle(e.id,e.throttle))return void this.log("debug",`Handler ${e.id} throttled`);e.debounce&&e.debounce>0&&await this.debounce(e.id,e.debounce);const n={$event:t,$prevResult:void 0,$results:{}};await this.executeActionChain(e.actions,r,n)}async executeActionChain(e,t,r){const n=[];for(let i=0;i<e.length;i++){const s=e[i];if(s.condition){const e=this.buildActionContext(t,r);if(!this.evaluateCondition(s.condition,e,r.$event)){this.log("debug",`Action ${s.id||i} skipped by condition`);continue}}const a=this.executeSingleAction(s,t,r);s.async?n.push(a):await a}n.length>0&&await Promise.allSettled(n)}async executeSingleAction(e,t,r){var n,i,s,a,o,c;const u=e.id||e.alias||e.builtinAction||e.actionDefinitionVersionId||"unknown";e.silent||this.options.executor.showLoading();try{const o=this.buildActionContext(t,r),c=this.resolveParams(e.params||{},o);null==(i=(n=this.options).onActionStart)||i.call(n,e,c);const l=await this.executeWithRetry(e,c);r.$prevResult=l,e.id&&(r.$results[e.id]=l),null==(a=(s=this.options).onActionComplete)||a.call(s,e,{success:!0,data:l}),this.log("debug",`Action ${u} completed successfully`),e.onSuccess&&e.onSuccess.length>0&&await this.executeActionChain(e.onSuccess,t,r)}catch(l){this.log("error",`Action ${u} failed:`,l),null==(c=(o=this.options).onActionComplete)||c.call(o,e,{success:!1,error:l}),e.onError&&e.onError.length>0&&await this.executeActionChain(e.onError,t,{...r,$prevResult:{error:l.message}})}finally{e.silent||this.options.executor.hideLoading(),e.onFinally&&e.onFinally.length>0&&await this.executeActionChain(e.onFinally,t,r)}}async executeWithRetry(e,t){var r,n,i,s,a;const o=(null==(n=null==(r=e.policy)?void 0:r.retry)?void 0:n.maxAttempts)??1,c=(null==(s=null==(i=e.policy)?void 0:i.retry)?void 0:s.backoffMs)??1e3,u=null==(a=e.policy)?void 0:a.timeoutMs;let l;for(let d=1;d<=o;d++)try{let r;if(e.builtinAction)r=this.executeBuiltinAction(e.builtinAction,t);else{if(!e.actionDefinitionVersionId)throw new w("unknown","Action must specify builtinAction or actionDefinitionVersionId");r=this.executeCustomAction(e.actionDefinitionVersionId,t)}return u&&(r=this.withTimeout(r,u)),await r}catch(h){l=h,this.log("warn",`Action attempt ${d}/${o} failed:`,h),d<o&&await this.delay(c*d)}throw l||new Error("Action failed after all retries")}async executeBuiltinAction(e,t){switch(e){case"setState":return this.options.executor.setState(t.key,t.value),{success:!0};case"navigate":return this.options.executor.navigate({to:t.to??t.url,type:t.replace?"replace":t.external?"external":"push",params:t.params,query:t.query,newWindow:t.newWindow??t.newTab}),{success:!0};case"openDialog":return await this.options.executor.openDialog({type:t.type,content:t.content,title:t.title});case"closeDialog":return this.options.executor.closeDialog(t.dialogId),{success:!0};case"showToast":return this.options.executor.showToast({message:t.message,type:t.type,duration:t.duration}),{success:!0};case"showLoading":return this.options.executor.showLoading(t.message),{success:!0};case"hideLoading":return this.options.executor.hideLoading(),{success:!0};case"refreshData":return await this.options.executor.refreshData(t.queryId),{success:!0};case"track":return this.options.executor.track({eventName:t.eventName,params:t.params}),{success:!0};default:throw new w(e,`Unknown builtin action: ${e}`)}}async executeCustomAction(e,t){const r=e.split("@")[0],n=await this.options.executor.executeAction(r,{...t,actionDefinitionVersionId:e});if(!n.success)throw new w(r,n.errorMessage||"Action execution failed",void 0,e,{errorCode:n.errorCode});return n.data}resolveParams(e,t){const r={};for(const[n,i]of Object.entries(e))r[n]=this.resolveValue(i,t);return r}resolveValue(t,r){if(null==t)return t;if("string"==typeof t){if(t.startsWith("${")&&t.endsWith("}")){const e=t.slice(2,-1);return this.options.expressionEngine.evaluateWithFallback(e,r,t)}return t.includes("${")?this.options.expressionEngine.evaluateTemplate(t,r):t}if("number"==typeof t||"boolean"==typeof t)return t;if(Array.isArray(t))return t.map(e=>this.resolveValue(e,r));if("object"==typeof t){const n=t;if("string"==typeof n.type&&e.EXPRESSION_TYPES.includes(n.type)&&"string"==typeof n.value){const e=n;return this.options.expressionEngine.evaluateWithFallback(e.value,r,e.fallback)}const i={};for(const[e,t]of Object.entries(n))i[e]=this.resolveValue(t,r);return i}return t}evaluateCondition(e,t,r){const n={...t,local:{...t.local||{},$event:r}},i=void 0===e.fallback||e.fallback,s=this.options.expressionEngine.evaluateWithFallback(e.value,n,i);return Boolean(s)}buildActionContext(e,t){return{...e,local:{...e.local||{},$event:t.$event,$prevResult:t.$prevResult,$results:t.$results}}}withTimeout(e,t){return new Promise((r,n)=>{const i=setTimeout(()=>{n(new Error(`Action timed out after ${t}ms`))},t);e.then(e=>{clearTimeout(i),r(e)}).catch(e=>{clearTimeout(i),n(e)})})}debounce(e,t){return new Promise(r=>{const n=this.debounceTimers.get(e);n&&clearTimeout(n);const i=setTimeout(()=>{this.debounceTimers.delete(e),r()},t);this.debounceTimers.set(e,i)})}throttle(e,t){const r=Date.now();return!(r-(this.throttleTimers.get(e)??0)<t||(this.throttleTimers.set(e,r),0))}delay(e){return new Promise(t=>setTimeout(t,e))}destroy(){this.debounceTimers.forEach(e=>clearTimeout(e)),this.debounceTimers.clear(),this.throttleTimers.clear()}log(e,t,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}};R.EXPRESSION_TYPES=["state","binding","local","template","computed"];var _=R,$=class{constructor(e){this.pos=0,this.tokens=[],this.input=e}tokenize(){for(this.pos=0,this.tokens=[];this.pos<this.input.length&&(this.skipWhitespace(),!(this.pos>=this.input.length));){const e=this.readToken();e&&this.tokens.push(e)}return this.tokens.push({type:"EOF",value:null,start:this.input.length,end:this.input.length}),this.tokens}readToken(){const e=this.input[this.pos],t=this.pos;if(this.isDigit(e)||"-"===e&&this.isDigit(this.peek(1)))return this.readNumber();if('"'===e||"'"===e)return this.readString(e);if(this.isIdentifierStart(e))return this.readIdentifier();const r=this.readOperator();if(r)return r;switch(e){case".":return this.pos++,{type:"DOT",value:".",start:t,end:this.pos};case"[":return this.pos++,{type:"LBRACKET",value:"[",start:t,end:this.pos};case"]":return this.pos++,{type:"RBRACKET",value:"]",start:t,end:this.pos};case"(":return this.pos++,{type:"LPAREN",value:"(",start:t,end:this.pos};case")":return this.pos++,{type:"RPAREN",value:")",start:t,end:this.pos};case",":return this.pos++,{type:"COMMA",value:",",start:t,end:this.pos};case"?":return this.pos++,{type:"QUESTION",value:"?",start:t,end:this.pos};case":":return this.pos++,{type:"COLON",value:":",start:t,end:this.pos}}throw new Error(`Unexpected character '${e}' at position ${this.pos}`)}readNumber(){const e=this.pos;let t="";for("-"===this.input[this.pos]&&(t+="-",this.pos++);this.isDigit(this.input[this.pos]);)t+=this.input[this.pos],this.pos++;if("."===this.input[this.pos]&&this.isDigit(this.peek(1)))for(t+=".",this.pos++;this.isDigit(this.input[this.pos]);)t+=this.input[this.pos],this.pos++;return{type:"NUMBER",value:parseFloat(t),start:e,end:this.pos}}readString(e){const t=this.pos;this.pos++;let r="";for(;this.pos<this.input.length&&this.input[this.pos]!==e;){if("\\"===this.input[this.pos]){this.pos++;const e=this.input[this.pos];switch(e){case"n":r+="\n";break;case"t":r+="\t";break;case"r":r+="\r";break;case"\\":r+="\\";break;case'"':r+='"';break;case"'":r+="'";break;default:r+=e}}else r+=this.input[this.pos];this.pos++}if(this.input[this.pos]!==e)throw new Error(`Unterminated string at position ${t}`);return this.pos++,{type:"STRING",value:r,start:t,end:this.pos}}readIdentifier(){const e=this.pos;let t="";for(;this.pos<this.input.length&&this.isIdentifierChar(this.input[this.pos]);)t+=this.input[this.pos],this.pos++;return"true"===t?{type:"BOOLEAN",value:!0,start:e,end:this.pos}:"false"===t?{type:"BOOLEAN",value:!1,start:e,end:this.pos}:"null"===t?{type:"NULL",value:null,start:e,end:this.pos}:{type:"IDENTIFIER",value:t,start:e,end:this.pos}}readOperator(){const e=this.pos,t=this.input.slice(this.pos,this.pos+2),r=this.input[this.pos];return["==","!=",">=","<=","&&","||","??"].includes(t)?(this.pos+=2,{type:"OPERATOR",value:t,start:e,end:this.pos}):["+","-","*","/","%",">","<","!"].includes(r)?(this.pos++,{type:"OPERATOR",value:r,start:e,end:this.pos}):null}skipWhitespace(){for(;this.pos<this.input.length&&/\s/.test(this.input[this.pos]);)this.pos++}isDigit(e){return/[0-9]/.test(e)}isIdentifierStart(e){return/[a-zA-Z_$]/.test(e)}isIdentifierChar(e){return/[a-zA-Z0-9_$]/.test(e)}peek(e=1){return this.input[this.pos+e]||""}},D=l(h()),C={"||":1,"??":1,"&&":2,"==":3,"!=":3,"<":4,">":4,"<=":4,">=":4,"+":5,"-":5,"*":6,"/":6,"%":6},x=class{constructor(e){this.pos=0,this.tokens=e}parse(){const e=this.parseExpression();if("EOF"!==this.current().type)throw new Error(`Unexpected token '${this.current().value}' at position ${this.current().start}`);return e}parseExpression(){return this.parseTernary()}parseTernary(){const e=this.parseBinary(0);if("QUESTION"===this.current().type){this.advance();const t=this.parseExpression();return this.expect("COLON"),{type:"conditional",test:e,consequent:t,alternate:this.parseExpression(),raw:void 0}}return e}parseBinary(e){let t=this.parseUnary();for(;;){const r=this.current();if("OPERATOR"!==r.type)break;const n=C[r.value];if(void 0===n||n<e)break;this.advance();const i=this.parseBinary(n+1);t={type:"binary",operator:r.value,left:t,right:i,raw:void 0}}return t}parseUnary(){const e=this.current();if("OPERATOR"===e.type&&("!"===e.value||"-"===e.value)){this.advance();const t=this.parseUnary();return{type:"unary",operator:e.value,argument:t,raw:void 0}}return this.parsePostfix()}parsePostfix(){let e=this.parsePrimary();for(;;){const t=this.current();if("DOT"===t.type)this.advance(),e={type:"member",object:e,property:this.expect("IDENTIFIER").value,computed:!1,raw:void 0};else if("LBRACKET"===t.type){this.advance();const t=this.parseExpression();this.expect("RBRACKET"),e={type:"member",object:e,property:t,computed:!0,raw:void 0}}else{if("LPAREN"!==t.type||"identifier"!==e.type)break;{const r=e.name;if(!D.ALLOWED_FUNCTION_NAMES.includes(r))throw new Error(`Unknown function '${r}' at position ${t.start}`);this.advance();const n=this.parseArguments();this.expect("RPAREN"),e={type:"call",callee:r,arguments:n,raw:void 0}}}}return e}parsePrimary(){const e=this.current();if("NUMBER"===e.type||"STRING"===e.type||"BOOLEAN"===e.type||"NULL"===e.type)return this.advance(),{type:"literal",value:e.value,start:e.start,end:e.end,raw:void 0};if("IDENTIFIER"===e.type)return this.advance(),{type:"identifier",name:e.value,start:e.start,end:e.end,raw:void 0};if("LBRACKET"===e.type)return this.parseArray();if("LPAREN"===e.type){this.advance();const e=this.parseExpression();return this.expect("RPAREN"),e}throw new Error(`Unexpected token '${e.value}' at position ${e.start}`)}parseArray(){const e=this.current().start;this.advance();const t=[];for(;"RBRACKET"!==this.current().type&&(t.push(this.parseExpression()),"COMMA"===this.current().type);)this.advance();const r=this.current().end;return this.expect("RBRACKET"),{type:"array",elements:t,start:e,end:r,raw:void 0}}parseArguments(){const e=[];if("RPAREN"!==this.current().type)for(e.push(this.parseExpression());"COMMA"===this.current().type;)this.advance(),e.push(this.parseExpression());return e}current(){return this.tokens[this.pos]}advance(){return this.tokens[this.pos++]}expect(e){const t=this.current();if(t.type!==e)throw new Error(`Expected '${e}' but got '${t.type}' at position ${t.start}`);return this.advance()}},M={len:e=>"string"==typeof e||Array.isArray(e)?e.length:0,trim:e=>String(e??"").trim(),upper:e=>String(e??"").toUpperCase(),lower:e=>String(e??"").toLowerCase(),substr:(e,t,r)=>{const n=String(e??""),i=Number(t)||0,s=void 0!==r?Number(r):void 0;return n.substring(i,void 0!==s?i+s:void 0)},concat:(...e)=>e.map(e=>String(e??"")).join(""),replace:(e,t,r)=>String(e??"").split(String(t)).join(String(r)),split:(e,t)=>String(e??"").split(String(t)),join:(e,t)=>Array.isArray(e)?e.join(void 0!==t?String(t):","):"",startsWith:(e,t)=>String(e??"").startsWith(String(t)),endsWith:(e,t)=>String(e??"").endsWith(String(t)),contains:(e,t)=>String(e??"").includes(String(t)),toNumber:e=>{const t=Number(e);return isNaN(t)?0:t},toString:e=>String(e??""),toInt:e=>Math.trunc(Number(e)||0),toFloat:e=>parseFloat(String(e))||0,round:(e,t)=>{const r=Number(e)||0,n=Number(t)||0,i=Math.pow(10,n);return Math.round(r*i)/i},floor:e=>Math.floor(Number(e)||0),ceil:e=>Math.ceil(Number(e)||0),abs:e=>Math.abs(Number(e)||0),min:(...e)=>{const t=e.map(e=>Number(e)).filter(e=>!isNaN(e));return t.length>0?Math.min(...t):0},max:(...e)=>{const t=e.map(e=>Number(e)).filter(e=>!isNaN(e));return t.length>0?Math.max(...t):0},sum:e=>Array.isArray(e)?e.reduce((e,t)=>e+(Number(t)||0),0):0,avg:e=>Array.isArray(e)&&0!==e.length?e.reduce((e,t)=>e+(Number(t)||0),0)/e.length:0,random:()=>Math.random(),randomInt:(e,t)=>{const r=Math.ceil(Number(e)||0),n=Math.floor(Number(t)||100);return Math.floor(Math.random()*(n-r+1))+r},now:()=>Date.now(),today:()=>(new Date).toISOString().split("T")[0],dateFormat:(e,t)=>{const r=new Date(Number(e)||Date.now()),n=e=>e.toString().padStart(2,"0");return String(t||"YYYY-MM-DD").replace("YYYY",r.getFullYear().toString()).replace("MM",n(r.getMonth()+1)).replace("DD",n(r.getDate())).replace("HH",n(r.getHours())).replace("mm",n(r.getMinutes())).replace("ss",n(r.getSeconds()))},dateParse:e=>new Date(String(e)).getTime(),year:e=>new Date(Number(e)||Date.now()).getFullYear(),month:e=>new Date(Number(e)||Date.now()).getMonth()+1,day:e=>new Date(Number(e)||Date.now()).getDate(),addDays:(e,t)=>{const r=new Date(Number(e)||Date.now());return r.setDate(r.getDate()+(Number(t)||0)),r.getTime()},diffDays:(e,t)=>{const r=new Date(Number(e)||Date.now()),n=new Date(Number(t)||Date.now()),i=Math.abs(n.getTime()-r.getTime());return Math.floor(i/864e5)},isNull:e=>null==e,isUndefined:e=>void 0===e,isEmpty:e=>null==e||("string"==typeof e||Array.isArray(e)?0===e.length:"object"==typeof e&&0===Object.keys(e).length),isArray:e=>Array.isArray(e),isObject:e=>null!==e&&"object"==typeof e&&!Array.isArray(e),isString:e=>"string"==typeof e,isNumber:e=>"number"==typeof e&&!isNaN(e),isBoolean:e=>"boolean"==typeof e,typeOf:e=>null===e?"null":Array.isArray(e)?"array":typeof e,default:(e,t)=>e??t,coalesce:(...e)=>{for(const t of e)if(null!=t)return t;return null},ifElse:(e,t,r)=>e?t:r,first:e=>{if(Array.isArray(e))return e[0]},last:e=>{if(Array.isArray(e))return e[e.length-1]},at:(e,t)=>{if(Array.isArray(e))return e[Number(t)||0]},slice:(e,t,r)=>Array.isArray(e)?e.slice(Number(t)||0,void 0!==r?Number(r):void 0):[],includes:(e,t)=>!!Array.isArray(e)&&e.includes(t),indexOf:(e,t)=>Array.isArray(e)?e.indexOf(t):-1,reverse:e=>Array.isArray(e)?[...e].reverse():[],sort:e=>Array.isArray(e)?[...e].sort():[],unique:e=>Array.isArray(e)?[...new Set(e)]:[],flatten:e=>Array.isArray(e)?e.flat():[],count:e=>Array.isArray(e)?e.length:0,get:(e,t,r)=>{if(null==e)return r;const n=String(t).split(".");let i=e;for(const s of n){if(null==i)return r;i=i[s]}return i??r},keys:e=>"object"!=typeof e||null===e?[]:Object.keys(e),values:e=>"object"!=typeof e||null===e?[]:Object.values(e),entries:e=>"object"!=typeof e||null===e?[]:Object.entries(e),has:(e,t)=>"object"==typeof e&&null!==e&&String(t)in e,merge:(...e)=>{const t={};for(const r of e)"object"==typeof r&&null!==r&&Object.assign(t,r);return t},and:(...e)=>e.every(e=>Boolean(e)),or:(...e)=>e.some(e=>Boolean(e)),not:e=>!e,eq:(e,t)=>e===t,ne:(e,t)=>e!==t,gt:(e,t)=>Number(e)>Number(t),gte:(e,t)=>Number(e)>=Number(t),lt:(e,t)=>Number(e)<Number(t),lte:(e,t)=>Number(e)<=Number(t),between:(e,t,r)=>{const n=Number(e);return n>=Number(t)&&n<=Number(r)},formatNumber:(e,t)=>{const r=Number(e)||0,n=Number(t)??0;return r.toLocaleString(void 0,{minimumFractionDigits:n,maximumFractionDigits:n})},formatCurrency:(e,t)=>{const r=Number(e)||0,n=String(t||"CNY");return r.toLocaleString("zh-CN",{style:"currency",currency:n})},formatPercent:(e,t)=>{const r=Number(e)||0,n=Number(t)??0;return(100*r).toFixed(n)+"%"},currency:(e,t,r)=>{const n=Number(e)||0,i=String(t??"¥"),s=Number(r)??2;return`${i}${n.toLocaleString(void 0,{minimumFractionDigits:s,maximumFractionDigits:s})}`},percent:(e,t)=>{const r=Number(e)||0,n=Number(t)??0;return(100*r).toFixed(n)+"%"},number:(e,t)=>{const r=Number(e)||0,n=Number(t)??0;return r.toLocaleString(void 0,{minimumFractionDigits:n,maximumFractionDigits:n})},pluralize:(e,t,r)=>{const n=Number(e)||0;return`${n} ${String(1===n?t:r)}`},mask:(e,t,r,n)=>{const i=String(e??""),s=Number(t)||3,a=Number(r)||4,o=String(n??"*");if(i.length<=s+a)return i;const c=i.slice(0,s),u=i.slice(-a);return c+o.repeat(i.length-s-a)+u},jsonParse:e=>{try{return JSON.parse(String(e))}catch{return null}},jsonStringify:e=>JSON.stringify(e),toJSON:e=>JSON.stringify(e),fromJSON:e=>{try{return JSON.parse(String(e))}catch{return null}},clamp:(e,t,r)=>{const n=Number(e)||0,i=Number(t)||0,s=Number(r)||100;return Math.min(Math.max(n,i),s)},length:e=>Array.isArray(e)||"string"==typeof e?e.length:0,average:e=>Array.isArray(e)&&0!==e.length?e.reduce((e,t)=>e+(Number(t)||0),0)/e.length:0,dateAdd:(e,t,r)=>{const n=new Date(Number(e)||Date.now()),i=Number(t)||0;switch(String(r??"day").toLowerCase()){case"year":case"years":n.setFullYear(n.getFullYear()+i);break;case"month":case"months":n.setMonth(n.getMonth()+i);break;case"week":case"weeks":n.setDate(n.getDate()+7*i);break;case"day":case"days":default:n.setDate(n.getDate()+i);break;case"hour":case"hours":n.setHours(n.getHours()+i);break;case"minute":case"minutes":n.setMinutes(n.getMinutes()+i)}return n.getTime()},dateDiff:(e,t,r)=>{const n=new Date(Number(e)||Date.now()),i=new Date(Number(t)||Date.now()).getTime()-n.getTime();switch(String(r??"day").toLowerCase()){case"year":case"years":return Math.floor(i/31536e6);case"month":case"months":return Math.floor(i/2592e6);case"week":case"weeks":return Math.floor(i/6048e5);case"day":case"days":default:return Math.floor(i/864e5);case"hour":case"hours":return Math.floor(i/36e5);case"minute":case"minutes":return Math.floor(i/6e4)}},$if:(e,t,r)=>e?t:r,toBoolean:e=>"string"==typeof e?"false"!==e.toLowerCase()&&"0"!==e&&""!==e:Boolean(e),substring:(e,t,r)=>{const n=String(e??""),i=Number(t)||0,s=void 0!==r?Number(r):void 0;return n.substring(i,s)},padStart:(e,t,r)=>{const n=String(e??""),i=Number(t)||0,s=String(r??" ");return n.padStart(i,s)},padEnd:(e,t,r)=>{const n=String(e??""),i=Number(t)||0,s=String(r??" ");return n.padEnd(i,s)},repeat:(e,t)=>{const r=String(e??""),n=Math.max(0,Math.floor(Number(t)||0));return r.repeat(n)}},L=class{constructor(e={}){this.depth=0,this.startTime=0,this.options={maxDepth:100,timeout:1e3,debug:!1,...e}}evaluate(e,t){this.depth=0,this.startTime=Date.now();try{return{value:this.evaluateNode(e,t)}}catch(r){return{value:void 0,error:r instanceof Error?r:new Error(String(r))}}}evaluateNode(e,t){switch(this.checkLimits(),e.type){case"literal":return this.evaluateLiteral(e);case"identifier":return this.evaluateIdentifier(e,t);case"member":return this.evaluateMember(e,t);case"call":return this.evaluateCall(e,t);case"binary":return this.evaluateBinary(e,t);case"unary":return this.evaluateUnary(e,t);case"conditional":return this.evaluateConditional(e,t);case"array":return this.evaluateArray(e,t);default:throw new v("",`Unknown node type: ${e.type}`)}}evaluateLiteral(e){return e.value}evaluateIdentifier(e,t){var r,n;const i=e.name;switch(i){case"state":return t.state;case"binding":case"query":return t.binding;case"local":return t.local;case"props":return t.props;case"event":return t.event;case"item":return null==(r=t.local)?void 0:r.item;case"index":return null==(n=t.local)?void 0:n.index;default:if(t.local&&i in t.local)return t.local[i];throw new v("",`Unknown variable '${i}'. Available: state, binding, local, props, event`)}}evaluateMember(e,t){const r=this.evaluateNode(e.object,t);if(null==r)return;let n;return n=e.computed?this.evaluateNode(e.property,t):e.property,"object"==typeof r&&null!==r?r[n]:void 0}evaluateCall(e,t){const r=M[e.callee];if(!r)throw new v("",`Unknown function '${e.callee}'`);return r(...e.arguments.map(e=>this.evaluateNode(e,t)))}evaluateBinary(e,t){const r=e.operator;if("&&"===r){const r=this.evaluateNode(e.left,t);return r?this.evaluateNode(e.right,t):r}if("||"===r){return this.evaluateNode(e.left,t)||this.evaluateNode(e.right,t)}if("??"===r){const r=this.evaluateNode(e.left,t);return null!=r?r:this.evaluateNode(e.right,t)}const n=this.evaluateNode(e.left,t),i=this.evaluateNode(e.right,t);switch(r){case"+":return"string"==typeof n||"string"==typeof i?String(n)+String(i):n+i;case"-":return n-i;case"*":return n*i;case"/":return n/i;case"%":return n%i;case"==":return n===i;case"!=":return n!==i;case"<":return n<i;case">":return n>i;case"<=":return n<=i;case">=":return n>=i;default:throw new v("",`Unknown operator '${r}'`)}}evaluateUnary(e,t){const r=this.evaluateNode(e.argument,t);switch(e.operator){case"!":return!r;case"-":return-r;default:throw new v("",`Unknown unary operator '${e.operator}'`)}}evaluateConditional(e,t){return this.evaluateNode(e.test,t)?this.evaluateNode(e.consequent,t):this.evaluateNode(e.alternate,t)}evaluateArray(e,t){return e.elements.map(e=>this.evaluateNode(e,t))}checkLimits(){if(this.depth++,this.depth>(this.options.maxDepth??100))throw new v("","Maximum recursion depth exceeded");if(Date.now()-this.startTime>(this.options.timeout??1e3))throw new v("","Expression evaluation timeout")}},k=class{constructor(e={}){this.astCache=new Map,this.options={cacheAST:!0,maxCacheSize:1e3,...e},this.evaluator=new L(e)}evaluate(e,t){try{const r=this.parse(e);return this.evaluator.evaluate(r,t)}catch(r){return{value:void 0,error:r instanceof Error?r:new Error(String(r))}}}evaluateWithFallback(e,t,r){const n="string"==typeof e?e:e.value,i="object"==typeof e&&void 0!==e.fallback?e.fallback:r,s=this.evaluate(n,t);return s.error?(this.log("warn",`Expression evaluation failed: ${s.error.message}`,n),i):s.value}evaluateTemplate(e,t){return e.replace(/\$\{([^}]+)\}/g,(e,r)=>{const n=this.evaluate(r.trim(),t);return n.error?(this.log("warn",`Template expression failed: ${n.error.message}`,r),""):String(n.value??"")})}parse(e){if(this.options.cacheAST){const t=this.astCache.get(e);if(t)return t}try{const t=new $(e).tokenize(),r=new x(t).parse();return this.options.cacheAST&&(this.astCache.size>=(this.options.maxCacheSize??1e3)&&Array.from(this.astCache.keys()).slice(0,Math.floor(this.astCache.size/2)).forEach(e=>this.astCache.delete(e)),this.astCache.set(e,r)),r}catch(t){throw new v(e,t instanceof Error?t.message:"Parse error")}}validate(e){const t=[],r=[],n=[],i=[];try{const t=this.parse(e);return this.collectReferences(t,n,i),{valid:!0,errors:[],warnings:r,referencedPaths:n,usedFunctions:i}}catch(s){return t.push({type:"invalid_syntax",message:s instanceof Error?s.message:"Parse error"}),{valid:!1,errors:t,warnings:r,referencedPaths:n,usedFunctions:i}}}clearCache(){this.astCache.clear()}collectReferences(e,t,r){switch(e.type){case"identifier":t.push(e.name);break;case"member":{const r=this.buildMemberPath(e);r&&t.push(r);break}case"call":r.push(e.callee),e.arguments.forEach(e=>this.collectReferences(e,t,r));break;case"binary":this.collectReferences(e.left,t,r),this.collectReferences(e.right,t,r);break;case"unary":this.collectReferences(e.argument,t,r);break;case"conditional":this.collectReferences(e.test,t,r),this.collectReferences(e.consequent,t,r),this.collectReferences(e.alternate,t,r);break;case"array":e.elements.forEach(e=>this.collectReferences(e,t,r))}}buildMemberPath(e){if("identifier"===e.type)return e.name;if("member"===e.type&&!e.computed){const t=this.buildMemberPath(e.object);if(t)return`${t}.${e.property}`}return null}log(e,t,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}},U=class{constructor(e){this.loadingCount=0,this.loadingElement=null,this.clipboard={write:async e=>{try{return await navigator.clipboard.writeText(e),!0}catch(t){return this.log("error","Clipboard write failed:",t),this.fallbackCopy(e)}},read:async()=>{try{return await navigator.clipboard.readText()}catch(e){return this.log("error","Clipboard read failed:",e),null}}},this.storage={get:e=>{const t=`${this.storageNamespace}:${e}`,r=localStorage.getItem(t);if(!r)return null;try{const e=JSON.parse(r);return e.expires&&Date.now()>e.expires?(localStorage.removeItem(t),null):e.value}catch{return null}},set:(e,t,r)=>{const n=`${this.storageNamespace}:${e}`,i={value:t,expires:(null==r?void 0:r.ttlSeconds)?Date.now()+1e3*r.ttlSeconds:void 0};("session"===(null==r?void 0:r.level)?sessionStorage:localStorage).setItem(n,JSON.stringify(i))},remove:e=>{const t=`${this.storageNamespace}:${e}`;localStorage.removeItem(t),sessionStorage.removeItem(t)},clear:()=>{const e=`${this.storageNamespace}:`;for(let t=localStorage.length-1;t>=0;t--){const r=localStorage.key(t);(null==r?void 0:r.startsWith(e))&&localStorage.removeItem(r)}for(let t=sessionStorage.length-1;t>=0;t--){const r=sessionStorage.key(t);(null==r?void 0:r.startsWith(e))&&sessionStorage.removeItem(r)}}},this.options=e,this.storageNamespace=`djvlc:${e.context.appId}`}async navigate(e){this.log("debug","Navigate:",e),this.track({eventName:"djvlc_navigate",params:{to:e.to,type:e.type},type:"click"});let t=e.to;if(e.query){const r=new URLSearchParams(e.query);t+=(t.includes("?")?"&":"?")+r.toString()}switch(e.type){case"external":e.newWindow?window.open(t,"_blank","noopener,noreferrer"):window.location.href=t;break;case"replace":window.location.replace(t);break;default:e.newWindow?window.open(t,"_blank"):window.location.href=t}}track(e){this.log("debug","Track event:",e);const t=this.options.context;fetch(`${this.options.apiBaseUrl}/track`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify({eventName:e.eventName,params:e.params,type:e.type||"custom",timestamp:Date.now(),context:{pageVersionId:t.pageVersionId,runtimeVersion:t.runtimeVersion,userId:t.userId,deviceId:t.deviceId,channel:t.channel,appId:t.appId,env:t.env}}),keepalive:!0}).catch(e=>{this.log("warn","Track failed:",e)})}async requestData(e,t){this.log("debug",`Requesting data: ${e}`,t);const r=performance.now(),n=this.options.context;try{const i=await fetch(`${this.options.apiBaseUrl}/data/query`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify({queryVersionId:e,params:t||{},context:{pageVersionId:n.pageVersionId,uid:n.userId,deviceId:n.deviceId}})});if(!i.ok){const e=await i.text();throw new Error(`HTTP ${i.status}: ${e||i.statusText}`)}const s=await i.json(),a=performance.now()-r;if(this.log("debug",`Data query completed in ${a.toFixed(2)}ms`),!s.success)throw new Error(s.message||s.errorMessage||"Query failed");return this.options.stateManager.setQuery(e,s.data),s.data}catch(i){const t=performance.now()-r;throw this.log("error",`Data query failed: ${e} (${t.toFixed(2)}ms)`,i),i}}async executeAction(e,t={}){this.log("debug",`Executing action: ${e}`,t);const r=performance.now(),n=this.options.context,i=this.generateIdempotencyKey(e,t);this.track({eventName:"djvlc_action_start",params:{actionType:e,idempotencyKey:i},type:"custom"});try{const s=await fetch(`${this.options.apiBaseUrl}/actions/execute`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify({actionType:e,params:t||{},context:{pageVersionId:n.pageVersionId,uid:n.userId,deviceId:n.deviceId,channel:n.channel,appId:n.appId},idempotencyKey:i})});if(!s.ok){const t=await s.text(),n=performance.now()-r;return this.log("error",`Action HTTP error: ${e} (${n.toFixed(2)}ms)`,t),{success:!1,errorCode:`HTTP_${s.status}`,errorMessage:t||s.statusText}}const a=await s.json(),o=performance.now()-r;return this.log("debug",`Action completed in ${o.toFixed(2)}ms`,{success:a.success}),this.track({eventName:a.success?"djvlc_action_success":"djvlc_action_fail",params:{actionType:e,idempotencyKey:i,duration:Math.round(o),errorCode:a.errorCode},type:"custom"}),{success:a.success,data:a.data,errorCode:a.errorCode,errorMessage:a.errorMessage}}catch(s){const t=performance.now()-r;return this.log("error",`Action failed: ${e} (${t.toFixed(2)}ms)`,s),this.track({eventName:"djvlc_action_error",params:{actionType:e,idempotencyKey:i,duration:Math.round(t),errorMessage:s instanceof Error?s.message:"Unknown error"},type:"custom"}),{success:!1,errorCode:"NETWORK_ERROR",errorMessage:s instanceof Error?s.message:"Action failed"}}}async openDialog(e){return this.log("debug","Open dialog:",e),new Promise(t=>{const r=new CustomEvent("djvlc:openDialog",{detail:{options:e,resolve:e=>t(e)}});document.dispatchEvent(r),setTimeout(()=>{t({confirmed:!1})},6e4)})}closeDialog(e){this.log("debug","Close dialog:",e);const t=new CustomEvent("djvlc:closeDialog",{detail:{dialogId:e}});document.dispatchEvent(t)}showToast(e){this.log("debug","Show toast:",e);const t=document.createElement("div");switch(t.className=`djvlc-toast djvlc-toast-${e.type||"info"} djvlc-toast-${e.position||"top"}`,t.setAttribute("role","alert"),t.textContent=e.message,Object.assign(t.style,{position:"fixed",left:"50%",transform:"translateX(-50%)",padding:"12px 24px",borderRadius:"8px",color:"#fff",fontSize:"14px",zIndex:"10000",boxShadow:"0 4px 12px rgba(0,0,0,0.15)",transition:"opacity 0.3s, transform 0.3s",opacity:"0"}),t.style.backgroundColor={success:"#52c41a",error:"#ff4d4f",warning:"#faad14",info:"#1890ff"}[e.type||"info"],e.position){case"center":t.style.top="50%",t.style.transform="translate(-50%, -50%)";break;case"bottom":t.style.bottom="20px";break;default:t.style.top="20px"}document.body.appendChild(t),requestAnimationFrame(()=>{t.style.opacity="1"}),setTimeout(()=>{t.style.opacity="0",setTimeout(()=>t.remove(),300)},e.duration||3e3)}showLoading(e){this.loadingCount++,1===this.loadingCount&&(this.loadingElement=document.createElement("div"),this.loadingElement.className="djvlc-loading-overlay",this.loadingElement.innerHTML=`\n <div class="djvlc-loading-content">\n <div class="djvlc-loading-spinner"></div>\n <div class="djvlc-loading-message">${e||"加载中..."}</div>\n </div>\n `,Object.assign(this.loadingElement.style,{position:"fixed",top:"0",left:"0",right:"0",bottom:"0",backgroundColor:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:"10001"}),document.body.appendChild(this.loadingElement))}hideLoading(){this.loadingCount=Math.max(0,this.loadingCount-1),0===this.loadingCount&&this.loadingElement&&(this.loadingElement.remove(),this.loadingElement=null)}async share(e){if(this.log("debug","Share:",e),navigator.share)try{return await navigator.share({title:e.title,text:e.description,url:e.url}),{success:!0,channel:"native"}}catch(t){if("AbortError"===t.name)return{success:!1,cancelReason:"User cancelled"};throw t}return e.url&&await this.clipboard.write(e.url)?(this.showToast({message:"链接已复制",type:"success"}),{success:!0,channel:"link"}):{success:!1,cancelReason:"Share not supported"}}async confirm(e){return this.log("debug","Confirm:",e),window.confirm(e.content)}async showActionSheet(e){return this.log("debug","Show action sheet:",e),new Promise(t=>{const r=new CustomEvent("djvlc:showActionSheet",{detail:{options:e,resolve:e=>t(e)}});document.dispatchEvent(r),setTimeout(()=>{t({cancelled:!0})},6e4)})}previewImage(e){this.log("debug","Preview image:",e);const t=new CustomEvent("djvlc:previewImage",{detail:e});document.dispatchEvent(t)}async scanCode(){return this.log("debug","Scan code"),new Promise(e=>{const t=new CustomEvent("djvlc:scanCode",{detail:{resolve:t=>e(t)}});document.dispatchEvent(t),setTimeout(()=>{e({success:!1,cancelReason:"Timeout"})},6e4)})}getState(e){return this.options.stateManager.getVariable(e)}setState(e,t){this.options.stateManager.setVariable(e,t)}getContext(){const e=this.options.context;return{pageVersionId:e.pageVersionId,componentVersionId:"",instanceId:"",userId:e.userId,deviceId:e.deviceId,channel:e.channel,appId:e.appId,env:e.env}}buildHeaders(){const e={"Content-Type":"application/json",...this.options.headers};return this.options.authToken&&(e.Authorization=`Bearer ${this.options.authToken}`),e}generateIdempotencyKey(e,t){const r=Date.now(),n=JSON.stringify(t||{});return`${e}:${r}:${this.simpleHash(n)}`}simpleHash(e){let t=0;for(let r=0;r<e.length;r++)t=(t<<5)-t+e.charCodeAt(r),t&=t;return Math.abs(t).toString(36)}fallbackCopy(e){const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select();try{return document.execCommand("copy"),!0}catch{return!1}finally{document.body.removeChild(t)}}log(e,t,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}},P=class{constructor(e={}){var t;this.blockedComponentsMap=new Map,this.blockedActionsSet=new Set,this.allowedCapabilitiesSet=null,this.options={enableSRI:!0,cdnDomains:[],apiDomains:[],blockedComponents:[],blockedActions:[],applyCSPOnInit:!1,...e},this.updateBlockedList((null==(t=e.blockedComponents)?void 0:t.map(e=>`${e.name}@${e.version}`))||[],e.blockedActions||[]),e.allowedCapabilities&&(this.allowedCapabilitiesSet=new Set(e.allowedCapabilities)),e.applyCSPOnInit&&this.applyCSP()}updateBlockedList(e,t){this.blockedComponentsMap.clear(),e.forEach(e=>{const[t,r]=e.split("@");t&&r&&this.blockedComponentsMap.set(e,{name:t,version:r,reason:"Blocked by registry"})}),this.blockedActionsSet=new Set(t)}addBlockedComponent(e){const t=`${e.name}@${e.version}`;this.blockedComponentsMap.set(t,e),this.log("warn",`Component blocked: ${t} - ${e.reason}`)}removeBlockedComponent(e,t){const r=`${e}@${t}`;this.blockedComponentsMap.delete(r),this.log("info",`Component unblocked: ${r}`)}isComponentBlocked(e,t){return this.blockedComponentsMap.has(`${e}@${t}`)}getBlockedInfo(e,t){return this.blockedComponentsMap.get(`${e}@${t}`)}getAllBlockedComponents(){return Array.from(this.blockedComponentsMap.values())}isActionBlocked(e){return this.blockedActionsSet.has(e)}isCapabilityAllowed(e){return!this.allowedCapabilitiesSet||this.allowedCapabilitiesSet.has(e)}validateCapabilities(e,t,r){if(!this.allowedCapabilitiesSet)return{valid:!0,disallowed:[]};const n=r.filter(e=>!this.allowedCapabilitiesSet.has(e));return n.length>0&&this.log("warn",`Component ${e}@${t} uses disallowed capabilities: ${n.join(", ")}`),{valid:0===n.length,disallowed:n}}async validateIntegrity(e,t,r,n){if(!this.options.enableSRI)return;const[i,s]=n.split("-");if(!i||!s)throw new g(e,t,n,"Invalid integrity format");const a=await this.computeHash(r,i);if(a!==s)throw this.log("error",`Integrity check failed for ${e}@${t}`),new g(e,t,s,a);this.log("debug",`Integrity check passed for ${e}@${t}`)}async generateIntegrity(e,t="sha384"){return`${t}-${await this.computeHash(e,t)}`}isAllowedUrl(e,t){const r="cdn"===t?this.options.cdnDomains:this.options.apiDomains;if(!r||0===r.length)return!0;try{const t=new URL(e);return r.some(e=>{if(e.startsWith("*.")){const r=e.slice(2);return t.hostname.endsWith(r)||t.hostname===r.slice(1)}return t.hostname===e})}catch{return!1}}validateExternalUrl(e){try{const t=new URL(e);if(!["http:","https:"].includes(t.protocol))return{safe:!1,reason:`Unsafe protocol: ${t.protocol}`};const r=t.hostname;return"localhost"===r||"127.0.0.1"===r||r.startsWith("192.168.")||r.startsWith("10.")||r.startsWith("172.16.")?{safe:!1,reason:"Internal network address not allowed"}:{safe:!0}}catch{return{safe:!1,reason:"Invalid URL format"}}}generateCSPPolicy(){const e=this.options.cdnDomains||[],t=this.options.apiDomains||[],r=["'self'",...e].join(" "),n=["'self'",...t,...e].join(" ");return["default-src 'self'",`script-src ${r}`,`style-src ${["'self'","'unsafe-inline'",...e].join(" ")}`,`img-src ${["'self'","data:","blob:",...e].join(" ")}`,`font-src ${["'self'","data:",...e].join(" ")}`,`connect-src ${n}`,"frame-ancestors 'self'","base-uri 'self'","form-action 'self'","upgrade-insecure-requests"].join("; ")}applyCSP(){if(document.querySelector('meta[http-equiv="Content-Security-Policy"]'))return void this.log("debug","CSP meta tag already exists, skipping");const e=document.createElement("meta");e.httpEquiv="Content-Security-Policy",e.content=this.generateCSPPolicy(),document.head.appendChild(e),this.log("info","CSP policy applied")}assertNotBlocked(e,t){const r=this.getBlockedInfo(e,t);if(r)throw new b(e,t,r.reason)}createSafeEvaluator(){return(e,t)=>{const r=Object.keys(t),n=Object.values(t);return new Function(...r,`"use strict"; return (${e});`)(...n)}}async computeHash(e,t){const r=(new TextEncoder).encode(e),n=await crypto.subtle.digest(t.toUpperCase(),r),i=Array.from(new Uint8Array(n));return btoa(String.fromCharCode(...i))}log(e,t,...r){this.options.logger&&this.options.logger[e](t,...r)}},j=class{constructor(e){this.spans=new Map,this.metrics=[],this.errors=[],this.options={enabled:!0,sampleRate:1,batchSize:50,flushInterval:3e4,...e},this.traceId=this.generateTraceId(),this.shouldSample=Math.random()<(this.options.sampleRate??1),this.options.enabled&&this.options.endpoint&&this.startAutoFlush(),"undefined"!=typeof window&&(window.addEventListener("beforeunload",()=>this.flush()),window.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&this.flush()}))}getTraceId(){return this.traceId}getTraceparent(e){const t=e||this.generateSpanId(),r=this.shouldSample?"01":"00";return`00-${this.traceId}-${t}-${r}`}parseTraceparent(e){const t=e.split("-");if(4!==t.length)return null;const[,r,n,i]=t;return{traceId:r,parentSpanId:n,sampled:"01"===i}}startSpan(e,t,r){const n={spanId:this.generateSpanId(),traceId:this.traceId,parentSpanId:t,name:e,startTime:performance.now(),attributes:{pageVersionId:this.options.pageVersionId,...r}};return this.spans.set(n.spanId,n),this.log("debug",`Span started: ${e} (${n.spanId})`),n}endSpan(e,t="ok",r){const n=this.spans.get(e);if(n){n.endTime=performance.now(),n.status=t,r&&(n.attributes={...n.attributes,...r});const i=n.endTime-n.startTime;this.log("debug",`Span ended: ${n.name} (${e}) - ${i.toFixed(2)}ms [${t}]`)}}recordPageLoad(e){this.recordMetricInternal({type:"pageLoadTime",value:e,pageVersionId:this.options.pageVersionId,timestamp:Date.now()})}recordComponentLoad(e,t,r,n){this.recordMetricInternal({type:"componentLoadTime",value:r,pageVersionId:this.options.pageVersionId,componentName:e,componentVersion:t,timestamp:Date.now()}),n||this.recordError(new Error(`Component load failed: ${e}@${t}`),{componentVersion:`${e}@${t}`})}recordFirstRender(e){this.recordMetricInternal({type:"firstRenderTime",value:e,pageVersionId:this.options.pageVersionId,timestamp:Date.now()})}recordActionExecute(e,t,r,n){this.recordMetricInternal({type:"actionExecuteTime",value:r,pageVersionId:this.options.pageVersionId,actionType:e,timestamp:Date.now()}),n||this.recordError(new Error(`Action failed: ${e}`),{actionId:t})}recordQueryExecute(e,t,r,n=!1){this.recordMetricInternal({type:"queryFetchTime",value:t,pageVersionId:this.options.pageVersionId,queryId:e,timestamp:Date.now()}),this.log("debug",`Query ${e}: ${t.toFixed(2)}ms, cache: ${n}, success: ${r}`)}recordExpressionEval(e,t,r){t>1&&this.recordMetricInternal({type:"expressionEvalTime",value:t,pageVersionId:this.options.pageVersionId,timestamp:Date.now()})}recordError(e,t){var r,n;const i={type:e.name||"Error",message:e.message,stack:e.stack,traceId:this.traceId,pageVersionId:this.options.pageVersionId,componentVersion:null==t?void 0:t.componentVersion,actionId:null==t?void 0:t.actionId,context:t,timestamp:Date.now()};this.errors.push(i),this.log("error",`Error recorded: ${e.message}`),null==(n=(r=this.options).onError)||n.call(r,i),this.errors.length>=(this.options.batchSize??50)&&this.flush()}getMetrics(){return[...this.metrics]}getSpans(){return Array.from(this.spans.values())}getErrors(){return[...this.errors]}getPerformanceSummary(){const e=this.metrics.filter(e=>"componentLoadTime"===e.type),t=this.metrics.find(e=>"pageLoadTime"===e.type),r=this.metrics.find(e=>"firstRenderTime"===e.type);return{pageLoadTime:null==t?void 0:t.value,firstRenderTime:null==r?void 0:r.value,componentCount:e.length,avgComponentLoadTime:e.length>0?e.reduce((e,t)=>e+t.value,0)/e.length:0,errorCount:this.errors.length}}clear(){this.spans.clear(),this.metrics=[],this.errors=[]}async flush(){if(!this.shouldSample||!this.options.enabled)return;if(0===this.metrics.length&&0===this.errors.length&&0===this.spans.size)return;const e={traceId:this.traceId,pageVersionId:this.options.pageVersionId,appId:this.options.appId,runtimeVersion:this.options.runtimeVersion,spans:this.getSpans(),metrics:this.metrics,errors:this.errors,timestamp:Date.now()};if(this.clear(),this.options.endpoint)try{await fetch(this.options.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0}),this.log("debug","Telemetry flushed successfully")}catch(t){this.log("warn","Failed to flush telemetry:",t)}else this.log("debug","No endpoint configured, telemetry data discarded")}destroy(){this.flushTimer&&clearInterval(this.flushTimer),this.flush()}recordMetricInternal(e){var t,r;this.metrics.push(e),null==(r=(t=this.options).onMetric)||r.call(t,e),this.metrics.length>=(this.options.batchSize??50)&&this.flush()}startAutoFlush(){const e=this.options.flushInterval??3e4;this.flushTimer=setInterval(()=>this.flush(),e)}generateTraceId(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,e=>e.toString(16).padStart(2,"0")).join("")}generateSpanId(){const e=new Uint8Array(8);return crypto.getRandomValues(e),Array.from(e,e=>e.toString(16).padStart(2,"0")).join("")}log(e,t,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}},B=class e{constructor(e){this.container=null,this.renderedElements=new Map,this.componentEventListeners=new Map,this.expressionContext={state:{},binding:{},local:{}},this.loopContextStack=[],this.styleElement=null,this.options=e}init(){this.log("debug","Renderer initialized")}render(e,t){this.container=t,this.log("debug","Rendering page",e.pageId),this.cleanup(),t.innerHTML="",this.applyPageConfig(e,t),this.initializePageState(e);const r=this.renderNode(e.root);r&&t.appendChild(r),this.log("info",`Page rendered with root component: ${e.root.componentType}`)}updateComponent(e,t){const r=this.renderedElements.get(e);r?this.applyProps(r,t):this.log("warn",`Component not found: ${e}`)}updateContext(e){this.expressionContext={...this.expressionContext,...e}}getContext(){return{...this.expressionContext}}destroy(){this.cleanup(),this.container&&(this.container.innerHTML=""),this.log("debug","Renderer destroyed")}cleanup(){this.componentEventListeners.forEach((e,t)=>{const r=this.renderedElements.get(t);r&&e.forEach(({event:e,handler:t})=>{r.removeEventListener(e,t)})}),this.componentEventListeners.clear(),this.renderedElements.forEach(e=>{e.remove()}),this.renderedElements.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null),this.loopContextStack=[]}renderNode(e){const{id:t,componentType:r,componentVersion:n}=e;try{if(e.condition&&!this.evaluateCondition(e.condition))return this.log("debug",`Component ${t} hidden by condition`),null;if(e.loop)return this.renderLoop(e);const i=this.createElement(e);if(!i)return null;i.setAttribute("data-component-id",t),i.setAttribute("data-component-type",r),n&&i.setAttribute("data-component-version",n);const s=this.resolveProps(e.props);if(this.applyProps(i,s),e.style&&this.applyStyles(i,e.style),e.layout&&this.applyLayout(i,e.layout),this.options.injectHostApi(i,t),e.eventHandlers&&e.eventHandlers.length>0&&this.bindEventHandlers(i,t,e.eventHandlers),this.renderChildren(i,e),e.ref){const t=this.expressionContext.local,r=t.$refs||{};r[e.ref]=i,this.expressionContext={...this.expressionContext,local:{...t,$refs:r}}}return this.renderedElements.set(t,i),i}catch(i){return this.log("error",`Failed to render component: ${t}`,i),this.options.onRenderError?this.options.onRenderError(t,i):this.createErrorFallback(t,r,i)}}createElement(e){var t;const{componentType:r}=e,n=this.options.components.get(r);if(n&&customElements.get(r))return document.createElement(r);const i=`${r}-${null==(t=e.componentVersion)?void 0:t.replace(/\./g,"-")}`;if(customElements.get(i))return document.createElement(i);const s=document.createElement("div");return s.className=`djvlc-component djvlc-${r}`,n||(this.log("warn",`Component not loaded: ${r}`),s.classList.add("djvlc-component-fallback")),s}renderLoop(e){const{loop:t}=e;if(!t)return null;const r=this.evaluateExpression(t.items);if(!Array.isArray(r))return this.log("warn",`Loop items is not an array for ${e.id}`),null;const n=document.createDocumentFragment();r.forEach((r,i)=>{this.loopContextStack.push({item:r,index:i,loopConfig:t});const s={...this.expressionContext},a={...this.expressionContext.local,[t.itemName]:r,item:r,index:i};t.indexName&&(a[t.indexName]=i),this.expressionContext={...this.expressionContext,local:a};const o={...e,id:`${e.id}_${i}`,loop:void 0},c=this.renderNode(o);if(c){const e=this.evaluateExpression(t.key);c.setAttribute("data-loop-key",String(e??i)),n.appendChild(c)}this.expressionContext=s,this.loopContextStack.pop()});const i=document.createElement("div");return i.className="djvlc-loop-container",i.setAttribute("data-loop-id",e.id),i.appendChild(n),i}renderChildren(e,t){if(t.slots&&Object.keys(t.slots).length>0)for(const[r,n]of Object.entries(t.slots)){const t=this.createSlotContainer(r);for(const e of n){const r=this.renderNode(e);r&&t.appendChild(r)}e.appendChild(t)}}createSlotContainer(e){const t=document.createElement("div");return t.className=`djvlc-slot djvlc-slot-${e}`,t.setAttribute("data-slot",e),t}bindEventHandlers(e,t,r){const n=[];for(const i of r){const{eventName:r,preventDefault:s,stopPropagation:a,throttle:o,debounce:c,condition:u}=i;let l=e=>{if(u&&!this.evaluateCondition(u))return;s&&e.preventDefault(),a&&e.stopPropagation();const n=e.detail||{};this.options.onComponentEvent&&this.options.onComponentEvent(t,r,[i],n)};o&&o>0&&(l=this.createThrottledHandler(l,o)),c&&c>0&&(l=this.createDebouncedHandler(l,c)),e.addEventListener(r,l),n.push({event:r,handler:l})}this.componentEventListeners.set(t,n)}createThrottledHandler(e,t){let r=0;return n=>{const i=Date.now();i-r>=t&&(r=i,e(n))}}createDebouncedHandler(e,t){let r=null;return n=>{r&&clearTimeout(r),r=setTimeout(()=>{e(n),r=null},t)}}evaluateCondition(e){const t=this.evaluateExpression(e);return Boolean(t)}evaluateExpression(e){if(null==e)return e;if("object"==typeof e&&"type"in e&&"value"in e){const t=e,r=this.buildExpressionContext();return this.options.expressionEngine.evaluateWithFallback(t.value,r,t.fallback)}if("string"==typeof e){const t=this.buildExpressionContext();return this.options.expressionEngine.evaluateWithFallback(e,t,void 0)}return e}buildExpressionContext(){const e={};for(const t of this.loopContextStack)e[t.loopConfig.itemName]=t.item,e.item=t.item,e.index=t.index,t.loopConfig.indexName&&(e[t.loopConfig.indexName]=t.index);return{...this.expressionContext,local:{...this.expressionContext.local,...e}}}resolveProps(e){const t={};for(const[r,n]of Object.entries(e))t[r]=this.resolveValue(n);return t}resolveValue(t){if(null==t)return t;if("string"==typeof t)return t.includes("${")?this.options.expressionEngine.evaluateTemplate(t,this.buildExpressionContext()):t;if("number"==typeof t||"boolean"==typeof t)return t;if(Array.isArray(t))return t.map(e=>this.resolveValue(e));if("object"==typeof t){const r=t;if("string"==typeof r.type&&e.EXPRESSION_TYPES.includes(r.type)&&"string"==typeof r.value){const e=r;return this.options.expressionEngine.evaluateWithFallback(e.value,this.buildExpressionContext(),e.fallback)}const n={};for(const[e,t]of Object.entries(r))n[e]=this.resolveValue(t);return n}return t}applyProps(e,t){for(const[r,n]of Object.entries(t))null!=n&&(e.tagName.includes("-")?e[r]=n:"boolean"==typeof n?n?e.setAttribute(r,""):e.removeAttribute(r):"object"==typeof n?e.setAttribute(r,JSON.stringify(n)):e.setAttribute(r,String(n)))}applyStyles(e,t){if(t.inline)for(const[r,n]of Object.entries(t.inline)){if(null==n)continue;const t=this.resolveValue(n);let i;i="number"==typeof t?["zIndex","opacity","flex","fontWeight","lineHeight"].includes(r)?String(t):`${t}px`:String(t);const s=r.replace(/([A-Z])/g,"-$1").toLowerCase();e.style.setProperty(s,i)}t.className&&e.classList.add(...String(t.className).split(" ").filter(Boolean))}applyLayout(e,t){const{x:r,y:n,width:i,height:s,rotation:a,zIndex:o,responsive:c}=t;e.style.position="absolute",void 0!==r&&(e.style.left=`${r}px`),void 0!==n&&(e.style.top=`${n}px`),void 0!==i&&(e.style.width=`${i}px`),void 0!==s&&(e.style.height=`${s}px`),void 0!==a&&(e.style.transform=`rotate(${a}deg)`),void 0!==o&&(e.style.zIndex=String(o)),c&&this.applyResponsiveLayout(e,c)}applyResponsiveLayout(e,t){const r=e.getAttribute("data-component-id");if(!r)return;let n="";if(t.mobile&&(n+=`\n @media (max-width: 767px) {\n [data-component-id="${r}"] {\n ${this.layoutToCSS(t.mobile)}\n }\n }\n `),t.tablet&&(n+=`\n @media (min-width: 768px) and (max-width: 1023px) {\n [data-component-id="${r}"] {\n ${this.layoutToCSS(t.tablet)}\n }\n }\n `),t.desktop&&(n+=`\n @media (min-width: 1440px) {\n [data-component-id="${r}"] {\n ${this.layoutToCSS(t.desktop)}\n }\n }\n `),n){const e=document.createElement("style");e.setAttribute("data-djvlc-responsive",r),e.textContent=n,document.head.appendChild(e)}}layoutToCSS(e){const t=[];return void 0!==e.x&&t.push(`left: ${e.x}px`),void 0!==e.y&&t.push(`top: ${e.y}px`),void 0!==e.width&&t.push(`width: ${e.width}px`),void 0!==e.height&&t.push(`height: ${e.height}px`),void 0!==e.rotation&&t.push(`transform: rotate(${e.rotation}deg)`),void 0!==e.zIndex&&t.push(`z-index: ${e.zIndex}`),t.join("; ")}applyPageConfig(e,t){t.classList.add("djvlc-page"),t.setAttribute("data-page-id",e.pageId),t.setAttribute("data-page-version",e.pageVersion),t.setAttribute("data-schema-version",e.schemaVersion);const r=e.config;r&&(this.applyLayoutConfig(t,r.layout),r.styles&&this.applyStylesConfig(t,r.styles),r.behavior&&this.applyBehaviorConfig(t,r.behavior))}applyBehaviorConfig(e,t){t.debug&&e.setAttribute("data-debug","true"),t.i18n&&this.applyI18nConfig(e,t.i18n)}applyI18nConfig(e,t){const r=this.detectLocale(t);e.setAttribute("lang",r),e.setAttribute("data-locale",r),e.setAttribute("data-default-locale",t.defaultLocale),e.setAttribute("data-supported-locales",t.supportedLocales.join(",")),t.translationBundleId&&e.setAttribute("data-translation-bundle",t.translationBundleId),e.style.setProperty("--djvlc-locale",r),e.style.setProperty("--djvlc-dir",this.getTextDirection(r)),"rtl"===this.getTextDirection(r)?(e.setAttribute("dir","rtl"),e.classList.add("djvlc-rtl")):e.setAttribute("dir","ltr"),this.expressionContext={...this.expressionContext,local:{...this.expressionContext.local,$locale:r,$defaultLocale:t.defaultLocale,$supportedLocales:t.supportedLocales}},this.log("debug",`I18n configured: locale=${r}, default=${t.defaultLocale}`)}detectLocale(e){const{defaultLocale:t,supportedLocales:r,detection:n="browser"}=e;let i=null;switch(n){case"browser":case"header":i=this.detectBrowserLocale(r);break;case"url":i=this.detectUrlLocale(r);break;case"path":i=this.detectPathLocale(r);break;case"cookie":i=this.detectCookieLocale(r);break;case"manual":i=t;break;default:i=null}return i&&r.includes(i)?i:t}detectBrowserLocale(e){if("undefined"==typeof navigator)return null;const t=navigator.languages||[navigator.language];for(const r of t){if(e.includes(r))return r;const t=r.split("-")[0],n=e.find(e=>e===t||e.startsWith(`${t}-`));if(n)return n}return null}detectUrlLocale(e){if("undefined"==typeof window)return null;const t=new URLSearchParams(window.location.search),r=t.get("lang")||t.get("locale");return r&&e.includes(r)?r:null}detectPathLocale(e){if("undefined"==typeof window)return null;const t=window.location.pathname.split("/").filter(Boolean);if(t.length>0){const r=t[0];if(e.includes(r))return r}return null}detectCookieLocale(e){if("undefined"==typeof document)return null;const t=document.cookie.split(";");for(const r of t){const[t,n]=r.trim().split("=");if("lang"===t||"locale"===t||"language"===t){const t=decodeURIComponent(n);if(e.includes(t))return t}}return null}getTextDirection(e){const t=e.split("-")[0];return["ar","ar-SA","ar-EG","ar-AE","he","he-IL","fa","fa-IR","ur","ur-PK","yi","ps","dv"].some(r=>r===e||r===t)?"rtl":"ltr"}applyLayoutConfig(e,t){if(e.setAttribute("data-canvas-type",t.canvasType),t.canvasSize&&"responsive"!==t.canvasType&&(e.style.width=`${t.canvasSize.width}px`,e.style.minHeight=`${t.canvasSize.height}px`),t.maxWidth&&(e.style.maxWidth=`${t.maxWidth}px`,e.style.marginLeft="auto",e.style.marginRight="auto"),t.padding){const{top:r=0,right:n=0,bottom:i=0,left:s=0}=t.padding;e.style.padding=`${r}px ${n}px ${i}px ${s}px`}t.viewport&&(t.viewport.mobile&&e.style.setProperty("--djvlc-breakpoint-mobile",`${t.viewport.mobile}px`),t.viewport.tablet&&e.style.setProperty("--djvlc-breakpoint-tablet",`${t.viewport.tablet}px`),t.viewport.desktop&&e.style.setProperty("--djvlc-breakpoint-desktop",`${t.viewport.desktop}px`))}applyStylesConfig(e,t){if(t.theme&&this.applyThemeConfig(e,t.theme),t.background&&this.applyBackgroundConfig(e,t.background),t.cssVariables)for(const[r,n]of Object.entries(t.cssVariables)){const t=r.startsWith("--")?r:`--${r}`;e.style.setProperty(t,n)}t.customCSS&&this.injectCustomCSS(t.customCSS)}applyThemeConfig(e,t){if(t.preset&&(e.setAttribute("data-theme",t.preset),"system"===t.preset)){const t=window.matchMedia("(prefers-color-scheme: dark)").matches;e.setAttribute("data-theme-resolved",t?"dark":"light")}if(t.variables)for(const[r,n]of Object.entries(t.variables)){const t=r.startsWith("--")?r:`--theme-${r}`;e.style.setProperty(t,n)}t.transition&&e.style.setProperty("--djvlc-theme-transition","all 0.3s ease")}applyBackgroundConfig(e,t){switch(t.type){case"color":e.style.backgroundColor=t.value;break;case"image":e.style.backgroundImage=`url(${t.value})`,e.style.backgroundSize=t.size||"cover",e.style.backgroundPosition=t.position||"center",e.style.backgroundRepeat=t.repeat||"no-repeat";break;case"gradient":e.style.backgroundImage=t.value}}injectCustomCSS(e){e.trim()&&(this.styleElement=document.createElement("style"),this.styleElement.setAttribute("data-djvlc-custom","true"),this.styleElement.textContent=e,document.head.appendChild(this.styleElement))}initializePageState(e){if(e.state&&e.state.fields){const t={};for(const[r,n]of Object.entries(e.state.fields))n&&"object"==typeof n&&(t[r]=n.initialValue);this.expressionContext={...this.expressionContext,state:t}}}createErrorFallback(e,t,r){const n=document.createElement("div");return n.className="djvlc-error-boundary",n.setAttribute("data-component-id",e),n.setAttribute("data-error","true"),n.innerHTML=`\n <div class="djvlc-error-content">\n <span class="djvlc-error-icon">⚠️</span>\n <span class="djvlc-error-message">组件渲染失败: ${t}</span>\n ${this.options.debug?`<pre class="djvlc-error-detail">${r.message}</pre>`:""}\n </div>\n `,n}log(e,t,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}};B.EXPRESSION_TYPES=["state","binding","local","template","computed"];var q=B,V=class{constructor(e){this.lifecycle=null,this.mounted=!1,this.destroyed=!1,this.cleanupFns=[],this.options=e}register(e){var t,r,n;e?(this.lifecycle=e,this.log("debug","Lifecycle hooks registered",{onMounted:(null==(t=e.onMounted)?void 0:t.length)??0,onBeforeUnmount:(null==(r=e.onBeforeUnmount)?void 0:r.length)??0,onVisibilityChange:(null==(n=e.onVisibilityChange)?void 0:n.length)??0}),e.onVisibilityChange&&e.onVisibilityChange.length>0&&this.setupVisibilityListener()):this.log("debug","No lifecycle hooks defined")}async triggerMounted(){var e,t,r;this.mounted||this.destroyed||(this.mounted=!0,this.log("debug","Triggering onMounted lifecycle"),await this.executeLifecycleActions("mounted",null==(e=this.lifecycle)?void 0:e.onMounted),null==(r=(t=this.options).onLifecycleEvent)||r.call(t,"mounted"))}async triggerBeforeUnmount(){var e,t,r;this.mounted&&!this.destroyed&&(this.log("debug","Triggering onBeforeUnmount lifecycle"),await this.executeLifecycleActions("beforeUnmount",null==(e=this.lifecycle)?void 0:e.onBeforeUnmount),null==(r=(t=this.options).onLifecycleEvent)||r.call(t,"beforeUnmount"))}async triggerVisibilityChange(e){var t,r,n;if(!this.mounted||this.destroyed)return;this.log("debug","Triggering onVisibilityChange lifecycle",{isVisible:e});const i=this.options.getContext(),s={...i,local:{...i.local,$visible:e,$hidden:!e}};await this.executeLifecycleActionsWithContext("visibilityChange",null==(t=this.lifecycle)?void 0:t.onVisibilityChange,s),null==(n=(r=this.options).onLifecycleEvent)||n.call(r,"visibilityChange",{isVisible:e})}async destroy(){this.destroyed||(await this.triggerBeforeUnmount(),this.cleanupFns.forEach(e=>e()),this.cleanupFns=[],this.destroyed=!0,this.lifecycle=null,this.log("debug","LifecycleManager destroyed"))}isMounted(){return this.mounted&&!this.destroyed}isDestroyed(){return this.destroyed}setupVisibilityListener(){const e=()=>{const e="visible"===document.visibilityState;this.triggerVisibilityChange(e).catch(e=>{this.log("error","Failed to handle visibility change",e)})};document.addEventListener("visibilitychange",e),this.cleanupFns.push(()=>{document.removeEventListener("visibilitychange",e)}),this.log("debug","Visibility listener registered")}async executeLifecycleActions(e,t){if(!t||0===t.length)return;const r=this.options.getContext();await this.executeLifecycleActionsWithContext(e,t,r)}async executeLifecycleActionsWithContext(e,t,r){if(t&&0!==t.length){this.log("debug",`Executing ${t.length} actions for ${e}`);try{const n={id:`lifecycle_${e}`,eventName:e,actions:t};await this.options.actionBridge.handleEvent(n,{lifecycle:e},r),this.log("debug",`Lifecycle ${e} actions completed`)}catch(n){this.log("error",`Failed to execute lifecycle ${e} actions`,n)}}}log(e,t,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}},F=d.CURRENT_SCHEMA_VERSION,H="1.0.0";function K(e){return new Y(e)}var Y=class{constructor(e){this.container=null,this.options={channel:"prod",debug:!1,enableSRI:!0,env:"production",...e},this.logger=this.createLogger(),this.stateManager=new N,this.eventBus=new O({debug:e.debug,logger:this.logger}),this.expressionEngine=new k({debug:e.debug,logger:this.logger}),this.pageLoader=new S({apiBaseUrl:e.apiBaseUrl,channel:e.channel,authToken:e.authToken,previewToken:e.previewToken,headers:e.headers,logger:this.logger}),this.componentLoader=new I({cdnBaseUrl:e.cdnBaseUrl,enableSRI:e.enableSRI,logger:this.logger}),this.assetLoader=new T({cdnHosts:[new URL(e.cdnBaseUrl).host],apiHosts:[new URL(e.apiBaseUrl).host]}),this.securityManager=new P({enableSRI:e.enableSRI,cdnDomains:[new URL(e.cdnBaseUrl).host],apiDomains:[new URL(e.apiBaseUrl).host],logger:this.logger}),this.log("info","Runtime created",{version:H})}async init(){this.log("info","Initializing runtime");const e=performance.now();try{this.container=this.resolveContainer(),this.assetLoader.preconnectAll(),this.pageLoader.preconnect(),customElements.get("djvlc-fallback")||customElements.define("djvlc-fallback",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).innerHTML='\n <style>\n :host {\n display: block;\n padding: 16px;\n background: #fff2f0;\n border: 1px solid #ffccc7;\n border-radius: 4px;\n color: #ff4d4f;\n font-size: 14px;\n }\n .title {\n font-weight: 600;\n margin-bottom: 8px;\n }\n .message {\n color: #666;\n }\n </style>\n <div class="title">组件加载失败</div>\n <div class="message"><slot>请刷新页面重试</slot></div>\n '}static get observedAttributes(){return["message","component-name"]}attributeChangedCallback(e,t,r){if("message"===e&&this.shadowRoot){const e=this.shadowRoot.querySelector(".message");e&&(e.textContent=r)}if("component-name"===e&&this.shadowRoot){const e=this.shadowRoot.querySelector(".title");e&&(e.textContent=`组件 ${r} 加载失败`)}}}),customElements.get("djvlc-blocked")||customElements.define("djvlc-blocked",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).innerHTML='\n <style>\n :host {\n display: block;\n padding: 16px;\n background: #fffbe6;\n border: 1px solid #ffe58f;\n border-radius: 4px;\n color: #faad14;\n font-size: 14px;\n }\n .icon {\n margin-right: 8px;\n }\n </style>\n <span class="icon">⚠️</span>\n <span>此组件已被暂停使用</span>\n '}}),customElements.get("djvlc-error-boundary")||customElements.define("djvlc-error-boundary",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).innerHTML="\n <style>\n :host {\n display: block;\n padding: 16px;\n background: #f5f5f5;\n border: 1px dashed #d9d9d9;\n border-radius: 4px;\n color: #999;\n font-size: 14px;\n text-align: center;\n }\n </style>\n <slot>渲染出错</slot>\n "}}),this.stateManager.setPhase("resolving");const t=performance.now()-e;this.log("info",`Runtime initialized in ${t.toFixed(2)}ms`)}catch(t){throw this.handleError(t),t}}async load(){var e,t,r;this.log("info","Loading page:",this.options.pageUid);const n=performance.now();try{this.stateManager.setPhase("resolving");const i=await this.pageLoader.resolve(this.options.pageUid,{uid:this.options.userId,deviceId:this.options.deviceId});if(this.validateSchemaVersion(i.pageJson),this.stateManager.setPage(i),this.telemetryManager=new j({pageVersionId:i.pageVersionId,appId:this.options.appId,debug:this.options.debug,logger:this.logger,onMetric:this.options.onMetric}),i.runtimeConfig){const t=(null==(e=i.runtimeConfig.blockedComponents)?void 0:e.map(e=>`${e.name}@${e.version}`))||[];this.securityManager.updateBlockedList(t,[]),this.componentLoader.updateBlockedList(t)}this.stateManager.setPhase("loading"),this.componentLoader.preload(i.manifest.components),(await this.componentLoader.loadAll(i.manifest)).forEach((e,t)=>{this.stateManager.setComponentStatus(t,e),this.telemetryManager.recordComponentLoad(e.name,e.version,e.loadTime||0,"loaded"===e.status)}),this.initHostApi(i),this.initActionBridge(),this.initDataBindingManager(i.pageJson),this.initRenderer(),this.initLifecycleManager(i.pageJson);const s=performance.now()-n;return this.telemetryManager.recordPageLoad(s),this.log("info",`Page loaded in ${s.toFixed(2)}ms`),this.emitEvent("page:loaded",{page:i,loadTime:s}),null==(r=(t=this.options).onLoad)||r.call(t,i),i}catch(i){throw this.stateManager.setPhase("error"),this.handleError(i),i}}async render(){const e=this.stateManager.getState();if(!e.page||!this.container)throw new f("Page not loaded");this.log("info","Rendering page");const t=performance.now();try{this.stateManager.setPhase("rendering"),this.renderer.updateContext(this.stateManager.getExpressionContext()),this.renderer.render(e.page.pageJson,this.container),await this.dataBindingManager.initializeBindings(this.stateManager.getExpressionContext()),this.stateManager.setPhase("ready");const r=performance.now()-t;this.telemetryManager.recordFirstRender(r),this.log("info",`Page rendered in ${r.toFixed(2)}ms`),await this.lifecycleManager.triggerMounted(),this.emitEvent("page:rendered",{renderTime:r})}catch(r){throw this.stateManager.setPhase("error"),this.handleError(r),r}}getHostApi(){return this.hostApi}getState(){return this.stateManager.getState()}onStateChange(e){return this.stateManager.subscribe(e)}on(e,t){return this.eventBus.on(e,t)}updateComponent(e,t){this.renderer.updateComponent(e,t)}setVariable(e,t){this.stateManager.setVariable(e,t),this.renderer.updateContext(this.stateManager.getExpressionContext()),this.dataBindingManager.onStateChange(e,this.stateManager.getExpressionContext())}getVariable(e){return this.stateManager.getVariable(e)}async refreshData(e){await this.dataBindingManager.refreshBinding(e,this.stateManager.getExpressionContext()),this.renderer.updateContext(this.stateManager.getExpressionContext())}async executeAction(e,t){return this.hostApi.executeAction(e,t)}async destroy(){var e,t,r,n,i;this.log("info","Destroying runtime"),await(null==(e=this.lifecycleManager)?void 0:e.destroy()),null==(t=this.telemetryManager)||t.flush(),null==(r=this.dataBindingManager)||r.destroy(),null==(n=this.actionBridge)||n.destroy(),null==(i=this.renderer)||i.destroy(),this.eventBus.clear(),this.stateManager.setDestroyed(),this.container&&(this.container.innerHTML=""),this.emitEvent("page:destroyed",{}),this.log("info","Runtime destroyed")}validateSchemaVersion(e){if(e.schemaVersion!==F)throw new f(`Unsupported schema version: ${e.schemaVersion}. Only ${F} is supported.`,{schemaVersion:e.schemaVersion,supportedVersion:F})}resolveContainer(){const{container:e}=this.options;if("string"==typeof e){const t=document.querySelector(e);if(!t)throw new Error(`Container not found: ${e}`);return t}return e}initHostApi(e){this.hostApi=new U({apiBaseUrl:this.options.apiBaseUrl,authToken:this.options.authToken,headers:this.options.headers,stateManager:this.stateManager,eventBus:this.eventBus,expressionEngine:this.expressionEngine,context:{pageUid:e.pageUid,pageVersionId:e.pageVersionId,runtimeVersion:H,userId:this.options.userId,deviceId:this.options.deviceId,channel:this.options.channel,appId:this.options.appId||"",env:this.options.env||"production",isEditMode:!1,isPreviewMode:e.isPreview||!1},debug:this.options.debug,logger:this.logger})}initActionBridge(){this.actionBridge=new _({executor:{executeAction:(e,t)=>this.hostApi.executeAction(e,t),requestData:(e,t)=>this.hostApi.requestData(e,t),navigate:e=>this.hostApi.navigate(e),openDialog:e=>this.hostApi.openDialog(e),closeDialog:()=>this.hostApi.closeDialog(),showToast:e=>this.hostApi.showToast(e),showLoading:e=>this.hostApi.showLoading(e),hideLoading:()=>this.hostApi.hideLoading(),track:e=>this.hostApi.track(e),setState:(e,t)=>this.stateManager.setVariable(e,t),getState:e=>this.stateManager.getVariable(e),refreshData:e=>this.refreshData(e)},expressionEngine:this.expressionEngine,debug:this.options.debug,logger:this.logger,onActionStart:(e,t)=>{this.emitEvent("action:executing",{action:e,params:t})},onActionComplete:(e,t)=>{var r;t.success?this.emitEvent("action:executed",{action:e,data:t.data}):this.emitEvent("action:error",{action:e,error:null==(r=t.error)?void 0:r.message})}})}initDataBindingManager(e){this.dataBindingManager=new A({requester:{requestData:(e,t)=>this.hostApi.requestData(e,t)},stateSetter:{setVariable:(e,t)=>this.stateManager.setVariable(e,t),getVariable:e=>this.stateManager.getVariable(e)},expressionEngine:this.expressionEngine,debug:this.options.debug,logger:this.logger,onDataLoaded:(e,t)=>{var r;this.emitEvent("query:fetched",{bindingId:e,data:t}),null==(r=this.renderer)||r.updateContext(this.stateManager.getExpressionContext())},onDataError:(e,t)=>{this.emitEvent("query:error",{bindingId:e,error:t.message})}}),e.dataBindings&&this.dataBindingManager.registerBindings(e.dataBindings),this.stateManager.onStateChange(({key:e})=>{this.dataBindingManager.onStateChange(e,this.stateManager.getExpressionContext())})}initLifecycleManager(e){this.lifecycleManager=new V({actionBridge:this.actionBridge,getContext:()=>this.stateManager.getExpressionContext(),debug:this.options.debug,logger:this.logger,onLifecycleEvent:(e,t)=>{this.emitEvent(`page:lifecycle:${e}`,t??{})}}),this.lifecycleManager.register(e.lifecycle)}initRenderer(){const e=new Map;this.stateManager.getState().components.forEach((t,r)=>{if("loaded"===t.status&&t.component){const[n,i]=r.split("@");e.set(n,{name:n,version:i,Component:t.component,loadTime:t.loadTime||0})}}),this.renderer=new q({expressionEngine:this.expressionEngine,components:e,injectHostApi:(e,t)=>{e.hostApi=this.hostApi,e.componentId=t},onComponentEvent:(e,t,r,n)=>{this.handleComponentEvent(e,t,r,n)},debug:this.options.debug,logger:this.logger,onRenderError:(e,t)=>(this.log("error",`Render error in ${e}:`,t),this.emitEvent("component:error",{componentId:e,error:t.message}),function(e,t){const r=document.createElement("djvlc-error-boundary");return t&&r.setAttribute("message",t),r}(0,t.message))}),this.renderer.init()}handleComponentEvent(e,t,r,n){this.log("debug",`Component event: ${e}.${t}`,n);for(const i of r)this.actionBridge.handleEvent(i,n,this.stateManager.getExpressionContext())}handleError(e){var t;const r=e instanceof m?{type:"LOAD_ERROR",message:e.message,code:e.code,details:e.details,traceId:e.traceId,timestamp:e.timestamp}:{type:"UNKNOWN_ERROR",message:e.message,cause:e,timestamp:Date.now()};this.stateManager.setError(r),null==(t=this.telemetryManager)||t.recordError(e),this.emitEvent("page:error",{error:e.message}),this.options.onError&&this.options.onError(r)}emitEvent(e,t){var r;const n=O.createEvent(e,t,null==(r=this.telemetryManager)?void 0:r.getTraceId());this.eventBus.emit(n),this.options.onEvent&&this.options.onEvent(n)}createLogger(){return{debug:(...e)=>{this.options.debug},info:(...e)=>{},warn:(...e)=>{},error:(...e)=>{}}}log(e,t,...r){this.logger[e](t,...r)}},z=l(h());function J(e){if("undefined"!=typeof PerformanceObserver)try{const t=performance.getEntriesByType("paint").find(e=>"first-contentful-paint"===e.name);t&&(e.fcp=t.startTime),new PerformanceObserver(t=>{const r=t.getEntries(),n=r[r.length-1];n&&(e.lcp=n.startTime)}).observe({type:"largest-contentful-paint",buffered:!0}),new PerformanceObserver(t=>{const r=t.getEntries();if(r.length>0){const t=r[0];e.fid=t.processingStart-t.startTime}}).observe({type:"first-input",buffered:!0});let r=0;new PerformanceObserver(t=>{for(const n of t.getEntries()){const t=n;!t.hadRecentInput&&t.value&&(r+=t.value,e.cls=r)}}).observe({type:"layout-shift",buffered:!0})}catch{}}z.ErrorCode,z.ErrorMessages;class Q{constructor(e=!0){this.marks=new Map,this.measures=new Map,this.enabled=e}mark(e){this.enabled&&(this.marks.set(e,performance.now()),"function"==typeof performance.mark&&performance.mark(`djvlc:${e}`))}measure(e,t,r){if(!this.enabled)return 0;const n=this.marks.get(t),i=r?this.marks.get(r):performance.now();if(void 0===n)return 0;const s=(i??performance.now())-n;if(this.measures.set(e,s),"function"==typeof performance.measure)try{performance.measure(`djvlc:${e}`,`djvlc:${t}`,r?`djvlc:${r}`:void 0)}catch{}return s}getMeasures(){return Object.fromEntries(this.measures)}clear(){this.marks.clear(),this.measures.clear()}}function G(e=!0){return new Q(e)}function W(){const e=performance.timing||{},t=performance.getEntriesByType("navigation")[0];return t?{dns:t.domainLookupEnd-t.domainLookupStart,tcp:t.connectEnd-t.connectStart,ssl:t.secureConnectionStart>0?t.connectEnd-t.secureConnectionStart:0,ttfb:t.responseStart-t.requestStart,download:t.responseEnd-t.responseStart,domParse:t.domInteractive-t.responseEnd,domContentLoaded:t.domContentLoadedEventEnd-t.domContentLoadedEventStart,load:t.loadEventEnd-t.loadEventStart,total:t.loadEventEnd-t.startTime}:{dns:e.domainLookupEnd-e.domainLookupStart,tcp:e.connectEnd-e.connectStart,ttfb:e.responseStart-e.requestStart,download:e.responseEnd-e.responseStart,domParse:e.domInteractive-e.responseEnd,domContentLoaded:e.domContentLoadedEventEnd-e.domContentLoadedEventStart,load:e.loadEventEnd-e.loadEventStart,total:e.loadEventEnd-e.navigationStart}}function X(e){return performance.getEntriesByType("resource").filter(e||(()=>!0)).map(e=>({name:e.name,type:e.initiatorType,duration:e.duration,size:e.transferSize||0}))}function Z(){return X(e=>e.name.includes("/components/")||e.name.includes("/runtime/"))}function ee(e){e.forEach(e=>{const t=document.createElement("link");t.rel="preconnect",t.href=e.startsWith("http")?e:`https://${e}`,t.crossOrigin="anonymous",document.head.appendChild(t)})}function te(e,r=t){[`${e}/runtime/${r}/runtime.esm.js`,`${e}/runtime/${r}/runtime.css`].forEach(e=>{const t=document.createElement("link");t.rel="preload",t.href=e,t.as=e.endsWith(".js")?"script":"style",e.endsWith(".js")&&(t.crossOrigin="anonymous"),document.head.appendChild(t)})}function re(){const e="djv_device_id";let t=localStorage.getItem(e);if(!t){t=`${Date.now()}-${Math.random().toString(36).substring(2,11)}`;try{localStorage.setItem(e,t)}catch{}}return t}function ne(){return Array.from({length:32},()=>Math.floor(16*Math.random()).toString(16)).join("")}function ie(){return Array.from({length:16},()=>Math.floor(16*Math.random()).toString(16)).join("")}function se(){return`00-${ne()}-${ie()}-01`}const ae={getParam:(e,t=window.location.href)=>new URL(t).searchParams.get(e),setParam(e,t){const r=new URL(window.location.href);r.searchParams.set(e,t),window.history.replaceState({},"",r.toString())},removeParam(e){const t=new URL(window.location.href);t.searchParams.delete(e),window.history.replaceState({},"",t.toString())},build(e,t){const r=new URL(e,window.location.origin);return Object.entries(t).forEach(([e,t])=>{void 0!==t&&r.searchParams.set(e,String(t))}),r.toString()}};function oe(e){const t=()=>{e("visible"===document.visibilityState)};return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)}function ce(e){const t=()=>e(!0),r=()=>e(!1);return window.addEventListener("online",t),window.addEventListener("offline",r),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",r)}}function ue(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}function le(){return/MicroMessenger/i.test(navigator.userAgent)}async function he(){if("function"!=typeof createImageBitmap)return!1;try{const e=await(await fetch("data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA=")).blob();return await createImageBitmap(e),!0}catch{return!1}}async function de(e,t){var r,n,i,s;const{retryCount:a=3,retryDelay:o=1e3,timeout:c=3e4,collectWebVitals:u=!1}=t,l={initTime:0,loadTime:0,renderTime:0,totalTime:0,componentLoadCount:0,componentLoadErrors:0,dataRequestCount:0,dataRequestErrors:0},h=performance.now();let d=0,p=0,m=0;const f=K({container:e,pageUid:t.pageUid,apiBaseUrl:t.apiBaseUrl,cdnBaseUrl:t.cdnBaseUrl,channel:t.channel,userId:t.userId,deviceId:t.deviceId,authToken:t.authToken,previewToken:t.previewToken,debug:t.debug,enableSRI:t.enableSRI,headers:t.headers,onError:t.onError?e=>{var r;return null==(r=t.onError)?void 0:r.call(t,new Error(e.message))}:void 0,onMetric:e=>{if("object"==typeof e&&null!==e){const t=e;"component_load"===t.type&&(l.componentLoadCount++,t.error&&l.componentLoadErrors++),"data_request"===t.type&&(l.dataRequestCount++,t.error&&l.dataRequestErrors++)}}}),y=async(e,t,r)=>{try{return await e()}catch(n){if(t>0)return await new Promise(e=>setTimeout(e,r)),y(e,t-1,r);throw n}};try{await y(async()=>{var e,r;await(e=(async()=>{var e,r,n,i;d=performance.now(),null==(e=t.onPhaseChange)||e.call(t,"initializing"),await f.init(),l.initTime=performance.now()-d,p=performance.now(),null==(r=t.onPhaseChange)||r.call(t,"loading"),await f.load(),l.loadTime=performance.now()-p,m=performance.now(),null==(n=t.onPhaseChange)||n.call(t,"rendering"),await f.render(),l.renderTime=performance.now()-m,null==(i=t.onPhaseChange)||i.call(t,"ready")})(),r=c,Promise.race([e,new Promise((e,t)=>setTimeout(()=>t(new Error("加载超时")),r))]))},a,o),l.totalTime=performance.now()-h,u&&J(l),null==(r=t.onLoad)||r.call(t,f.getState()),null==(n=t.onMetric)||n.call(t,l)}catch(g){l.totalTime=performance.now()-h,null==(i=t.onMetric)||i.call(t,l);const e=g instanceof Error?g:new Error(String(g));throw null==(s=t.onError)||s.call(t,e),e}return{runtime:f,metrics:l,destroy:()=>f.destroy(),refresh:async()=>{await f.load(),await f.render()},setVariable:(e,t)=>f.setVariable(e,t),refreshData:e=>f.refreshData(e)}}function pe(e,t){const r="string"==typeof e?document.querySelector(e):e;if(!r)return{cancel:()=>{},promise:Promise.reject(new Error("Container element not found"))};let n,i,s=!1,a=null;const o=new Promise((e,t)=>{n=e,i=t});if(t.placeholder){const e="string"==typeof t.placeholder?(()=>{const e=document.createElement("div");return e.innerHTML=t.placeholder,e.firstElementChild})():t.placeholder;e&&r.appendChild(e)}return a=new IntersectionObserver(async o=>{const c=o[0];if((null==c?void 0:c.isIntersecting)&&!s){null==a||a.disconnect(),a=null,r.innerHTML="";try{const r=await de(e,t);n(r)}catch(u){i(u)}}},{rootMargin:t.rootMargin||"100px",threshold:t.threshold||0}),a.observe(r),{cancel:()=>{s=!0,null==a||a.disconnect(),i(new Error("Lazy mount cancelled"))},promise:o}}async function me(e,t){const{concurrency:r=3,continueOnError:n=!0}=t||{},i=performance.now(),s=new Map,a=new Map;for(let o=0;o<e.length;o+=r){const t=e.slice(o,o+r).map(async({id:e,container:t,options:r})=>{try{const n=await de(t,r);s.set(e,n)}catch(i){if(a.set(e,i),!n)throw i}});await Promise.all(t)}return{results:s,errors:a,totalTime:performance.now()-i}}async function fe(e){return ee([new URL(e.apiBaseUrl).host,new URL(e.cdnBaseUrl).host]),te(e.cdnBaseUrl,t),{mount:t=>de(t,e)}}class ye{constructor(e={}){this.events=[],this.flushTimer=null,this.config={endpoint:e.endpoint||"/api/track",batchSize:e.batchSize||10,flushInterval:e.flushInterval||5e3,enabled:!1!==e.enabled,sampleRate:e.sampleRate??1,reporter:e.reporter||this.defaultReporter.bind(this)},this.traceId=ne(),this.config.enabled&&this.config.flushInterval>0&&(this.flushTimer=setInterval(()=>this.flush(),this.config.flushInterval))}track(e,t,r){if(!this.config.enabled)return;if(Math.random()>this.config.sampleRate)return;const n={event:e,data:t,timestamp:Date.now(),traceId:this.traceId,...r};this.events.push(n),this.events.length>=this.config.batchSize&&this.flush()}trackPageView(e,t){this.track("page_view",{url:window.location.href,referrer:document.referrer,title:document.title},{pageUid:e,pageVersionId:t})}trackComponentView(e,t,r){this.track("component_view",{componentType:t},{componentId:e,pageUid:r})}trackComponentClick(e,t,r){this.track("component_click",{componentType:t},{componentId:e,pageUid:r})}trackAction(e,t,r,n){this.track("action_execute",{actionType:e,success:t,duration:r},{pageUid:n})}trackError(e,t){this.track("error",{message:e.message,stack:e.stack,...t})}async flush(){if(0===this.events.length)return;const e=[...this.events];this.events=[];try{await this.config.reporter(e)}catch(t){this.events=[...e,...this.events]}}destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flush()}async defaultReporter(e){this.config.endpoint&&await fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:e}),keepalive:!0})}}function ge(e){return new ye(e)}class be{constructor(e={}){this.config={endpoint:e.endpoint||"/api/errors",enabled:!1!==e.enabled,sampleRate:e.sampleRate??1,ignorePatterns:e.ignorePatterns||[],reporter:e.reporter||this.defaultReporter.bind(this),maxStackDepth:e.maxStackDepth||50},this.traceId=ne(),this.boundHandlers={error:this.handleError.bind(this),unhandledrejection:this.handleUnhandledRejection.bind(this)}}start(){this.config.enabled&&(window.addEventListener("error",this.boundHandlers.error),window.addEventListener("unhandledrejection",this.boundHandlers.unhandledrejection))}stop(){window.removeEventListener("error",this.boundHandlers.error),window.removeEventListener("unhandledrejection",this.boundHandlers.unhandledrejection)}report(e,t){if(!this.config.enabled)return;if(Math.random()>this.config.sampleRate)return;if(this.shouldIgnore(e.message))return;const r={message:e.message,stack:this.truncateStack(e.stack),type:"runtime",timestamp:Date.now(),url:window.location.href,userAgent:navigator.userAgent,context:t,traceId:this.traceId};this.config.reporter(r)}setTraceId(e){this.traceId=e}handleError(e){var t;if(!this.config.enabled)return;if(Math.random()>this.config.sampleRate)return;if(this.shouldIgnore(e.message))return;const r={message:e.message,stack:this.truncateStack(null==(t=e.error)?void 0:t.stack),type:"error",timestamp:Date.now(),url:window.location.href,userAgent:navigator.userAgent,context:{filename:e.filename,lineno:e.lineno,colno:e.colno},traceId:this.traceId};this.config.reporter(r)}handleUnhandledRejection(e){if(!this.config.enabled)return;if(Math.random()>this.config.sampleRate)return;const t=e.reason,r=t instanceof Error?t.message:String(t);if(this.shouldIgnore(r))return;const n={message:r,stack:t instanceof Error?this.truncateStack(t.stack):void 0,type:"unhandledrejection",timestamp:Date.now(),url:window.location.href,userAgent:navigator.userAgent,traceId:this.traceId};this.config.reporter(n)}shouldIgnore(e){return this.config.ignorePatterns.some(t=>t.test(e))}truncateStack(e){if(e)return e.split("\n").slice(0,this.config.maxStackDepth).join("\n")}async defaultReporter(e){if(this.config.endpoint)try{await fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0})}catch{}}}function ve(e){return new be(e)}class we{constructor(e="djvlc",t=!1){this.namespace=e,this.storage=t?sessionStorage:localStorage}getKey(e){return`${this.namespace}:${e}`}get(e){try{const t=this.storage.getItem(this.getKey(e));if(!t)return null;const{value:r,expires:n}=JSON.parse(t);return n&&Date.now()>n?(this.remove(e),null):r}catch{return null}}set(e,t,r){try{const n={value:t,expires:r?Date.now()+r:void 0};this.storage.setItem(this.getKey(e),JSON.stringify(n))}catch{}}remove(e){this.storage.removeItem(this.getKey(e))}clear(){const e=[];for(let t=0;t<this.storage.length;t++){const r=this.storage.key(t);(null==r?void 0:r.startsWith(`${this.namespace}:`))&&e.push(r)}e.forEach(e=>this.storage.removeItem(e))}}function Ee(e,t){return new we(e,t)}const Se={RUNTIME_VERSION:t,mount:de,lazyMount:pe,batchMount:me,warmup:fe,createTrackingManager:ge,createErrorReporter:ve,createPerformanceMonitor:G,getPagePerformance:W,getResourcePerformance:X,getRuntimeResourcePerformance:Z,createStorageHelper:Ee,preconnect:ee,preloadAssets:te,getDeviceId:re,generateTraceId:ne,generateSpanId:ie,generateTraceparent:se,urlUtils:ae,onVisibilityChange:oe,onNetworkChange:ce,isMobile:ue,isWeChat:le,supportsWebP:he,createRuntime:K};return e.ErrorReporter=be,e.PerformanceMonitor=Q,e.RUNTIME_VERSION=t,e.StorageHelper=we,e.TrackingManager=ye,e.batchMount=me,e.collectWebVitalsMetrics=J,e.createErrorReporter=ve,e.createPerformanceMonitor=G,e.createRuntime=K,e.createStorageHelper=Ee,e.createTrackingManager=ge,e.default=Se,e.generateSpanId=ie,e.generateTraceId=ne,e.generateTraceparent=se,e.getDeviceId=re,e.getPagePerformance=W,e.getResourcePerformance=X,e.getRuntimeResourcePerformance=Z,e.isMobile=ue,e.isWeChat=le,e.lazyMount=pe,e.mount=de,e.onNetworkChange=ce,e.onVisibilityChange=oe,e.preconnect=ee,e.preloadAssets=te,e.supportsWebP=he,e.urlUtils=ae,e.warmup=fe,Object.defineProperties(e,{t:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),e}({});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@djvlc/runtime-web",
3
- "version": "1.0.3",
3
+ "version": "1.0.5",
4
4
  "description": "DJV 低代码平台浏览器版运行时(CDN 发布用)",
5
5
  "type": "module",
6
6
  "main": "./dist/runtime.iife.js",
@@ -33,9 +33,8 @@
33
33
  "clean": "rimraf dist"
34
34
  },
35
35
  "dependencies": {
36
- "@djvlc/contracts-types": "^1.4.0",
37
36
  "@djvlc/openapi-user-client": "^1.5.0",
38
- "@djvlc/runtime-core": "1.0.0"
37
+ "@djvlc/runtime-core": "1.0.2"
39
38
  },
40
39
  "devDependencies": {
41
40
  "@types/node": "^20.10.0",
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAKpD,eAAO,MAAM,eAAe,QAA6E,CAAC;AAI1G;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,aAAa;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,iBAAiB;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,iBAAiB;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS;IACT,OAAO,CAAC,EAAE,SAAS,GAAG,MAAM,GAAG,MAAM,CAAC;IACtC,YAAY;IACZ,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,YAAY;IACZ,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,eAAe;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,6BAA6B;IAC7B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW;IACX,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,kBAAkB;IAClB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,aAAa;IACb,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,aAAa;IACb,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,OAAO,KAAK,IAAI,CAAC;IACjC,WAAW;IACX,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,aAAa;IACb,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI,CAAC;CACtC;AAED;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,YAAY;IACZ,OAAO,EAAE,UAAU,CAAC,OAAO,aAAa,CAAC,CAAC;IAC1C,WAAW;IACX,OAAO,EAAE,MAAM,IAAI,CAAC;CACrB;AAID;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,KAAK,CACzB,SAAS,EAAE,MAAM,GAAG,WAAW,EAC/B,OAAO,EAAE,YAAY,GACpB,OAAO,CAAC,WAAW,CAAC,CAoCtB;AAID;;;;;;;;;GASG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI,CAQhD;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,GAAE,MAAwB,GAAG,IAAI,CAgBzF;AAED;;GAEG;AACH,wBAAgB,WAAW,IAAI,MAAM,CAcpC;AAED;;GAEG;AACH,wBAAgB,eAAe,IAAI,MAAM,CAIxC;AAED;;GAEG;AACH,wBAAgB,cAAc,IAAI,MAAM,CAIvC;AAED;;GAEG;AACH,wBAAgB,mBAAmB,IAAI,MAAM,CAI5C;AAID,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,YAAY,EAAE,cAAc,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;;;;;;;;;;;;AAIjG,wBAUE"}