@doubao-dev/kit 0.9.0 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/277~0.js +1 -1
- package/dist/assets/web-sdk-debugger/__doubao_web_sdk_native_modules/applet-bridge-module-core.js +1 -1
- package/dist/assets/web-sdk-debugger/assets/framework/{doubao-apps-api.template.ebf75b699f.bundle → doubao-apps-api.template.a6a4208461.bundle} +0 -0
- package/dist/assets/web-sdk-debugger/assets/framework/doubao-apps-api.template.js +0 -0
- package/dist/assets/web-sdk-debugger/assets/framework/{doubao-apps-framework.template.d266ec6564.bundle → doubao-apps-framework.template.b424cdeeba.bundle} +0 -0
- package/dist/assets/web-sdk-debugger/assets/framework/doubao-apps-framework.template.js +0 -0
- package/dist/assets/web-sdk-debugger/index.html +1 -1
- package/dist/assets/web-sdk-debugger/static/js/{index.687797d67a.js → index.c66a9f9f15.js} +2 -2
- package/dist/cli/index.js +1 -1
- package/dist/sdk.js +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(()=>{"use strict";var e,t,r,i,a,n,s,o,l,d,u,c,p={72941(e,t,r){let i,a,n;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){let t=o(e)?e.appTheme:void 0;return"light"===t||"dark"===t?t:void 0}function d(e){var t;return"string"==typeof(null==(t=e.web)?void 0:t.entry)}function u(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 c(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 p{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(d),this.pageIdEntryMap=u(this.pageEntries,e=>e.id),this.pagePathEntryMap=u(this.pageEntries,e=>{var t;return(null==(t=e.path)?void 0:t.startsWith("/"))?e.path:void 0}),this.widgetEntries=e.widgets,this.widgetEntryMap=u(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 c(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 h(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 a=await i.json();if(!o(a))throw Error("Invalid Web manifest: expected a JSON object");return new p(a)}function m(e,t,r){var i,a;let n="item"in t?t.item:t,s="id"in n||"widgetId"in n?"string"==typeof(null==(i=n.web)?void 0:i.entry)?n.web.entry:void 0:n.entry;if(!s)return;let o=new URL(e,r??(null==(a=globalThis.location)?void 0:a.href)??"http://localhost/");return o.pathname=o.pathname.replace(/\/base\/manifest\.json$/,"/"),new URL(s,o).toString()}function g(){let e=Error("Widget host call was cancelled");return e.name="AbortError",e}function f(e){if(e.aborted)throw g()}function v(e,t){return f(t),new Promise((r,i)=>{let a=!1,n=e=>{a||(a=!0,t.removeEventListener("abort",s),e())},s=()=>n(()=>i(g()));t.addEventListener("abort",s,{once:!0}),Promise.resolve().then(e).then(e=>n(()=>r(e)),e=>n(()=>i(e)))})}function y(e){return(null==e?void 0:e.type)==="call"}function b(e){return(null==e?void 0:e.type)==="callback"}function w(e){return(null==e?void 0:e.type)==="event"}class _ 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 S(e,t){return{type:"callback",callbackId:e.callbackId,params:{code:1,data:t}}}function x(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 I(e){return e instanceof Error?e.message:String(e)}function k(e,t){return t instanceof _?x(e,t.message,t.errNo,t.errMsg):x(e,I(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 C{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),a="function"==typeof t?{handler:t,canIUse:!0}:{...t,canIUse:t.canIUse??!0};return this.registry.set(e,a),this.handlers[e]=a.handler,()=>{if(this.registry.get(e)===a){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,a]of Object.entries(e))r.push(this.register(i,a,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),a="function"==typeof t?{source:t}:t;return this.stopEventSource(e),this.eventSources.set(e,a),(this.eventSourceRetainCounts.get(e)??0)>0&&this.startEventSource(e,a),()=>{if(this.eventSources.get(e)===a){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,a]of Object.entries(e))r.push(this.registerEventSource(i,a,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(!y(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(!y(e))return;let i=t[e.name];if(!i)return x(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=>k(e,t));return t??x(e,`API ${e.name} is not implemented in Doubao Web SDK`)}catch(t){return k(e,t)}}(e,this.handlers,i);let a=this.registry.has(e.name)?103:-1;if(!r)return x(e,`API ${e.name} is not implemented in Doubao Web SDK`,a);try{let t=r(e.name);return t instanceof Promise?t.then(()=>x(e,`API ${e.name} is not implemented in Doubao Web SDK`,a)).catch(t=>k(e,t)):x(e,`API ${e.name} is not implemented in Doubao Web SDK`,a)}catch(t){return k(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 E(this,e)}fork(){let e=new C(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,a;null==(a=this.eventSources.get(e))||null==(i=a.onSubscribe)||i.call(a,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 E{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 N=new C;function T(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:i;return null==e?void 0:e.getPackageInfo()}async function A(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 M(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 j(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i;return await (null==t?void 0:t.reLaunch(e)),!!t}function R(){return"0.9.0"}function P(e){var t;let{screenWidth:r,statusBarHeight:i}=e??(null==(t=globalThis.lynx)?void 0:t.__globalProps),a=Math.round(i)+4,n=Math.round(r)-12;return{bottom:a+36,height:36,left:n-84,right:n,top:a,width:84}}function L(){return(navigator.language||"zh-CN").replace(/-/g,"_")}function O(){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:R()??""}function U(){return navigator.userAgentData}function $(){var e;let t=null==(e=U())?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 q(){var e,t;let r=null==(e=U())?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 a=navigator.userAgent??"";return(null==(t=/(?:edg|chrome|crios|firefox|fxios|version)\/([\d.]+)/i.exec(a))?void 0:t[1])??void 0}function B(){var e;let t=navigator.userAgent??"",r=navigator.platform??"",i=(null==(e=U())?void 0:e.platform)??"",a=`${i} ${r} ${t}`,n=navigator.maxTouchPoints??0;return/android/i.test(a)?{platform:"android",brand:"Android"}:/iphone/i.test(a)?{platform:"ios",brand:"iPhone"}:/ipad/i.test(a)||/mac/i.test(r)&&n>1?{platform:"ios",brand:"iPad"}:/mac/i.test(a)?{platform:"mac",brand:"Mac"}:/win/i.test(a)?{platform:"windows",brand:"Windows"}:/linux/i.test(a)?{platform:"linux",brand:"Linux"}:{platform:"web",brand:"Browser"}}function F(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:T();return{appId:(null==e?void 0:e.appId)??"",name:(null==e?void 0:e.name)??"",iconSrc:null==e?void 0:e.iconSrc}}function W(e){var t,r,i,a,n;if((null==e?void 0:e.containerWidth)!==void 0){let{density:t=1,screenWidth:r=0,screenHeight:i=0,containerWidth:a=0,containerHeight:n=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:a,windowHeight:n,statusBarHeight:s,screenTop:o,safeArea:{left:c,right:a-p,top:d,bottom:n-u,width:a-c-p,height:n-d-u}}}let s=Math.round((null==(a=window.visualViewport)?void 0:a.width)??window.innerWidth??0),o=Math.round((null==(n=window.visualViewport)?void 0:n.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 z(){return B().platform}function H(){var e,t,r,i,a;let n=navigator.userAgent??"",s=z();return"android"===s?null==(e=/android\s+([\d.]+)/i.exec(n))?void 0:e[1]:"ios"===s?null==(r=/(?:iphone os|cpu os)\s+([\d_]+)/i.exec(n))||null==(t=r[1])?void 0:t.replace(/_/g,"."):"mac"===s?null==(a=/mac os x\s+([\d_]+)/i.exec(n))||null==(i=a[1])?void 0:i.replace(/_/g,"."):void 0}function V(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:z();return"android"===e?"Android":"ios"===e?"iOS":"mac"===e?"macOS":"windows"===e?"Windows":"linux"===e?"Linux":"Web"}function G(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=B(),i=navigator.platform||z();return{abi:i,deviceAbi:i,benchmarkLevel:-1,brand:r.brand,model:function(){let e=navigator.userAgent??"",t=z();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?B().brand:"mac"===t||"windows"===t||"linux"===t?navigator.platform||B().brand:$()}(),system:function(){let e=z(),t=H();if("web"!==e){let r=V(e);return t?`${r} ${t}`:r}let r=q(),i=$();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 J(){let e=G(),t=W(),r=t.windowWidth>t.windowHeight,i=O();return{os:V(e.platform),platform:e.platform,osVersion:H(),deviceBrand:e.brand,language:L(),deviceModel:e.model,deviceType:e.model,deviceAbi:e.deviceAbi,cpuType:e.cpuType,memorySize:e.memorySize,benchmarkLevel:e.benchmarkLevel,appVersion:q(),appTheme:i,theme:i,channel:"release",screenOrientation:+!!r,isLandscape:+!!r,abi:e.abi}}function K(e){var t,r,i;let a,n=W(e),s=G(e);return{...n,brand:s.brand,model:s.model,language:(null==e||null==(t=e.language)?void 0:t.replace(/-/g,"_"))??L(),version:(null==e?void 0:e.appVersion)??q(),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)??O(),benchmarkLevel:s.benchmarkLevel,enableDebug:(null==e?void 0:e.channel)==="debug",deviceOrientation:(i=n.windowWidth>n.windowHeight,!0===(a=(null==e?void 0:e.isLandscape)??(null==e?void 0:e.screenOrientation))||1===a||"string"==typeof a&&a.toLowerCase().includes("landscape")?"landscape":!1===a||0===a||"string"==typeof a&&a.toLowerCase().includes("portrait")?"portrait":i?"landscape":"portrait"),abi:s.abi}}function Z(){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 X(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)??L(),version:(null==e?void 0:e.appVersion)??q(),theme:(null==e?void 0:e.appTheme)??O()}}function Y(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:T(),t=arguments.length>1?arguments[1]:void 0;return{miniProgram:{appId:F(e).appId,envVersion:(null==t?void 0:t.channel)==="debug"?"develop":"release",version:(null==e?void 0:e.versionName)??""}}}function Q(e){var t;return(null==e||null==(t=e.navigation)?void 0:t.getPackageInfo())??(null==e?void 0:e.packageInfo)}N.handlers,r(31178),r(32085),r(12021);var ee=r(95550),et=r(66013);r(46455);function er(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 ei(e){if(ea(e)>1048576)throw Error("data size must be less than or equal to 1048576 bytes")}function ea(e){return new TextEncoder().encode(e).byteLength}function en(e){return Object.values(e).reduce((e,t)=>e+ea(t),0)}function es(e){if(e>0xa00000)throw new _("total storage size exceeded",1600002)}function eo(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(er(r),"string"!=typeof i)throw Error("Storage values must be serialized strings");ei(i),t+=ea(i)}es(t)}let el=new Map,ed=new Map,eu=new Set;function ec(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,et.My)((0,ee.sc)(i))}`}function ep(){let e=Date.now();return{entries:Object.fromEntries(["/","/temp","/user"].map(t=>[t,{type:"directory",createTime:e,lastModifiedTime:e}]))}}function eh(){return a??=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(),a=void 0},e(r.result)},r.onerror=()=>{a=void 0,t(r.error)},r.onblocked=()=>{a=void 0,t(Error("Storage database upgrade is blocked; close other app views and retry"))}})}function em(e){return IDBKeyRange.bound([e],[e,[]])}function eg(e){return new Promise((t,r)=>{e.oncomplete=()=>t(),e.onabort=()=>{let t=e.error,i=new _((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 ef(e,t){let r=await eh(),i=r.transaction(["storage","files"]),a=eg(i);for(let[r,a]of[["storage",t.storageSnapshot],["files",t.fileSystemSnapshot.entries]]){let t=i.objectStore(r).openCursor(em(e));t.onsuccess=()=>{let e=t.result;e&&(Object.defineProperty(a,String(e.key[1]),{value:"files"===r?Object.freeze(e.value):e.value,enumerable:!0,configurable:!0,writable:!0}),e.continue())}}if(await a,0===Object.keys(t.fileSystemSnapshot.entries).length){t.fileSystemSnapshot=ep();let i=r.transaction("files","readwrite"),a=eg(i);for(let[r,a]of Object.entries(t.fileSystemSnapshot.entries))i.objectStore("files").put(a,[e,r]);await a}}function ev(e){let t=el.get(e);if(!t){let r={storageSnapshot:{},fileSystemSnapshot:{entries:{}}};t={snapshot:r,references:0,ready:ef(e,r)},el.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||el.get(e)!==r||el.delete(e)};r.ready.then(t,t)}}}function ey(e,t){let r=ev(e),i=async()=>(await r.ready,t()),a=(ed.get(e)??Promise.resolve()).then(i,i);ed.set(e,a);let n=()=>{ed.get(e)===a&&ed.delete(e),r.release()};return a.then(n,n),a}function eb(e){var t;let r=null==(t=el.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 ew(e){return eb(e).fileSystemSnapshot}function e_(e){return eu.add(e),()=>{eu.delete(e)}}function eS(e,t,r){let i={...r??eb(e),fileSystemNamespace:e,mutationId:t};for(let e of eu)try{e(i)}catch(e){console.error("Cannot deliver application storage update",e)}}function ex(e,t){let r={};for(let i of new Set([...Object.keys(e),...Object.keys(t)])){let a=Object.hasOwn(t,i)?t[i]:null,n=Object.hasOwn(e,i)?e[i]:void 0,s=o(n)&&o(a)&&n.type===a.type&&n.data===a.data&&n.createTime===a.createTime&&n.lastModifiedTime===a.lastModifiedTime;n===(a??void 0)||s||Object.defineProperty(r,i,{value:a,enumerable:!0})}return r}async function eI(e,t){let r=eb(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)&&eo(r.storageSnapshot),t.fileSystemChanges&&eC(r.fileSystemSnapshot,ew(e));let i=(await eh()).transaction(["storage","files"],"readwrite"),a=eg(i);try{for(let[r,a]of(t.clearStorage&&i.objectStore("storage").delete(em(e)),[["storage",t.storageChanges],["files",t.fileSystemChanges]])){let t=i.objectStore(r);for(let[i,n]of Object.entries(a??{}))null===n?t.delete([e,i]):t.put("files"===r?Object.freeze(n):n,[e,i])}}catch(e){throw i.abort(),await a.catch(()=>{}),e}await a,el.get(e).snapshot=r,eS(e,t.mutationId,t)}function ek(e){return o(e)&&"directory"===e.type}function eC(e,t){if(!o(e)||!o(e.entries))throw Error("Invalid file snapshot");let r={user:0,temp:0};for(let[i,a]of Object.entries(e.entries)){if(!o(a)||!["file","directory"].includes(String(a.type))||!Number.isFinite(a.createTime)||0>Number(a.createTime)||!Number.isFinite(a.lastModifiedTime)||0>Number(a.lastModifiedTime)||"/"!==i&&(!/^\/(user|temp)(\/[^/]+)*$/.test(i)||i.split("/").some(e=>"."===e||".."===e||/[\\\0]/.test(e)))||"/"!==i&&!ek(e.entries[i.slice(0,i.lastIndexOf("/"))||"/"])||["/","/user","/temp"].includes(i)&&"directory"!==a.type)throw Error(`Invalid file entry: ${i}`);if("file"===a.type){if("string"!=typeof a.data)throw Error(`Invalid file data: ${i}`);if((null==t?void 0:t.entries[i])!==a&&(a.data.length%4!=0||/[^A-Za-z0-9+/=]/.test(a.data)||!/^[^=]*={0,2}$/.test(a.data)))throw Error(`Invalid base64 file: ${i}`);let e=i.startsWith("/user/")?"user":"temp";r[e]+=Math.floor(3*a.data.length/4)-(a.data.endsWith("==")?2:+!!a.data.endsWith("="))}}for(let t of["/","/user","/temp"])if(!ek(e.entries[t]))throw Error(`Missing file directory: ${t}`);if(r.user>0x3200000||r.temp>0x6400000)throw new _("total file storage size exceeded",208)}function eE(e){if(!o(e)||"doubao-web-storage"!==e.format||1!==e.version||!o(e.storageSnapshot))throw Error("存储与文件备份格式无效");eo(e.storageSnapshot),eC(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 eN=r(59933),eT=r(12683);function eA(e){if(e.startsWith("/")||e.includes("\\")||e.includes("\0")||/^[a-z]:/i.test(e))throw new _("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 _("ZIP entry escapes the target directory",213);t.pop()}else t.push(r);return t.join("/")}function eM(e){return Math.floor(3*e.length/4)-(e.endsWith("==")?2:+!!e.endsWith("="))}function ej(e){if(e>0xa00000)throw new _("total size limit exceeded",208)}function eR(e,t,r){let i=t.startsWith("/user/")?"/user/":"/temp/",a=("/user/"===i?50:100)*1048576,n=r;for(let[r,a]of Object.entries(e.entries))r!==t&&r.startsWith(i)&&"file"===a.type&&(n+=eM(a.data));if(n>a)throw new _("total size limit exceeded",208)}function eP(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 eL(e,t){let r=e[t];if("string"!=typeof r)throw new _(`${t} must be a string`,104);return r}function eO(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 _("invalid applet file path",213);try{t=decodeURIComponent(e)}catch{throw new _("invalid applet file path",213)}if("."===t||".."===t||t.includes("/")||t.includes("\\")||t.includes("\0"))throw new _("invalid applet file path",213);return t}function eU(e){let t=/^appletfile:\/\/(user|temp)(?:\/(.*))?$/.exec(e);if(!t)throw new _("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 a=i.split("/").map(eD);return`/${r}/${a.join("/")}`}function e$(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 _("invalid base64 data",104);return{type:"file",data:r,createTime:0,lastModifiedTime:0}}function eq(e){let t=eU(e);if("/temp"===t||"/user"===t)return"";let r=t.lastIndexOf("/");return t.slice(0,r)}function eB(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function eF(e){let t=e.split("/").filter(Boolean),r=t.shift();if("temp"!==r&&"user"!==r)throw new _(`invalid applet file path: ${e}`,213);let i=t.map(eB).join("/");return i.length>0?`appletfile://${r}/${i}`:`appletfile://${r}`}function eW(e,t){return e.entries[eU(t)]}function ez(e,t){let r=e$(t);if(r)return r;let i=eU(t),a=e.entries[i];if(!a)throw new _(`file not found: ${i}`,203);if("file"!==a.type)throw new _(`path is a directory: ${i}`,1901001);return a}function eH(e,t){let r=eU(t),i=e.entries[r];if(!i)throw new _(`directory not found: ${r}`,203);if("directory"!==i.type)throw new _(`path is not a directory: ${r}`,1901002);return i}function eV(e,t){let r=eq(t);if(!r)throw new _(`invalid parent directory: ${t}`,213);let i=Date.now(),a="";for(let t of r.split("/").filter(Boolean)){a+=`/${t}`;let r=e.entries[a];if((null==r?void 0:r.type)==="file")throw new _(`path is not a directory: ${a}`,1901002);r||(e.entries[a]={type:"directory",createTime:i,lastModifiedTime:i})}}function eG(e){let t;try{t=atob(e)}catch{throw new _("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 eJ(e,t){let r="string"==typeof e?e:String(e??"");return"base64"===t?eG(r):new TextEncoder().encode(r)}function eK(e,t,r){let i=eU(t),a=Date.now(),n=e.entries[i];if((null==n?void 0:n.type)==="directory")throw new _(`path is a directory: ${i}`,1901001);eR(e,i,r.byteLength),eV(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==n?void 0:n.createTime)??a,lastModifiedTime:a}}function eZ(e,t,r){let i=eP(e),a=eL(t,"dirPath"),n=eU(a),s=Date.now(),o=i.entries[n];if((null==o?void 0:o.type)==="directory")return{};if(o)throw new _(`path is not a directory: ${n}`,1901002);if(!0===t.recursive){let e="";for(let t of n.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 _(`path is not a directory: ${e}`,1901002)}else{let e=eq(a);if(!e)throw new _(`invalid parent directory: ${a}`,213);let t=i.entries[e];if(!t)throw new _(`directory not found: ${e}`,203);if("directory"!==t.type)throw new _(`path is not a directory: ${e}`,1901002);i.entries[n]={type:"directory",createTime:s,lastModifiedTime:s}}return r(),{}}function eX(e,t,r){let i=eP(e),a=eL(t,"dirPath"),n=eU(a);if("/temp"===n||"/user"===n)throw new _("cannot remove root directory",213);eH(i,a);let s=`${n}/`,o=Object.keys(i.entries).filter(e=>e.startsWith(s));if(!0!==t.recursive&&o.length>0)throw new _(`directory is not empty: ${n}`,1901001);for(let e of o)delete i.entries[e];return delete i.entries[n],r(),{}}function eY(e,t,r){let i=eP(e),a=eL(t,"filePath"),n=eU(a);return ez(i,a),delete i.entries[n],r(),{}}function eQ(e,t){let r=eP(e),i=eL(t,"path"),a=e$(i),n=a?i:eU(i),s=a??r.entries[n];if(!s)throw new _(`path not found: ${n}`,203);return{size:"file"===s.type?eM(s.data):0,lastModifiedTime:s.lastModifiedTime,isDirectory:"directory"===s.type}}let e0={"doubao.readFile":function(e,t){var r;let i=ez(eP(e),eL(t,"filePath"));return ej(eM(i.data)),{data:(r=i.data,"utf-8"===eO(t,"encoding")?new TextDecoder().decode(eG(r)):r)}},"doubao.writeFile":function(e,t,r){let i=eP(e),a=eJ(t.data,eO(t,"encoding"));return ej(a.byteLength),eK(i,eL(t,"filePath"),a),r(),{}},"doubao.appendFile":function(e,t,r){let i=eP(e),a=eL(t,"filePath"),n=eU(a),s=i.entries[n];if((null==s?void 0:s.type)==="directory")throw new _(`path is a directory: ${n}`,1901001);let o=eJ(t.data,eO(t,"encoding"));ej(o.byteLength),eR(i,n,((null==s?void 0:s.type)==="file"?eM(s.data):0)+o.byteLength);let l=(null==s?void 0:s.type)==="file"?eG(s.data):new Uint8Array,d=new Uint8Array(l.length+o.length);return d.set(l),d.set(o,l.length),eK(i,a,d),r(),{}},"doubao.access":function(e,t){let r=eP(e),i=eL(t,"path");if(!eW(r,i))throw new _(`path not found: ${i}`,203);return{}},"doubao.mkdir":eZ,"doubao.rmdir":eX,"doubao.readdir":function(e,t){let r=eP(e),i=eL(t,"dirPath");return eH(r,i),{files:function(e,t){let r=eU(t),i="/"===r?"/":`${r}/`,a=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&&a.add(e)}return[...a]}(r,i)}},"doubao.unlink":eY,"doubao.stat":eQ,"doubao.copyFile":function(e,t,r){let i=eP(e),a=ez(i,eL(t,"srcPath")),n=eL(t,"destPath");return eR(i,eU(n),eM(a.data)),eK(i,n,eG(a.data)),r(),{}},"doubao.getFileInfo":function(e,t){let r=eL(t,"filePath"),{size:i}=eQ(e,{path:r});if(void 0===t.digestAlgorithm)return{size:i};let a=eL(t,"digestAlgorithm").toLowerCase(),n=ez(eP(e),r),s="md5"===a?eN.Fx:"sha1"===a?eN.e8:void 0;if(!s)throw new _(`unsupported digest algorithm: ${a}`,102);return{size:i,digest:(0,et.My)(s(eG(n.data)))}},"doubao.rename":function(e,t,r){let i=eP(e),a=eL(t,"oldPath"),n=eL(t,"newPath"),s=eU(a),o=eU(n),l=i.entries[s];if(!l)throw new _(`path not found: ${s}`,203);if("/temp"===s||"/user"===s)throw new _("cannot rename root directory",213);if(s===o)return{};if("directory"===l.type&&o.startsWith(`${s}/`))throw new _("cannot move a directory into itself",213);if(i.entries[o])throw new _(`target already exists: ${o}`,102);for(let e of(eV(i,n),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=eP(e),a=eL(t,"filePath"),n=ez(i,a),s=t.length??0;if("number"!=typeof s||!Number.isSafeInteger(s)||s<0)throw new _("length must be a non-negative integer",104);eR(i,eU(a),s);let o=eG(n.data),l=new Uint8Array(s);return l.set(o.slice(0,s)),eK(i,a,l),r(),{}},"doubao.saveFile":function(e,t,r){let i,a,n=eP(e),s=eL(t,"tempFilePath"),o=e$(s),l=o??ez(n,s),d=eO(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"===(a=eU(s))||"/user"===a?"":a.slice(a.lastIndexOf("/")+1),c=`/user/${Date.now()}`,p=d&&d.length>0?d:eF(`${c}_${u}`);for(let e=1;!d&&n.entries[eU(p)];e++)p=eF(`${c}_${e}_${u}`);return eR(n,eU(p),eM(l.data)),eK(n,p,eG(l.data)),o||eU(s)===eU(p)||delete n.entries[eU(s)],r(),{savedFilePath:p}},"doubao.getSavedFileList":function(e){return{fileList:Object.entries(eP(e).entries).flatMap(e=>{let[t,r]=e;return t.startsWith("/user/")&&"file"===r.type?[{filePath:eF(t),size:eM(r.data),createTime:r.createTime}]:[]})}},"doubao.removeSavedFile":function(e,t,r){var i;let a=eL(t,"filePath");return(null==(i=eW(eP(e),a))?void 0:i.type)==="directory"?eX(e,{dirPath:a},r):eY(e,t,r)},"doubao.unzip":function(e,t,r){let i=eP(e),a=ez(i,eL(t,"zipFilePath")),n=eL(t,"targetPath"),s=eU(n),o=function(e,t){try{let r=function(e,t){let r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=e.length-22,a=Math.max(0,e.length-65557);for(;i>=a&&(0x6054b50!==r.getUint32(i,!0)||i+22+r.getUint16(i+20,!0)!==e.length);)i--;if(i<a||0!==r.getUint16(i+4,!0)||0!==r.getUint16(i+6,!0))throw Error("Invalid or multipart ZIP archive");let n=r.getUint16(i+10,!0),s=r.getUint32(i+16,!0);if(65535===n||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");n=Number(r.getBigUint64(e+32,!0)),s=Number(r.getBigUint64(e+48,!0))}if(!Number.isSafeInteger(n)||n>e.length/46||!Number.isSafeInteger(s))throw Error("Invalid ZIP directory size");let o=new Map,l=0;for(let a=0;a<n;a++){if(s+46>i||0x2014b50!==r.getUint32(s,!0))throw Error("Invalid ZIP directory entry");let a=r.getUint16(s+8,!0),n=r.getUint16(s+28,!0),d=r.getUint16(s+30,!0),u=s+46+n+d+r.getUint16(s+32,!0);if(u>i||1&a)throw Error("Invalid or encrypted ZIP entry");let c=(0,eT.he)(e.subarray(s+46,s+46+n),!(2048&a));eA(c);let p=r.getUint32(s+24,!0);if(0xffffffff===p){let e=s+46+n,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 _("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,a=0,n=new eT.HJ(e=>{eA(e.name);let r=new eT.uZ(e.name);r.ondata=()=>{};let n=[],s=0;e.ondata=(o,l,d)=>{if(o)throw o;if((a+=l.length)>t)throw new _("ZIP expanded size exceeds the file system quota",208);if(n.push(l),s+=l.length,r.push(l,d),d){let t=new Uint8Array(s),a=0;for(let e of n)t.set(e,a),a+=e.length;i.set(e.name,{data:t,crc:r.crc>>>0})}},e.start()});n.register(eT.mM);for(let t=0;t<e.length;t+=65536)n.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 _)throw e;throw new _(`Unable to unzip file: ${e instanceof Error?e.message:String(e)}`,102)}}(eG(a.data),(s.startsWith("/user")?50:100)*1048576),l={...e,fileSystemSnapshot:{entries:{...i.entries}}};for(let[e,t]of(eZ(l,{dirPath:n,recursive:!0},()=>{}),o)){let r=eA(e);if(!r)continue;let i=eF(`${s}/${r}`);e.endsWith("/")?eZ(l,{dirPath:i,recursive:!0},()=>{}):eK(l.fileSystemSnapshot,i,t)}return i.entries=l.fileSystemSnapshot.entries,r(),{}}},e1="doubao.__webSyncBridgePersist",e2="doubao.__webSyncBridgeUpdated";r(20789),r(62839),r(66876),r(35336);let e3="doubao.getPerformanceEntries",e4="doubao.setPerformanceBufferSize",e6="doubao.onPerformanceEntries",e5="doubao.__webPerformanceTiming",e8="__WEB_PERFORMANCE_WIDGET_IDENTITY__",e9=[e3,e4,e6];class e7{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},a=i("create_lynx_start"),n=i("layout_start"),s=i("layout_end");if(void 0===a||void 0===n||void 0===s||s<n||n<a)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,a);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:a,duration:s-a,...d,...void 0!==p&&p>=a&&p<=s?{viewLayerReadyTime:p}:{},viewLayerRenderStartTime:n,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 te(e,t){try{await (null==t?void 0:t(e.params))}catch{}}let tt=new Map,tr={"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 S(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 S(e,{})}};function ti(){var e;return null==(e=globalThis.navigator)?void 0:e.clipboard}function ta(e,t){let r=ti();if(!r||"function"!=typeof r[t])throw new _(`${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 _(`${e} failed: ${r}`,o(t)&&("NotAllowedError"===t.name||"SecurityError"===t.name)?106:102);return i.cause=t,i}async function ts(e){let t=ta("setClipboardData","writeText");try{await t.writeText(e)}catch(e){throw tn("setClipboardData",e)}}async function to(){let e=ta("getClipboardData","readText");try{let t=await e.readText();if("string"==typeof t)return t}catch(e){throw tn("getClipboardData",e)}throw new _("getClipboardData failed: clipboard did not return text",102)}function tl(e,t,r){let i=(null==t?void 0:t.fileSystemNamespace)??ec(null==t?void 0:t.globalProps);return ey(i,async()=>{try{var a,n;let s=ew(i),l={fileSystemNamespace:i,fileSystemSnapshot:{entries:{...s.entries}},apiResults:{"doubao.getSystemInfo":{platform:null==t||null==(n=t.globalProps)||null==(a=n.os)?void 0:a.toLowerCase()}},storageSnapshot:{},supportedAPIs:[]},d=!1,u=(0,e0[e.name])(l,o(e.params)?e.params:{},()=>{d=!0});return d?await eI(i,{fileSystemChanges:ex(s.entries,l.fileSystemSnapshot.entries),mutationId:r}):r&&eS(i,r,{}),S(e,u)}catch(e){throw r&&eS(i,r),e}})}let td=Object.fromEntries(Object.keys(e0).map(e=>[e,tl]));async function tu(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:a}=e,n=await new Promise((e,r)=>{let i=new Image,n=()=>{null==t||t.removeEventListener("abort",s),i.onload=i.onerror=null},s=()=>{n(),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=()=>{n(),e(i)},i.onerror=()=>{n(),r(Error(`failed to load image: ${a}`))},i.src=a)}),s=null==(r=a.match(/^data:image\/([^;,]+)/i))?void 0:r[1],o=null==(i=a.match(/\.([a-zA-Z0-9]+)(?:[?#].*)?$/))?void 0:i[1];return{width:n.naturalWidth||n.width,height:n.naturalHeight||n.height,orientation:"up",path:a,type:((null==s?void 0:s.split("+")[0])??o??"").toLowerCase()}}function tc(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 tp(e){return async(t,r)=>{let i=t.params;if(!i||"string"!=typeof i.url||!i.url.trim())return x(t,"invalid url",104);try{return await e(i,null==r?void 0:r.navigation)?S(t,{}):x(t,"No active Runtime to navigate",102)}catch(e){return x(t,I(e),e instanceof _?e.errNo:102)}}}let th={"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 x(e,"url and mode must describe a valid page route",104);if(!(null==t||null==(r=t.navigation)?void 0:r.openPage))return x(e,"No active Runtime to open page",102);try{return await t.navigation.openPage(i),S(e,{})}catch(t){return x(e,I(t),t instanceof _?t.errNo:102)}},"doubao.enableAlertBeforeUnload":(e,t)=>{var r;let i=null==(r=e.params)?void 0:r.message;return"string"!=typeof i?x(e,"message must be a string",104):tm(e,i,t)},"doubao.disableAlertBeforeUnload":(e,t)=>tm(e,void 0,t),"doubao.getCurrentPages":{handler:(e,t)=>S(e,tc(t)),syncResult:tc},"doubao.navigateTo":tp(A),"doubao.redirectTo":tp(M),"doubao.reLaunch":tp(j),"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)?x(e,"No pages in back stack",102):S(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)?x(e,"No active Runtime to exit app",102):S(e,{})};function tm(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)?S(e,{}):x(e,"not found page",102):x(e,"alert before unload is only supported in page container",103)}let tg=Object.fromEntries(["setStorage","getStorage","removeStorage","clearStorage","getStorageInfo"].map(e=>[`doubao.${e}`,async(t,r)=>{let i=(null==r?void 0:r.fileSystemNamespace)??ec(null==r?void 0:r.globalProps);return ey(i,async()=>{var r,a;let n=o(t.params)?t.params:{},s=eb(i).storageSnapshot,l={};switch(e){case"setStorage":{let e,t;if("string"!=typeof n.data)throw Error("data must be a serialized string");let o=(r=n.key,a=n.data,e=er(r),ei(a),t=Object.prototype.hasOwnProperty.call(s,e)?s[e]:void 0,es(en(s)-(void 0===t?0:ea(t))+ea(a)),e);await eI(i,{storageChanges:{[o]:n.data}});break}case"getStorage":let d;l={data:Object.hasOwn(s,d=er(n.key))?s[d]:void 0};break;case"removeStorage":await eI(i,{storageChanges:{[er(n.key)]:null}});break;case"clearStorage":await eI(i,{clearStorage:!0});break;case"getStorageInfo":l={keys:Object.keys(s),currentSize:Math.ceil(en(s)/1024),limitSize:10240}}return S(t,l)})}])),tf={...{"doubao.getClipboardData":{canIUse:()=>{var e;return"function"==typeof(null==(e=ti())?void 0:e.readText)},handler:async e=>S(e,{data:await to()})},"doubao.setClipboardData":{canIUse:()=>{var e;return"function"==typeof(null==(e=ti())?void 0:e.writeText)},handler:async e=>{let{data:t}=function(e){if(!o(e)||"string"!=typeof e.data)throw new _("data must be a string",104);return{data:e.data}}(e.params);return await ts(t),S(e,{})}}},...tr,...td,...{"doubao.getImageInfo":async e=>S(e,await tu(e.params))},...th,...tg,...{[e1]: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 a="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(e0,i.name)||!o(i.params))throw Error("Invalid synchronous file operation");return tl({...e,name:i.name,params:i.params},t,a)}let n={storageChanges:o(r.storageChanges)?r.storageChanges:void 0,clearStorage:!0===r.clearStorage,fileSystemChanges:o(r.fileSystemChanges)?r.fileSystemChanges:void 0,mutationId:a};return await ey(i,async()=>{try{await eI(i,n)}catch(e){throw eS(i,n.mutationId),e}}),S(e,{})}},...{"doubao.canIUse":{handler:(e,t)=>{let{schema:r}=e.params;return S(e,{result:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:N;return t.canIUse(e,{apiRegistry:t})}(r,null==t?void 0:t.apiRegistry)})}},"doubao.getAccountInfo":{handler:(e,t)=>{var r;return S(e,Y(null==t||null==(r=t.navigation)?void 0:r.getPackageInfo(),null==t?void 0:t.globalProps))},syncResult:e=>Y(Q(e),null==e?void 0:e.globalProps)},"doubao.getPackageInfo":{handler:(e,t)=>{var r;return S(e,F(null==t||null==(r=t.navigation)?void 0:r.getPackageInfo()))},syncResult:e=>F(Q(e))},"doubao.getAppBaseInfo":{handler:(e,t)=>S(e,X(null==t?void 0:t.globalProps)),syncResult:e=>X(null==e?void 0:e.globalProps)},"doubao.getMenuButtonBoundingClientRect":{handler:(e,t)=>S(e,P(null==t?void 0:t.globalProps)),syncResult:e=>P(null==e?void 0:e.globalProps)},"doubao.getSystemInfo":{handler:(e,t)=>S(e,K(null==t?void 0:t.globalProps)),syncResult:e=>K(null==e?void 0:e.globalProps)},"doubao.getWindowInfo":{handler:(e,t)=>S(e,W(null==t?void 0:t.globalProps)),syncResult:e=>W(null==e?void 0:e.globalProps)},"doubao.getDeviceInfo":{handler:(e,t)=>S(e,G(null==t?void 0:t.globalProps)),syncResult:e=>G(null==e?void 0:e.globalProps)},"doubao.getNetworkType":{handler:e=>S(e,Z()),syncResult:Z}}};N.registerMany(tf,{override:!0}),N.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 tv{router;navigation;onEmpty;runtime;callers=new Map;destroyed=!1;performance=new e7;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,a;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=tt.get(i)??{receivers:new Set,recent:[]},tt.set(i,e),e.receivers.add(r),a=()=>{let t=Date.now();e.recent=e.recent.filter(e=>1e4>=Math.abs(t-e.timestamp))},{publish(t){for(let r of(a(),e.recent.push({message:t,timestamp:t.timestamp??Date.now()}),[...e.receivers]))r(t)},replay(t,r,i){for(let n of(a(),e.recent))n.message.name===t&&n.timestamp>=r&&i(n.message)},release(){e.receivers.delete(r),0===e.receivers.size&&tt.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)??N}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 a=(null==t?void 0:t.apiRegistry)??this.apiRegistry;this.unsubscribeStorage??=e_(e=>{for(let t of this.callers.values())t.fileSystemNamespace===e.fileSystemNamespace&&t.events.emitPrivate(e2,e)});let n=a.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:n,main:r}),i}resolveStorageNamespace(e,t,r){var i,a,n;return(null==(i=this.runtime)?void 0:i.getFileSystemNamespace())??(null==(a=e.options)?void 0:a.fileSystemNamespace)??r??ec(t,null==(n=e.options)?void 0:n.userId)}async prepareStorage(e,t,r){let i=this.getCaller(e),a=this.resolveStorageNamespace(i,t,r);if(i.fileSystemNamespace!==a){var n;null==(n=i.storage)||n.release(),i.storage=void 0,i.fileSystemNamespace=a}i.storage??=ev(a),await i.storage.ready}createSyncBridgeData(e,t,r){var i;let a=this.getCaller(e),n=function(e,t){var r;let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:ec(e),a=arguments.length>3?arguments[3]:void 0,n=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:N;return e.getSupportedNames({apiRegistry:e})}(t);return{hostFileSystem:Object.keys(e0).every(r=>null==t?void 0:t.canIUse(r,{globalProps:e})),fileSystemNamespace:i,...eb(i),hostStorage:!!(null==t?void 0:t.canIUse("doubao.setStorage",{globalProps:e})),apiResults:(r=null==e?void 0:e.packageInfo,(t??N).getSyncResults({globalProps:e,navigation:a,packageInfo:r})),supportedAPIs:n}}(t,(null==(i=a.options)?void 0:i.apiRegistry)??this.apiRegistry,this.resolveStorageNamespace(a,t,r),this.navigation);return n.performance=this.performance.snapshot(),a.fileSystemNamespace=n.fileSystemNamespace,n.supportedAPIs.push(...e9,e2),n}getCurrentPagesSnapshot(){return this.navigation?{"doubao.getCurrentPages":{pages:this.navigation.getCurrentPages()}}:void 0}publishPageStack(){let e=this.getCurrentPagesSnapshot();if(e)for(let t of this.callers.values())t.events.emit(e2,{apiResults:e})}beginPerformance(e,t){var r,i,a;let n=this.getCaller(e),s=t.globalProps??{},l=o(s.__VIEW_CONTEXT__)?s.__VIEW_CONTEXT__:{},d=o(s[e8])?s[e8]:l,u="PAGE"===t.containerType,c=null==(i=this.navigation)||null==(r=i.getCurrentPages().at(-2))?void 0:r.route.split("?")[0],p=null==(a=[...this.callers.values()].findLast(e=>{var t;return(null==(t=e.performanceTrace)?void 0:t.path)===c}))?void 0:a.performanceTrace;n.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(e2,{performance:this.performance.snapshot()}),e.length&&t.events.emit(e6,{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 a=this.getCaller(e);if(!y(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:"",n="applet.subscribeEvent"===t.name&&!a.events.isSubscribed(i);if(tr[t.name](t,{...r,events:a.events}),"applet.subscribeEvent"===t.name&&i===e2&&(null==r?void 0:r.environment)!=="sandbox"){let e=this.resolveStorageNamespace(a,null==r?void 0:r.globalProps,a.fileSystemNamespace??(null==r?void 0:r.fileSystemNamespace));a.events.emitPrivate(i,{apiResults:this.getCurrentPagesSnapshot(),performance:this.performance.snapshot(),fileSystemNamespace:e,...eb(e)})}return n&&i&&"number"==typeof e.timestamp&&this.getApplicationEvents().replay(i,e.timestamp,a.send),{routed:!1}}return(null==(i=t.target)?void 0:i.scope)!=="main"||"self"!==t.target.target||!this.router||a.main?{routed:!1}:this.router.call(e,t)}async dispatch(e,t,r,i,a){var n,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:a.containerType,element:a.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 te(e,t)}(r,null==c?void 0:c.onWidgetInteraction);if(e)return await e}let m=await this.handleMessage(e,r,a);if(m.routed)return await m.result;let g=await (null==c||null==(n=c.appletSessionMessageHandler)?void 0:n.call(c,r,p));if(null==g?void 0:g.routed)return await g.result;"iframe"!==d&&h&&w(r)&&"__bridge_ready__"===r.name&&(null==c||null==(s=c.onReady)||s.call(c));let f=h&&b(r),v="inline"===d&&"sandbox"!==a.environment;if(f&&v&&"TOOL"!==a.containerType)return u.send(r),r;let _=r=>("iframe"!==d&&"postMessage"===t&&b(r)&&this.callers.get(e)===u&&u.send(r),r);try{if(h&&y(r)&&"sandbox"!==a.environment){let e=o(r.params)?r.params:{};if(r.name===e5){let t=u.performanceTrace?this.performance.recordTiming(u.performanceTrace,e.timing):[];return t.length&&this.publishPerformance(t),_(S(r,{}))}if(r.name===e3)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===e4)return this.performance.setBufferSize(e.size),this.publishPerformance(),_(S(r,{}));if("doubao.canIUse"===r.name&&e9.includes(String(e.schema)))return _(S(r,{result:!0}))}let n=this.runtime?this.runtime.nativeModulesCallHandler:null==c?void 0:c.nativeModulesCallHandler,s=await (null==n?void 0:n(t,r,i,p));if(void 0===s&&h&&w(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"===a.environment||void 0===s&&v)return _(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??N;return(i,a,n)=>{if(("AppletJSModule"!==n||"log"!==i)&&"AppletBridgeModule"===n&&"postMessage"===i)return r.dispatch(a,e,t)}}({...a,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,a.globalProps,u.fileSystemNamespace??a.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&&y(r)&&r.name===e1&&b(m)&&o(m.params)&&1!==m.params.code){let e=["Synchronous API persistence failed",m.params];n?await n("log",{level:"error",args:e},"AppletJSModule",p):console.error(...e)}return _(m)}catch(e){if("iframe"===d)throw e;return _(y(r)?k(r,e):void 0)}}handleMainBridgeMessage(e){var t;return!this.destroyed&&(null!=(t=this.router)&&!!t.handleMainBridgeMessage(e)||!!w(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,a;let n=this.callers.get(e);n&&(this.callers.delete(e),null==(t=n.storage)||t.release(),this.callers.size||(null==(i=this.unsubscribeStorage)||i.call(this),this.unsubscribeStorage=void 0),n.abortController.abort(),n.events.destroy(),null==(r=this.router)||r.cancel(e),n.main||this.destroyed||[...this.callers.values()].some(e=>!e.main)||null==(a=this.onEmpty)||a.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)}}function ty(e){if(!e.resourceUrl)throw Error("Container.render requires a resourceUrl");return e.resourceUrl}function tb(e){return e.containerType??"PAGE"}function tw(e){return"WIDGET"===e?"content":"fill"}let t_=/(?:^|[.-])[a-f\d]{8,}(?=[.-]|$)/i;function tS(e){let t=new URL(e),r=t.pathname.slice(t.pathname.lastIndexOf("/")+1),i=R();return i&&!t_.test(r)&&t.searchParams.set("__doubao_resource_reload",i),t.href}function tx(e){return"localhost"===e||"::1"===e||/^127(?:\.\d{1,3}){3}$/.test(e)}function tI(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 tk{options;shared;sandboxUrl;targetOrigin;views=new Map;nextId=0;view=null;port=null;handshakeTimer=null;loaded=!1;failed=!1;connected=!1;constructor(e,t=!1){this.options=e,this.shared=t;let r=new URL(e.sandboxUrl??"https://apps-web-sdk-sandbox.doubaocdn.com/sandbox");if("https:"!==r.protocol&&!("http:"===r.protocol&&tx(r.hostname)))throw Error("iframe isolation url must use HTTPS (HTTP is only allowed on localhost)");this.sandboxUrl=tS(r),this.targetOrigin=r.origin}attach(e){if(this.failed)throw Error("iframe sandbox failed; restart the Runtime before opening another view");let t=this.createView(e.containerType),r=`container-${++this.nextId}`;return this.views.set(r,{...e,visible:"PAGE"===e.containerType}),this.updateVisibility(),{id:r,iframe:t,post:e=>this.post(r,e),setVisible:e=>{let t=this.views.get(r);t&&(t.visible=e,this.updateVisibility())},detach:()=>{this.views.has(r)&&(this.post(r,{type:"dispose"}),this.views.delete(r),this.updateVisibility())}}}clear(){var e;this.destroyChannel(),this.views.clear(),null==(e=this.view)||e.remove(),this.view=null,this.loaded=!1,this.failed=!1}createView(e){var t,r;if(new URL((null==(t=globalThis.location)?void 0:t.href)??"http://localhost/").origin===this.targetOrigin)throw Error("iframe isolation requires a cross-origin sandbox URL");if(this.view)return this.view;let i=document.createElement("iframe");i.className=this.options.className??"doubao-web-container-view",i.dataset.containerType=this.shared?"RUNTIME":e,i.dataset.webSizing=tw(e),i.referrerPolicy="no-referrer",i.title="Doubao app content",i.sandbox.add("allow-scripts","allow-same-origin");let a=tx((null==(r=globalThis.location)?void 0:r.hostname)??"");a&&i.setAttribute("credentialless",""),i.setAttribute("allow",a?"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;let n=this.options.container??document.body;return this.shared?n.append(i):n.replaceChildren(i),i}updateVisibility(){this.shared&&this.view&&(this.view.style.display=[...this.views.values()].some(e=>"PAGE"===e.containerType&&e.visible)?"block":"none")}handleLoad(){if(this.failed||!this.view)return;if(this.loaded)return void this.fail(Error("iframe navigated after the sandbox runtime loaded"));this.loaded=!0;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.addEventListener("close",()=>{this.port===e.port1&&this.fail(Error("iframe message port closed"))}),e.port1.start(),this.handshakeTimer=setTimeout(()=>this.fail(Error("iframe sandbox handshake timed out")),1e4);let t={type:"doubao-web-sdk:connect",protocolVersion:this.shared?2:1,sdkVersion:R()??""};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;if(!e.data||"object"!=typeof e.data)return void this.fail(Error("iframe sandbox sent an invalid protocol message"),e);let i=e.data;if(!this.connected){let t=this.shared?2:1;if("connected"!==i.type||i.protocolVersion!==t)return void this.fail(Error("iframe sandbox protocol version mismatch"),e);for(let e of(this.connected=!0,this.clearHandshakeTimer(),this.views.values()))e.onConnected();return}if(this.shared){if("container"!==i.type||"string"!=typeof i.containerId||!i.message||"object"!=typeof i.message)return void this.fail(Error("iframe sandbox sent an invalid container message"),e);null==(t=this.views.get(i.containerId))||t.onMessage(i.message,e)}else"container"!==i.type?null==(r=this.views.values().next().value)||r.onMessage(i,e):this.fail(Error("iframe sandbox sent an invalid protocol message"),e)}post(e,t){this.connected&&this.port&&this.views.has(e)&&this.port.postMessage(this.shared?{type:"container",containerId:e,message:t}:t)}fail(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tI(e);if(this.failed)return;this.failed=!0,this.destroyChannel(),null==(t=this.view)||t.remove(),this.view=null;let i=[...this.views.values()];for(let t of(this.views.clear(),i))t.onError(e,r)}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}}class tC{page;container;options;sandbox;connection=null;bridge=null;caller;failed=!1;visible=!0;preparedForRender=!1;preparedContainerType=null;renderMessage=null;view=null;constructor(e,t,r=!1){this.page=r,this.container=e.container,this.options=e,this.sandbox=t??new tk(e)}get element(){return this.view}prepare(e){this.clear();try{this.createView(e),this.preparedForRender=!0}catch(e){throw this.clear(),e}}createView(e){if(this.view)return this.preparedContainerType!==e?this.abortRender(Error("iframe container type cannot change after preparation")):this.view;try{this.connection=this.sandbox.attach({containerType:e,onConnected:()=>{this.renderMessage&&this.postOrFail(this.renderMessage)},onMessage:(e,t)=>this.handleMessage(e,t),onError:(e,t)=>this.fail(e,t)})}catch(e){return this.abortRender(e instanceof Error?e:Error(String(e)))}return this.view=this.sandbox.shared?document.createElement("div"):this.connection.iframe,this.sandbox.shared&&(this.view.dataset.containerId=this.connection.id,this.view.dataset.containerType=e,this.view.style.display="none",this.container.replaceChildren(this.view)),this.preparedContainerType=e,this.view}render(e){var t;this.preparedForRender||this.clear(),this.preparedForRender=!1;let r=tb(e),i=new URL(ty(e),document.baseURI).href,a=e.initData??{},n={...J(),...e.globalProps??{}};this.bridge=e.bridge??(null==(t=this.options.runtime)?void 0:t.bridge)??new tv,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,n,this.options.fileSystemNamespace).then(()=>{var t,l,d;if(this.caller!==o)return;s.beginPerformance(o,{...e,containerType:r,globalProps:n});let u=s.createSyncBridgeData(o,n,this.options.fileSystemNamespace);this.renderMessage={type:"render",captureWidgetTap:this.options.captureWidgetTap,resourceUrl:i,...this.sandbox.shared?{groupId:e.groupId,page:this.page,pageCapsule:e.pageCapsule}:{},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:a,globalProps:n,visible:this.visible,syncBridgeData:u},this.postOrFail(this.renderMessage)}).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,r;null==(e=this.connection)||e.detach(),this.connection=null,this.sandbox.shared||this.sandbox.clear(),this.caller&&(null==(t=this.bridge)||t.unregister(this.caller)),this.caller=void 0,this.bridge=null,this.sandbox.shared&&(null==(r=this.view)||r.remove()),this.view=null,this.preparedContainerType=null,this.renderMessage=null,this.failed=!1,this.preparedForRender=!1,this.container.replaceChildren()}setVisible(e){var t,r;this.visible=e,this.caller&&(null==(t=this.bridge)||t.setVisible(this.caller,e)),this.sandbox.shared&&(null==(r=this.connection)||r.setVisible(e)),this.renderMessage&&(this.renderMessage.visible=e,this.postOrFail({type:"set-visible",visible: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,tI(e)),e}handleMessage(e,t){var r,i,a,n;switch(e.type){case"ready":null==(r=(i=this.options).onReady)||r.call(i);break;case"error":this.fail(Error(e.message),t);break;case"resize":(null==(a=this.renderMessage)?void 0:a.containerType)!=="WIDGET"||!Number.isFinite(e.height)||e.height<0?this.fail(Error("only Widget containers may resize the iframe"),t):this.connection&&(this.connection.iframe.style.height=`${e.height}px`,this.connection.iframe.height=String(e.height));break;case"page-capsule":this.page&&("close"===e.action||"more"===e.action)?null==(n=this.view)||n.dispatchEvent(new CustomEvent(`doubao:page-capsule-${e.action}`,{bubbles:!0})):this.fail(Error("iframe sandbox sent an invalid page action"),t);break;case"native-call":!Number.isSafeInteger(e.requestId)||e.requestId<=0||("AppletBridgeModule"!==e.moduleName||"postMessage"!==e.name)&&("AppletJSModule"!==e.moduleName&&"LynxConsoleModule"!==e.moduleName&&"Console"!==e.moduleName||"log"!==e.name)?this.fail(Error("iframe sandbox sent an invalid bridge call"),t):this.handleNativeCall(e);break;case"connected":this.fail(Error("iframe sandbox connected more than once"),t);break;default:this.fail(Error("iframe sandbox sent an invalid protocol message"),t)}}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:I(t)});return}this.bridge===r&&this.caller===i&&this.postOrFail({type:"bridge-result",requestId:e.requestId,result:t})}}post(e){var t;null==(t=this.connection)||t.post(e)}postOrFail(e){try{this.post(e)}catch(e){this.fail(e instanceof Error?e:Error(String(e)))}}fail(e){var t,r,i,a,n;let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tI(e);this.failed||(this.failed=!0,null==(t=this.connection)||t.detach(),this.connection=null,this.sandbox.shared||this.sandbox.clear(),this.caller&&(null==(a=this.bridge)||a.unregister(this.caller)),this.caller=void 0,this.bridge=null,this.sandbox.shared&&(null==(n=this.view)||n.remove()),this.view=null,this.renderMessage=null,null==(r=(i=this.options).onError)||r.call(i,e,s))}}let tE={mode:"iframe",createContainer:e=>new tC(e),createRuntime(e){if(!e.container)return tE;let t=new tk(e,!0);return{mode:"iframe",createContainer:e=>new tC(e,t),createPage(e){let r=new tC(e,t,!0);return{render:e=>r.render({...e,containerType:"PAGE"}),clear:()=>r.clear(),setVisible:e=>r.setVisible(e),sendEvent:(e,t)=>r.sendEvent(e,t),updateGlobalProps:e=>r.updateGlobalProps(e),reload:()=>r.reload()}},clear:()=>t.clear()}}};function tN(){var e;return(null==(e=globalThis.location)?void 0:e.href)??"http://localhost/"}function tT(e){return new URL(e,tN()).toString()}function tA(e,t){if(!t)return e;let r=new URL(e,tN());return r.searchParams.set("__doubao_resource_reload",t),r.toString()}class tM{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&&f(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?v(()=>i,r.signal):i}async fetchPackage(e,t){return{manifestUrl:e,resourceRoot:t,manifest:await h(e,{fetcher:this.options.fetcher})}}async loadPackage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t.signal&&f(t.signal);let{manifestUrl:r,resourceRoot:i}=await this.getPackageSource(e,t),a=tT(r),n=await this.cached(a,()=>this.fetchPackage(a,i),t);if(e&&n.manifest.appId&&n.manifest.appId!==e)throw Error("Resolved package appId must match the requested application");return n}resolveWidget(e,t){let r=this.tryResolveWidgetFromPackage(e,t),i=e.manifest.appRuntimeEntry?m(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?tA(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(tT(e.manifestUrl),Promise.resolve(e))}deletePackage(e){this.packages.delete(tT(e))}clearPackageCache(e){e?this.deletePackage(e):this.packages.clear()}resolveWidgetEntry(e,t){let r=e.manifest.name??t.name,i=m(e.manifestUrl,t);return{appId:e.manifest.appId,entry:t,iconSrc:e.manifest.iconSrc??c(t.icons),appName:r,resourceUrl:i?tA(i,e.resourceUrlVersion??this.resourceUrlVersion):void 0}}tryResolveWidgetFromPackage(e,t){let r=e.manifest.getOptionalWidgetEntry(t);if(r)return this.resolveWidgetEntry(e,r)}}class tj{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((a,n)=>{this.pendingCalls.set(r,{callbackId:t.callbackId,reject:n,resolve:a,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(b(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 tR="onBackground",tP="onDestroy",tL="onForeground",tO="onHide",tD="onShow";function tU(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 t$(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 tq(e,t){return{packageInfo:t,...e}}function tB(e){return{appId:e.appId,name:e.name,iconSrc:e.iconSrc,versionName:e.versionName}}function tF(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return tq(t,tB(e))}function tW(e){if(o(e))return{...e};if("string"!=typeof e)return{};try{let t=JSON.parse(e);return o(t)?t:{}}catch{return{}}}class tz{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=tE,r){var i,a;this.sandboxUrl=e.sandboxUrl,this.packageManager=e.packageManager??new tM({resolveManifestUrl:()=>this.manifestUrl});let n=new tj(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=(null==(a=t.createRuntime)?void 0:a.call(t,{container:null==(i=this.pageHost)?void 0:i.container,sandboxUrl:e.sandboxUrl,className:e.className}))??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 tv(n,{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=>{f(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 v(()=>e,r)}return f(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,a;let n;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=m(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,f(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=tA(l,this.packageInfo.resourceUrlVersion),p=e.pageCapsule??this.pageCapsule,h=`page-${++this.nextPageIndex}`,g=(n=tW(null==(a=u.globalProps)?void 0:a.__VIEW_CONTEXT__),{...o(u.initData)?tW(u.initData.viewContext):{},...n,viewId:h,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(t$(s.path,e));try{let t;try{let e,r;t=y.render({resourceUrl:c,groupId:this.manifest.appId,initData:o(u.initData)?{...u.initData,viewContext:g}:{viewContext:g},globalProps:(e=null==p?void 0:p.statusBarHeight,r="number"==typeof e&&Number.isFinite(e)?{statusBarHeight:e}:{},{...u.globalProps,...r,__VIEW_CONTEXT__:g}),pageCapsule:p})}finally{this.pendingPages.pop()}let r=this.getCurrentStackItem();return v={id:h,pageId:s.id,route:s.path,resourceUrl:c,entry:s,element:t,isReady:!1,options:{...e,entry:s,pageCapsule:p},pendingLifecycleEvents:[],page:y},this.stack.push(v),this.bridge.publishPageStack(),r&&(null==(i=r.backPrompt)||i.abort(),this.visible&&this.sendPageLifecycleEvent(r,tO),r.page.setVisible(!1)),this.updateEmptyState(),v.page.setVisible(this.visible),this.visible&&this.sendPageLifecycleEvent(v,tD),this.sendAppEvent("onPageOpened",{viewId:v.id}),this.toStackEntry(v)}catch(e){throw y.clear(),this.updateEmptyState(),e}}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?tD:tO)),this.appRuntime&&this.sendAppEvent(e?tL:tR)}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(){var e,t;this.lifecycle.abort(),this.lifecycle=new AbortController,this.packageLoading=void 0,this.clearPages(),this.clearAppRuntime(),null==(e=(t=this.runtimeKernel).clear)||e.call(t),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(){let e=this.stack.splice(0);if(0!==e.length){for(let t of(this.bridge.publishPageStack(),e.reverse()))this.destroyStackItem(t);this.updateEmptyState()}}async withPageTransition(e){let t=this.bridge.register();try{return await e()}finally{this.bridge.unregister(t)}}destroyStackItem(e){var t;null==(t=e.backPrompt)||t.abort();let r=this.toStackEntry(e);return this.sendPageLifecycleEvent(e,tP),e.page.clear(),r}removeStackItem(e,t){this.bridge.publishPageStack();let r=this.destroyStackItem(e),i=this.getCurrentStackItem();return t&&i&&this.visible&&(i.page.setVisible(!0),this.sendPageLifecycleEvent(i,tD)),this.updateEmptyState(),r}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,a,n,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=m(this.manifestUrl,this.manifest.appRuntimeEntry);if(!o)throw Error("No Web entry configured for app runtime");let l=tA(o,this.packageInfo.resourceUrlVersion),d=new Promise((e,t)=>{i=e,a=t});d.catch(()=>{});let u={promise:d,resolve:i,reject:a,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{n=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 a=t.createContainer({...e,container:i});return{render:e=>(r.append(i),a.render(e)),clear(){a.clear(),i.remove()},sendEvent:a.sendEvent.bind(a),sendBridgeMessage:a.sendBridgeMessage.bind(a)}}({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!==n||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:n,isReady:!1,pendingEvents:[{name:this.visible?tL:tR,params:{}},...this.pendingAppEvents.splice(0)]};let e=void 0!==s.groupId?s.groupId:this.appGroupId;n.render({bridge:this.bridge,resourceUrl:l,groupId:null===e?void 0:e??this.manifest.appId,containerType:"APP",initData:this.appInitData??{},globalProps:{...tF(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==n||n.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(tR),r.container.sendEvent(tP)),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 tU(e,this.manifest)}catch(e){throw Object.assign(new _(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=>t$(e.route,e.options)),...this.pendingPages]}getPackageInfo(){var e;return this.packageSnapshot?tB(this.manifest):{appId:null==(e=this.packageSource)?void 0:e.appId}}resolveFileSystemNamespace(){return void 0!==this.configuredFileSystemNamespace?this.configuredFileSystemNamespace:ec({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",a=this.getCurrentStackItem(),n=e=>e.entry.path===r.path,s="replace"===i?a&&n(a)?this.stack.length-1:-1:"navigate"===i||"pop_to"===i?this.stack.findLastIndex(n):-1;if(s>=0){var o;let e=this.stack[s],r=t.globalProps??{};for(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);this.bridge.publishPageStack(),e.page.updateGlobalProps({__LOCATION__:r.__LOCATION__,__RENDER_DATA__:r.__RENDER_DATA__}),e.page.setVisible(this.visible),a!==e&&this.visible&&this.sendPageLifecycleEvent(e,tD),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:t$(e.route,e.options).route,resourceUrl:e.resourceUrl,entry:e.entry,element:e.element}}}class tH{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,a,n,s,o,l,d,u;let c=e.fileSystemNamespace??ec({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==(a=e.viewContext)?void 0:a.conversationId)??"",c,e.versionTag??(null==(n=e.viewContext)?void 0:n.versionTag)??"",h].join("\0"),f=this.runtimes.get(g);if(f&&!f.isDestroyed)return f;let v=new tz({packageManager:m,pageHost:e.pageHost,sandboxUrl:e.sandboxUrl,manifest:(null==(s=e.packageInfo)?void 0:s.manifest)??new p({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??N,className:e.className,fileSystemNamespace:c,nativeModulesCallHandler:e.nativeModulesCallHandler,appInitData:e.appInitData,appGlobalProps:tq(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??tE,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 tV(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,a;this.prepared||this.clear(),this.prepared=!1;let{application:n,applicationPackage:s,appRuntimeEntry:o,...l}=e,d=(null==n?void 0:n.appId)??(null==(i=l.globalProps)||null==(r=i.packageInfo)?void 0:r.appId),u=(null==n?void 0:n.appRuntimeEntry)??o,c=(null==n?void 0:n.viewContext)??(null==(a=l.globalProps)?void 0:a.__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==n?void 0:n.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 tH(void 0,!0),r(64041),r(91394),r(25907),r(92151);var tG=r(13817);let tJ=/^\/assets\/framework\/doubao-apps-(?:api|framework|react|react-dev)\.template\.js$/,tK="embed-webview",tZ="__channel_ack__",tX=new WeakMap,tY=e=>({url:e});function tQ(e){if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}}function t0(e){return"string"==typeof e?e:JSON.stringify(e??{})}let t1=globalThis.HTMLElement??class{},t2="region-to-decode";function t3(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:a}=e;return![t,r,i,a].every(Number.isFinite)||t<0||r<0||i<=0||a<=0?null:{x:t,y:r,width:i,height:a}}class t4{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,t2,{configurable:!0,get:()=>t3(e.getAttribute(t2)),set:t=>{let r=t3(t);r?e.setAttribute(t2,JSON.stringify(r)):e.removeAttribute(t2)}})}connectedCallback(){this.attributes.observe(this.element,{attributes:!0,attributeFilter:[t2,"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=t3(this.element.getAttribute(t2)),a=this.image;if(!i||!a)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),a.addEventListener("load",this.update),a.addEventListener("error",this.clearCrop));let n=a.naturalWidth,s=a.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(!a.complete||!n||!s||a.getAttribute("src")!==d)return void this.clearCrop();let u=Math.min(i.width,n-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,a,n,s,o,l,d,u,c,p={72941(e,t,r){let i,a,n;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){let t=o(e)?e.appTheme:void 0;return"light"===t||"dark"===t?t:void 0}function d(e){var t;return"string"==typeof(null==(t=e.web)?void 0:t.entry)}function u(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 c(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 p{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(d),this.pageIdEntryMap=u(this.pageEntries,e=>e.id),this.pagePathEntryMap=u(this.pageEntries,e=>{var t;return(null==(t=e.path)?void 0:t.startsWith("/"))?e.path:void 0}),this.widgetEntries=e.widgets,this.widgetEntryMap=u(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 c(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 h(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 a=await i.json();if(!o(a))throw Error("Invalid Web manifest: expected a JSON object");return new p(a)}function m(e,t,r){var i,a;let n="item"in t?t.item:t,s="id"in n||"widgetId"in n?"string"==typeof(null==(i=n.web)?void 0:i.entry)?n.web.entry:void 0:n.entry;if(!s)return;let o=new URL(e,r??(null==(a=globalThis.location)?void 0:a.href)??"http://localhost/");return o.pathname=o.pathname.replace(/\/base\/manifest\.json$/,"/"),new URL(s,o).toString()}function g(){let e=Error("Widget host call was cancelled");return e.name="AbortError",e}function f(e){if(e.aborted)throw g()}function v(e,t){return f(t),new Promise((r,i)=>{let a=!1,n=e=>{a||(a=!0,t.removeEventListener("abort",s),e())},s=()=>n(()=>i(g()));t.addEventListener("abort",s,{once:!0}),Promise.resolve().then(e).then(e=>n(()=>r(e)),e=>n(()=>i(e)))})}function y(e){return(null==e?void 0:e.type)==="call"}function b(e){return(null==e?void 0:e.type)==="callback"}function w(e){return(null==e?void 0:e.type)==="event"}class _ 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 S(e,t){return{type:"callback",callbackId:e.callbackId,params:{code:1,data:t}}}function x(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 I(e){return e instanceof Error?e.message:String(e)}function k(e,t){return t instanceof _?x(e,t.message,t.errNo,t.errMsg):x(e,I(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 C{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),a="function"==typeof t?{handler:t,canIUse:!0}:{...t,canIUse:t.canIUse??!0};return this.registry.set(e,a),this.handlers[e]=a.handler,()=>{if(this.registry.get(e)===a){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,a]of Object.entries(e))r.push(this.register(i,a,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),a="function"==typeof t?{source:t}:t;return this.stopEventSource(e),this.eventSources.set(e,a),(this.eventSourceRetainCounts.get(e)??0)>0&&this.startEventSource(e,a),()=>{if(this.eventSources.get(e)===a){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,a]of Object.entries(e))r.push(this.registerEventSource(i,a,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(!y(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(!y(e))return;let i=t[e.name];if(!i)return x(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=>k(e,t));return t??x(e,`API ${e.name} is not implemented in Doubao Web SDK`)}catch(t){return k(e,t)}}(e,this.handlers,i);let a=this.registry.has(e.name)?103:-1;if(!r)return x(e,`API ${e.name} is not implemented in Doubao Web SDK`,a);try{let t=r(e.name);return t instanceof Promise?t.then(()=>x(e,`API ${e.name} is not implemented in Doubao Web SDK`,a)).catch(t=>k(e,t)):x(e,`API ${e.name} is not implemented in Doubao Web SDK`,a)}catch(t){return k(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 E(this,e)}fork(){let e=new C(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,a;null==(a=this.eventSources.get(e))||null==(i=a.onSubscribe)||i.call(a,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 E{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 N=new C;function T(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:i;return null==e?void 0:e.getPackageInfo()}async function A(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 M(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 j(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i;return await (null==t?void 0:t.reLaunch(e)),!!t}function R(){return"0.9.1"}function P(e){var t;let{screenWidth:r,statusBarHeight:i}=e??(null==(t=globalThis.lynx)?void 0:t.__globalProps),a=Math.round(i)+4,n=Math.round(r)-12;return{bottom:a+36,height:36,left:n-84,right:n,top:a,width:84}}function L(){return(navigator.language||"zh-CN").replace(/-/g,"_")}function O(){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:R()??""}function U(){return navigator.userAgentData}function $(){var e;let t=null==(e=U())?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 q(){var e,t;let r=null==(e=U())?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 a=navigator.userAgent??"";return(null==(t=/(?:edg|chrome|crios|firefox|fxios|version)\/([\d.]+)/i.exec(a))?void 0:t[1])??void 0}function B(){var e;let t=navigator.userAgent??"",r=navigator.platform??"",i=(null==(e=U())?void 0:e.platform)??"",a=`${i} ${r} ${t}`,n=navigator.maxTouchPoints??0;return/android/i.test(a)?{platform:"android",brand:"Android"}:/iphone/i.test(a)?{platform:"ios",brand:"iPhone"}:/ipad/i.test(a)||/mac/i.test(r)&&n>1?{platform:"ios",brand:"iPad"}:/mac/i.test(a)?{platform:"mac",brand:"Mac"}:/win/i.test(a)?{platform:"windows",brand:"Windows"}:/linux/i.test(a)?{platform:"linux",brand:"Linux"}:{platform:"web",brand:"Browser"}}function F(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:T();return{appId:(null==e?void 0:e.appId)??"",name:(null==e?void 0:e.name)??"",iconSrc:null==e?void 0:e.iconSrc}}function W(e){var t,r,i,a,n;if((null==e?void 0:e.containerWidth)!==void 0){let{density:t=1,screenWidth:r=0,screenHeight:i=0,containerWidth:a=0,containerHeight:n=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:a,windowHeight:n,statusBarHeight:s,screenTop:o,safeArea:{left:c,right:a-p,top:d,bottom:n-u,width:a-c-p,height:n-d-u}}}let s=Math.round((null==(a=window.visualViewport)?void 0:a.width)??window.innerWidth??0),o=Math.round((null==(n=window.visualViewport)?void 0:n.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 z(){return B().platform}function H(){var e,t,r,i,a;let n=navigator.userAgent??"",s=z();return"android"===s?null==(e=/android\s+([\d.]+)/i.exec(n))?void 0:e[1]:"ios"===s?null==(r=/(?:iphone os|cpu os)\s+([\d_]+)/i.exec(n))||null==(t=r[1])?void 0:t.replace(/_/g,"."):"mac"===s?null==(a=/mac os x\s+([\d_]+)/i.exec(n))||null==(i=a[1])?void 0:i.replace(/_/g,"."):void 0}function V(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:z();return"android"===e?"Android":"ios"===e?"iOS":"mac"===e?"macOS":"windows"===e?"Windows":"linux"===e?"Linux":"Web"}function G(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=B(),i=navigator.platform||z();return{abi:i,deviceAbi:i,benchmarkLevel:-1,brand:r.brand,model:function(){let e=navigator.userAgent??"",t=z();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?B().brand:"mac"===t||"windows"===t||"linux"===t?navigator.platform||B().brand:$()}(),system:function(){let e=z(),t=H();if("web"!==e){let r=V(e);return t?`${r} ${t}`:r}let r=q(),i=$();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 J(){let e=G(),t=W(),r=t.windowWidth>t.windowHeight,i=O();return{os:V(e.platform),platform:e.platform,osVersion:H(),deviceBrand:e.brand,language:L(),deviceModel:e.model,deviceType:e.model,deviceAbi:e.deviceAbi,cpuType:e.cpuType,memorySize:e.memorySize,benchmarkLevel:e.benchmarkLevel,appVersion:q(),appTheme:i,theme:i,channel:"release",screenOrientation:+!!r,isLandscape:+!!r,abi:e.abi}}function K(e){var t,r,i;let a,n=W(e),s=G(e);return{...n,brand:s.brand,model:s.model,language:(null==e||null==(t=e.language)?void 0:t.replace(/-/g,"_"))??L(),version:(null==e?void 0:e.appVersion)??q(),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)??O(),benchmarkLevel:s.benchmarkLevel,enableDebug:(null==e?void 0:e.channel)==="debug",deviceOrientation:(i=n.windowWidth>n.windowHeight,!0===(a=(null==e?void 0:e.isLandscape)??(null==e?void 0:e.screenOrientation))||1===a||"string"==typeof a&&a.toLowerCase().includes("landscape")?"landscape":!1===a||0===a||"string"==typeof a&&a.toLowerCase().includes("portrait")?"portrait":i?"landscape":"portrait"),abi:s.abi}}function Z(){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 X(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)??L(),version:(null==e?void 0:e.appVersion)??q(),theme:(null==e?void 0:e.appTheme)??O()}}function Y(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:T(),t=arguments.length>1?arguments[1]:void 0;return{miniProgram:{appId:F(e).appId,envVersion:(null==t?void 0:t.channel)==="debug"?"develop":"release",version:(null==e?void 0:e.versionName)??""}}}function Q(e){var t;return(null==e||null==(t=e.navigation)?void 0:t.getPackageInfo())??(null==e?void 0:e.packageInfo)}N.handlers,r(31178),r(32085),r(12021);var ee=r(95550),et=r(66013);r(46455);function er(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 ei(e){if(ea(e)>1048576)throw Error("data size must be less than or equal to 1048576 bytes")}function ea(e){return new TextEncoder().encode(e).byteLength}function en(e){return Object.values(e).reduce((e,t)=>e+ea(t),0)}function es(e){if(e>0xa00000)throw new _("total storage size exceeded",1600002)}function eo(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(er(r),"string"!=typeof i)throw Error("Storage values must be serialized strings");ei(i),t+=ea(i)}es(t)}let el=new Map,ed=new Map,eu=new Set;function ec(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,et.My)((0,ee.sc)(i))}`}function ep(){let e=Date.now();return{entries:Object.fromEntries(["/","/temp","/user"].map(t=>[t,{type:"directory",createTime:e,lastModifiedTime:e}]))}}function eh(){return a??=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(),a=void 0},e(r.result)},r.onerror=()=>{a=void 0,t(r.error)},r.onblocked=()=>{a=void 0,t(Error("Storage database upgrade is blocked; close other app views and retry"))}})}function em(e){return IDBKeyRange.bound([e],[e,[]])}function eg(e){return new Promise((t,r)=>{e.oncomplete=()=>t(),e.onabort=()=>{let t=e.error,i=new _((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 ef(e,t){let r=await eh(),i=r.transaction(["storage","files"]),a=eg(i);for(let[r,a]of[["storage",t.storageSnapshot],["files",t.fileSystemSnapshot.entries]]){let t=i.objectStore(r).openCursor(em(e));t.onsuccess=()=>{let e=t.result;e&&(Object.defineProperty(a,String(e.key[1]),{value:"files"===r?Object.freeze(e.value):e.value,enumerable:!0,configurable:!0,writable:!0}),e.continue())}}if(await a,0===Object.keys(t.fileSystemSnapshot.entries).length){t.fileSystemSnapshot=ep();let i=r.transaction("files","readwrite"),a=eg(i);for(let[r,a]of Object.entries(t.fileSystemSnapshot.entries))i.objectStore("files").put(a,[e,r]);await a}}function ev(e){let t=el.get(e);if(!t){let r={storageSnapshot:{},fileSystemSnapshot:{entries:{}}};t={snapshot:r,references:0,ready:ef(e,r)},el.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||el.get(e)!==r||el.delete(e)};r.ready.then(t,t)}}}function ey(e,t){let r=ev(e),i=async()=>(await r.ready,t()),a=(ed.get(e)??Promise.resolve()).then(i,i);ed.set(e,a);let n=()=>{ed.get(e)===a&&ed.delete(e),r.release()};return a.then(n,n),a}function eb(e){var t;let r=null==(t=el.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 ew(e){return eb(e).fileSystemSnapshot}function e_(e){return eu.add(e),()=>{eu.delete(e)}}function eS(e,t,r){let i={...r??eb(e),fileSystemNamespace:e,mutationId:t};for(let e of eu)try{e(i)}catch(e){console.error("Cannot deliver application storage update",e)}}function ex(e,t){let r={};for(let i of new Set([...Object.keys(e),...Object.keys(t)])){let a=Object.hasOwn(t,i)?t[i]:null,n=Object.hasOwn(e,i)?e[i]:void 0,s=o(n)&&o(a)&&n.type===a.type&&n.data===a.data&&n.createTime===a.createTime&&n.lastModifiedTime===a.lastModifiedTime;n===(a??void 0)||s||Object.defineProperty(r,i,{value:a,enumerable:!0})}return r}async function eI(e,t){let r=eb(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)&&eo(r.storageSnapshot),t.fileSystemChanges&&eC(r.fileSystemSnapshot,ew(e));let i=(await eh()).transaction(["storage","files"],"readwrite"),a=eg(i);try{for(let[r,a]of(t.clearStorage&&i.objectStore("storage").delete(em(e)),[["storage",t.storageChanges],["files",t.fileSystemChanges]])){let t=i.objectStore(r);for(let[i,n]of Object.entries(a??{}))null===n?t.delete([e,i]):t.put("files"===r?Object.freeze(n):n,[e,i])}}catch(e){throw i.abort(),await a.catch(()=>{}),e}await a,el.get(e).snapshot=r,eS(e,t.mutationId,t)}function ek(e){return o(e)&&"directory"===e.type}function eC(e,t){if(!o(e)||!o(e.entries))throw Error("Invalid file snapshot");let r={user:0,temp:0};for(let[i,a]of Object.entries(e.entries)){if(!o(a)||!["file","directory"].includes(String(a.type))||!Number.isFinite(a.createTime)||0>Number(a.createTime)||!Number.isFinite(a.lastModifiedTime)||0>Number(a.lastModifiedTime)||"/"!==i&&(!/^\/(user|temp)(\/[^/]+)*$/.test(i)||i.split("/").some(e=>"."===e||".."===e||/[\\\0]/.test(e)))||"/"!==i&&!ek(e.entries[i.slice(0,i.lastIndexOf("/"))||"/"])||["/","/user","/temp"].includes(i)&&"directory"!==a.type)throw Error(`Invalid file entry: ${i}`);if("file"===a.type){if("string"!=typeof a.data)throw Error(`Invalid file data: ${i}`);if((null==t?void 0:t.entries[i])!==a&&(a.data.length%4!=0||/[^A-Za-z0-9+/=]/.test(a.data)||!/^[^=]*={0,2}$/.test(a.data)))throw Error(`Invalid base64 file: ${i}`);let e=i.startsWith("/user/")?"user":"temp";r[e]+=Math.floor(3*a.data.length/4)-(a.data.endsWith("==")?2:+!!a.data.endsWith("="))}}for(let t of["/","/user","/temp"])if(!ek(e.entries[t]))throw Error(`Missing file directory: ${t}`);if(r.user>0x3200000||r.temp>0x6400000)throw new _("total file storage size exceeded",208)}function eE(e){if(!o(e)||"doubao-web-storage"!==e.format||1!==e.version||!o(e.storageSnapshot))throw Error("存储与文件备份格式无效");eo(e.storageSnapshot),eC(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 eN=r(59933),eT=r(12683);function eA(e){if(e.startsWith("/")||e.includes("\\")||e.includes("\0")||/^[a-z]:/i.test(e))throw new _("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 _("ZIP entry escapes the target directory",213);t.pop()}else t.push(r);return t.join("/")}function eM(e){return Math.floor(3*e.length/4)-(e.endsWith("==")?2:+!!e.endsWith("="))}function ej(e){if(e>0xa00000)throw new _("total size limit exceeded",208)}function eR(e,t,r){let i=t.startsWith("/user/")?"/user/":"/temp/",a=("/user/"===i?50:100)*1048576,n=r;for(let[r,a]of Object.entries(e.entries))r!==t&&r.startsWith(i)&&"file"===a.type&&(n+=eM(a.data));if(n>a)throw new _("total size limit exceeded",208)}function eP(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 eL(e,t){let r=e[t];if("string"!=typeof r)throw new _(`${t} must be a string`,104);return r}function eO(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 _("invalid applet file path",213);try{t=decodeURIComponent(e)}catch{throw new _("invalid applet file path",213)}if("."===t||".."===t||t.includes("/")||t.includes("\\")||t.includes("\0"))throw new _("invalid applet file path",213);return t}function eU(e){let t=/^appletfile:\/\/(user|temp)(?:\/(.*))?$/.exec(e);if(!t)throw new _("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 a=i.split("/").map(eD);return`/${r}/${a.join("/")}`}function e$(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 _("invalid base64 data",104);return{type:"file",data:r,createTime:0,lastModifiedTime:0}}function eq(e){let t=eU(e);if("/temp"===t||"/user"===t)return"";let r=t.lastIndexOf("/");return t.slice(0,r)}function eB(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function eF(e){let t=e.split("/").filter(Boolean),r=t.shift();if("temp"!==r&&"user"!==r)throw new _(`invalid applet file path: ${e}`,213);let i=t.map(eB).join("/");return i.length>0?`appletfile://${r}/${i}`:`appletfile://${r}`}function eW(e,t){return e.entries[eU(t)]}function ez(e,t){let r=e$(t);if(r)return r;let i=eU(t),a=e.entries[i];if(!a)throw new _(`file not found: ${i}`,203);if("file"!==a.type)throw new _(`path is a directory: ${i}`,1901001);return a}function eH(e,t){let r=eU(t),i=e.entries[r];if(!i)throw new _(`directory not found: ${r}`,203);if("directory"!==i.type)throw new _(`path is not a directory: ${r}`,1901002);return i}function eV(e,t){let r=eq(t);if(!r)throw new _(`invalid parent directory: ${t}`,213);let i=Date.now(),a="";for(let t of r.split("/").filter(Boolean)){a+=`/${t}`;let r=e.entries[a];if((null==r?void 0:r.type)==="file")throw new _(`path is not a directory: ${a}`,1901002);r||(e.entries[a]={type:"directory",createTime:i,lastModifiedTime:i})}}function eG(e){let t;try{t=atob(e)}catch{throw new _("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 eJ(e,t){let r="string"==typeof e?e:String(e??"");return"base64"===t?eG(r):new TextEncoder().encode(r)}function eK(e,t,r){let i=eU(t),a=Date.now(),n=e.entries[i];if((null==n?void 0:n.type)==="directory")throw new _(`path is a directory: ${i}`,1901001);eR(e,i,r.byteLength),eV(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==n?void 0:n.createTime)??a,lastModifiedTime:a}}function eZ(e,t,r){let i=eP(e),a=eL(t,"dirPath"),n=eU(a),s=Date.now(),o=i.entries[n];if((null==o?void 0:o.type)==="directory")return{};if(o)throw new _(`path is not a directory: ${n}`,1901002);if(!0===t.recursive){let e="";for(let t of n.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 _(`path is not a directory: ${e}`,1901002)}else{let e=eq(a);if(!e)throw new _(`invalid parent directory: ${a}`,213);let t=i.entries[e];if(!t)throw new _(`directory not found: ${e}`,203);if("directory"!==t.type)throw new _(`path is not a directory: ${e}`,1901002);i.entries[n]={type:"directory",createTime:s,lastModifiedTime:s}}return r(),{}}function eX(e,t,r){let i=eP(e),a=eL(t,"dirPath"),n=eU(a);if("/temp"===n||"/user"===n)throw new _("cannot remove root directory",213);eH(i,a);let s=`${n}/`,o=Object.keys(i.entries).filter(e=>e.startsWith(s));if(!0!==t.recursive&&o.length>0)throw new _(`directory is not empty: ${n}`,1901001);for(let e of o)delete i.entries[e];return delete i.entries[n],r(),{}}function eY(e,t,r){let i=eP(e),a=eL(t,"filePath"),n=eU(a);return ez(i,a),delete i.entries[n],r(),{}}function eQ(e,t){let r=eP(e),i=eL(t,"path"),a=e$(i),n=a?i:eU(i),s=a??r.entries[n];if(!s)throw new _(`path not found: ${n}`,203);return{size:"file"===s.type?eM(s.data):0,lastModifiedTime:s.lastModifiedTime,isDirectory:"directory"===s.type}}let e0={"doubao.readFile":function(e,t){var r;let i=ez(eP(e),eL(t,"filePath"));return ej(eM(i.data)),{data:(r=i.data,"utf-8"===eO(t,"encoding")?new TextDecoder().decode(eG(r)):r)}},"doubao.writeFile":function(e,t,r){let i=eP(e),a=eJ(t.data,eO(t,"encoding"));return ej(a.byteLength),eK(i,eL(t,"filePath"),a),r(),{}},"doubao.appendFile":function(e,t,r){let i=eP(e),a=eL(t,"filePath"),n=eU(a),s=i.entries[n];if((null==s?void 0:s.type)==="directory")throw new _(`path is a directory: ${n}`,1901001);let o=eJ(t.data,eO(t,"encoding"));ej(o.byteLength),eR(i,n,((null==s?void 0:s.type)==="file"?eM(s.data):0)+o.byteLength);let l=(null==s?void 0:s.type)==="file"?eG(s.data):new Uint8Array,d=new Uint8Array(l.length+o.length);return d.set(l),d.set(o,l.length),eK(i,a,d),r(),{}},"doubao.access":function(e,t){let r=eP(e),i=eL(t,"path");if(!eW(r,i))throw new _(`path not found: ${i}`,203);return{}},"doubao.mkdir":eZ,"doubao.rmdir":eX,"doubao.readdir":function(e,t){let r=eP(e),i=eL(t,"dirPath");return eH(r,i),{files:function(e,t){let r=eU(t),i="/"===r?"/":`${r}/`,a=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&&a.add(e)}return[...a]}(r,i)}},"doubao.unlink":eY,"doubao.stat":eQ,"doubao.copyFile":function(e,t,r){let i=eP(e),a=ez(i,eL(t,"srcPath")),n=eL(t,"destPath");return eR(i,eU(n),eM(a.data)),eK(i,n,eG(a.data)),r(),{}},"doubao.getFileInfo":function(e,t){let r=eL(t,"filePath"),{size:i}=eQ(e,{path:r});if(void 0===t.digestAlgorithm)return{size:i};let a=eL(t,"digestAlgorithm").toLowerCase(),n=ez(eP(e),r),s="md5"===a?eN.Fx:"sha1"===a?eN.e8:void 0;if(!s)throw new _(`unsupported digest algorithm: ${a}`,102);return{size:i,digest:(0,et.My)(s(eG(n.data)))}},"doubao.rename":function(e,t,r){let i=eP(e),a=eL(t,"oldPath"),n=eL(t,"newPath"),s=eU(a),o=eU(n),l=i.entries[s];if(!l)throw new _(`path not found: ${s}`,203);if("/temp"===s||"/user"===s)throw new _("cannot rename root directory",213);if(s===o)return{};if("directory"===l.type&&o.startsWith(`${s}/`))throw new _("cannot move a directory into itself",213);if(i.entries[o])throw new _(`target already exists: ${o}`,102);for(let e of(eV(i,n),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=eP(e),a=eL(t,"filePath"),n=ez(i,a),s=t.length??0;if("number"!=typeof s||!Number.isSafeInteger(s)||s<0)throw new _("length must be a non-negative integer",104);eR(i,eU(a),s);let o=eG(n.data),l=new Uint8Array(s);return l.set(o.slice(0,s)),eK(i,a,l),r(),{}},"doubao.saveFile":function(e,t,r){let i,a,n=eP(e),s=eL(t,"tempFilePath"),o=e$(s),l=o??ez(n,s),d=eO(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"===(a=eU(s))||"/user"===a?"":a.slice(a.lastIndexOf("/")+1),c=`/user/${Date.now()}`,p=d&&d.length>0?d:eF(`${c}_${u}`);for(let e=1;!d&&n.entries[eU(p)];e++)p=eF(`${c}_${e}_${u}`);return eR(n,eU(p),eM(l.data)),eK(n,p,eG(l.data)),o||eU(s)===eU(p)||delete n.entries[eU(s)],r(),{savedFilePath:p}},"doubao.getSavedFileList":function(e){return{fileList:Object.entries(eP(e).entries).flatMap(e=>{let[t,r]=e;return t.startsWith("/user/")&&"file"===r.type?[{filePath:eF(t),size:eM(r.data),createTime:r.createTime}]:[]})}},"doubao.removeSavedFile":function(e,t,r){var i;let a=eL(t,"filePath");return(null==(i=eW(eP(e),a))?void 0:i.type)==="directory"?eX(e,{dirPath:a},r):eY(e,t,r)},"doubao.unzip":function(e,t,r){let i=eP(e),a=ez(i,eL(t,"zipFilePath")),n=eL(t,"targetPath"),s=eU(n),o=function(e,t){try{let r=function(e,t){let r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=e.length-22,a=Math.max(0,e.length-65557);for(;i>=a&&(0x6054b50!==r.getUint32(i,!0)||i+22+r.getUint16(i+20,!0)!==e.length);)i--;if(i<a||0!==r.getUint16(i+4,!0)||0!==r.getUint16(i+6,!0))throw Error("Invalid or multipart ZIP archive");let n=r.getUint16(i+10,!0),s=r.getUint32(i+16,!0);if(65535===n||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");n=Number(r.getBigUint64(e+32,!0)),s=Number(r.getBigUint64(e+48,!0))}if(!Number.isSafeInteger(n)||n>e.length/46||!Number.isSafeInteger(s))throw Error("Invalid ZIP directory size");let o=new Map,l=0;for(let a=0;a<n;a++){if(s+46>i||0x2014b50!==r.getUint32(s,!0))throw Error("Invalid ZIP directory entry");let a=r.getUint16(s+8,!0),n=r.getUint16(s+28,!0),d=r.getUint16(s+30,!0),u=s+46+n+d+r.getUint16(s+32,!0);if(u>i||1&a)throw Error("Invalid or encrypted ZIP entry");let c=(0,eT.he)(e.subarray(s+46,s+46+n),!(2048&a));eA(c);let p=r.getUint32(s+24,!0);if(0xffffffff===p){let e=s+46+n,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 _("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,a=0,n=new eT.HJ(e=>{eA(e.name);let r=new eT.uZ(e.name);r.ondata=()=>{};let n=[],s=0;e.ondata=(o,l,d)=>{if(o)throw o;if((a+=l.length)>t)throw new _("ZIP expanded size exceeds the file system quota",208);if(n.push(l),s+=l.length,r.push(l,d),d){let t=new Uint8Array(s),a=0;for(let e of n)t.set(e,a),a+=e.length;i.set(e.name,{data:t,crc:r.crc>>>0})}},e.start()});n.register(eT.mM);for(let t=0;t<e.length;t+=65536)n.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 _)throw e;throw new _(`Unable to unzip file: ${e instanceof Error?e.message:String(e)}`,102)}}(eG(a.data),(s.startsWith("/user")?50:100)*1048576),l={...e,fileSystemSnapshot:{entries:{...i.entries}}};for(let[e,t]of(eZ(l,{dirPath:n,recursive:!0},()=>{}),o)){let r=eA(e);if(!r)continue;let i=eF(`${s}/${r}`);e.endsWith("/")?eZ(l,{dirPath:i,recursive:!0},()=>{}):eK(l.fileSystemSnapshot,i,t)}return i.entries=l.fileSystemSnapshot.entries,r(),{}}},e1="doubao.__webSyncBridgePersist",e2="doubao.__webSyncBridgeUpdated";r(20789),r(62839),r(66876),r(35336);let e3="doubao.getPerformanceEntries",e4="doubao.setPerformanceBufferSize",e6="doubao.onPerformanceEntries",e5="doubao.__webPerformanceTiming",e8="__WEB_PERFORMANCE_WIDGET_IDENTITY__",e9=[e3,e4,e6];class e7{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},a=i("create_lynx_start"),n=i("layout_start"),s=i("layout_end");if(void 0===a||void 0===n||void 0===s||s<n||n<a)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,a);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:a,duration:s-a,...d,...void 0!==p&&p>=a&&p<=s?{viewLayerReadyTime:p}:{},viewLayerRenderStartTime:n,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 te(e,t){try{await (null==t?void 0:t(e.params))}catch{}}let tt=new Map,tr={"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 S(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 S(e,{})}};function ti(){var e;return null==(e=globalThis.navigator)?void 0:e.clipboard}function ta(e,t){let r=ti();if(!r||"function"!=typeof r[t])throw new _(`${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 _(`${e} failed: ${r}`,o(t)&&("NotAllowedError"===t.name||"SecurityError"===t.name)?106:102);return i.cause=t,i}async function ts(e){let t=ta("setClipboardData","writeText");try{await t.writeText(e)}catch(e){throw tn("setClipboardData",e)}}async function to(){let e=ta("getClipboardData","readText");try{let t=await e.readText();if("string"==typeof t)return t}catch(e){throw tn("getClipboardData",e)}throw new _("getClipboardData failed: clipboard did not return text",102)}function tl(e,t,r){let i=(null==t?void 0:t.fileSystemNamespace)??ec(null==t?void 0:t.globalProps);return ey(i,async()=>{try{var a,n;let s=ew(i),l={fileSystemNamespace:i,fileSystemSnapshot:{entries:{...s.entries}},apiResults:{"doubao.getSystemInfo":{platform:null==t||null==(n=t.globalProps)||null==(a=n.os)?void 0:a.toLowerCase()}},storageSnapshot:{},supportedAPIs:[]},d=!1,u=(0,e0[e.name])(l,o(e.params)?e.params:{},()=>{d=!0});return d?await eI(i,{fileSystemChanges:ex(s.entries,l.fileSystemSnapshot.entries),mutationId:r}):r&&eS(i,r,{}),S(e,u)}catch(e){throw r&&eS(i,r),e}})}let td=Object.fromEntries(Object.keys(e0).map(e=>[e,tl]));async function tu(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:a}=e,n=await new Promise((e,r)=>{let i=new Image,n=()=>{null==t||t.removeEventListener("abort",s),i.onload=i.onerror=null},s=()=>{n(),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=()=>{n(),e(i)},i.onerror=()=>{n(),r(Error(`failed to load image: ${a}`))},i.src=a)}),s=null==(r=a.match(/^data:image\/([^;,]+)/i))?void 0:r[1],o=null==(i=a.match(/\.([a-zA-Z0-9]+)(?:[?#].*)?$/))?void 0:i[1];return{width:n.naturalWidth||n.width,height:n.naturalHeight||n.height,orientation:"up",path:a,type:((null==s?void 0:s.split("+")[0])??o??"").toLowerCase()}}function tc(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 tp(e){return async(t,r)=>{let i=t.params;if(!i||"string"!=typeof i.url||!i.url.trim())return x(t,"invalid url",104);try{return await e(i,null==r?void 0:r.navigation)?S(t,{}):x(t,"No active Runtime to navigate",102)}catch(e){return x(t,I(e),e instanceof _?e.errNo:102)}}}let th={"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 x(e,"url and mode must describe a valid page route",104);if(!(null==t||null==(r=t.navigation)?void 0:r.openPage))return x(e,"No active Runtime to open page",102);try{return await t.navigation.openPage(i),S(e,{})}catch(t){return x(e,I(t),t instanceof _?t.errNo:102)}},"doubao.enableAlertBeforeUnload":(e,t)=>{var r;let i=null==(r=e.params)?void 0:r.message;return"string"!=typeof i?x(e,"message must be a string",104):tm(e,i,t)},"doubao.disableAlertBeforeUnload":(e,t)=>tm(e,void 0,t),"doubao.getCurrentPages":{handler:(e,t)=>S(e,tc(t)),syncResult:tc},"doubao.navigateTo":tp(A),"doubao.redirectTo":tp(M),"doubao.reLaunch":tp(j),"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)?x(e,"No pages in back stack",102):S(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)?x(e,"No active Runtime to exit app",102):S(e,{})};function tm(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)?S(e,{}):x(e,"not found page",102):x(e,"alert before unload is only supported in page container",103)}let tg=Object.fromEntries(["setStorage","getStorage","removeStorage","clearStorage","getStorageInfo"].map(e=>[`doubao.${e}`,async(t,r)=>{let i=(null==r?void 0:r.fileSystemNamespace)??ec(null==r?void 0:r.globalProps);return ey(i,async()=>{var r,a;let n=o(t.params)?t.params:{},s=eb(i).storageSnapshot,l={};switch(e){case"setStorage":{let e,t;if("string"!=typeof n.data)throw Error("data must be a serialized string");let o=(r=n.key,a=n.data,e=er(r),ei(a),t=Object.prototype.hasOwnProperty.call(s,e)?s[e]:void 0,es(en(s)-(void 0===t?0:ea(t))+ea(a)),e);await eI(i,{storageChanges:{[o]:n.data}});break}case"getStorage":let d;l={data:Object.hasOwn(s,d=er(n.key))?s[d]:void 0};break;case"removeStorage":await eI(i,{storageChanges:{[er(n.key)]:null}});break;case"clearStorage":await eI(i,{clearStorage:!0});break;case"getStorageInfo":l={keys:Object.keys(s),currentSize:Math.ceil(en(s)/1024),limitSize:10240}}return S(t,l)})}])),tf={...{"doubao.getClipboardData":{canIUse:()=>{var e;return"function"==typeof(null==(e=ti())?void 0:e.readText)},handler:async e=>S(e,{data:await to()})},"doubao.setClipboardData":{canIUse:()=>{var e;return"function"==typeof(null==(e=ti())?void 0:e.writeText)},handler:async e=>{let{data:t}=function(e){if(!o(e)||"string"!=typeof e.data)throw new _("data must be a string",104);return{data:e.data}}(e.params);return await ts(t),S(e,{})}}},...tr,...td,...{"doubao.getImageInfo":async e=>S(e,await tu(e.params))},...th,...tg,...{[e1]: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 a="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(e0,i.name)||!o(i.params))throw Error("Invalid synchronous file operation");return tl({...e,name:i.name,params:i.params},t,a)}let n={storageChanges:o(r.storageChanges)?r.storageChanges:void 0,clearStorage:!0===r.clearStorage,fileSystemChanges:o(r.fileSystemChanges)?r.fileSystemChanges:void 0,mutationId:a};return await ey(i,async()=>{try{await eI(i,n)}catch(e){throw eS(i,n.mutationId),e}}),S(e,{})}},...{"doubao.canIUse":{handler:(e,t)=>{let{schema:r}=e.params;return S(e,{result:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:N;return t.canIUse(e,{apiRegistry:t})}(r,null==t?void 0:t.apiRegistry)})}},"doubao.getAccountInfo":{handler:(e,t)=>{var r;return S(e,Y(null==t||null==(r=t.navigation)?void 0:r.getPackageInfo(),null==t?void 0:t.globalProps))},syncResult:e=>Y(Q(e),null==e?void 0:e.globalProps)},"doubao.getPackageInfo":{handler:(e,t)=>{var r;return S(e,F(null==t||null==(r=t.navigation)?void 0:r.getPackageInfo()))},syncResult:e=>F(Q(e))},"doubao.getAppBaseInfo":{handler:(e,t)=>S(e,X(null==t?void 0:t.globalProps)),syncResult:e=>X(null==e?void 0:e.globalProps)},"doubao.getMenuButtonBoundingClientRect":{handler:(e,t)=>S(e,P(null==t?void 0:t.globalProps)),syncResult:e=>P(null==e?void 0:e.globalProps)},"doubao.getSystemInfo":{handler:(e,t)=>S(e,K(null==t?void 0:t.globalProps)),syncResult:e=>K(null==e?void 0:e.globalProps)},"doubao.getWindowInfo":{handler:(e,t)=>S(e,W(null==t?void 0:t.globalProps)),syncResult:e=>W(null==e?void 0:e.globalProps)},"doubao.getDeviceInfo":{handler:(e,t)=>S(e,G(null==t?void 0:t.globalProps)),syncResult:e=>G(null==e?void 0:e.globalProps)},"doubao.getNetworkType":{handler:e=>S(e,Z()),syncResult:Z}}};N.registerMany(tf,{override:!0}),N.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 tv{router;navigation;onEmpty;runtime;callers=new Map;destroyed=!1;performance=new e7;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,a;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=tt.get(i)??{receivers:new Set,recent:[]},tt.set(i,e),e.receivers.add(r),a=()=>{let t=Date.now();e.recent=e.recent.filter(e=>1e4>=Math.abs(t-e.timestamp))},{publish(t){for(let r of(a(),e.recent.push({message:t,timestamp:t.timestamp??Date.now()}),[...e.receivers]))r(t)},replay(t,r,i){for(let n of(a(),e.recent))n.message.name===t&&n.timestamp>=r&&i(n.message)},release(){e.receivers.delete(r),0===e.receivers.size&&tt.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)??N}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 a=(null==t?void 0:t.apiRegistry)??this.apiRegistry;this.unsubscribeStorage??=e_(e=>{for(let t of this.callers.values())t.fileSystemNamespace===e.fileSystemNamespace&&t.events.emitPrivate(e2,e)});let n=a.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:n,main:r}),i}resolveStorageNamespace(e,t,r){var i,a,n;return(null==(i=this.runtime)?void 0:i.getFileSystemNamespace())??(null==(a=e.options)?void 0:a.fileSystemNamespace)??r??ec(t,null==(n=e.options)?void 0:n.userId)}async prepareStorage(e,t,r){let i=this.getCaller(e),a=this.resolveStorageNamespace(i,t,r);if(i.fileSystemNamespace!==a){var n;null==(n=i.storage)||n.release(),i.storage=void 0,i.fileSystemNamespace=a}i.storage??=ev(a),await i.storage.ready}createSyncBridgeData(e,t,r){var i;let a=this.getCaller(e),n=function(e,t){var r;let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:ec(e),a=arguments.length>3?arguments[3]:void 0,n=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:N;return e.getSupportedNames({apiRegistry:e})}(t);return{hostFileSystem:Object.keys(e0).every(r=>null==t?void 0:t.canIUse(r,{globalProps:e})),fileSystemNamespace:i,...eb(i),hostStorage:!!(null==t?void 0:t.canIUse("doubao.setStorage",{globalProps:e})),apiResults:(r=null==e?void 0:e.packageInfo,(t??N).getSyncResults({globalProps:e,navigation:a,packageInfo:r})),supportedAPIs:n}}(t,(null==(i=a.options)?void 0:i.apiRegistry)??this.apiRegistry,this.resolveStorageNamespace(a,t,r),this.navigation);return n.performance=this.performance.snapshot(),a.fileSystemNamespace=n.fileSystemNamespace,n.supportedAPIs.push(...e9,e2),n}getCurrentPagesSnapshot(){return this.navigation?{"doubao.getCurrentPages":{pages:this.navigation.getCurrentPages()}}:void 0}publishPageStack(){let e=this.getCurrentPagesSnapshot();if(e)for(let t of this.callers.values())t.events.emit(e2,{apiResults:e})}beginPerformance(e,t){var r,i,a;let n=this.getCaller(e),s=t.globalProps??{},l=o(s.__VIEW_CONTEXT__)?s.__VIEW_CONTEXT__:{},d=o(s[e8])?s[e8]:l,u="PAGE"===t.containerType,c=null==(i=this.navigation)||null==(r=i.getCurrentPages().at(-2))?void 0:r.route.split("?")[0],p=null==(a=[...this.callers.values()].findLast(e=>{var t;return(null==(t=e.performanceTrace)?void 0:t.path)===c}))?void 0:a.performanceTrace;n.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(e2,{performance:this.performance.snapshot()}),e.length&&t.events.emit(e6,{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 a=this.getCaller(e);if(!y(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:"",n="applet.subscribeEvent"===t.name&&!a.events.isSubscribed(i);if(tr[t.name](t,{...r,events:a.events}),"applet.subscribeEvent"===t.name&&i===e2&&(null==r?void 0:r.environment)!=="sandbox"){let e=this.resolveStorageNamespace(a,null==r?void 0:r.globalProps,a.fileSystemNamespace??(null==r?void 0:r.fileSystemNamespace));a.events.emitPrivate(i,{apiResults:this.getCurrentPagesSnapshot(),performance:this.performance.snapshot(),fileSystemNamespace:e,...eb(e)})}return n&&i&&"number"==typeof e.timestamp&&this.getApplicationEvents().replay(i,e.timestamp,a.send),{routed:!1}}return(null==(i=t.target)?void 0:i.scope)!=="main"||"self"!==t.target.target||!this.router||a.main?{routed:!1}:this.router.call(e,t)}async dispatch(e,t,r,i,a){var n,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:a.containerType,element:a.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 te(e,t)}(r,null==c?void 0:c.onWidgetInteraction);if(e)return await e}let m=await this.handleMessage(e,r,a);if(m.routed)return await m.result;let g=await (null==c||null==(n=c.appletSessionMessageHandler)?void 0:n.call(c,r,p));if(null==g?void 0:g.routed)return await g.result;"iframe"!==d&&h&&w(r)&&"__bridge_ready__"===r.name&&(null==c||null==(s=c.onReady)||s.call(c));let f=h&&b(r),v="inline"===d&&"sandbox"!==a.environment;if(f&&v&&"TOOL"!==a.containerType)return u.send(r),r;let _=r=>("iframe"!==d&&"postMessage"===t&&b(r)&&this.callers.get(e)===u&&u.send(r),r);try{if(h&&y(r)&&"sandbox"!==a.environment){let e=o(r.params)?r.params:{};if(r.name===e5){let t=u.performanceTrace?this.performance.recordTiming(u.performanceTrace,e.timing):[];return t.length&&this.publishPerformance(t),_(S(r,{}))}if(r.name===e3)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===e4)return this.performance.setBufferSize(e.size),this.publishPerformance(),_(S(r,{}));if("doubao.canIUse"===r.name&&e9.includes(String(e.schema)))return _(S(r,{result:!0}))}let n=this.runtime?this.runtime.nativeModulesCallHandler:null==c?void 0:c.nativeModulesCallHandler,s=await (null==n?void 0:n(t,r,i,p));if(void 0===s&&h&&w(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"===a.environment||void 0===s&&v)return _(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??N;return(i,a,n)=>{if(("AppletJSModule"!==n||"log"!==i)&&"AppletBridgeModule"===n&&"postMessage"===i)return r.dispatch(a,e,t)}}({...a,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,a.globalProps,u.fileSystemNamespace??a.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&&y(r)&&r.name===e1&&b(m)&&o(m.params)&&1!==m.params.code){let e=["Synchronous API persistence failed",m.params];n?await n("log",{level:"error",args:e},"AppletJSModule",p):console.error(...e)}return _(m)}catch(e){if("iframe"===d)throw e;return _(y(r)?k(r,e):void 0)}}handleMainBridgeMessage(e){var t;return!this.destroyed&&(null!=(t=this.router)&&!!t.handleMainBridgeMessage(e)||!!w(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,a;let n=this.callers.get(e);n&&(this.callers.delete(e),null==(t=n.storage)||t.release(),this.callers.size||(null==(i=this.unsubscribeStorage)||i.call(this),this.unsubscribeStorage=void 0),n.abortController.abort(),n.events.destroy(),null==(r=this.router)||r.cancel(e),n.main||this.destroyed||[...this.callers.values()].some(e=>!e.main)||null==(a=this.onEmpty)||a.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)}}function ty(e){if(!e.resourceUrl)throw Error("Container.render requires a resourceUrl");return e.resourceUrl}function tb(e){return e.containerType??"PAGE"}function tw(e){return"WIDGET"===e?"content":"fill"}let t_=/(?:^|[.-])[a-f\d]{8,}(?=[.-]|$)/i;function tS(e){let t=new URL(e),r=t.pathname.slice(t.pathname.lastIndexOf("/")+1),i=R();return i&&!t_.test(r)&&t.searchParams.set("__doubao_resource_reload",i),t.href}function tx(e){return"localhost"===e||"::1"===e||/^127(?:\.\d{1,3}){3}$/.test(e)}function tI(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 tk{options;shared;sandboxUrl;targetOrigin;views=new Map;nextId=0;view=null;port=null;handshakeTimer=null;loaded=!1;failed=!1;connected=!1;constructor(e,t=!1){this.options=e,this.shared=t;let r=new URL(e.sandboxUrl??"https://apps-web-sdk-sandbox.doubaocdn.com/sandbox");if("https:"!==r.protocol&&!("http:"===r.protocol&&tx(r.hostname)))throw Error("iframe isolation url must use HTTPS (HTTP is only allowed on localhost)");this.sandboxUrl=tS(r),this.targetOrigin=r.origin}attach(e){if(this.failed)throw Error("iframe sandbox failed; restart the Runtime before opening another view");let t=this.createView(e.containerType),r=`container-${++this.nextId}`;return this.views.set(r,{...e,visible:"PAGE"===e.containerType}),this.updateVisibility(),{id:r,iframe:t,post:e=>this.post(r,e),setVisible:e=>{let t=this.views.get(r);t&&(t.visible=e,this.updateVisibility())},detach:()=>{this.views.has(r)&&(this.post(r,{type:"dispose"}),this.views.delete(r),this.updateVisibility())}}}clear(){var e;this.destroyChannel(),this.views.clear(),null==(e=this.view)||e.remove(),this.view=null,this.loaded=!1,this.failed=!1}createView(e){var t,r;if(new URL((null==(t=globalThis.location)?void 0:t.href)??"http://localhost/").origin===this.targetOrigin)throw Error("iframe isolation requires a cross-origin sandbox URL");if(this.view)return this.view;let i=document.createElement("iframe");i.className=this.options.className??"doubao-web-container-view",i.dataset.containerType=this.shared?"RUNTIME":e,i.dataset.webSizing=tw(e),i.referrerPolicy="no-referrer",i.title="Doubao app content",i.sandbox.add("allow-scripts","allow-same-origin");let a=tx((null==(r=globalThis.location)?void 0:r.hostname)??"");a&&i.setAttribute("credentialless",""),i.setAttribute("allow",a?"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;let n=this.options.container??document.body;return this.shared?n.append(i):n.replaceChildren(i),i}updateVisibility(){this.shared&&this.view&&(this.view.style.display=[...this.views.values()].some(e=>"PAGE"===e.containerType&&e.visible)?"block":"none")}handleLoad(){if(this.failed||!this.view)return;if(this.loaded)return void this.fail(Error("iframe navigated after the sandbox runtime loaded"));this.loaded=!0;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.addEventListener("close",()=>{this.port===e.port1&&this.fail(Error("iframe message port closed"))}),e.port1.start(),this.handshakeTimer=setTimeout(()=>this.fail(Error("iframe sandbox handshake timed out")),1e4);let t={type:"doubao-web-sdk:connect",protocolVersion:this.shared?2:1,sdkVersion:R()??""};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;if(!e.data||"object"!=typeof e.data)return void this.fail(Error("iframe sandbox sent an invalid protocol message"),e);let i=e.data;if(!this.connected){let t=this.shared?2:1;if("connected"!==i.type||i.protocolVersion!==t)return void this.fail(Error("iframe sandbox protocol version mismatch"),e);for(let e of(this.connected=!0,this.clearHandshakeTimer(),this.views.values()))e.onConnected();return}if(this.shared){if("container"!==i.type||"string"!=typeof i.containerId||!i.message||"object"!=typeof i.message)return void this.fail(Error("iframe sandbox sent an invalid container message"),e);null==(t=this.views.get(i.containerId))||t.onMessage(i.message,e)}else"container"!==i.type?null==(r=this.views.values().next().value)||r.onMessage(i,e):this.fail(Error("iframe sandbox sent an invalid protocol message"),e)}post(e,t){this.connected&&this.port&&this.views.has(e)&&this.port.postMessage(this.shared?{type:"container",containerId:e,message:t}:t)}fail(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tI(e);if(this.failed)return;this.failed=!0,this.destroyChannel(),null==(t=this.view)||t.remove(),this.view=null;let i=[...this.views.values()];for(let t of(this.views.clear(),i))t.onError(e,r)}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}}class tC{page;container;options;sandbox;connection=null;bridge=null;caller;failed=!1;visible=!0;preparedForRender=!1;preparedContainerType=null;renderMessage=null;view=null;constructor(e,t,r=!1){this.page=r,this.container=e.container,this.options=e,this.sandbox=t??new tk(e)}get element(){return this.view}prepare(e){this.clear();try{this.createView(e),this.preparedForRender=!0}catch(e){throw this.clear(),e}}createView(e){if(this.view)return this.preparedContainerType!==e?this.abortRender(Error("iframe container type cannot change after preparation")):this.view;try{this.connection=this.sandbox.attach({containerType:e,onConnected:()=>{this.renderMessage&&this.postOrFail(this.renderMessage)},onMessage:(e,t)=>this.handleMessage(e,t),onError:(e,t)=>this.fail(e,t)})}catch(e){return this.abortRender(e instanceof Error?e:Error(String(e)))}return this.view=this.sandbox.shared?document.createElement("div"):this.connection.iframe,this.sandbox.shared&&(this.view.dataset.containerId=this.connection.id,this.view.dataset.containerType=e,this.view.style.display="none",this.container.replaceChildren(this.view)),this.preparedContainerType=e,this.view}render(e){var t;this.preparedForRender||this.clear(),this.preparedForRender=!1;let r=tb(e),i=new URL(ty(e),document.baseURI).href,a=e.initData??{},n={...J(),...e.globalProps??{}};this.bridge=e.bridge??(null==(t=this.options.runtime)?void 0:t.bridge)??new tv,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,n,this.options.fileSystemNamespace).then(()=>{var t,l,d;if(this.caller!==o)return;s.beginPerformance(o,{...e,containerType:r,globalProps:n});let u=s.createSyncBridgeData(o,n,this.options.fileSystemNamespace);this.renderMessage={type:"render",captureWidgetTap:this.options.captureWidgetTap,resourceUrl:i,...this.sandbox.shared?{groupId:e.groupId,page:this.page,pageCapsule:e.pageCapsule}:{},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:a,globalProps:n,visible:this.visible,syncBridgeData:u},this.postOrFail(this.renderMessage)}).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,r;null==(e=this.connection)||e.detach(),this.connection=null,this.sandbox.shared||this.sandbox.clear(),this.caller&&(null==(t=this.bridge)||t.unregister(this.caller)),this.caller=void 0,this.bridge=null,this.sandbox.shared&&(null==(r=this.view)||r.remove()),this.view=null,this.preparedContainerType=null,this.renderMessage=null,this.failed=!1,this.preparedForRender=!1,this.container.replaceChildren()}setVisible(e){var t,r;this.visible=e,this.caller&&(null==(t=this.bridge)||t.setVisible(this.caller,e)),this.sandbox.shared&&(null==(r=this.connection)||r.setVisible(e)),this.renderMessage&&(this.renderMessage.visible=e,this.postOrFail({type:"set-visible",visible: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,tI(e)),e}handleMessage(e,t){var r,i,a,n;switch(e.type){case"ready":null==(r=(i=this.options).onReady)||r.call(i);break;case"error":this.fail(Error(e.message),t);break;case"resize":(null==(a=this.renderMessage)?void 0:a.containerType)!=="WIDGET"||!Number.isFinite(e.height)||e.height<0?this.fail(Error("only Widget containers may resize the iframe"),t):this.connection&&(this.connection.iframe.style.height=`${e.height}px`,this.connection.iframe.height=String(e.height));break;case"page-capsule":this.page&&("close"===e.action||"more"===e.action)?null==(n=this.view)||n.dispatchEvent(new CustomEvent(`doubao:page-capsule-${e.action}`,{bubbles:!0})):this.fail(Error("iframe sandbox sent an invalid page action"),t);break;case"native-call":!Number.isSafeInteger(e.requestId)||e.requestId<=0||("AppletBridgeModule"!==e.moduleName||"postMessage"!==e.name)&&("AppletJSModule"!==e.moduleName&&"LynxConsoleModule"!==e.moduleName&&"Console"!==e.moduleName||"log"!==e.name)?this.fail(Error("iframe sandbox sent an invalid bridge call"),t):this.handleNativeCall(e);break;case"connected":this.fail(Error("iframe sandbox connected more than once"),t);break;default:this.fail(Error("iframe sandbox sent an invalid protocol message"),t)}}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:I(t)});return}this.bridge===r&&this.caller===i&&this.postOrFail({type:"bridge-result",requestId:e.requestId,result:t})}}post(e){var t;null==(t=this.connection)||t.post(e)}postOrFail(e){try{this.post(e)}catch(e){this.fail(e instanceof Error?e:Error(String(e)))}}fail(e){var t,r,i,a,n;let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tI(e);this.failed||(this.failed=!0,null==(t=this.connection)||t.detach(),this.connection=null,this.sandbox.shared||this.sandbox.clear(),this.caller&&(null==(a=this.bridge)||a.unregister(this.caller)),this.caller=void 0,this.bridge=null,this.sandbox.shared&&(null==(n=this.view)||n.remove()),this.view=null,this.renderMessage=null,null==(r=(i=this.options).onError)||r.call(i,e,s))}}let tE={mode:"iframe",createContainer:e=>new tC(e),createRuntime(e){if(!e.container)return tE;let t=new tk(e,!0);return{mode:"iframe",createContainer:e=>new tC(e,t),createPage(e){let r=new tC(e,t,!0);return{render:e=>r.render({...e,containerType:"PAGE"}),clear:()=>r.clear(),setVisible:e=>r.setVisible(e),sendEvent:(e,t)=>r.sendEvent(e,t),updateGlobalProps:e=>r.updateGlobalProps(e),reload:()=>r.reload()}},clear:()=>t.clear()}}};function tN(){var e;return(null==(e=globalThis.location)?void 0:e.href)??"http://localhost/"}function tT(e){return new URL(e,tN()).toString()}function tA(e,t){if(!t)return e;let r=new URL(e,tN());return r.searchParams.set("__doubao_resource_reload",t),r.toString()}class tM{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&&f(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?v(()=>i,r.signal):i}async fetchPackage(e,t){return{manifestUrl:e,resourceRoot:t,manifest:await h(e,{fetcher:this.options.fetcher})}}async loadPackage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t.signal&&f(t.signal);let{manifestUrl:r,resourceRoot:i}=await this.getPackageSource(e,t),a=tT(r),n=await this.cached(a,()=>this.fetchPackage(a,i),t);if(e&&n.manifest.appId&&n.manifest.appId!==e)throw Error("Resolved package appId must match the requested application");return n}resolveWidget(e,t){let r=this.tryResolveWidgetFromPackage(e,t),i=e.manifest.appRuntimeEntry?m(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?tA(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(tT(e.manifestUrl),Promise.resolve(e))}deletePackage(e){this.packages.delete(tT(e))}clearPackageCache(e){e?this.deletePackage(e):this.packages.clear()}resolveWidgetEntry(e,t){let r=e.manifest.name??t.name,i=m(e.manifestUrl,t);return{appId:e.manifest.appId,entry:t,iconSrc:e.manifest.iconSrc??c(t.icons),appName:r,resourceUrl:i?tA(i,e.resourceUrlVersion??this.resourceUrlVersion):void 0}}tryResolveWidgetFromPackage(e,t){let r=e.manifest.getOptionalWidgetEntry(t);if(r)return this.resolveWidgetEntry(e,r)}}class tj{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((a,n)=>{this.pendingCalls.set(r,{callbackId:t.callbackId,reject:n,resolve:a,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(b(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 tR="onBackground",tP="onDestroy",tL="onForeground",tO="onHide",tD="onShow";function tU(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 t$(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 tq(e,t){return{packageInfo:t,...e}}function tB(e){return{appId:e.appId,name:e.name,iconSrc:e.iconSrc,versionName:e.versionName}}function tF(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return tq(t,tB(e))}function tW(e){if(o(e))return{...e};if("string"!=typeof e)return{};try{let t=JSON.parse(e);return o(t)?t:{}}catch{return{}}}class tz{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=tE,r){var i,a;this.sandboxUrl=e.sandboxUrl,this.packageManager=e.packageManager??new tM({resolveManifestUrl:()=>this.manifestUrl});let n=new tj(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=(null==(a=t.createRuntime)?void 0:a.call(t,{container:null==(i=this.pageHost)?void 0:i.container,sandboxUrl:e.sandboxUrl,className:e.className}))??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 tv(n,{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=>{f(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 v(()=>e,r)}return f(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,a;let n;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=m(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,f(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=tA(l,this.packageInfo.resourceUrlVersion),p=e.pageCapsule??this.pageCapsule,h=`page-${++this.nextPageIndex}`,g=(n=tW(null==(a=u.globalProps)?void 0:a.__VIEW_CONTEXT__),{...o(u.initData)?tW(u.initData.viewContext):{},...n,viewId:h,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(t$(s.path,e));try{let t;try{let e,r;t=y.render({resourceUrl:c,groupId:this.manifest.appId,initData:o(u.initData)?{...u.initData,viewContext:g}:{viewContext:g},globalProps:(e=null==p?void 0:p.statusBarHeight,r="number"==typeof e&&Number.isFinite(e)?{statusBarHeight:e}:{},{...u.globalProps,...r,__VIEW_CONTEXT__:g}),pageCapsule:p})}finally{this.pendingPages.pop()}let r=this.getCurrentStackItem();return v={id:h,pageId:s.id,route:s.path,resourceUrl:c,entry:s,element:t,isReady:!1,options:{...e,entry:s,pageCapsule:p},pendingLifecycleEvents:[],page:y},this.stack.push(v),this.bridge.publishPageStack(),r&&(null==(i=r.backPrompt)||i.abort(),this.visible&&this.sendPageLifecycleEvent(r,tO),r.page.setVisible(!1)),this.updateEmptyState(),v.page.setVisible(this.visible),this.visible&&this.sendPageLifecycleEvent(v,tD),this.sendAppEvent("onPageOpened",{viewId:v.id}),this.toStackEntry(v)}catch(e){throw y.clear(),this.updateEmptyState(),e}}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?tD:tO)),this.appRuntime&&this.sendAppEvent(e?tL:tR)}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(){var e,t;this.lifecycle.abort(),this.lifecycle=new AbortController,this.packageLoading=void 0,this.clearPages(),this.clearAppRuntime(),null==(e=(t=this.runtimeKernel).clear)||e.call(t),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(){let e=this.stack.splice(0);if(0!==e.length){for(let t of(this.bridge.publishPageStack(),e.reverse()))this.destroyStackItem(t);this.updateEmptyState()}}async withPageTransition(e){let t=this.bridge.register();try{return await e()}finally{this.bridge.unregister(t)}}destroyStackItem(e){var t;null==(t=e.backPrompt)||t.abort();let r=this.toStackEntry(e);return this.sendPageLifecycleEvent(e,tP),e.page.clear(),r}removeStackItem(e,t){this.bridge.publishPageStack();let r=this.destroyStackItem(e),i=this.getCurrentStackItem();return t&&i&&this.visible&&(i.page.setVisible(!0),this.sendPageLifecycleEvent(i,tD)),this.updateEmptyState(),r}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,a,n,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=m(this.manifestUrl,this.manifest.appRuntimeEntry);if(!o)throw Error("No Web entry configured for app runtime");let l=tA(o,this.packageInfo.resourceUrlVersion),d=new Promise((e,t)=>{i=e,a=t});d.catch(()=>{});let u={promise:d,resolve:i,reject:a,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{n=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 a=t.createContainer({...e,container:i});return{render:e=>(r.append(i),a.render(e)),clear(){a.clear(),i.remove()},sendEvent:a.sendEvent.bind(a),sendBridgeMessage:a.sendBridgeMessage.bind(a)}}({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!==n||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:n,isReady:!1,pendingEvents:[{name:this.visible?tL:tR,params:{}},...this.pendingAppEvents.splice(0)]};let e=void 0!==s.groupId?s.groupId:this.appGroupId;n.render({bridge:this.bridge,resourceUrl:l,groupId:null===e?void 0:e??this.manifest.appId,containerType:"APP",initData:this.appInitData??{},globalProps:{...tF(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==n||n.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(tR),r.container.sendEvent(tP)),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 tU(e,this.manifest)}catch(e){throw Object.assign(new _(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=>t$(e.route,e.options)),...this.pendingPages]}getPackageInfo(){var e;return this.packageSnapshot?tB(this.manifest):{appId:null==(e=this.packageSource)?void 0:e.appId}}resolveFileSystemNamespace(){return void 0!==this.configuredFileSystemNamespace?this.configuredFileSystemNamespace:ec({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",a=this.getCurrentStackItem(),n=e=>e.entry.path===r.path,s="replace"===i?a&&n(a)?this.stack.length-1:-1:"navigate"===i||"pop_to"===i?this.stack.findLastIndex(n):-1;if(s>=0){var o;let e=this.stack[s],r=t.globalProps??{};for(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);this.bridge.publishPageStack(),e.page.updateGlobalProps({__LOCATION__:r.__LOCATION__,__RENDER_DATA__:r.__RENDER_DATA__}),e.page.setVisible(this.visible),a!==e&&this.visible&&this.sendPageLifecycleEvent(e,tD),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:t$(e.route,e.options).route,resourceUrl:e.resourceUrl,entry:e.entry,element:e.element}}}class tH{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,a,n,s,o,l,d,u;let c=e.fileSystemNamespace??ec({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==(a=e.viewContext)?void 0:a.conversationId)??"",c,e.versionTag??(null==(n=e.viewContext)?void 0:n.versionTag)??"",h].join("\0"),f=this.runtimes.get(g);if(f&&!f.isDestroyed)return f;let v=new tz({packageManager:m,pageHost:e.pageHost,sandboxUrl:e.sandboxUrl,manifest:(null==(s=e.packageInfo)?void 0:s.manifest)??new p({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??N,className:e.className,fileSystemNamespace:c,nativeModulesCallHandler:e.nativeModulesCallHandler,appInitData:e.appInitData,appGlobalProps:tq(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??tE,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 tV(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,a;this.prepared||this.clear(),this.prepared=!1;let{application:n,applicationPackage:s,appRuntimeEntry:o,...l}=e,d=(null==n?void 0:n.appId)??(null==(i=l.globalProps)||null==(r=i.packageInfo)?void 0:r.appId),u=(null==n?void 0:n.appRuntimeEntry)??o,c=(null==n?void 0:n.viewContext)??(null==(a=l.globalProps)?void 0:a.__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==n?void 0:n.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 tH(void 0,!0),r(64041),r(91394),r(25907),r(92151);var tG=r(13817);let tJ=/^\/assets\/framework\/doubao-apps-(?:api|framework|react|react-dev)\.template\.js$/,tK="embed-webview",tZ="__channel_ack__",tX=new WeakMap,tY=e=>({url:e});function tQ(e){if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}}function t0(e){return"string"==typeof e?e:JSON.stringify(e??{})}let t1=globalThis.HTMLElement??class{},t2="region-to-decode";function t3(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:a}=e;return![t,r,i,a].every(Number.isFinite)||t<0||r<0||i<=0||a<=0?null:{x:t,y:r,width:i,height:a}}class t4{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,t2,{configurable:!0,get:()=>t3(e.getAttribute(t2)),set:t=>{let r=t3(t);r?e.setAttribute(t2,JSON.stringify(r)):e.removeAttribute(t2)}})}connectedCallback(){this.attributes.observe(this.element,{attributes:!0,attributeFilter:[t2,"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=t3(this.element.getAttribute(t2)),a=this.image;if(!i||!a)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),a.addEventListener("load",this.update),a.addEventListener("error",this.clearCrop));let n=a.naturalWidth,s=a.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(!a.complete||!n||!s||a.getAttribute("src")!==d)return void this.clearCrop();let u=Math.min(i.width,n-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 ${(n-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 t6=new Set;var t5=r(76935);let t8=new WeakMap;function t9(e,t,r){let i=new Map;for(let a of t){let t=Reflect.get(e,a);i.set(a,Object.getOwnPropertyDescriptor(e,a)),Object.defineProperty(e,a,{configurable:!0,writable:!0,value(){for(var e=arguments.length,i=Array(e),a=0;a<e;a++)i[a]=arguments[a];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 t7{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=t8.get(t);if(!r){let e=new Set;r={portals:e,cleanup:t9(t,["appendChild","insertBefore","removeChild","replaceChild","append","prepend","replaceChildren"],()=>{for(let t of e)t.restore()})},t8.set(t,r)}r.portals.add(this),this.cleanupElement=t9(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=t8.get(this.parent);null==e||e.portals.delete(this),(null==e?void 0:e.portals.size)===0&&(e.cleanup(),t8.delete(this.parent))}}class re{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,a){this.element=e,this.namespace=t,this.map=r,this.onError=i,this.onClick=a,this.portal=new t7(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)},a=JSON.stringify(e.position);this.marker&&a===this.positionKey||(i.position=e.position&&[e.position.longitude,e.position.latitude]),this.portal.mount(this.content);let n=JSON.stringify(e);if(this.marker&&this.optionsKey===n)return void this.syncZIndex();this.optionsKey=n,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=a}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 rt=e=>{let{longitude:t,latitude:r}=e;return[t,r]};function rr(e,t,r,i,a){let n=new Set(t.map(e=>{let{id:t}=e;return t}));for(let[t,r]of e)n.has(t)||(r.destroy(),e.delete(t));for(let n of t)try{let t=r(n),a=e.get(n.id);if(a){let{id:e,...r}=t;a.setOptions(r)}else e.set(n.id,i(t,n))}catch(e){a(e)}}class ri{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 a of e){var i;if(!a.id.startsWith("__doubao_polyline_arrow__:"))continue;let n=null==(i=a.edgeTextureAssets)?void 0:i.find(e=>{let{id:t}=e;return"__doubao_polyline_arrow_texture__"===t});if(n)try{let i=decodeURIComponent(a.id.slice(26));e.some(e=>e.id===i)&&(t.set(i,{iconPath:n.url}),r.add(a))}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,a=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 纹理"),!a&&(null==(t=e.routeLabel)?void 0:t.length)&&this.warn("当前图商的 routeLabel"),r.some(e=>e.collideDetection)&&this.warn("polyline POI 碰撞避让"),rr(this.polylines,r,e=>{var t;return{id:e.id,path:e.points.map(rt),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),rr(this.polygons,e.polygons??[],e=>({id:e.id,path:e.points.map(rt),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),rr(this.circles,e.circles??[],e=>({id:e.id,center:rt(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),rr(this.arcs,e.arcs??[],e=>({id:e.id,path:[rt(e.start),rt(e.mid??e.middle),rt(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),rr(this.routeLabels,a?e.routeLabel??[]:[],e=>({id:e.id,path:e.points.map(rt),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 ra={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"}}}},rn=new WeakMap,rs=new WeakMap,ro=new WeakMap,rl=new WeakMap;function rd(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 ru(e,t,r){let i=Number(e.getAttribute(t));return Number.isFinite(i)&&e.hasAttribute(t)?i:r}function rc(e,t,r){let i=e.getAttribute(t);return null===i?r:"false"!==i&&"0"!==i}function rp(e){let{longitude:t,latitude:r}=e;return[t,r]}function rh(e){return{longitude:e.lng,latitude:e.lat}}function rm(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};e.dispatchEvent(new CustomEvent(t,{detail:r,bubbles:!1}))}function rg(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 rf(e){return rn.get(e)??{}}function rv(e){return rs.get(e)??{}}function ry(e){let t=rl.get(e);if(t)return t;let r=e.closest("map");return r?ro.get(r):void 0}class rb{element;map;namespace;syncingMarkers=!1;overlays;markers=new Map;cleanupTileLoad;surface;resize;sizeFrame=0;generation=0;loading=!1;initializationBlocked=!1;disposed=!1;visible;ready=!1;lastAttributes="";lastOverlays="";lastStyle="";lastLogoPosition="";suspendedViewport;warnings=new Set;constructor(e,t=!0){var r;if(this.element=e,this.visible=t,ro.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==(r=this.resize)||r.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),rg(this.element,Error(`Web Map 暂不支持 ${e}`)))}getMapConfig(){let e=rd(this.element,"extra-params",rf(this.element));return ra[(null==e?void 0:e.useAliMap)===!0?"amap":"baidu"]}initialize(){var e;if(!this.visible||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&&(tx(r)||"[::1]"===r||r.endsWith(".localhost"))){this.initializationBlocked=!0,rg(this.element,Error("当前豆包百度地图账号未授权本地域名,请使用获准域名的 sandbox 调试地图。"));return}this.loading=!0;let i=++this.generation,a=document.createElement("div");a.dataset.doubaoMapSurface="",a.style.cssText="position:absolute;inset:0;width:100%;height:100%;",this.element.prepend(a),this.surface=a,Promise.resolve().then(()=>t5.H3.load(t)).then(e=>{this.isCurrent(i)&&this.surface===a?this.createMap(e,a,i):a.remove()}).catch(e=>{this.isCurrent(i)&&(rg(this.element,e),this.surface=void 0),a.remove()}).finally(()=>{this.generation===i&&(this.loading=!1)})}isCurrent(e){return this.visible&&!this.disposed&&this.generation===e}createMap(e,t,r){let i=this.element,a=rd(i,"center",rf(i)),n=rd(i,"scale-range",rf(i));try{let s=new e.Map(t,{center:a&&rp(a),zoom:ru(i,"scale",16),zooms:n??[3,20],rotation:ru(i,"rotate",0),logoPosition:i.getAttribute("logo-position")||"bottom-left",eventContext:!0,enableNativeInteraction:rc(i,"native-interaction-enabled",!0),showScale:rc(i,"enable-scale-controls",!1),zoomEnable:rc(i,"enable-scale",!0),dragEnable:rc(i,"enable-drag",!0),rotateEnable:rc(i,"enable-rotate",!1)});this.map=s,this.namespace=e,this.overlays=new ri(e,s,e=>rg(i,e),e=>rm(i,"clickpolyline",{id:e}));let o=!1,l=()=>{this.isCurrent(r)&&!o&&(o=!0,rm(i,"maptileload"))};if("baidu"===e.getProvider()){let e=s.getNative();e.addEventListener("firsttileloaded",l),this.cleanupTileLoad=()=>e.removeEventListener("firsttileloaded",l)}let d=()=>{this.isCurrent(r)&&!this.ready&&(this.ready=!0,this.update(!0),this.restoreViewport(),rm(i,"mapload"),"amap"===e.getProvider()&&l())};s.on("complete",d),s.on("click",e=>{this.isCurrent(r)&&e.lnglat&&rm(i,"clickmap",{point:rh(e.lnglat)})}),s.on("error",e=>{this.isCurrent(r)&&rg(i,e)}),s.on("warning",e=>{this.isCurrent(r)&&rg(i,Error(e.reason??e.feature??"Web Map 能力降级"))});let u=(e,t,a)=>{if(!this.isCurrent(r)||!s.isReady())return;let n=t.context,o=(null==n?void 0:n.bounds)??s.getBounds();rm(i,"regionchange",{type:(null==n?void 0:n.phase)??e,...a?{causedBy:a}:{},center:rh((null==n?void 0:n.center)??s.getCenter()),scale:(null==n?void 0:n.zoom)??s.getZoom(),rotate:(null==n?void 0:n.rotation)??s.getRotation(),region:{southwest:rh(o.getSouthWest()),northeast:rh(o.getNorthEast())}})};s.on("movestart",e=>u("begin",e,"drag")),s.on("moveend",e=>u("end",e,"drag")),s.on("zoomstart",e=>u("begin",e,"scale")),s.on("zoomend",e=>u("end",e,"scale")),"baidu"!==e.getProvider()&&(s.on("rotatestart",e=>u("begin",e)),s.on("rotateend",e=>u("end",e))),s.isReady()&&d()}catch(e){var s,o;null==(s=this.cleanupTileLoad)||s.call(this),null==(o=this.overlays)||o.destroy(),this.destroyMap(),this.map=void 0,this.namespace=void 0,this.overlays=void 0,t.remove(),this.surface===t&&(this.surface=void 0),rg(i,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,a=this.map,n=rf(i),s=JSON.stringify({center:rd(i,"center",n),scale:i.getAttribute("scale"),scales:rd(i,"scale-range",n),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=rd(i,"scale-range",n);e&&a.setZooms(e);let t=rd(i,"center",n);t?a.setZoomAndCenter(ru(i,"scale",16),rp(t)):a.setZoom(ru(i,"scale",16)),a.setRotation(ru(i,"rotate",0)),a.setShowScale(rc(i,"enable-scale-controls",!1)),a.setNativeInteractionEnabled(rc(i,"native-interaction-enabled",!0)),a.setStatus({zoomEnable:rc(i,"enable-scale",!0),dragEnable:rc(i,"enable-drag",!0),rotateEnable:rc(i,"enable-rotate",!1)})}catch(e){rg(i,e)}}let o=i.getAttribute("map-style")||"normal-light";if(o!==this.lastStyle){this.lastStyle=o;try{a.setMapStyle((null==(e=this.namespace)?void 0:e.getProvider())==="baidu"?{styleId:o}:o)}catch(e){rg(i,e)}}rc(i,"enable-tilt",!1)&&this.warn("地图倾斜");let l=i.getAttribute("logo-position")||"bottom-left";if(l!==this.lastLogoPosition){this.lastLogoPosition=l;try{a.setLogoPosition(l)}catch(e){rg(i,e)}}let d={polyline:rd(i,"polyline",n),polygons:rd(i,"polygons",n),circles:rd(i,"circles",n),arcs:rd(i,"arcs",n),routeLabel:rd(i,"route-label",n)},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),rl.delete(e));for(let i of r){let r=rv(i);rc(i,"enable-collide-with-poi",!1)&&this.warn("marker POI 碰撞避让");let a=rd(i,"container-position",r),n=rc(i,"enable-drag",!1),s=!a&&"amap"===t.getProvider();n&&!s&&this.warn(a?"固定屏幕位置的 marker 拖动":"百度自定义内容 marker 拖动");let o=rc(i,"enable-click",!0);n&&!o&&this.warn("关闭点击时的 marker 拖动");let l=this.markers.get(i);l||(l=new re(i,t,e,e=>rg(this.element,e),()=>rm(i,"clickmarker")),this.markers.set(i,l),rl.set(i,this)),l.sync({position:rd(i,"position",r),containerPosition:a,anchor:rd(i,"anchor",r)??[.5,1],rotation:ru(i,"rotation",0),alpha:ru(i,"alpha",1),clickable:o,draggable:n&&s&&o,animate:rd(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}restoreViewport(){let e=this.suspendedViewport;if((this.suspendedViewport=void 0,e)&&e.attributes===this.lastAttributes)try{let t=this.getMap();t.setZoomAndCenter(e.scale,rp(e.center),!0),t.setRotation(e.rotate)}catch(e){rg(this.element,e)}}installMethods(){Object.assign(this.element,{setCenter:e=>{let{center:t,animated:r,duration:i}=e;return this.getMap().setCenter(rp(t),!1===r,i)},getCenter:()=>rh(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:rh(e.getSouthWest()),northeast:rh(e.getNorthEast())}},setBound:e=>{let{southwest:t,northeast:r,animated:i,duration:a}=e;return this.getMap().setBounds([t.longitude,t.latitude,r.longitude,r.latitude],!1===i,void 0,a)},fitPoints:e=>{let{points:t,padding:r=[0,0,0,0],animated:i,duration:a}=e;return this.getMap().setFitView(t.map(rp),!1===i,[r[2]??0,r[3]??0,r[0]??0,r[1]??0],void 0,a)},setAnchor:e=>{let{position:t}=e;return this.getMap().setAnchor([t.x,t.y])},latLngToPx:e=>{let{latLng:t}=e,r=this.getMap().lngLatToContainer(rp(t));return{x:r.x,y:r.y}},pxToLatLng:e=>{let{x:t,y:r}=e;return{latLng:rh(this.getMap().containerToLngLat([t,r]))}}})}setVisible(e){this.visible===e||this.disposed||(this.visible=e,e?this.initialize():(this.ready&&this.map&&(this.suspendedViewport={center:rh(this.map.getCenter()),scale:this.map.getZoom(),rotate:this.map.getRotation(),attributes:this.lastAttributes}),this.destroyMapResources()))}destroyMapResources(){var e,t,r;for(let[t,r]of(this.generation+=1,this.loading=!1,this.ready=!1,null==(e=this.cleanupTileLoad)||e.call(this),this.cleanupTileLoad=void 0,this.markers))rl.delete(t),r.destroy();this.markers.clear(),null==(t=this.overlays)||t.destroy(),this.overlays=void 0,this.destroyMap(),this.map=void 0,this.namespace=void 0,null==(r=this.surface)||r.remove(),this.surface=void 0,this.lastAttributes="",this.lastOverlays="",this.lastStyle="",this.lastLogoPosition=""}destroyMap(){var e;let t=this.map;if(t){if((null==(e=this.namespace)?void 0:e.getProvider())==="baidu")return void this.destroyBaiduMap(t);t.destroy()}}destroyBaiduMap(e){var t,r,i;let a=(null==(t=e.getNative().tileMgr)?void 0:t.tileLayers.slice())??[],n=this.surface?[...this.surface.querySelectorAll("canvas")]:[];try{e.destroy()}finally{for(let e of n){let t=e.getContext("webgl2")??e.getContext("webgl");null==t||null==(r=t.getExtension("WEBGL_lose_context"))||r.loseContext()}for(let e of a)clearTimeout(e.processDataTimer??void 0),e.processDataTimer=null,null==(i=e.callbackDataQueue)||i.splice(0)}}dispose(){var e;this.disposed||(this.disposed=!0,null==(e=this.resize)||e.disconnect(),cancelAnimationFrame(this.sizeFrame),this.destroyMapResources(),this.suspendedViewport=void 0,ro.delete(this.element))}}class rw{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 r_(e){var t;null==(t=e.registerPlugin)||t.call(e,rw)}let rS="x-video-engine",rx=globalThis.HTMLElement??class{};if("object"!=typeof customElements||customElements.get(tK)||customElements.define(tK,class e extends t1{static observedAttributes=["src"];#e=null;#t=null;#r=!1;messageOrigin;connectedCallback(){this.#r=!0,this.style.display||(this.style.display="block"),this.#i(),this.#a()}disconnectedCallback(){var e;this.#r=!1,this.#n(),null==(e=this.#e)||e.remove(),this.#e=null,window.removeEventListener("message",this.#s)}attributeChangedCallback(e){"src"===e&&this.#r&&this.#a()}get src(){return this.getAttribute("src")}set src(e){null===e?this.removeAttribute("src"):this.setAttribute("src",e)}reload(){this.#a(!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}#a(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.#i(),r=this.getAttribute("src");if(!r)return;let i=tY(r);this.messageOrigin="window"===i.messageTransport?new URL(i.url,document.baseURI).origin:void 0,(e||t.getAttribute("src")!==i.url)&&(this.#n(),t.toggleAttribute("credentialless",!0===i.credentialless),t.src=i.url)}#n(){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===tZ)return;let t=tQ(e.data);this.#g(t)||this.#f(t0(e.data))};#c(){var e;this.#n();let t=null==(e=this.#e)?void 0:e.contentWindow;if(!t)return;let r=new MessageChannel;r.port1.onmessage=e=>{e.data!==tZ&&this.#g(tQ(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(tQ(e)),Promise.resolve({})),postMessageSync:e=>{let t=tQ(e);return y(t)?x(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(!y(e))return!1;if("doubao.postMessage"===e.name){let t=o(e.params)?e.params.data:void 0;return this.#f(t0(t)),this.#o(S(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=tX.get(t);if(e)return e}let e=t.parentNode;t=e instanceof ShadowRoot?e.host:e}}(this);if(!t)return void this.#o(x(e,`API ${e.name} is not available in this web-view host`));let r=await t(e);this.#o(r??x(e,`API ${e.name} is not implemented in Doubao Web SDK`))}#o(e){var t,r,i;let a=JSON.stringify(e);if(this.messageOrigin){null==(i=this.#e)||null==(r=i.contentWindow)||r.postMessage({type:"__doubao_web_view_message__",payload:a},this.messageOrigin);return}if(this.#t)return void this.#t.postMessage(a);let n=this.#l();null==n||null==(t=n.onWebViewMessage)||t.call(n,a)}#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&&!n){let e=customElements.get("x-markdown");e?(r_(e),n=Promise.resolve()):n=customElements.whenDefined("x-markdown").then(e=>{r_(e)})}if("object"!=typeof customElements||customElements.get(rS)||customElements.define(rS,class e extends rx{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(t6.has(e))continue;t6.add(e);let t=e=>{if(!(t2 in e.prototype)){var t;null==(t=e.registerPlugin)||t.call(e,t4)}},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 rf(this)[t]},set(e){var r;let i=rn.get(this)??{};i[t]=e,rn.set(this,i),null==(r=ro.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=ry(this))?void 0:e.updateMarkers()})}attributeChangedCallback(){var e;null==(e=ry(this))||e.updateMarkers()}refreshMarker(){var e;null==(e=ry(this))||e.updateMarkers()}}for(let t of["position","anchor","animate","container-position"])Object.defineProperty(e.prototype,t,{configurable:!0,get(){return rv(this)[t]},set(e){var r;let i=rs.get(this)??{};i[t]=e,rs.set(this,i),null==(r=ry(this))||r.updateMarkers()}});customElements.define("map-marker",e)}()}function rI(e,t){if(e&&"event"===t.type&&t.name===e2&&o(t.params)){var r;null==(r=e.sendSyncBridgeUpdate)||r.call(e,t),o(t.params.globalProps)&&(e.globalProps={...e.globalProps,...t.params.globalProps})}if(e&&"event"===t.type&&"onThemeChange"===t.name){let r=l(t.params),i=l(e.globalProps);r&&i!==r&&(e.globalProps={...e.globalProps,appTheme:r})}"function"==typeof(null==e?void 0:e.sendGlobalEvent)&&e.sendGlobalEvent("__APPLET_BRIDGE__",[t])}class rk{container;className;options;runtimeContext;bridge=null;caller;cleanupWidgetTapCapture=null;cleanupWebMapHost=null;view=null;visible=!0;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,a;this.clear();let n=Date.now(),s=document.createElement("lynx-view");s.resolveBundle=e=>(function(e,t,r){let i=new URL(e,t);if(i.origin!==new URL(t).origin||!tJ.test(i.pathname))return e;let a={"/assets/framework/doubao-apps-api.template.js":"/assets/framework/doubao-apps-api.template.ebf75b699f.bundle","/assets/framework/doubao-apps-framework.template.js":"/assets/framework/doubao-apps-framework.template.d266ec6564.bundle","/assets/framework/doubao-apps-react.template.js":"/assets/framework/doubao-apps-react.template.5960027cd6.bundle","/assets/framework/doubao-apps-react-dev.template.js":"/assets/framework/doubao-apps-react-dev.template.d2d1100932.bundle"}[i.pathname]??i.pathname,n=r?new URL(a.slice(1),new URL(r,t)):new URL(a,t);return n.search=i.search,n.hash=i.hash,n.href})(e,document.baseURI,this.options.resourceBaseUrl);let 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=tb(e),u=tw(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={...J(),...e.globalProps??{}};this.bridge=e.bridge??(null==(a=this.options.runtime)?void 0:a.bridge)??new tv,this.caller=e.bridgeCaller??this.bridge.register(e=>rI(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,a,l,m;let g,f,v,y,w,_,S,x,I,k;if(this.view!==s)return;"direct"===this.runtimeContext.environment&&p.beginPerformance(h,{...e,containerType:d,globalProps:c});let C="sandbox"===this.runtimeContext.environment?this.runtimeContext.syncBridgeData:p.createSyncBridgeData(h,c,this.options.fileSystemNamespace);t=this.runtimeContext.environment,r=this.options.resourceBaseUrl,g=(null==(i=globalThis.document)?void 0:i.baseURI)??(null==(a=globalThis.location)?void 0:a.href)??"http://localhost/",f=new URL(r??g,g),v=new URL("./__doubao_web_sdk_native_modules/",f).href,y=tS(new URL("applet-bridge-module.js",v)),w=tS(new URL("applet-js-module.js",v)),x={AppletBridgeModule:((S=new URLSearchParams((_=new URL(y)).hash.slice(1))).set("__doubao_sync_bridge",JSON.stringify({...C,fileSystemSnapshot:ep(),storageSnapshot:{}})),_.hash=S.toString(),_.href),AppletJSModule:w},"direct"===t&&(x.LynxConsoleModule=tS(new URL("console-module.js",v)),"APP"===d&&(x.LynxDevToolSetModule=w)),s.nativeModulesMap=x,(0,tG.B)(s),s.napiModulesMap={...s.napiModulesMap,WebSyncBridge:s.nativeModulesMap.AppletBridgeModule};let E=s.onNapiModulesCall;s.onNapiModulesCall=(e,t,r,i,a)=>("WebSyncBridge"===r&&"subscribeSyncUpdates"===e&&(s.sendSyncBridgeUpdate=a,s.sendSyncBridgeUpdate({type:"event",name:e2,params:C,timestamp:Date.now()})),null==E?void 0:E(e,t,r,i,a)),s.globalProps={...c,__DOUBAO_WEB_SDK_SYNC_BRIDGE__:C};let N={containerType:d,element:s,globalProps:c,fileSystemNamespace:C.fileSystemNamespace,environment:this.runtimeContext.environment};s.onNativeModulesCall=(e,t,r)=>p.dispatch(h,e,t,r,N),l=async e=>{let t=await p.dispatch(h,"postMessage",e,"AppletBridgeModule",N);return b(t)?t:void 0},tX.set(s,l),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&&(n=t.create_lynx_start),p.dispatch(h,"postMessage",{type:"call",name:e5,params:{timing:{create_lynx_start:n,...o(t)?t:{}}},callbackId:0},"AppletBridgeModule",N)}),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=(m=this.options.onWidgetInteraction,I=0,k=e=>{e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();var t={sequence:I+=1,type:"tap"};try{Promise.resolve(null==m?void 0:m(t)).catch(()=>void 0)}catch{}},s.addEventListener("click",k,!0),()=>s.removeEventListener("click",k,!0))),s.url=ty(e),this.container.replaceChildren(s),this.cleanupWebMapHost=function(e){let t,r=!(arguments.length>1)||void 0===arguments[1]||arguments[1],i=new Map,a=new Set,n=[],s=0,o=!1,l=r,d=e=>{for(let t of e.querySelectorAll("*"))"map"!==t.localName||ro.has(t)||a.add(new rb(t,l)),t.shadowRoot&&u(t.shadowRoot);for(let e of a)e.element.isConnected||(e.dispose(),a.delete(e))},u=e=>{if(i.has(e)||o)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(d(e),t)){let e=i.target,t=e instanceof Element?e.closest("map"):null;if(t){var r;null==(r=ro.get(t))||r.update()}}});t.observe(e,{childList:!0,subtree:!0,attributes:!0}),i.set(e,t),d(e)},c=()=>{if(o)return;let r=e.shadowRoot??e;if(u(r),e.shadowRoot&&t!==r)for(let e of(t=r,[0,16,100,500,2e3,1e4]))n.push(setTimeout(()=>{o||d(r)},e));else e.shadowRoot||(s=requestAnimationFrame(c))};c();let p=()=>{for(let e of(o=!0,cancelAnimationFrame(s),n))clearTimeout(e);for(let e of i.values())e.disconnect();for(let e of a)e.dispose()};return p.setVisible=e=>{for(let t of(l=e,a))t.setVisible(l)},p}(s,this.visible)};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){var t,r;this.visible=e,null==(t=this.cleanupWebMapHost)||t.setVisible(e),this.caller&&(null==(r=this.bridge)||r.setVisible(this.caller,e))}sendEvent(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t=this.view,rI(t,{type:"event",name:e,params:r,timestamp:Date.now()})}sendBridgeMessage(e){rI(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 rC=`<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 t6=new Set;var t5=r(76935);let t8=new WeakMap;function t9(e,t,r){let i=new Map;for(let a of t){let t=Reflect.get(e,a);i.set(a,Object.getOwnPropertyDescriptor(e,a)),Object.defineProperty(e,a,{configurable:!0,writable:!0,value(){for(var e=arguments.length,i=Array(e),a=0;a<e;a++)i[a]=arguments[a];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 t7{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=t8.get(t);if(!r){let e=new Set;r={portals:e,cleanup:t9(t,["appendChild","insertBefore","removeChild","replaceChild","append","prepend","replaceChildren"],()=>{for(let t of e)t.restore()})},t8.set(t,r)}r.portals.add(this),this.cleanupElement=t9(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=t8.get(this.parent);null==e||e.portals.delete(this),(null==e?void 0:e.portals.size)===0&&(e.cleanup(),t8.delete(this.parent))}}class re{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,a){this.element=e,this.namespace=t,this.map=r,this.onError=i,this.onClick=a,this.portal=new t7(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)},a=JSON.stringify(e.position);this.marker&&a===this.positionKey||(i.position=e.position&&[e.position.longitude,e.position.latitude]),this.portal.mount(this.content);let n=JSON.stringify(e);if(this.marker&&this.optionsKey===n)return void this.syncZIndex();this.optionsKey=n,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=a}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 rt=e=>{let{longitude:t,latitude:r}=e;return[t,r]};function rr(e,t,r,i,a){let n=new Set(t.map(e=>{let{id:t}=e;return t}));for(let[t,r]of e)n.has(t)||(r.destroy(),e.delete(t));for(let n of t)try{let t=r(n),a=e.get(n.id);if(a){let{id:e,...r}=t;a.setOptions(r)}else e.set(n.id,i(t,n))}catch(e){a(e)}}class ri{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 a of e){var i;if(!a.id.startsWith("__doubao_polyline_arrow__:"))continue;let n=null==(i=a.edgeTextureAssets)?void 0:i.find(e=>{let{id:t}=e;return"__doubao_polyline_arrow_texture__"===t});if(n)try{let i=decodeURIComponent(a.id.slice(26));e.some(e=>e.id===i)&&(t.set(i,{iconPath:n.url}),r.add(a))}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,a=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 纹理"),!a&&(null==(t=e.routeLabel)?void 0:t.length)&&this.warn("当前图商的 routeLabel"),r.some(e=>e.collideDetection)&&this.warn("polyline POI 碰撞避让"),rr(this.polylines,r,e=>{var t;return{id:e.id,path:e.points.map(rt),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),rr(this.polygons,e.polygons??[],e=>({id:e.id,path:e.points.map(rt),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),rr(this.circles,e.circles??[],e=>({id:e.id,center:rt(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),rr(this.arcs,e.arcs??[],e=>({id:e.id,path:[rt(e.start),rt(e.mid??e.middle),rt(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),rr(this.routeLabels,a?e.routeLabel??[]:[],e=>({id:e.id,path:e.points.map(rt),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 ra={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"}}}},rn=new WeakMap,rs=new WeakMap,ro=new WeakMap,rl=new WeakMap;function rd(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 ru(e,t,r){let i=Number(e.getAttribute(t));return Number.isFinite(i)&&e.hasAttribute(t)?i:r}function rc(e,t,r){let i=e.getAttribute(t);return null===i?r:"false"!==i&&"0"!==i}function rp(e){let{longitude:t,latitude:r}=e;return[t,r]}function rh(e){return{longitude:e.lng,latitude:e.lat}}function rm(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};e.dispatchEvent(new CustomEvent(t,{detail:r,bubbles:!1}))}function rg(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 rf(e){return rn.get(e)??{}}function rv(e){return rs.get(e)??{}}function ry(e){let t=rl.get(e);if(t)return t;let r=e.closest("map");return r?ro.get(r):void 0}class rb{element;map;namespace;syncingMarkers=!1;overlays;markers=new Map;cleanupTileLoad;surface;resize;sizeFrame=0;generation=0;loading=!1;initializationBlocked=!1;disposed=!1;visible;ready=!1;lastAttributes="";lastOverlays="";lastStyle="";lastLogoPosition="";suspendedViewport;warnings=new Set;constructor(e,t=!0){var r;if(this.element=e,this.visible=t,ro.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==(r=this.resize)||r.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),rg(this.element,Error(`Web Map 暂不支持 ${e}`)))}getMapConfig(){let e=rd(this.element,"extra-params",rf(this.element));return ra[(null==e?void 0:e.useAliMap)===!0?"amap":"baidu"]}initialize(){var e;if(!this.visible||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&&(tx(r)||"[::1]"===r||r.endsWith(".localhost"))){this.initializationBlocked=!0,rg(this.element,Error("当前豆包百度地图账号未授权本地域名,请使用获准域名的 sandbox 调试地图。"));return}this.loading=!0;let i=++this.generation,a=document.createElement("div");a.dataset.doubaoMapSurface="",a.style.cssText="position:absolute;inset:0;width:100%;height:100%;",this.element.prepend(a),this.surface=a,Promise.resolve().then(()=>t5.H3.load(t)).then(e=>{this.isCurrent(i)&&this.surface===a?this.createMap(e,a,i):a.remove()}).catch(e=>{this.isCurrent(i)&&(rg(this.element,e),this.surface=void 0),a.remove()}).finally(()=>{this.generation===i&&(this.loading=!1)})}isCurrent(e){return this.visible&&!this.disposed&&this.generation===e}createMap(e,t,r){let i=this.element,a=rd(i,"center",rf(i)),n=rd(i,"scale-range",rf(i));try{let s=new e.Map(t,{center:a&&rp(a),zoom:ru(i,"scale",16),zooms:n??[3,20],rotation:ru(i,"rotate",0),logoPosition:i.getAttribute("logo-position")||"bottom-left",eventContext:!0,enableNativeInteraction:rc(i,"native-interaction-enabled",!0),showScale:rc(i,"enable-scale-controls",!1),zoomEnable:rc(i,"enable-scale",!0),dragEnable:rc(i,"enable-drag",!0),rotateEnable:rc(i,"enable-rotate",!1)});this.map=s,this.namespace=e,this.overlays=new ri(e,s,e=>rg(i,e),e=>rm(i,"clickpolyline",{id:e}));let o=!1,l=()=>{this.isCurrent(r)&&!o&&(o=!0,rm(i,"maptileload"))};if("baidu"===e.getProvider()){let e=s.getNative();e.addEventListener("firsttileloaded",l),this.cleanupTileLoad=()=>e.removeEventListener("firsttileloaded",l)}let d=()=>{this.isCurrent(r)&&!this.ready&&(this.ready=!0,this.update(!0),this.restoreViewport(),rm(i,"mapload"),"amap"===e.getProvider()&&l())};s.on("complete",d),s.on("click",e=>{this.isCurrent(r)&&e.lnglat&&rm(i,"clickmap",{point:rh(e.lnglat)})}),s.on("error",e=>{this.isCurrent(r)&&rg(i,e)}),s.on("warning",e=>{this.isCurrent(r)&&rg(i,Error(e.reason??e.feature??"Web Map 能力降级"))});let u=(e,t,a)=>{if(!this.isCurrent(r)||!s.isReady())return;let n=t.context,o=(null==n?void 0:n.bounds)??s.getBounds();rm(i,"regionchange",{type:(null==n?void 0:n.phase)??e,...a?{causedBy:a}:{},center:rh((null==n?void 0:n.center)??s.getCenter()),scale:(null==n?void 0:n.zoom)??s.getZoom(),rotate:(null==n?void 0:n.rotation)??s.getRotation(),region:{southwest:rh(o.getSouthWest()),northeast:rh(o.getNorthEast())}})};s.on("movestart",e=>u("begin",e,"drag")),s.on("moveend",e=>u("end",e,"drag")),s.on("zoomstart",e=>u("begin",e,"scale")),s.on("zoomend",e=>u("end",e,"scale")),"baidu"!==e.getProvider()&&(s.on("rotatestart",e=>u("begin",e)),s.on("rotateend",e=>u("end",e))),s.isReady()&&d()}catch(e){var s,o;null==(s=this.cleanupTileLoad)||s.call(this),null==(o=this.overlays)||o.destroy(),this.destroyMap(),this.map=void 0,this.namespace=void 0,this.overlays=void 0,t.remove(),this.surface===t&&(this.surface=void 0),rg(i,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,a=this.map,n=rf(i),s=JSON.stringify({center:rd(i,"center",n),scale:i.getAttribute("scale"),scales:rd(i,"scale-range",n),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=rd(i,"scale-range",n);e&&a.setZooms(e);let t=rd(i,"center",n);t?a.setZoomAndCenter(ru(i,"scale",16),rp(t)):a.setZoom(ru(i,"scale",16)),a.setRotation(ru(i,"rotate",0)),a.setShowScale(rc(i,"enable-scale-controls",!1)),a.setNativeInteractionEnabled(rc(i,"native-interaction-enabled",!0)),a.setStatus({zoomEnable:rc(i,"enable-scale",!0),dragEnable:rc(i,"enable-drag",!0),rotateEnable:rc(i,"enable-rotate",!1)})}catch(e){rg(i,e)}}let o=i.getAttribute("map-style")||"normal-light";if(o!==this.lastStyle){this.lastStyle=o;try{a.setMapStyle((null==(e=this.namespace)?void 0:e.getProvider())==="baidu"?{styleId:o}:o)}catch(e){rg(i,e)}}rc(i,"enable-tilt",!1)&&this.warn("地图倾斜");let l=i.getAttribute("logo-position")||"bottom-left";if(l!==this.lastLogoPosition){this.lastLogoPosition=l;try{a.setLogoPosition(l)}catch(e){rg(i,e)}}let d={polyline:rd(i,"polyline",n),polygons:rd(i,"polygons",n),circles:rd(i,"circles",n),arcs:rd(i,"arcs",n),routeLabel:rd(i,"route-label",n)},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),rl.delete(e));for(let i of r){let r=rv(i);rc(i,"enable-collide-with-poi",!1)&&this.warn("marker POI 碰撞避让");let a=rd(i,"container-position",r),n=rc(i,"enable-drag",!1),s=!a&&"amap"===t.getProvider();n&&!s&&this.warn(a?"固定屏幕位置的 marker 拖动":"百度自定义内容 marker 拖动");let o=rc(i,"enable-click",!0);n&&!o&&this.warn("关闭点击时的 marker 拖动");let l=this.markers.get(i);l||(l=new re(i,t,e,e=>rg(this.element,e),()=>rm(i,"clickmarker")),this.markers.set(i,l),rl.set(i,this)),l.sync({position:rd(i,"position",r),containerPosition:a,anchor:rd(i,"anchor",r)??[.5,1],rotation:ru(i,"rotation",0),alpha:ru(i,"alpha",1),clickable:o,draggable:n&&s&&o,animate:rd(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}restoreViewport(){let e=this.suspendedViewport;if((this.suspendedViewport=void 0,e)&&e.attributes===this.lastAttributes)try{let t=this.getMap();t.setZoomAndCenter(e.scale,rp(e.center),!0),t.setRotation(e.rotate)}catch(e){rg(this.element,e)}}installMethods(){Object.assign(this.element,{setCenter:e=>{let{center:t,animated:r,duration:i}=e;return this.getMap().setCenter(rp(t),!1===r,i)},getCenter:()=>rh(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:rh(e.getSouthWest()),northeast:rh(e.getNorthEast())}},setBound:e=>{let{southwest:t,northeast:r,animated:i,duration:a}=e;return this.getMap().setBounds([t.longitude,t.latitude,r.longitude,r.latitude],!1===i,void 0,a)},fitPoints:e=>{let{points:t,padding:r=[0,0,0,0],animated:i,duration:a}=e;return this.getMap().setFitView(t.map(rp),!1===i,[r[2]??0,r[3]??0,r[0]??0,r[1]??0],void 0,a)},setAnchor:e=>{let{position:t}=e;return this.getMap().setAnchor([t.x,t.y])},latLngToPx:e=>{let{latLng:t}=e,r=this.getMap().lngLatToContainer(rp(t));return{x:r.x,y:r.y}},pxToLatLng:e=>{let{x:t,y:r}=e;return{latLng:rh(this.getMap().containerToLngLat([t,r]))}}})}setVisible(e){this.visible===e||this.disposed||(this.visible=e,e?this.initialize():(this.ready&&this.map&&(this.suspendedViewport={center:rh(this.map.getCenter()),scale:this.map.getZoom(),rotate:this.map.getRotation(),attributes:this.lastAttributes}),this.destroyMapResources()))}destroyMapResources(){var e,t,r;for(let[t,r]of(this.generation+=1,this.loading=!1,this.ready=!1,null==(e=this.cleanupTileLoad)||e.call(this),this.cleanupTileLoad=void 0,this.markers))rl.delete(t),r.destroy();this.markers.clear(),null==(t=this.overlays)||t.destroy(),this.overlays=void 0,this.destroyMap(),this.map=void 0,this.namespace=void 0,null==(r=this.surface)||r.remove(),this.surface=void 0,this.lastAttributes="",this.lastOverlays="",this.lastStyle="",this.lastLogoPosition=""}destroyMap(){var e;let t=this.map;if(t){if((null==(e=this.namespace)?void 0:e.getProvider())==="baidu")return void this.destroyBaiduMap(t);t.destroy()}}destroyBaiduMap(e){var t,r,i;let a=(null==(t=e.getNative().tileMgr)?void 0:t.tileLayers.slice())??[],n=this.surface?[...this.surface.querySelectorAll("canvas")]:[];try{e.destroy()}finally{for(let e of n){let t=e.getContext("webgl2")??e.getContext("webgl");null==t||null==(r=t.getExtension("WEBGL_lose_context"))||r.loseContext()}for(let e of a)clearTimeout(e.processDataTimer??void 0),e.processDataTimer=null,null==(i=e.callbackDataQueue)||i.splice(0)}}dispose(){var e;this.disposed||(this.disposed=!0,null==(e=this.resize)||e.disconnect(),cancelAnimationFrame(this.sizeFrame),this.destroyMapResources(),this.suspendedViewport=void 0,ro.delete(this.element))}}class rw{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 r_(e){var t;null==(t=e.registerPlugin)||t.call(e,rw)}let rS="x-video-engine",rx=globalThis.HTMLElement??class{};if("object"!=typeof customElements||customElements.get(tK)||customElements.define(tK,class e extends t1{static observedAttributes=["src"];#e=null;#t=null;#r=!1;messageOrigin;connectedCallback(){this.#r=!0,this.style.display||(this.style.display="block"),this.#i(),this.#a()}disconnectedCallback(){var e;this.#r=!1,this.#n(),null==(e=this.#e)||e.remove(),this.#e=null,window.removeEventListener("message",this.#s)}attributeChangedCallback(e){"src"===e&&this.#r&&this.#a()}get src(){return this.getAttribute("src")}set src(e){null===e?this.removeAttribute("src"):this.setAttribute("src",e)}reload(){this.#a(!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}#a(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.#i(),r=this.getAttribute("src");if(!r)return;let i=tY(r);this.messageOrigin="window"===i.messageTransport?new URL(i.url,document.baseURI).origin:void 0,(e||t.getAttribute("src")!==i.url)&&(this.#n(),t.toggleAttribute("credentialless",!0===i.credentialless),t.src=i.url)}#n(){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===tZ)return;let t=tQ(e.data);this.#g(t)||this.#f(t0(e.data))};#c(){var e;this.#n();let t=null==(e=this.#e)?void 0:e.contentWindow;if(!t)return;let r=new MessageChannel;r.port1.onmessage=e=>{e.data!==tZ&&this.#g(tQ(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(tQ(e)),Promise.resolve({})),postMessageSync:e=>{let t=tQ(e);return y(t)?x(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(!y(e))return!1;if("doubao.postMessage"===e.name){let t=o(e.params)?e.params.data:void 0;return this.#f(t0(t)),this.#o(S(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=tX.get(t);if(e)return e}let e=t.parentNode;t=e instanceof ShadowRoot?e.host:e}}(this);if(!t)return void this.#o(x(e,`API ${e.name} is not available in this web-view host`));let r=await t(e);this.#o(r??x(e,`API ${e.name} is not implemented in Doubao Web SDK`))}#o(e){var t,r,i;let a=JSON.stringify(e);if(this.messageOrigin){null==(i=this.#e)||null==(r=i.contentWindow)||r.postMessage({type:"__doubao_web_view_message__",payload:a},this.messageOrigin);return}if(this.#t)return void this.#t.postMessage(a);let n=this.#l();null==n||null==(t=n.onWebViewMessage)||t.call(n,a)}#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&&!n){let e=customElements.get("x-markdown");e?(r_(e),n=Promise.resolve()):n=customElements.whenDefined("x-markdown").then(e=>{r_(e)})}if("object"!=typeof customElements||customElements.get(rS)||customElements.define(rS,class e extends rx{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(t6.has(e))continue;t6.add(e);let t=e=>{if(!(t2 in e.prototype)){var t;null==(t=e.registerPlugin)||t.call(e,t4)}},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 rf(this)[t]},set(e){var r;let i=rn.get(this)??{};i[t]=e,rn.set(this,i),null==(r=ro.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=ry(this))?void 0:e.updateMarkers()})}attributeChangedCallback(){var e;null==(e=ry(this))||e.updateMarkers()}refreshMarker(){var e;null==(e=ry(this))||e.updateMarkers()}}for(let t of["position","anchor","animate","container-position"])Object.defineProperty(e.prototype,t,{configurable:!0,get(){return rv(this)[t]},set(e){var r;let i=rs.get(this)??{};i[t]=e,rs.set(this,i),null==(r=ry(this))||r.updateMarkers()}});customElements.define("map-marker",e)}()}function rI(e,t){if(e&&"event"===t.type&&t.name===e2&&o(t.params)){var r;null==(r=e.sendSyncBridgeUpdate)||r.call(e,t),o(t.params.globalProps)&&(e.globalProps={...e.globalProps,...t.params.globalProps})}if(e&&"event"===t.type&&"onThemeChange"===t.name){let r=l(t.params),i=l(e.globalProps);r&&i!==r&&(e.globalProps={...e.globalProps,appTheme:r})}"function"==typeof(null==e?void 0:e.sendGlobalEvent)&&e.sendGlobalEvent("__APPLET_BRIDGE__",[t])}class rk{container;className;options;runtimeContext;bridge=null;caller;cleanupWidgetTapCapture=null;cleanupWebMapHost=null;view=null;visible=!0;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,a;this.clear();let n=Date.now(),s=document.createElement("lynx-view");s.resolveBundle=e=>(function(e,t,r){let i=new URL(e,t);if(i.origin!==new URL(t).origin||!tJ.test(i.pathname))return e;let a={"/assets/framework/doubao-apps-api.template.js":"/assets/framework/doubao-apps-api.template.a6a4208461.bundle","/assets/framework/doubao-apps-framework.template.js":"/assets/framework/doubao-apps-framework.template.b424cdeeba.bundle","/assets/framework/doubao-apps-react.template.js":"/assets/framework/doubao-apps-react.template.5960027cd6.bundle","/assets/framework/doubao-apps-react-dev.template.js":"/assets/framework/doubao-apps-react-dev.template.d2d1100932.bundle"}[i.pathname]??i.pathname,n=r?new URL(a.slice(1),new URL(r,t)):new URL(a,t);return n.search=i.search,n.hash=i.hash,n.href})(e,document.baseURI,this.options.resourceBaseUrl);let 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=tb(e),u=tw(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={...J(),...e.globalProps??{}};this.bridge=e.bridge??(null==(a=this.options.runtime)?void 0:a.bridge)??new tv,this.caller=e.bridgeCaller??this.bridge.register(e=>rI(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,a,l,m;let g,f,v,y,w,_,S,x,I,k;if(this.view!==s)return;"direct"===this.runtimeContext.environment&&p.beginPerformance(h,{...e,containerType:d,globalProps:c});let C="sandbox"===this.runtimeContext.environment?this.runtimeContext.syncBridgeData:p.createSyncBridgeData(h,c,this.options.fileSystemNamespace);t=this.runtimeContext.environment,r=this.options.resourceBaseUrl,g=(null==(i=globalThis.document)?void 0:i.baseURI)??(null==(a=globalThis.location)?void 0:a.href)??"http://localhost/",f=new URL(r??g,g),v=new URL("./__doubao_web_sdk_native_modules/",f).href,y=tS(new URL("applet-bridge-module.js",v)),w=tS(new URL("applet-js-module.js",v)),x={AppletBridgeModule:((S=new URLSearchParams((_=new URL(y)).hash.slice(1))).set("__doubao_sync_bridge",JSON.stringify({...C,fileSystemSnapshot:ep(),storageSnapshot:{}})),_.hash=S.toString(),_.href),AppletJSModule:w},"direct"===t&&(x.LynxConsoleModule=tS(new URL("console-module.js",v)),"APP"===d&&(x.LynxDevToolSetModule=w)),s.nativeModulesMap=x,(0,tG.B)(s),s.napiModulesMap={...s.napiModulesMap,WebSyncBridge:s.nativeModulesMap.AppletBridgeModule};let E=s.onNapiModulesCall;s.onNapiModulesCall=(e,t,r,i,a)=>("WebSyncBridge"===r&&"subscribeSyncUpdates"===e&&(s.sendSyncBridgeUpdate=a,s.sendSyncBridgeUpdate({type:"event",name:e2,params:C,timestamp:Date.now()})),null==E?void 0:E(e,t,r,i,a)),s.globalProps={...c,__DOUBAO_WEB_SDK_SYNC_BRIDGE__:C};let N={containerType:d,element:s,globalProps:c,fileSystemNamespace:C.fileSystemNamespace,environment:this.runtimeContext.environment};s.onNativeModulesCall=(e,t,r)=>p.dispatch(h,e,t,r,N),l=async e=>{let t=await p.dispatch(h,"postMessage",e,"AppletBridgeModule",N);return b(t)?t:void 0},tX.set(s,l),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&&(n=t.create_lynx_start),p.dispatch(h,"postMessage",{type:"call",name:e5,params:{timing:{create_lynx_start:n,...o(t)?t:{}}},callbackId:0},"AppletBridgeModule",N)}),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=(m=this.options.onWidgetInteraction,I=0,k=e=>{e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();var t={sequence:I+=1,type:"tap"};try{Promise.resolve(null==m?void 0:m(t)).catch(()=>void 0)}catch{}},s.addEventListener("click",k,!0),()=>s.removeEventListener("click",k,!0))),s.url=ty(e),this.container.replaceChildren(s),this.cleanupWebMapHost=function(e){let t,r=!(arguments.length>1)||void 0===arguments[1]||arguments[1],i=new Map,a=new Set,n=[],s=0,o=!1,l=r,d=e=>{for(let t of e.querySelectorAll("*"))"map"!==t.localName||ro.has(t)||a.add(new rb(t,l)),t.shadowRoot&&u(t.shadowRoot);for(let e of a)e.element.isConnected||(e.dispose(),a.delete(e))},u=e=>{if(i.has(e)||o)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(d(e),t)){let e=i.target,t=e instanceof Element?e.closest("map"):null;if(t){var r;null==(r=ro.get(t))||r.update()}}});t.observe(e,{childList:!0,subtree:!0,attributes:!0}),i.set(e,t),d(e)},c=()=>{if(o)return;let r=e.shadowRoot??e;if(u(r),e.shadowRoot&&t!==r)for(let e of(t=r,[0,16,100,500,2e3,1e4]))n.push(setTimeout(()=>{o||d(r)},e));else e.shadowRoot||(s=requestAnimationFrame(c))};c();let p=()=>{for(let e of(o=!0,cancelAnimationFrame(s),n))clearTimeout(e);for(let e of i.values())e.disconnect();for(let e of a)e.dispose()};return p.setVisible=e=>{for(let t of(l=e,a))t.setVisible(l)},p}(s,this.visible)};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){var t,r;this.visible=e,null==(t=this.cleanupWebMapHost)||t.setVisible(e),this.caller&&(null==(r=this.bridge)||r.setVisible(this.caller,e))}sendEvent(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t=this.view,rI(t,{type:"event",name:e,params:r,timestamp:Date.now()})}sendBridgeMessage(e){rI(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 rC=`<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>`,rE=`<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"/>
|