@doubao-dev/kit 0.8.0-rc.11 → 0.8.0-rc.12

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,4 +1,4 @@
1
- (()=>{"use strict";var e,t,r,i,n,a,s,o,l,d,u,c,p={38114(e,t,r){let i,n,a;r(52205),r(40768),r(76235),r(15254),r(42949),r(18723),r(37891);var s=r(63159);function o(e){return"object"==typeof e&&null!==e}function l(e){var t;return"string"==typeof(null==(t=e.web)?void 0:t.entry)}function d(e,t){let r=new Map;for(let i of e){let e=t(i);e&&!r.has(e)&&r.set(e,i)}return r}function u(e){return"string"==typeof e?e||void 0:(null==e?void 0:e["3x"])||(null==e?void 0:e["2x"])||(null==e?void 0:e["1x"])}r(84086),r(21301),r(49678),r(32037),r(14104),r(66249),r(99811),r(40009),r(13035),r(13412),r(17973),r(64955),r(91016),r(23306),r(76619),r(57857),r(9975),r(93885),r(812),r(74180),r(994),r(4267),r(74678),r(55910),r(76691),r(72919);class c{raw;appEntry;pageEntries;pageIdEntryMap;pagePathEntryMap;widgetEntries;widgetEntryMap;constructor(e){var t;let r;this.raw=e,this.appEntry="string"==typeof(r=(null==(t=e.applet.web)?void 0:t.appRuntimeEntry)??e.applet.appRuntimeEntry)&&r?{entry:r}:null,this.pageEntries=e.applet.pages.filter(l),this.pageIdEntryMap=d(this.pageEntries,e=>e.id),this.pagePathEntryMap=d(this.pageEntries,e=>{var t;return(null==(t=e.path)?void 0:t.startsWith("/"))?e.path:void 0}),this.widgetEntries=e.widgets,this.widgetEntryMap=d(this.widgetEntries,e=>e.widgetId)}get appId(){return"string"==typeof this.raw.appId?this.raw.appId:void 0}get name(){return this.raw.applet.name}get iconSrc(){return u(this.raw.applet.icons)}get versionName(){return this.raw.versionName||this.raw.versionTag||this.raw.versionCode||void 0}get pages(){return this.getPageEntries()}get widgets(){return this.getWidgetEntries()}get appRuntimeEntry(){return this.appEntry}getPageEntries(){return[...this.pageEntries]}getWidgetEntries(){return[...this.widgetEntries]}getOptionalWidgetEntry(e){return e?this.widgetEntryMap.get(e):this.widgetEntries[0]}getPageEntry(e){let t=e?e.startsWith("/")?this.pagePathEntryMap.get(e):this.pageIdEntryMap.get(e):this.pageEntries[0];if(!t)throw Error(e?`Unknown pages entry: ${e}`:"No pages entries in Web manifest");return t}getWidgetEntry(e){let t=this.getOptionalWidgetEntry(e);if(!t)throw Error(e?`Unknown widgets entry: ${e}`:"No widgets entries in Web manifest");return t}}async function p(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.fetcher??fetch,i=await r(e,{cache:"no-store",headers:{Accept:"application/json"}});if(!i.ok)throw Error(`Failed to load Web manifest: ${i.status} ${i.statusText}`);let n=await i.json();if(!o(n))throw Error("Invalid Web manifest: expected a JSON object");return new c(n)}function h(e,t,r){var i,n;let a="item"in t?t.item:t,s="id"in a||"widgetId"in a?"string"==typeof(null==(i=a.web)?void 0:i.entry)?a.web.entry:void 0:a.entry;if(!s)return;let o=new URL(e,r??(null==(n=globalThis.location)?void 0:n.href)??"http://localhost/");return o.pathname=o.pathname.replace(/\/base\/manifest\.json$/,"/"),new URL(s,o).toString()}function m(){let e=Error("Widget host call was cancelled");return e.name="AbortError",e}function g(e){if(e.aborted)throw m()}function f(e,t){return g(t),new Promise((r,i)=>{let n=!1,a=e=>{n||(n=!0,t.removeEventListener("abort",s),e())},s=()=>a(()=>i(m()));t.addEventListener("abort",s,{once:!0}),Promise.resolve().then(e).then(e=>a(()=>r(e)),e=>a(()=>i(e)))})}function v(e){return(null==e?void 0:e.type)==="call"}function y(e){return(null==e?void 0:e.type)==="callback"}function b(e){return(null==e?void 0:e.type)==="event"}class w extends Error{errNo;errMsg;constructor(e,t,r=e){super(e),this.errNo=t,this.errMsg=r,Object.setPrototypeOf(this,new.target.prototype),this.name="BridgeAPIError"}}function _(e,t){return{type:"callback",callbackId:e.callbackId,params:{code:1,data:t}}}function S(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:t;return{type:"callback",callbackId:e.callbackId,params:{code:0,msg:t,errNo:r,errMsg:i}}}function x(e){return e instanceof Error?e.message:String(e)}function I(e,t){return t instanceof w?S(e,t.message,t.errNo,t.errMsg):S(e,x(t))}r(67548),r(70954),r(98803),r(79162),r(15385),r(39342),r(69152),r(61955),r(82689),r(84847),r(16285),r(20602),r(33307),r(94341),r(7270),r(44997),r(50364),r(79780),r(80372),r(72498),r(37928),r(25597),r(92321);class k{registry=new Map;eventSources=new Map;eventSourceCleanups=new Map;eventSourceRetainCounts=new Map;eventControllers=new Set;handlers={};constructor(e){e&&this.registerMany(e)}register(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!r.override&&this.registry.has(e))throw Error(`Bridge API handler ${e} is already registered`);let i=this.registry.get(e),n="function"==typeof t?{handler:t,canIUse:!0}:{...t,canIUse:t.canIUse??!0};return this.registry.set(e,n),this.handlers[e]=n.handler,()=>{if(this.registry.get(e)===n){if(i){this.registry.set(e,i),this.handlers[e]=i.handler;return}this.registry.delete(e),delete this.handlers[e]}}}registerMany(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=[];try{for(let[i,n]of Object.entries(e))r.push(this.register(i,n,t))}catch(e){for(let e of r.reverse())e();throw e}return()=>{for(let e of r.reverse())e()}}get(e){var t;return null==(t=this.registry.get(e))?void 0:t.handler}getSyncResults(e){let t={};for(let[r,i]of this.registry)i.syncResult&&this.canIUse(r,e)&&(t[r]="function"==typeof i.syncResult?i.syncResult({...e,apiRegistry:this}):i.syncResult);return t}registerEventSource(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!r.override&&this.eventSources.has(e))throw Error(`Bridge event source ${e} is already registered`);let i=this.eventSources.get(e),n="function"==typeof t?{source:t}:t;return this.stopEventSource(e),this.eventSources.set(e,n),(this.eventSourceRetainCounts.get(e)??0)>0&&this.startEventSource(e,n),()=>{if(this.eventSources.get(e)===n){if(this.stopEventSource(e),i){this.eventSources.set(e,i),(this.eventSourceRetainCounts.get(e)??0)>0&&this.startEventSource(e,i);return}this.eventSources.delete(e)}}}registerEventSources(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=[];try{for(let[i,n]of Object.entries(e))r.push(this.registerEventSource(i,n,t))}catch(e){for(let e of r.reverse())e();throw e}return()=>{for(let e of r.reverse())e()}}canIUse(e,t){let r=this.registry.get(e);if(r)return"function"==typeof r.canIUse?r.canIUse({...t,apiRegistry:this}):r.canIUse;let i=this.eventSources.get(e);return!!i&&("function"==typeof i.canIUse?i.canIUse({...t,apiRegistry:this}):i.canIUse??!0)}dispatch(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;if(!v(e))return;let i={...t,apiRegistry:this};if(this.canIUse(e.name,i))return function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!v(e))return;let i=t[e.name];if(!i)return S(e,`API ${e.name} is not implemented in Doubao Web SDK`);try{let t=i(e,r);if(t instanceof Promise)return t.catch(t=>I(e,t));return t??S(e,`API ${e.name} is not implemented in Doubao Web SDK`)}catch(t){return I(e,t)}}(e,this.handlers,i);let n=this.registry.has(e.name)?103:-1;if(!r)return S(e,`API ${e.name} is not implemented in Doubao Web SDK`,n);try{let t=r(e.name);return t instanceof Promise?t.then(()=>S(e,`API ${e.name} is not implemented in Doubao Web SDK`,n)).catch(t=>I(e,t)):S(e,`API ${e.name} is not implemented in Doubao Web SDK`,n)}catch(t){return I(e,t)}}getSupportedNames(e){return[...new Set([...this.registry.keys(),...this.eventSources.keys()])].filter(t=>this.canIUse(t,e))}emitEvent(e,t){let r=!1;for(let i of this.eventControllers)r=i.emit(e,t)||r;return r}createEventController(e){return new C(this,e)}fork(){let e=new k(this.getRegistrations());return e.registerEventSources(this.getEventSources()),e}getRegistrations(){return Object.fromEntries(this.registry)}getEventSources(){return Object.fromEntries(this.eventSources)}attachEventController(e){return this.eventControllers.add(e),()=>{this.eventControllers.delete(e)}}retainEventSource(e){let t=this.eventSourceRetainCounts.get(e)??0;if(this.eventSourceRetainCounts.set(e,t+1),t>0)return;let r=this.eventSources.get(e);r&&this.startEventSource(e,r)}releaseEventSource(e){let t=this.eventSourceRetainCounts.get(e)??0;if(t<=1){this.eventSourceRetainCounts.delete(e),this.stopEventSource(e);return}this.eventSourceRetainCounts.set(e,t-1)}notifyEventSubscription(e,t,r){var i,n;null==(n=this.eventSources.get(e))||null==(i=n.onSubscribe)||i.call(n,t,r)}startEventSource(e,t){this.stopEventSource(e);let r=t.source(t=>{this.emitEvent(e,t)});"function"==typeof r&&this.eventSourceCleanups.set(e,r)}stopEventSource(e){var t;null==(t=this.eventSourceCleanups.get(e))||t(),this.eventSourceCleanups.delete(e)}}class C{apiRegistry;dispatch;cleanupRegistry;subscribedEventNames=new Set;cleanups=new Set;destroyed=!1;visible=!0;visibilityListeners=new Set;constructor(e,t){this.apiRegistry=e,this.dispatch=t,this.cleanupRegistry=this.apiRegistry.attachEventController(this)}subscribe(e,t){this.destroyed||this.subscribedEventNames.has(e)||(this.subscribedEventNames.add(e),this.apiRegistry.retainEventSource(e),this.apiRegistry.notifyEventSubscription(e,this,t))}unsubscribe(e){this.subscribedEventNames.delete(e)&&this.apiRegistry.releaseEventSource(e)}isSubscribed(e){return this.subscribedEventNames.has(e)}emit(e,t){return!!this.isSubscribed(e)&&this.emitPrivate(e,t)}emitPrivate(e,t){return!this.destroyed&&(this.dispatch(e,t),!0)}setVisible(e){for(let t of(this.visible=e,this.visibilityListeners))t(e)}onVisibilityChange(e){return e(this.visible),this.visibilityListeners.add(e),()=>this.visibilityListeners.delete(e)}onDestroy(e){return this.destroyed?(e(),()=>{}):(this.cleanups.add(e),()=>this.cleanups.delete(e))}destroy(){if(!this.destroyed){for(let e of(this.destroyed=!0,this.cleanups))try{e()}catch(e){console.error("Failed to clean up bridge API resources",e)}for(let e of(this.cleanups.clear(),this.visibilityListeners.clear(),this.subscribedEventNames))this.apiRegistry.releaseEventSource(e);this.subscribedEventNames.clear(),this.cleanupRegistry()}}}let E=new k;function N(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:i;return null==e?void 0:e.getPackageInfo()}async function T(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i;return await (null==t?void 0:t.navigateTo(e)),!!t}async function A(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i;return await (null==t?void 0:t.redirectTo(e)),!!t}async function M(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i;return await (null==t?void 0:t.reLaunch(e)),!!t}function j(){return"0.8.0-rc.11"}function R(e){var t;let{screenWidth:r,statusBarHeight:i}=e??(null==(t=globalThis.lynx)?void 0:t.__globalProps),n=Math.round(i)+4,a=Math.round(r)-12;return{bottom:n+36,height:36,left:a-84,right:a,top:n,width:84}}function P(){return(navigator.language||"zh-CN").replace(/-/g,"_")}function L(){var e,t,r;return(null==(t=(r=window).matchMedia)||null==(e=t.call(r,"(prefers-color-scheme: dark)"))?void 0:e.matches)?"dark":"light"}function D(){return"string"==typeof DoubaoAppsSDKVersion?DoubaoAppsSDKVersion:j()??""}function O(){return navigator.userAgentData}function U(){var e;let t=null==(e=O())?void 0:e.brands,r=null==t?void 0:t.find(e=>{let{brand:t}=e;return!/not.a.brand/i.test(t)});if(null==r?void 0:r.brand)return r.brand;let i=navigator.userAgent??"";return/edg\//i.test(i)?"Microsoft Edge":/chrome|crios/i.test(i)?"Chrome":/firefox|fxios/i.test(i)?"Firefox":/safari/i.test(i)?"Safari":"Browser"}function $(){var e,t;let r=null==(e=O())?void 0:e.brands,i=null==r?void 0:r.find(e=>{let{brand:t}=e;return!/not.a.brand/i.test(t)});if(null==i?void 0:i.version)return i.version;let n=navigator.userAgent??"";return(null==(t=/(?:edg|chrome|crios|firefox|fxios|version)\/([\d.]+)/i.exec(n))?void 0:t[1])??void 0}function q(){var e;let t=navigator.userAgent??"",r=navigator.platform??"",i=(null==(e=O())?void 0:e.platform)??"",n=`${i} ${r} ${t}`,a=navigator.maxTouchPoints??0;return/android/i.test(n)?{platform:"android",brand:"Android"}:/iphone/i.test(n)?{platform:"ios",brand:"iPhone"}:/ipad/i.test(n)||/mac/i.test(r)&&a>1?{platform:"ios",brand:"iPad"}:/mac/i.test(n)?{platform:"mac",brand:"Mac"}:/win/i.test(n)?{platform:"windows",brand:"Windows"}:/linux/i.test(n)?{platform:"linux",brand:"Linux"}:{platform:"web",brand:"Browser"}}function B(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:N();return{appId:(null==e?void 0:e.appId)??"",name:(null==e?void 0:e.name)??"",iconSrc:null==e?void 0:e.iconSrc}}function F(e){var t,r,i,n,a;if((null==e?void 0:e.containerWidth)!==void 0){let{density:t=1,screenWidth:r=0,screenHeight:i=0,containerWidth:n=0,containerHeight:a=0,statusBarHeight:s=0,topHeight:o=s,safeArea:l={}}=e,{marginTop:d=0,marginBottom:u=0,marginLeft:c=0,marginRight:p=0}=l;return{pixelRatio:t,screenWidth:r,screenHeight:i,windowWidth:n,windowHeight:a,statusBarHeight:s,screenTop:o,safeArea:{left:c,right:n-p,top:d,bottom:a-u,width:n-c-p,height:a-d-u}}}let s=Math.round((null==(n=window.visualViewport)?void 0:n.width)??window.innerWidth??0),o=Math.round((null==(a=window.visualViewport)?void 0:a.height)??window.innerHeight??0),l=window.devicePixelRatio??1,d=Math.round((null==(t=window.screen)?void 0:t.width)??s),u=Math.round((null==(r=window.screen)?void 0:r.height)??o),c=Math.round((null==(i=window.visualViewport)?void 0:i.offsetTop)??0);return{pixelRatio:l,screenWidth:d,screenHeight:u,windowWidth:s,windowHeight:o,statusBarHeight:c,safeArea:{left:0,right:s,top:c,bottom:o,width:s,height:Math.max(0,o-c)},screenTop:c}}function W(){return q().platform}function z(){var e,t,r,i,n;let a=navigator.userAgent??"",s=W();return"android"===s?null==(e=/android\s+([\d.]+)/i.exec(a))?void 0:e[1]:"ios"===s?null==(r=/(?:iphone os|cpu os)\s+([\d_]+)/i.exec(a))||null==(t=r[1])?void 0:t.replace(/_/g,"."):"mac"===s?null==(n=/mac os x\s+([\d_]+)/i.exec(a))||null==(i=n[1])?void 0:i.replace(/_/g,"."):void 0}function H(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:W();return"android"===e?"Android":"ios"===e?"iOS":"mac"===e?"macOS":"windows"===e?"Windows":"linux"===e?"Linux":"Web"}function V(e){let t;if((null==e?void 0:e.deviceModel)!==void 0){let t=e.os??e.devicePlatform??"";return{abi:e.abi,deviceAbi:e.deviceAbi,cpuType:e.cpuType,benchmarkLevel:"number"==typeof e.benchmarkLevel?e.benchmarkLevel:-1,brand:e.deviceBrand??"",model:e.deviceModel??e.deviceType??"",system:e.osVersion?`${t} ${e.osVersion}`:t,platform:(e.platform??t).toLowerCase(),memorySize:null==e.memorySize?"":String(e.memorySize)}}let r=q(),i=navigator.platform||W();return{abi:i,deviceAbi:i,benchmarkLevel:-1,brand:r.brand,model:function(){let e=navigator.userAgent??"",t=W();if("android"===t){var r,i;return(null==(i=/android\s+[\d.]+;\s*([^;)]+)/i.exec(e))||null==(r=i[1])?void 0:r.trim())||"Android"}return"ios"===t?q().brand:"mac"===t||"windows"===t||"linux"===t?navigator.platform||q().brand:U()}(),system:function(){let e=W(),t=z();if("web"!==e){let r=H(e);return t?`${r} ${t}`:r}let r=$(),i=U();return r?`${i} ${r}`:"Web"}(),platform:r.platform,cpuType:i,memorySize:"number"==typeof(t=navigator.deviceMemory)&&Number.isFinite(t)?String(Math.round(1024*t)):""}}function G(){let e=V(),t=F(),r=t.windowWidth>t.windowHeight;return{os:H(e.platform),platform:e.platform,osVersion:z(),deviceBrand:e.brand,language:P(),deviceModel:e.model,deviceType:e.model,deviceAbi:e.deviceAbi,cpuType:e.cpuType,memorySize:e.memorySize,benchmarkLevel:e.benchmarkLevel,appVersion:$(),appTheme:L(),channel:"release",screenOrientation:+!!r,isLandscape:+!!r,abi:e.abi}}function J(e){var t,r,i;let n,a=F(e),s=V(e);return{...a,brand:s.brand,model:s.model,language:(null==e||null==(t=e.language)?void 0:t.replace(/-/g,"_"))??P(),version:(null==e?void 0:e.appVersion)??$(),system:s.system,platform:(null==e||null==(r=e.os)?void 0:r.toLowerCase())??s.platform,SDKVersion:D(),theme:(null==e?void 0:e.appTheme)??L(),benchmarkLevel:s.benchmarkLevel,enableDebug:(null==e?void 0:e.channel)==="debug",deviceOrientation:(i=a.windowWidth>a.windowHeight,!0===(n=(null==e?void 0:e.isLandscape)??(null==e?void 0:e.screenOrientation))||1===n||"string"==typeof n&&n.toLowerCase().includes("landscape")?"landscape":!1===n||0===n||"string"==typeof n&&n.toLowerCase().includes("portrait")?"portrait":i?"landscape":"portrait"),abi:s.abi}}function K(){let e={isConnected:!1!==navigator.onLine,networkType:!1===navigator.onLine?"none":"unknown",hasSystemProxy:!1,weakNet:!1};return{networkType:e.networkType,signalStrength:e.signalStrength,hasSystemProxy:e.hasSystemProxy??!1,weakNet:e.weakNet??!1}}function Z(e){return{SDKVersion:D(),enableDebug:(null==e?void 0:e.channel)==="debug",host:{appId:(null==e?void 0:e.appName)??""},language:(null==e?void 0:e.language)??P(),version:(null==e?void 0:e.appVersion)??$(),theme:(null==e?void 0:e.appTheme)??L()}}function X(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:N(),t=arguments.length>1?arguments[1]:void 0;return{miniProgram:{appId:B(e).appId,envVersion:(null==t?void 0:t.channel)==="debug"?"develop":"release",version:(null==e?void 0:e.versionName)??""}}}function Y(e){var t;return(null==e||null==(t=e.navigation)?void 0:t.getPackageInfo())??(null==e?void 0:e.packageInfo)}E.handlers,r(31178),r(32085),r(12021);var Q=r(95550),ee=r(66013);r(46455);function et(e){if("string"!=typeof e)throw Error("key must be a string");if(0===e.length)throw Error("key must not be empty");if(e.length>1024)throw Error("key length must be less than or equal to 1024");return e}function er(e){if(ei(e)>1048576)throw Error("data size must be less than or equal to 1048576 bytes")}function ei(e){return new TextEncoder().encode(e).byteLength}function en(e){return Object.values(e).reduce((e,t)=>e+ei(t),0)}function ea(e){if(e>0xa00000)throw new w("total storage size exceeded",1600002)}function es(e){if(!o(e)||Array.isArray(e))throw Error("Storage snapshot must be an object");let t=0;for(let[r,i]of Object.entries(e)){if(et(r),"string"!=typeof i)throw Error("Storage values must be serialized strings");er(i),t+=ei(i)}ea(t)}let eo=new Map,el=new Map,ed=new Set;function eu(e,t){var r;let i=JSON.stringify([(null==e||null==(r=e.packageInfo)?void 0:r.appId)||"unknown-app",t??null]);return`web-storage:${(0,ee.My)((0,Q.sc)(i))}`}function ec(){let e=Date.now();return{entries:Object.fromEntries(["/","/temp","/user"].map(t=>[t,{type:"directory",createTime:e,lastModifiedTime:e}]))}}function ep(){return n??=new Promise((e,t)=>{let r=indexedDB.open("doubao-web-sdk-files",2);r.onupgradeneeded=()=>{let e=r.result;for(let t of["storage","files"])e.objectStoreNames.contains(t)||e.createObjectStore(t)},r.onsuccess=()=>{r.result.onversionchange=()=>{r.result.close(),n=void 0},e(r.result)},r.onerror=()=>{n=void 0,t(r.error)},r.onblocked=()=>{n=void 0,t(Error("Storage database upgrade is blocked; close other app views and retry"))}})}function eh(e){return IDBKeyRange.bound([e],[e,[]])}function em(e){return new Promise((t,r)=>{e.oncomplete=()=>t(),e.onabort=()=>{let t=e.error,i=new w((null==t?void 0:t.message)??"Storage transaction failed",(null==t?void 0:t.name)==="QuotaExceededError"?208:102);i.cause=t,r(i)}})}async function eg(e,t){let r=await ep(),i=r.transaction(["storage","files"]),n=em(i);for(let[r,n]of[["storage",t.storageSnapshot],["files",t.fileSystemSnapshot.entries]]){let t=i.objectStore(r).openCursor(eh(e));t.onsuccess=()=>{let e=t.result;e&&(Object.defineProperty(n,String(e.key[1]),{value:"files"===r?Object.freeze(e.value):e.value,enumerable:!0,configurable:!0,writable:!0}),e.continue())}}if(await n,0===Object.keys(t.fileSystemSnapshot.entries).length){t.fileSystemSnapshot=ec();let i=r.transaction("files","readwrite"),n=em(i);for(let[r,n]of Object.entries(t.fileSystemSnapshot.entries))i.objectStore("files").put(n,[e,r]);await n}}function ef(e){let t=eo.get(e);if(!t){let r={storageSnapshot:{},fileSystemSnapshot:{entries:{}}};t={snapshot:r,references:0,ready:eg(e,r)},eo.set(e,t)}t.references+=1;let r=t,i=!1;return{ready:t.ready,release(){if(i)return;i=!0,r.references-=1;let t=()=>{r.references||eo.get(e)!==r||eo.delete(e)};r.ready.then(t,t)}}}function ev(e,t){let r=ef(e),i=async()=>(await r.ready,t()),n=(el.get(e)??Promise.resolve()).then(i,i);el.set(e,n);let a=()=>{el.get(e)===n&&el.delete(e),r.release()};return n.then(a,a),n}function ey(e){var t;let r=null==(t=eo.get(e))?void 0:t.snapshot;if(!r)throw Error("Application storage is not initialized");return{storageSnapshot:{...r.storageSnapshot},fileSystemSnapshot:{entries:{...r.fileSystemSnapshot.entries}}}}function eb(e){return ey(e).fileSystemSnapshot}function ew(e){return ed.add(e),()=>{ed.delete(e)}}function e_(e,t,r){let i={...r??ey(e),fileSystemNamespace:e,mutationId:t};for(let e of ed)try{e(i)}catch(e){console.error("Cannot deliver application storage update",e)}}function eS(e,t){let r={};for(let i of new Set([...Object.keys(e),...Object.keys(t)])){let n=Object.hasOwn(t,i)?t[i]:null,a=Object.hasOwn(e,i)?e[i]:void 0,s=o(a)&&o(n)&&a.type===n.type&&a.data===n.data&&a.createTime===n.createTime&&a.lastModifiedTime===n.lastModifiedTime;a===(n??void 0)||s||Object.defineProperty(r,i,{value:n,enumerable:!0})}return r}async function ex(e,t){let r=ey(e);for(let[e,i]of(t.clearStorage&&(r.storageSnapshot={}),[[r.storageSnapshot,t.storageChanges],[r.fileSystemSnapshot.entries,t.fileSystemChanges]]))for(let[t,r]of Object.entries(i??{}))null===r?delete e[t]:Object.defineProperty(e,t,{value:r,enumerable:!0,writable:!0,configurable:!0});(t.storageChanges||t.clearStorage)&&es(r.storageSnapshot),t.fileSystemChanges&&ek(r.fileSystemSnapshot,eb(e));let i=(await ep()).transaction(["storage","files"],"readwrite"),n=em(i);try{for(let[r,n]of(t.clearStorage&&i.objectStore("storage").delete(eh(e)),[["storage",t.storageChanges],["files",t.fileSystemChanges]])){let t=i.objectStore(r);for(let[i,a]of Object.entries(n??{}))null===a?t.delete([e,i]):t.put("files"===r?Object.freeze(a):a,[e,i])}}catch(e){throw i.abort(),await n.catch(()=>{}),e}await n,eo.get(e).snapshot=r,e_(e,t.mutationId,t)}function eI(e){return o(e)&&"directory"===e.type}function ek(e,t){if(!o(e)||!o(e.entries))throw Error("Invalid file snapshot");let r={user:0,temp:0};for(let[i,n]of Object.entries(e.entries)){if(!o(n)||!["file","directory"].includes(String(n.type))||!Number.isFinite(n.createTime)||0>Number(n.createTime)||!Number.isFinite(n.lastModifiedTime)||0>Number(n.lastModifiedTime)||"/"!==i&&(!/^\/(user|temp)(\/[^/]+)*$/.test(i)||i.split("/").some(e=>"."===e||".."===e||/[\\\0]/.test(e)))||"/"!==i&&!eI(e.entries[i.slice(0,i.lastIndexOf("/"))||"/"])||["/","/user","/temp"].includes(i)&&"directory"!==n.type)throw Error(`Invalid file entry: ${i}`);if("file"===n.type){if("string"!=typeof n.data)throw Error(`Invalid file data: ${i}`);if((null==t?void 0:t.entries[i])!==n&&(n.data.length%4!=0||/[^A-Za-z0-9+/=]/.test(n.data)||!/^[^=]*={0,2}$/.test(n.data)))throw Error(`Invalid base64 file: ${i}`);let e=i.startsWith("/user/")?"user":"temp";r[e]+=Math.floor(3*n.data.length/4)-(n.data.endsWith("==")?2:+!!n.data.endsWith("="))}}for(let t of["/","/user","/temp"])if(!eI(e.entries[t]))throw Error(`Missing file directory: ${t}`);if(r.user>0x3200000||r.temp>0x6400000)throw new w("total file storage size exceeded",208)}function eC(e){if(!o(e)||"doubao-web-storage"!==e.format||1!==e.version||!o(e.storageSnapshot))throw Error("存储与文件备份格式无效");es(e.storageSnapshot),ek(e.fileSystemSnapshot)}r(20303),r(99166),r(6106),r(22742),r(37553),r(62148),r(89055),r(12205),r(65850),r(65135),r(5876),r(94359),r(28016),r(38641),r(82247),r(11839),r(56109),r(63589),r(45249);var eE=r(59933),eN=r(12683);function eT(e){if(e.startsWith("/")||e.includes("\\")||e.includes("\0")||/^[a-z]:/i.test(e))throw new w("ZIP entry escapes the target directory",213);let t=[];for(let r of e.split("/"))if(r&&"."!==r)if(".."===r){if(!t.length)throw new w("ZIP entry escapes the target directory",213);t.pop()}else t.push(r);return t.join("/")}function eA(e){return Math.floor(3*e.length/4)-(e.endsWith("==")?2:+!!e.endsWith("="))}function eM(e){if(e>0xa00000)throw new w("total size limit exceeded",208)}function ej(e,t,r){let i=t.startsWith("/user/")?"/user/":"/temp/",n=("/user/"===i?50:100)*1048576,a=r;for(let[r,n]of Object.entries(e.entries))r!==t&&r.startsWith(i)&&"file"===n.type&&(a+=eA(n.data));if(a>n)throw new w("total size limit exceeded",208)}function eR(e){o(e.fileSystemSnapshot)||(e.fileSystemSnapshot={entries:{}}),o(e.fileSystemSnapshot.entries)||(e.fileSystemSnapshot.entries={});let t=Date.now();for(let i of["/","/temp","/user"]){var r;(null==(r=e.fileSystemSnapshot.entries[i])?void 0:r.type)!=="directory"&&(e.fileSystemSnapshot.entries[i]={type:"directory",createTime:t,lastModifiedTime:t})}return e.fileSystemSnapshot}function eP(e,t){let r=e[t];if("string"!=typeof r)throw new w(`${t} must be a string`,104);return r}function eL(e,t){let r=e[t];return"string"==typeof r?r:void 0}function eD(e){let t;if(0===e.length||e.includes("?")||e.includes("#")||/%(?![0-9a-f]{2})/i.test(e))throw new w("invalid applet file path",213);try{t=decodeURIComponent(e)}catch{throw new w("invalid applet file path",213)}if("."===t||".."===t||t.includes("/")||t.includes("\\")||t.includes("\0"))throw new w("invalid applet file path",213);return t}function eO(e){let t=/^appletfile:\/\/(user|temp)(?:\/(.*))?$/.exec(e);if(!t)throw new w("path must use appletfile://user or appletfile://temp",213);let r=t[1],i=t[2];if(void 0===i||0===i.length)return`/${r}`;let n=i.split("/").map(eD);return`/${r}/${n.join("/")}`}function eU(e){let t=/^data:[^,]*;base64,([A-Za-z0-9+/]*={0,2})$/.exec(e);if(!t)return;let r=t[1];if(r.length%4==1||r.endsWith("=")&&r.length%4!=0)throw new w("invalid base64 data",104);return{type:"file",data:r,createTime:0,lastModifiedTime:0}}function e$(e){let t=eO(e);if("/temp"===t||"/user"===t)return"";let r=t.lastIndexOf("/");return t.slice(0,r)}function eq(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function eB(e){let t=e.split("/").filter(Boolean),r=t.shift();if("temp"!==r&&"user"!==r)throw new w(`invalid applet file path: ${e}`,213);let i=t.map(eq).join("/");return i.length>0?`appletfile://${r}/${i}`:`appletfile://${r}`}function eF(e,t){return e.entries[eO(t)]}function eW(e,t){let r=eU(t);if(r)return r;let i=eO(t),n=e.entries[i];if(!n)throw new w(`file not found: ${i}`,203);if("file"!==n.type)throw new w(`path is a directory: ${i}`,1901001);return n}function ez(e,t){let r=eO(t),i=e.entries[r];if(!i)throw new w(`directory not found: ${r}`,203);if("directory"!==i.type)throw new w(`path is not a directory: ${r}`,1901002);return i}function eH(e,t){let r=e$(t);if(!r)throw new w(`invalid parent directory: ${t}`,213);let i=Date.now(),n="";for(let t of r.split("/").filter(Boolean)){n+=`/${t}`;let r=e.entries[n];if((null==r?void 0:r.type)==="file")throw new w(`path is not a directory: ${n}`,1901002);r||(e.entries[n]={type:"directory",createTime:i,lastModifiedTime:i})}}function eV(e){let t;try{t=atob(e)}catch{throw new w("invalid base64 data",104)}let r=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)r[e]=t.charCodeAt(e);return r}function eG(e,t){let r="string"==typeof e?e:String(e??"");return"base64"===t?eV(r):new TextEncoder().encode(r)}function eJ(e,t,r){let i=eO(t),n=Date.now(),a=e.entries[i];if((null==a?void 0:a.type)==="directory")throw new w(`path is a directory: ${i}`,1901001);ej(e,i,r.byteLength),eH(e,t),e.entries[i]={type:"file",data:function(e){let t="";for(let r=0;r<e.length;r+=1)t+=String.fromCharCode(e[r]);return btoa(t)}(r),createTime:(null==a?void 0:a.createTime)??n,lastModifiedTime:n}}function eK(e,t,r){let i=eR(e),n=eP(t,"dirPath"),a=eO(n),s=Date.now(),o=i.entries[a];if((null==o?void 0:o.type)==="directory")return{};if(o)throw new w(`path is not a directory: ${a}`,1901002);if(!0===t.recursive){let e="";for(let t of a.split("/").filter(Boolean))if(e+=`/${t}`,i.entries[e]||(i.entries[e]={type:"directory",createTime:s,lastModifiedTime:s}),"directory"!==i.entries[e].type)throw new w(`path is not a directory: ${e}`,1901002)}else{let e=e$(n);if(!e)throw new w(`invalid parent directory: ${n}`,213);let t=i.entries[e];if(!t)throw new w(`directory not found: ${e}`,203);if("directory"!==t.type)throw new w(`path is not a directory: ${e}`,1901002);i.entries[a]={type:"directory",createTime:s,lastModifiedTime:s}}return r(),{}}function eZ(e,t,r){let i=eR(e),n=eP(t,"dirPath"),a=eO(n);if("/temp"===a||"/user"===a)throw new w("cannot remove root directory",213);ez(i,n);let s=`${a}/`,o=Object.keys(i.entries).filter(e=>e.startsWith(s));if(!0!==t.recursive&&o.length>0)throw new w(`directory is not empty: ${a}`,1901001);for(let e of o)delete i.entries[e];return delete i.entries[a],r(),{}}function eX(e,t,r){let i=eR(e),n=eP(t,"filePath"),a=eO(n);return eW(i,n),delete i.entries[a],r(),{}}function eY(e,t){let r=eR(e),i=eP(t,"path"),n=eU(i),a=n?i:eO(i),s=n??r.entries[a];if(!s)throw new w(`path not found: ${a}`,203);return{size:"file"===s.type?eA(s.data):0,lastModifiedTime:s.lastModifiedTime,isDirectory:"directory"===s.type}}let eQ={"doubao.readFile":function(e,t){var r;let i=eW(eR(e),eP(t,"filePath"));return eM(eA(i.data)),{data:(r=i.data,"utf-8"===eL(t,"encoding")?new TextDecoder().decode(eV(r)):r)}},"doubao.writeFile":function(e,t,r){let i=eR(e),n=eG(t.data,eL(t,"encoding"));return eM(n.byteLength),eJ(i,eP(t,"filePath"),n),r(),{}},"doubao.appendFile":function(e,t,r){let i=eR(e),n=eP(t,"filePath"),a=eO(n),s=i.entries[a];if((null==s?void 0:s.type)==="directory")throw new w(`path is a directory: ${a}`,1901001);let o=eG(t.data,eL(t,"encoding"));eM(o.byteLength),ej(i,a,((null==s?void 0:s.type)==="file"?eA(s.data):0)+o.byteLength);let l=(null==s?void 0:s.type)==="file"?eV(s.data):new Uint8Array,d=new Uint8Array(l.length+o.length);return d.set(l),d.set(o,l.length),eJ(i,n,d),r(),{}},"doubao.access":function(e,t){let r=eR(e),i=eP(t,"path");if(!eF(r,i))throw new w(`path not found: ${i}`,203);return{}},"doubao.mkdir":eK,"doubao.rmdir":eZ,"doubao.readdir":function(e,t){let r=eR(e),i=eP(t,"dirPath");return ez(r,i),{files:function(e,t){let r=eO(t),i="/"===r?"/":`${r}/`,n=new Set;for(let t of Object.keys(e.entries)){if(t===r||!t.startsWith(i))continue;let e=t.slice(i.length).split("/")[0];e&&n.add(e)}return[...n]}(r,i)}},"doubao.unlink":eX,"doubao.stat":eY,"doubao.copyFile":function(e,t,r){let i=eR(e),n=eW(i,eP(t,"srcPath")),a=eP(t,"destPath");return ej(i,eO(a),eA(n.data)),eJ(i,a,eV(n.data)),r(),{}},"doubao.getFileInfo":function(e,t){let r=eP(t,"filePath"),{size:i}=eY(e,{path:r});if(void 0===t.digestAlgorithm)return{size:i};let n=eP(t,"digestAlgorithm").toLowerCase(),a=eW(eR(e),r),s="md5"===n?eE.Fx:"sha1"===n?eE.e8:void 0;if(!s)throw new w(`unsupported digest algorithm: ${n}`,102);return{size:i,digest:(0,ee.My)(s(eV(a.data)))}},"doubao.rename":function(e,t,r){let i=eR(e),n=eP(t,"oldPath"),a=eP(t,"newPath"),s=eO(n),o=eO(a),l=i.entries[s];if(!l)throw new w(`path not found: ${s}`,203);if("/temp"===s||"/user"===s)throw new w("cannot rename root directory",213);if(s===o)return{};if("directory"===l.type&&o.startsWith(`${s}/`))throw new w("cannot move a directory into itself",213);if(i.entries[o])throw new w(`target already exists: ${o}`,102);for(let e of(eH(i,a),Object.keys(i.entries)))if(e===s||e.startsWith(`${s}/`)){let t=o+e.slice(s.length);i.entries[t]=i.entries[e],delete i.entries[e]}return r(),{}},"doubao.truncate":function(e,t,r){let i=eR(e),n=eP(t,"filePath"),a=eW(i,n),s=t.length??0;if("number"!=typeof s||!Number.isSafeInteger(s)||s<0)throw new w("length must be a non-negative integer",104);ej(i,eO(n),s);let o=eV(a.data),l=new Uint8Array(s);return l.set(o.slice(0,s)),eJ(i,n,l),r(),{}},"doubao.saveFile":function(e,t,r){let i,n,a=eR(e),s=eP(t,"tempFilePath"),o=eU(s),l=o??eW(a,s),d=eL(t,"filePath"),u=o?(i=s.slice(5,s.indexOf(";")),`media.${({"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","audio/wav":"wav","audio/aac":"aac","audio/mp4":"mp4"})[i]??"bin"}`):"/temp"===(n=eO(s))||"/user"===n?"":n.slice(n.lastIndexOf("/")+1),c=`/user/${Date.now()}`,p=d&&d.length>0?d:eB(`${c}_${u}`);for(let e=1;!d&&a.entries[eO(p)];e++)p=eB(`${c}_${e}_${u}`);return ej(a,eO(p),eA(l.data)),eJ(a,p,eV(l.data)),o||eO(s)===eO(p)||delete a.entries[eO(s)],r(),{savedFilePath:p}},"doubao.getSavedFileList":function(e){return{fileList:Object.entries(eR(e).entries).flatMap(e=>{let[t,r]=e;return t.startsWith("/user/")&&"file"===r.type?[{filePath:eB(t),size:eA(r.data),createTime:r.createTime}]:[]})}},"doubao.removeSavedFile":function(e,t,r){var i;let n=eP(t,"filePath");return(null==(i=eF(eR(e),n))?void 0:i.type)==="directory"?eZ(e,{dirPath:n},r):eX(e,t,r)},"doubao.unzip":function(e,t,r){let i=eR(e),n=eW(i,eP(t,"zipFilePath")),a=eP(t,"targetPath"),s=eO(a),o=function(e,t){try{let r=function(e,t){let r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=e.length-22,n=Math.max(0,e.length-65557);for(;i>=n&&(0x6054b50!==r.getUint32(i,!0)||i+22+r.getUint16(i+20,!0)!==e.length);)i--;if(i<n||0!==r.getUint16(i+4,!0)||0!==r.getUint16(i+6,!0))throw Error("Invalid or multipart ZIP archive");let a=r.getUint16(i+10,!0),s=r.getUint32(i+16,!0);if(65535===a||0xffffffff===s){if(i<20||0x7064b50!==r.getUint32(i-20,!0))throw Error("Invalid ZIP64 archive");let e=Number(r.getBigUint64(i-12,!0));if(0x6064b50!==r.getUint32(e,!0))throw Error("Invalid ZIP64 directory");a=Number(r.getBigUint64(e+32,!0)),s=Number(r.getBigUint64(e+48,!0))}if(!Number.isSafeInteger(a)||a>e.length/46||!Number.isSafeInteger(s))throw Error("Invalid ZIP directory size");let o=new Map,l=0;for(let n=0;n<a;n++){if(s+46>i||0x2014b50!==r.getUint32(s,!0))throw Error("Invalid ZIP directory entry");let n=r.getUint16(s+8,!0),a=r.getUint16(s+28,!0),d=r.getUint16(s+30,!0),u=s+46+a+d+r.getUint16(s+32,!0);if(u>i||1&n)throw Error("Invalid or encrypted ZIP entry");let c=(0,eN.he)(e.subarray(s+46,s+46+a),!(2048&n));eT(c);let p=r.getUint32(s+24,!0);if(0xffffffff===p){let e=s+46+a,t=e+d;for(;e+4<=t&&1!==r.getUint16(e,!0);)e+=4+r.getUint16(e+2,!0);if(e+12>t||8>r.getUint16(e+2,!0))throw Error("Invalid ZIP64 file size");p=Number(r.getBigUint64(e+4,!0))}if(!Number.isSafeInteger(l+=p)||l>t)throw new w("ZIP expanded size exceeds the file system quota",208);o.set(c,r.getUint32(s+16,!0)),s=u}return o}(e,t),i=new Map,n=0,a=new eN.HJ(e=>{eT(e.name);let r=new eN.uZ(e.name);r.ondata=()=>{};let a=[],s=0;e.ondata=(o,l,d)=>{if(o)throw o;if((n+=l.length)>t)throw new w("ZIP expanded size exceeds the file system quota",208);if(a.push(l),s+=l.length,r.push(l,d),d){let t=new Uint8Array(s),n=0;for(let e of a)t.set(e,n),n+=e.length;i.set(e.name,{data:t,crc:r.crc>>>0})}},e.start()});a.register(eN.mM);for(let t=0;t<e.length;t+=65536)a.push(e.subarray(t,t+65536),t+65536>=e.length);if(i.size!==r.size)throw Error("ZIP entry count does not match its directory");for(let[e,t]of i)if(t.crc!==r.get(e))throw Error("ZIP entry checksum does not match");return new Map([...i].map(e=>{let[t,r]=e;return[t,r.data]}))}catch(e){if(e instanceof w)throw e;throw new w(`Unable to unzip file: ${e instanceof Error?e.message:String(e)}`,102)}}(eV(n.data),(s.startsWith("/user")?50:100)*1048576),l={...e,fileSystemSnapshot:{entries:{...i.entries}}};for(let[e,t]of(eK(l,{dirPath:a,recursive:!0},()=>{}),o)){let r=eT(e);if(!r)continue;let i=eB(`${s}/${r}`);e.endsWith("/")?eK(l,{dirPath:i,recursive:!0},()=>{}):eJ(l.fileSystemSnapshot,i,t)}return i.entries=l.fileSystemSnapshot.entries,r(),{}}},e0="doubao.__webSyncBridgePersist",e1="doubao.__webSyncBridgeUpdated";r(20789),r(62839),r(66876),r(35336);let e2="doubao.getPerformanceEntries",e3="doubao.setPerformanceBufferSize",e4="doubao.onPerformanceEntries",e6="doubao.__webPerformanceTiming",e5="__WEB_PERFORMANCE_WIDGET_IDENTITY__",e8=[e2,e3,e4];class e9{entries=[];bufferSize=30;launchStart=Date.now();launched=!1;snapshot(){return{entries:this.entries.map(e=>({...e})),bufferSize:this.bufferSize}}setBufferSize(e){if("number"!=typeof e||!Number.isInteger(e)||e<1||e>1e3)throw Error("size must be between 1 and 1000");this.bufferSize=e,this.entries=this.entries.slice(-e)}reset(){this.entries=[],this.bufferSize=30,this.launchStart=Date.now(),this.launched=!1}recordTiming(e,t){if(e.completed||!o(t))return[];let r=e.timing??={};for(let e of["create_lynx_start","layout_start","layout_end","lepus_execute_start","lepus_execute_end","parseChangesEnd"]){let i=t[e];"number"==typeof i&&Number.isFinite(i)&&i>0&&(r[e]=i)}let i=e=>{let t=r[e];return"number"==typeof t&&Number.isFinite(t)&&t>0?t:void 0},n=i("create_lynx_start"),a=i("layout_start"),s=i("layout_end");if(void 0===n||void 0===a||void 0===s||s<a||a<n)return[];e.completed=!0;let l=[],d=void 0===e.pageId?{}:{path:e.path,pageId:e.pageId};if(void 0!==e.pageId){let t=!this.launched,r=Math.min(e.startTime,n);if(t){let t=Math.min(this.launchStart,r);l.push({entryType:"navigation",name:"appLaunch",startTime:t,duration:s-t,...d,navigationStart:r,navigationType:e.navigationType})}l.push({entryType:"navigation",name:"route",startTime:r,duration:s-r,...d,navigationStart:r,navigationType:e.navigationType,referrerPath:e.referrerPath,referrerPageId:e.referrerPageId}),this.launched=!0}let u=i("lepus_execute_start"),c=i("lepus_execute_end"),p=c??i("parseChangesEnd");return void 0!==u&&void 0!==c&&c>=u&&l.push({entryType:"script",name:"evaluateScript",startTime:u,duration:c-u,moduleName:e.moduleName}),(void 0!==e.pageId||void 0!==e.widgetId)&&l.push({entryType:"render",name:"firstRender",startTime:n,duration:s-n,...d,...void 0!==p&&p>=n&&p<=s?{viewLayerReadyTime:p}:{},viewLayerRenderStartTime:a,viewLayerRenderEndTime:s,...void 0===e.widgetId?{}:{widgetId:e.widgetId,widgetInstanceId:e.widgetInstanceId,isAppColdLaunch:e.isAppColdLaunch}}),this.entries=[...this.entries,...l].slice(-this.bufferSize),l}}async function e7(e,t){try{await (null==t?void 0:t(e.params))}catch{}}let te=new Map,tt={"applet.subscribeEvent":(e,t)=>{let r=o(e.params)&&"string"==typeof e.params.eventName?e.params.eventName:"";if(r){var i;null==t||null==(i=t.events)||i.subscribe(r,t)}return _(e,{})},"applet.unsubscribeEvent":(e,t)=>{let r=o(e.params)&&"string"==typeof e.params.eventName?e.params.eventName:"";if(r){var i;null==t||null==(i=t.events)||i.unsubscribe(r)}return _(e,{})}};function tr(){var e;return null==(e=globalThis.navigator)?void 0:e.clipboard}function ti(e,t){let r=tr();if(!r||"function"!=typeof r[t])throw new w(`${e} is not supported in this browser`,103);return r}function tn(e,t){let r=o(t)&&"string"==typeof t.message?t.message:String(t),i=new w(`${e} failed: ${r}`,o(t)&&("NotAllowedError"===t.name||"SecurityError"===t.name)?106:102);return i.cause=t,i}async function ta(e){let t=ti("setClipboardData","writeText");try{await t.writeText(e)}catch(e){throw tn("setClipboardData",e)}}async function ts(){let e=ti("getClipboardData","readText");try{let t=await e.readText();if("string"==typeof t)return t}catch(e){throw tn("getClipboardData",e)}throw new w("getClipboardData failed: clipboard did not return text",102)}function to(e,t,r){let i=(null==t?void 0:t.fileSystemNamespace)??eu(null==t?void 0:t.globalProps);return ev(i,async()=>{try{var n,a;let s=eb(i),l={fileSystemNamespace:i,fileSystemSnapshot:{entries:{...s.entries}},apiResults:{"doubao.getSystemInfo":{platform:null==t||null==(a=t.globalProps)||null==(n=a.os)?void 0:n.toLowerCase()}},storageSnapshot:{},supportedAPIs:[]},d=!1,u=(0,eQ[e.name])(l,o(e.params)?e.params:{},()=>{d=!0});return d?await ex(i,{fileSystemChanges:eS(s.entries,l.fileSystemSnapshot.entries),mutationId:r}):r&&e_(i,r,{}),_(e,u)}catch(e){throw r&&e_(i,r),e}})}let tl=Object.fromEntries(Object.keys(eQ).map(e=>[e,to]));async function td(e,t){var r,i;if("string"!=typeof(null==e?void 0:e.src)||!e.src)throw Error("src must be a non-empty string");let{src:n}=e,a=await new Promise((e,r)=>{let i=new Image,a=()=>{null==t||t.removeEventListener("abort",s),i.onload=i.onerror=null},s=()=>{a(),i.removeAttribute("src"),r(null==t?void 0:t.reason)};(null==t?void 0:t.aborted)?s():(null==t||t.addEventListener("abort",s,{once:!0}),i.onload=()=>{a(),e(i)},i.onerror=()=>{a(),r(Error(`failed to load image: ${n}`))},i.src=n)}),s=null==(r=n.match(/^data:image\/([^;,]+)/i))?void 0:r[1],o=null==(i=n.match(/\.([a-zA-Z0-9]+)(?:[?#].*)?$/))?void 0:i[1];return{width:a.naturalWidth||a.width,height:a.naturalHeight||a.height,orientation:"up",path:n,type:((null==s?void 0:s.split("+")[0])??o??"").toLowerCase()}}function tu(e){return{pages:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:i;return(null==e?void 0:e.getCurrentPages())??[]}(null==e?void 0:e.navigation)}}function tc(e){return async(t,r)=>{let i=t.params;if(!i||"string"!=typeof i.url||!i.url.trim())return S(t,"invalid url",104);try{return await e(i,null==r?void 0:r.navigation)?_(t,{}):S(t,"No active Runtime to navigate",102)}catch(e){return S(t,x(e),e instanceof w?e.errNo:102)}}}let tp={"doubao.openPage":async(e,t)=>{var r;let i=e.params;if(!i||"string"!=typeof i.url||!i.url.trim()||void 0!==i.mode&&!["push","replace","navigate","pop_to"].includes(i.mode))return S(e,"url and mode must describe a valid page route",104);if(!(null==t||null==(r=t.navigation)?void 0:r.openPage))return S(e,"No active Runtime to open page",102);try{return await t.navigation.openPage(i),_(e,{})}catch(t){return S(e,x(t),t instanceof w?t.errNo:102)}},"doubao.enableAlertBeforeUnload":(e,t)=>{var r;let i=null==(r=e.params)?void 0:r.message;return"string"!=typeof i?S(e,"message must be a string",104):th(e,i,t)},"doubao.disableAlertBeforeUnload":(e,t)=>th(e,void 0,t),"doubao.getCurrentPages":{handler:(e,t)=>_(e,tu(t)),syncResult:tu},"doubao.navigateTo":tc(T),"doubao.redirectTo":tc(A),"doubao.reLaunch":tc(M),"doubao.navigateBack":(e,t)=>!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i;return(null==t?void 0:t.navigateBack(e))??!1}(e.params??{},null==t?void 0:t.navigation)?S(e,"No pages in back stack",102):_(e,{}),"doubao.exitApp":(e,t)=>!function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:i;return null==e||e.exitApp(),!!e}(null==t?void 0:t.navigation)?S(e,"No active Runtime to exit app",102):_(e,{})};function th(e,t,r){var i;return(null==r?void 0:r.containerType)==="PAGE"&&(null==(i=r.navigation)?void 0:i.setAlertBeforeUnload)?r.navigation.setAlertBeforeUnload(t,r.element)?_(e,{}):S(e,"not found page",102):S(e,"alert before unload is only supported in page container",103)}let tm=Object.fromEntries(["setStorage","getStorage","removeStorage","clearStorage","getStorageInfo"].map(e=>[`doubao.${e}`,async(t,r)=>{let i=(null==r?void 0:r.fileSystemNamespace)??eu(null==r?void 0:r.globalProps);return ev(i,async()=>{var r,n;let a=o(t.params)?t.params:{},s=ey(i).storageSnapshot,l={};switch(e){case"setStorage":{let e,t;if("string"!=typeof a.data)throw Error("data must be a serialized string");let o=(r=a.key,n=a.data,e=et(r),er(n),t=Object.prototype.hasOwnProperty.call(s,e)?s[e]:void 0,ea(en(s)-(void 0===t?0:ei(t))+ei(n)),e);await ex(i,{storageChanges:{[o]:a.data}});break}case"getStorage":let d;l={data:Object.hasOwn(s,d=et(a.key))?s[d]:void 0};break;case"removeStorage":await ex(i,{storageChanges:{[et(a.key)]:null}});break;case"clearStorage":await ex(i,{clearStorage:!0});break;case"getStorageInfo":l={keys:Object.keys(s),currentSize:Math.ceil(en(s)/1024),limitSize:10240}}return _(t,l)})}])),tg={...{"doubao.getClipboardData":{canIUse:()=>{var e;return"function"==typeof(null==(e=tr())?void 0:e.readText)},handler:async e=>_(e,{data:await ts()})},"doubao.setClipboardData":{canIUse:()=>{var e;return"function"==typeof(null==(e=tr())?void 0:e.writeText)},handler:async e=>{let{data:t}=function(e){if(!o(e)||"string"!=typeof e.data)throw new w("data must be a string",104);return{data:e.data}}(e.params);return await ta(t),_(e,{})}}},...tt,...tl,...{"doubao.getImageInfo":async e=>_(e,await td(e.params))},...tp,...tm,...{[e0]:async(e,t)=>{let r=o(e.params)?e.params:{},i=null==t?void 0:t.fileSystemNamespace;if(!i||r.fileSystemNamespace!==i)throw Error("Storage scope does not match the calling application");let n="string"==typeof r.mutationId?r.mutationId:void 0;if(void 0!==r.fileSystemOperation){let i=r.fileSystemOperation;if(!o(i)||"string"!=typeof i.name||!Object.hasOwn(eQ,i.name)||!o(i.params))throw Error("Invalid synchronous file operation");return to({...e,name:i.name,params:i.params},t,n)}let a={storageChanges:o(r.storageChanges)?r.storageChanges:void 0,clearStorage:!0===r.clearStorage,fileSystemChanges:o(r.fileSystemChanges)?r.fileSystemChanges:void 0,mutationId:n};return await ev(i,async()=>{try{await ex(i,a)}catch(e){throw e_(i,a.mutationId),e}}),_(e,{})}},...{"doubao.canIUse":{handler:(e,t)=>{let{schema:r}=e.params;return _(e,{result:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:E;return t.canIUse(e,{apiRegistry:t})}(r,null==t?void 0:t.apiRegistry)})}},"doubao.getAccountInfo":{handler:(e,t)=>{var r;return _(e,X(null==t||null==(r=t.navigation)?void 0:r.getPackageInfo(),null==t?void 0:t.globalProps))},syncResult:e=>X(Y(e),null==e?void 0:e.globalProps)},"doubao.getPackageInfo":{handler:(e,t)=>{var r;return _(e,B(null==t||null==(r=t.navigation)?void 0:r.getPackageInfo()))},syncResult:e=>B(Y(e))},"doubao.getAppBaseInfo":{handler:(e,t)=>_(e,Z(null==t?void 0:t.globalProps)),syncResult:e=>Z(null==e?void 0:e.globalProps)},"doubao.getMenuButtonBoundingClientRect":{handler:(e,t)=>_(e,R(null==t?void 0:t.globalProps)),syncResult:e=>R(null==e?void 0:e.globalProps)},"doubao.getSystemInfo":{handler:(e,t)=>_(e,J(null==t?void 0:t.globalProps)),syncResult:e=>J(null==e?void 0:e.globalProps)},"doubao.getWindowInfo":{handler:(e,t)=>_(e,F(null==t?void 0:t.globalProps)),syncResult:e=>F(null==e?void 0:e.globalProps)},"doubao.getDeviceInfo":{handler:(e,t)=>_(e,V(null==t?void 0:t.globalProps)),syncResult:e=>V(null==e?void 0:e.globalProps)},"doubao.getNetworkType":{handler:e=>_(e,K()),syncResult:K}}};E.registerMany(tg,{override:!0}),E.registerEventSources({onThemeChange:e=>{let t=matchMedia("(prefers-color-scheme: dark)"),r=()=>e({appTheme:matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"});return t.addEventListener("change",r),()=>t.removeEventListener("change",r)}},{override:!0});class tf{router;navigation;onEmpty;runtime;callers=new Map;destroyed=!1;performance=new e9;applicationLifecycle=new AbortController;nextPerformancePageId=Math.floor(1e12*Math.random());eventKey=Symbol("application events");applicationEvents;applicationEventKey;unsubscribeStorage;getApplicationEvents(){var e,t,r;let i=(null==(e=this.runtime)?void 0:e.getFileSystemNamespace())??this.eventKey;if(this.applicationEventKey!==i){let e,n;null==(t=this.applicationEvents)||t.release(),this.applicationEventKey=i,this.applicationEvents=(r=e=>{for(let t of this.callers.values())t.events.isSubscribed(e.name)&&t.send(e)},e=te.get(i)??{receivers:new Set,recent:[]},te.set(i,e),e.receivers.add(r),n=()=>{let t=Date.now();e.recent=e.recent.filter(e=>1e4>=Math.abs(t-e.timestamp))},{publish(t){for(let r of(n(),e.recent.push({message:t,timestamp:t.timestamp??Date.now()}),[...e.receivers]))r(t)},replay(t,r,i){for(let a of(n(),e.recent))a.message.name===t&&a.timestamp>=r&&i(a.message)},release(){e.receivers.delete(r),0===e.receivers.size&&te.delete(i)}})}return this.applicationEvents}constructor(e,t,r,i){this.router=e,this.navigation=t,this.onEmpty=r,this.runtime=i}get apiRegistry(){var e;return(null==(e=this.runtime)?void 0:e.apiRegistry)??E}register(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:()=>{},t=arguments.length>1?arguments[1]:void 0,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(this.destroyed)throw Error("RuntimeBridge was destroyed");let i=Symbol("caller");this.getApplicationEvents();let n=(null==t?void 0:t.apiRegistry)??this.apiRegistry;this.unsubscribeStorage??=ew(e=>{for(let t of this.callers.values())t.fileSystemNamespace===e.fileSystemNamespace&&t.events.emitPrivate(e1,e)});let a=n.createEventController((t,r)=>{e({type:"event",name:t,params:r,timestamp:Date.now()})});return this.callers.set(i,{abortController:new AbortController,send:e,options:t,events:a,main:r}),i}resolveStorageNamespace(e,t,r){var i,n,a;return(null==(i=this.runtime)?void 0:i.getFileSystemNamespace())??(null==(n=e.options)?void 0:n.fileSystemNamespace)??r??eu(t,null==(a=e.options)?void 0:a.userId)}async prepareStorage(e,t,r){let i=this.getCaller(e),n=this.resolveStorageNamespace(i,t,r);if(i.fileSystemNamespace!==n){var a;null==(a=i.storage)||a.release(),i.storage=void 0,i.fileSystemNamespace=n}i.storage??=ef(n),await i.storage.ready}createSyncBridgeData(e,t,r){var i;let n=this.getCaller(e),a=function(e,t){var r;let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:eu(e),n=arguments.length>3?arguments[3]:void 0,a=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:E;return e.getSupportedNames({apiRegistry:e})}(t);return{hostFileSystem:Object.keys(eQ).every(r=>null==t?void 0:t.canIUse(r,{globalProps:e})),fileSystemNamespace:i,...ey(i),hostStorage:!!(null==t?void 0:t.canIUse("doubao.setStorage",{globalProps:e})),apiResults:(r=null==e?void 0:e.packageInfo,(t??E).getSyncResults({globalProps:e,navigation:n,packageInfo:r})),supportedAPIs:a}}(t,(null==(i=n.options)?void 0:i.apiRegistry)??this.apiRegistry,this.resolveStorageNamespace(n,t,r),this.navigation);return a.performance=this.performance.snapshot(),n.fileSystemNamespace=a.fileSystemNamespace,a.supportedAPIs.push(...e8,e1),a}beginPerformance(e,t){var r,i,n;let a=this.getCaller(e),s=t.globalProps??{},l=o(s.__VIEW_CONTEXT__)?s.__VIEW_CONTEXT__:{},d=o(s[e5])?s[e5]:l,u="PAGE"===t.containerType,c=null==(i=this.navigation)||null==(r=i.getCurrentPages().at(-2))?void 0:r.route.split("?")[0],p=null==(n=[...this.callers.values()].findLast(e=>{var t;return(null==(t=e.performanceTrace)?void 0:t.path)===c}))?void 0:n.performanceTrace;a.performanceTrace={startTime:Date.now(),moduleName:`${t.resourceUrl}#main-thread`,...u?{path:"string"==typeof l.pageUrl?l.pageUrl:String(s.__LOCATION__??"").split("?")[0],pageId:++this.nextPerformancePageId,navigationType:s.__WEB_NAVIGATION_TYPE__??"openPage",referrerPath:null==p?void 0:p.path,referrerPageId:null==p?void 0:p.pageId}:"WIDGET"===t.containerType?{widgetId:"string"==typeof d.widgetId?d.widgetId:void 0,widgetInstanceId:"string"==typeof d.widgetInstanceId?d.widgetInstanceId:void 0,isAppColdLaunch:![...this.callers.values()].some(e=>{var t;return null==(t=e.performanceTrace)?void 0:t.completed})}:{}}}resetApplication(){this.applicationLifecycle.abort(),this.applicationLifecycle=new AbortController,this.performance.reset()}publishPerformance(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];for(let t of this.callers.values())t.events.emitPrivate(e1,{performance:this.performance.snapshot()}),e.length&&t.events.emit(e4,{entries:e})}getCaller(e){let t=this.callers.get(e);if(!t)throw Error("Caller was detached from the RuntimeBridge");return t}async handleMessage(e,t,r){var i;let n=this.getCaller(e);if(!v(t))return{routed:!1};if("applet.subscribeEvent"===t.name||"applet.unsubscribeEvent"===t.name){let e=o(t.params)?t.params:{},i="string"==typeof e.eventName?e.eventName:"",a="applet.subscribeEvent"===t.name&&!n.events.isSubscribed(i);if(tt[t.name](t,{...r,events:n.events}),"applet.subscribeEvent"===t.name&&i===e1&&(null==r?void 0:r.environment)!=="sandbox"){let e=this.resolveStorageNamespace(n,null==r?void 0:r.globalProps,n.fileSystemNamespace??(null==r?void 0:r.fileSystemNamespace));n.events.emitPrivate(i,{performance:this.performance.snapshot(),fileSystemNamespace:e,...ey(e)})}return a&&i&&"number"==typeof e.timestamp&&this.getApplicationEvents().replay(i,e.timestamp,n.send),{routed:!1}}return(null==(i=t.target)?void 0:i.scope)!=="main"||"self"!==t.target.target||!this.router||n.main?{routed:!1}:this.router.call(e,t)}async dispatch(e,t,r,i,n){var a,s,l;let d=arguments.length>5&&void 0!==arguments[5]?arguments[5]:"inline",u=this.callers.get(e);if(!u)return;let c=u.options,p={containerType:n.containerType,element:n.element},h="AppletBridgeModule"===i&&"postMessage"===t;if(h){let e=function(e,t){var r,i;if(!("object"!=typeof(r=e)||null===r||Array.isArray(r))&&"event"===r.type&&"doubao.__widgetInteraction"===r.name&&!("object"!=typeof(i=r.params)||null===i||Array.isArray(i))&&"tap"===i.type&&Number.isSafeInteger(i.sequence)&&"number"==typeof i.sequence&&i.sequence>0)return e7(e,t)}(r,null==c?void 0:c.onWidgetInteraction);if(e)return await e}let m=await this.handleMessage(e,r,n);if(m.routed)return await m.result;let g=await (null==c||null==(a=c.appletSessionMessageHandler)?void 0:a.call(c,r,p));if(null==g?void 0:g.routed)return await g.result;"iframe"!==d&&h&&b(r)&&"__bridge_ready__"===r.name&&(null==c||null==(s=c.onReady)||s.call(c));let f=h&&y(r),w="inline"===d&&"sandbox"!==n.environment;if(f&&w&&"TOOL"!==n.containerType)return u.send(r),r;let S=r=>("iframe"!==d&&"postMessage"===t&&y(r)&&this.callers.get(e)===u&&u.send(r),r);try{if(h&&v(r)&&"sandbox"!==n.environment){let e=o(r.params)?r.params:{};if(r.name===e6){let t=u.performanceTrace?this.performance.recordTiming(u.performanceTrace,e.timing):[];return t.length&&this.publishPerformance(t),S(_(r,{}))}if(r.name===e2)return S(_(r,{entries:(l=this.performance.snapshot(),l.entries.filter(t=>(void 0===e.entryType||t.entryType===e.entryType)&&(void 0===e.name||t.name===e.name)).map(e=>({...e})))}));if(r.name===e3)return this.performance.setBufferSize(e.size),this.publishPerformance(),S(_(r,{}));if("doubao.canIUse"===r.name&&e8.includes(String(e.schema)))return S(_(r,{result:!0}))}let a=this.runtime?this.runtime.nativeModulesCallHandler:null==c?void 0:c.nativeModulesCallHandler,s=await (null==a?void 0:a(t,r,i,p));if(void 0===s&&h&&b(r)&&"__bridge_ready__"!==r.name){this.callers.get(e)===u&&this.getApplicationEvents().publish(r);return}if(f){let e=void 0===s?r:s;if("sandbox"===n.environment||void 0===s&&w)return S(e);return e}let d=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0,r=e.apiRegistry??E;return(i,n,a)=>{if(("AppletJSModule"!==a||"log"!==i)&&"AppletBridgeModule"===a&&"postMessage"===i)return r.dispatch(n,e,t)}}({...n,signal:u.abortController.signal,getAppletContext:null==c?void 0:c.getAppletContext,applicationLifecycle:this.runtime?{owner:this.applicationLifecycle,signal:this.applicationLifecycle.signal}:void 0,fileSystemNamespace:this.resolveStorageNamespace(u,n.globalProps,u.fileSystemNamespace??n.fileSystemNamespace),navigation:this.navigation,apiRegistry:(null==c?void 0:c.apiRegistry)??this.apiRegistry,events:u.events,emitEvent:(e,t)=>u.events.emit(e,t)},null==c?void 0:c.onUnsupportedAPI),m=void 0===s?await d(t,r,i):s;if(h&&v(r)&&r.name===e0&&y(m)&&o(m.params)&&1!==m.params.code){let e=["Synchronous API persistence failed",m.params];a?await a("log",{level:"error",args:e},"AppletJSModule",p):console.error(...e)}return S(m)}catch(e){if("iframe"===d)throw e;return S(v(r)?I(r,e):void 0)}}handleMainBridgeMessage(e){var t;return!this.destroyed&&(null!=(t=this.router)&&!!t.handleMainBridgeMessage(e)||!!b(e)&&"__bridge_ready__"!==e.name&&(this.getApplicationEvents().publish(e),!0))}setVisible(e,t){var r;null==(r=this.callers.get(e))||r.events.setVisible(t)}unregister(e){var t,r,i,n;let a=this.callers.get(e);a&&(this.callers.delete(e),null==(t=a.storage)||t.release(),this.callers.size||(null==(i=this.unsubscribeStorage)||i.call(this),this.unsubscribeStorage=void 0),a.abortController.abort(),a.events.destroy(),null==(r=this.router)||r.cancel(e),a.main||this.destroyed||[...this.callers.values()].some(e=>!e.main)||null==(n=this.onEmpty)||n.call(this))}fail(e){var t;null==(t=this.router)||t.fail(e)}destroy(){var e,t;if(!this.destroyed)for(let r of(this.destroyed=!0,null==(e=this.applicationEvents)||e.release(),this.applicationEvents=void 0,this.applicationLifecycle.abort(),null==(t=this.router)||t.destroy(),this.callers.keys()))this.unregister(r)}}let tv=/(?:^|[.-])[a-f\d]{8,}(?=[.-]|$)/i;function ty(e){let t=new URL(e),r=t.pathname.slice(t.pathname.lastIndexOf("/")+1),i=j();return i&&!tv.test(r)&&t.searchParams.set("__doubao_resource_reload",i),t.href}function tb(e){return"localhost"===e||"::1"===e||/^127(?:\.\d{1,3}){3}$/.test(e)}function tw(e){if(!e.resourceUrl)throw Error("Container.render requires a resourceUrl");return e.resourceUrl}function t_(e){return e.containerType??"PAGE"}function tS(e){return"WIDGET"===e?"content":"fill"}function tx(e){if("function"==typeof CustomEvent)return new CustomEvent("error",{detail:{error:e}});let t=new Event("error");return Object.defineProperty(t,"detail",{value:{error:e}}),t}class tI{container;options;sandboxUrl;targetOrigin;bridge=null;caller;connected=!1;failed=!1;handshakeTimer=null;loaded=!1;loadCount=0;port=null;preparedForRender=!1;preparedContainerType=null;renderMessage=null;view=null;constructor(e){let t=new URL(e.sandboxUrl??"https://apps-web-sdk-sandbox.doubaocdn.com/sandbox");if("https:"!==t.protocol&&!("http:"===t.protocol&&tb(t.hostname)))throw Error("iframe isolation url must use HTTPS (HTTP is only allowed on localhost)");this.container=e.container,this.options=e,this.sandboxUrl=ty(t),this.targetOrigin=t.origin}get element(){return this.view}prepare(e){this.clear();try{this.createView(e),this.preparedForRender=!0}catch(e){throw this.clear(),e}}createView(e){var t,r;if(new URL((null==(t=globalThis.location)?void 0:t.href)??"http://localhost/").origin===this.targetOrigin)return this.abortRender(Error("iframe isolation requires a cross-origin sandbox URL"));if(this.view)return this.preparedContainerType!==e?this.abortRender(Error("iframe container type cannot change after preparation")):this.view;let i=document.createElement("iframe");i.className=this.options.className??"doubao-web-container-view",i.dataset.containerType=e,i.dataset.webSizing=tS(e),i.referrerPolicy="no-referrer",i.title="Doubao app content",i.sandbox.add("allow-scripts","allow-same-origin");let n=tb((null==(r=globalThis.location)?void 0:r.hostname)??"");return n&&i.setAttribute("credentialless",""),i.setAttribute("allow",n?"picture-in-picture 'none'; local-network-access 'src'; loopback-network 'src'":"picture-in-picture 'none'"),i.src=this.sandboxUrl,i.style.display="APP"===e||"TOOL"===e?"none":"block",i.style.border="0",i.style.width="100%",i.style.height="WIDGET"===e?"0px":"100%",i.addEventListener("load",()=>this.handleLoad()),this.view=i,this.preparedContainerType=e,this.container.replaceChildren(i),i}render(e){var t;this.preparedForRender||this.clear(),this.preparedForRender=!1;let r=t_(e),i=new URL(tw(e),document.baseURI).href,n=e.initData??{},a={...G(),...e.globalProps??{}};this.bridge=e.bridge??(null==(t=this.options.runtime)?void 0:t.bridge)??new tf,this.caller=e.bridgeCaller??this.bridge.register(e=>this.sendBridgeMessage(e),e.bridge||this.options.runtime?{...this.options,apiRegistry:void 0}:this.options,"APP"===r);let s=this.bridge,o=this.caller;try{let t=this.createView(r);return s.prepareStorage(o,a,this.options.fileSystemNamespace).then(()=>{var t,l,d;if(this.caller!==o)return;s.beginPerformance(o,{...e,containerType:r,globalProps:a});let u=s.createSyncBridgeData(o,a,this.options.fileSystemNamespace);this.renderMessage={type:"render",captureWidgetTap:this.options.captureWidgetTap,resourceUrl:i,resourceRoot:(null==(t=e.applicationPackage)?void 0:t.resourceRoot)??(null==(d=this.options.runtime)||null==(l=d.packageInfo)?void 0:l.resourceRoot),containerType:r,initData:n,globalProps:a,syncBridgeData:u},this.connected?this.postOrFail(this.renderMessage):this.loaded&&this.connect()}).catch(e=>{this.caller===o&&this.fail(e instanceof Error?e:Error(String(e)))}),t}catch(e){throw this.clear(),e}}clear(){var e,t;this.connected&&this.post({type:"dispose"}),this.destroyChannel(),this.caller&&(null==(t=this.bridge)||t.unregister(this.caller)),this.caller=void 0,this.bridge=null,null==(e=this.view)||e.remove(),this.view=null,this.preparedContainerType=null,this.renderMessage=null,this.connected=!1,this.failed=!1,this.loaded=!1,this.loadCount=0,this.preparedForRender=!1,this.container.replaceChildren()}setVisible(e){if(this.caller){var t;null==(t=this.bridge)||t.setVisible(this.caller,e)}}sendEvent(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.postOrFail({type:"global-event",name:e,params:t})}sendBridgeMessage(e){this.postOrFail({type:"bridge-message",message:e})}sendGlobalEvent(e,t){this.postOrFail({type:"raw-global-event",name:e,params:t})}updateData(e){this.renderMessage&&(this.renderMessage.initData=e),this.postOrFail({type:"update-data",data:e})}updateGlobalProps(e){this.renderMessage&&(this.renderMessage.globalProps={...this.renderMessage.globalProps,...e}),this.postOrFail({type:"update-global-props",props:e})}reload(){this.post({type:"reload"})}abortRender(e){var t,r;throw null==(t=(r=this.options).onError)||t.call(r,e,tx(e)),e}handleLoad(){this.failed||!this.view||((this.loadCount+=1,this.loadCount>1)?this.fail(Error("iframe navigated after the sandbox runtime loaded")):(this.loaded=!0,this.renderMessage&&this.connect()))}connect(){if(this.failed||!this.view||this.connected||this.port)return;let e=new MessageChannel;this.port=e.port1,e.port1.onmessage=e=>this.handleMessage(e),e.port1.onmessageerror=e=>this.fail(Error("iframe message could not be decoded"),e),e.port1.start(),this.handshakeTimer=setTimeout(()=>this.fail(Error("iframe sandbox handshake timed out")),1e4);let t={type:"doubao-web-sdk:connect",protocolVersion:1,sdkVersion:j()??""};try{var r;null==(r=this.view.contentWindow)||r.postMessage(t,this.targetOrigin,[e.port2])}catch(e){this.fail(e instanceof Error?e:Error(String(e)))}}handleMessage(e){var t,r,i;if(!e.data||"object"!=typeof e.data)return void this.fail(Error("iframe sandbox sent an invalid protocol message"),e);let n=e.data;if(!this.connected)return"connected"!==n.type||1!==n.protocolVersion?void this.fail(Error("iframe sandbox protocol version mismatch"),e):(this.connected=!0,this.clearHandshakeTimer(),void(this.renderMessage&&this.postOrFail(this.renderMessage)));switch(n.type){case"ready":null==(t=(r=this.options).onReady)||t.call(r);break;case"error":this.fail(Error(n.message),e);break;case"resize":(null==(i=this.renderMessage)?void 0:i.containerType)!=="WIDGET"||!Number.isFinite(n.height)||n.height<0?this.fail(Error("only Widget containers may resize the iframe"),e):this.view&&(this.view.style.height=`${n.height}px`,this.view.height=String(n.height));break;case"native-call":!Number.isSafeInteger(n.requestId)||n.requestId<=0||("AppletBridgeModule"!==n.moduleName||"postMessage"!==n.name)&&("AppletJSModule"!==n.moduleName&&"LynxConsoleModule"!==n.moduleName&&"Console"!==n.moduleName||"log"!==n.name)?this.fail(Error("iframe sandbox sent an invalid bridge call"),e):this.handleNativeCall(n);break;case"connected":this.fail(Error("iframe sandbox connected more than once"),e);break;default:this.fail(Error("iframe sandbox sent an invalid protocol message"),e)}}async handleNativeCall(e){let t;if(!this.renderMessage||!this.view)return;let r=this.bridge,i=this.caller;if(r&&i){try{t=await r.dispatch(i,e.name,e.data,e.moduleName,{containerType:this.renderMessage.containerType,element:this.view,globalProps:this.renderMessage.globalProps,fileSystemNamespace:this.renderMessage.syncBridgeData.fileSystemNamespace},"iframe")}catch(t){if(this.bridge!==r||this.caller!==i)return;this.postOrFail({type:"bridge-result",requestId:e.requestId,error:x(t)});return}this.bridge===r&&this.caller===i&&this.postOrFail({type:"bridge-result",requestId:e.requestId,result:t})}}post(e){this.connected&&this.port&&this.port.postMessage(e)}postOrFail(e){try{this.post(e)}catch(e){this.fail(e instanceof Error?e:Error(String(e)))}}fail(e){var t,r,i,n;let a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tx(e);this.failed||(this.failed=!0,this.destroyChannel(),this.caller&&(null==(n=this.bridge)||n.unregister(this.caller)),this.caller=void 0,this.bridge=null,null==(t=this.view)||t.remove(),this.view=null,this.renderMessage=null,null==(r=(i=this.options).onError)||r.call(i,e,a))}clearHandshakeTimer(){null!==this.handshakeTimer&&clearTimeout(this.handshakeTimer),this.handshakeTimer=null}destroyChannel(){var e;this.clearHandshakeTimer(),null==(e=this.port)||e.close(),this.port=null,this.connected=!1}}let tk={mode:"iframe",createContainer:e=>new tI(e)};function tC(){var e;return(null==(e=globalThis.location)?void 0:e.href)??"http://localhost/"}function tE(e){return new URL(e,tC()).toString()}function tN(e,t){if(!t)return e;let r=new URL(e,tC());return r.searchParams.set("__doubao_resource_reload",t),r.toString()}class tT{options;packages=new Map;resolveManifestUrl;resourceUrlVersion;constructor(e={}){this.options=e,this.resolveManifestUrl=e.resolveManifestUrl,this.resourceUrlVersion=e.resourceUrlVersion}configure(e){e.resolveManifestUrl&&(this.resolveManifestUrl=e.resolveManifestUrl),"resourceUrlVersion"in e&&(this.resourceUrlVersion=e.resourceUrlVersion)}async getPackageSource(e){if(arguments.length>1&&void 0!==arguments[1]&&arguments[1],!this.resolveManifestUrl)throw Error("PackageManager requires resolveManifestUrl");return{manifestUrl:await this.resolveManifestUrl({appId:e})}}cached(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};r.signal&&g(r.signal);let i=this.packages.get(e);return(!i||r.forceReload)&&(i=t(),this.packages.set(e,i),i.catch(()=>{this.packages.get(e)===i&&this.packages.delete(e)})),r.signal?f(()=>i,r.signal):i}async fetchPackage(e,t){return{manifestUrl:e,resourceRoot:t,manifest:await p(e,{fetcher:this.options.fetcher})}}async loadPackage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t.signal&&g(t.signal);let{manifestUrl:r,resourceRoot:i}=await this.getPackageSource(e,t),n=tE(r),a=await this.cached(n,()=>this.fetchPackage(n,i),t);if(e&&a.manifest.appId&&a.manifest.appId!==e)throw Error("Resolved package appId must match the requested application");return a}resolveWidget(e,t){let r=this.tryResolveWidgetFromPackage(e,t),i=e.manifest.appRuntimeEntry?h(e.manifestUrl,e.manifest.appRuntimeEntry):void 0;return{packageInfo:e,appId:e.manifest.appId,appName:(null==r?void 0:r.appName)??e.manifest.name,icon:(null==r?void 0:r.iconSrc)??e.manifest.iconSrc,appRuntimeEntry:i?tN(i,e.resourceUrlVersion??this.resourceUrlVersion):void 0,resourceUrl:(null==r?void 0:r.resourceUrl)??"",titleType:null==r?void 0:r.entry.titleType,boxType:null==r?void 0:r.entry.boxType}}preload(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.loadPackage(e,t)}setPackage(e){this.packages.set(tE(e.manifestUrl),Promise.resolve(e))}deletePackage(e){this.packages.delete(tE(e))}clearPackageCache(e){e?this.deletePackage(e):this.packages.clear()}resolveWidgetEntry(e,t){let r=e.manifest.name??t.name,i=h(e.manifestUrl,t);return{appId:e.manifest.appId,entry:t,iconSrc:e.manifest.iconSrc??u(t.icons),appName:r,resourceUrl:i?tN(i,e.resourceUrlVersion??this.resourceUrlVersion):void 0}}tryResolveWidgetFromPackage(e,t){let r=e.manifest.getOptionalWidgetEntry(t);if(r)return this.resolveWidgetEntry(e,r)}}class tA{send;ready;pendingCalls=new Map;destroyed=!1;nextCallbackId=1e6;constructor(e,t){this.send=e,this.ready=t}call(e,t){if(this.destroyed)return Promise.reject(Error("RuntimeRouter was destroyed"));let r=this.nextCallbackId++,i={...t,callbackId:r};return new Promise((n,a)=>{this.pendingCalls.set(r,{callbackId:t.callbackId,reject:a,resolve:n,caller:e}),(async()=>{try{await this.ready(),this.pendingCalls.has(r)&&this.send(i)}catch(t){let e=this.pendingCalls.get(r);if(!e)return;this.pendingCalls.delete(r),e.reject(t instanceof Error?t:Error(String(t)))}})()})}handleMainBridgeMessage(e){if(y(e)){let t=this.pendingCalls.get(e.callbackId);return!!t&&(this.pendingCalls.delete(e.callbackId),t.resolve({routed:!0,result:{...e,callbackId:t.callbackId}}),!0)}return!1}cancel(e){for(let[t,r]of this.pendingCalls)r.caller===e&&(this.pendingCalls.delete(t),r.reject(Error("Caller was detached from the RuntimeBridge")))}destroy(){this.destroyed||(this.destroyed=!0,this.fail(Error("RuntimeRouter was destroyed")))}fail(e){for(let t of this.pendingCalls.values())t.reject(e);this.pendingCalls.clear()}}let tM="onBackground",tj="onDestroy",tR="onForeground",tP="onHide",tL="onShow";function tD(e,t){let r=function(e){let{pageId:t,viewData:r}=function(e){if(!e)throw Error("route url must be a non-empty string");let t=e.indexOf("?"),r=-1===t?e:e.slice(0,t);if(!r)throw Error("route url must include a page path");let i={};return new URLSearchParams(-1===t?"":e.slice(t+1)).forEach((e,t)=>{i[t]=e}),{pageId:r,viewData:i}}(e.url),i=JSON.stringify(r);return{pageId:t,initData:{viewData:r,viewContext:{}},globalProps:{__LOCATION__:e.url,__RENDER_DATA__:i,__VIEW_CONTEXT__:{}}}}(e);return{...r,entry:t.getPageEntry(r.pageId)}}function tO(e,t){var r;let i=Object.entries((null==(r=t.initData)?void 0:r.viewData)??{}).map(e=>{let[t,r]=e;return`${encodeURIComponent(t)}=${encodeURIComponent(r)}`}).join("&");return{route:`${e}${i?`?${i}`:""}`}}function tU(e,t){return{packageInfo:t,...e}}function t$(e){return{appId:e.appId,name:e.name,iconSrc:e.iconSrc,versionName:e.versionName}}function tq(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return tU(t,t$(e))}function tB(e){if(o(e))return{...e};if("string"!=typeof e)return{};try{let t=JSON.parse(e);return o(t)?t:{}}catch{return{}}}class tF{pageHost;visible=!0;className;onError;appGlobalProps;appInitData;getRuntimeGlobalProps;configuredFileSystemNamespace;userId;runtimeKernel;packageSnapshot;packageLoading;packageSource;lifecycle=new AbortController;get packageInfo(){if(this.destroyed)throw Error("Runtime was destroyed");if(!this.packageSnapshot)throw Error("Runtime package is not loaded");return this.packageSnapshot}get manifest(){return this.packageInfo.manifest}get manifestUrl(){return this.packageInfo.manifestUrl}pageCapsule;resolvedFileSystemNamespace;appRuntime=null;appStart=null;bridge;packageManager;sandboxUrl;viewContext;appGroupId;destroyed=!1;pendingAppEvents=[];clearingAppRuntime=!1;appCallController=new AbortController;apiContextOwner={};stack=[];pendingPages=[];nextPageIndex=0;constructor(e,t=tk,r){this.sandboxUrl=e.sandboxUrl,this.packageManager=e.packageManager??new tT({resolveManifestUrl:()=>this.manifestUrl});let i=new tA(e=>this.sendAppBridgeMessage(e),async()=>{if(await this.ensureAppRuntime(),!this.appStart)throw Error("No Web entry configured for app runtime");return this.appStart.promise});this.appGroupId=e.appGroupId,this.viewContext=e.viewContext,this.pageHost=e.pageHost,this.runtimeKernel=t,"manifest"in e?(this.packageSnapshot={manifest:e.manifest,manifestUrl:String(e.manifestUrl),resourceRoot:e.resourceRoot,resourceUrlVersion:""},e.packageManager||this.packageManager.setPackage(this.packageSnapshot)):this.packageSource=e,this.pageCapsule=e.pageCapsule,this.className=e.className,this.onError=e.onError,this.appGlobalProps=e.appGlobalProps,this.appInitData=e.appInitData,this.getRuntimeGlobalProps=e.getRuntimeGlobalProps,this.configuredFileSystemNamespace=e.fileSystemNamespace,this.userId=e.userId,this.resolvedFileSystemNamespace=this.resolveFileSystemNamespace(),this.updateEmptyState(),this.bridge=new tf(i,{getCurrentPages:()=>this.getCurrentPages(),getPackageInfo:()=>this.getPackageInfo(),navigateTo:e=>this.navigateToBridgePage(e),openPage:e=>this.openBridgePage(e),redirectTo:e=>this.redirectToBridgePage(e),reLaunch:e=>this.reLaunchBridgePage(e),navigateBack:e=>this.requestBack(e),setAlertBeforeUnload:(e,t)=>{let r=this.stack.find(e=>e.element===t);return!!r&&(r.alertBeforeUnloadMessage=e,!0)},exitApp:()=>this.exitBridgeApp()},r,{apiRegistry:e.apiRegistry,getFileSystemNamespace:()=>this.fileSystemNamespace,nativeModulesCallHandler:e.nativeModulesCallHandler})}async loadPackage(){var e,t;if(this.destroyed)throw new DOMException("Runtime was destroyed","AbortError");let r=(null==(e=this.packageSource)?void 0:e.signal)?AbortSignal.any([this.lifecycle.signal,this.packageSource.signal]):this.lifecycle.signal;if(!this.packageSnapshot){if(!this.packageLoading){let e=this.packageSource,i=this.packageManager.loadPackage(e.appId,{signal:r,versionTag:e.versionTag??(null==(t=e.viewContext)?void 0:t.versionTag)}).then(e=>{g(r),this.destroyed||this.packageSnapshot||(this.packageSnapshot={...e,resourceUrlVersion:""},this.resolvedFileSystemNamespace=this.resolveFileSystemNamespace())}).catch(e=>{throw this.packageLoading===i&&(this.packageLoading=void 0),e});this.packageLoading=i}let e=this.packageLoading;await f(()=>e,r)}return g(r),this.packageInfo}get fileSystemNamespace(){return this.resolvedFileSystemNamespace}get isDestroyed(){return this.destroyed}get pages(){return this.stack.map(e=>this.toStackEntry(e))}get currentPage(){let e=this.getCurrentStackItem();return e?this.toStackEntry(e):null}setManifest(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.manifestUrl;this.clear(),this.packageSnapshot={...this.packageSnapshot,manifest:e,manifestUrl:String(r),resourceUrlVersion:(null==(t=this.packageSnapshot)?void 0:t.resourceUrlVersion)??"1"},this.packageManager.setPackage(this.packageSnapshot),this.resolvedFileSystemNamespace=this.resolveFileSystemNamespace()}async pushPage(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.packageSnapshot||await this.loadPackage(),this.pushLoadedPage(e)}async pushLoadedPage(e,t){var r,i,n;let a;if(this.destroyed)throw Error("Runtime was destroyed");if(!this.pageHost)throw Error("Opening Pages requires a Runtime pageHost");let s=this.resolvePageEntry(e),l=h(this.manifestUrl,s);if(!l)throw Error(`No Web entry configured for page entry: ${s.id}`);let d=this.lifecycle.signal;if(this.startAppRuntime(),this.appStart&&await this.appStart.promise,g(d),"all"===t)this.clearPages();else if("current"===t){let e=this.stack.pop();e&&this.removeStackItem(e,!1)}let u={...e,globalProps:{...e.globalProps,...null==(r=this.getRuntimeGlobalProps)?void 0:r.call(this)}},c=tN(l,this.packageInfo.resourceUrlVersion),p=e.pageCapsule??this.pageCapsule,m=`page-${++this.nextPageIndex}`,f=(a=tB(null==(n=u.globalProps)?void 0:n.__VIEW_CONTEXT__),{...o(u.initData)?tB(u.initData.viewContext):{},...a,viewId:m,pageName:s.id,pageUrl:s.path}),v=null,y=this.pageHost.createPage({className:this.className,runtime:this,onError:this.onError,onReady:()=>{v&&this.stack.includes(v)&&(v.isReady=!0,this.flushPageLifecycleEvents(v))}},this.runtimeKernel,()=>this.exitBridgeApp());void 0!==e.pageCapsule&&(this.pageCapsule=e.pageCapsule),this.pendingPages.push(tO(s.path,e));try{let t,r,n=y.render({resourceUrl:c,groupId:this.manifest.appId,initData:o(u.initData)?{...u.initData,viewContext:f}:{viewContext:f},globalProps:(t=null==p?void 0:p.statusBarHeight,r="number"==typeof t&&Number.isFinite(t)?{statusBarHeight:t}:{},{...u.globalProps,...r,__VIEW_CONTEXT__:f}),pageCapsule:p}),a=this.getCurrentStackItem();return a&&(null==(i=a.backPrompt)||i.abort(),this.visible&&this.sendPageLifecycleEvent(a,tP),a.page.setVisible(!1)),v={id:m,pageId:s.id,route:s.path,resourceUrl:c,entry:s,element:n,isReady:!1,options:{...e,entry:s,pageCapsule:p},pendingLifecycleEvents:[],page:y},this.stack.push(v),this.updateEmptyState(),v.page.setVisible(this.visible),this.visible&&this.sendPageLifecycleEvent(v,tL),this.sendAppEvent("onPageOpened",{viewId:v.id}),this.toStackEntry(v)}catch(e){throw y.clear(),this.updateEmptyState(),e}finally{this.pendingPages.pop()}}async replacePage(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this.packageSnapshot||await this.loadPackage(),this.destroyed)throw Error("Runtime was destroyed");return this.withPageTransition(()=>this.pushLoadedPage(e,"current"))}async reLaunchPage(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this.packageSnapshot||await this.loadPackage(),this.destroyed)throw Error("Runtime was destroyed");return this.withPageTransition(()=>this.pushLoadedPage(e,"all"))}popPage(){let e=this.stack.pop();return e?this.removeStackItem(e,!0):null}setVisible(e){if(this.destroyed||this.visible===e)return;this.visible=e;let t=this.getCurrentStackItem();t&&(t.page.setVisible(e),this.sendPageLifecycleEvent(t,e?tL:tP)),this.appRuntime&&this.sendAppEvent(e?tR:tM)}requestBack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.getCurrentStackItem();if(!t)return!1;if(1===this.stack.length){var r;return this.setVisible(!1),null==(r=this.pageHost)||r.hide(),!0}let i=()=>{if(this.destroyed||this.getCurrentStackItem()!==t)return;let r=Math.min(Math.max(1,Math.floor(e.delta??1)),this.stack.length-1);for(let e=0;e<r;e+=1)this.popPage()};if(void 0===t.alertBeforeUnloadMessage||!this.pageHost)return i(),!0;if(!t.backPrompt||t.backPrompt.signal.aborted){let e=new AbortController;t.backPrompt=e;let r=r=>{t.backPrompt===e&&(t.backPrompt=void 0,r&&!e.signal.aborted&&i())};this.pageHost.confirmBeforeUnload(t.alertBeforeUnloadMessage,e.signal).then(e=>{r(e)},()=>{r(!0)})}return!0}clear(){this.lifecycle.abort(),this.lifecycle=new AbortController,this.packageLoading=void 0,this.clearPages(),this.clearAppRuntime(),this.bridge.resetApplication(),this.packageSnapshot&&(this.packageSnapshot={...this.packageSnapshot,resourceUrlVersion:String(Number(this.packageSnapshot.resourceUrlVersion??0)+1)})}async restart(){if(this.packageSnapshot||await this.loadPackage(),this.destroyed)throw Error("Runtime was destroyed");await this.withPageTransition(async()=>{let e=this.stack.map(e=>{let{options:t}=e;return t});for(let t of(this.clear(),e))await this.pushLoadedPage(t)})}reload(){var e;null==(e=this.getCurrentStackItem())||e.page.reload()}destroy(){var e;this.destroyed||(this.destroyed=!0,this.bridge.destroy(),this.clear(),null==(e=this.pageHost)||e.destroy())}clearPages(){for(;this.stack.length>0;){let e=this.stack.pop();e&&this.removeStackItem(e,!1)}}async withPageTransition(e){let t=this.bridge.register();try{return await e()}finally{this.bridge.unregister(t)}}removeStackItem(e,t){var r;null==(r=e.backPrompt)||r.abort();let i=this.toStackEntry(e);this.sendPageLifecycleEvent(e,tj),e.page.clear();let n=this.getCurrentStackItem();return t&&n&&this.visible&&(n.page.setVisible(!0),this.sendPageLifecycleEvent(n,tL)),this.updateEmptyState(),i}async ensureAppRuntime(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.packageSnapshot||await this.loadPackage(),this.startAppRuntime(e)}startAppRuntime(){var e,t,r;let i,n,a,s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this.destroyed)throw Error("Runtime was destroyed");if(this.clearingAppRuntime)throw Error("Runtime is being cleared");if(null==(e=this.appStart)?void 0:e.error)throw this.appStart.error;if(this.appRuntime||!this.manifest.appRuntimeEntry)return;let o=h(this.manifestUrl,this.manifest.appRuntimeEntry);if(!o)throw Error("No Web entry configured for app runtime");let l=tN(o,this.packageInfo.resourceUrlVersion),d=new Promise((e,t)=>{i=e,n=t});d.catch(()=>{});let u={promise:d,resolve:i,reject:n,error:void 0};this.appStart=u;let c=e=>{var t;this.appStart!==u||this.destroyed||this.clearingAppRuntime||((null==(t=this.appRuntime)?void 0:t.isReady)||(u.error=e,u.reject(e)),this.bridge.fail(e))},p=this.appCallController.signal;try{a=function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:document.body,i=document.createElement("div");i.className="doubao-runtime-app",i.hidden=!0,i.style.display="none";let n=t.createContainer({...e,container:i});return{render:e=>(r.append(i),n.render(e)),clear(){n.clear(),i.remove()},sendEvent:n.sendEvent.bind(n),sendBridgeMessage:n.sendBridgeMessage.bind(n)}}({runtime:this,sandboxUrl:this.sandboxUrl,className:this.className,onError:(e,t)=>{var r;this.appStart!==u||this.destroyed||this.clearingAppRuntime||(c(e),null==(r=this.onError)||r.call(this,e,t))},appletSessionMessageHandler:(e,t)=>{var r;return this.appStart!==u||this.destroyed||this.clearingAppRuntime||this.bridge.handleMainBridgeMessage(e)?{routed:!0}:(null==(r=s.appletSessionMessageHandler)?void 0:r.call(s,e,t))??{routed:!1}},getAppletContext:()=>({owner:this.apiContextOwner,signal:p,source:"app",viewContext:s.viewContext??this.viewContext}),onReady:()=>{var e;let t=this.appRuntime;this.clearingAppRuntime||!t||t.container!==a||t.isReady||u.error||(t.isReady=!0,this.flushAppEvents(),u.resolve(),null==(e=s.onReady)||e.call(s))}},this.runtimeKernel,null==(t=this.pageHost)?void 0:t.container),this.appRuntime={container:a,isReady:!1,pendingEvents:[{name:this.visible?tR:tM,params:{}},...this.pendingAppEvents.splice(0)]};let e=void 0!==s.groupId?s.groupId:this.appGroupId;a.render({bridge:this.bridge,resourceUrl:l,groupId:null===e?void 0:e??this.manifest.appId,containerType:"APP",initData:this.appInitData??{},globalProps:{...tq(this.manifest,this.appGlobalProps),...null==(r=this.getRuntimeGlobalProps)?void 0:r.call(this)}})}catch(e){throw c(e instanceof Error?e:Error(String(e))),this.appRuntime=null,null==a||a.clear(),e}}clearAppRuntime(){var e;if(this.clearingAppRuntime)return;this.clearingAppRuntime=!0;let t=Error(this.destroyed?"Runtime was destroyed":"Runtime was cleared");null==(e=this.appStart)||e.reject(t),this.bridge.fail(t),this.pendingAppEvents=[];let r=this.appRuntime;(null==r?void 0:r.isReady)&&(this.visible&&r.container.sendEvent(tM),r.container.sendEvent(tj)),null==r||r.container.clear(),this.appCallController.abort(),this.appCallController=new AbortController,this.appRuntime=null,this.appStart=null,this.clearingAppRuntime=!1}sendAppEvent(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=this.appRuntime;if(!this.destroyed&&!this.clearingAppRuntime){if(!r)return void this.pendingAppEvents.push({name:e,params:t});if(!r.isReady)return void r.pendingEvents.push({name:e,params:t});r.container.sendEvent(e,t)}}sendAppBridgeMessage(e){if(!this.clearingAppRuntime){var t;null==(t=this.appRuntime)||t.container.sendBridgeMessage(e)}}flushAppEvents(){let e=this.appRuntime;if(null==e?void 0:e.isReady)for(let t of e.pendingEvents.splice(0))e.container.sendEvent(t.name,t.params)}sendPageLifecycleEvent(e,t){let r,i=(r={viewId:e.id,pageName:e.pageId,pageUrl:e.route},{viewId:e.id,eventName:JSON.stringify(r)});e.isReady?e.page.sendEvent(t,i):e.pendingLifecycleEvents.push({name:t,params:i})}flushPageLifecycleEvents(e){if(e.isReady)for(let t of e.pendingLifecycleEvents.splice(0))e.page.sendEvent(t.name,t.params)}resolvePageEntry(e){return e.entry??this.manifest.getPageEntry(e.pageId)}resolveRoutePageOptions(e){try{return tD(e,this.manifest)}catch(e){throw Object.assign(new w(e instanceof Error?e.message:String(e),104),{cause:e})}}getCurrentStackItem(){return this.stack[this.stack.length-1]??null}updateEmptyState(){var e;null==(e=this.pageHost)||e.setEmpty(0===this.stack.length)}getCurrentPages(){return[...this.stack.map(e=>tO(e.route,e.options)),...this.pendingPages]}getPackageInfo(){var e;return this.packageSnapshot?t$(this.manifest):{appId:null==(e=this.packageSource)?void 0:e.appId}}resolveFileSystemNamespace(){return void 0!==this.configuredFileSystemNamespace?this.configuredFileSystemNamespace:eu({packageInfo:this.getPackageInfo()},this.userId)}withNavigationType(e,t){return{...e,globalProps:{...e.globalProps,__WEB_NAVIGATION_TYPE__:t}}}async openBridgePage(e){this.packageSnapshot||await this.loadPackage();let t=this.resolveRoutePageOptions(e),r=this.resolvePageEntry(t),i=e.mode??"push",n=this.getCurrentStackItem(),a=e=>e.entry.path===r.path,s="replace"===i?n&&a(n)?this.stack.length-1:-1:"navigate"===i||"pop_to"===i?this.stack.findLastIndex(a):-1;if(s>=0){var o;let e=this.stack[s],r=t.globalProps??{};for(e.page.updateGlobalProps({__LOCATION__:r.__LOCATION__,__RENDER_DATA__:r.__RENDER_DATA__}),e.options={...e.options,initData:t.initData,globalProps:{...e.options.globalProps,...r}},null==(o=e.backPrompt)||o.abort();this.stack.length-1>s;)this.removeStackItem(this.stack.pop(),!1);e.page.setVisible(this.visible),n!==e&&this.visible&&this.sendPageLifecycleEvent(e,tL);let i=this.getCurrentPages();for(let e of this.stack)e.page.sendEvent(e1,{apiResults:{"doubao.getCurrentPages":{pages:i}}});this.updateEmptyState();return}"replace"===i||"pop_to"===i?await this.replacePage(t):await this.pushLoadedPage(t)}async navigateToBridgePage(e){this.packageSnapshot||await this.loadPackage(),await this.pushLoadedPage(this.withNavigationType(this.resolveRoutePageOptions(e),"navigateTo"))}async redirectToBridgePage(e){this.packageSnapshot||await this.loadPackage();let t=this.withNavigationType(this.resolveRoutePageOptions(e),"redirectTo");await this.replacePage(t)}async reLaunchBridgePage(e){this.packageSnapshot||await this.loadPackage();let t=this.withNavigationType(this.resolveRoutePageOptions(e),"reLaunch");await this.reLaunchPage(t)}exitBridgeApp(){this.clear()}toStackEntry(e){return{id:e.id,pageId:e.pageId,route:e.route,url:tO(e.route,e.options).route,resourceUrl:e.resourceUrl,entry:e.entry,element:e.element}}}class tW{kernel;autoRelease;runtimes=new Map;packageManagers=new WeakMap;nextPackageManagerId=0;constructor(e,t=!1){this.kernel=e,this.autoRelease=t}acquire(e){var t,r,i,n,a,s,o,l,d,u;let p=e.fileSystemNamespace??eu({packageInfo:{appId:e.appId}},e.userId),h=new URL(e.appRuntimeEntry,null==(t=globalThis.location)?void 0:t.href).href,m=e.packageManager;m&&!this.packageManagers.has(m)&&this.packageManagers.set(m,this.nextPackageManagerId++);let g=[m?this.packageManagers.get(m):"",String(e.sandboxUrl??""),(null==(r=e.packageInfo)?void 0:r.manifestUrl)??"",(null==(i=e.packageInfo)?void 0:i.resourceRoot)??"",e.appId,(null==(n=e.viewContext)?void 0:n.conversationId)??"",p,e.versionTag??(null==(a=e.viewContext)?void 0:a.versionTag)??"",h].join("\0"),f=this.runtimes.get(g);if(f&&!f.isDestroyed)return f;let v=new tF({packageManager:m,pageHost:e.pageHost,sandboxUrl:e.sandboxUrl,manifest:(null==(s=e.packageInfo)?void 0:s.manifest)??new c({manifestVersion:"3.0",packageName:e.appId,appId:e.appId,versionCode:"",applet:{appletId:e.appId,digest:"",appRuntimeEntry:h,pages:[]},widgets:[]}),manifestUrl:(null==(o=e.packageInfo)?void 0:o.manifestUrl)??h,resourceRoot:null==(l=e.packageInfo)?void 0:l.resourceRoot,registerPageController:!1,appGroupId:null,apiRegistry:e.apiRegistry??E,className:e.className,fileSystemNamespace:p,nativeModulesCallHandler:e.nativeModulesCallHandler,appInitData:e.appInitData,appGlobalProps:tU(e.appGlobalProps??{},{appId:e.appId}),getRuntimeGlobalProps:e.getRuntimeGlobalProps,viewContext:{appId:e.appId,conversationId:null==(d=e.viewContext)?void 0:d.conversationId,versionTag:e.versionTag??(null==(u=e.viewContext)?void 0:u.versionTag)},onError:e.onError},this.kernel??tk,this.autoRelease?()=>this.release(v):void 0);return this.runtimes.set(g,v),v}release(e){for(let[t,r]of this.runtimes)if(r===e){this.runtimes.delete(t),e.destroy();return}}destroy(){let e=[...this.runtimes.values()];for(let t of(this.runtimes.clear(),e))t.destroy()}}function tz(e,t){return class extends e{hostOptions;prepared=!1;constructor(e){super({...e,sandboxUrl:e.runtime?e.runtime.sandboxUrl:e.sandboxUrl}),this.hostOptions=e}prepare(e){super.prepare(e),this.prepared=!0}clear(){this.prepared=!1,super.clear()}render(e){var r,i,n;this.prepared||this.clear(),this.prepared=!1;let{application:a,applicationPackage:s,appRuntimeEntry:o,...l}=e,d=(null==a?void 0:a.appId)??(null==(i=l.globalProps)||null==(r=i.packageInfo)?void 0:r.appId),u=(null==a?void 0:a.appRuntimeEntry)??o,c=(null==a?void 0:a.viewContext)??(null==(n=l.globalProps)?void 0:n.__VIEW_CONTEXT__),p=this.hostOptions.runtime??(d&&u?(this.hostOptions.runtimeManager??t()).acquire({appId:d,appRuntimeEntry:u,packageInfo:s,packageManager:this.hostOptions.packageManager,sandboxUrl:this.hostOptions.sandboxUrl,apiRegistry:this.hostOptions.apiRegistry,nativeModulesCallHandler:this.hostOptions.nativeModulesCallHandler,versionTag:(null==a?void 0:a.versionTag)??(null==c?void 0:c.versionTag),viewContext:c,userId:this.hostOptions.userId,fileSystemNamespace:this.hostOptions.fileSystemNamespace}):void 0),h=null==p?void 0:p.bridge.register();try{return super.render({...l,applicationPackage:s,bridge:(null==p?void 0:p.bridge)??l.bridge})}catch(e){throw this.clear(),e}finally{h&&(null==p||p.bridge.unregister(h))}}}}new tW(void 0,!0),r(34974),r(71463),r(25907),r(92151);var tH=r(59314);let tV="embed-webview",tG="__channel_ack__",tJ=new WeakMap,tK=e=>({url:e});function tZ(e){if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}}function tX(e){return"string"==typeof e?e:JSON.stringify(e??{})}let tY=globalThis.HTMLElement??class{},tQ="region-to-decode";function t0(e){if("string"==typeof e)try{e=JSON.parse(e)}catch{return null}if(!e||"object"!=typeof e)return null;let{x:t,y:r,width:i,height:n}=e;return![t,r,i,n].every(Number.isFinite)||t<0||r<0||i<=0||n<=0?null:{x:t,y:r,width:i,height:n}}class t1{element;static observedAttributes=[];image;attributes=new MutationObserver(()=>this.update());resize;viewSize;cropStyle;constructor(e){var t;this.element=e,this.image=(null==(t=e.shadowRoot)?void 0:t.querySelector("#img"))??null,Object.defineProperty(e,tQ,{configurable:!0,get:()=>t0(e.getAttribute(tQ)),set:t=>{let r=t0(t);r?e.setAttribute(tQ,JSON.stringify(r)):e.removeAttribute(tQ)}})}connectedCallback(){this.attributes.observe(this.element,{attributes:!0,attributeFilter:[tQ,"src","mode","auto-size"]}),this.update()}clearCrop=()=>{var e;null==(e=this.cropStyle)||e.remove(),this.cropStyle=void 0};stopRendering(){var e,t,r;null==(e=this.resize)||e.disconnect(),this.resize=void 0,this.viewSize=void 0,null==(t=this.image)||t.removeEventListener("load",this.update),null==(r=this.image)||r.removeEventListener("error",this.clearCrop),this.clearCrop()}update=()=>{var e,t,r;let i=t0(this.element.getAttribute(tQ)),n=this.image;if(!i||!n)return void this.stopRendering();this.resize||(this.resize=new ResizeObserver(e=>{let[t]=e;this.viewSize=t.contentRect,this.update()}),this.resize.observe(this.element),n.addEventListener("load",this.update),n.addEventListener("error",this.clearCrop));let a=n.naturalWidth,s=n.naturalHeight,o=this.element.getAttribute("src"),l=this.element.getRootNode().host,d=o?(null==l||null==(e=l.resolveResource)?void 0:e.call(l,o))??o:o;if(!n.complete||!a||!s||n.getAttribute("src")!==d)return void this.clearCrop();let u=Math.min(i.width,a-i.x),c=Math.min(i.height,s-i.y),p=getComputedStyle(this.element),h=Number.parseFloat(p.paddingLeft)||0,m=Number.parseFloat(p.paddingTop)||0,g=(null==(t=this.viewSize)?void 0:t.width)??this.element.clientWidth-h-(Number.parseFloat(p.paddingRight)||0),f=(null==(r=this.viewSize)?void 0:r.height)??this.element.clientHeight-m-(Number.parseFloat(p.paddingBottom)||0);if(u<=0||c<=0||g<=0||f<=0)return void this.clearCrop();let v=g/u,y=f/c,b=this.element.getAttribute("mode");"aspectFit"===b?v=y=Math.min(v,y):"aspectFill"===b?v=y=Math.max(v,y):"center"===b&&(v=y=1);let w=h+(g-u*v)/2-i.x*v,_=m+(f-c*y)/2-i.y*y;this.cropStyle||(this.cropStyle=this.element.ownerDocument.createElement("style"),this.cropStyle.setAttribute("data-doubao-image-region",""),this.element.shadowRoot.append(this.cropStyle)),this.cropStyle.textContent=`#img {
1
+ (()=>{"use strict";var e,t,r,i,n,a,s,o,l,d,u,c,p={38114(e,t,r){let i,n,a;r(52205),r(40768),r(76235),r(15254),r(42949),r(18723),r(37891);var s=r(63159);function o(e){return"object"==typeof e&&null!==e}function l(e){var t;return"string"==typeof(null==(t=e.web)?void 0:t.entry)}function d(e,t){let r=new Map;for(let i of e){let e=t(i);e&&!r.has(e)&&r.set(e,i)}return r}function u(e){return"string"==typeof e?e||void 0:(null==e?void 0:e["3x"])||(null==e?void 0:e["2x"])||(null==e?void 0:e["1x"])}r(84086),r(21301),r(49678),r(32037),r(14104),r(66249),r(99811),r(40009),r(13035),r(13412),r(17973),r(64955),r(91016),r(23306),r(76619),r(57857),r(9975),r(93885),r(812),r(74180),r(994),r(4267),r(74678),r(55910),r(76691),r(72919);class c{raw;appEntry;pageEntries;pageIdEntryMap;pagePathEntryMap;widgetEntries;widgetEntryMap;constructor(e){var t;let r;this.raw=e,this.appEntry="string"==typeof(r=(null==(t=e.applet.web)?void 0:t.appRuntimeEntry)??e.applet.appRuntimeEntry)&&r?{entry:r}:null,this.pageEntries=e.applet.pages.filter(l),this.pageIdEntryMap=d(this.pageEntries,e=>e.id),this.pagePathEntryMap=d(this.pageEntries,e=>{var t;return(null==(t=e.path)?void 0:t.startsWith("/"))?e.path:void 0}),this.widgetEntries=e.widgets,this.widgetEntryMap=d(this.widgetEntries,e=>e.widgetId)}get appId(){return"string"==typeof this.raw.appId?this.raw.appId:void 0}get name(){return this.raw.applet.name}get iconSrc(){return u(this.raw.applet.icons)}get versionName(){return this.raw.versionName||this.raw.versionTag||this.raw.versionCode||void 0}get pages(){return this.getPageEntries()}get widgets(){return this.getWidgetEntries()}get appRuntimeEntry(){return this.appEntry}getPageEntries(){return[...this.pageEntries]}getWidgetEntries(){return[...this.widgetEntries]}getOptionalWidgetEntry(e){return e?this.widgetEntryMap.get(e):this.widgetEntries[0]}getPageEntry(e){let t=e?e.startsWith("/")?this.pagePathEntryMap.get(e):this.pageIdEntryMap.get(e):this.pageEntries[0];if(!t)throw Error(e?`Unknown pages entry: ${e}`:"No pages entries in Web manifest");return t}getWidgetEntry(e){let t=this.getOptionalWidgetEntry(e);if(!t)throw Error(e?`Unknown widgets entry: ${e}`:"No widgets entries in Web manifest");return t}}async function p(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.fetcher??fetch,i=await r(e,{cache:"no-store",headers:{Accept:"application/json"}});if(!i.ok)throw Error(`Failed to load Web manifest: ${i.status} ${i.statusText}`);let n=await i.json();if(!o(n))throw Error("Invalid Web manifest: expected a JSON object");return new c(n)}function h(e,t,r){var i,n;let a="item"in t?t.item:t,s="id"in a||"widgetId"in a?"string"==typeof(null==(i=a.web)?void 0:i.entry)?a.web.entry:void 0:a.entry;if(!s)return;let o=new URL(e,r??(null==(n=globalThis.location)?void 0:n.href)??"http://localhost/");return o.pathname=o.pathname.replace(/\/base\/manifest\.json$/,"/"),new URL(s,o).toString()}function m(){let e=Error("Widget host call was cancelled");return e.name="AbortError",e}function g(e){if(e.aborted)throw m()}function f(e,t){return g(t),new Promise((r,i)=>{let n=!1,a=e=>{n||(n=!0,t.removeEventListener("abort",s),e())},s=()=>a(()=>i(m()));t.addEventListener("abort",s,{once:!0}),Promise.resolve().then(e).then(e=>a(()=>r(e)),e=>a(()=>i(e)))})}function v(e){return(null==e?void 0:e.type)==="call"}function y(e){return(null==e?void 0:e.type)==="callback"}function b(e){return(null==e?void 0:e.type)==="event"}class w extends Error{errNo;errMsg;constructor(e,t,r=e){super(e),this.errNo=t,this.errMsg=r,Object.setPrototypeOf(this,new.target.prototype),this.name="BridgeAPIError"}}function _(e,t){return{type:"callback",callbackId:e.callbackId,params:{code:1,data:t}}}function S(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:t;return{type:"callback",callbackId:e.callbackId,params:{code:0,msg:t,errNo:r,errMsg:i}}}function x(e){return e instanceof Error?e.message:String(e)}function I(e,t){return t instanceof w?S(e,t.message,t.errNo,t.errMsg):S(e,x(t))}r(67548),r(70954),r(98803),r(79162),r(15385),r(39342),r(69152),r(61955),r(82689),r(84847),r(16285),r(20602),r(33307),r(94341),r(7270),r(44997),r(50364),r(79780),r(80372),r(72498),r(37928),r(25597),r(92321);class k{registry=new Map;eventSources=new Map;eventSourceCleanups=new Map;eventSourceRetainCounts=new Map;eventControllers=new Set;handlers={};constructor(e){e&&this.registerMany(e)}register(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!r.override&&this.registry.has(e))throw Error(`Bridge API handler ${e} is already registered`);let i=this.registry.get(e),n="function"==typeof t?{handler:t,canIUse:!0}:{...t,canIUse:t.canIUse??!0};return this.registry.set(e,n),this.handlers[e]=n.handler,()=>{if(this.registry.get(e)===n){if(i){this.registry.set(e,i),this.handlers[e]=i.handler;return}this.registry.delete(e),delete this.handlers[e]}}}registerMany(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=[];try{for(let[i,n]of Object.entries(e))r.push(this.register(i,n,t))}catch(e){for(let e of r.reverse())e();throw e}return()=>{for(let e of r.reverse())e()}}get(e){var t;return null==(t=this.registry.get(e))?void 0:t.handler}getSyncResults(e){let t={};for(let[r,i]of this.registry)i.syncResult&&this.canIUse(r,e)&&(t[r]="function"==typeof i.syncResult?i.syncResult({...e,apiRegistry:this}):i.syncResult);return t}registerEventSource(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!r.override&&this.eventSources.has(e))throw Error(`Bridge event source ${e} is already registered`);let i=this.eventSources.get(e),n="function"==typeof t?{source:t}:t;return this.stopEventSource(e),this.eventSources.set(e,n),(this.eventSourceRetainCounts.get(e)??0)>0&&this.startEventSource(e,n),()=>{if(this.eventSources.get(e)===n){if(this.stopEventSource(e),i){this.eventSources.set(e,i),(this.eventSourceRetainCounts.get(e)??0)>0&&this.startEventSource(e,i);return}this.eventSources.delete(e)}}}registerEventSources(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=[];try{for(let[i,n]of Object.entries(e))r.push(this.registerEventSource(i,n,t))}catch(e){for(let e of r.reverse())e();throw e}return()=>{for(let e of r.reverse())e()}}canIUse(e,t){let r=this.registry.get(e);if(r)return"function"==typeof r.canIUse?r.canIUse({...t,apiRegistry:this}):r.canIUse;let i=this.eventSources.get(e);return!!i&&("function"==typeof i.canIUse?i.canIUse({...t,apiRegistry:this}):i.canIUse??!0)}dispatch(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;if(!v(e))return;let i={...t,apiRegistry:this};if(this.canIUse(e.name,i))return function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!v(e))return;let i=t[e.name];if(!i)return S(e,`API ${e.name} is not implemented in Doubao Web SDK`);try{let t=i(e,r);if(t instanceof Promise)return t.catch(t=>I(e,t));return t??S(e,`API ${e.name} is not implemented in Doubao Web SDK`)}catch(t){return I(e,t)}}(e,this.handlers,i);let n=this.registry.has(e.name)?103:-1;if(!r)return S(e,`API ${e.name} is not implemented in Doubao Web SDK`,n);try{let t=r(e.name);return t instanceof Promise?t.then(()=>S(e,`API ${e.name} is not implemented in Doubao Web SDK`,n)).catch(t=>I(e,t)):S(e,`API ${e.name} is not implemented in Doubao Web SDK`,n)}catch(t){return I(e,t)}}getSupportedNames(e){return[...new Set([...this.registry.keys(),...this.eventSources.keys()])].filter(t=>this.canIUse(t,e))}emitEvent(e,t){let r=!1;for(let i of this.eventControllers)r=i.emit(e,t)||r;return r}createEventController(e){return new C(this,e)}fork(){let e=new k(this.getRegistrations());return e.registerEventSources(this.getEventSources()),e}getRegistrations(){return Object.fromEntries(this.registry)}getEventSources(){return Object.fromEntries(this.eventSources)}attachEventController(e){return this.eventControllers.add(e),()=>{this.eventControllers.delete(e)}}retainEventSource(e){let t=this.eventSourceRetainCounts.get(e)??0;if(this.eventSourceRetainCounts.set(e,t+1),t>0)return;let r=this.eventSources.get(e);r&&this.startEventSource(e,r)}releaseEventSource(e){let t=this.eventSourceRetainCounts.get(e)??0;if(t<=1){this.eventSourceRetainCounts.delete(e),this.stopEventSource(e);return}this.eventSourceRetainCounts.set(e,t-1)}notifyEventSubscription(e,t,r){var i,n;null==(n=this.eventSources.get(e))||null==(i=n.onSubscribe)||i.call(n,t,r)}startEventSource(e,t){this.stopEventSource(e);let r=t.source(t=>{this.emitEvent(e,t)});"function"==typeof r&&this.eventSourceCleanups.set(e,r)}stopEventSource(e){var t;null==(t=this.eventSourceCleanups.get(e))||t(),this.eventSourceCleanups.delete(e)}}class C{apiRegistry;dispatch;cleanupRegistry;subscribedEventNames=new Set;cleanups=new Set;destroyed=!1;visible=!0;visibilityListeners=new Set;constructor(e,t){this.apiRegistry=e,this.dispatch=t,this.cleanupRegistry=this.apiRegistry.attachEventController(this)}subscribe(e,t){this.destroyed||this.subscribedEventNames.has(e)||(this.subscribedEventNames.add(e),this.apiRegistry.retainEventSource(e),this.apiRegistry.notifyEventSubscription(e,this,t))}unsubscribe(e){this.subscribedEventNames.delete(e)&&this.apiRegistry.releaseEventSource(e)}isSubscribed(e){return this.subscribedEventNames.has(e)}emit(e,t){return!!this.isSubscribed(e)&&this.emitPrivate(e,t)}emitPrivate(e,t){return!this.destroyed&&(this.dispatch(e,t),!0)}setVisible(e){for(let t of(this.visible=e,this.visibilityListeners))t(e)}onVisibilityChange(e){return e(this.visible),this.visibilityListeners.add(e),()=>this.visibilityListeners.delete(e)}onDestroy(e){return this.destroyed?(e(),()=>{}):(this.cleanups.add(e),()=>this.cleanups.delete(e))}destroy(){if(!this.destroyed){for(let e of(this.destroyed=!0,this.cleanups))try{e()}catch(e){console.error("Failed to clean up bridge API resources",e)}for(let e of(this.cleanups.clear(),this.visibilityListeners.clear(),this.subscribedEventNames))this.apiRegistry.releaseEventSource(e);this.subscribedEventNames.clear(),this.cleanupRegistry()}}}let E=new k;function N(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:i;return null==e?void 0:e.getPackageInfo()}async function T(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i;return await (null==t?void 0:t.navigateTo(e)),!!t}async function A(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i;return await (null==t?void 0:t.redirectTo(e)),!!t}async function M(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i;return await (null==t?void 0:t.reLaunch(e)),!!t}function j(){return"0.8.0-rc.12"}function R(e){var t;let{screenWidth:r,statusBarHeight:i}=e??(null==(t=globalThis.lynx)?void 0:t.__globalProps),n=Math.round(i)+4,a=Math.round(r)-12;return{bottom:n+36,height:36,left:a-84,right:a,top:n,width:84}}function P(){return(navigator.language||"zh-CN").replace(/-/g,"_")}function L(){var e,t,r;return(null==(t=(r=window).matchMedia)||null==(e=t.call(r,"(prefers-color-scheme: dark)"))?void 0:e.matches)?"dark":"light"}function D(){return"string"==typeof DoubaoAppsSDKVersion?DoubaoAppsSDKVersion:j()??""}function O(){return navigator.userAgentData}function U(){var e;let t=null==(e=O())?void 0:e.brands,r=null==t?void 0:t.find(e=>{let{brand:t}=e;return!/not.a.brand/i.test(t)});if(null==r?void 0:r.brand)return r.brand;let i=navigator.userAgent??"";return/edg\//i.test(i)?"Microsoft Edge":/chrome|crios/i.test(i)?"Chrome":/firefox|fxios/i.test(i)?"Firefox":/safari/i.test(i)?"Safari":"Browser"}function $(){var e,t;let r=null==(e=O())?void 0:e.brands,i=null==r?void 0:r.find(e=>{let{brand:t}=e;return!/not.a.brand/i.test(t)});if(null==i?void 0:i.version)return i.version;let n=navigator.userAgent??"";return(null==(t=/(?:edg|chrome|crios|firefox|fxios|version)\/([\d.]+)/i.exec(n))?void 0:t[1])??void 0}function q(){var e;let t=navigator.userAgent??"",r=navigator.platform??"",i=(null==(e=O())?void 0:e.platform)??"",n=`${i} ${r} ${t}`,a=navigator.maxTouchPoints??0;return/android/i.test(n)?{platform:"android",brand:"Android"}:/iphone/i.test(n)?{platform:"ios",brand:"iPhone"}:/ipad/i.test(n)||/mac/i.test(r)&&a>1?{platform:"ios",brand:"iPad"}:/mac/i.test(n)?{platform:"mac",brand:"Mac"}:/win/i.test(n)?{platform:"windows",brand:"Windows"}:/linux/i.test(n)?{platform:"linux",brand:"Linux"}:{platform:"web",brand:"Browser"}}function B(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:N();return{appId:(null==e?void 0:e.appId)??"",name:(null==e?void 0:e.name)??"",iconSrc:null==e?void 0:e.iconSrc}}function F(e){var t,r,i,n,a;if((null==e?void 0:e.containerWidth)!==void 0){let{density:t=1,screenWidth:r=0,screenHeight:i=0,containerWidth:n=0,containerHeight:a=0,statusBarHeight:s=0,topHeight:o=s,safeArea:l={}}=e,{marginTop:d=0,marginBottom:u=0,marginLeft:c=0,marginRight:p=0}=l;return{pixelRatio:t,screenWidth:r,screenHeight:i,windowWidth:n,windowHeight:a,statusBarHeight:s,screenTop:o,safeArea:{left:c,right:n-p,top:d,bottom:a-u,width:n-c-p,height:a-d-u}}}let s=Math.round((null==(n=window.visualViewport)?void 0:n.width)??window.innerWidth??0),o=Math.round((null==(a=window.visualViewport)?void 0:a.height)??window.innerHeight??0),l=window.devicePixelRatio??1,d=Math.round((null==(t=window.screen)?void 0:t.width)??s),u=Math.round((null==(r=window.screen)?void 0:r.height)??o),c=Math.round((null==(i=window.visualViewport)?void 0:i.offsetTop)??0);return{pixelRatio:l,screenWidth:d,screenHeight:u,windowWidth:s,windowHeight:o,statusBarHeight:c,safeArea:{left:0,right:s,top:c,bottom:o,width:s,height:Math.max(0,o-c)},screenTop:c}}function W(){return q().platform}function z(){var e,t,r,i,n;let a=navigator.userAgent??"",s=W();return"android"===s?null==(e=/android\s+([\d.]+)/i.exec(a))?void 0:e[1]:"ios"===s?null==(r=/(?:iphone os|cpu os)\s+([\d_]+)/i.exec(a))||null==(t=r[1])?void 0:t.replace(/_/g,"."):"mac"===s?null==(n=/mac os x\s+([\d_]+)/i.exec(a))||null==(i=n[1])?void 0:i.replace(/_/g,"."):void 0}function H(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:W();return"android"===e?"Android":"ios"===e?"iOS":"mac"===e?"macOS":"windows"===e?"Windows":"linux"===e?"Linux":"Web"}function V(e){let t;if((null==e?void 0:e.deviceModel)!==void 0){let t=e.os??e.devicePlatform??"";return{abi:e.abi,deviceAbi:e.deviceAbi,cpuType:e.cpuType,benchmarkLevel:"number"==typeof e.benchmarkLevel?e.benchmarkLevel:-1,brand:e.deviceBrand??"",model:e.deviceModel??e.deviceType??"",system:e.osVersion?`${t} ${e.osVersion}`:t,platform:(e.platform??t).toLowerCase(),memorySize:null==e.memorySize?"":String(e.memorySize)}}let r=q(),i=navigator.platform||W();return{abi:i,deviceAbi:i,benchmarkLevel:-1,brand:r.brand,model:function(){let e=navigator.userAgent??"",t=W();if("android"===t){var r,i;return(null==(i=/android\s+[\d.]+;\s*([^;)]+)/i.exec(e))||null==(r=i[1])?void 0:r.trim())||"Android"}return"ios"===t?q().brand:"mac"===t||"windows"===t||"linux"===t?navigator.platform||q().brand:U()}(),system:function(){let e=W(),t=z();if("web"!==e){let r=H(e);return t?`${r} ${t}`:r}let r=$(),i=U();return r?`${i} ${r}`:"Web"}(),platform:r.platform,cpuType:i,memorySize:"number"==typeof(t=navigator.deviceMemory)&&Number.isFinite(t)?String(Math.round(1024*t)):""}}function G(){let e=V(),t=F(),r=t.windowWidth>t.windowHeight;return{os:H(e.platform),platform:e.platform,osVersion:z(),deviceBrand:e.brand,language:P(),deviceModel:e.model,deviceType:e.model,deviceAbi:e.deviceAbi,cpuType:e.cpuType,memorySize:e.memorySize,benchmarkLevel:e.benchmarkLevel,appVersion:$(),appTheme:L(),channel:"release",screenOrientation:+!!r,isLandscape:+!!r,abi:e.abi}}function J(e){var t,r,i;let n,a=F(e),s=V(e);return{...a,brand:s.brand,model:s.model,language:(null==e||null==(t=e.language)?void 0:t.replace(/-/g,"_"))??P(),version:(null==e?void 0:e.appVersion)??$(),system:s.system,platform:(null==e||null==(r=e.os)?void 0:r.toLowerCase())??s.platform,SDKVersion:D(),theme:(null==e?void 0:e.appTheme)??L(),benchmarkLevel:s.benchmarkLevel,enableDebug:(null==e?void 0:e.channel)==="debug",deviceOrientation:(i=a.windowWidth>a.windowHeight,!0===(n=(null==e?void 0:e.isLandscape)??(null==e?void 0:e.screenOrientation))||1===n||"string"==typeof n&&n.toLowerCase().includes("landscape")?"landscape":!1===n||0===n||"string"==typeof n&&n.toLowerCase().includes("portrait")?"portrait":i?"landscape":"portrait"),abi:s.abi}}function K(){let e={isConnected:!1!==navigator.onLine,networkType:!1===navigator.onLine?"none":"unknown",hasSystemProxy:!1,weakNet:!1};return{networkType:e.networkType,signalStrength:e.signalStrength,hasSystemProxy:e.hasSystemProxy??!1,weakNet:e.weakNet??!1}}function Z(e){return{SDKVersion:D(),enableDebug:(null==e?void 0:e.channel)==="debug",host:{appId:(null==e?void 0:e.appName)??""},language:(null==e?void 0:e.language)??P(),version:(null==e?void 0:e.appVersion)??$(),theme:(null==e?void 0:e.appTheme)??L()}}function X(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:N(),t=arguments.length>1?arguments[1]:void 0;return{miniProgram:{appId:B(e).appId,envVersion:(null==t?void 0:t.channel)==="debug"?"develop":"release",version:(null==e?void 0:e.versionName)??""}}}function Y(e){var t;return(null==e||null==(t=e.navigation)?void 0:t.getPackageInfo())??(null==e?void 0:e.packageInfo)}E.handlers,r(31178),r(32085),r(12021);var Q=r(95550),ee=r(66013);r(46455);function et(e){if("string"!=typeof e)throw Error("key must be a string");if(0===e.length)throw Error("key must not be empty");if(e.length>1024)throw Error("key length must be less than or equal to 1024");return e}function er(e){if(ei(e)>1048576)throw Error("data size must be less than or equal to 1048576 bytes")}function ei(e){return new TextEncoder().encode(e).byteLength}function en(e){return Object.values(e).reduce((e,t)=>e+ei(t),0)}function ea(e){if(e>0xa00000)throw new w("total storage size exceeded",1600002)}function es(e){if(!o(e)||Array.isArray(e))throw Error("Storage snapshot must be an object");let t=0;for(let[r,i]of Object.entries(e)){if(et(r),"string"!=typeof i)throw Error("Storage values must be serialized strings");er(i),t+=ei(i)}ea(t)}let eo=new Map,el=new Map,ed=new Set;function eu(e,t){var r;let i=JSON.stringify([(null==e||null==(r=e.packageInfo)?void 0:r.appId)||"unknown-app",t??null]);return`web-storage:${(0,ee.My)((0,Q.sc)(i))}`}function ec(){let e=Date.now();return{entries:Object.fromEntries(["/","/temp","/user"].map(t=>[t,{type:"directory",createTime:e,lastModifiedTime:e}]))}}function ep(){return n??=new Promise((e,t)=>{let r=indexedDB.open("doubao-web-sdk-files",2);r.onupgradeneeded=()=>{let e=r.result;for(let t of["storage","files"])e.objectStoreNames.contains(t)||e.createObjectStore(t)},r.onsuccess=()=>{r.result.onversionchange=()=>{r.result.close(),n=void 0},e(r.result)},r.onerror=()=>{n=void 0,t(r.error)},r.onblocked=()=>{n=void 0,t(Error("Storage database upgrade is blocked; close other app views and retry"))}})}function eh(e){return IDBKeyRange.bound([e],[e,[]])}function em(e){return new Promise((t,r)=>{e.oncomplete=()=>t(),e.onabort=()=>{let t=e.error,i=new w((null==t?void 0:t.message)??"Storage transaction failed",(null==t?void 0:t.name)==="QuotaExceededError"?208:102);i.cause=t,r(i)}})}async function eg(e,t){let r=await ep(),i=r.transaction(["storage","files"]),n=em(i);for(let[r,n]of[["storage",t.storageSnapshot],["files",t.fileSystemSnapshot.entries]]){let t=i.objectStore(r).openCursor(eh(e));t.onsuccess=()=>{let e=t.result;e&&(Object.defineProperty(n,String(e.key[1]),{value:"files"===r?Object.freeze(e.value):e.value,enumerable:!0,configurable:!0,writable:!0}),e.continue())}}if(await n,0===Object.keys(t.fileSystemSnapshot.entries).length){t.fileSystemSnapshot=ec();let i=r.transaction("files","readwrite"),n=em(i);for(let[r,n]of Object.entries(t.fileSystemSnapshot.entries))i.objectStore("files").put(n,[e,r]);await n}}function ef(e){let t=eo.get(e);if(!t){let r={storageSnapshot:{},fileSystemSnapshot:{entries:{}}};t={snapshot:r,references:0,ready:eg(e,r)},eo.set(e,t)}t.references+=1;let r=t,i=!1;return{ready:t.ready,release(){if(i)return;i=!0,r.references-=1;let t=()=>{r.references||eo.get(e)!==r||eo.delete(e)};r.ready.then(t,t)}}}function ev(e,t){let r=ef(e),i=async()=>(await r.ready,t()),n=(el.get(e)??Promise.resolve()).then(i,i);el.set(e,n);let a=()=>{el.get(e)===n&&el.delete(e),r.release()};return n.then(a,a),n}function ey(e){var t;let r=null==(t=eo.get(e))?void 0:t.snapshot;if(!r)throw Error("Application storage is not initialized");return{storageSnapshot:{...r.storageSnapshot},fileSystemSnapshot:{entries:{...r.fileSystemSnapshot.entries}}}}function eb(e){return ey(e).fileSystemSnapshot}function ew(e){return ed.add(e),()=>{ed.delete(e)}}function e_(e,t,r){let i={...r??ey(e),fileSystemNamespace:e,mutationId:t};for(let e of ed)try{e(i)}catch(e){console.error("Cannot deliver application storage update",e)}}function eS(e,t){let r={};for(let i of new Set([...Object.keys(e),...Object.keys(t)])){let n=Object.hasOwn(t,i)?t[i]:null,a=Object.hasOwn(e,i)?e[i]:void 0,s=o(a)&&o(n)&&a.type===n.type&&a.data===n.data&&a.createTime===n.createTime&&a.lastModifiedTime===n.lastModifiedTime;a===(n??void 0)||s||Object.defineProperty(r,i,{value:n,enumerable:!0})}return r}async function ex(e,t){let r=ey(e);for(let[e,i]of(t.clearStorage&&(r.storageSnapshot={}),[[r.storageSnapshot,t.storageChanges],[r.fileSystemSnapshot.entries,t.fileSystemChanges]]))for(let[t,r]of Object.entries(i??{}))null===r?delete e[t]:Object.defineProperty(e,t,{value:r,enumerable:!0,writable:!0,configurable:!0});(t.storageChanges||t.clearStorage)&&es(r.storageSnapshot),t.fileSystemChanges&&ek(r.fileSystemSnapshot,eb(e));let i=(await ep()).transaction(["storage","files"],"readwrite"),n=em(i);try{for(let[r,n]of(t.clearStorage&&i.objectStore("storage").delete(eh(e)),[["storage",t.storageChanges],["files",t.fileSystemChanges]])){let t=i.objectStore(r);for(let[i,a]of Object.entries(n??{}))null===a?t.delete([e,i]):t.put("files"===r?Object.freeze(a):a,[e,i])}}catch(e){throw i.abort(),await n.catch(()=>{}),e}await n,eo.get(e).snapshot=r,e_(e,t.mutationId,t)}function eI(e){return o(e)&&"directory"===e.type}function ek(e,t){if(!o(e)||!o(e.entries))throw Error("Invalid file snapshot");let r={user:0,temp:0};for(let[i,n]of Object.entries(e.entries)){if(!o(n)||!["file","directory"].includes(String(n.type))||!Number.isFinite(n.createTime)||0>Number(n.createTime)||!Number.isFinite(n.lastModifiedTime)||0>Number(n.lastModifiedTime)||"/"!==i&&(!/^\/(user|temp)(\/[^/]+)*$/.test(i)||i.split("/").some(e=>"."===e||".."===e||/[\\\0]/.test(e)))||"/"!==i&&!eI(e.entries[i.slice(0,i.lastIndexOf("/"))||"/"])||["/","/user","/temp"].includes(i)&&"directory"!==n.type)throw Error(`Invalid file entry: ${i}`);if("file"===n.type){if("string"!=typeof n.data)throw Error(`Invalid file data: ${i}`);if((null==t?void 0:t.entries[i])!==n&&(n.data.length%4!=0||/[^A-Za-z0-9+/=]/.test(n.data)||!/^[^=]*={0,2}$/.test(n.data)))throw Error(`Invalid base64 file: ${i}`);let e=i.startsWith("/user/")?"user":"temp";r[e]+=Math.floor(3*n.data.length/4)-(n.data.endsWith("==")?2:+!!n.data.endsWith("="))}}for(let t of["/","/user","/temp"])if(!eI(e.entries[t]))throw Error(`Missing file directory: ${t}`);if(r.user>0x3200000||r.temp>0x6400000)throw new w("total file storage size exceeded",208)}function eC(e){if(!o(e)||"doubao-web-storage"!==e.format||1!==e.version||!o(e.storageSnapshot))throw Error("存储与文件备份格式无效");es(e.storageSnapshot),ek(e.fileSystemSnapshot)}r(20303),r(99166),r(6106),r(22742),r(37553),r(62148),r(89055),r(12205),r(65850),r(65135),r(5876),r(94359),r(28016),r(38641),r(82247),r(11839),r(56109),r(63589),r(45249);var eE=r(59933),eN=r(12683);function eT(e){if(e.startsWith("/")||e.includes("\\")||e.includes("\0")||/^[a-z]:/i.test(e))throw new w("ZIP entry escapes the target directory",213);let t=[];for(let r of e.split("/"))if(r&&"."!==r)if(".."===r){if(!t.length)throw new w("ZIP entry escapes the target directory",213);t.pop()}else t.push(r);return t.join("/")}function eA(e){return Math.floor(3*e.length/4)-(e.endsWith("==")?2:+!!e.endsWith("="))}function eM(e){if(e>0xa00000)throw new w("total size limit exceeded",208)}function ej(e,t,r){let i=t.startsWith("/user/")?"/user/":"/temp/",n=("/user/"===i?50:100)*1048576,a=r;for(let[r,n]of Object.entries(e.entries))r!==t&&r.startsWith(i)&&"file"===n.type&&(a+=eA(n.data));if(a>n)throw new w("total size limit exceeded",208)}function eR(e){o(e.fileSystemSnapshot)||(e.fileSystemSnapshot={entries:{}}),o(e.fileSystemSnapshot.entries)||(e.fileSystemSnapshot.entries={});let t=Date.now();for(let i of["/","/temp","/user"]){var r;(null==(r=e.fileSystemSnapshot.entries[i])?void 0:r.type)!=="directory"&&(e.fileSystemSnapshot.entries[i]={type:"directory",createTime:t,lastModifiedTime:t})}return e.fileSystemSnapshot}function eP(e,t){let r=e[t];if("string"!=typeof r)throw new w(`${t} must be a string`,104);return r}function eL(e,t){let r=e[t];return"string"==typeof r?r:void 0}function eD(e){let t;if(0===e.length||e.includes("?")||e.includes("#")||/%(?![0-9a-f]{2})/i.test(e))throw new w("invalid applet file path",213);try{t=decodeURIComponent(e)}catch{throw new w("invalid applet file path",213)}if("."===t||".."===t||t.includes("/")||t.includes("\\")||t.includes("\0"))throw new w("invalid applet file path",213);return t}function eO(e){let t=/^appletfile:\/\/(user|temp)(?:\/(.*))?$/.exec(e);if(!t)throw new w("path must use appletfile://user or appletfile://temp",213);let r=t[1],i=t[2];if(void 0===i||0===i.length)return`/${r}`;let n=i.split("/").map(eD);return`/${r}/${n.join("/")}`}function eU(e){let t=/^data:[^,]*;base64,([A-Za-z0-9+/]*={0,2})$/.exec(e);if(!t)return;let r=t[1];if(r.length%4==1||r.endsWith("=")&&r.length%4!=0)throw new w("invalid base64 data",104);return{type:"file",data:r,createTime:0,lastModifiedTime:0}}function e$(e){let t=eO(e);if("/temp"===t||"/user"===t)return"";let r=t.lastIndexOf("/");return t.slice(0,r)}function eq(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function eB(e){let t=e.split("/").filter(Boolean),r=t.shift();if("temp"!==r&&"user"!==r)throw new w(`invalid applet file path: ${e}`,213);let i=t.map(eq).join("/");return i.length>0?`appletfile://${r}/${i}`:`appletfile://${r}`}function eF(e,t){return e.entries[eO(t)]}function eW(e,t){let r=eU(t);if(r)return r;let i=eO(t),n=e.entries[i];if(!n)throw new w(`file not found: ${i}`,203);if("file"!==n.type)throw new w(`path is a directory: ${i}`,1901001);return n}function ez(e,t){let r=eO(t),i=e.entries[r];if(!i)throw new w(`directory not found: ${r}`,203);if("directory"!==i.type)throw new w(`path is not a directory: ${r}`,1901002);return i}function eH(e,t){let r=e$(t);if(!r)throw new w(`invalid parent directory: ${t}`,213);let i=Date.now(),n="";for(let t of r.split("/").filter(Boolean)){n+=`/${t}`;let r=e.entries[n];if((null==r?void 0:r.type)==="file")throw new w(`path is not a directory: ${n}`,1901002);r||(e.entries[n]={type:"directory",createTime:i,lastModifiedTime:i})}}function eV(e){let t;try{t=atob(e)}catch{throw new w("invalid base64 data",104)}let r=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)r[e]=t.charCodeAt(e);return r}function eG(e,t){let r="string"==typeof e?e:String(e??"");return"base64"===t?eV(r):new TextEncoder().encode(r)}function eJ(e,t,r){let i=eO(t),n=Date.now(),a=e.entries[i];if((null==a?void 0:a.type)==="directory")throw new w(`path is a directory: ${i}`,1901001);ej(e,i,r.byteLength),eH(e,t),e.entries[i]={type:"file",data:function(e){let t="";for(let r=0;r<e.length;r+=1)t+=String.fromCharCode(e[r]);return btoa(t)}(r),createTime:(null==a?void 0:a.createTime)??n,lastModifiedTime:n}}function eK(e,t,r){let i=eR(e),n=eP(t,"dirPath"),a=eO(n),s=Date.now(),o=i.entries[a];if((null==o?void 0:o.type)==="directory")return{};if(o)throw new w(`path is not a directory: ${a}`,1901002);if(!0===t.recursive){let e="";for(let t of a.split("/").filter(Boolean))if(e+=`/${t}`,i.entries[e]||(i.entries[e]={type:"directory",createTime:s,lastModifiedTime:s}),"directory"!==i.entries[e].type)throw new w(`path is not a directory: ${e}`,1901002)}else{let e=e$(n);if(!e)throw new w(`invalid parent directory: ${n}`,213);let t=i.entries[e];if(!t)throw new w(`directory not found: ${e}`,203);if("directory"!==t.type)throw new w(`path is not a directory: ${e}`,1901002);i.entries[a]={type:"directory",createTime:s,lastModifiedTime:s}}return r(),{}}function eZ(e,t,r){let i=eR(e),n=eP(t,"dirPath"),a=eO(n);if("/temp"===a||"/user"===a)throw new w("cannot remove root directory",213);ez(i,n);let s=`${a}/`,o=Object.keys(i.entries).filter(e=>e.startsWith(s));if(!0!==t.recursive&&o.length>0)throw new w(`directory is not empty: ${a}`,1901001);for(let e of o)delete i.entries[e];return delete i.entries[a],r(),{}}function eX(e,t,r){let i=eR(e),n=eP(t,"filePath"),a=eO(n);return eW(i,n),delete i.entries[a],r(),{}}function eY(e,t){let r=eR(e),i=eP(t,"path"),n=eU(i),a=n?i:eO(i),s=n??r.entries[a];if(!s)throw new w(`path not found: ${a}`,203);return{size:"file"===s.type?eA(s.data):0,lastModifiedTime:s.lastModifiedTime,isDirectory:"directory"===s.type}}let eQ={"doubao.readFile":function(e,t){var r;let i=eW(eR(e),eP(t,"filePath"));return eM(eA(i.data)),{data:(r=i.data,"utf-8"===eL(t,"encoding")?new TextDecoder().decode(eV(r)):r)}},"doubao.writeFile":function(e,t,r){let i=eR(e),n=eG(t.data,eL(t,"encoding"));return eM(n.byteLength),eJ(i,eP(t,"filePath"),n),r(),{}},"doubao.appendFile":function(e,t,r){let i=eR(e),n=eP(t,"filePath"),a=eO(n),s=i.entries[a];if((null==s?void 0:s.type)==="directory")throw new w(`path is a directory: ${a}`,1901001);let o=eG(t.data,eL(t,"encoding"));eM(o.byteLength),ej(i,a,((null==s?void 0:s.type)==="file"?eA(s.data):0)+o.byteLength);let l=(null==s?void 0:s.type)==="file"?eV(s.data):new Uint8Array,d=new Uint8Array(l.length+o.length);return d.set(l),d.set(o,l.length),eJ(i,n,d),r(),{}},"doubao.access":function(e,t){let r=eR(e),i=eP(t,"path");if(!eF(r,i))throw new w(`path not found: ${i}`,203);return{}},"doubao.mkdir":eK,"doubao.rmdir":eZ,"doubao.readdir":function(e,t){let r=eR(e),i=eP(t,"dirPath");return ez(r,i),{files:function(e,t){let r=eO(t),i="/"===r?"/":`${r}/`,n=new Set;for(let t of Object.keys(e.entries)){if(t===r||!t.startsWith(i))continue;let e=t.slice(i.length).split("/")[0];e&&n.add(e)}return[...n]}(r,i)}},"doubao.unlink":eX,"doubao.stat":eY,"doubao.copyFile":function(e,t,r){let i=eR(e),n=eW(i,eP(t,"srcPath")),a=eP(t,"destPath");return ej(i,eO(a),eA(n.data)),eJ(i,a,eV(n.data)),r(),{}},"doubao.getFileInfo":function(e,t){let r=eP(t,"filePath"),{size:i}=eY(e,{path:r});if(void 0===t.digestAlgorithm)return{size:i};let n=eP(t,"digestAlgorithm").toLowerCase(),a=eW(eR(e),r),s="md5"===n?eE.Fx:"sha1"===n?eE.e8:void 0;if(!s)throw new w(`unsupported digest algorithm: ${n}`,102);return{size:i,digest:(0,ee.My)(s(eV(a.data)))}},"doubao.rename":function(e,t,r){let i=eR(e),n=eP(t,"oldPath"),a=eP(t,"newPath"),s=eO(n),o=eO(a),l=i.entries[s];if(!l)throw new w(`path not found: ${s}`,203);if("/temp"===s||"/user"===s)throw new w("cannot rename root directory",213);if(s===o)return{};if("directory"===l.type&&o.startsWith(`${s}/`))throw new w("cannot move a directory into itself",213);if(i.entries[o])throw new w(`target already exists: ${o}`,102);for(let e of(eH(i,a),Object.keys(i.entries)))if(e===s||e.startsWith(`${s}/`)){let t=o+e.slice(s.length);i.entries[t]=i.entries[e],delete i.entries[e]}return r(),{}},"doubao.truncate":function(e,t,r){let i=eR(e),n=eP(t,"filePath"),a=eW(i,n),s=t.length??0;if("number"!=typeof s||!Number.isSafeInteger(s)||s<0)throw new w("length must be a non-negative integer",104);ej(i,eO(n),s);let o=eV(a.data),l=new Uint8Array(s);return l.set(o.slice(0,s)),eJ(i,n,l),r(),{}},"doubao.saveFile":function(e,t,r){let i,n,a=eR(e),s=eP(t,"tempFilePath"),o=eU(s),l=o??eW(a,s),d=eL(t,"filePath"),u=o?(i=s.slice(5,s.indexOf(";")),`media.${({"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","audio/wav":"wav","audio/aac":"aac","audio/mp4":"mp4"})[i]??"bin"}`):"/temp"===(n=eO(s))||"/user"===n?"":n.slice(n.lastIndexOf("/")+1),c=`/user/${Date.now()}`,p=d&&d.length>0?d:eB(`${c}_${u}`);for(let e=1;!d&&a.entries[eO(p)];e++)p=eB(`${c}_${e}_${u}`);return ej(a,eO(p),eA(l.data)),eJ(a,p,eV(l.data)),o||eO(s)===eO(p)||delete a.entries[eO(s)],r(),{savedFilePath:p}},"doubao.getSavedFileList":function(e){return{fileList:Object.entries(eR(e).entries).flatMap(e=>{let[t,r]=e;return t.startsWith("/user/")&&"file"===r.type?[{filePath:eB(t),size:eA(r.data),createTime:r.createTime}]:[]})}},"doubao.removeSavedFile":function(e,t,r){var i;let n=eP(t,"filePath");return(null==(i=eF(eR(e),n))?void 0:i.type)==="directory"?eZ(e,{dirPath:n},r):eX(e,t,r)},"doubao.unzip":function(e,t,r){let i=eR(e),n=eW(i,eP(t,"zipFilePath")),a=eP(t,"targetPath"),s=eO(a),o=function(e,t){try{let r=function(e,t){let r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=e.length-22,n=Math.max(0,e.length-65557);for(;i>=n&&(0x6054b50!==r.getUint32(i,!0)||i+22+r.getUint16(i+20,!0)!==e.length);)i--;if(i<n||0!==r.getUint16(i+4,!0)||0!==r.getUint16(i+6,!0))throw Error("Invalid or multipart ZIP archive");let a=r.getUint16(i+10,!0),s=r.getUint32(i+16,!0);if(65535===a||0xffffffff===s){if(i<20||0x7064b50!==r.getUint32(i-20,!0))throw Error("Invalid ZIP64 archive");let e=Number(r.getBigUint64(i-12,!0));if(0x6064b50!==r.getUint32(e,!0))throw Error("Invalid ZIP64 directory");a=Number(r.getBigUint64(e+32,!0)),s=Number(r.getBigUint64(e+48,!0))}if(!Number.isSafeInteger(a)||a>e.length/46||!Number.isSafeInteger(s))throw Error("Invalid ZIP directory size");let o=new Map,l=0;for(let n=0;n<a;n++){if(s+46>i||0x2014b50!==r.getUint32(s,!0))throw Error("Invalid ZIP directory entry");let n=r.getUint16(s+8,!0),a=r.getUint16(s+28,!0),d=r.getUint16(s+30,!0),u=s+46+a+d+r.getUint16(s+32,!0);if(u>i||1&n)throw Error("Invalid or encrypted ZIP entry");let c=(0,eN.he)(e.subarray(s+46,s+46+a),!(2048&n));eT(c);let p=r.getUint32(s+24,!0);if(0xffffffff===p){let e=s+46+a,t=e+d;for(;e+4<=t&&1!==r.getUint16(e,!0);)e+=4+r.getUint16(e+2,!0);if(e+12>t||8>r.getUint16(e+2,!0))throw Error("Invalid ZIP64 file size");p=Number(r.getBigUint64(e+4,!0))}if(!Number.isSafeInteger(l+=p)||l>t)throw new w("ZIP expanded size exceeds the file system quota",208);o.set(c,r.getUint32(s+16,!0)),s=u}return o}(e,t),i=new Map,n=0,a=new eN.HJ(e=>{eT(e.name);let r=new eN.uZ(e.name);r.ondata=()=>{};let a=[],s=0;e.ondata=(o,l,d)=>{if(o)throw o;if((n+=l.length)>t)throw new w("ZIP expanded size exceeds the file system quota",208);if(a.push(l),s+=l.length,r.push(l,d),d){let t=new Uint8Array(s),n=0;for(let e of a)t.set(e,n),n+=e.length;i.set(e.name,{data:t,crc:r.crc>>>0})}},e.start()});a.register(eN.mM);for(let t=0;t<e.length;t+=65536)a.push(e.subarray(t,t+65536),t+65536>=e.length);if(i.size!==r.size)throw Error("ZIP entry count does not match its directory");for(let[e,t]of i)if(t.crc!==r.get(e))throw Error("ZIP entry checksum does not match");return new Map([...i].map(e=>{let[t,r]=e;return[t,r.data]}))}catch(e){if(e instanceof w)throw e;throw new w(`Unable to unzip file: ${e instanceof Error?e.message:String(e)}`,102)}}(eV(n.data),(s.startsWith("/user")?50:100)*1048576),l={...e,fileSystemSnapshot:{entries:{...i.entries}}};for(let[e,t]of(eK(l,{dirPath:a,recursive:!0},()=>{}),o)){let r=eT(e);if(!r)continue;let i=eB(`${s}/${r}`);e.endsWith("/")?eK(l,{dirPath:i,recursive:!0},()=>{}):eJ(l.fileSystemSnapshot,i,t)}return i.entries=l.fileSystemSnapshot.entries,r(),{}}},e0="doubao.__webSyncBridgePersist",e1="doubao.__webSyncBridgeUpdated";r(20789),r(62839),r(66876),r(35336);let e2="doubao.getPerformanceEntries",e3="doubao.setPerformanceBufferSize",e4="doubao.onPerformanceEntries",e6="doubao.__webPerformanceTiming",e5="__WEB_PERFORMANCE_WIDGET_IDENTITY__",e8=[e2,e3,e4];class e9{entries=[];bufferSize=30;launchStart=Date.now();launched=!1;snapshot(){return{entries:this.entries.map(e=>({...e})),bufferSize:this.bufferSize}}setBufferSize(e){if("number"!=typeof e||!Number.isInteger(e)||e<1||e>1e3)throw Error("size must be between 1 and 1000");this.bufferSize=e,this.entries=this.entries.slice(-e)}reset(){this.entries=[],this.bufferSize=30,this.launchStart=Date.now(),this.launched=!1}recordTiming(e,t){if(e.completed||!o(t))return[];let r=e.timing??={};for(let e of["create_lynx_start","layout_start","layout_end","lepus_execute_start","lepus_execute_end","parseChangesEnd"]){let i=t[e];"number"==typeof i&&Number.isFinite(i)&&i>0&&(r[e]=i)}let i=e=>{let t=r[e];return"number"==typeof t&&Number.isFinite(t)&&t>0?t:void 0},n=i("create_lynx_start"),a=i("layout_start"),s=i("layout_end");if(void 0===n||void 0===a||void 0===s||s<a||a<n)return[];e.completed=!0;let l=[],d=void 0===e.pageId?{}:{path:e.path,pageId:e.pageId};if(void 0!==e.pageId){let t=!this.launched,r=Math.min(e.startTime,n);if(t){let t=Math.min(this.launchStart,r);l.push({entryType:"navigation",name:"appLaunch",startTime:t,duration:s-t,...d,navigationStart:r,navigationType:e.navigationType})}l.push({entryType:"navigation",name:"route",startTime:r,duration:s-r,...d,navigationStart:r,navigationType:e.navigationType,referrerPath:e.referrerPath,referrerPageId:e.referrerPageId}),this.launched=!0}let u=i("lepus_execute_start"),c=i("lepus_execute_end"),p=c??i("parseChangesEnd");return void 0!==u&&void 0!==c&&c>=u&&l.push({entryType:"script",name:"evaluateScript",startTime:u,duration:c-u,moduleName:e.moduleName}),(void 0!==e.pageId||void 0!==e.widgetId)&&l.push({entryType:"render",name:"firstRender",startTime:n,duration:s-n,...d,...void 0!==p&&p>=n&&p<=s?{viewLayerReadyTime:p}:{},viewLayerRenderStartTime:a,viewLayerRenderEndTime:s,...void 0===e.widgetId?{}:{widgetId:e.widgetId,widgetInstanceId:e.widgetInstanceId,isAppColdLaunch:e.isAppColdLaunch}}),this.entries=[...this.entries,...l].slice(-this.bufferSize),l}}async function e7(e,t){try{await (null==t?void 0:t(e.params))}catch{}}let te=new Map,tt={"applet.subscribeEvent":(e,t)=>{let r=o(e.params)&&"string"==typeof e.params.eventName?e.params.eventName:"";if(r){var i;null==t||null==(i=t.events)||i.subscribe(r,t)}return _(e,{})},"applet.unsubscribeEvent":(e,t)=>{let r=o(e.params)&&"string"==typeof e.params.eventName?e.params.eventName:"";if(r){var i;null==t||null==(i=t.events)||i.unsubscribe(r)}return _(e,{})}};function tr(){var e;return null==(e=globalThis.navigator)?void 0:e.clipboard}function ti(e,t){let r=tr();if(!r||"function"!=typeof r[t])throw new w(`${e} is not supported in this browser`,103);return r}function tn(e,t){let r=o(t)&&"string"==typeof t.message?t.message:String(t),i=new w(`${e} failed: ${r}`,o(t)&&("NotAllowedError"===t.name||"SecurityError"===t.name)?106:102);return i.cause=t,i}async function ta(e){let t=ti("setClipboardData","writeText");try{await t.writeText(e)}catch(e){throw tn("setClipboardData",e)}}async function ts(){let e=ti("getClipboardData","readText");try{let t=await e.readText();if("string"==typeof t)return t}catch(e){throw tn("getClipboardData",e)}throw new w("getClipboardData failed: clipboard did not return text",102)}function to(e,t,r){let i=(null==t?void 0:t.fileSystemNamespace)??eu(null==t?void 0:t.globalProps);return ev(i,async()=>{try{var n,a;let s=eb(i),l={fileSystemNamespace:i,fileSystemSnapshot:{entries:{...s.entries}},apiResults:{"doubao.getSystemInfo":{platform:null==t||null==(a=t.globalProps)||null==(n=a.os)?void 0:n.toLowerCase()}},storageSnapshot:{},supportedAPIs:[]},d=!1,u=(0,eQ[e.name])(l,o(e.params)?e.params:{},()=>{d=!0});return d?await ex(i,{fileSystemChanges:eS(s.entries,l.fileSystemSnapshot.entries),mutationId:r}):r&&e_(i,r,{}),_(e,u)}catch(e){throw r&&e_(i,r),e}})}let tl=Object.fromEntries(Object.keys(eQ).map(e=>[e,to]));async function td(e,t){var r,i;if("string"!=typeof(null==e?void 0:e.src)||!e.src)throw Error("src must be a non-empty string");let{src:n}=e,a=await new Promise((e,r)=>{let i=new Image,a=()=>{null==t||t.removeEventListener("abort",s),i.onload=i.onerror=null},s=()=>{a(),i.removeAttribute("src"),r(null==t?void 0:t.reason)};(null==t?void 0:t.aborted)?s():(null==t||t.addEventListener("abort",s,{once:!0}),i.onload=()=>{a(),e(i)},i.onerror=()=>{a(),r(Error(`failed to load image: ${n}`))},i.src=n)}),s=null==(r=n.match(/^data:image\/([^;,]+)/i))?void 0:r[1],o=null==(i=n.match(/\.([a-zA-Z0-9]+)(?:[?#].*)?$/))?void 0:i[1];return{width:a.naturalWidth||a.width,height:a.naturalHeight||a.height,orientation:"up",path:n,type:((null==s?void 0:s.split("+")[0])??o??"").toLowerCase()}}function tu(e){return{pages:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:i;return(null==e?void 0:e.getCurrentPages())??[]}(null==e?void 0:e.navigation)}}function tc(e){return async(t,r)=>{let i=t.params;if(!i||"string"!=typeof i.url||!i.url.trim())return S(t,"invalid url",104);try{return await e(i,null==r?void 0:r.navigation)?_(t,{}):S(t,"No active Runtime to navigate",102)}catch(e){return S(t,x(e),e instanceof w?e.errNo:102)}}}let tp={"doubao.openPage":async(e,t)=>{var r;let i=e.params;if(!i||"string"!=typeof i.url||!i.url.trim()||void 0!==i.mode&&!["push","replace","navigate","pop_to"].includes(i.mode))return S(e,"url and mode must describe a valid page route",104);if(!(null==t||null==(r=t.navigation)?void 0:r.openPage))return S(e,"No active Runtime to open page",102);try{return await t.navigation.openPage(i),_(e,{})}catch(t){return S(e,x(t),t instanceof w?t.errNo:102)}},"doubao.enableAlertBeforeUnload":(e,t)=>{var r;let i=null==(r=e.params)?void 0:r.message;return"string"!=typeof i?S(e,"message must be a string",104):th(e,i,t)},"doubao.disableAlertBeforeUnload":(e,t)=>th(e,void 0,t),"doubao.getCurrentPages":{handler:(e,t)=>_(e,tu(t)),syncResult:tu},"doubao.navigateTo":tc(T),"doubao.redirectTo":tc(A),"doubao.reLaunch":tc(M),"doubao.navigateBack":(e,t)=>!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i;return(null==t?void 0:t.navigateBack(e))??!1}(e.params??{},null==t?void 0:t.navigation)?S(e,"No pages in back stack",102):_(e,{}),"doubao.exitApp":(e,t)=>!function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:i;return null==e||e.exitApp(),!!e}(null==t?void 0:t.navigation)?S(e,"No active Runtime to exit app",102):_(e,{})};function th(e,t,r){var i;return(null==r?void 0:r.containerType)==="PAGE"&&(null==(i=r.navigation)?void 0:i.setAlertBeforeUnload)?r.navigation.setAlertBeforeUnload(t,r.element)?_(e,{}):S(e,"not found page",102):S(e,"alert before unload is only supported in page container",103)}let tm=Object.fromEntries(["setStorage","getStorage","removeStorage","clearStorage","getStorageInfo"].map(e=>[`doubao.${e}`,async(t,r)=>{let i=(null==r?void 0:r.fileSystemNamespace)??eu(null==r?void 0:r.globalProps);return ev(i,async()=>{var r,n;let a=o(t.params)?t.params:{},s=ey(i).storageSnapshot,l={};switch(e){case"setStorage":{let e,t;if("string"!=typeof a.data)throw Error("data must be a serialized string");let o=(r=a.key,n=a.data,e=et(r),er(n),t=Object.prototype.hasOwnProperty.call(s,e)?s[e]:void 0,ea(en(s)-(void 0===t?0:ei(t))+ei(n)),e);await ex(i,{storageChanges:{[o]:a.data}});break}case"getStorage":let d;l={data:Object.hasOwn(s,d=et(a.key))?s[d]:void 0};break;case"removeStorage":await ex(i,{storageChanges:{[et(a.key)]:null}});break;case"clearStorage":await ex(i,{clearStorage:!0});break;case"getStorageInfo":l={keys:Object.keys(s),currentSize:Math.ceil(en(s)/1024),limitSize:10240}}return _(t,l)})}])),tg={...{"doubao.getClipboardData":{canIUse:()=>{var e;return"function"==typeof(null==(e=tr())?void 0:e.readText)},handler:async e=>_(e,{data:await ts()})},"doubao.setClipboardData":{canIUse:()=>{var e;return"function"==typeof(null==(e=tr())?void 0:e.writeText)},handler:async e=>{let{data:t}=function(e){if(!o(e)||"string"!=typeof e.data)throw new w("data must be a string",104);return{data:e.data}}(e.params);return await ta(t),_(e,{})}}},...tt,...tl,...{"doubao.getImageInfo":async e=>_(e,await td(e.params))},...tp,...tm,...{[e0]:async(e,t)=>{let r=o(e.params)?e.params:{},i=null==t?void 0:t.fileSystemNamespace;if(!i||r.fileSystemNamespace!==i)throw Error("Storage scope does not match the calling application");let n="string"==typeof r.mutationId?r.mutationId:void 0;if(void 0!==r.fileSystemOperation){let i=r.fileSystemOperation;if(!o(i)||"string"!=typeof i.name||!Object.hasOwn(eQ,i.name)||!o(i.params))throw Error("Invalid synchronous file operation");return to({...e,name:i.name,params:i.params},t,n)}let a={storageChanges:o(r.storageChanges)?r.storageChanges:void 0,clearStorage:!0===r.clearStorage,fileSystemChanges:o(r.fileSystemChanges)?r.fileSystemChanges:void 0,mutationId:n};return await ev(i,async()=>{try{await ex(i,a)}catch(e){throw e_(i,a.mutationId),e}}),_(e,{})}},...{"doubao.canIUse":{handler:(e,t)=>{let{schema:r}=e.params;return _(e,{result:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:E;return t.canIUse(e,{apiRegistry:t})}(r,null==t?void 0:t.apiRegistry)})}},"doubao.getAccountInfo":{handler:(e,t)=>{var r;return _(e,X(null==t||null==(r=t.navigation)?void 0:r.getPackageInfo(),null==t?void 0:t.globalProps))},syncResult:e=>X(Y(e),null==e?void 0:e.globalProps)},"doubao.getPackageInfo":{handler:(e,t)=>{var r;return _(e,B(null==t||null==(r=t.navigation)?void 0:r.getPackageInfo()))},syncResult:e=>B(Y(e))},"doubao.getAppBaseInfo":{handler:(e,t)=>_(e,Z(null==t?void 0:t.globalProps)),syncResult:e=>Z(null==e?void 0:e.globalProps)},"doubao.getMenuButtonBoundingClientRect":{handler:(e,t)=>_(e,R(null==t?void 0:t.globalProps)),syncResult:e=>R(null==e?void 0:e.globalProps)},"doubao.getSystemInfo":{handler:(e,t)=>_(e,J(null==t?void 0:t.globalProps)),syncResult:e=>J(null==e?void 0:e.globalProps)},"doubao.getWindowInfo":{handler:(e,t)=>_(e,F(null==t?void 0:t.globalProps)),syncResult:e=>F(null==e?void 0:e.globalProps)},"doubao.getDeviceInfo":{handler:(e,t)=>_(e,V(null==t?void 0:t.globalProps)),syncResult:e=>V(null==e?void 0:e.globalProps)},"doubao.getNetworkType":{handler:e=>_(e,K()),syncResult:K}}};E.registerMany(tg,{override:!0}),E.registerEventSources({onThemeChange:e=>{let t=matchMedia("(prefers-color-scheme: dark)"),r=()=>e({appTheme:matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"});return t.addEventListener("change",r),()=>t.removeEventListener("change",r)}},{override:!0});class tf{router;navigation;onEmpty;runtime;callers=new Map;destroyed=!1;performance=new e9;applicationLifecycle=new AbortController;nextPerformancePageId=Math.floor(1e12*Math.random());eventKey=Symbol("application events");applicationEvents;applicationEventKey;unsubscribeStorage;getApplicationEvents(){var e,t,r;let i=(null==(e=this.runtime)?void 0:e.getFileSystemNamespace())??this.eventKey;if(this.applicationEventKey!==i){let e,n;null==(t=this.applicationEvents)||t.release(),this.applicationEventKey=i,this.applicationEvents=(r=e=>{for(let t of this.callers.values())t.events.isSubscribed(e.name)&&t.send(e)},e=te.get(i)??{receivers:new Set,recent:[]},te.set(i,e),e.receivers.add(r),n=()=>{let t=Date.now();e.recent=e.recent.filter(e=>1e4>=Math.abs(t-e.timestamp))},{publish(t){for(let r of(n(),e.recent.push({message:t,timestamp:t.timestamp??Date.now()}),[...e.receivers]))r(t)},replay(t,r,i){for(let a of(n(),e.recent))a.message.name===t&&a.timestamp>=r&&i(a.message)},release(){e.receivers.delete(r),0===e.receivers.size&&te.delete(i)}})}return this.applicationEvents}constructor(e,t,r,i){this.router=e,this.navigation=t,this.onEmpty=r,this.runtime=i}get apiRegistry(){var e;return(null==(e=this.runtime)?void 0:e.apiRegistry)??E}register(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:()=>{},t=arguments.length>1?arguments[1]:void 0,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(this.destroyed)throw Error("RuntimeBridge was destroyed");let i=Symbol("caller");this.getApplicationEvents();let n=(null==t?void 0:t.apiRegistry)??this.apiRegistry;this.unsubscribeStorage??=ew(e=>{for(let t of this.callers.values())t.fileSystemNamespace===e.fileSystemNamespace&&t.events.emitPrivate(e1,e)});let a=n.createEventController((t,r)=>{e({type:"event",name:t,params:r,timestamp:Date.now()})});return this.callers.set(i,{abortController:new AbortController,send:e,options:t,events:a,main:r}),i}resolveStorageNamespace(e,t,r){var i,n,a;return(null==(i=this.runtime)?void 0:i.getFileSystemNamespace())??(null==(n=e.options)?void 0:n.fileSystemNamespace)??r??eu(t,null==(a=e.options)?void 0:a.userId)}async prepareStorage(e,t,r){let i=this.getCaller(e),n=this.resolveStorageNamespace(i,t,r);if(i.fileSystemNamespace!==n){var a;null==(a=i.storage)||a.release(),i.storage=void 0,i.fileSystemNamespace=n}i.storage??=ef(n),await i.storage.ready}createSyncBridgeData(e,t,r){var i;let n=this.getCaller(e),a=function(e,t){var r;let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:eu(e),n=arguments.length>3?arguments[3]:void 0,a=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:E;return e.getSupportedNames({apiRegistry:e})}(t);return{hostFileSystem:Object.keys(eQ).every(r=>null==t?void 0:t.canIUse(r,{globalProps:e})),fileSystemNamespace:i,...ey(i),hostStorage:!!(null==t?void 0:t.canIUse("doubao.setStorage",{globalProps:e})),apiResults:(r=null==e?void 0:e.packageInfo,(t??E).getSyncResults({globalProps:e,navigation:n,packageInfo:r})),supportedAPIs:a}}(t,(null==(i=n.options)?void 0:i.apiRegistry)??this.apiRegistry,this.resolveStorageNamespace(n,t,r),this.navigation);return a.performance=this.performance.snapshot(),n.fileSystemNamespace=a.fileSystemNamespace,a.supportedAPIs.push(...e8,e1),a}beginPerformance(e,t){var r,i,n;let a=this.getCaller(e),s=t.globalProps??{},l=o(s.__VIEW_CONTEXT__)?s.__VIEW_CONTEXT__:{},d=o(s[e5])?s[e5]:l,u="PAGE"===t.containerType,c=null==(i=this.navigation)||null==(r=i.getCurrentPages().at(-2))?void 0:r.route.split("?")[0],p=null==(n=[...this.callers.values()].findLast(e=>{var t;return(null==(t=e.performanceTrace)?void 0:t.path)===c}))?void 0:n.performanceTrace;a.performanceTrace={startTime:Date.now(),moduleName:`${t.resourceUrl}#main-thread`,...u?{path:"string"==typeof l.pageUrl?l.pageUrl:String(s.__LOCATION__??"").split("?")[0],pageId:++this.nextPerformancePageId,navigationType:s.__WEB_NAVIGATION_TYPE__??"openPage",referrerPath:null==p?void 0:p.path,referrerPageId:null==p?void 0:p.pageId}:"WIDGET"===t.containerType?{widgetId:"string"==typeof d.widgetId?d.widgetId:void 0,widgetInstanceId:"string"==typeof d.widgetInstanceId?d.widgetInstanceId:void 0,isAppColdLaunch:![...this.callers.values()].some(e=>{var t;return null==(t=e.performanceTrace)?void 0:t.completed})}:{}}}resetApplication(){this.applicationLifecycle.abort(),this.applicationLifecycle=new AbortController,this.performance.reset()}publishPerformance(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];for(let t of this.callers.values())t.events.emitPrivate(e1,{performance:this.performance.snapshot()}),e.length&&t.events.emit(e4,{entries:e})}getCaller(e){let t=this.callers.get(e);if(!t)throw Error("Caller was detached from the RuntimeBridge");return t}async handleMessage(e,t,r){var i;let n=this.getCaller(e);if(!v(t))return{routed:!1};if("applet.subscribeEvent"===t.name||"applet.unsubscribeEvent"===t.name){let e=o(t.params)?t.params:{},i="string"==typeof e.eventName?e.eventName:"",a="applet.subscribeEvent"===t.name&&!n.events.isSubscribed(i);if(tt[t.name](t,{...r,events:n.events}),"applet.subscribeEvent"===t.name&&i===e1&&(null==r?void 0:r.environment)!=="sandbox"){let e=this.resolveStorageNamespace(n,null==r?void 0:r.globalProps,n.fileSystemNamespace??(null==r?void 0:r.fileSystemNamespace));n.events.emitPrivate(i,{performance:this.performance.snapshot(),fileSystemNamespace:e,...ey(e)})}return a&&i&&"number"==typeof e.timestamp&&this.getApplicationEvents().replay(i,e.timestamp,n.send),{routed:!1}}return(null==(i=t.target)?void 0:i.scope)!=="main"||"self"!==t.target.target||!this.router||n.main?{routed:!1}:this.router.call(e,t)}async dispatch(e,t,r,i,n){var a,s,l;let d=arguments.length>5&&void 0!==arguments[5]?arguments[5]:"inline",u=this.callers.get(e);if(!u)return;let c=u.options,p={containerType:n.containerType,element:n.element},h="AppletBridgeModule"===i&&"postMessage"===t;if(h){let e=function(e,t){var r,i;if(!("object"!=typeof(r=e)||null===r||Array.isArray(r))&&"event"===r.type&&"doubao.__widgetInteraction"===r.name&&!("object"!=typeof(i=r.params)||null===i||Array.isArray(i))&&"tap"===i.type&&Number.isSafeInteger(i.sequence)&&"number"==typeof i.sequence&&i.sequence>0)return e7(e,t)}(r,null==c?void 0:c.onWidgetInteraction);if(e)return await e}let m=await this.handleMessage(e,r,n);if(m.routed)return await m.result;let g=await (null==c||null==(a=c.appletSessionMessageHandler)?void 0:a.call(c,r,p));if(null==g?void 0:g.routed)return await g.result;"iframe"!==d&&h&&b(r)&&"__bridge_ready__"===r.name&&(null==c||null==(s=c.onReady)||s.call(c));let f=h&&y(r),w="inline"===d&&"sandbox"!==n.environment;if(f&&w&&"TOOL"!==n.containerType)return u.send(r),r;let S=r=>("iframe"!==d&&"postMessage"===t&&y(r)&&this.callers.get(e)===u&&u.send(r),r);try{if(h&&v(r)&&"sandbox"!==n.environment){let e=o(r.params)?r.params:{};if(r.name===e6){let t=u.performanceTrace?this.performance.recordTiming(u.performanceTrace,e.timing):[];return t.length&&this.publishPerformance(t),S(_(r,{}))}if(r.name===e2)return S(_(r,{entries:(l=this.performance.snapshot(),l.entries.filter(t=>(void 0===e.entryType||t.entryType===e.entryType)&&(void 0===e.name||t.name===e.name)).map(e=>({...e})))}));if(r.name===e3)return this.performance.setBufferSize(e.size),this.publishPerformance(),S(_(r,{}));if("doubao.canIUse"===r.name&&e8.includes(String(e.schema)))return S(_(r,{result:!0}))}let a=this.runtime?this.runtime.nativeModulesCallHandler:null==c?void 0:c.nativeModulesCallHandler,s=await (null==a?void 0:a(t,r,i,p));if(void 0===s&&h&&b(r)&&"__bridge_ready__"!==r.name){this.callers.get(e)===u&&this.getApplicationEvents().publish(r);return}if(f){let e=void 0===s?r:s;if("sandbox"===n.environment||void 0===s&&w)return S(e);return e}let d=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0,r=e.apiRegistry??E;return(i,n,a)=>{if(("AppletJSModule"!==a||"log"!==i)&&"AppletBridgeModule"===a&&"postMessage"===i)return r.dispatch(n,e,t)}}({...n,signal:u.abortController.signal,getAppletContext:null==c?void 0:c.getAppletContext,applicationLifecycle:this.runtime?{owner:this.applicationLifecycle,signal:this.applicationLifecycle.signal}:void 0,fileSystemNamespace:this.resolveStorageNamespace(u,n.globalProps,u.fileSystemNamespace??n.fileSystemNamespace),navigation:this.navigation,apiRegistry:(null==c?void 0:c.apiRegistry)??this.apiRegistry,events:u.events,emitEvent:(e,t)=>u.events.emit(e,t)},null==c?void 0:c.onUnsupportedAPI),m=void 0===s?await d(t,r,i):s;if(h&&v(r)&&r.name===e0&&y(m)&&o(m.params)&&1!==m.params.code){let e=["Synchronous API persistence failed",m.params];a?await a("log",{level:"error",args:e},"AppletJSModule",p):console.error(...e)}return S(m)}catch(e){if("iframe"===d)throw e;return S(v(r)?I(r,e):void 0)}}handleMainBridgeMessage(e){var t;return!this.destroyed&&(null!=(t=this.router)&&!!t.handleMainBridgeMessage(e)||!!b(e)&&"__bridge_ready__"!==e.name&&(this.getApplicationEvents().publish(e),!0))}setVisible(e,t){var r;null==(r=this.callers.get(e))||r.events.setVisible(t)}unregister(e){var t,r,i,n;let a=this.callers.get(e);a&&(this.callers.delete(e),null==(t=a.storage)||t.release(),this.callers.size||(null==(i=this.unsubscribeStorage)||i.call(this),this.unsubscribeStorage=void 0),a.abortController.abort(),a.events.destroy(),null==(r=this.router)||r.cancel(e),a.main||this.destroyed||[...this.callers.values()].some(e=>!e.main)||null==(n=this.onEmpty)||n.call(this))}fail(e){var t;null==(t=this.router)||t.fail(e)}destroy(){var e,t;if(!this.destroyed)for(let r of(this.destroyed=!0,null==(e=this.applicationEvents)||e.release(),this.applicationEvents=void 0,this.applicationLifecycle.abort(),null==(t=this.router)||t.destroy(),this.callers.keys()))this.unregister(r)}}let tv=/(?:^|[.-])[a-f\d]{8,}(?=[.-]|$)/i;function ty(e){let t=new URL(e),r=t.pathname.slice(t.pathname.lastIndexOf("/")+1),i=j();return i&&!tv.test(r)&&t.searchParams.set("__doubao_resource_reload",i),t.href}function tb(e){return"localhost"===e||"::1"===e||/^127(?:\.\d{1,3}){3}$/.test(e)}function tw(e){if(!e.resourceUrl)throw Error("Container.render requires a resourceUrl");return e.resourceUrl}function t_(e){return e.containerType??"PAGE"}function tS(e){return"WIDGET"===e?"content":"fill"}function tx(e){if("function"==typeof CustomEvent)return new CustomEvent("error",{detail:{error:e}});let t=new Event("error");return Object.defineProperty(t,"detail",{value:{error:e}}),t}class tI{container;options;sandboxUrl;targetOrigin;bridge=null;caller;connected=!1;failed=!1;handshakeTimer=null;loaded=!1;loadCount=0;port=null;preparedForRender=!1;preparedContainerType=null;renderMessage=null;view=null;constructor(e){let t=new URL(e.sandboxUrl??"https://apps-web-sdk-sandbox.doubaocdn.com/sandbox");if("https:"!==t.protocol&&!("http:"===t.protocol&&tb(t.hostname)))throw Error("iframe isolation url must use HTTPS (HTTP is only allowed on localhost)");this.container=e.container,this.options=e,this.sandboxUrl=ty(t),this.targetOrigin=t.origin}get element(){return this.view}prepare(e){this.clear();try{this.createView(e),this.preparedForRender=!0}catch(e){throw this.clear(),e}}createView(e){var t,r;if(new URL((null==(t=globalThis.location)?void 0:t.href)??"http://localhost/").origin===this.targetOrigin)return this.abortRender(Error("iframe isolation requires a cross-origin sandbox URL"));if(this.view)return this.preparedContainerType!==e?this.abortRender(Error("iframe container type cannot change after preparation")):this.view;let i=document.createElement("iframe");i.className=this.options.className??"doubao-web-container-view",i.dataset.containerType=e,i.dataset.webSizing=tS(e),i.referrerPolicy="no-referrer",i.title="Doubao app content",i.sandbox.add("allow-scripts","allow-same-origin");let n=tb((null==(r=globalThis.location)?void 0:r.hostname)??"");return n&&i.setAttribute("credentialless",""),i.setAttribute("allow",n?"picture-in-picture 'none'; local-network-access 'src'; loopback-network 'src'":"picture-in-picture 'none'"),i.src=this.sandboxUrl,i.style.display="APP"===e||"TOOL"===e?"none":"block",i.style.border="0",i.style.width="100%",i.style.height="WIDGET"===e?"0px":"100%",i.addEventListener("load",()=>this.handleLoad()),this.view=i,this.preparedContainerType=e,this.container.replaceChildren(i),i}render(e){var t;this.preparedForRender||this.clear(),this.preparedForRender=!1;let r=t_(e),i=new URL(tw(e),document.baseURI).href,n=e.initData??{},a={...G(),...e.globalProps??{}};this.bridge=e.bridge??(null==(t=this.options.runtime)?void 0:t.bridge)??new tf,this.caller=e.bridgeCaller??this.bridge.register(e=>this.sendBridgeMessage(e),e.bridge||this.options.runtime?{...this.options,apiRegistry:void 0}:this.options,"APP"===r);let s=this.bridge,o=this.caller;try{let t=this.createView(r);return s.prepareStorage(o,a,this.options.fileSystemNamespace).then(()=>{var t,l,d;if(this.caller!==o)return;s.beginPerformance(o,{...e,containerType:r,globalProps:a});let u=s.createSyncBridgeData(o,a,this.options.fileSystemNamespace);this.renderMessage={type:"render",captureWidgetTap:this.options.captureWidgetTap,resourceUrl:i,resourceRoot:(null==(t=e.applicationPackage)?void 0:t.resourceRoot)??(null==(d=this.options.runtime)||null==(l=d.packageInfo)?void 0:l.resourceRoot),containerType:r,initData:n,globalProps:a,syncBridgeData:u},this.connected?this.postOrFail(this.renderMessage):this.loaded&&this.connect()}).catch(e=>{this.caller===o&&this.fail(e instanceof Error?e:Error(String(e)))}),t}catch(e){throw this.clear(),e}}clear(){var e,t;this.connected&&this.post({type:"dispose"}),this.destroyChannel(),this.caller&&(null==(t=this.bridge)||t.unregister(this.caller)),this.caller=void 0,this.bridge=null,null==(e=this.view)||e.remove(),this.view=null,this.preparedContainerType=null,this.renderMessage=null,this.connected=!1,this.failed=!1,this.loaded=!1,this.loadCount=0,this.preparedForRender=!1,this.container.replaceChildren()}setVisible(e){if(this.caller){var t;null==(t=this.bridge)||t.setVisible(this.caller,e)}}sendEvent(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.postOrFail({type:"global-event",name:e,params:t})}sendBridgeMessage(e){this.postOrFail({type:"bridge-message",message:e})}sendGlobalEvent(e,t){this.postOrFail({type:"raw-global-event",name:e,params:t})}updateData(e){this.renderMessage&&(this.renderMessage.initData=e),this.postOrFail({type:"update-data",data:e})}updateGlobalProps(e){this.renderMessage&&(this.renderMessage.globalProps={...this.renderMessage.globalProps,...e}),this.postOrFail({type:"update-global-props",props:e})}reload(){this.post({type:"reload"})}abortRender(e){var t,r;throw null==(t=(r=this.options).onError)||t.call(r,e,tx(e)),e}handleLoad(){this.failed||!this.view||((this.loadCount+=1,this.loadCount>1)?this.fail(Error("iframe navigated after the sandbox runtime loaded")):(this.loaded=!0,this.renderMessage&&this.connect()))}connect(){if(this.failed||!this.view||this.connected||this.port)return;let e=new MessageChannel;this.port=e.port1,e.port1.onmessage=e=>this.handleMessage(e),e.port1.onmessageerror=e=>this.fail(Error("iframe message could not be decoded"),e),e.port1.start(),this.handshakeTimer=setTimeout(()=>this.fail(Error("iframe sandbox handshake timed out")),1e4);let t={type:"doubao-web-sdk:connect",protocolVersion:1,sdkVersion:j()??""};try{var r;null==(r=this.view.contentWindow)||r.postMessage(t,this.targetOrigin,[e.port2])}catch(e){this.fail(e instanceof Error?e:Error(String(e)))}}handleMessage(e){var t,r,i;if(!e.data||"object"!=typeof e.data)return void this.fail(Error("iframe sandbox sent an invalid protocol message"),e);let n=e.data;if(!this.connected)return"connected"!==n.type||1!==n.protocolVersion?void this.fail(Error("iframe sandbox protocol version mismatch"),e):(this.connected=!0,this.clearHandshakeTimer(),void(this.renderMessage&&this.postOrFail(this.renderMessage)));switch(n.type){case"ready":null==(t=(r=this.options).onReady)||t.call(r);break;case"error":this.fail(Error(n.message),e);break;case"resize":(null==(i=this.renderMessage)?void 0:i.containerType)!=="WIDGET"||!Number.isFinite(n.height)||n.height<0?this.fail(Error("only Widget containers may resize the iframe"),e):this.view&&(this.view.style.height=`${n.height}px`,this.view.height=String(n.height));break;case"native-call":!Number.isSafeInteger(n.requestId)||n.requestId<=0||("AppletBridgeModule"!==n.moduleName||"postMessage"!==n.name)&&("AppletJSModule"!==n.moduleName&&"LynxConsoleModule"!==n.moduleName&&"Console"!==n.moduleName||"log"!==n.name)?this.fail(Error("iframe sandbox sent an invalid bridge call"),e):this.handleNativeCall(n);break;case"connected":this.fail(Error("iframe sandbox connected more than once"),e);break;default:this.fail(Error("iframe sandbox sent an invalid protocol message"),e)}}async handleNativeCall(e){let t;if(!this.renderMessage||!this.view)return;let r=this.bridge,i=this.caller;if(r&&i){try{t=await r.dispatch(i,e.name,e.data,e.moduleName,{containerType:this.renderMessage.containerType,element:this.view,globalProps:this.renderMessage.globalProps,fileSystemNamespace:this.renderMessage.syncBridgeData.fileSystemNamespace},"iframe")}catch(t){if(this.bridge!==r||this.caller!==i)return;this.postOrFail({type:"bridge-result",requestId:e.requestId,error:x(t)});return}this.bridge===r&&this.caller===i&&this.postOrFail({type:"bridge-result",requestId:e.requestId,result:t})}}post(e){this.connected&&this.port&&this.port.postMessage(e)}postOrFail(e){try{this.post(e)}catch(e){this.fail(e instanceof Error?e:Error(String(e)))}}fail(e){var t,r,i,n;let a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tx(e);this.failed||(this.failed=!0,this.destroyChannel(),this.caller&&(null==(n=this.bridge)||n.unregister(this.caller)),this.caller=void 0,this.bridge=null,null==(t=this.view)||t.remove(),this.view=null,this.renderMessage=null,null==(r=(i=this.options).onError)||r.call(i,e,a))}clearHandshakeTimer(){null!==this.handshakeTimer&&clearTimeout(this.handshakeTimer),this.handshakeTimer=null}destroyChannel(){var e;this.clearHandshakeTimer(),null==(e=this.port)||e.close(),this.port=null,this.connected=!1}}let tk={mode:"iframe",createContainer:e=>new tI(e)};function tC(){var e;return(null==(e=globalThis.location)?void 0:e.href)??"http://localhost/"}function tE(e){return new URL(e,tC()).toString()}function tN(e,t){if(!t)return e;let r=new URL(e,tC());return r.searchParams.set("__doubao_resource_reload",t),r.toString()}class tT{options;packages=new Map;resolveManifestUrl;resourceUrlVersion;constructor(e={}){this.options=e,this.resolveManifestUrl=e.resolveManifestUrl,this.resourceUrlVersion=e.resourceUrlVersion}configure(e){e.resolveManifestUrl&&(this.resolveManifestUrl=e.resolveManifestUrl),"resourceUrlVersion"in e&&(this.resourceUrlVersion=e.resourceUrlVersion)}async getPackageSource(e){if(arguments.length>1&&void 0!==arguments[1]&&arguments[1],!this.resolveManifestUrl)throw Error("PackageManager requires resolveManifestUrl");return{manifestUrl:await this.resolveManifestUrl({appId:e})}}cached(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};r.signal&&g(r.signal);let i=this.packages.get(e);return(!i||r.forceReload)&&(i=t(),this.packages.set(e,i),i.catch(()=>{this.packages.get(e)===i&&this.packages.delete(e)})),r.signal?f(()=>i,r.signal):i}async fetchPackage(e,t){return{manifestUrl:e,resourceRoot:t,manifest:await p(e,{fetcher:this.options.fetcher})}}async loadPackage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t.signal&&g(t.signal);let{manifestUrl:r,resourceRoot:i}=await this.getPackageSource(e,t),n=tE(r),a=await this.cached(n,()=>this.fetchPackage(n,i),t);if(e&&a.manifest.appId&&a.manifest.appId!==e)throw Error("Resolved package appId must match the requested application");return a}resolveWidget(e,t){let r=this.tryResolveWidgetFromPackage(e,t),i=e.manifest.appRuntimeEntry?h(e.manifestUrl,e.manifest.appRuntimeEntry):void 0;return{packageInfo:e,appId:e.manifest.appId,appName:(null==r?void 0:r.appName)??e.manifest.name,icon:(null==r?void 0:r.iconSrc)??e.manifest.iconSrc,appRuntimeEntry:i?tN(i,e.resourceUrlVersion??this.resourceUrlVersion):void 0,resourceUrl:(null==r?void 0:r.resourceUrl)??"",titleType:null==r?void 0:r.entry.titleType,boxType:null==r?void 0:r.entry.boxType}}preload(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.loadPackage(e,t)}setPackage(e){this.packages.set(tE(e.manifestUrl),Promise.resolve(e))}deletePackage(e){this.packages.delete(tE(e))}clearPackageCache(e){e?this.deletePackage(e):this.packages.clear()}resolveWidgetEntry(e,t){let r=e.manifest.name??t.name,i=h(e.manifestUrl,t);return{appId:e.manifest.appId,entry:t,iconSrc:e.manifest.iconSrc??u(t.icons),appName:r,resourceUrl:i?tN(i,e.resourceUrlVersion??this.resourceUrlVersion):void 0}}tryResolveWidgetFromPackage(e,t){let r=e.manifest.getOptionalWidgetEntry(t);if(r)return this.resolveWidgetEntry(e,r)}}class tA{send;ready;pendingCalls=new Map;destroyed=!1;nextCallbackId=1e6;constructor(e,t){this.send=e,this.ready=t}call(e,t){if(this.destroyed)return Promise.reject(Error("RuntimeRouter was destroyed"));let r=this.nextCallbackId++,i={...t,callbackId:r};return new Promise((n,a)=>{this.pendingCalls.set(r,{callbackId:t.callbackId,reject:a,resolve:n,caller:e}),(async()=>{try{await this.ready(),this.pendingCalls.has(r)&&this.send(i)}catch(t){let e=this.pendingCalls.get(r);if(!e)return;this.pendingCalls.delete(r),e.reject(t instanceof Error?t:Error(String(t)))}})()})}handleMainBridgeMessage(e){if(y(e)){let t=this.pendingCalls.get(e.callbackId);return!!t&&(this.pendingCalls.delete(e.callbackId),t.resolve({routed:!0,result:{...e,callbackId:t.callbackId}}),!0)}return!1}cancel(e){for(let[t,r]of this.pendingCalls)r.caller===e&&(this.pendingCalls.delete(t),r.reject(Error("Caller was detached from the RuntimeBridge")))}destroy(){this.destroyed||(this.destroyed=!0,this.fail(Error("RuntimeRouter was destroyed")))}fail(e){for(let t of this.pendingCalls.values())t.reject(e);this.pendingCalls.clear()}}let tM="onBackground",tj="onDestroy",tR="onForeground",tP="onHide",tL="onShow";function tD(e,t){let r=function(e){let{pageId:t,viewData:r}=function(e){if(!e)throw Error("route url must be a non-empty string");let t=e.indexOf("?"),r=-1===t?e:e.slice(0,t);if(!r)throw Error("route url must include a page path");let i={};return new URLSearchParams(-1===t?"":e.slice(t+1)).forEach((e,t)=>{i[t]=e}),{pageId:r,viewData:i}}(e.url),i=JSON.stringify(r);return{pageId:t,initData:{viewData:r,viewContext:{}},globalProps:{__LOCATION__:e.url,__RENDER_DATA__:i,__VIEW_CONTEXT__:{}}}}(e);return{...r,entry:t.getPageEntry(r.pageId)}}function tO(e,t){var r;let i=Object.entries((null==(r=t.initData)?void 0:r.viewData)??{}).map(e=>{let[t,r]=e;return`${encodeURIComponent(t)}=${encodeURIComponent(r)}`}).join("&");return{route:`${e}${i?`?${i}`:""}`}}function tU(e,t){return{packageInfo:t,...e}}function t$(e){return{appId:e.appId,name:e.name,iconSrc:e.iconSrc,versionName:e.versionName}}function tq(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return tU(t,t$(e))}function tB(e){if(o(e))return{...e};if("string"!=typeof e)return{};try{let t=JSON.parse(e);return o(t)?t:{}}catch{return{}}}class tF{pageHost;visible=!0;className;onError;appGlobalProps;appInitData;getRuntimeGlobalProps;configuredFileSystemNamespace;userId;runtimeKernel;packageSnapshot;packageLoading;packageSource;lifecycle=new AbortController;get packageInfo(){if(this.destroyed)throw Error("Runtime was destroyed");if(!this.packageSnapshot)throw Error("Runtime package is not loaded");return this.packageSnapshot}get manifest(){return this.packageInfo.manifest}get manifestUrl(){return this.packageInfo.manifestUrl}pageCapsule;resolvedFileSystemNamespace;appRuntime=null;appStart=null;bridge;packageManager;sandboxUrl;viewContext;appGroupId;destroyed=!1;pendingAppEvents=[];clearingAppRuntime=!1;appCallController=new AbortController;apiContextOwner={};stack=[];pendingPages=[];nextPageIndex=0;constructor(e,t=tk,r){this.sandboxUrl=e.sandboxUrl,this.packageManager=e.packageManager??new tT({resolveManifestUrl:()=>this.manifestUrl});let i=new tA(e=>this.sendAppBridgeMessage(e),async()=>{if(await this.ensureAppRuntime(),!this.appStart)throw Error("No Web entry configured for app runtime");return this.appStart.promise});this.appGroupId=e.appGroupId,this.viewContext=e.viewContext,this.pageHost=e.pageHost,this.runtimeKernel=t,"manifest"in e?(this.packageSnapshot={manifest:e.manifest,manifestUrl:String(e.manifestUrl),resourceRoot:e.resourceRoot,resourceUrlVersion:""},e.packageManager||this.packageManager.setPackage(this.packageSnapshot)):this.packageSource=e,this.pageCapsule=e.pageCapsule,this.className=e.className,this.onError=e.onError,this.appGlobalProps=e.appGlobalProps,this.appInitData=e.appInitData,this.getRuntimeGlobalProps=e.getRuntimeGlobalProps,this.configuredFileSystemNamespace=e.fileSystemNamespace,this.userId=e.userId,this.resolvedFileSystemNamespace=this.resolveFileSystemNamespace(),this.updateEmptyState(),this.bridge=new tf(i,{getCurrentPages:()=>this.getCurrentPages(),getPackageInfo:()=>this.getPackageInfo(),navigateTo:e=>this.navigateToBridgePage(e),openPage:e=>this.openBridgePage(e),redirectTo:e=>this.redirectToBridgePage(e),reLaunch:e=>this.reLaunchBridgePage(e),navigateBack:e=>this.requestBack(e),setAlertBeforeUnload:(e,t)=>{let r=this.stack.find(e=>e.element===t);return!!r&&(r.alertBeforeUnloadMessage=e,!0)},exitApp:()=>this.exitBridgeApp()},r,{apiRegistry:e.apiRegistry,getFileSystemNamespace:()=>this.fileSystemNamespace,nativeModulesCallHandler:e.nativeModulesCallHandler})}async loadPackage(){var e,t;if(this.destroyed)throw new DOMException("Runtime was destroyed","AbortError");let r=(null==(e=this.packageSource)?void 0:e.signal)?AbortSignal.any([this.lifecycle.signal,this.packageSource.signal]):this.lifecycle.signal;if(!this.packageSnapshot){if(!this.packageLoading){let e=this.packageSource,i=this.packageManager.loadPackage(e.appId,{signal:r,versionTag:e.versionTag??(null==(t=e.viewContext)?void 0:t.versionTag)}).then(e=>{g(r),this.destroyed||this.packageSnapshot||(this.packageSnapshot={...e,resourceUrlVersion:""},this.resolvedFileSystemNamespace=this.resolveFileSystemNamespace())}).catch(e=>{throw this.packageLoading===i&&(this.packageLoading=void 0),e});this.packageLoading=i}let e=this.packageLoading;await f(()=>e,r)}return g(r),this.packageInfo}get fileSystemNamespace(){return this.resolvedFileSystemNamespace}get isDestroyed(){return this.destroyed}get pages(){return this.stack.map(e=>this.toStackEntry(e))}get currentPage(){let e=this.getCurrentStackItem();return e?this.toStackEntry(e):null}setManifest(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.manifestUrl;this.clear(),this.packageSnapshot={...this.packageSnapshot,manifest:e,manifestUrl:String(r),resourceUrlVersion:(null==(t=this.packageSnapshot)?void 0:t.resourceUrlVersion)??"1"},this.packageManager.setPackage(this.packageSnapshot),this.resolvedFileSystemNamespace=this.resolveFileSystemNamespace()}async pushPage(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.packageSnapshot||await this.loadPackage(),this.pushLoadedPage(e)}async pushLoadedPage(e,t){var r,i,n;let a;if(this.destroyed)throw Error("Runtime was destroyed");if(!this.pageHost)throw Error("Opening Pages requires a Runtime pageHost");let s=this.resolvePageEntry(e),l=h(this.manifestUrl,s);if(!l)throw Error(`No Web entry configured for page entry: ${s.id}`);let d=this.lifecycle.signal;if(this.startAppRuntime(),this.appStart&&await this.appStart.promise,g(d),"all"===t)this.clearPages();else if("current"===t){let e=this.stack.pop();e&&this.removeStackItem(e,!1)}let u={...e,globalProps:{...e.globalProps,...null==(r=this.getRuntimeGlobalProps)?void 0:r.call(this)}},c=tN(l,this.packageInfo.resourceUrlVersion),p=e.pageCapsule??this.pageCapsule,m=`page-${++this.nextPageIndex}`,f=(a=tB(null==(n=u.globalProps)?void 0:n.__VIEW_CONTEXT__),{...o(u.initData)?tB(u.initData.viewContext):{},...a,viewId:m,pageName:s.id,pageUrl:s.path}),v=null,y=this.pageHost.createPage({className:this.className,runtime:this,onError:this.onError,onReady:()=>{v&&this.stack.includes(v)&&(v.isReady=!0,this.flushPageLifecycleEvents(v))}},this.runtimeKernel,()=>this.exitBridgeApp());void 0!==e.pageCapsule&&(this.pageCapsule=e.pageCapsule),this.pendingPages.push(tO(s.path,e));try{let t,r,n=y.render({resourceUrl:c,groupId:this.manifest.appId,initData:o(u.initData)?{...u.initData,viewContext:f}:{viewContext:f},globalProps:(t=null==p?void 0:p.statusBarHeight,r="number"==typeof t&&Number.isFinite(t)?{statusBarHeight:t}:{},{...u.globalProps,...r,__VIEW_CONTEXT__:f}),pageCapsule:p}),a=this.getCurrentStackItem();return a&&(null==(i=a.backPrompt)||i.abort(),this.visible&&this.sendPageLifecycleEvent(a,tP),a.page.setVisible(!1)),v={id:m,pageId:s.id,route:s.path,resourceUrl:c,entry:s,element:n,isReady:!1,options:{...e,entry:s,pageCapsule:p},pendingLifecycleEvents:[],page:y},this.stack.push(v),this.updateEmptyState(),v.page.setVisible(this.visible),this.visible&&this.sendPageLifecycleEvent(v,tL),this.sendAppEvent("onPageOpened",{viewId:v.id}),this.toStackEntry(v)}catch(e){throw y.clear(),this.updateEmptyState(),e}finally{this.pendingPages.pop()}}async replacePage(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this.packageSnapshot||await this.loadPackage(),this.destroyed)throw Error("Runtime was destroyed");return this.withPageTransition(()=>this.pushLoadedPage(e,"current"))}async reLaunchPage(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this.packageSnapshot||await this.loadPackage(),this.destroyed)throw Error("Runtime was destroyed");return this.withPageTransition(()=>this.pushLoadedPage(e,"all"))}popPage(){let e=this.stack.pop();return e?this.removeStackItem(e,!0):null}setVisible(e){if(this.destroyed||this.visible===e)return;this.visible=e;let t=this.getCurrentStackItem();t&&(t.page.setVisible(e),this.sendPageLifecycleEvent(t,e?tL:tP)),this.appRuntime&&this.sendAppEvent(e?tR:tM)}requestBack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.getCurrentStackItem();if(!t)return!1;if(1===this.stack.length){var r;return this.setVisible(!1),null==(r=this.pageHost)||r.hide(),!0}let i=()=>{if(this.destroyed||this.getCurrentStackItem()!==t)return;let r=Math.min(Math.max(1,Math.floor(e.delta??1)),this.stack.length-1);for(let e=0;e<r;e+=1)this.popPage()};if(void 0===t.alertBeforeUnloadMessage||!this.pageHost)return i(),!0;if(!t.backPrompt||t.backPrompt.signal.aborted){let e=new AbortController;t.backPrompt=e;let r=r=>{t.backPrompt===e&&(t.backPrompt=void 0,r&&!e.signal.aborted&&i())};this.pageHost.confirmBeforeUnload(t.alertBeforeUnloadMessage,e.signal).then(e=>{r(e)},()=>{r(!0)})}return!0}clear(){this.lifecycle.abort(),this.lifecycle=new AbortController,this.packageLoading=void 0,this.clearPages(),this.clearAppRuntime(),this.bridge.resetApplication(),this.packageSnapshot&&(this.packageSnapshot={...this.packageSnapshot,resourceUrlVersion:String(Number(this.packageSnapshot.resourceUrlVersion??0)+1)})}async restart(){if(this.packageSnapshot||await this.loadPackage(),this.destroyed)throw Error("Runtime was destroyed");await this.withPageTransition(async()=>{let e=this.stack.map(e=>{let{options:t}=e;return t});for(let t of(this.clear(),e))await this.pushLoadedPage(t)})}reload(){var e;null==(e=this.getCurrentStackItem())||e.page.reload()}destroy(){var e;this.destroyed||(this.destroyed=!0,this.bridge.destroy(),this.clear(),null==(e=this.pageHost)||e.destroy())}clearPages(){for(;this.stack.length>0;){let e=this.stack.pop();e&&this.removeStackItem(e,!1)}}async withPageTransition(e){let t=this.bridge.register();try{return await e()}finally{this.bridge.unregister(t)}}removeStackItem(e,t){var r;null==(r=e.backPrompt)||r.abort();let i=this.toStackEntry(e);this.sendPageLifecycleEvent(e,tj),e.page.clear();let n=this.getCurrentStackItem();return t&&n&&this.visible&&(n.page.setVisible(!0),this.sendPageLifecycleEvent(n,tL)),this.updateEmptyState(),i}async ensureAppRuntime(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.packageSnapshot||await this.loadPackage(),this.startAppRuntime(e)}startAppRuntime(){var e,t,r;let i,n,a,s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this.destroyed)throw Error("Runtime was destroyed");if(this.clearingAppRuntime)throw Error("Runtime is being cleared");if(null==(e=this.appStart)?void 0:e.error)throw this.appStart.error;if(this.appRuntime||!this.manifest.appRuntimeEntry)return;let o=h(this.manifestUrl,this.manifest.appRuntimeEntry);if(!o)throw Error("No Web entry configured for app runtime");let l=tN(o,this.packageInfo.resourceUrlVersion),d=new Promise((e,t)=>{i=e,n=t});d.catch(()=>{});let u={promise:d,resolve:i,reject:n,error:void 0};this.appStart=u;let c=e=>{var t;this.appStart!==u||this.destroyed||this.clearingAppRuntime||((null==(t=this.appRuntime)?void 0:t.isReady)||(u.error=e,u.reject(e)),this.bridge.fail(e))},p=this.appCallController.signal;try{a=function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:document.body,i=document.createElement("div");i.className="doubao-runtime-app",i.hidden=!0,i.style.display="none";let n=t.createContainer({...e,container:i});return{render:e=>(r.append(i),n.render(e)),clear(){n.clear(),i.remove()},sendEvent:n.sendEvent.bind(n),sendBridgeMessage:n.sendBridgeMessage.bind(n)}}({runtime:this,sandboxUrl:this.sandboxUrl,className:this.className,onError:(e,t)=>{var r;this.appStart!==u||this.destroyed||this.clearingAppRuntime||(c(e),null==(r=this.onError)||r.call(this,e,t))},appletSessionMessageHandler:(e,t)=>{var r;return this.appStart!==u||this.destroyed||this.clearingAppRuntime||this.bridge.handleMainBridgeMessage(e)?{routed:!0}:(null==(r=s.appletSessionMessageHandler)?void 0:r.call(s,e,t))??{routed:!1}},getAppletContext:()=>({owner:this.apiContextOwner,signal:p,source:"app",viewContext:s.viewContext??this.viewContext}),onReady:()=>{var e;let t=this.appRuntime;this.clearingAppRuntime||!t||t.container!==a||t.isReady||u.error||(t.isReady=!0,this.flushAppEvents(),u.resolve(),null==(e=s.onReady)||e.call(s))}},this.runtimeKernel,null==(t=this.pageHost)?void 0:t.container),this.appRuntime={container:a,isReady:!1,pendingEvents:[{name:this.visible?tR:tM,params:{}},...this.pendingAppEvents.splice(0)]};let e=void 0!==s.groupId?s.groupId:this.appGroupId;a.render({bridge:this.bridge,resourceUrl:l,groupId:null===e?void 0:e??this.manifest.appId,containerType:"APP",initData:this.appInitData??{},globalProps:{...tq(this.manifest,this.appGlobalProps),...null==(r=this.getRuntimeGlobalProps)?void 0:r.call(this)}})}catch(e){throw c(e instanceof Error?e:Error(String(e))),this.appRuntime=null,null==a||a.clear(),e}}clearAppRuntime(){var e;if(this.clearingAppRuntime)return;this.clearingAppRuntime=!0;let t=Error(this.destroyed?"Runtime was destroyed":"Runtime was cleared");null==(e=this.appStart)||e.reject(t),this.bridge.fail(t),this.pendingAppEvents=[];let r=this.appRuntime;(null==r?void 0:r.isReady)&&(this.visible&&r.container.sendEvent(tM),r.container.sendEvent(tj)),null==r||r.container.clear(),this.appCallController.abort(),this.appCallController=new AbortController,this.appRuntime=null,this.appStart=null,this.clearingAppRuntime=!1}sendAppEvent(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=this.appRuntime;if(!this.destroyed&&!this.clearingAppRuntime){if(!r)return void this.pendingAppEvents.push({name:e,params:t});if(!r.isReady)return void r.pendingEvents.push({name:e,params:t});r.container.sendEvent(e,t)}}sendAppBridgeMessage(e){if(!this.clearingAppRuntime){var t;null==(t=this.appRuntime)||t.container.sendBridgeMessage(e)}}flushAppEvents(){let e=this.appRuntime;if(null==e?void 0:e.isReady)for(let t of e.pendingEvents.splice(0))e.container.sendEvent(t.name,t.params)}sendPageLifecycleEvent(e,t){let r,i=(r={viewId:e.id,pageName:e.pageId,pageUrl:e.route},{viewId:e.id,eventName:JSON.stringify(r)});e.isReady?e.page.sendEvent(t,i):e.pendingLifecycleEvents.push({name:t,params:i})}flushPageLifecycleEvents(e){if(e.isReady)for(let t of e.pendingLifecycleEvents.splice(0))e.page.sendEvent(t.name,t.params)}resolvePageEntry(e){return e.entry??this.manifest.getPageEntry(e.pageId)}resolveRoutePageOptions(e){try{return tD(e,this.manifest)}catch(e){throw Object.assign(new w(e instanceof Error?e.message:String(e),104),{cause:e})}}getCurrentStackItem(){return this.stack[this.stack.length-1]??null}updateEmptyState(){var e;null==(e=this.pageHost)||e.setEmpty(0===this.stack.length)}getCurrentPages(){return[...this.stack.map(e=>tO(e.route,e.options)),...this.pendingPages]}getPackageInfo(){var e;return this.packageSnapshot?t$(this.manifest):{appId:null==(e=this.packageSource)?void 0:e.appId}}resolveFileSystemNamespace(){return void 0!==this.configuredFileSystemNamespace?this.configuredFileSystemNamespace:eu({packageInfo:this.getPackageInfo()},this.userId)}withNavigationType(e,t){return{...e,globalProps:{...e.globalProps,__WEB_NAVIGATION_TYPE__:t}}}async openBridgePage(e){this.packageSnapshot||await this.loadPackage();let t=this.resolveRoutePageOptions(e),r=this.resolvePageEntry(t),i=e.mode??"push",n=this.getCurrentStackItem(),a=e=>e.entry.path===r.path,s="replace"===i?n&&a(n)?this.stack.length-1:-1:"navigate"===i||"pop_to"===i?this.stack.findLastIndex(a):-1;if(s>=0){var o;let e=this.stack[s],r=t.globalProps??{};for(e.page.updateGlobalProps({__LOCATION__:r.__LOCATION__,__RENDER_DATA__:r.__RENDER_DATA__}),e.options={...e.options,initData:t.initData,globalProps:{...e.options.globalProps,...r}},null==(o=e.backPrompt)||o.abort();this.stack.length-1>s;)this.removeStackItem(this.stack.pop(),!1);e.page.setVisible(this.visible),n!==e&&this.visible&&this.sendPageLifecycleEvent(e,tL);let i=this.getCurrentPages();for(let e of this.stack)e.page.sendEvent(e1,{apiResults:{"doubao.getCurrentPages":{pages:i}}});this.updateEmptyState();return}"replace"===i||"pop_to"===i?await this.replacePage(t):await this.pushLoadedPage(t)}async navigateToBridgePage(e){this.packageSnapshot||await this.loadPackage(),await this.pushLoadedPage(this.withNavigationType(this.resolveRoutePageOptions(e),"navigateTo"))}async redirectToBridgePage(e){this.packageSnapshot||await this.loadPackage();let t=this.withNavigationType(this.resolveRoutePageOptions(e),"redirectTo");await this.replacePage(t)}async reLaunchBridgePage(e){this.packageSnapshot||await this.loadPackage();let t=this.withNavigationType(this.resolveRoutePageOptions(e),"reLaunch");await this.reLaunchPage(t)}exitBridgeApp(){this.clear()}toStackEntry(e){return{id:e.id,pageId:e.pageId,route:e.route,url:tO(e.route,e.options).route,resourceUrl:e.resourceUrl,entry:e.entry,element:e.element}}}class tW{kernel;autoRelease;runtimes=new Map;packageManagers=new WeakMap;nextPackageManagerId=0;constructor(e,t=!1){this.kernel=e,this.autoRelease=t}acquire(e){var t,r,i,n,a,s,o,l,d,u;let p=e.fileSystemNamespace??eu({packageInfo:{appId:e.appId}},e.userId),h=new URL(e.appRuntimeEntry,null==(t=globalThis.location)?void 0:t.href).href,m=e.packageManager;m&&!this.packageManagers.has(m)&&this.packageManagers.set(m,this.nextPackageManagerId++);let g=[m?this.packageManagers.get(m):"",String(e.sandboxUrl??""),(null==(r=e.packageInfo)?void 0:r.manifestUrl)??"",(null==(i=e.packageInfo)?void 0:i.resourceRoot)??"",e.appId,(null==(n=e.viewContext)?void 0:n.conversationId)??"",p,e.versionTag??(null==(a=e.viewContext)?void 0:a.versionTag)??"",h].join("\0"),f=this.runtimes.get(g);if(f&&!f.isDestroyed)return f;let v=new tF({packageManager:m,pageHost:e.pageHost,sandboxUrl:e.sandboxUrl,manifest:(null==(s=e.packageInfo)?void 0:s.manifest)??new c({manifestVersion:"3.0",packageName:e.appId,appId:e.appId,versionCode:"",applet:{appletId:e.appId,digest:"",appRuntimeEntry:h,pages:[]},widgets:[]}),manifestUrl:(null==(o=e.packageInfo)?void 0:o.manifestUrl)??h,resourceRoot:null==(l=e.packageInfo)?void 0:l.resourceRoot,registerPageController:!1,appGroupId:null,apiRegistry:e.apiRegistry??E,className:e.className,fileSystemNamespace:p,nativeModulesCallHandler:e.nativeModulesCallHandler,appInitData:e.appInitData,appGlobalProps:tU(e.appGlobalProps??{},{appId:e.appId}),getRuntimeGlobalProps:e.getRuntimeGlobalProps,viewContext:{appId:e.appId,conversationId:null==(d=e.viewContext)?void 0:d.conversationId,versionTag:e.versionTag??(null==(u=e.viewContext)?void 0:u.versionTag)},onError:e.onError},this.kernel??tk,this.autoRelease?()=>this.release(v):void 0);return this.runtimes.set(g,v),v}release(e){for(let[t,r]of this.runtimes)if(r===e){this.runtimes.delete(t),e.destroy();return}}destroy(){let e=[...this.runtimes.values()];for(let t of(this.runtimes.clear(),e))t.destroy()}}function tz(e,t){return class extends e{hostOptions;prepared=!1;constructor(e){super({...e,sandboxUrl:e.runtime?e.runtime.sandboxUrl:e.sandboxUrl}),this.hostOptions=e}prepare(e){super.prepare(e),this.prepared=!0}clear(){this.prepared=!1,super.clear()}render(e){var r,i,n;this.prepared||this.clear(),this.prepared=!1;let{application:a,applicationPackage:s,appRuntimeEntry:o,...l}=e,d=(null==a?void 0:a.appId)??(null==(i=l.globalProps)||null==(r=i.packageInfo)?void 0:r.appId),u=(null==a?void 0:a.appRuntimeEntry)??o,c=(null==a?void 0:a.viewContext)??(null==(n=l.globalProps)?void 0:n.__VIEW_CONTEXT__),p=this.hostOptions.runtime??(d&&u?(this.hostOptions.runtimeManager??t()).acquire({appId:d,appRuntimeEntry:u,packageInfo:s,packageManager:this.hostOptions.packageManager,sandboxUrl:this.hostOptions.sandboxUrl,apiRegistry:this.hostOptions.apiRegistry,nativeModulesCallHandler:this.hostOptions.nativeModulesCallHandler,versionTag:(null==a?void 0:a.versionTag)??(null==c?void 0:c.versionTag),viewContext:c,userId:this.hostOptions.userId,fileSystemNamespace:this.hostOptions.fileSystemNamespace}):void 0),h=null==p?void 0:p.bridge.register();try{return super.render({...l,applicationPackage:s,bridge:(null==p?void 0:p.bridge)??l.bridge})}catch(e){throw this.clear(),e}finally{h&&(null==p||p.bridge.unregister(h))}}}}new tW(void 0,!0),r(34974),r(71463),r(25907),r(92151);var tH=r(59314);let tV="embed-webview",tG="__channel_ack__",tJ=new WeakMap,tK=e=>({url:e});function tZ(e){if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}}function tX(e){return"string"==typeof e?e:JSON.stringify(e??{})}let tY=globalThis.HTMLElement??class{},tQ="region-to-decode";function t0(e){if("string"==typeof e)try{e=JSON.parse(e)}catch{return null}if(!e||"object"!=typeof e)return null;let{x:t,y:r,width:i,height:n}=e;return![t,r,i,n].every(Number.isFinite)||t<0||r<0||i<=0||n<=0?null:{x:t,y:r,width:i,height:n}}class t1{element;static observedAttributes=[];image;attributes=new MutationObserver(()=>this.update());resize;viewSize;cropStyle;constructor(e){var t;this.element=e,this.image=(null==(t=e.shadowRoot)?void 0:t.querySelector("#img"))??null,Object.defineProperty(e,tQ,{configurable:!0,get:()=>t0(e.getAttribute(tQ)),set:t=>{let r=t0(t);r?e.setAttribute(tQ,JSON.stringify(r)):e.removeAttribute(tQ)}})}connectedCallback(){this.attributes.observe(this.element,{attributes:!0,attributeFilter:[tQ,"src","mode","auto-size"]}),this.update()}clearCrop=()=>{var e;null==(e=this.cropStyle)||e.remove(),this.cropStyle=void 0};stopRendering(){var e,t,r;null==(e=this.resize)||e.disconnect(),this.resize=void 0,this.viewSize=void 0,null==(t=this.image)||t.removeEventListener("load",this.update),null==(r=this.image)||r.removeEventListener("error",this.clearCrop),this.clearCrop()}update=()=>{var e,t,r;let i=t0(this.element.getAttribute(tQ)),n=this.image;if(!i||!n)return void this.stopRendering();this.resize||(this.resize=new ResizeObserver(e=>{let[t]=e;this.viewSize=t.contentRect,this.update()}),this.resize.observe(this.element),n.addEventListener("load",this.update),n.addEventListener("error",this.clearCrop));let a=n.naturalWidth,s=n.naturalHeight,o=this.element.getAttribute("src"),l=this.element.getRootNode().host,d=o?(null==l||null==(e=l.resolveResource)?void 0:e.call(l,o))??o:o;if(!n.complete||!a||!s||n.getAttribute("src")!==d)return void this.clearCrop();let u=Math.min(i.width,a-i.x),c=Math.min(i.height,s-i.y),p=getComputedStyle(this.element),h=Number.parseFloat(p.paddingLeft)||0,m=Number.parseFloat(p.paddingTop)||0,g=(null==(t=this.viewSize)?void 0:t.width)??this.element.clientWidth-h-(Number.parseFloat(p.paddingRight)||0),f=(null==(r=this.viewSize)?void 0:r.height)??this.element.clientHeight-m-(Number.parseFloat(p.paddingBottom)||0);if(u<=0||c<=0||g<=0||f<=0)return void this.clearCrop();let v=g/u,y=f/c,b=this.element.getAttribute("mode");"aspectFit"===b?v=y=Math.min(v,y):"aspectFill"===b?v=y=Math.max(v,y):"center"===b&&(v=y=1);let w=h+(g-u*v)/2-i.x*v,_=m+(f-c*y)/2-i.y*y;this.cropStyle||(this.cropStyle=this.element.ownerDocument.createElement("style"),this.cropStyle.setAttribute("data-doubao-image-region",""),this.element.shadowRoot.append(this.cropStyle)),this.cropStyle.textContent=`#img {
2
2
  position: absolute !important;
3
3
  margin: 0 !important;
4
4
  padding: 0 !important;
@@ -16,7 +16,7 @@
16
16
  object-fit: fill !important;
17
17
  clip-path: inset(${i.y*y}px ${(a-i.x-u)*v}px
18
18
  ${(s-i.y-c)*y}px ${i.x*v}px) !important;
19
- }`};dispose(){this.attributes.disconnect(),this.stopRendering()}}let t2=new Set;var t3=r(94763);let t4=new WeakMap;function t6(e,t,r){let i=new Map;for(let n of t){let t=Reflect.get(e,n);i.set(n,Object.getOwnPropertyDescriptor(e,n)),Object.defineProperty(e,n,{configurable:!0,writable:!0,value(){for(var e=arguments.length,i=Array(e),n=0;n<e;n++)i[n]=arguments[n];return r(),Reflect.apply(t,this,i)}})}return()=>{for(let[t,r]of i)r?Object.defineProperty(e,t,r):Reflect.deleteProperty(e,t)}}class t5{element;placeholder=document.createComment("map-marker");parent;cleanupElement;constructor(e){this.element=e;let t=e.parentNode;if(!t)throw Error("Web Map Marker requires a component parent");this.parent=t;let r=t4.get(t);if(!r){let e=new Set;r={portals:e,cleanup:t6(t,["appendChild","insertBefore","removeChild","replaceChild","append","prepend","replaceChildren"],()=>{for(let t of e)t.restore()})},t4.set(t,r)}r.portals.add(this),this.cleanupElement=t6(e,["remove","replaceWith","before","after"],()=>{for(let e of r.portals)e.restore()})}get connected(){return this.element.parentNode===this.parent?this.element.isConnected:this.placeholder.isConnected}mount(e){if(this.element.parentNode!==e){if(this.element.parentNode!==this.parent)throw Error("Web Map Marker component parent changed");Node.prototype.insertBefore.call(this.parent,this.placeholder,this.element),e.appendChild(this.element)}}restore(){this.placeholder.parentNode===this.parent&&Node.prototype.replaceChild.call(this.parent,this.element,this.placeholder)}destroy(){this.restore(),this.cleanupElement();let e=t4.get(this.parent);null==e||e.portals.delete(this),(null==e?void 0:e.portals.size)===0&&(e.cleanup(),t4.delete(this.parent))}}class t8{element;namespace;map;onError;onClick;content=document.createElement("div");portal;originalStyles=new Map;styleObserver=new MutationObserver(()=>this.syncZIndex());marker;defaultZIndex;positionKey;optionsKey;waitingForPosition=!1;syncing=!1;disposed=!1;constructor(e,t,r,i,n){this.element=e,this.namespace=t,this.map=r,this.onError=i,this.onClick=n,this.portal=new t5(e),this.content.style.cssText="width:0;height:0;overflow:visible;",this.styleObserver.observe(e,{attributes:!0,attributeFilter:["style","class"]})}get connected(){return this.portal.connected}sync(e){if(!this.disposed&&!this.syncing){this.syncing=!0;try{if(!e.position&&!e.containerPosition){var t;this.portal.restore(),null==(t=this.marker)||t.destroy(),this.marker=void 0,this.optionsKey=void 0,this.positionKey=void 0,this.waitingForPosition=!0,this.style("visibility","hidden");return}this.waitingForPosition&&(this.style("visibility",this.originalStyles.get("visibility")??""),this.waitingForPosition=!1),this.style("position","relative"),"inline"===getComputedStyle(this.element).display&&this.style("display","inline-block"),this.element.style.width||this.style("width","max-content"),this.style("transform",`translate(${-100*e.anchor[0]}%, ${-100*e.anchor[1]}%)`);let r="amap"===this.namespace.getProvider(),i={content:this.content,containerPosition:e.containerPosition?[e.containerPosition.x,e.containerPosition.y]:null,anchor:r?"top-left":0,angle:e.rotation,opacity:e.alpha,clickable:e.clickable,draggable:e.draggable,bubble:!e.clickable,animation:e.animate??(r?{scale:{from:1,to:1,duration:0}}:null)},n=JSON.stringify(e.position);this.marker&&n===this.positionKey||(i.position=e.position&&[e.position.longitude,e.position.latitude]),this.portal.mount(this.content);let a=JSON.stringify(e);if(this.marker&&this.optionsKey===a)return void this.syncZIndex();this.optionsKey=a,this.marker?this.marker.setOptions(i):(this.marker=new this.namespace.Marker(i),this.defaultZIndex=this.marker.getzIndex(),this.marker.on("click",this.onClick)),this.syncZIndex(),this.marker.getMap()!==this.map&&this.marker.setMap(this.map),this.positionKey=n}catch(e){this.onError(e)}finally{this.syncing=!1}}}syncZIndex(){if(this.marker&&!this.disposed)try{let e=Number.parseInt(getComputedStyle(this.element).zIndex,10),t=Number.isFinite(e)?e:this.defaultZIndex;void 0!==t&&t!==this.marker.getzIndex()&&this.marker.setzIndex(t)}catch(e){this.onError(e)}}style(e,t){this.originalStyles.has(e)||this.originalStyles.set(e,this.element.style.getPropertyValue(e)),this.element.style.getPropertyValue(e)!==t&&this.element.style.setProperty(e,t)}destroy(){var e;if(!this.disposed)for(let[t,r]of(this.disposed=!0,this.styleObserver.disconnect(),this.portal.destroy(),null==(e=this.marker)||e.destroy(),this.originalStyles))this.element.style.setProperty(t,r)}}let t9=e=>{let{longitude:t,latitude:r}=e;return[t,r]};function t7(e,t,r,i,n){let a=new Set(t.map(e=>{let{id:t}=e;return t}));for(let[t,r]of e)a.has(t)||(r.destroy(),e.delete(t));for(let a of t)try{let t=r(a),n=e.get(a.id);if(n){let{id:e,...r}=t;n.setOptions(r)}else e.set(a.id,i(t,a))}catch(e){n(e)}}class re{namespace;map;onError;onPolylineClick;polylines=new Map;polygons=new Map;circles=new Map;arcs=new Map;routeLabels=new Map;warnings=new Set;constructor(e,t,r,i){this.namespace=e,this.map=t,this.onError=r,this.onPolylineClick=i}warn(e){this.warnings.has(e)||(this.warnings.add(e),this.onError(Error(`Web Map 暂不支持 ${e}`)))}add(e){e.on("warning",e=>{this.onError(e.error??Error(e.reason??e.feature??"Web Map 覆盖物降级"))});try{return this.map.add(e),e}catch(t){throw e.destroy(),t}}sync(e){var t;let r=function(e){let t=new Map,r=new Set;for(let n of e){var i;if(!n.id.startsWith("__doubao_polyline_arrow__:"))continue;let a=null==(i=n.edgeTextureAssets)?void 0:i.find(e=>{let{id:t}=e;return"__doubao_polyline_arrow_texture__"===t});if(a)try{let i=decodeURIComponent(n.id.slice(26));e.some(e=>e.id===i)&&(t.set(i,{iconPath:a.url}),r.add(n))}catch{}}return e.filter(e=>!r.has(e)).map(e=>({...e,arrow:t.get(e.id)??e.arrow}))}(e.polyline??[]),i=this.namespace.supports("Polyline.edgeTexture").supported,n=this.namespace.supports("RouteLabel").supported;!i&&r.some(e=>{var t,r;return(null==(t=e.edgeTexture)?void 0:t.length)||(null==(r=e.edgeTextureAssets)?void 0:r.length)})&&this.warn("当前图商的 polyline 纹理"),!n&&(null==(t=e.routeLabel)?void 0:t.length)&&this.warn("当前图商的 routeLabel"),r.some(e=>e.collideDetection)&&this.warn("polyline POI 碰撞避让"),t7(this.polylines,r,e=>{var t;return{id:e.id,path:e.points.map(t9),strokeColors:e.edgeColor??[],arrow:e.arrow??null,edgeTexture:i?e.edgeTexture??[]:[],edgeTextureAssets:i?e.edgeTextureAssets??[]:[],strokeColor:(null==(t=e.edgeColor)?void 0:t[0])??"#0066ff",strokeWeight:e.width??2,strokeStyle:e.dottedLine?"dashed":"solid",lineCap:"line_cap_round"===e.lineCapType?"round":"butt",lineJoin:"line_join_round"===e.lineJoinType?"round":"line_join_miter"===e.lineJoinType?"miter":"bevel",zIndex:e.zIndex??0}},(e,t)=>{let r=new this.namespace.Polyline(e);return r.on("click",()=>this.onPolylineClick(t.id)),this.add(r)},this.onError),t7(this.polygons,e.polygons??[],e=>({id:e.id,path:e.points.map(t9),fillColor:e.fillColor,strokeColor:e.strokeColor,strokeWeight:e.strokeWidth,strokeStyle:e.dottedLine?"dashed":"solid",zIndex:e.zIndex}),e=>{let t=new this.namespace.Polygon(e);return this.add(t)},this.onError),t7(this.circles,e.circles??[],e=>({id:e.id,center:t9(e.center),radius:e.radius,fillColor:e.fillColor,strokeColor:e.strokeColor,strokeWeight:e.strokeWidth,zIndex:e.zIndex}),e=>{let t=new this.namespace.Circle(e);return this.add(t)},this.onError),t7(this.arcs,e.arcs??[],e=>({id:e.id,path:[t9(e.start),t9(e.mid??e.middle),t9(e.end)],strokeColor:e.color??"#0066ff",strokeWeight:e.width??2,zIndex:e.zIndex}),e=>{let t=new this.namespace.Arc(e);return this.add(t)},this.onError),t7(this.routeLabels,n?e.routeLabel??[]:[],e=>({id:e.id,path:e.points.map(t9),text:e.text,textColor:e.textColor??"#000000",fontSize:e.fontSize??12,fontWeight:e.fontWeight??"normal",borderColor:e.borderColor??"#cccccc",borderWidth:e.borderWidth??0,zIndex:e.zIndex??0}),e=>this.add(new this.namespace.RouteLabel(e)),this.onError)}destroy(){for(let e of[this.polylines,this.polygons,this.circles,this.arcs,this.routeLabels]){for(let t of e.values())t.destroy();e.clear()}}}let rt={baidu:{provider:"baidu",security:{baidu:{serviceHost:"https://api.doubao-dev.com/_BMapService/"}}},amap:{provider:"amap",key:{amap:"f57928bd7156da61d512795ec5c0c968"},security:{amap:{serviceHost:"https://api.doubao-dev.com/_AMapService"}}}},rr=new WeakMap,ri=new WeakMap,rn=new WeakMap,ra=new WeakMap;function rs(e,t,r){if(t in r)return r[t];let i=e.getAttribute(t);if(i)try{return JSON.parse(i)}catch{return}}function ro(e,t,r){let i=Number(e.getAttribute(t));return Number.isFinite(i)&&e.hasAttribute(t)?i:r}function rl(e,t,r){let i=e.getAttribute(t);return null===i?r:"false"!==i&&"0"!==i}function rd(e){let{longitude:t,latitude:r}=e;return[t,r]}function ru(e){return{longitude:e.lng,latitude:e.lat}}function rc(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};e.dispatchEvent(new CustomEvent(t,{detail:r,bubbles:!1}))}function rp(e,t){let r=t instanceof Error?t:Error(String(t));console.error("[Doubao Map]",r.message),e.dispatchEvent(new CustomEvent("error",{detail:{error:r}}))}function rh(e){return rr.get(e)??{}}function rm(e){return ri.get(e)??{}}function rg(e){let t=ra.get(e);if(t)return t;let r=e.closest("map");return r?rn.get(r):void 0}class rf{element;map;namespace;syncingMarkers=!1;overlays;markers=new Map;cleanupTileLoad;surface;resize;sizeFrame=0;loading=!1;initializationBlocked=!1;disposed=!1;ready=!1;lastAttributes="";lastOverlays="";lastStyle="";lastLogoPosition="";warnings=new Set;constructor(e){var t;if(this.element=e,rn.set(e,this),this.installMethods(),"inline"===getComputedStyle(e).display&&(e.style.display="block"),"static"===getComputedStyle(e).position&&(e.style.position="relative"),e.style.overflow="hidden",this.resize="function"==typeof ResizeObserver?new ResizeObserver(()=>this.initialize()):void 0,null==(t=this.resize)||t.observe(e),!this.resize){let e=()=>{this.disposed||this.map||this.loading||this.initializationBlocked||(this.initialize(),this.sizeFrame=requestAnimationFrame(e))};this.sizeFrame=requestAnimationFrame(e)}this.initialize()}warn(e){this.warnings.has(e)||(this.warnings.add(e),rp(this.element,Error(`Web Map 暂不支持 ${e}`)))}getMapConfig(){let e=rs(this.element,"extra-params",rh(this.element));return rt[(null==e?void 0:e.useAliMap)===!0?"amap":"baidu"]}initialize(){var e;if(this.disposed||this.loading||this.initializationBlocked||this.map||this.element.clientWidth<=0||this.element.clientHeight<=0)return;let t=this.getMapConfig(),r=(null==(e=this.element.ownerDocument.location)?void 0:e.hostname)??"";if("baidu"===t.provider&&(tb(r)||"[::1]"===r||r.endsWith(".localhost"))){this.initializationBlocked=!0,rp(this.element,Error("当前豆包百度地图账号未授权本地域名,请使用获准域名的 sandbox 调试地图。"));return}this.loading=!0;let i=document.createElement("div");i.dataset.doubaoMapSurface="",i.style.cssText="position:absolute;inset:0;width:100%;height:100%;",this.element.prepend(i),this.surface=i,Promise.resolve().then(()=>t3.H3.load(t)).then(e=>{this.disposed||this.createMap(e,i)}).catch(e=>{this.disposed||rp(this.element,e),i.remove(),this.surface=void 0}).finally(()=>{this.loading=!1})}createMap(e,t){let r=this.element,i=rs(r,"center",rh(r)),n=rs(r,"scale-range",rh(r));try{let a=new e.Map(t,{center:i&&rd(i),zoom:ro(r,"scale",16),zooms:n??[3,20],rotation:ro(r,"rotate",0),logoPosition:r.getAttribute("logo-position")||"bottom-left",eventContext:!0,enableNativeInteraction:rl(r,"native-interaction-enabled",!0),showScale:rl(r,"enable-scale-controls",!1),zoomEnable:rl(r,"enable-scale",!0),dragEnable:rl(r,"enable-drag",!0),rotateEnable:rl(r,"enable-rotate",!1)});this.map=a,this.namespace=e,this.overlays=new re(e,a,e=>rp(r,e),e=>rc(r,"clickpolyline",{id:e}));let s=!1,o=()=>{this.disposed||s||(s=!0,rc(r,"maptileload"))};if("baidu"===e.getProvider()){let e=a.getNative();e.addEventListener("firsttileloaded",o),this.cleanupTileLoad=()=>e.removeEventListener("firsttileloaded",o)}let l=()=>{this.disposed||this.ready||(this.ready=!0,rc(r,"mapload"),"amap"===e.getProvider()&&o(),this.update(!0))};a.on("complete",l),a.on("click",e=>{e.lnglat&&rc(r,"clickmap",{point:ru(e.lnglat)})}),a.on("error",e=>rp(r,e)),a.on("warning",e=>{rp(r,Error(e.reason??e.feature??"Web Map 能力降级"))});let d=(e,t,i)=>{if(!a.isReady())return;let n=t.context,s=(null==n?void 0:n.bounds)??a.getBounds();rc(r,"regionchange",{type:(null==n?void 0:n.phase)??e,...i?{causedBy:i}:{},center:ru((null==n?void 0:n.center)??a.getCenter()),scale:(null==n?void 0:n.zoom)??a.getZoom(),rotate:(null==n?void 0:n.rotation)??a.getRotation(),region:{southwest:ru(s.getSouthWest()),northeast:ru(s.getNorthEast())}})};a.on("movestart",e=>d("begin",e,"drag")),a.on("moveend",e=>d("end",e,"drag")),a.on("zoomstart",e=>d("begin",e,"scale")),a.on("zoomend",e=>d("end",e,"scale")),"baidu"!==e.getProvider()&&(a.on("rotatestart",e=>d("begin",e)),a.on("rotateend",e=>d("end",e))),a.isReady()&&l()}catch(e){var a,s,o;null==(a=this.cleanupTileLoad)||a.call(this),null==(s=this.overlays)||s.destroy(),null==(o=this.map)||o.destroy(),this.map=void 0,t.remove(),rp(r,e)}}update(){var e,t;let r=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!this.ready||!this.map||this.disposed)return;let i=this.element,n=this.map,a=rh(i),s=JSON.stringify({center:rs(i,"center",a),scale:i.getAttribute("scale"),scales:rs(i,"scale-range",a),rotate:i.getAttribute("rotate"),showScale:i.getAttribute("enable-scale-controls"),enableScale:i.getAttribute("enable-scale"),enableDrag:i.getAttribute("enable-drag"),enableRotate:i.getAttribute("enable-rotate"),nativeInteraction:i.getAttribute("native-interaction-enabled")});if(r||s!==this.lastAttributes){this.lastAttributes=s;try{let e=rs(i,"scale-range",a);e&&n.setZooms(e);let t=rs(i,"center",a);t?n.setZoomAndCenter(ro(i,"scale",16),rd(t)):n.setZoom(ro(i,"scale",16)),n.setRotation(ro(i,"rotate",0)),n.setShowScale(rl(i,"enable-scale-controls",!1)),n.setNativeInteractionEnabled(rl(i,"native-interaction-enabled",!0)),n.setStatus({zoomEnable:rl(i,"enable-scale",!0),dragEnable:rl(i,"enable-drag",!0),rotateEnable:rl(i,"enable-rotate",!1)})}catch(e){rp(i,e)}}let o=i.getAttribute("map-style")||"normal-light";if(o!==this.lastStyle){this.lastStyle=o;try{n.setMapStyle((null==(e=this.namespace)?void 0:e.getProvider())==="baidu"?{styleId:o}:o)}catch(e){rp(i,e)}}rl(i,"enable-tilt",!1)&&this.warn("地图倾斜");let l=i.getAttribute("logo-position")||"bottom-left";if(l!==this.lastLogoPosition){this.lastLogoPosition=l;try{n.setLogoPosition(l)}catch(e){rp(i,e)}}let d={polyline:rs(i,"polyline",a),polygons:rs(i,"polygons",a),circles:rs(i,"circles",a),arcs:rs(i,"arcs",a),routeLabel:rs(i,"route-label",a)},u=JSON.stringify(d);(r||u!==this.lastOverlays)&&(this.lastOverlays=u,null==(t=this.overlays)||t.sync(d)),this.updateMarkers()}updateMarkers(){let e=this.map,t=this.namespace;if((null==e?void 0:e.isReady())&&t&&!this.syncingMarkers){this.syncingMarkers=!0;try{let r=new Set([...this.element.querySelectorAll("map-marker")].filter(e=>e.closest("map")===this.element));for(let[e,t]of this.markers)r.has(e)&&t.connected||(r.delete(e),t.destroy(),this.markers.delete(e),ra.delete(e));for(let i of r){let r=rm(i);rl(i,"enable-collide-with-poi",!1)&&this.warn("marker POI 碰撞避让");let n=rs(i,"container-position",r),a=rl(i,"enable-drag",!1),s=!n&&"amap"===t.getProvider();a&&!s&&this.warn(n?"固定屏幕位置的 marker 拖动":"百度自定义内容 marker 拖动");let o=rl(i,"enable-click",!0);a&&!o&&this.warn("关闭点击时的 marker 拖动");let l=this.markers.get(i);l||(l=new t8(i,t,e,e=>rp(this.element,e),()=>rc(i,"clickmarker")),this.markers.set(i,l),ra.set(i,this)),l.sync({position:rs(i,"position",r),containerPosition:n,anchor:rs(i,"anchor",r)??[.5,1],rotation:ro(i,"rotation",0),alpha:ro(i,"alpha",1),clickable:o,draggable:a&&s&&o,animate:rs(i,"animate",r)})}}finally{this.syncingMarkers=!1}}}getMap(){var e;if(!(null==(e=this.map)?void 0:e.isReady()))throw Error("Web Map 尚未加载完成");return this.map}installMethods(){Object.assign(this.element,{setCenter:e=>{let{center:t,animated:r,duration:i}=e;return this.getMap().setCenter(rd(t),!1===r,i)},getCenter:()=>ru(this.getMap().getCenter()),setScale:e=>{let{scale:t,animated:r,duration:i}=e;return this.getMap().setZoom(t,!1===r,i)},getScale:()=>({scale:this.getMap().getZoom()}),getBound:()=>{let e=this.getMap().getBounds();return{southwest:ru(e.getSouthWest()),northeast:ru(e.getNorthEast())}},setBound:e=>{let{southwest:t,northeast:r,animated:i,duration:n}=e;return this.getMap().setBounds([t.longitude,t.latitude,r.longitude,r.latitude],!1===i,void 0,n)},fitPoints:e=>{let{points:t,padding:r=[0,0,0,0],animated:i,duration:n}=e;return this.getMap().setFitView(t.map(rd),!1===i,[r[2]??0,r[3]??0,r[0]??0,r[1]??0],void 0,n)},setAnchor:e=>{let{position:t}=e;return this.getMap().setAnchor([t.x,t.y])},latLngToPx:e=>{let{latLng:t}=e,r=this.getMap().lngLatToContainer(rd(t));return{x:r.x,y:r.y}},pxToLatLng:e=>{let{x:t,y:r}=e;return{latLng:ru(this.getMap().containerToLngLat([t,r]))}}})}dispose(){var e,t,r,i,n;if(!this.disposed){for(let[r,i]of(this.disposed=!0,null==(e=this.resize)||e.disconnect(),cancelAnimationFrame(this.sizeFrame),null==(t=this.cleanupTileLoad)||t.call(this),this.markers))ra.delete(r),i.destroy();this.markers.clear(),null==(r=this.overlays)||r.destroy(),null==(i=this.map)||i.destroy(),null==(n=this.surface)||n.remove(),rn.delete(this.element)}}}class rv{element;static observedAttributes=[];constructor(e){this.element=e}forwardLinkEvent=e=>{this.element.dispatchEvent(new CustomEvent("link",{detail:e.detail,bubbles:!0,composed:!0}))};connectedCallback(){this.element.addEventListener("bindlink",this.forwardLinkEvent);let e=this.element.markdownStyle??{};this.element.markdownStyle={...e,link:{...e.link,textDecoration:"none"},orderedList:{...e.orderedList,paddingLeft:0},unorderedList:{...e.unorderedList,paddingLeft:0}}}}function ry(e){var t;null==(t=e.registerPlugin)||t.call(e,rv)}let rb="x-video-engine",rw=globalThis.HTMLElement??class{};if("object"!=typeof customElements||customElements.get(tV)||customElements.define(tV,class e extends tY{static observedAttributes=["src"];#e=null;#t=null;#r=!1;messageOrigin;connectedCallback(){this.#r=!0,this.style.display||(this.style.display="block"),this.#i(),this.#n()}disconnectedCallback(){var e;this.#r=!1,this.#a(),null==(e=this.#e)||e.remove(),this.#e=null,window.removeEventListener("message",this.#s)}attributeChangedCallback(e){"src"===e&&this.#r&&this.#n()}get src(){return this.getAttribute("src")}set src(e){null===e?this.removeAttribute("src"):this.setAttribute("src",e)}reload(){this.#n(!0)}postMessage(e){let t=o(e)?e.data:void 0;this.#o({type:"event",name:"message",params:{data:t},timestamp:Date.now()})}eval(e){let t=o(e)&&"string"==typeof e.func?e.func:"";if(t)try{if(this.messageOrigin){var r,i;null==(i=this.#e)||null==(r=i.contentWindow)||r.postMessage({type:"__doubao_web_view_eval__",code:t},this.messageOrigin);return}let e=this.#l();null==e||e.eval(t)}catch{}}onGoBack(){return{consumed:!1}}#i(){if(this.#e)return this.#e;let e=this.shadowRoot??this.attachShadow({mode:"open"}),t=document.createElement("iframe");return t.style.cssText="display:block;width:100%;height:100%;border:none;",t.addEventListener("load",this.#d),t.addEventListener("error",this.#u),e.replaceChildren(t),this.#e=t,window.addEventListener("message",this.#s),t}#n(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.#i(),r=this.getAttribute("src");if(!r)return;let i=tK(r);this.messageOrigin="window"===i.messageTransport?new URL(i.url,document.baseURI).origin:void 0,(e||t.getAttribute("src")!==i.url)&&(this.#a(),t.toggleAttribute("credentialless",!0===i.credentialless),t.src=i.url)}#a(){var e;null==(e=this.#t)||e.close(),this.#t=null}#l(){try{var e;let t=(null==(e=this.#e)?void 0:e.contentWindow)??null;return null==t||t.document,t}catch{return null}}#d=()=>{this.messageOrigin||(this.#c(),this.#p(),this.#h()),this.#m("load",{url:this.getAttribute("src")??""})};#u=()=>{this.#m("error",{errorMsg:`Failed to load ${this.getAttribute("src")??""}`,errorCode:-1})};#s=e=>{if(!this.#e||e.source!==this.#e.contentWindow||this.messageOrigin&&e.origin!==this.messageOrigin||e.data===tG)return;let t=tZ(e.data);this.#g(t)||this.#f(tX(e.data))};#c(){var e;this.#a();let t=null==(e=this.#e)?void 0:e.contentWindow;if(!t)return;let r=new MessageChannel;r.port1.onmessage=e=>{e.data!==tG&&this.#g(tZ(e.data))},this.#t=r.port1,t.postMessage("__channel_init__","*",[r.port2])}#p(){let e=this.#l();e&&!e.AppletBridgeModule&&(e.AppletBridgeModule={postMessage:e=>(this.#g(tZ(e)),Promise.resolve({})),postMessageSync:e=>{let t=tZ(e);return v(t)?S(t,"Sync AppletBridgeModule APIs are not supported in Doubao Web SDK web-view"):void 0}})}#h(){let e=this.#l();e&&this.#f(JSON.stringify({type:"__doubao_web_view_set_title__",title:e.document.title||""}))}#g(e){if(o(e)&&"event"===e.type)return"__bridge_ready__"===e.name;if(!v(e))return!1;if("doubao.postMessage"===e.name){let t=o(e.params)?e.params.data:void 0;return this.#f(tX(t)),this.#o(_(e,{})),!0}return this.#v(e),!0}async #v(e){let t=function(e){let t=e;for(;t;){if(t instanceof Element){let e=tJ.get(t);if(e)return e}let e=t.parentNode;t=e instanceof ShadowRoot?e.host:e}}(this);if(!t)return void this.#o(S(e,`API ${e.name} is not available in this web-view host`));let r=await t(e);this.#o(r??S(e,`API ${e.name} is not implemented in Doubao Web SDK`))}#o(e){var t,r,i;let n=JSON.stringify(e);if(this.messageOrigin){null==(i=this.#e)||null==(r=i.contentWindow)||r.postMessage({type:"__doubao_web_view_message__",payload:n},this.messageOrigin);return}if(this.#t)return void this.#t.postMessage(n);let a=this.#l();null==a||null==(t=a.onWebViewMessage)||t.call(a,n)}#f(e){this.#m("message",{msg:e,data:e})}#m(e,t){for(let r of[e,`bind${e}`])this.dispatchEvent(new CustomEvent(r,{bubbles:!0,composed:!0,detail:t}))}}),"object"==typeof customElements&&!a){let e=customElements.get("x-markdown");e?(ry(e),a=Promise.resolve()):a=customElements.whenDefined("x-markdown").then(e=>{ry(e)})}if("object"!=typeof customElements||customElements.get(rb)||customElements.define(rb,class e extends rw{static observedAttributes=["play-url","video-model","vid","auto-prepare","initial-time","objectfit","muted","loop","volume","speed"];video=null;prepared=!1;firstFrame=!1;stopped=!0;playbackState=-1;playRequest=0;connectedCallback(){if(this.video)return;let e=this.shadowRoot??this.attachShadow({mode:"open"}),t=document.createElement("style");t.textContent=":host{display:block;width:100%;height:100%}video{display:block;width:100%;height:100%}";let r=document.createElement("video");this.video=r,r.playsInline=!0,e.replaceChildren(t,r);let i=(e,t)=>r.addEventListener(e,e=>{e.stopPropagation(),this.video===r&&this.isConnected&&t()});i("loadedmetadata",()=>{r.currentTime=this.numberAttribute("initial-time",0)/1e3}),i("canplay",()=>this.notifyPrepared()),i("loadeddata",()=>{this.firstFrame||(this.firstFrame=!0,this.emit("firstframe"))}),i("playing",()=>{this.stopped=!1,this.setPlaybackState(1)}),i("pause",()=>this.setPlaybackState(2*!this.stopped)),i("seeked",()=>this.emit("seek")),i("timeupdate",()=>this.emit("timeupdate",{current:1e3*r.currentTime,total:Number.isFinite(r.duration)?1e3*r.duration:0})),i("ended",()=>{this.stopped=!0,this.setPlaybackState(0),this.emit("completion")}),i("error",()=>{var e,t;return this.reportError((null==(e=r.error)?void 0:e.message)||"Video resource could not be played",null==(t=r.error)?void 0:t.code)}),document.addEventListener("visibilitychange",this.handleVisibility),this.syncAttributes(),this.syncSource()}disconnectedCallback(){var e;let t=this.video;this.video=null,this.playRequest++,document.removeEventListener("visibilitychange",this.handleVisibility),t&&(t.pause(),t.removeAttribute("src"),t.load()),null==(e=this.shadowRoot)||e.replaceChildren()}attributeChangedCallback(e,t,r){this.video&&t!==r&&(["play-url","video-model","vid"].includes(e)?this.syncSource():(this.syncAttributes(),"auto-prepare"!==e||this.booleanAttribute("auto-prepare",!0)||(this.video.preload="none")))}booleanAttribute(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.getAttribute(e);return null===r?t:"false"!==r&&"0"!==r}numberAttribute(e,t){let r=this.getAttribute(e),i=null===r||""===r.trim()?0/0:Number(r);return Number.isFinite(i)&&i>=0?i:t}syncAttributes(){let e=this.video;e.muted=this.booleanAttribute("muted"),e.loop=this.booleanAttribute("loop"),e.volume=Math.min(1,this.numberAttribute("volume",1));try{e.playbackRate=this.numberAttribute("speed",1)||1,e.defaultPlaybackRate=e.playbackRate}catch(e){this.reportError(String(e))}let t=this.getAttribute("objectfit")??"contain";e.style.objectFit=["contain","cover","fill"].includes(t)?t:"contain",this.booleanAttribute("auto-prepare",!0)&&(e.preload="auto",e.controls=!0)}syncSource(){let e=this.video,t=this.getAttribute("play-url")||"";t&&e.getAttribute("src")===t||(this.playRequest++,this.prepared=this.firstFrame=!1,this.stopped=!0,this.playbackState=-1,e.pause(),e.preload=this.booleanAttribute("auto-prepare",!0)?"auto":"none",e.controls="auto"===e.preload,t?e.src=t:e.removeAttribute("src"),e.load(),queueMicrotask(()=>{this.isConnected&&this.video===e&&(this.getAttribute("play-url")||"")===t&&(t?this.emit("redirect"):(this.getAttribute("video-model")||this.getAttribute("vid"))&&this.reportError("Web VideoEngine requires play-url; video-model and vid are not supported"))}))}notifyPrepared(){var e;this.prepared||(null==(e=this.video)?void 0:e.preload)!=="auto"||(this.prepared=!0,this.emit("canplay"))}emit(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:"error"!==e}))}setPlaybackState(e){this.playbackState!==e&&(this.playbackState=e,this.emit("playbackstatechanged",{playbackState:e}))}reportError(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;this.emit("error",{errorCode:t,errorMsg:e})}getMedia(){var e;if(!(null==(e=this.video)?void 0:e.getAttribute("src")))throw Error("Web VideoEngine requires play-url");return this.video}handleVisibility=()=>{var e;document.hidden&&this.booleanAttribute("pause-on-hide")&&(null==(e=this.video)?void 0:e.getAttribute("src"))&&this.pause()};prepare(){let e=this.getMedia();e.preload="auto",e.controls=!0,this.prepared=!1,e.readyState>=3?queueMicrotask(()=>{this.video===e&&this.notifyPrepared()}):e.load()}play(){let e=this.getMedia();this.stopped=!1;let t=++this.playRequest;e.play().catch(r=>{this.video===e&&t===this.playRequest&&this.reportError(String(r))})}pause(){let e=this.getMedia();this.playRequest++,this.stopped=!1,e.pause(),this.setPlaybackState(2)}stop(){let e=this.getMedia();this.playRequest++,this.stopped=!0,e.pause(),e.currentTime=0,this.setPlaybackState(0)}seek(e){if(!e||!Number.isFinite(e.position)||e.position<0)throw Error("seek.position must be a non-negative number in milliseconds");let t=this.getMedia(),r=Math.min(e.position/1e3,Number.isFinite(t.duration)?t.duration:1/0);e.play||this.pause(),t.currentTime===r?queueMicrotask(()=>{this.video===t&&this.emit("seek")}):t.currentTime=r,e.play&&this.play()}getDuration(){let e=this.getMedia().duration;if(!Number.isFinite(e))throw Error("Video duration is not available yet");return{duration:1e3*e}}}),"object"==typeof customElements)for(let e of["x-image","filter-image"]){if(t2.has(e))continue;t2.add(e);let t=e=>{if(!(tQ in e.prototype)){var t;null==(t=e.registerPlugin)||t.call(e,t1)}},r=customElements.get(e);r?t(r):customElements.whenDefined(e).then(t)}if("object"==typeof document&&"object"==typeof customElements){let e=document.createElement("map").constructor.prototype;for(let t of["center","scale-range","polyline","polygons","circles","arcs","route-label","extra-params"])t in e||Object.defineProperty(e,t,{configurable:!0,get(){return rh(this)[t]},set(e){var r;let i=rr.get(this)??{};i[t]=e,rr.set(this,i),null==(r=rn.get(this))||r.update()}});!function(){if(customElements.get("map-marker"))return;class e extends HTMLElement{static observedAttributes=["position","anchor","alpha","rotation","enable-click","enable-drag","animate","container-position"];connectedCallback(){queueMicrotask(()=>{var e;return null==(e=rg(this))?void 0:e.updateMarkers()})}attributeChangedCallback(){var e;null==(e=rg(this))||e.updateMarkers()}refreshMarker(){var e;null==(e=rg(this))||e.updateMarkers()}}for(let t of["position","anchor","animate","container-position"])Object.defineProperty(e.prototype,t,{configurable:!0,get(){return rm(this)[t]},set(e){var r;let i=ri.get(this)??{};i[t]=e,ri.set(this,i),null==(r=rg(this))||r.updateMarkers()}});customElements.define("map-marker",e)}()}function r_(e,t){if(e&&"event"===t.type&&t.name===e1&&o(t.params)){var r;null==(r=e.sendSyncBridgeUpdate)||r.call(e,t),o(t.params.globalProps)&&(e.globalProps={...e.globalProps,...t.params.globalProps})}"function"==typeof(null==e?void 0:e.sendGlobalEvent)&&e.sendGlobalEvent("__APPLET_BRIDGE__",[t])}class rS{container;className;options;runtimeContext;bridge=null;caller;cleanupWidgetTapCapture=null;cleanupWebMapHost=null;view=null;constructor(e,t={environment:"direct"}){let r=e.container;if(!r)throw Error("Container requires a container element");this.container=r,this.className=e.className??"doubao-web-container-view",this.options=e,this.runtimeContext=t}get element(){return this.view}prepare(){this.clear()}render(e){var t,r,i,n;this.clear();let a=Date.now(),s=document.createElement("lynx-view"),l="sandbox"===this.runtimeContext.environment?this.runtimeContext.resourceRoot:(null==(t=e.applicationPackage)?void 0:t.resourceRoot)??(null==(i=this.options.runtime)||null==(r=i.packageInfo)?void 0:r.resourceRoot);l&&(s.resolveResource=e=>{let t=e.startsWith("/base/")?e.slice(1):e;return t?new URL(t,l).href:t}),s.injectStyleRules=['[doubao-component="popup"] > .popup-container { top: 0; left: 0; z-index: 1000; }'];let d=t_(e),u=tS(d);s.className=this.className,e.groupId&&s.setAttribute("lynx-group-id",e.groupId),s.dataset.containerType=d,s.dataset.webSizing=u,s.style.display="APP"===d||"TOOL"===d?"none":"block",s.style.width="100%",s.style.height="content"===u?"auto":"100%","content"===u&&s.setAttribute("height","auto"),s.initData=e.initData??{};let c={...G(),...e.globalProps??{}};this.bridge=e.bridge??(null==(n=this.options.runtime)?void 0:n.bridge)??new tf,this.caller=e.bridgeCaller??this.bridge.register(e=>r_(s,e),e.bridge||this.options.runtime?{...this.options,apiRegistry:void 0}:this.options,"APP"===d);let p=this.bridge,h=this.caller;this.view=s;let m=()=>{var t,r,i,n,l;let m,g,f,v,b,w,_,S,x,I,k,C,E,N,T,A,M;if(this.view!==s)return;"direct"===this.runtimeContext.environment&&p.beginPerformance(h,{...e,containerType:d,globalProps:c});let j="sandbox"===this.runtimeContext.environment?this.runtimeContext.syncBridgeData:p.createSyncBridgeData(h,c,this.options.fileSystemNamespace);t=this.runtimeContext.environment,m=new URL("./__doubao_web_sdk_native_modules/",(null==(r=globalThis.document)?void 0:r.baseURI)??(null==(i=globalThis.location)?void 0:i.href)??"http://localhost/").href,g=ty(new URL("applet-bridge-module.js",m)),f=ty(new URL("applet-js-module.js",m)),w={AppletBridgeModule:((b=new URLSearchParams((v=new URL(g)).hash.slice(1))).set("__doubao_sync_bridge",JSON.stringify({...j,fileSystemSnapshot:ec(),storageSnapshot:{}})),v.hash=b.toString(),v.href),AppletJSModule:f},"direct"===t&&(w.LynxConsoleModule=ty(new URL("console-module.js",m)),"APP"===d&&(w.LynxDevToolSetModule=f)),s.nativeModulesMap=w,(0,tH.B)(s),s.napiModulesMap={...s.napiModulesMap,WebSyncBridge:s.nativeModulesMap.AppletBridgeModule};let R=s.onNapiModulesCall;s.onNapiModulesCall=(e,t,r,i,n)=>("WebSyncBridge"===r&&"subscribeSyncUpdates"===e&&(s.sendSyncBridgeUpdate=n,s.sendSyncBridgeUpdate({type:"event",name:e1,params:j,timestamp:Date.now()})),null==R?void 0:R(e,t,r,i,n)),s.globalProps={...c,__DOUBAO_WEB_SDK_SYNC_BRIDGE__:j};let P={containerType:d,element:s,globalProps:c,fileSystemNamespace:j.fileSystemNamespace,environment:this.runtimeContext.environment};s.onNativeModulesCall=(e,t,r)=>p.dispatch(h,e,t,r,P),n=async e=>{let t=await p.dispatch(h,"postMessage",e,"AppletBridgeModule",P);return y(t)?t:void 0},tJ.set(s,n),s.transformVW=!0,s.transformVH="content"!==u,s.transformREM=!1,s.addEventListener("timing",e=>{let t=e.detail;o(t)&&"number"==typeof t.create_lynx_start&&Number.isFinite(t.create_lynx_start)&&t.create_lynx_start>0&&(a=t.create_lynx_start),p.dispatch(h,"postMessage",{type:"call",name:e6,params:{timing:{create_lynx_start:a,...o(t)?t:{}}},callbackId:0},"AppletBridgeModule",P)}),s.addEventListener("error",e=>{var t,r;let i;null==(t=(r=this.options).onError)||t.call(r,(null==(i=e.detail)?void 0:i.error)instanceof Error?i.error:Error(String((null==i?void 0:i.error)??i??"Unknown Container runtime error")),e)}),"WIDGET"===d&&this.options.captureWidgetTap&&(this.cleanupWidgetTapCapture=(l=this.options.onWidgetInteraction,_=0,S=e=>{e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();var t={sequence:_+=1,type:"tap"};try{Promise.resolve(null==l?void 0:l(t)).catch(()=>void 0)}catch{}},s.addEventListener("click",S,!0),()=>s.removeEventListener("click",S,!0))),s.url=tw(e),this.container.replaceChildren(s),this.cleanupWebMapHost=(I=new Map,k=new Set,C=[],E=0,N=!1,T=e=>{for(let t of e.querySelectorAll("*"))"map"!==t.localName||rn.has(t)||k.add(new rf(t)),t.shadowRoot&&A(t.shadowRoot);for(let e of k)e.element.isConnected||(e.dispose(),k.delete(e))},A=e=>{if(I.has(e)||N)return;let t=new MutationObserver(t=>{if(!(t.some(e=>{let t=e.target;return t instanceof Element&&t.closest("[data-doubao-map-surface]")})&&t.every(e=>e.target instanceof Element&&e.target.closest("[data-doubao-map-surface]"))))for(let i of(T(e),t)){let e=i.target,t=e instanceof Element?e.closest("map"):null;if(t){var r;null==(r=rn.get(t))||r.update()}}});t.observe(e,{childList:!0,subtree:!0,attributes:!0}),I.set(e,t),T(e)},(M=()=>{if(N)return;let e=s.shadowRoot??s;if(A(e),s.shadowRoot&&x!==e)for(let t of(x=e,[0,16,100,500,2e3,1e4]))C.push(setTimeout(()=>{N||T(e)},t));else s.shadowRoot||(E=requestAnimationFrame(M))})(),()=>{for(let e of(N=!0,cancelAnimationFrame(E),C))clearTimeout(e);for(let e of I.values())e.disconnect();for(let e of k)e.dispose()})};return"sandbox"===this.runtimeContext.environment?m():p.prepareStorage(h,c,this.options.fileSystemNamespace).then(m).catch(e=>{if(this.view===s){var t,r;null==(t=(r=this.options).onError)||t.call(r,e,new Event("error"))}}),s}clear(){var e,t,r,i;null==(e=this.cleanupWebMapHost)||e.call(this),this.cleanupWebMapHost=null,null==(t=this.cleanupWidgetTapCapture)||t.call(this),this.cleanupWidgetTapCapture=null,this.caller&&(null==(i=this.bridge)||i.unregister(this.caller)),this.caller=void 0,this.bridge=null,null==(r=this.view)||r.remove(),this.view=null,this.container.replaceChildren()}setVisible(e){if(this.caller){var t;null==(t=this.bridge)||t.setVisible(this.caller,e)}}sendEvent(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t=this.view,r_(t,{type:"event",name:e,params:r,timestamp:Date.now()})}sendBridgeMessage(e){r_(this.view,e)}sendGlobalEvent(e,t){var r,i;null==(i=this.view)||null==(r=i.sendGlobalEvent)||r.call(i,e,t)}updateData(e){var t,r;null==(r=this.view)||null==(t=r.updateData)||t.call(r,e)}updateGlobalProps(e){this.view&&(this.view.globalProps={...this.view.globalProps,...e})}reload(){var e,t;null==(t=this.view)||null==(e=t.reload)||e.call(t)}}let rx=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
19
+ }`};dispose(){this.attributes.disconnect(),this.stopRendering()}}let t2=new Set;var t3=r(44360);let t4=new WeakMap;function t6(e,t,r){let i=new Map;for(let n of t){let t=Reflect.get(e,n);i.set(n,Object.getOwnPropertyDescriptor(e,n)),Object.defineProperty(e,n,{configurable:!0,writable:!0,value(){for(var e=arguments.length,i=Array(e),n=0;n<e;n++)i[n]=arguments[n];return r(),Reflect.apply(t,this,i)}})}return()=>{for(let[t,r]of i)r?Object.defineProperty(e,t,r):Reflect.deleteProperty(e,t)}}class t5{element;placeholder=document.createComment("map-marker");parent;cleanupElement;constructor(e){this.element=e;let t=e.parentNode;if(!t)throw Error("Web Map Marker requires a component parent");this.parent=t;let r=t4.get(t);if(!r){let e=new Set;r={portals:e,cleanup:t6(t,["appendChild","insertBefore","removeChild","replaceChild","append","prepend","replaceChildren"],()=>{for(let t of e)t.restore()})},t4.set(t,r)}r.portals.add(this),this.cleanupElement=t6(e,["remove","replaceWith","before","after"],()=>{for(let e of r.portals)e.restore()})}get connected(){return this.element.parentNode===this.parent?this.element.isConnected:this.placeholder.isConnected}mount(e){if(this.element.parentNode!==e){if(this.element.parentNode!==this.parent)throw Error("Web Map Marker component parent changed");Node.prototype.insertBefore.call(this.parent,this.placeholder,this.element),e.appendChild(this.element)}}restore(){this.placeholder.parentNode===this.parent&&Node.prototype.replaceChild.call(this.parent,this.element,this.placeholder)}destroy(){this.restore(),this.cleanupElement();let e=t4.get(this.parent);null==e||e.portals.delete(this),(null==e?void 0:e.portals.size)===0&&(e.cleanup(),t4.delete(this.parent))}}class t8{element;namespace;map;onError;onClick;content=document.createElement("div");portal;originalStyles=new Map;styleObserver=new MutationObserver(()=>this.syncZIndex());marker;defaultZIndex;positionKey;optionsKey;waitingForPosition=!1;syncing=!1;disposed=!1;constructor(e,t,r,i,n){this.element=e,this.namespace=t,this.map=r,this.onError=i,this.onClick=n,this.portal=new t5(e),this.content.style.cssText="width:0;height:0;overflow:visible;",this.styleObserver.observe(e,{attributes:!0,attributeFilter:["style","class"]})}get connected(){return this.portal.connected}sync(e){if(!this.disposed&&!this.syncing){this.syncing=!0;try{if(!e.position&&!e.containerPosition){var t;this.portal.restore(),null==(t=this.marker)||t.destroy(),this.marker=void 0,this.optionsKey=void 0,this.positionKey=void 0,this.waitingForPosition=!0,this.style("visibility","hidden");return}this.waitingForPosition&&(this.style("visibility",this.originalStyles.get("visibility")??""),this.waitingForPosition=!1),this.style("position","relative"),"inline"===getComputedStyle(this.element).display&&this.style("display","inline-block"),this.element.style.width||this.style("width","max-content"),this.style("transform",`translate(${-100*e.anchor[0]}%, ${-100*e.anchor[1]}%)`);let r="amap"===this.namespace.getProvider(),i={content:this.content,containerPosition:e.containerPosition?[e.containerPosition.x,e.containerPosition.y]:null,anchor:r?"top-left":0,angle:e.rotation,opacity:e.alpha,clickable:e.clickable,draggable:e.draggable,bubble:!e.clickable,animation:e.animate??(r?{scale:{from:1,to:1,duration:0}}:null)},n=JSON.stringify(e.position);this.marker&&n===this.positionKey||(i.position=e.position&&[e.position.longitude,e.position.latitude]),this.portal.mount(this.content);let a=JSON.stringify(e);if(this.marker&&this.optionsKey===a)return void this.syncZIndex();this.optionsKey=a,this.marker?this.marker.setOptions(i):(this.marker=new this.namespace.Marker(i),this.defaultZIndex=this.marker.getzIndex(),this.marker.on("click",this.onClick)),this.syncZIndex(),this.marker.getMap()!==this.map&&this.marker.setMap(this.map),this.positionKey=n}catch(e){this.onError(e)}finally{this.syncing=!1}}}syncZIndex(){if(this.marker&&!this.disposed)try{let e=Number.parseInt(getComputedStyle(this.element).zIndex,10),t=Number.isFinite(e)?e:this.defaultZIndex;void 0!==t&&t!==this.marker.getzIndex()&&this.marker.setzIndex(t)}catch(e){this.onError(e)}}style(e,t){this.originalStyles.has(e)||this.originalStyles.set(e,this.element.style.getPropertyValue(e)),this.element.style.getPropertyValue(e)!==t&&this.element.style.setProperty(e,t)}destroy(){var e;if(!this.disposed)for(let[t,r]of(this.disposed=!0,this.styleObserver.disconnect(),this.portal.destroy(),null==(e=this.marker)||e.destroy(),this.originalStyles))this.element.style.setProperty(t,r)}}let t9=e=>{let{longitude:t,latitude:r}=e;return[t,r]};function t7(e,t,r,i,n){let a=new Set(t.map(e=>{let{id:t}=e;return t}));for(let[t,r]of e)a.has(t)||(r.destroy(),e.delete(t));for(let a of t)try{let t=r(a),n=e.get(a.id);if(n){let{id:e,...r}=t;n.setOptions(r)}else e.set(a.id,i(t,a))}catch(e){n(e)}}class re{namespace;map;onError;onPolylineClick;polylines=new Map;polygons=new Map;circles=new Map;arcs=new Map;routeLabels=new Map;warnings=new Set;constructor(e,t,r,i){this.namespace=e,this.map=t,this.onError=r,this.onPolylineClick=i}warn(e){this.warnings.has(e)||(this.warnings.add(e),this.onError(Error(`Web Map 暂不支持 ${e}`)))}add(e){e.on("warning",e=>{this.onError(e.error??Error(e.reason??e.feature??"Web Map 覆盖物降级"))});try{return this.map.add(e),e}catch(t){throw e.destroy(),t}}sync(e){var t;let r=function(e){let t=new Map,r=new Set;for(let n of e){var i;if(!n.id.startsWith("__doubao_polyline_arrow__:"))continue;let a=null==(i=n.edgeTextureAssets)?void 0:i.find(e=>{let{id:t}=e;return"__doubao_polyline_arrow_texture__"===t});if(a)try{let i=decodeURIComponent(n.id.slice(26));e.some(e=>e.id===i)&&(t.set(i,{iconPath:a.url}),r.add(n))}catch{}}return e.filter(e=>!r.has(e)).map(e=>({...e,arrow:t.get(e.id)??e.arrow}))}(e.polyline??[]),i=this.namespace.supports("Polyline.edgeTexture").supported,n=this.namespace.supports("RouteLabel").supported;!i&&r.some(e=>{var t,r;return(null==(t=e.edgeTexture)?void 0:t.length)||(null==(r=e.edgeTextureAssets)?void 0:r.length)})&&this.warn("当前图商的 polyline 纹理"),!n&&(null==(t=e.routeLabel)?void 0:t.length)&&this.warn("当前图商的 routeLabel"),r.some(e=>e.collideDetection)&&this.warn("polyline POI 碰撞避让"),t7(this.polylines,r,e=>{var t;return{id:e.id,path:e.points.map(t9),strokeColors:e.edgeColor??[],arrow:e.arrow??null,edgeTexture:i?e.edgeTexture??[]:[],edgeTextureAssets:i?e.edgeTextureAssets??[]:[],strokeColor:(null==(t=e.edgeColor)?void 0:t[0])??"#0066ff",strokeWeight:e.width??2,strokeStyle:e.dottedLine?"dashed":"solid",lineCap:"line_cap_round"===e.lineCapType?"round":"butt",lineJoin:"line_join_round"===e.lineJoinType?"round":"line_join_miter"===e.lineJoinType?"miter":"bevel",zIndex:e.zIndex??0}},(e,t)=>{let r=new this.namespace.Polyline(e);return r.on("click",()=>this.onPolylineClick(t.id)),this.add(r)},this.onError),t7(this.polygons,e.polygons??[],e=>({id:e.id,path:e.points.map(t9),fillColor:e.fillColor,strokeColor:e.strokeColor,strokeWeight:e.strokeWidth,strokeStyle:e.dottedLine?"dashed":"solid",zIndex:e.zIndex}),e=>{let t=new this.namespace.Polygon(e);return this.add(t)},this.onError),t7(this.circles,e.circles??[],e=>({id:e.id,center:t9(e.center),radius:e.radius,fillColor:e.fillColor,strokeColor:e.strokeColor,strokeWeight:e.strokeWidth,zIndex:e.zIndex}),e=>{let t=new this.namespace.Circle(e);return this.add(t)},this.onError),t7(this.arcs,e.arcs??[],e=>({id:e.id,path:[t9(e.start),t9(e.mid??e.middle),t9(e.end)],strokeColor:e.color??"#0066ff",strokeWeight:e.width??2,zIndex:e.zIndex}),e=>{let t=new this.namespace.Arc(e);return this.add(t)},this.onError),t7(this.routeLabels,n?e.routeLabel??[]:[],e=>({id:e.id,path:e.points.map(t9),text:e.text,textColor:e.textColor??"#000000",fontSize:e.fontSize??12,fontWeight:e.fontWeight??"normal",borderColor:e.borderColor??"#cccccc",borderWidth:e.borderWidth??0,zIndex:e.zIndex??0}),e=>this.add(new this.namespace.RouteLabel(e)),this.onError)}destroy(){for(let e of[this.polylines,this.polygons,this.circles,this.arcs,this.routeLabels]){for(let t of e.values())t.destroy();e.clear()}}}let rt={baidu:{provider:"baidu",security:{baidu:{serviceHost:"https://api.doubao-dev.com/_BMapService/"}}},amap:{provider:"amap",key:{amap:"f57928bd7156da61d512795ec5c0c968"},security:{amap:{serviceHost:"https://api.doubao-dev.com/_AMapService"}}}},rr=new WeakMap,ri=new WeakMap,rn=new WeakMap,ra=new WeakMap;function rs(e,t,r){if(t in r)return r[t];let i=e.getAttribute(t);if(i)try{return JSON.parse(i)}catch{return}}function ro(e,t,r){let i=Number(e.getAttribute(t));return Number.isFinite(i)&&e.hasAttribute(t)?i:r}function rl(e,t,r){let i=e.getAttribute(t);return null===i?r:"false"!==i&&"0"!==i}function rd(e){let{longitude:t,latitude:r}=e;return[t,r]}function ru(e){return{longitude:e.lng,latitude:e.lat}}function rc(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};e.dispatchEvent(new CustomEvent(t,{detail:r,bubbles:!1}))}function rp(e,t){let r=t instanceof Error?t:Error(String(t));console.error("[Doubao Map]",r.message),e.dispatchEvent(new CustomEvent("error",{detail:{error:r}}))}function rh(e){return rr.get(e)??{}}function rm(e){return ri.get(e)??{}}function rg(e){let t=ra.get(e);if(t)return t;let r=e.closest("map");return r?rn.get(r):void 0}class rf{element;map;namespace;syncingMarkers=!1;overlays;markers=new Map;cleanupTileLoad;surface;resize;sizeFrame=0;loading=!1;initializationBlocked=!1;disposed=!1;ready=!1;lastAttributes="";lastOverlays="";lastStyle="";lastLogoPosition="";warnings=new Set;constructor(e){var t;if(this.element=e,rn.set(e,this),this.installMethods(),"inline"===getComputedStyle(e).display&&(e.style.display="block"),"static"===getComputedStyle(e).position&&(e.style.position="relative"),e.style.overflow="hidden",this.resize="function"==typeof ResizeObserver?new ResizeObserver(()=>this.initialize()):void 0,null==(t=this.resize)||t.observe(e),!this.resize){let e=()=>{this.disposed||this.map||this.loading||this.initializationBlocked||(this.initialize(),this.sizeFrame=requestAnimationFrame(e))};this.sizeFrame=requestAnimationFrame(e)}this.initialize()}warn(e){this.warnings.has(e)||(this.warnings.add(e),rp(this.element,Error(`Web Map 暂不支持 ${e}`)))}getMapConfig(){let e=rs(this.element,"extra-params",rh(this.element));return rt[(null==e?void 0:e.useAliMap)===!0?"amap":"baidu"]}initialize(){var e;if(this.disposed||this.loading||this.initializationBlocked||this.map||this.element.clientWidth<=0||this.element.clientHeight<=0)return;let t=this.getMapConfig(),r=(null==(e=this.element.ownerDocument.location)?void 0:e.hostname)??"";if("baidu"===t.provider&&(tb(r)||"[::1]"===r||r.endsWith(".localhost"))){this.initializationBlocked=!0,rp(this.element,Error("当前豆包百度地图账号未授权本地域名,请使用获准域名的 sandbox 调试地图。"));return}this.loading=!0;let i=document.createElement("div");i.dataset.doubaoMapSurface="",i.style.cssText="position:absolute;inset:0;width:100%;height:100%;",this.element.prepend(i),this.surface=i,Promise.resolve().then(()=>t3.H3.load(t)).then(e=>{this.disposed||this.createMap(e,i)}).catch(e=>{this.disposed||rp(this.element,e),i.remove(),this.surface=void 0}).finally(()=>{this.loading=!1})}createMap(e,t){let r=this.element,i=rs(r,"center",rh(r)),n=rs(r,"scale-range",rh(r));try{let a=new e.Map(t,{center:i&&rd(i),zoom:ro(r,"scale",16),zooms:n??[3,20],rotation:ro(r,"rotate",0),logoPosition:r.getAttribute("logo-position")||"bottom-left",eventContext:!0,enableNativeInteraction:rl(r,"native-interaction-enabled",!0),showScale:rl(r,"enable-scale-controls",!1),zoomEnable:rl(r,"enable-scale",!0),dragEnable:rl(r,"enable-drag",!0),rotateEnable:rl(r,"enable-rotate",!1)});this.map=a,this.namespace=e,this.overlays=new re(e,a,e=>rp(r,e),e=>rc(r,"clickpolyline",{id:e}));let s=!1,o=()=>{this.disposed||s||(s=!0,rc(r,"maptileload"))};if("baidu"===e.getProvider()){let e=a.getNative();e.addEventListener("firsttileloaded",o),this.cleanupTileLoad=()=>e.removeEventListener("firsttileloaded",o)}let l=()=>{this.disposed||this.ready||(this.ready=!0,rc(r,"mapload"),"amap"===e.getProvider()&&o(),this.update(!0))};a.on("complete",l),a.on("click",e=>{e.lnglat&&rc(r,"clickmap",{point:ru(e.lnglat)})}),a.on("error",e=>rp(r,e)),a.on("warning",e=>{rp(r,Error(e.reason??e.feature??"Web Map 能力降级"))});let d=(e,t,i)=>{if(!a.isReady())return;let n=t.context,s=(null==n?void 0:n.bounds)??a.getBounds();rc(r,"regionchange",{type:(null==n?void 0:n.phase)??e,...i?{causedBy:i}:{},center:ru((null==n?void 0:n.center)??a.getCenter()),scale:(null==n?void 0:n.zoom)??a.getZoom(),rotate:(null==n?void 0:n.rotation)??a.getRotation(),region:{southwest:ru(s.getSouthWest()),northeast:ru(s.getNorthEast())}})};a.on("movestart",e=>d("begin",e,"drag")),a.on("moveend",e=>d("end",e,"drag")),a.on("zoomstart",e=>d("begin",e,"scale")),a.on("zoomend",e=>d("end",e,"scale")),"baidu"!==e.getProvider()&&(a.on("rotatestart",e=>d("begin",e)),a.on("rotateend",e=>d("end",e))),a.isReady()&&l()}catch(e){var a,s,o;null==(a=this.cleanupTileLoad)||a.call(this),null==(s=this.overlays)||s.destroy(),null==(o=this.map)||o.destroy(),this.map=void 0,t.remove(),rp(r,e)}}update(){var e,t;let r=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!this.ready||!this.map||this.disposed)return;let i=this.element,n=this.map,a=rh(i),s=JSON.stringify({center:rs(i,"center",a),scale:i.getAttribute("scale"),scales:rs(i,"scale-range",a),rotate:i.getAttribute("rotate"),showScale:i.getAttribute("enable-scale-controls"),enableScale:i.getAttribute("enable-scale"),enableDrag:i.getAttribute("enable-drag"),enableRotate:i.getAttribute("enable-rotate"),nativeInteraction:i.getAttribute("native-interaction-enabled")});if(r||s!==this.lastAttributes){this.lastAttributes=s;try{let e=rs(i,"scale-range",a);e&&n.setZooms(e);let t=rs(i,"center",a);t?n.setZoomAndCenter(ro(i,"scale",16),rd(t)):n.setZoom(ro(i,"scale",16)),n.setRotation(ro(i,"rotate",0)),n.setShowScale(rl(i,"enable-scale-controls",!1)),n.setNativeInteractionEnabled(rl(i,"native-interaction-enabled",!0)),n.setStatus({zoomEnable:rl(i,"enable-scale",!0),dragEnable:rl(i,"enable-drag",!0),rotateEnable:rl(i,"enable-rotate",!1)})}catch(e){rp(i,e)}}let o=i.getAttribute("map-style")||"normal-light";if(o!==this.lastStyle){this.lastStyle=o;try{n.setMapStyle((null==(e=this.namespace)?void 0:e.getProvider())==="baidu"?{styleId:o}:o)}catch(e){rp(i,e)}}rl(i,"enable-tilt",!1)&&this.warn("地图倾斜");let l=i.getAttribute("logo-position")||"bottom-left";if(l!==this.lastLogoPosition){this.lastLogoPosition=l;try{n.setLogoPosition(l)}catch(e){rp(i,e)}}let d={polyline:rs(i,"polyline",a),polygons:rs(i,"polygons",a),circles:rs(i,"circles",a),arcs:rs(i,"arcs",a),routeLabel:rs(i,"route-label",a)},u=JSON.stringify(d);(r||u!==this.lastOverlays)&&(this.lastOverlays=u,null==(t=this.overlays)||t.sync(d)),this.updateMarkers()}updateMarkers(){let e=this.map,t=this.namespace;if((null==e?void 0:e.isReady())&&t&&!this.syncingMarkers){this.syncingMarkers=!0;try{let r=new Set([...this.element.querySelectorAll("map-marker")].filter(e=>e.closest("map")===this.element));for(let[e,t]of this.markers)r.has(e)&&t.connected||(r.delete(e),t.destroy(),this.markers.delete(e),ra.delete(e));for(let i of r){let r=rm(i);rl(i,"enable-collide-with-poi",!1)&&this.warn("marker POI 碰撞避让");let n=rs(i,"container-position",r),a=rl(i,"enable-drag",!1),s=!n&&"amap"===t.getProvider();a&&!s&&this.warn(n?"固定屏幕位置的 marker 拖动":"百度自定义内容 marker 拖动");let o=rl(i,"enable-click",!0);a&&!o&&this.warn("关闭点击时的 marker 拖动");let l=this.markers.get(i);l||(l=new t8(i,t,e,e=>rp(this.element,e),()=>rc(i,"clickmarker")),this.markers.set(i,l),ra.set(i,this)),l.sync({position:rs(i,"position",r),containerPosition:n,anchor:rs(i,"anchor",r)??[.5,1],rotation:ro(i,"rotation",0),alpha:ro(i,"alpha",1),clickable:o,draggable:a&&s&&o,animate:rs(i,"animate",r)})}}finally{this.syncingMarkers=!1}}}getMap(){var e;if(!(null==(e=this.map)?void 0:e.isReady()))throw Error("Web Map 尚未加载完成");return this.map}installMethods(){Object.assign(this.element,{setCenter:e=>{let{center:t,animated:r,duration:i}=e;return this.getMap().setCenter(rd(t),!1===r,i)},getCenter:()=>ru(this.getMap().getCenter()),setScale:e=>{let{scale:t,animated:r,duration:i}=e;return this.getMap().setZoom(t,!1===r,i)},getScale:()=>({scale:this.getMap().getZoom()}),getBound:()=>{let e=this.getMap().getBounds();return{southwest:ru(e.getSouthWest()),northeast:ru(e.getNorthEast())}},setBound:e=>{let{southwest:t,northeast:r,animated:i,duration:n}=e;return this.getMap().setBounds([t.longitude,t.latitude,r.longitude,r.latitude],!1===i,void 0,n)},fitPoints:e=>{let{points:t,padding:r=[0,0,0,0],animated:i,duration:n}=e;return this.getMap().setFitView(t.map(rd),!1===i,[r[2]??0,r[3]??0,r[0]??0,r[1]??0],void 0,n)},setAnchor:e=>{let{position:t}=e;return this.getMap().setAnchor([t.x,t.y])},latLngToPx:e=>{let{latLng:t}=e,r=this.getMap().lngLatToContainer(rd(t));return{x:r.x,y:r.y}},pxToLatLng:e=>{let{x:t,y:r}=e;return{latLng:ru(this.getMap().containerToLngLat([t,r]))}}})}dispose(){var e,t,r,i,n;if(!this.disposed){for(let[r,i]of(this.disposed=!0,null==(e=this.resize)||e.disconnect(),cancelAnimationFrame(this.sizeFrame),null==(t=this.cleanupTileLoad)||t.call(this),this.markers))ra.delete(r),i.destroy();this.markers.clear(),null==(r=this.overlays)||r.destroy(),null==(i=this.map)||i.destroy(),null==(n=this.surface)||n.remove(),rn.delete(this.element)}}}class rv{element;static observedAttributes=[];constructor(e){this.element=e}forwardLinkEvent=e=>{this.element.dispatchEvent(new CustomEvent("link",{detail:e.detail,bubbles:!0,composed:!0}))};connectedCallback(){this.element.addEventListener("bindlink",this.forwardLinkEvent);let e=this.element.markdownStyle??{};this.element.markdownStyle={...e,link:{...e.link,textDecoration:"none"},orderedList:{...e.orderedList,paddingLeft:0},unorderedList:{...e.unorderedList,paddingLeft:0}}}}function ry(e){var t;null==(t=e.registerPlugin)||t.call(e,rv)}let rb="x-video-engine",rw=globalThis.HTMLElement??class{};if("object"!=typeof customElements||customElements.get(tV)||customElements.define(tV,class e extends tY{static observedAttributes=["src"];#e=null;#t=null;#r=!1;messageOrigin;connectedCallback(){this.#r=!0,this.style.display||(this.style.display="block"),this.#i(),this.#n()}disconnectedCallback(){var e;this.#r=!1,this.#a(),null==(e=this.#e)||e.remove(),this.#e=null,window.removeEventListener("message",this.#s)}attributeChangedCallback(e){"src"===e&&this.#r&&this.#n()}get src(){return this.getAttribute("src")}set src(e){null===e?this.removeAttribute("src"):this.setAttribute("src",e)}reload(){this.#n(!0)}postMessage(e){let t=o(e)?e.data:void 0;this.#o({type:"event",name:"message",params:{data:t},timestamp:Date.now()})}eval(e){let t=o(e)&&"string"==typeof e.func?e.func:"";if(t)try{if(this.messageOrigin){var r,i;null==(i=this.#e)||null==(r=i.contentWindow)||r.postMessage({type:"__doubao_web_view_eval__",code:t},this.messageOrigin);return}let e=this.#l();null==e||e.eval(t)}catch{}}onGoBack(){return{consumed:!1}}#i(){if(this.#e)return this.#e;let e=this.shadowRoot??this.attachShadow({mode:"open"}),t=document.createElement("iframe");return t.style.cssText="display:block;width:100%;height:100%;border:none;",t.addEventListener("load",this.#d),t.addEventListener("error",this.#u),e.replaceChildren(t),this.#e=t,window.addEventListener("message",this.#s),t}#n(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.#i(),r=this.getAttribute("src");if(!r)return;let i=tK(r);this.messageOrigin="window"===i.messageTransport?new URL(i.url,document.baseURI).origin:void 0,(e||t.getAttribute("src")!==i.url)&&(this.#a(),t.toggleAttribute("credentialless",!0===i.credentialless),t.src=i.url)}#a(){var e;null==(e=this.#t)||e.close(),this.#t=null}#l(){try{var e;let t=(null==(e=this.#e)?void 0:e.contentWindow)??null;return null==t||t.document,t}catch{return null}}#d=()=>{this.messageOrigin||(this.#c(),this.#p(),this.#h()),this.#m("load",{url:this.getAttribute("src")??""})};#u=()=>{this.#m("error",{errorMsg:`Failed to load ${this.getAttribute("src")??""}`,errorCode:-1})};#s=e=>{if(!this.#e||e.source!==this.#e.contentWindow||this.messageOrigin&&e.origin!==this.messageOrigin||e.data===tG)return;let t=tZ(e.data);this.#g(t)||this.#f(tX(e.data))};#c(){var e;this.#a();let t=null==(e=this.#e)?void 0:e.contentWindow;if(!t)return;let r=new MessageChannel;r.port1.onmessage=e=>{e.data!==tG&&this.#g(tZ(e.data))},this.#t=r.port1,t.postMessage("__channel_init__","*",[r.port2])}#p(){let e=this.#l();e&&!e.AppletBridgeModule&&(e.AppletBridgeModule={postMessage:e=>(this.#g(tZ(e)),Promise.resolve({})),postMessageSync:e=>{let t=tZ(e);return v(t)?S(t,"Sync AppletBridgeModule APIs are not supported in Doubao Web SDK web-view"):void 0}})}#h(){let e=this.#l();e&&this.#f(JSON.stringify({type:"__doubao_web_view_set_title__",title:e.document.title||""}))}#g(e){if(o(e)&&"event"===e.type)return"__bridge_ready__"===e.name;if(!v(e))return!1;if("doubao.postMessage"===e.name){let t=o(e.params)?e.params.data:void 0;return this.#f(tX(t)),this.#o(_(e,{})),!0}return this.#v(e),!0}async #v(e){let t=function(e){let t=e;for(;t;){if(t instanceof Element){let e=tJ.get(t);if(e)return e}let e=t.parentNode;t=e instanceof ShadowRoot?e.host:e}}(this);if(!t)return void this.#o(S(e,`API ${e.name} is not available in this web-view host`));let r=await t(e);this.#o(r??S(e,`API ${e.name} is not implemented in Doubao Web SDK`))}#o(e){var t,r,i;let n=JSON.stringify(e);if(this.messageOrigin){null==(i=this.#e)||null==(r=i.contentWindow)||r.postMessage({type:"__doubao_web_view_message__",payload:n},this.messageOrigin);return}if(this.#t)return void this.#t.postMessage(n);let a=this.#l();null==a||null==(t=a.onWebViewMessage)||t.call(a,n)}#f(e){this.#m("message",{msg:e,data:e})}#m(e,t){for(let r of[e,`bind${e}`])this.dispatchEvent(new CustomEvent(r,{bubbles:!0,composed:!0,detail:t}))}}),"object"==typeof customElements&&!a){let e=customElements.get("x-markdown");e?(ry(e),a=Promise.resolve()):a=customElements.whenDefined("x-markdown").then(e=>{ry(e)})}if("object"!=typeof customElements||customElements.get(rb)||customElements.define(rb,class e extends rw{static observedAttributes=["play-url","video-model","vid","auto-prepare","initial-time","objectfit","muted","loop","volume","speed"];video=null;prepared=!1;firstFrame=!1;stopped=!0;playbackState=-1;playRequest=0;connectedCallback(){if(this.video)return;let e=this.shadowRoot??this.attachShadow({mode:"open"}),t=document.createElement("style");t.textContent=":host{display:block;width:100%;height:100%}video{display:block;width:100%;height:100%}";let r=document.createElement("video");this.video=r,r.playsInline=!0,e.replaceChildren(t,r);let i=(e,t)=>r.addEventListener(e,e=>{e.stopPropagation(),this.video===r&&this.isConnected&&t()});i("loadedmetadata",()=>{r.currentTime=this.numberAttribute("initial-time",0)/1e3}),i("canplay",()=>this.notifyPrepared()),i("loadeddata",()=>{this.firstFrame||(this.firstFrame=!0,this.emit("firstframe"))}),i("playing",()=>{this.stopped=!1,this.setPlaybackState(1)}),i("pause",()=>this.setPlaybackState(2*!this.stopped)),i("seeked",()=>this.emit("seek")),i("timeupdate",()=>this.emit("timeupdate",{current:1e3*r.currentTime,total:Number.isFinite(r.duration)?1e3*r.duration:0})),i("ended",()=>{this.stopped=!0,this.setPlaybackState(0),this.emit("completion")}),i("error",()=>{var e,t;return this.reportError((null==(e=r.error)?void 0:e.message)||"Video resource could not be played",null==(t=r.error)?void 0:t.code)}),document.addEventListener("visibilitychange",this.handleVisibility),this.syncAttributes(),this.syncSource()}disconnectedCallback(){var e;let t=this.video;this.video=null,this.playRequest++,document.removeEventListener("visibilitychange",this.handleVisibility),t&&(t.pause(),t.removeAttribute("src"),t.load()),null==(e=this.shadowRoot)||e.replaceChildren()}attributeChangedCallback(e,t,r){this.video&&t!==r&&(["play-url","video-model","vid"].includes(e)?this.syncSource():(this.syncAttributes(),"auto-prepare"!==e||this.booleanAttribute("auto-prepare",!0)||(this.video.preload="none")))}booleanAttribute(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.getAttribute(e);return null===r?t:"false"!==r&&"0"!==r}numberAttribute(e,t){let r=this.getAttribute(e),i=null===r||""===r.trim()?0/0:Number(r);return Number.isFinite(i)&&i>=0?i:t}syncAttributes(){let e=this.video;e.muted=this.booleanAttribute("muted"),e.loop=this.booleanAttribute("loop"),e.volume=Math.min(1,this.numberAttribute("volume",1));try{e.playbackRate=this.numberAttribute("speed",1)||1,e.defaultPlaybackRate=e.playbackRate}catch(e){this.reportError(String(e))}let t=this.getAttribute("objectfit")??"contain";e.style.objectFit=["contain","cover","fill"].includes(t)?t:"contain",this.booleanAttribute("auto-prepare",!0)&&(e.preload="auto",e.controls=!0)}syncSource(){let e=this.video,t=this.getAttribute("play-url")||"";t&&e.getAttribute("src")===t||(this.playRequest++,this.prepared=this.firstFrame=!1,this.stopped=!0,this.playbackState=-1,e.pause(),e.preload=this.booleanAttribute("auto-prepare",!0)?"auto":"none",e.controls="auto"===e.preload,t?e.src=t:e.removeAttribute("src"),e.load(),queueMicrotask(()=>{this.isConnected&&this.video===e&&(this.getAttribute("play-url")||"")===t&&(t?this.emit("redirect"):(this.getAttribute("video-model")||this.getAttribute("vid"))&&this.reportError("Web VideoEngine requires play-url; video-model and vid are not supported"))}))}notifyPrepared(){var e;this.prepared||(null==(e=this.video)?void 0:e.preload)!=="auto"||(this.prepared=!0,this.emit("canplay"))}emit(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:"error"!==e}))}setPlaybackState(e){this.playbackState!==e&&(this.playbackState=e,this.emit("playbackstatechanged",{playbackState:e}))}reportError(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;this.emit("error",{errorCode:t,errorMsg:e})}getMedia(){var e;if(!(null==(e=this.video)?void 0:e.getAttribute("src")))throw Error("Web VideoEngine requires play-url");return this.video}handleVisibility=()=>{var e;document.hidden&&this.booleanAttribute("pause-on-hide")&&(null==(e=this.video)?void 0:e.getAttribute("src"))&&this.pause()};prepare(){let e=this.getMedia();e.preload="auto",e.controls=!0,this.prepared=!1,e.readyState>=3?queueMicrotask(()=>{this.video===e&&this.notifyPrepared()}):e.load()}play(){let e=this.getMedia();this.stopped=!1;let t=++this.playRequest;e.play().catch(r=>{this.video===e&&t===this.playRequest&&this.reportError(String(r))})}pause(){let e=this.getMedia();this.playRequest++,this.stopped=!1,e.pause(),this.setPlaybackState(2)}stop(){let e=this.getMedia();this.playRequest++,this.stopped=!0,e.pause(),e.currentTime=0,this.setPlaybackState(0)}seek(e){if(!e||!Number.isFinite(e.position)||e.position<0)throw Error("seek.position must be a non-negative number in milliseconds");let t=this.getMedia(),r=Math.min(e.position/1e3,Number.isFinite(t.duration)?t.duration:1/0);e.play||this.pause(),t.currentTime===r?queueMicrotask(()=>{this.video===t&&this.emit("seek")}):t.currentTime=r,e.play&&this.play()}getDuration(){let e=this.getMedia().duration;if(!Number.isFinite(e))throw Error("Video duration is not available yet");return{duration:1e3*e}}}),"object"==typeof customElements)for(let e of["x-image","filter-image"]){if(t2.has(e))continue;t2.add(e);let t=e=>{if(!(tQ in e.prototype)){var t;null==(t=e.registerPlugin)||t.call(e,t1)}},r=customElements.get(e);r?t(r):customElements.whenDefined(e).then(t)}if("object"==typeof document&&"object"==typeof customElements){let e=document.createElement("map").constructor.prototype;for(let t of["center","scale-range","polyline","polygons","circles","arcs","route-label","extra-params"])t in e||Object.defineProperty(e,t,{configurable:!0,get(){return rh(this)[t]},set(e){var r;let i=rr.get(this)??{};i[t]=e,rr.set(this,i),null==(r=rn.get(this))||r.update()}});!function(){if(customElements.get("map-marker"))return;class e extends HTMLElement{static observedAttributes=["position","anchor","alpha","rotation","enable-click","enable-drag","animate","container-position"];connectedCallback(){queueMicrotask(()=>{var e;return null==(e=rg(this))?void 0:e.updateMarkers()})}attributeChangedCallback(){var e;null==(e=rg(this))||e.updateMarkers()}refreshMarker(){var e;null==(e=rg(this))||e.updateMarkers()}}for(let t of["position","anchor","animate","container-position"])Object.defineProperty(e.prototype,t,{configurable:!0,get(){return rm(this)[t]},set(e){var r;let i=ri.get(this)??{};i[t]=e,ri.set(this,i),null==(r=rg(this))||r.updateMarkers()}});customElements.define("map-marker",e)}()}function r_(e,t){if(e&&"event"===t.type&&t.name===e1&&o(t.params)){var r;null==(r=e.sendSyncBridgeUpdate)||r.call(e,t),o(t.params.globalProps)&&(e.globalProps={...e.globalProps,...t.params.globalProps})}"function"==typeof(null==e?void 0:e.sendGlobalEvent)&&e.sendGlobalEvent("__APPLET_BRIDGE__",[t])}class rS{container;className;options;runtimeContext;bridge=null;caller;cleanupWidgetTapCapture=null;cleanupWebMapHost=null;view=null;constructor(e,t={environment:"direct"}){let r=e.container;if(!r)throw Error("Container requires a container element");this.container=r,this.className=e.className??"doubao-web-container-view",this.options=e,this.runtimeContext=t}get element(){return this.view}prepare(){this.clear()}render(e){var t,r,i,n;this.clear();let a=Date.now(),s=document.createElement("lynx-view"),l="sandbox"===this.runtimeContext.environment?this.runtimeContext.resourceRoot:(null==(t=e.applicationPackage)?void 0:t.resourceRoot)??(null==(i=this.options.runtime)||null==(r=i.packageInfo)?void 0:r.resourceRoot);l&&(s.resolveResource=e=>{let t=e.startsWith("/base/")?e.slice(1):e;return t?new URL(t,l).href:t}),s.injectStyleRules=['[doubao-component="popup"] > .popup-container { top: 0; left: 0; z-index: 1000; }'];let d=t_(e),u=tS(d);s.className=this.className,e.groupId&&s.setAttribute("lynx-group-id",e.groupId),s.dataset.containerType=d,s.dataset.webSizing=u,s.style.display="APP"===d||"TOOL"===d?"none":"block",s.style.width="100%",s.style.height="content"===u?"auto":"100%","content"===u&&s.setAttribute("height","auto"),s.initData=e.initData??{};let c={...G(),...e.globalProps??{}};this.bridge=e.bridge??(null==(n=this.options.runtime)?void 0:n.bridge)??new tf,this.caller=e.bridgeCaller??this.bridge.register(e=>r_(s,e),e.bridge||this.options.runtime?{...this.options,apiRegistry:void 0}:this.options,"APP"===d);let p=this.bridge,h=this.caller;this.view=s;let m=()=>{var t,r,i,n,l;let m,g,f,v,b,w,_,S,x,I,k,C,E,N,T,A,M;if(this.view!==s)return;"direct"===this.runtimeContext.environment&&p.beginPerformance(h,{...e,containerType:d,globalProps:c});let j="sandbox"===this.runtimeContext.environment?this.runtimeContext.syncBridgeData:p.createSyncBridgeData(h,c,this.options.fileSystemNamespace);t=this.runtimeContext.environment,m=new URL("./__doubao_web_sdk_native_modules/",(null==(r=globalThis.document)?void 0:r.baseURI)??(null==(i=globalThis.location)?void 0:i.href)??"http://localhost/").href,g=ty(new URL("applet-bridge-module.js",m)),f=ty(new URL("applet-js-module.js",m)),w={AppletBridgeModule:((b=new URLSearchParams((v=new URL(g)).hash.slice(1))).set("__doubao_sync_bridge",JSON.stringify({...j,fileSystemSnapshot:ec(),storageSnapshot:{}})),v.hash=b.toString(),v.href),AppletJSModule:f},"direct"===t&&(w.LynxConsoleModule=ty(new URL("console-module.js",m)),"APP"===d&&(w.LynxDevToolSetModule=f)),s.nativeModulesMap=w,(0,tH.B)(s),s.napiModulesMap={...s.napiModulesMap,WebSyncBridge:s.nativeModulesMap.AppletBridgeModule};let R=s.onNapiModulesCall;s.onNapiModulesCall=(e,t,r,i,n)=>("WebSyncBridge"===r&&"subscribeSyncUpdates"===e&&(s.sendSyncBridgeUpdate=n,s.sendSyncBridgeUpdate({type:"event",name:e1,params:j,timestamp:Date.now()})),null==R?void 0:R(e,t,r,i,n)),s.globalProps={...c,__DOUBAO_WEB_SDK_SYNC_BRIDGE__:j};let P={containerType:d,element:s,globalProps:c,fileSystemNamespace:j.fileSystemNamespace,environment:this.runtimeContext.environment};s.onNativeModulesCall=(e,t,r)=>p.dispatch(h,e,t,r,P),n=async e=>{let t=await p.dispatch(h,"postMessage",e,"AppletBridgeModule",P);return y(t)?t:void 0},tJ.set(s,n),s.transformVW=!0,s.transformVH="content"!==u,s.transformREM=!1,s.addEventListener("timing",e=>{let t=e.detail;o(t)&&"number"==typeof t.create_lynx_start&&Number.isFinite(t.create_lynx_start)&&t.create_lynx_start>0&&(a=t.create_lynx_start),p.dispatch(h,"postMessage",{type:"call",name:e6,params:{timing:{create_lynx_start:a,...o(t)?t:{}}},callbackId:0},"AppletBridgeModule",P)}),s.addEventListener("error",e=>{var t,r;let i;null==(t=(r=this.options).onError)||t.call(r,(null==(i=e.detail)?void 0:i.error)instanceof Error?i.error:Error(String((null==i?void 0:i.error)??i??"Unknown Container runtime error")),e)}),"WIDGET"===d&&this.options.captureWidgetTap&&(this.cleanupWidgetTapCapture=(l=this.options.onWidgetInteraction,_=0,S=e=>{e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();var t={sequence:_+=1,type:"tap"};try{Promise.resolve(null==l?void 0:l(t)).catch(()=>void 0)}catch{}},s.addEventListener("click",S,!0),()=>s.removeEventListener("click",S,!0))),s.url=tw(e),this.container.replaceChildren(s),this.cleanupWebMapHost=(I=new Map,k=new Set,C=[],E=0,N=!1,T=e=>{for(let t of e.querySelectorAll("*"))"map"!==t.localName||rn.has(t)||k.add(new rf(t)),t.shadowRoot&&A(t.shadowRoot);for(let e of k)e.element.isConnected||(e.dispose(),k.delete(e))},A=e=>{if(I.has(e)||N)return;let t=new MutationObserver(t=>{if(!(t.some(e=>{let t=e.target;return t instanceof Element&&t.closest("[data-doubao-map-surface]")})&&t.every(e=>e.target instanceof Element&&e.target.closest("[data-doubao-map-surface]"))))for(let i of(T(e),t)){let e=i.target,t=e instanceof Element?e.closest("map"):null;if(t){var r;null==(r=rn.get(t))||r.update()}}});t.observe(e,{childList:!0,subtree:!0,attributes:!0}),I.set(e,t),T(e)},(M=()=>{if(N)return;let e=s.shadowRoot??s;if(A(e),s.shadowRoot&&x!==e)for(let t of(x=e,[0,16,100,500,2e3,1e4]))C.push(setTimeout(()=>{N||T(e)},t));else s.shadowRoot||(E=requestAnimationFrame(M))})(),()=>{for(let e of(N=!0,cancelAnimationFrame(E),C))clearTimeout(e);for(let e of I.values())e.disconnect();for(let e of k)e.dispose()})};return"sandbox"===this.runtimeContext.environment?m():p.prepareStorage(h,c,this.options.fileSystemNamespace).then(m).catch(e=>{if(this.view===s){var t,r;null==(t=(r=this.options).onError)||t.call(r,e,new Event("error"))}}),s}clear(){var e,t,r,i;null==(e=this.cleanupWebMapHost)||e.call(this),this.cleanupWebMapHost=null,null==(t=this.cleanupWidgetTapCapture)||t.call(this),this.cleanupWidgetTapCapture=null,this.caller&&(null==(i=this.bridge)||i.unregister(this.caller)),this.caller=void 0,this.bridge=null,null==(r=this.view)||r.remove(),this.view=null,this.container.replaceChildren()}setVisible(e){if(this.caller){var t;null==(t=this.bridge)||t.setVisible(this.caller,e)}}sendEvent(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t=this.view,r_(t,{type:"event",name:e,params:r,timestamp:Date.now()})}sendBridgeMessage(e){r_(this.view,e)}sendGlobalEvent(e,t){var r,i;null==(i=this.view)||null==(r=i.sendGlobalEvent)||r.call(i,e,t)}updateData(e){var t,r;null==(r=this.view)||null==(t=r.updateData)||t.call(r,e)}updateGlobalProps(e){this.view&&(this.view.globalProps={...this.view.globalProps,...e})}reload(){var e,t;null==(t=this.view)||null==(e=t.reload)||e.call(t)}}let rx=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
20
20
  <path d="M3.74902 7.91113C4.90234 7.91131 5.83691 8.84664 5.83691 10C5.83674 11.1532 4.90223 12.0877 3.74902 12.0879C2.59566 12.0879 1.66033 11.1533 1.66016 10C1.66016 8.84653 2.59555 7.91113 3.74902 7.91113ZM9.99805 7.91113C11.1514 7.91131 12.0859 8.84664 12.0859 10C12.0858 11.1532 11.1513 12.0877 9.99805 12.0879C8.84469 12.0879 7.90936 11.1533 7.90918 10C7.90918 8.84653 8.84458 7.91113 9.99805 7.91113ZM16.249 7.91113C17.4023 7.91131 18.3369 8.84664 18.3369 10C18.3367 11.1532 17.4022 12.0877 16.249 12.0879C15.0957 12.0879 14.1603 11.1533 14.1602 10C14.1602 8.84653 15.0956 7.91113 16.249 7.91113Z" fill="black"/>
21
21
  </svg>`,rI=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
22
22
  <path d="M9.99622 18.176C8.86678 18.176 7.8086 17.9623 6.82166 17.5348C5.83472 17.1126 4.96653 16.5267 4.21709 15.7773C3.46765 15.0331 2.87919 14.1676 2.45169 13.1806C2.02947 12.1884 1.81836 11.1276 1.81836 9.99817C1.81836 8.86873 2.02947 7.81055 2.45169 6.82361C2.87919 5.8314 3.46765 4.96057 4.21709 4.21113C4.96653 3.46169 5.83472 2.87586 6.82166 2.45364C7.8086 2.03142 8.86678 1.82031 9.99622 1.82031C11.1257 1.82031 12.1838 2.03142 13.1708 2.45364C14.163 2.87586 15.0338 3.46169 15.7833 4.21113C16.5327 4.96057 17.1185 5.8314 17.5408 6.82361C17.9682 7.81055 18.182 8.86873 18.182 9.99817C18.182 11.1276 17.9682 12.1884 17.5408 13.1806C17.1185 14.1676 16.5327 15.0331 15.7833 15.7773C15.0338 16.5267 14.163 17.1126 13.1708 17.5348C12.1838 17.9623 11.1257 18.176 9.99622 18.176ZM9.99622 16.561C10.904 16.561 11.7537 16.3895 12.5454 16.0465C13.337 15.7087 14.0337 15.239 14.6354 14.6373C15.2423 14.0356 15.7147 13.339 16.0524 12.5473C16.3902 11.7557 16.5591 10.9059 16.5591 9.99817C16.5591 9.0904 16.3902 8.24068 16.0524 7.44902C15.7147 6.65208 15.2423 5.95542 14.6354 5.35904C14.0337 4.75738 13.337 4.28766 12.5454 3.94988C11.7537 3.60683 10.904 3.4353 9.99622 3.4353C9.09373 3.4353 8.24401 3.60683 7.44707 3.94988C6.65541 4.28766 5.95875 4.75738 5.35708 5.35904C4.75542 5.95542 4.28306 6.65208 3.94001 7.44902C3.60224 8.24068 3.43335 9.0904 3.43335 9.99817C3.43335 10.9059 3.60224 11.7557 3.94001 12.5473C4.28306 13.339 4.75542 14.0356 5.35708 14.6373C5.95875 15.239 6.65541 15.7087 7.44707 16.0465C8.24401 16.3895 9.09373 16.561 9.99622 16.561ZM10.0041 13.0856C9.43414 13.0856 8.91164 12.9458 8.43665 12.6661C7.96693 12.3863 7.59221 12.0116 7.31249 11.5419C7.03277 11.0722 6.89291 10.5523 6.89291 9.98234C6.89291 9.41234 7.03277 8.89248 7.31249 8.42277C7.59221 7.95305 7.96693 7.57833 8.43665 7.29861C8.91164 7.01361 9.43414 6.87111 10.0041 6.87111C10.5741 6.87111 11.0914 7.01361 11.5558 7.29861C12.0255 7.57833 12.4002 7.95305 12.68 8.42277C12.9597 8.89248 13.0995 9.41234 13.0995 9.98234C13.0995 10.5523 12.9597 11.0722 12.68 11.5419C12.4002 12.0116 12.0255 12.3863 11.5558 12.6661C11.0914 12.9458 10.5741 13.0856 10.0041 13.0856Z" fill="black"/>
@@ -48,4 +48,4 @@ ${i}
48
48
  event: ${e.event}
49
49
  data: ${JSON.stringify(e)}
50
50
 
51
- `}function mV(e,t){return t.find(t=>null==e?void 0:e.widgets.some(e=>e.widgetId===t))}function mG(e,t,r,i){var n;return{event:t,request_id:i.requestId,reply_message_id:i.replyMessageId,trace:{trace_id:(null==(n=e.trace)?void 0:n.trace_id)||`trace_mock_${e.idempotency_key??i.requestId}`,component:"mock_simulator",stage:t,sampled:!0},...r}}let mJ=async e=>{var t;let r=`找到和 ${(null==(t=e.arguments)?void 0:t.keyword)||"调试数据"} 相关的模拟结果`,i={content:[{type:"text",text:r}],structuredContent:{entities:[{entity_type:"debug_item",entity_id:"debug-item-1",name:"调试示例数据"}]},isError:!1},n=JSON.stringify(i);return{status:"succeeded",result:i.structuredContent,raw_result_text:r,raw_mcp_result_json:n,miniapp:{is_mini_app:!0,mcp_channel:"flow_miniapp"},debug:{mock:!0}}},mK=n0(nX),mZ=dI({requestHandler:async(e,t,r)=>{let i=e.params,n=r??nJ(i);return nF(n.url,"request"),nB(async t=>{var r,a;let s,o,l=await fetch("/__web_sdk_request_proxy__",{signal:t,body:JSON.stringify((s=new Headers(n.headers),{data:(o=n.body instanceof ArrayBuffer)?nH(n.body):n.body,dataEncoding:o?"base64":void 0,header:Object.fromEntries(s),method:n.method,url:n.url})),headers:{"content-type":"application/json"},method:"POST"}),d=(null==(r=l.headers.get("content-type"))?void 0:r.toLowerCase())??"",u=await l.text();if(!d.includes("application/json"))throw Error(`Request proxy returned a non-JSON response. Make sure the debugger is started with the local request proxy. Response starts with: ${u.slice(0,120)}`);let c=u?JSON.parse(u):{};if(!l.ok)throw Error((null==c?void 0:c.message)||`Request proxy failed with status ${l.status}`);if((null==c?void 0:c.dataEncoding)==="base64"&&"string"==typeof c.data){let t=nV((a=c.data,Uint8Array.from(atob(a),e=>e.charCodeAt(0)).buffer),i.dataType);return _(e,{statusCode:c.statusCode,header:c.header,data:t})}return _(e,c)})}});function mX(e,t){if(e.has(t))return!1;if(e.add(t),e.size>100){let t=e.values().next().value;t&&e.delete(t)}return!0}function mY(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";return new URL(window.location.href).searchParams.get(e)||r||t}async function mQ(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:fetch;try{var t;let r=await e("/__web_sdk_debug_context",{cache:"no-store",headers:{Accept:"application/json"}});return r.ok?!(t=await r.json())||"object"!=typeof t||Array.isArray(t)?{}:t:{}}catch{return{}}}async function m0(e,t){let r=t.skills,i=t.mcpServers,n=[];if("function"==typeof r&&n.push(Promise.resolve(r()).catch(()=>void 0)),"function"==typeof i){let t=e.getState();n.push(Promise.resolve(i({appKey:t.manifest.appId,appName:t.manifest.name,manifest:t.manifest.raw})).catch(()=>void 0))}await Promise.all(n)}function m1(){return(0,s.jsx)("main",{className:"chrome-devtools-unavailable-page",children:(0,s.jsx)("section",{className:"wsd-chrome-devtools",children:(0,s.jsx)("div",{className:"wsd-chrome-devtools-empty",children:"Chrome DevTools frontend is unavailable"})})})}function m2(e){let{serverDebugContext:t}=e,r=(0,iO.useMemo)(()=>(function(e){let t=e.searchParams.get("messages");if(null!==t)try{let e=JSON.parse(t);if(Array.isArray(e))return e;console.error("Failed to read initial messages: messages must be an array")}catch(e){console.error("Failed to read initial messages",e)}})(new URL(window.location.href)),[]),i=(0,iO.useMemo)(()=>new URL(window.location.href).searchParams.get("manifest")||nZ,[]),n=void 0!==r,a=(0,iO.useMemo)(()=>mY("mcp","",void 0),[]),o=(0,iO.useMemo)(()=>{let e;return(e=new URL(window.location.href)).searchParams.get("mcpOriginal")||e.searchParams.get("mcpEndpoint")||""},[]),l=(0,iO.useMemo)(()=>mY("simulatorManifest","/__simulator_manifest/manifest.yaml",void 0),[]),d=(0,iO.useMemo)(()=>new URL(window.location.href).searchParams.get("simulatorManifestOriginal")||"",[]),u=(0,iO.useMemo)(()=>mY("simulatorSkills","/__simulator_skills/index.json",void 0),[]),c=(0,iO.useMemo)(()=>new URL(window.location.href).searchParams.get("simulatorSkillsOriginal")||"",[]),p=(0,iO.useMemo)(()=>n0(new URL(window.location.href).searchParams.get("simulator")||mK),[]),h=(0,iO.useMemo)(()=>{let e;return(e=new URL(window.location.href)).searchParams.get("launchDir")||e.searchParams.get("projectPath")||e.searchParams.get("cwd")||""},[]),m=(0,iO.useMemo)(()=>`${window.location.origin}${window.location.pathname}`,[]),g=(0,iO.useMemo)(()=>{let e;return null!==(e=new URL(window.location.href).searchParams.get("DEBUG"))&&"0"!==e&&"false"!==e.toLowerCase()},[]),f=(0,iO.useMemo)(()=>"1"===new URL(window.location.href).searchParams.get("simulatorMock")||"true"===String((void 0)??"").toLowerCase(),[]),v=(0,iO.useRef)(null),y=(0,iO.useMemo)(()=>new iL,[]),b=y.clientId,[w,_]=(0,iO.useState)(),S=(0,iO.useRef)(new Set),x=(0,iO.useMemo)(()=>(function(e){var t,r,i,n,a,s;let o,l,d=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},u={mcpEndpoint:mP((t={mcpEndpoint:e,simulatorManifestUrl:d.simulatorManifestUrl,simulatorSkillsIndexUrl:d.simulatorSkillsIndexUrl}).mcpEndpoint),simulatorManifestUrl:mP(t.simulatorManifestUrl),simulatorSkillsIndexUrl:mP(t.simulatorSkillsIndexUrl)},c=function(){let e,t,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{mcpServers:async e=>{let t=Object.entries(Object.fromEntries(Object.entries((e.manifest??{}).tools??{}).filter(e=>{let[,t]=e;return!0===t.is_client_tool}))).map(e=>{let[t,r]=e;return{name:t,description:r.description,input_schema_json:function e(t){if(Array.isArray(t))return t.map(e);if(!rP(t))return t;let r={};for(let[i,n]of Object.entries(t))r[i]="type"===i&&"int"===n?"integer":"type"===i&&"float"===n?"number":e(n);return r}(r.input_schema)}});return 0===t.length?(az(r.onTraceEvent,{event:"client_tools_empty",app_key:e.appKey,server_id:aB,tool_count:0,tools:[]}),[]):(az(r.onTraceEvent,{event:"client_tools_resolved",app_key:e.appKey,server_id:aB,tool_count:t.length,tools:t.map(e=>e.name)}),[{server_id:aB,name:"Client Tool",description:"Client Tool runtime for simulator debugging",tools:t}])},toolExecutor:((t=async t=>{let i,n;try{i=function(e){let t=e.arguments;if(void 0===t){if(void 0===e.argumentsJson)t={};else if(void 0===(t=r3(e.argumentsJson)))throw Error("Tool arguments must be valid JSON")}if(!rP(t))throw Error("Tool arguments must be a JSON object");return t}(t),n="string"==typeof t.argumentsJson&&t.argumentsJson.trim()?t.argumentsJson:r6(i)}catch(e){return aK("CLIENT_TOOL_INVALID_ARGUMENTS",r5(e),!1)}try{var a;az(r.onTraceEvent,{event:"client_tool_call_started",request_id:t.requestId,trace_id:t.trace.trace_id,app_key:t.appKey,server_id:t.serverId,tool_call_id:t.toolCallId,tool_name:t.toolName,arguments:i,arguments_json:r6(i)});let s=await (()=>{var t,i;let n=null==(t=r.getRuntimeUrl)?void 0:t.call(r);if(!n)throw Error("Client Tool runtime is unavailable. Build the app with a Web Client Tool entry.");if(!e||e.runtimeUrl!==n){null==e||e.dispose();let t=(r.runtimeFactory??function(e,t){return new aH(e,t)})(n,null==(i=r.getRuntimeGlobalProps)?void 0:i.call(r));e=new aJ(n,t,r.onTraceEvent),az(r.onTraceEvent,{event:"client_tool_runtime_started",runtime_url:n})}return e})().invokeTool({toolId:t.toolName,input:n,context:{callbackId:t.toolCallId,conversationId:t.requestId,featureMap:void 0,msgId:t.replyMessageId,questionId:t.requestId},signal:t.signal}),o=function(e,t){var r,i;if(0===e.result)try{let i=function(e,t){if(!rP(e)||!Array.isArray(e.content))throw Error(`Client Tool "${t}" must return an MCP tool output object`);return e}(e.output,t.toolName),n=!0===i.isError?i:function(e,t){let r=aU(t.manifest,t.toolName);if(!r||"string"!=typeof r.kind)throw Error(`Client Tool "${t.toolName}" manifest output is required`);if("execution_result"===r.kind)return e;if("entities"!==r.kind)throw Error(`Client Tool "${t.toolName}" has unsupported output kind "${r.kind}"`);if(!rP(e)||!Array.isArray(e.structuredContent))throw Error(`Client Tool "${t.toolName}" must return structuredContent as an array`);return a$(e,t.manifest,t.toolName)}(i,t);return r=aq(n,{businessErrorCode:"CLIENT_TOOL_BUSINESS_ERROR",protocol:aW,source:"client_tool"}),{...r,debug:{...r.debug,mcp_output:i}}}catch(e){return aK("CLIENT_TOOL_INVALID_RESULT",r5(e),!1)}let n=void 0===(i=e.reason)?"":rP(i)?"string"==typeof i.message?i.message:r6(i):r5(i);return 2===e.result?aK("CLIENT_TOOL_NOT_FOUND",`Client Tool not found: ${e.toolId}`,!1):1===e.result?aK("CLIENT_TOOL_FAILED",n||`Client Tool failed: ${e.toolId}`,!1):aK("CLIENT_TOOL_UNKNOWN_RESULT",`Client Tool returned unknown status: ${String(e.result)}`,!1)}(s,t);return az(r.onTraceEvent,{event:"succeeded"===o.status?"client_tool_call_succeeded":"client_tool_call_failed",request_id:t.requestId,app_key:t.appKey,server_id:t.serverId,tool_call_id:t.toolCallId,tool_name:t.toolName,status:o.status,result:o.result,raw_mcp_result_json:o.raw_mcp_result_json,error:null==(a=o.error)?void 0:a.message}),o}catch(i){let e=r5(i);return az(r.onTraceEvent,{event:"client_tool_call_failed",request_id:t.requestId,app_key:t.appKey,server_id:t.serverId,tool_call_id:t.toolCallId,tool_name:t.toolName,error:e}),aK("CLIENT_TOOL_CALL_FAILED",e,!0)}}).dispose=()=>{null==e||e.dispose(),e=void 0},t)}}({getRuntimeGlobalProps:d.getClientToolRuntimeGlobalProps,getRuntimeUrl:d.getClientToolRuntimeUrl,onTraceEvent:d.onTraceEvent}),p=c.toolExecutor,h=c.mcpServers,m=()=>{var e;return l??=Promise.resolve(u.mcpEndpoint||(null==(e=d.getMcpEndpoint)?void 0:e.call(d))).then(e=>{let t=mP(e);return o=t?function(e){let t=rj(e.endpoint);if(!t)return{};let r=function(e,t){if(null==t?void 0:t.trim())return t.trim();let r=new URL(e);return`${r.hostname}_${r.port||r.protocol.replace(":","")}${r.pathname}`.replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/^_+|_+$/g,"")||"local_mcp"}(t,e.serverId);return{mcpServers:async i=>{let n;try{dC(e.onTraceEvent,{event:"local_mcp_tools_load_started",app_key:i.appKey,mcp_endpoint:t,server_id:r},i),n=await dN(t,{...e,signal:i.signal});let a=await n.client.listTools(void 0,{signal:i.signal}),s=n.client.getServerVersion(),o={server_id:r,name:(null==s?void 0:s.name)||r,description:n.client.getInstructions()||"",tools:a.tools.map(dE).filter(e=>e.name)};return dC(e.onTraceEvent,{event:"local_mcp_tools_loaded",app_key:i.appKey,mcp_endpoint:t,server_id:o.server_id,server_version:s,tools:o.tools.map(e=>e.name)},i),[o]}catch(n){var a;return null==(a=i.signal)||a.throwIfAborted(),dC(e.onTraceEvent,{event:"local_mcp_tools_load_failed",app_key:i.appKey,mcp_endpoint:t,server_id:r,error:r5(n),request_will_continue:!0,tool_count:0,tools:[]},i),console.warn("[web-sdk-debugger] Failed to load MCP tools",n),[]}finally{n&&await dT(n)}},toolExecutor:async r=>{var i;let n,a=r.arguments??r3(r.argumentsJson)??{},s=r.argumentsJson||r6(a),o=Date.now();try{dC(e.onTraceEvent,{event:"local_mcp_call_started",request_id:r.requestId,trace_id:r.trace.trace_id,app_key:r.appKey,server_id:r.serverId,tool_call_id:r.toolCallId,tool_name:r.toolName,arguments:a,arguments_json:s,mcp_endpoint:t}),n=await dN(t,{...e,signal:r.signal,headers:function(e,t){if(!e&&!t)return;let r=new Headers(e);for(let[e,i]of Object.entries(t??{}))r.set(e,i);return r}(e.headers,r.headers)}),null==(i=r.signal)||i.throwIfAborted();let l=await n.client.callTool({name:r.toolName,arguments:a,_meta:{request_id:r.requestId,trace_id:r.trace.trace_id,app_key:r.appKey,server_id:r.serverId,tool_call_id:r.toolCallId,tool_name:r.toolName,arguments_json:s}},{signal:r.signal}),d=!0===l.isError?l:a$(l,r.manifest,r.toolName),u=aq(d,{businessErrorCode:"LOCAL_MCP_BUSINESS_ERROR",protocol:"streamable_http",source:"local_mcp"});return u.debug={...u.debug,mcp_output:l},dC(e.onTraceEvent,{event:"local_mcp_call_succeeded",request_id:r.requestId,trace_id:r.trace.trace_id,app_key:r.appKey,server_id:r.serverId,tool_call_id:r.toolCallId,tool_name:r.toolName,status:u.status,result:u.result,raw_result_text:u.raw_result_text,raw_mcp_result:d,elapsed_ms:Date.now()-o,mcp_endpoint:t}),u}catch(n){if(aT(n))throw n;let i=r5(n);return dC(e.onTraceEvent,{event:"local_mcp_call_failed",request_id:r.requestId,trace_id:r.trace.trace_id,app_key:r.appKey,server_id:r.serverId,tool_call_id:r.toolCallId,tool_name:r.toolName,error:i,elapsed_ms:Date.now()-o,mcp_endpoint:t}),{status:"failed",result:{error:i},error:{code:"LOCAL_MCP_CALL_FAILED",message:i,retryable:!0,stage:"tool_execute"},raw_result_text:i}}finally{n&&await dT(n)}}}}({endpoint:t,onTraceEvent:d.onTraceEvent}):void 0})},g=async e=>{let[t,r]=await Promise.all([m(),h(e)]);if(!t)return r;let i=t.mcpServers;return[...await i(e),...r]},f=async e=>{if(e.serverId===aB)return p(e);let t=await m();if(!t){let e="Local MCP is not configured";return{status:"failed",result:{error:e},error:{code:"LOCAL_MCP_NOT_CONFIGURED",message:e,retryable:!1,stage:"tool_execute"},raw_result_text:e}}return t.toolExecutor(e)};return f.dispose=()=>{var e,t,r;null==(e=p.dispose)||e.call(p),null==o||null==(r=o.toolExecutor)||null==(t=r.dispose)||t.call(r)},{simulatorManifest:u.simulatorManifestUrl?(r=u.simulatorManifestUrl,i=d.onTraceEvent,n=d.getAppId,async e=>{let t;mD(i,"manifest",r);try{if(!(t=await fetch(r,{signal:e,cache:"no-store",headers:{Accept:"application/yaml, text/yaml, text/x-yaml, application/json, text/plain"}})).ok)throw m$("manifest",r,t);let a=await t.text(),s=function(e){let t=(0,aO.qg)(e);if(!rP(t))throw Error("Simulator manifest must be a YAML object");return t}(a),o=s.app_key?void 0:await (null==n?void 0:n());if(n&&!o&&!s.app_key)throw Error("Sandbox 调试应用尚未就绪,请重建调试会话后重试。");let l=o?{...s,app_key:o}:s;return mO(i,"manifest",r,t,{bytes:a.length}),{...l,raw_manifest_yaml:o?(0,aO.As)(l):a}}catch(e){throw mU(i,"manifest",r,e,t),console.warn("[web-sdk-debugger] Failed to load simulator manifest supplement",e),e}}):void 0,skills:u.simulatorSkillsIndexUrl?(a=u.simulatorSkillsIndexUrl,s=d.onTraceEvent,async e=>{let t;mD(s,"skill",a);try{var r;if(!(t=await fetch(a,{signal:e,cache:"no-store",headers:{Accept:"application/json"}})).ok)throw m$("skill",a,t);let i=await t.text();if(((null==(r=t.headers.get("content-type"))?void 0:r.toLowerCase())??"").includes("text/html")||/^<!doctype html\b|^<html[\s>]/i.test(i.trimStart()))throw Error(`Simulator skills index returned HTML instead of JSON (${a})`);let n=function(e){if(!rP(e)||!Array.isArray(e.skills))throw Error("Simulator skills index must contain a skills array");return e.skills.map((e,t)=>{var r;if(!(rP(r=e)&&"string"==typeof r.relativePath&&"string"==typeof r.content))throw Error(`Simulator skills index contains an invalid entry at index ${t}`);return e}).sort((e,t)=>e.relativePath<t.relativePath?-1:+(e.relativePath>t.relativePath))}(JSON.parse(i));return mO(s,"skill",a,t,{bytes:i.length,skill_paths:n.map(e=>e.relativePath)}),n}catch(e){throw mU(s,"skill",a,e,t),console.warn("[web-sdk-debugger] Failed to load simulator skills",e),e}}):void 0,mcpServers:g,toolExecutor:f}})(a,{getClientToolRuntimeGlobalProps:()=>{var e;let t=null==(e=v.current)?void 0:e.getState().manifest;return t?tq(t):void 0},getClientToolRuntimeUrl:()=>{var e;let t=null==(e=v.current)?void 0:e.getState();return t?function(e,t,r){var i,n,a,s,o,l;let d,u=(null==(a=t.applet)||null==(n=a.web)||null==(i=n.toolRuntimeEntry)?void 0:i.trim())||(null==(o=t.applet)||null==(s=o.toolRuntimeEntry)?void 0:s.trim());if(!u)return;let c=new URL(u,((d=new URL(String(e),(null==(l=globalThis.location)?void 0:l.href)||"http://localhost/")).pathname.endsWith("/base/manifest.json")?d.pathname=d.pathname.slice(0,-18):d.pathname=d.pathname.replace(/\/[^/]*$/,"/"),d.search="",d.hash="",d));return r&&c.searchParams.set("__doubao_resource_reload",r),c.toString()}(t.manifestUrl,t.manifest.raw,t.resourceUrlVersion):void 0},getMcpEndpoint:async()=>t.mcpProxyEndpoint,getAppId:async()=>(await mQ()).sandboxAppId,onTraceEvent:e=>{var t;return null==(t=v.current)?void 0:t.appendSimulatorTraceEvent(e)},simulatorManifestUrl:l,simulatorSkillsIndexUrl:u}),[a,l,u,t.mcpProxyEndpoint]),I=(0,iO.useMemo)(()=>{let e=f?{appKey:mq,appName:"调试示例应用插件",mcpServers:mz,simulatorFetch:function(e){let{getDebuggerState:t}=e;return async(e,r)=>{var i,n,a,s,o,l,d,u;let c,p,h,m,g,f,v,y,b=String(e);if(b.endsWith("/simulator/tool/report")){let e="string"==typeof(null==r?void 0:r.body)?JSON.parse(r.body):{};return new Response(JSON.stringify({code:0,message:"OK",request_id:e.request_id,tool_call_id:e.tool_call_id,trace:e.trace}),{headers:{"Content-Type":"application/json"},status:200,statusText:"OK"})}return b.endsWith("/simulator/chat")?(y=(i="string"!=typeof(null==r?void 0:r.body)?{}:JSON.parse(r.body),s=t(),p=((c=new URL(window.location.href).searchParams.get("simulatorMockWidget"))?mV(s,[c]):void 0)||mV(s,mW)||(null==s||null==(o=s.widgetSelection)?void 0:o.item.widgetId)||(null==(l=s)||null==(d=l.widgets.find(e=>{var t;return null==(t=e.web)?void 0:t.entry}))?void 0:d.widgetId)||(null==l||null==(u=l.widgets[0])?void 0:u.widgetId)||"weather-card",h=Date.now().toString(36),m={requestId:`req_mock_server_${h}`,replyMessageId:`msg_mock_reply_${h}`},g=(null==(n=i.message)?void 0:n.content)||"模拟请求",f=`call_mock_${h}`,v={applet_id:i.app_id||mq,widget_id:p,entity_id:"mock-entity-1",viewData:{source:"web-sdk-debugger-mock",keyword:g,widgetId:p},extra:{"doubao/outputTemplate":"mock.output.template"}},[mG(i,"ack",{ack:{request_id:m.requestId,message_id:m.replyMessageId,local_message_id:null==(a=i.message)?void 0:a.local_message_id}},m),mG(i,"tool_call",{tool_call:{tool_call_id:f,tool_name:mF,server_id:mB,app_key:i.app_id||mq,arguments_json:JSON.stringify({keyword:g}),status:"PENDING",timeout_ms:2e3}},m),mG(i,"tool_status",{tool_status:{tool_call_id:f,status:"RUNNING",progress:.6,message:"Mock tool running"}},m),mG(i,"text_delta",{text_delta:{block_id:"block_mock_text",op:"append",delta:`Mock 已收到:${g}`}},m),mG(i,"card_delta",{card_delta:{block_id:"block_mock_card",op:"append",card_id:`card_mock_${h}`,source_tool_call_id:f,source_entity_ids:["mock-entity-1"],is_final:!0,card:{card_id:`card_mock_${h}`,card_type:"mock_widget_card",title:"Mock 应用插件卡片",fallback_text:`使用 ${p} 渲染`,props_json:JSON.stringify(v)}}},m),mG(i,"debug",{debug_event:{category:"mock",title:"Mock Simulator",summary:"本地 mock SSE 已生成 text/card/tool 事件",data:{widget_id:p},redaction_level:"none"}},m),mG(i,"answer_finish",{answer_finish:{status:"completed",finish_reason:"stop",usage:{output_tokens:12}}},m),mG(i,"reply_finish",{reply_finish:{status:"completed",finish_reason:"stop",event_count:7}},m)]).map(mH).join(""),new Response(new ReadableStream({start(e){e.enqueue(new TextEncoder().encode(y)),e.close()}}),{headers:{"Content-Type":"text/event-stream"},status:200,statusText:"OK"})):new Response(JSON.stringify({ok:!1,error:"Unknown mock simulator endpoint"}),{status:404,statusText:"Not Found"})}}({getDebuggerState:()=>{var e;return(null==(e=v.current)?void 0:e.getState())??null}}),toolExecutor:mJ}:{},t=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return new si(e)}({manifestUrl:i,simulatorEndpoint:p,...x,...e});return r&&t.pushMessages(r),v.current=t,t},[i,p,x,f,r]),[k,C]=(0,iO.useState)(()=>{let e,t,r;return t=(e=new URL(window.location.href)).searchParams.get("view"),r=e.searchParams.get("debugMode")||e.searchParams.get("mode"),"conversation"===t||"tool"===t||"card"===t||"page"===t?t:"conversation"===r||"tool"===r||"card"===r||"page"===r?r:"conversation"}),E=cl((e,t)=>{mX(S.current,e)&&y.reportResult({commandId:e,...t}).catch(e=>console.error(e)).finally(()=>{_(t=>(null==t?void 0:t.commandId)===e?void 0:t)})}),N=cl(e=>{if("cancel_chat_query"===e.type){cj(I,e.commandId),E(e.commandId,{ok:!1,error:{code:"CHAT_TIMEOUT",message:"Chat query was cancelled after the debugger control timeout"}});return}"execute_sandbox_tool_call"===e.type?I.executeSandboxToolCall(e.toolCall).then(t=>{E(e.commandId,{ok:!0,result:{reported:t.reported,request_id:t.requestId,tool_call_id:t.toolCallId}})}).catch(t=>{E(e.commandId,{error:{code:"TOOL_CALL_FAILED",message:t instanceof Error?t.message:String(t)},ok:!1})}):(_(e),("render_page"===e.type||"render_widget"===e.type||"submit_chat_query"===e.type)&&C("render_page"===e.type?"page":"render_widget"===e.type?"card":"conversation"))}),T=cl(e=>{try{return I.navigateToPage(e.url,{routeMode:e.routeMode}),C("page"),!0}catch{return!1}}),A=cl(()=>{let{manifest:e}=I.getState();return{appKey:e.appId,appName:e.name}});(0,iO.useEffect)(()=>{let e=y.subscribe(e=>{if("control"===e.type)N(e.data);else if("status"===e.type&&"connected"!==e.status){let e=cj(I);e&&mX(S.current,e),_(void 0)}});return y.start(),()=>{e(),y.stop()}},[y,N,I]),(0,iO.useEffect)(()=>{if(n)return window.webSdkDebugger=I,()=>{window.webSdkDebugger===I&&delete window.webSdkDebugger}},[n,I]),(0,iO.useEffect)(()=>(function(e){let t=document.modelContext;if(!t)return()=>{};let r=new AbortController,i=new URL("/__wsd_mcp",window.location.href);async function n(e){let t=await dN(i.href,{});try{return await e(t.client)}finally{await dT(t)}}return i.searchParams.set("clientId",e),(async function(){let{tools:e}=await n(e=>e.listTools());for(let a of e){var i;r.signal.throwIfAborted(),await t.registerTool({name:a.name,description:a.description??"",inputSchema:a.inputSchema,annotations:{readOnlyHint:(null==(i=a.annotations)?void 0:i.readOnlyHint)===!0,untrustedContentHint:!0},execute:async function(e){let{signal:t}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return r.signal.throwIfAborted(),null==t||t.throwIfAborted(),n(async r=>{null==t||t.throwIfAborted();let i=await r.callTool({name:a.name,arguments:e},{signal:t,timeout:13e4}),n=JSON.stringify(i);if(i.isError)throw Error(n);return n})}},{signal:r.signal})}})().catch(e=>{r.signal.aborted||(r.abort(),console.warn("[web-sdk-debugger] Failed to register WebMCP tools",e))}),()=>r.abort()})(b),[b]),(0,iO.useEffect)(()=>{let e=!1;return I.loadManifest(i).then(()=>{if(!e){let e;return e=new URL(window.location.href),i===nZ?e.searchParams.delete("manifest"):e.searchParams.set("manifest",i),window.history.replaceState(null,"",e),m0(I,x)}}).catch(()=>{}),()=>{e=!0,I.destroy(),v.current===I&&(v.current=null)}},[i,x,I]);let M=(0,iO.useMemo)(()=>({launchDir:h,simulatorManifestOriginalUrl:d,simulatorManifestProxyUrl:l,simulatorManifestUrl:l,simulatorSkillsIndexOriginalUrl:c,simulatorSkillsIndexProxyUrl:u,simulatorSkillsIndexUrl:u,webUrl:m,...t,mcpEndpoint:a||t.mcpProxyEndpoint,mcpOriginalEndpoint:o||t.mcpOriginalEndpoint,mcpProxyEndpoint:a||t.mcpProxyEndpoint}),[h,a,o,d,l,c,u,m,t]);return(0,s.jsx)(iD.M,{children:(0,s.jsx)("section",{className:"workspace",children:(0,s.jsx)("section",{className:"debug-workspace",children:(0,s.jsx)("section",{className:"debug-mode-panel",children:(0,s.jsx)(ch,{capability:M.realDeviceDebug,getAppIdentity:A,children:(0,s.jsx)(mj,{messageInputDisabled:n,activeView:k,apiEnvironment:mZ,chromeDevToolsFrontendUrl:"/chrome-devtools/inspector.html",controlCommand:w,controlClientId:b,debugContext:M,onActiveViewChange:C,onControlResult:E,onNavigateToPage:T,showDebugTrace:g,connection:y,webSdkDebugger:I})})})})})})}function m3(e){let{serverDebugContext:t}=e;return window.location.pathname.startsWith("/chrome-devtools/")?(0,s.jsx)(m1,{}):(0,s.jsx)(m2,{serverDebugContext:t})}async function m4(){let e=await mQ();e.webViewOrigin&&(tK=t=>({messageTransport:"window",url:`${e.webViewOrigin}/__webview/bootstrap?${new URLSearchParams({url:t,parentOrigin:location.origin})}`}));let t=document.querySelector("#app");if(!t)throw Error("Cannot find #app");(0,rZ.H)(t).render((0,s.jsx)(m3,{serverDebugContext:e}))}(async function(){if("serviceWorker"in navigator){let e=e=>(null==e?void 0:e.scriptURL)===new URL("/__webview/sw.js",location.origin).href,t=e(navigator.serviceWorker.controller),r=await navigator.serviceWorker.getRegistrations();if(await Promise.all(r.filter(t=>e(t.active)||e(t.waiting)||e(t.installing)).map(e=>e.unregister())),t)return void location.reload()}await m4()})().catch(m4)}},h={};function m(e){var t=h[e];if(void 0!==t)return t.exports;var r=h[e]={id:e,exports:{}};return p[e].call(r.exports,r,r.exports,m),r.exports}m.m=p,m.c=h,t=(e="function"==typeof Symbol)?Symbol("rspack queues"):"__rspack_queues",r=m.aE=e?Symbol("rspack exports"):"__webpack_exports__",i=e?Symbol("rspack error"):"__rspack_error",n=e?Symbol("rspack done"):"__rspack_done",a=m.zS=e?Symbol("rspack defer"):"__rspack_defer",m.zT=e=>{if(e.some(e=>{var t=h[e];return!t||!1===t[n]}))return{then:(t,r)=>Promise.all(e.map(m)).then(t,r)}},s=e=>{e&&e.d<1&&(e.d=1,e.forEach(e=>e.r--),e.forEach(e=>e.r--?e.r++:e()))},m.a=(e,o,l,d)=>{l&&((u=[]).d=-1);var u,c,p,h,g=new Set,f=e.exports,v=new Promise((e,t)=>{h=t,p=e});v[r]=f,v[t]=e=>{u&&e(u),g.forEach(e),v.catch(()=>{})},e.exports=v;var y=e;d&&((y=Object.create(e)).exports=f),o(e=>{c=e.map(e=>{if(null!==e&&"object"==typeof e){if(!e[t]&&e[a]){var n=m.zT(e[a]);if(!n)return e;var o=e;e={then(e,t){n.then(()=>e(o),t)}}}if(e[t])return e;if(e.then){var l=[];l.d=0,e.then(e=>{d[r]=e,s(l)},e=>{d[i]=e,s(l)});var d={};return d[a]=!1,d[t]=e=>e(l),d}}var u={};return u[t]=()=>{},u[r]=e,u});var n,o=()=>c.map(e=>{if(e[a])return e;if(e[i])throw e[i];return e[r]}),l=new Promise(e=>{(n=()=>e(o)).r=0;var r=e=>e!==u&&!g.has(e)&&(g.add(e),e&&!e.d&&(n.r++,e.push(n)));c.map(e=>e[a]||e[t](r))});return n.r?l:o()},e=>(e?h(v[i]=e):(d&&(f=v[r]=y.exports),p(f)),s(u),v[n]=!0),y),u&&u.d<0&&(u.d=0)},m.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return m.d(t,{a:t}),t},m.d=(e,t,r)=>{var i=(t,r)=>{for(var i in t)m.o(t,i)&&!m.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,[r]:t[i]})};i(t,"get"),i(r,"value")},m.f={},m.e=(e,t)=>Promise.all(Object.keys(m.f).reduce((r,i)=>(m.f[i](e,r,t),r),[])),m.u=e=>"static/js/async/"+(({166:"xmarkdown-deps",350:"web-core-template-loader-thread",724:"web-elements",778:"legacy-wasm-js",894:"web-core-main-chunk",97:"web-core-worker-chunk"})[e]||e)+"."+({166:"ff739dc3dc",257:"4d55bd5ce8",350:"559b06cf7a",503:"259fed5610",724:"262cae995c",778:"555371d3dd",894:"0802207289",97:"97f5cf9510"})[e]+".js",m.miniCssF=e=>""+e+".css",m.g=(()=>{if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}})(),m.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),o={},m.l=function(e,t,r,i,n){if(o[e])return void o[e].push(t);if(void 0!==r)for(var a,s,l=document.getElementsByTagName("script"),d=0;d<l.length;d++){var u=l[d];if(u.getAttribute("src")==e||u.getAttribute("data-rspack")=="@byted-doubao-apps/web-sdk-debugger-app:"+r){a=u;break}}a||(s=!0,(a=document.createElement("script")).timeout=120,m.nc&&a.setAttribute("nonce",m.nc),a.setAttribute("data-rspack","@byted-doubao-apps/web-sdk-debugger-app:"+r),n&&a.setAttribute("fetchpriority",n),a.src=e),o[e]=[t];var c=function(t,r){a.onerror=a.onload=null,clearTimeout(p);var i=o[e];if(delete o[e],a.parentNode&&a.parentNode.removeChild(a),i&&i.forEach(function(e){return e(r)}),t)return t(r)},p=setTimeout(c.bind(null,void 0,{type:"timeout",target:a}),12e4);a.onerror=c.bind(null,a.onerror),a.onload=c.bind(null,a.onload),s&&document.head.appendChild(a)},m.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},l=[],m.O=(e,t,r,i)=>{if(t){i=i||0;for(var n=l.length;n>0&&l[n-1][2]>i;n--)l[n]=l[n-1];l[n]=[t,r,i];return}for(var a=1/0,n=0;n<l.length;n++){for(var[t,r,i]=l[n],s=!0,o=0;o<t.length;o++)(!1&i||a>=i)&&Object.keys(m.O).every(e=>m.O[e](t[o]))?t.splice(o--,1):(s=!1,i<a&&(a=i));if(s){l.splice(n--,1);var d=r();void 0!==d&&(e=d)}}return e},m.p="/",m.j="410",m.b=document.baseURI||self.location.href,d={410:0},m.f.j=function(e,t,r){var i=m.o(d,e)?d[e]:void 0;if(0!==i)if(i)t.push(i[2]);else{var n=new Promise((t,r)=>i=d[e]=[t,r]);t.push(i[2]=n);var a=m.p+m.u(e),s=Error();m.l(a,function(t){if(m.o(d,e)&&(0!==(i=d[e])&&(d[e]=void 0),i)){var r=t&&("load"===t.type?"missing":t.type),n=t&&t.target&&t.target.src;s.message="Loading chunk "+e+" failed.\n("+r+": "+n+")",s.name="ChunkLoadError",s.type=r,s.request=n,i[1](s)}},"chunk-"+e,e,r)}},m.O.j=e=>0===d[e],u=(e,t)=>{var r,i,[n,a,s]=t,o=0;if(n.some(e=>0!==d[e])){for(r in a)m.o(a,r)&&(m.m[r]=a[r]);if(s)var l=s(m)}for(e&&e(t);o<n.length;o++)i=n[o],m.o(d,i)&&d[i]&&d[i][0](),d[i]=0;return m.O(l)},(c=globalThis.rspackChunk_byted_doubao_apps_web_sdk_debugger_app||=[]).forEach(u.bind(null,0)),c.push=u.bind(null,c.push.bind(c));var g=m.O(void 0,["493","783","158","204"],()=>m(38114));g=m.O(g)})();
51
+ `}function mV(e,t){return t.find(t=>null==e?void 0:e.widgets.some(e=>e.widgetId===t))}function mG(e,t,r,i){var n;return{event:t,request_id:i.requestId,reply_message_id:i.replyMessageId,trace:{trace_id:(null==(n=e.trace)?void 0:n.trace_id)||`trace_mock_${e.idempotency_key??i.requestId}`,component:"mock_simulator",stage:t,sampled:!0},...r}}let mJ=async e=>{var t;let r=`找到和 ${(null==(t=e.arguments)?void 0:t.keyword)||"调试数据"} 相关的模拟结果`,i={content:[{type:"text",text:r}],structuredContent:{entities:[{entity_type:"debug_item",entity_id:"debug-item-1",name:"调试示例数据"}]},isError:!1},n=JSON.stringify(i);return{status:"succeeded",result:i.structuredContent,raw_result_text:r,raw_mcp_result_json:n,miniapp:{is_mini_app:!0,mcp_channel:"flow_miniapp"},debug:{mock:!0}}},mK=n0(nX),mZ=dI({requestHandler:async(e,t,r)=>{let i=e.params,n=r??nJ(i);return nF(n.url,"request"),nB(async t=>{var r,a;let s,o,l=await fetch("/__web_sdk_request_proxy__",{signal:t,body:JSON.stringify((s=new Headers(n.headers),{data:(o=n.body instanceof ArrayBuffer)?nH(n.body):n.body,dataEncoding:o?"base64":void 0,header:Object.fromEntries(s),method:n.method,url:n.url})),headers:{"content-type":"application/json"},method:"POST"}),d=(null==(r=l.headers.get("content-type"))?void 0:r.toLowerCase())??"",u=await l.text();if(!d.includes("application/json"))throw Error(`Request proxy returned a non-JSON response. Make sure the debugger is started with the local request proxy. Response starts with: ${u.slice(0,120)}`);let c=u?JSON.parse(u):{};if(!l.ok)throw Error((null==c?void 0:c.message)||`Request proxy failed with status ${l.status}`);if((null==c?void 0:c.dataEncoding)==="base64"&&"string"==typeof c.data){let t=nV((a=c.data,Uint8Array.from(atob(a),e=>e.charCodeAt(0)).buffer),i.dataType);return _(e,{statusCode:c.statusCode,header:c.header,data:t})}return _(e,c)})}});function mX(e,t){if(e.has(t))return!1;if(e.add(t),e.size>100){let t=e.values().next().value;t&&e.delete(t)}return!0}function mY(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";return new URL(window.location.href).searchParams.get(e)||r||t}async function mQ(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:fetch;try{var t;let r=await e("/__web_sdk_debug_context",{cache:"no-store",headers:{Accept:"application/json"}});return r.ok?!(t=await r.json())||"object"!=typeof t||Array.isArray(t)?{}:t:{}}catch{return{}}}async function m0(e,t){let r=t.skills,i=t.mcpServers,n=[];if("function"==typeof r&&n.push(Promise.resolve(r()).catch(()=>void 0)),"function"==typeof i){let t=e.getState();n.push(Promise.resolve(i({appKey:t.manifest.appId,appName:t.manifest.name,manifest:t.manifest.raw})).catch(()=>void 0))}await Promise.all(n)}function m1(){return(0,s.jsx)("main",{className:"chrome-devtools-unavailable-page",children:(0,s.jsx)("section",{className:"wsd-chrome-devtools",children:(0,s.jsx)("div",{className:"wsd-chrome-devtools-empty",children:"Chrome DevTools frontend is unavailable"})})})}function m2(e){let{serverDebugContext:t}=e,r=(0,iO.useMemo)(()=>(function(e){let t=e.searchParams.get("messages");if(null!==t)try{let e=JSON.parse(t);if(Array.isArray(e))return e;console.error("Failed to read initial messages: messages must be an array")}catch(e){console.error("Failed to read initial messages",e)}})(new URL(window.location.href)),[]),i=(0,iO.useMemo)(()=>new URL(window.location.href).searchParams.get("manifest")||nZ,[]),n=void 0!==r,a=(0,iO.useMemo)(()=>mY("mcp","",void 0),[]),o=(0,iO.useMemo)(()=>{let e;return(e=new URL(window.location.href)).searchParams.get("mcpOriginal")||e.searchParams.get("mcpEndpoint")||""},[]),l=(0,iO.useMemo)(()=>mY("simulatorManifest","/__simulator_manifest/manifest.yaml",void 0),[]),d=(0,iO.useMemo)(()=>new URL(window.location.href).searchParams.get("simulatorManifestOriginal")||"",[]),u=(0,iO.useMemo)(()=>mY("simulatorSkills","/__simulator_skills/index.json",void 0),[]),c=(0,iO.useMemo)(()=>new URL(window.location.href).searchParams.get("simulatorSkillsOriginal")||"",[]),p=(0,iO.useMemo)(()=>n0(new URL(window.location.href).searchParams.get("simulator")||mK),[]),h=(0,iO.useMemo)(()=>{let e;return(e=new URL(window.location.href)).searchParams.get("launchDir")||e.searchParams.get("projectPath")||e.searchParams.get("cwd")||""},[]),m=(0,iO.useMemo)(()=>`${window.location.origin}${window.location.pathname}`,[]),g=(0,iO.useMemo)(()=>{let e;return null!==(e=new URL(window.location.href).searchParams.get("DEBUG"))&&"0"!==e&&"false"!==e.toLowerCase()},[]),f=(0,iO.useMemo)(()=>"1"===new URL(window.location.href).searchParams.get("simulatorMock")||"true"===String((void 0)??"").toLowerCase(),[]),v=(0,iO.useRef)(null),y=(0,iO.useMemo)(()=>new iL,[]),b=y.clientId,[w,_]=(0,iO.useState)(),S=(0,iO.useRef)(new Set),x=(0,iO.useMemo)(()=>(function(e){var t,r,i,n,a,s;let o,l,d=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},u={mcpEndpoint:mP((t={mcpEndpoint:e,simulatorManifestUrl:d.simulatorManifestUrl,simulatorSkillsIndexUrl:d.simulatorSkillsIndexUrl}).mcpEndpoint),simulatorManifestUrl:mP(t.simulatorManifestUrl),simulatorSkillsIndexUrl:mP(t.simulatorSkillsIndexUrl)},c=function(){let e,t,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{mcpServers:async e=>{let t=Object.entries(Object.fromEntries(Object.entries((e.manifest??{}).tools??{}).filter(e=>{let[,t]=e;return!0===t.is_client_tool}))).map(e=>{let[t,r]=e;return{name:t,description:r.description,input_schema_json:function e(t){if(Array.isArray(t))return t.map(e);if(!rP(t))return t;let r={};for(let[i,n]of Object.entries(t))r[i]="type"===i&&"int"===n?"integer":"type"===i&&"float"===n?"number":e(n);return r}(r.input_schema)}});return 0===t.length?(az(r.onTraceEvent,{event:"client_tools_empty",app_key:e.appKey,server_id:aB,tool_count:0,tools:[]}),[]):(az(r.onTraceEvent,{event:"client_tools_resolved",app_key:e.appKey,server_id:aB,tool_count:t.length,tools:t.map(e=>e.name)}),[{server_id:aB,name:"Client Tool",description:"Client Tool runtime for simulator debugging",tools:t}])},toolExecutor:((t=async t=>{let i,n;try{i=function(e){let t=e.arguments;if(void 0===t){if(void 0===e.argumentsJson)t={};else if(void 0===(t=r3(e.argumentsJson)))throw Error("Tool arguments must be valid JSON")}if(!rP(t))throw Error("Tool arguments must be a JSON object");return t}(t),n="string"==typeof t.argumentsJson&&t.argumentsJson.trim()?t.argumentsJson:r6(i)}catch(e){return aK("CLIENT_TOOL_INVALID_ARGUMENTS",r5(e),!1)}try{var a;az(r.onTraceEvent,{event:"client_tool_call_started",request_id:t.requestId,trace_id:t.trace.trace_id,app_key:t.appKey,server_id:t.serverId,tool_call_id:t.toolCallId,tool_name:t.toolName,arguments:i,arguments_json:r6(i)});let s=await (()=>{var t,i;let n=null==(t=r.getRuntimeUrl)?void 0:t.call(r);if(!n)throw Error("Client Tool runtime is unavailable. Build the app with a Web Client Tool entry.");if(!e||e.runtimeUrl!==n){null==e||e.dispose();let t=(r.runtimeFactory??function(e,t){return new aH(e,t)})(n,null==(i=r.getRuntimeGlobalProps)?void 0:i.call(r));e=new aJ(n,t,r.onTraceEvent),az(r.onTraceEvent,{event:"client_tool_runtime_started",runtime_url:n})}return e})().invokeTool({toolId:t.toolName,input:n,context:{callbackId:t.toolCallId,conversationId:t.requestId,featureMap:void 0,msgId:t.replyMessageId,questionId:t.requestId},signal:t.signal}),o=function(e,t){var r,i;if(0===e.result)try{let i=function(e,t){if(!rP(e)||!Array.isArray(e.content))throw Error(`Client Tool "${t}" must return an MCP tool output object`);return e}(e.output,t.toolName),n=!0===i.isError?i:function(e,t){let r=aU(t.manifest,t.toolName);if(!r||"string"!=typeof r.kind)throw Error(`Client Tool "${t.toolName}" manifest output is required`);if("execution_result"===r.kind)return e;if("entities"!==r.kind)throw Error(`Client Tool "${t.toolName}" has unsupported output kind "${r.kind}"`);if(!rP(e)||!Array.isArray(e.structuredContent))throw Error(`Client Tool "${t.toolName}" must return structuredContent as an array`);return a$(e,t.manifest,t.toolName)}(i,t);return r=aq(n,{businessErrorCode:"CLIENT_TOOL_BUSINESS_ERROR",protocol:aW,source:"client_tool"}),{...r,debug:{...r.debug,mcp_output:i}}}catch(e){return aK("CLIENT_TOOL_INVALID_RESULT",r5(e),!1)}let n=void 0===(i=e.reason)?"":rP(i)?"string"==typeof i.message?i.message:r6(i):r5(i);return 2===e.result?aK("CLIENT_TOOL_NOT_FOUND",`Client Tool not found: ${e.toolId}`,!1):1===e.result?aK("CLIENT_TOOL_FAILED",n||`Client Tool failed: ${e.toolId}`,!1):aK("CLIENT_TOOL_UNKNOWN_RESULT",`Client Tool returned unknown status: ${String(e.result)}`,!1)}(s,t);return az(r.onTraceEvent,{event:"succeeded"===o.status?"client_tool_call_succeeded":"client_tool_call_failed",request_id:t.requestId,app_key:t.appKey,server_id:t.serverId,tool_call_id:t.toolCallId,tool_name:t.toolName,status:o.status,result:o.result,raw_mcp_result_json:o.raw_mcp_result_json,error:null==(a=o.error)?void 0:a.message}),o}catch(i){let e=r5(i);return az(r.onTraceEvent,{event:"client_tool_call_failed",request_id:t.requestId,app_key:t.appKey,server_id:t.serverId,tool_call_id:t.toolCallId,tool_name:t.toolName,error:e}),aK("CLIENT_TOOL_CALL_FAILED",e,!0)}}).dispose=()=>{null==e||e.dispose(),e=void 0},t)}}({getRuntimeGlobalProps:d.getClientToolRuntimeGlobalProps,getRuntimeUrl:d.getClientToolRuntimeUrl,onTraceEvent:d.onTraceEvent}),p=c.toolExecutor,h=c.mcpServers,m=()=>{var e;return l??=Promise.resolve(u.mcpEndpoint||(null==(e=d.getMcpEndpoint)?void 0:e.call(d))).then(e=>{let t=mP(e);return o=t?function(e){let t=rj(e.endpoint);if(!t)return{};let r=function(e,t){if(null==t?void 0:t.trim())return t.trim();let r=new URL(e);return`${r.hostname}_${r.port||r.protocol.replace(":","")}${r.pathname}`.replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/^_+|_+$/g,"")||"local_mcp"}(t,e.serverId);return{mcpServers:async i=>{let n;try{dC(e.onTraceEvent,{event:"local_mcp_tools_load_started",app_key:i.appKey,mcp_endpoint:t,server_id:r},i),n=await dN(t,{...e,signal:i.signal});let a=await n.client.listTools(void 0,{signal:i.signal}),s=n.client.getServerVersion(),o={server_id:r,name:(null==s?void 0:s.name)||r,description:n.client.getInstructions()||"",tools:a.tools.map(dE).filter(e=>e.name)};return dC(e.onTraceEvent,{event:"local_mcp_tools_loaded",app_key:i.appKey,mcp_endpoint:t,server_id:o.server_id,server_version:s,tools:o.tools.map(e=>e.name)},i),[o]}catch(n){var a;return null==(a=i.signal)||a.throwIfAborted(),dC(e.onTraceEvent,{event:"local_mcp_tools_load_failed",app_key:i.appKey,mcp_endpoint:t,server_id:r,error:r5(n),request_will_continue:!0,tool_count:0,tools:[]},i),console.warn("[web-sdk-debugger] Failed to load MCP tools",n),[]}finally{n&&await dT(n)}},toolExecutor:async r=>{var i;let n,a=r.arguments??r3(r.argumentsJson)??{},s=r.argumentsJson||r6(a),o=Date.now();try{dC(e.onTraceEvent,{event:"local_mcp_call_started",request_id:r.requestId,trace_id:r.trace.trace_id,app_key:r.appKey,server_id:r.serverId,tool_call_id:r.toolCallId,tool_name:r.toolName,arguments:a,arguments_json:s,mcp_endpoint:t}),n=await dN(t,{...e,signal:r.signal,headers:function(e,t){if(!e&&!t)return;let r=new Headers(e);for(let[e,i]of Object.entries(t??{}))r.set(e,i);return r}(e.headers,r.headers)}),null==(i=r.signal)||i.throwIfAborted();let l=await n.client.callTool({name:r.toolName,arguments:a,_meta:{request_id:r.requestId,trace_id:r.trace.trace_id,app_key:r.appKey,server_id:r.serverId,tool_call_id:r.toolCallId,tool_name:r.toolName,arguments_json:s}},{signal:r.signal}),d=!0===l.isError?l:a$(l,r.manifest,r.toolName),u=aq(d,{businessErrorCode:"LOCAL_MCP_BUSINESS_ERROR",protocol:"streamable_http",source:"local_mcp"});return u.debug={...u.debug,mcp_output:l},dC(e.onTraceEvent,{event:"local_mcp_call_succeeded",request_id:r.requestId,trace_id:r.trace.trace_id,app_key:r.appKey,server_id:r.serverId,tool_call_id:r.toolCallId,tool_name:r.toolName,status:u.status,result:u.result,raw_result_text:u.raw_result_text,raw_mcp_result:d,elapsed_ms:Date.now()-o,mcp_endpoint:t}),u}catch(n){if(aT(n))throw n;let i=r5(n);return dC(e.onTraceEvent,{event:"local_mcp_call_failed",request_id:r.requestId,trace_id:r.trace.trace_id,app_key:r.appKey,server_id:r.serverId,tool_call_id:r.toolCallId,tool_name:r.toolName,error:i,elapsed_ms:Date.now()-o,mcp_endpoint:t}),{status:"failed",result:{error:i},error:{code:"LOCAL_MCP_CALL_FAILED",message:i,retryable:!0,stage:"tool_execute"},raw_result_text:i}}finally{n&&await dT(n)}}}}({endpoint:t,onTraceEvent:d.onTraceEvent}):void 0})},g=async e=>{let[t,r]=await Promise.all([m(),h(e)]);if(!t)return r;let i=t.mcpServers;return[...await i(e),...r]},f=async e=>{if(e.serverId===aB)return p(e);let t=await m();if(!t){let e="Local MCP is not configured";return{status:"failed",result:{error:e},error:{code:"LOCAL_MCP_NOT_CONFIGURED",message:e,retryable:!1,stage:"tool_execute"},raw_result_text:e}}return t.toolExecutor(e)};return f.dispose=()=>{var e,t,r;null==(e=p.dispose)||e.call(p),null==o||null==(r=o.toolExecutor)||null==(t=r.dispose)||t.call(r)},{simulatorManifest:u.simulatorManifestUrl?(r=u.simulatorManifestUrl,i=d.onTraceEvent,n=d.getAppId,async e=>{let t;mD(i,"manifest",r);try{if(!(t=await fetch(r,{signal:e,cache:"no-store",headers:{Accept:"application/yaml, text/yaml, text/x-yaml, application/json, text/plain"}})).ok)throw m$("manifest",r,t);let a=await t.text(),s=function(e){let t=(0,aO.qg)(e);if(!rP(t))throw Error("Simulator manifest must be a YAML object");return t}(a),o=s.app_key?void 0:await (null==n?void 0:n());if(n&&!o&&!s.app_key)throw Error("Sandbox 调试应用尚未就绪,请重建调试会话后重试。");let l=o?{...s,app_key:o}:s;return mO(i,"manifest",r,t,{bytes:a.length}),{...l,raw_manifest_yaml:o?(0,aO.As)(l):a}}catch(e){throw mU(i,"manifest",r,e,t),console.warn("[web-sdk-debugger] Failed to load simulator manifest supplement",e),e}}):void 0,skills:u.simulatorSkillsIndexUrl?(a=u.simulatorSkillsIndexUrl,s=d.onTraceEvent,async e=>{let t;mD(s,"skill",a);try{var r;if(!(t=await fetch(a,{signal:e,cache:"no-store",headers:{Accept:"application/json"}})).ok)throw m$("skill",a,t);let i=await t.text();if(((null==(r=t.headers.get("content-type"))?void 0:r.toLowerCase())??"").includes("text/html")||/^<!doctype html\b|^<html[\s>]/i.test(i.trimStart()))throw Error(`Simulator skills index returned HTML instead of JSON (${a})`);let n=function(e){if(!rP(e)||!Array.isArray(e.skills))throw Error("Simulator skills index must contain a skills array");return e.skills.map((e,t)=>{var r;if(!(rP(r=e)&&"string"==typeof r.relativePath&&"string"==typeof r.content))throw Error(`Simulator skills index contains an invalid entry at index ${t}`);return e}).sort((e,t)=>e.relativePath<t.relativePath?-1:+(e.relativePath>t.relativePath))}(JSON.parse(i));return mO(s,"skill",a,t,{bytes:i.length,skill_paths:n.map(e=>e.relativePath)}),n}catch(e){throw mU(s,"skill",a,e,t),console.warn("[web-sdk-debugger] Failed to load simulator skills",e),e}}):void 0,mcpServers:g,toolExecutor:f}})(a,{getClientToolRuntimeGlobalProps:()=>{var e;let t=null==(e=v.current)?void 0:e.getState().manifest;return t?tq(t):void 0},getClientToolRuntimeUrl:()=>{var e;let t=null==(e=v.current)?void 0:e.getState();return t?function(e,t,r){var i,n,a,s,o,l;let d,u=(null==(a=t.applet)||null==(n=a.web)||null==(i=n.toolRuntimeEntry)?void 0:i.trim())||(null==(o=t.applet)||null==(s=o.toolRuntimeEntry)?void 0:s.trim());if(!u)return;let c=new URL(u,((d=new URL(String(e),(null==(l=globalThis.location)?void 0:l.href)||"http://localhost/")).pathname.endsWith("/base/manifest.json")?d.pathname=d.pathname.slice(0,-18):d.pathname=d.pathname.replace(/\/[^/]*$/,"/"),d.search="",d.hash="",d));return r&&c.searchParams.set("__doubao_resource_reload",r),c.toString()}(t.manifestUrl,t.manifest.raw,t.resourceUrlVersion):void 0},getMcpEndpoint:async()=>t.mcpProxyEndpoint,getAppId:async()=>(await mQ()).sandboxAppId,onTraceEvent:e=>{var t;return null==(t=v.current)?void 0:t.appendSimulatorTraceEvent(e)},simulatorManifestUrl:l,simulatorSkillsIndexUrl:u}),[a,l,u,t.mcpProxyEndpoint]),I=(0,iO.useMemo)(()=>{let e=f?{appKey:mq,appName:"调试示例应用插件",mcpServers:mz,simulatorFetch:function(e){let{getDebuggerState:t}=e;return async(e,r)=>{var i,n,a,s,o,l,d,u;let c,p,h,m,g,f,v,y,b=String(e);if(b.endsWith("/simulator/tool/report")){let e="string"==typeof(null==r?void 0:r.body)?JSON.parse(r.body):{};return new Response(JSON.stringify({code:0,message:"OK",request_id:e.request_id,tool_call_id:e.tool_call_id,trace:e.trace}),{headers:{"Content-Type":"application/json"},status:200,statusText:"OK"})}return b.endsWith("/simulator/chat")?(y=(i="string"!=typeof(null==r?void 0:r.body)?{}:JSON.parse(r.body),s=t(),p=((c=new URL(window.location.href).searchParams.get("simulatorMockWidget"))?mV(s,[c]):void 0)||mV(s,mW)||(null==s||null==(o=s.widgetSelection)?void 0:o.item.widgetId)||(null==(l=s)||null==(d=l.widgets.find(e=>{var t;return null==(t=e.web)?void 0:t.entry}))?void 0:d.widgetId)||(null==l||null==(u=l.widgets[0])?void 0:u.widgetId)||"weather-card",h=Date.now().toString(36),m={requestId:`req_mock_server_${h}`,replyMessageId:`msg_mock_reply_${h}`},g=(null==(n=i.message)?void 0:n.content)||"模拟请求",f=`call_mock_${h}`,v={applet_id:i.app_id||mq,widget_id:p,entity_id:"mock-entity-1",viewData:{source:"web-sdk-debugger-mock",keyword:g,widgetId:p},extra:{"doubao/outputTemplate":"mock.output.template"}},[mG(i,"ack",{ack:{request_id:m.requestId,message_id:m.replyMessageId,local_message_id:null==(a=i.message)?void 0:a.local_message_id}},m),mG(i,"tool_call",{tool_call:{tool_call_id:f,tool_name:mF,server_id:mB,app_key:i.app_id||mq,arguments_json:JSON.stringify({keyword:g}),status:"PENDING",timeout_ms:2e3}},m),mG(i,"tool_status",{tool_status:{tool_call_id:f,status:"RUNNING",progress:.6,message:"Mock tool running"}},m),mG(i,"text_delta",{text_delta:{block_id:"block_mock_text",op:"append",delta:`Mock 已收到:${g}`}},m),mG(i,"card_delta",{card_delta:{block_id:"block_mock_card",op:"append",card_id:`card_mock_${h}`,source_tool_call_id:f,source_entity_ids:["mock-entity-1"],is_final:!0,card:{card_id:`card_mock_${h}`,card_type:"mock_widget_card",title:"Mock 应用插件卡片",fallback_text:`使用 ${p} 渲染`,props_json:JSON.stringify(v)}}},m),mG(i,"debug",{debug_event:{category:"mock",title:"Mock Simulator",summary:"本地 mock SSE 已生成 text/card/tool 事件",data:{widget_id:p},redaction_level:"none"}},m),mG(i,"answer_finish",{answer_finish:{status:"completed",finish_reason:"stop",usage:{output_tokens:12}}},m),mG(i,"reply_finish",{reply_finish:{status:"completed",finish_reason:"stop",event_count:7}},m)]).map(mH).join(""),new Response(new ReadableStream({start(e){e.enqueue(new TextEncoder().encode(y)),e.close()}}),{headers:{"Content-Type":"text/event-stream"},status:200,statusText:"OK"})):new Response(JSON.stringify({ok:!1,error:"Unknown mock simulator endpoint"}),{status:404,statusText:"Not Found"})}}({getDebuggerState:()=>{var e;return(null==(e=v.current)?void 0:e.getState())??null}}),toolExecutor:mJ}:{},t=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return new si(e)}({manifestUrl:i,simulatorEndpoint:p,...x,...e});return r&&t.pushMessages(r),v.current=t,t},[i,p,x,f,r]),[k,C]=(0,iO.useState)(()=>{let e,t,r;return t=(e=new URL(window.location.href)).searchParams.get("view"),r=e.searchParams.get("debugMode")||e.searchParams.get("mode"),"conversation"===t||"tool"===t||"card"===t||"page"===t?t:"conversation"===r||"tool"===r||"card"===r||"page"===r?r:"conversation"}),E=cl((e,t)=>{mX(S.current,e)&&y.reportResult({commandId:e,...t}).catch(e=>console.error(e)).finally(()=>{_(t=>(null==t?void 0:t.commandId)===e?void 0:t)})}),N=cl(e=>{if("cancel_chat_query"===e.type){cj(I,e.commandId),E(e.commandId,{ok:!1,error:{code:"CHAT_TIMEOUT",message:"Chat query was cancelled after the debugger control timeout"}});return}"execute_sandbox_tool_call"===e.type?I.executeSandboxToolCall(e.toolCall).then(t=>{E(e.commandId,{ok:!0,result:{reported:t.reported,request_id:t.requestId,tool_call_id:t.toolCallId}})}).catch(t=>{E(e.commandId,{error:{code:"TOOL_CALL_FAILED",message:t instanceof Error?t.message:String(t)},ok:!1})}):(_(e),("render_page"===e.type||"render_widget"===e.type||"submit_chat_query"===e.type)&&C("render_page"===e.type?"page":"render_widget"===e.type?"card":"conversation"))}),T=cl(e=>{try{return I.navigateToPage(e.url,{routeMode:e.routeMode}),C("page"),!0}catch{return!1}}),A=cl(()=>{let{manifest:e}=I.getState();return{appKey:e.appId,appName:e.name}});(0,iO.useEffect)(()=>{let e=y.subscribe(e=>{if("control"===e.type)N(e.data);else if("status"===e.type&&"connected"!==e.status){let e=cj(I);e&&mX(S.current,e),_(void 0)}});return y.start(),()=>{e(),y.stop()}},[y,N,I]),(0,iO.useEffect)(()=>{if(n)return window.webSdkDebugger=I,()=>{window.webSdkDebugger===I&&delete window.webSdkDebugger}},[n,I]),(0,iO.useEffect)(()=>(function(e){let t=document.modelContext;if(!t)return()=>{};let r=new AbortController,i=new URL("/__wsd_mcp",window.location.href);async function n(e){let t=await dN(i.href,{});try{return await e(t.client)}finally{await dT(t)}}return i.searchParams.set("clientId",e),(async function(){let{tools:e}=await n(e=>e.listTools());for(let a of e){var i;r.signal.throwIfAborted(),await t.registerTool({name:a.name,description:a.description??"",inputSchema:a.inputSchema,annotations:{readOnlyHint:(null==(i=a.annotations)?void 0:i.readOnlyHint)===!0,untrustedContentHint:!0},execute:async function(e){let{signal:t}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return r.signal.throwIfAborted(),null==t||t.throwIfAborted(),n(async r=>{null==t||t.throwIfAborted();let i=await r.callTool({name:a.name,arguments:e},{signal:t,timeout:13e4}),n=JSON.stringify(i);if(i.isError)throw Error(n);return n})}},{signal:r.signal})}})().catch(e=>{r.signal.aborted||(r.abort(),console.warn("[web-sdk-debugger] Failed to register WebMCP tools",e))}),()=>r.abort()})(b),[b]),(0,iO.useEffect)(()=>{let e=!1;return I.loadManifest(i).then(()=>{if(!e){let e;return e=new URL(window.location.href),i===nZ?e.searchParams.delete("manifest"):e.searchParams.set("manifest",i),window.history.replaceState(null,"",e),m0(I,x)}}).catch(()=>{}),()=>{e=!0,I.destroy(),v.current===I&&(v.current=null)}},[i,x,I]);let M=(0,iO.useMemo)(()=>({launchDir:h,simulatorManifestOriginalUrl:d,simulatorManifestProxyUrl:l,simulatorManifestUrl:l,simulatorSkillsIndexOriginalUrl:c,simulatorSkillsIndexProxyUrl:u,simulatorSkillsIndexUrl:u,webUrl:m,...t,mcpEndpoint:a||t.mcpProxyEndpoint,mcpOriginalEndpoint:o||t.mcpOriginalEndpoint,mcpProxyEndpoint:a||t.mcpProxyEndpoint}),[h,a,o,d,l,c,u,m,t]);return(0,s.jsx)(iD.M,{children:(0,s.jsx)("section",{className:"workspace",children:(0,s.jsx)("section",{className:"debug-workspace",children:(0,s.jsx)("section",{className:"debug-mode-panel",children:(0,s.jsx)(ch,{capability:M.realDeviceDebug,getAppIdentity:A,children:(0,s.jsx)(mj,{messageInputDisabled:n,activeView:k,apiEnvironment:mZ,chromeDevToolsFrontendUrl:"/chrome-devtools/inspector.html",controlCommand:w,controlClientId:b,debugContext:M,onActiveViewChange:C,onControlResult:E,onNavigateToPage:T,showDebugTrace:g,connection:y,webSdkDebugger:I})})})})})})}function m3(e){let{serverDebugContext:t}=e;return window.location.pathname.startsWith("/chrome-devtools/")?(0,s.jsx)(m1,{}):(0,s.jsx)(m2,{serverDebugContext:t})}async function m4(){let e=await mQ();e.webViewOrigin&&(tK=t=>({messageTransport:"window",url:`${e.webViewOrigin}/__webview/bootstrap?${new URLSearchParams({url:t,parentOrigin:location.origin})}`}));let t=document.querySelector("#app");if(!t)throw Error("Cannot find #app");(0,rZ.H)(t).render((0,s.jsx)(m3,{serverDebugContext:e}))}(async function(){if("serviceWorker"in navigator){let e=e=>(null==e?void 0:e.scriptURL)===new URL("/__webview/sw.js",location.origin).href,t=e(navigator.serviceWorker.controller),r=await navigator.serviceWorker.getRegistrations();if(await Promise.all(r.filter(t=>e(t.active)||e(t.waiting)||e(t.installing)).map(e=>e.unregister())),t)return void location.reload()}await m4()})().catch(m4)}},h={};function m(e){var t=h[e];if(void 0!==t)return t.exports;var r=h[e]={id:e,exports:{}};return p[e].call(r.exports,r,r.exports,m),r.exports}m.m=p,m.c=h,t=(e="function"==typeof Symbol)?Symbol("rspack queues"):"__rspack_queues",r=m.aE=e?Symbol("rspack exports"):"__webpack_exports__",i=e?Symbol("rspack error"):"__rspack_error",n=e?Symbol("rspack done"):"__rspack_done",a=m.zS=e?Symbol("rspack defer"):"__rspack_defer",m.zT=e=>{if(e.some(e=>{var t=h[e];return!t||!1===t[n]}))return{then:(t,r)=>Promise.all(e.map(m)).then(t,r)}},s=e=>{e&&e.d<1&&(e.d=1,e.forEach(e=>e.r--),e.forEach(e=>e.r--?e.r++:e()))},m.a=(e,o,l,d)=>{l&&((u=[]).d=-1);var u,c,p,h,g=new Set,f=e.exports,v=new Promise((e,t)=>{h=t,p=e});v[r]=f,v[t]=e=>{u&&e(u),g.forEach(e),v.catch(()=>{})},e.exports=v;var y=e;d&&((y=Object.create(e)).exports=f),o(e=>{c=e.map(e=>{if(null!==e&&"object"==typeof e){if(!e[t]&&e[a]){var n=m.zT(e[a]);if(!n)return e;var o=e;e={then(e,t){n.then(()=>e(o),t)}}}if(e[t])return e;if(e.then){var l=[];l.d=0,e.then(e=>{d[r]=e,s(l)},e=>{d[i]=e,s(l)});var d={};return d[a]=!1,d[t]=e=>e(l),d}}var u={};return u[t]=()=>{},u[r]=e,u});var n,o=()=>c.map(e=>{if(e[a])return e;if(e[i])throw e[i];return e[r]}),l=new Promise(e=>{(n=()=>e(o)).r=0;var r=e=>e!==u&&!g.has(e)&&(g.add(e),e&&!e.d&&(n.r++,e.push(n)));c.map(e=>e[a]||e[t](r))});return n.r?l:o()},e=>(e?h(v[i]=e):(d&&(f=v[r]=y.exports),p(f)),s(u),v[n]=!0),y),u&&u.d<0&&(u.d=0)},m.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return m.d(t,{a:t}),t},m.d=(e,t,r)=>{var i=(t,r)=>{for(var i in t)m.o(t,i)&&!m.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,[r]:t[i]})};i(t,"get"),i(r,"value")},m.f={},m.e=(e,t)=>Promise.all(Object.keys(m.f).reduce((r,i)=>(m.f[i](e,r,t),r),[])),m.u=e=>"static/js/async/"+(({166:"xmarkdown-deps",350:"web-core-template-loader-thread",724:"web-elements",778:"legacy-wasm-js",894:"web-core-main-chunk",97:"web-core-worker-chunk"})[e]||e)+"."+({166:"ff739dc3dc",257:"4d55bd5ce8",350:"559b06cf7a",503:"259fed5610",724:"262cae995c",778:"555371d3dd",894:"0802207289",97:"97f5cf9510"})[e]+".js",m.miniCssF=e=>""+e+".css",m.g=(()=>{if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}})(),m.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),o={},m.l=function(e,t,r,i,n){if(o[e])return void o[e].push(t);if(void 0!==r)for(var a,s,l=document.getElementsByTagName("script"),d=0;d<l.length;d++){var u=l[d];if(u.getAttribute("src")==e||u.getAttribute("data-rspack")=="@byted-doubao-apps/web-sdk-debugger-app:"+r){a=u;break}}a||(s=!0,(a=document.createElement("script")).timeout=120,m.nc&&a.setAttribute("nonce",m.nc),a.setAttribute("data-rspack","@byted-doubao-apps/web-sdk-debugger-app:"+r),n&&a.setAttribute("fetchpriority",n),a.src=e),o[e]=[t];var c=function(t,r){a.onerror=a.onload=null,clearTimeout(p);var i=o[e];if(delete o[e],a.parentNode&&a.parentNode.removeChild(a),i&&i.forEach(function(e){return e(r)}),t)return t(r)},p=setTimeout(c.bind(null,void 0,{type:"timeout",target:a}),12e4);a.onerror=c.bind(null,a.onerror),a.onload=c.bind(null,a.onload),s&&document.head.appendChild(a)},m.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},l=[],m.O=(e,t,r,i)=>{if(t){i=i||0;for(var n=l.length;n>0&&l[n-1][2]>i;n--)l[n]=l[n-1];l[n]=[t,r,i];return}for(var a=1/0,n=0;n<l.length;n++){for(var[t,r,i]=l[n],s=!0,o=0;o<t.length;o++)(!1&i||a>=i)&&Object.keys(m.O).every(e=>m.O[e](t[o]))?t.splice(o--,1):(s=!1,i<a&&(a=i));if(s){l.splice(n--,1);var d=r();void 0!==d&&(e=d)}}return e},m.p="/",m.j="410",m.b=document.baseURI||self.location.href,d={410:0},m.f.j=function(e,t,r){var i=m.o(d,e)?d[e]:void 0;if(0!==i)if(i)t.push(i[2]);else{var n=new Promise((t,r)=>i=d[e]=[t,r]);t.push(i[2]=n);var a=m.p+m.u(e),s=Error();m.l(a,function(t){if(m.o(d,e)&&(0!==(i=d[e])&&(d[e]=void 0),i)){var r=t&&("load"===t.type?"missing":t.type),n=t&&t.target&&t.target.src;s.message="Loading chunk "+e+" failed.\n("+r+": "+n+")",s.name="ChunkLoadError",s.type=r,s.request=n,i[1](s)}},"chunk-"+e,e,r)}},m.O.j=e=>0===d[e],u=(e,t)=>{var r,i,[n,a,s]=t,o=0;if(n.some(e=>0!==d[e])){for(r in a)m.o(a,r)&&(m.m[r]=a[r]);if(s)var l=s(m)}for(e&&e(t);o<n.length;o++)i=n[o],m.o(d,i)&&d[i]&&d[i][0](),d[i]=0;return m.O(l)},(c=globalThis.rspackChunk_byted_doubao_apps_web_sdk_debugger_app||=[]).forEach(u.bind(null,0)),c.push=u.bind(null,c.push.bind(c));var g=m.O(void 0,["493","783","158","279"],()=>m(38114));g=m.O(g)})();