@doubao-dev/kit 0.8.0-rc.10 → 0.8.0-rc.11
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.js +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.e839caafce.js → index.072c936cc9.js} +1 -1
- 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,n,a,s,o,l,d,u,c,p={38114(e,t,r){let i,n,a;r(52205),r(40768),r(76235),r(15254),r(42949),r(18723),r(37891);var s=r(63159);function o(e){return"object"==typeof e&&null!==e}function l(e){var t;return"string"==typeof(null==(t=e.web)?void 0:t.entry)}function d(e,t){let r=new Map;for(let i of e){let e=t(i);e&&!r.has(e)&&r.set(e,i)}return r}function u(e){return"string"==typeof e?e||void 0:(null==e?void 0:e["3x"])||(null==e?void 0:e["2x"])||(null==e?void 0:e["1x"])}r(84086),r(21301),r(49678),r(32037),r(14104),r(66249),r(99811),r(40009),r(13035),r(13412),r(17973),r(64955),r(91016),r(23306),r(76619),r(57857),r(9975),r(93885),r(812),r(74180),r(994),r(4267),r(74678),r(55910),r(76691),r(72919);class c{raw;appEntry;pageEntries;pageIdEntryMap;pagePathEntryMap;widgetEntries;widgetEntryMap;constructor(e){var t;let r;this.raw=e,this.appEntry="string"==typeof(r=(null==(t=e.applet.web)?void 0:t.appRuntimeEntry)??e.applet.appRuntimeEntry)&&r?{entry:r}:null,this.pageEntries=e.applet.pages.filter(l),this.pageIdEntryMap=d(this.pageEntries,e=>e.id),this.pagePathEntryMap=d(this.pageEntries,e=>{var t;return(null==(t=e.path)?void 0:t.startsWith("/"))?e.path:void 0}),this.widgetEntries=e.widgets,this.widgetEntryMap=d(this.widgetEntries,e=>e.widgetId)}get appId(){return"string"==typeof this.raw.appId?this.raw.appId:void 0}get name(){return this.raw.applet.name}get iconSrc(){return u(this.raw.applet.icons)}get versionName(){return this.raw.versionName||this.raw.versionTag||this.raw.versionCode||void 0}get pages(){return this.getPageEntries()}get widgets(){return this.getWidgetEntries()}get appRuntimeEntry(){return this.appEntry}getPageEntries(){return[...this.pageEntries]}getWidgetEntries(){return[...this.widgetEntries]}getOptionalWidgetEntry(e){return e?this.widgetEntryMap.get(e):this.widgetEntries[0]}getPageEntry(e){let t=e?e.startsWith("/")?this.pagePathEntryMap.get(e):this.pageIdEntryMap.get(e):this.pageEntries[0];if(!t)throw Error(e?`Unknown pages entry: ${e}`:"No pages entries in Web manifest");return t}getWidgetEntry(e){let t=this.getOptionalWidgetEntry(e);if(!t)throw Error(e?`Unknown widgets entry: ${e}`:"No widgets entries in Web manifest");return t}}async function p(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.fetcher??fetch,i=await r(e,{cache:"no-store",headers:{Accept:"application/json"}});if(!i.ok)throw Error(`Failed to load Web manifest: ${i.status} ${i.statusText}`);let n=await i.json();if(!o(n))throw Error("Invalid Web manifest: expected a JSON object");return new c(n)}function h(e,t,r){var i,n;let a="item"in t?t.item:t,s="id"in a||"widgetId"in a?"string"==typeof(null==(i=a.web)?void 0:i.entry)?a.web.entry:void 0:a.entry;if(!s)return;let o=new URL(e,r??(null==(n=globalThis.location)?void 0:n.href)??"http://localhost/");return o.pathname=o.pathname.replace(/\/base\/manifest\.json$/,"/"),new URL(s,o).toString()}function m(){let e=Error("Widget host call was cancelled");return e.name="AbortError",e}function g(e){if(e.aborted)throw m()}function f(e,t){return g(t),new Promise((r,i)=>{let n=!1,a=e=>{n||(n=!0,t.removeEventListener("abort",s),e())},s=()=>a(()=>i(m()));t.addEventListener("abort",s,{once:!0}),Promise.resolve().then(e).then(e=>a(()=>r(e)),e=>a(()=>i(e)))})}function v(e){return(null==e?void 0:e.type)==="call"}function y(e){return(null==e?void 0:e.type)==="callback"}function b(e){return(null==e?void 0:e.type)==="event"}class w extends Error{errNo;errMsg;constructor(e,t,r=e){super(e),this.errNo=t,this.errMsg=r,Object.setPrototypeOf(this,new.target.prototype),this.name="BridgeAPIError"}}function _(e,t){return{type:"callback",callbackId:e.callbackId,params:{code:1,data:t}}}function S(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:t;return{type:"callback",callbackId:e.callbackId,params:{code:0,msg:t,errNo:r,errMsg:i}}}function x(e){return e instanceof Error?e.message:String(e)}function I(e,t){return t instanceof w?S(e,t.message,t.errNo,t.errMsg):S(e,x(t))}r(67548),r(70954),r(98803),r(79162),r(15385),r(39342),r(69152),r(61955),r(82689),r(84847),r(16285),r(20602),r(33307),r(94341),r(7270),r(44997),r(50364),r(79780),r(80372),r(72498),r(37928),r(25597),r(92321);class k{registry=new Map;eventSources=new Map;eventSourceCleanups=new Map;eventSourceRetainCounts=new Map;eventControllers=new Set;handlers={};constructor(e){e&&this.registerMany(e)}register(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!r.override&&this.registry.has(e))throw Error(`Bridge API handler ${e} is already registered`);let i=this.registry.get(e),n="function"==typeof t?{handler:t,canIUse:!0}:{...t,canIUse:t.canIUse??!0};return this.registry.set(e,n),this.handlers[e]=n.handler,()=>{if(this.registry.get(e)===n){if(i){this.registry.set(e,i),this.handlers[e]=i.handler;return}this.registry.delete(e),delete this.handlers[e]}}}registerMany(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=[];try{for(let[i,n]of Object.entries(e))r.push(this.register(i,n,t))}catch(e){for(let e of r.reverse())e();throw e}return()=>{for(let e of r.reverse())e()}}get(e){var t;return null==(t=this.registry.get(e))?void 0:t.handler}getSyncResults(e){let t={};for(let[r,i]of this.registry)i.syncResult&&this.canIUse(r,e)&&(t[r]="function"==typeof i.syncResult?i.syncResult({...e,apiRegistry:this}):i.syncResult);return t}registerEventSource(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!r.override&&this.eventSources.has(e))throw Error(`Bridge event source ${e} is already registered`);let i=this.eventSources.get(e),n="function"==typeof t?{source:t}:t;return this.stopEventSource(e),this.eventSources.set(e,n),(this.eventSourceRetainCounts.get(e)??0)>0&&this.startEventSource(e,n),()=>{if(this.eventSources.get(e)===n){if(this.stopEventSource(e),i){this.eventSources.set(e,i),(this.eventSourceRetainCounts.get(e)??0)>0&&this.startEventSource(e,i);return}this.eventSources.delete(e)}}}registerEventSources(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=[];try{for(let[i,n]of Object.entries(e))r.push(this.registerEventSource(i,n,t))}catch(e){for(let e of r.reverse())e();throw e}return()=>{for(let e of r.reverse())e()}}canIUse(e,t){let r=this.registry.get(e);if(r)return"function"==typeof r.canIUse?r.canIUse({...t,apiRegistry:this}):r.canIUse;let i=this.eventSources.get(e);return!!i&&("function"==typeof i.canIUse?i.canIUse({...t,apiRegistry:this}):i.canIUse??!0)}dispatch(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;if(!v(e))return;let i={...t,apiRegistry:this};if(this.canIUse(e.name,i))return function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!v(e))return;let i=t[e.name];if(!i)return S(e,`API ${e.name} is not implemented in Doubao Web SDK`);try{let t=i(e,r);if(t instanceof Promise)return t.catch(t=>I(e,t));return t??S(e,`API ${e.name} is not implemented in Doubao Web SDK`)}catch(t){return I(e,t)}}(e,this.handlers,i);let n=this.registry.has(e.name)?103:-1;if(!r)return S(e,`API ${e.name} is not implemented in Doubao Web SDK`,n);try{let t=r(e.name);return t instanceof Promise?t.then(()=>S(e,`API ${e.name} is not implemented in Doubao Web SDK`,n)).catch(t=>I(e,t)):S(e,`API ${e.name} is not implemented in Doubao Web SDK`,n)}catch(t){return I(e,t)}}getSupportedNames(e){return[...new Set([...this.registry.keys(),...this.eventSources.keys()])].filter(t=>this.canIUse(t,e))}emitEvent(e,t){let r=!1;for(let i of this.eventControllers)r=i.emit(e,t)||r;return r}createEventController(e){return new C(this,e)}fork(){let e=new k(this.getRegistrations());return e.registerEventSources(this.getEventSources()),e}getRegistrations(){return Object.fromEntries(this.registry)}getEventSources(){return Object.fromEntries(this.eventSources)}attachEventController(e){return this.eventControllers.add(e),()=>{this.eventControllers.delete(e)}}retainEventSource(e){let t=this.eventSourceRetainCounts.get(e)??0;if(this.eventSourceRetainCounts.set(e,t+1),t>0)return;let r=this.eventSources.get(e);r&&this.startEventSource(e,r)}releaseEventSource(e){let t=this.eventSourceRetainCounts.get(e)??0;if(t<=1){this.eventSourceRetainCounts.delete(e),this.stopEventSource(e);return}this.eventSourceRetainCounts.set(e,t-1)}notifyEventSubscription(e,t,r){var i,n;null==(n=this.eventSources.get(e))||null==(i=n.onSubscribe)||i.call(n,t,r)}startEventSource(e,t){this.stopEventSource(e);let r=t.source(t=>{this.emitEvent(e,t)});"function"==typeof r&&this.eventSourceCleanups.set(e,r)}stopEventSource(e){var t;null==(t=this.eventSourceCleanups.get(e))||t(),this.eventSourceCleanups.delete(e)}}class C{apiRegistry;dispatch;cleanupRegistry;subscribedEventNames=new Set;cleanups=new Set;destroyed=!1;visible=!0;visibilityListeners=new Set;constructor(e,t){this.apiRegistry=e,this.dispatch=t,this.cleanupRegistry=this.apiRegistry.attachEventController(this)}subscribe(e,t){this.destroyed||this.subscribedEventNames.has(e)||(this.subscribedEventNames.add(e),this.apiRegistry.retainEventSource(e),this.apiRegistry.notifyEventSubscription(e,this,t))}unsubscribe(e){this.subscribedEventNames.delete(e)&&this.apiRegistry.releaseEventSource(e)}isSubscribed(e){return this.subscribedEventNames.has(e)}emit(e,t){return!!this.isSubscribed(e)&&this.emitPrivate(e,t)}emitPrivate(e,t){return!this.destroyed&&(this.dispatch(e,t),!0)}setVisible(e){for(let t of(this.visible=e,this.visibilityListeners))t(e)}onVisibilityChange(e){return e(this.visible),this.visibilityListeners.add(e),()=>this.visibilityListeners.delete(e)}onDestroy(e){return this.destroyed?(e(),()=>{}):(this.cleanups.add(e),()=>this.cleanups.delete(e))}destroy(){if(!this.destroyed){for(let e of(this.destroyed=!0,this.cleanups))try{e()}catch(e){console.error("Failed to clean up bridge API resources",e)}for(let e of(this.cleanups.clear(),this.visibilityListeners.clear(),this.subscribedEventNames))this.apiRegistry.releaseEventSource(e);this.subscribedEventNames.clear(),this.cleanupRegistry()}}}let E=new k;function N(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:i;return null==e?void 0:e.getPackageInfo()}async function T(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i;return await (null==t?void 0:t.navigateTo(e)),!!t}async function A(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i;return await (null==t?void 0:t.redirectTo(e)),!!t}async function M(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i;return await (null==t?void 0:t.reLaunch(e)),!!t}function j(){return"0.8.0-rc.10"}function R(e){var t;let{screenWidth:r,statusBarHeight:i}=e??(null==(t=globalThis.lynx)?void 0:t.__globalProps),n=Math.round(i)+4,a=Math.round(r)-12;return{bottom:n+36,height:36,left:a-84,right:a,top:n,width:84}}function P(){return(navigator.language||"zh-CN").replace(/-/g,"_")}function L(){var e,t,r;return(null==(t=(r=window).matchMedia)||null==(e=t.call(r,"(prefers-color-scheme: dark)"))?void 0:e.matches)?"dark":"light"}function D(){return"string"==typeof DoubaoAppsSDKVersion?DoubaoAppsSDKVersion:j()??""}function O(){return navigator.userAgentData}function U(){var e;let t=null==(e=O())?void 0:e.brands,r=null==t?void 0:t.find(e=>{let{brand:t}=e;return!/not.a.brand/i.test(t)});if(null==r?void 0:r.brand)return r.brand;let i=navigator.userAgent??"";return/edg\//i.test(i)?"Microsoft Edge":/chrome|crios/i.test(i)?"Chrome":/firefox|fxios/i.test(i)?"Firefox":/safari/i.test(i)?"Safari":"Browser"}function $(){var e,t;let r=null==(e=O())?void 0:e.brands,i=null==r?void 0:r.find(e=>{let{brand:t}=e;return!/not.a.brand/i.test(t)});if(null==i?void 0:i.version)return i.version;let n=navigator.userAgent??"";return(null==(t=/(?:edg|chrome|crios|firefox|fxios|version)\/([\d.]+)/i.exec(n))?void 0:t[1])??void 0}function q(){var e;let t=navigator.userAgent??"",r=navigator.platform??"",i=(null==(e=O())?void 0:e.platform)??"",n=`${i} ${r} ${t}`,a=navigator.maxTouchPoints??0;return/android/i.test(n)?{platform:"android",brand:"Android"}:/iphone/i.test(n)?{platform:"ios",brand:"iPhone"}:/ipad/i.test(n)||/mac/i.test(r)&&a>1?{platform:"ios",brand:"iPad"}:/mac/i.test(n)?{platform:"mac",brand:"Mac"}:/win/i.test(n)?{platform:"windows",brand:"Windows"}:/linux/i.test(n)?{platform:"linux",brand:"Linux"}:{platform:"web",brand:"Browser"}}function B(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:N();return{appId:(null==e?void 0:e.appId)??"",name:(null==e?void 0:e.name)??"",iconSrc:null==e?void 0:e.iconSrc}}function F(e){var t,r,i,n,a;if((null==e?void 0:e.containerWidth)!==void 0){let{density:t=1,screenWidth:r=0,screenHeight:i=0,containerWidth:n=0,containerHeight:a=0,statusBarHeight:s=0,topHeight:o=s,safeArea:l={}}=e,{marginTop:d=0,marginBottom:u=0,marginLeft:c=0,marginRight:p=0}=l;return{pixelRatio:t,screenWidth:r,screenHeight:i,windowWidth:n,windowHeight:a,statusBarHeight:s,screenTop:o,safeArea:{left:c,right:n-p,top:d,bottom:a-u,width:n-c-p,height:a-d-u}}}let s=Math.round((null==(n=window.visualViewport)?void 0:n.width)??window.innerWidth??0),o=Math.round((null==(a=window.visualViewport)?void 0:a.height)??window.innerHeight??0),l=window.devicePixelRatio??1,d=Math.round((null==(t=window.screen)?void 0:t.width)??s),u=Math.round((null==(r=window.screen)?void 0:r.height)??o),c=Math.round((null==(i=window.visualViewport)?void 0:i.offsetTop)??0);return{pixelRatio:l,screenWidth:d,screenHeight:u,windowWidth:s,windowHeight:o,statusBarHeight:c,safeArea:{left:0,right:s,top:c,bottom:o,width:s,height:Math.max(0,o-c)},screenTop:c}}function W(){return q().platform}function z(){var e,t,r,i,n;let a=navigator.userAgent??"",s=W();return"android"===s?null==(e=/android\s+([\d.]+)/i.exec(a))?void 0:e[1]:"ios"===s?null==(r=/(?:iphone os|cpu os)\s+([\d_]+)/i.exec(a))||null==(t=r[1])?void 0:t.replace(/_/g,"."):"mac"===s?null==(n=/mac os x\s+([\d_]+)/i.exec(a))||null==(i=n[1])?void 0:i.replace(/_/g,"."):void 0}function H(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:W();return"android"===e?"Android":"ios"===e?"iOS":"mac"===e?"macOS":"windows"===e?"Windows":"linux"===e?"Linux":"Web"}function V(e){let t;if((null==e?void 0:e.deviceModel)!==void 0){let t=e.os??e.devicePlatform??"";return{abi:e.abi,deviceAbi:e.deviceAbi,cpuType:e.cpuType,benchmarkLevel:"number"==typeof e.benchmarkLevel?e.benchmarkLevel:-1,brand:e.deviceBrand??"",model:e.deviceModel??e.deviceType??"",system:e.osVersion?`${t} ${e.osVersion}`:t,platform:(e.platform??t).toLowerCase(),memorySize:null==e.memorySize?"":String(e.memorySize)}}let r=q(),i=navigator.platform||W();return{abi:i,deviceAbi:i,benchmarkLevel:-1,brand:r.brand,model:function(){let e=navigator.userAgent??"",t=W();if("android"===t){var r,i;return(null==(i=/android\s+[\d.]+;\s*([^;)]+)/i.exec(e))||null==(r=i[1])?void 0:r.trim())||"Android"}return"ios"===t?q().brand:"mac"===t||"windows"===t||"linux"===t?navigator.platform||q().brand:U()}(),system:function(){let e=W(),t=z();if("web"!==e){let r=H(e);return t?`${r} ${t}`:r}let r=$(),i=U();return r?`${i} ${r}`:"Web"}(),platform:r.platform,cpuType:i,memorySize:"number"==typeof(t=navigator.deviceMemory)&&Number.isFinite(t)?String(Math.round(1024*t)):""}}function G(){let e=V(),t=F(),r=t.windowWidth>t.windowHeight;return{os:H(e.platform),platform:e.platform,osVersion:z(),deviceBrand:e.brand,language:P(),deviceModel:e.model,deviceType:e.model,deviceAbi:e.deviceAbi,cpuType:e.cpuType,memorySize:e.memorySize,benchmarkLevel:e.benchmarkLevel,appVersion:$(),appTheme:L(),channel:"release",screenOrientation:+!!r,isLandscape:+!!r,abi:e.abi}}function J(e){var t,r,i;let n,a=F(e),s=V(e);return{...a,brand:s.brand,model:s.model,language:(null==e||null==(t=e.language)?void 0:t.replace(/-/g,"_"))??P(),version:(null==e?void 0:e.appVersion)??$(),system:s.system,platform:(null==e||null==(r=e.os)?void 0:r.toLowerCase())??s.platform,SDKVersion:D(),theme:(null==e?void 0:e.appTheme)??L(),benchmarkLevel:s.benchmarkLevel,enableDebug:(null==e?void 0:e.channel)==="debug",deviceOrientation:(i=a.windowWidth>a.windowHeight,!0===(n=(null==e?void 0:e.isLandscape)??(null==e?void 0:e.screenOrientation))||1===n||"string"==typeof n&&n.toLowerCase().includes("landscape")?"landscape":!1===n||0===n||"string"==typeof n&&n.toLowerCase().includes("portrait")?"portrait":i?"landscape":"portrait"),abi:s.abi}}function K(){let e={isConnected:!1!==navigator.onLine,networkType:!1===navigator.onLine?"none":"unknown",hasSystemProxy:!1,weakNet:!1};return{networkType:e.networkType,signalStrength:e.signalStrength,hasSystemProxy:e.hasSystemProxy??!1,weakNet:e.weakNet??!1}}function Z(e){return{SDKVersion:D(),enableDebug:(null==e?void 0:e.channel)==="debug",host:{appId:(null==e?void 0:e.appName)??""},language:(null==e?void 0:e.language)??P(),version:(null==e?void 0:e.appVersion)??$(),theme:(null==e?void 0:e.appTheme)??L()}}function X(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:N(),t=arguments.length>1?arguments[1]:void 0;return{miniProgram:{appId:B(e).appId,envVersion:(null==t?void 0:t.channel)==="debug"?"develop":"release",version:(null==e?void 0:e.versionName)??""}}}function Y(e){var t;return(null==e||null==(t=e.navigation)?void 0:t.getPackageInfo())??(null==e?void 0:e.packageInfo)}E.handlers,r(31178),r(32085),r(12021);var Q=r(95550),ee=r(66013);r(46455);function et(e){if("string"!=typeof e)throw Error("key must be a string");if(0===e.length)throw Error("key must not be empty");if(e.length>1024)throw Error("key length must be less than or equal to 1024");return e}function er(e){if(ei(e)>1048576)throw Error("data size must be less than or equal to 1048576 bytes")}function ei(e){return new TextEncoder().encode(e).byteLength}function en(e){return Object.values(e).reduce((e,t)=>e+ei(t),0)}function ea(e){if(e>0xa00000)throw new w("total storage size exceeded",1600002)}function es(e){if(!o(e)||Array.isArray(e))throw Error("Storage snapshot must be an object");let t=0;for(let[r,i]of Object.entries(e)){if(et(r),"string"!=typeof i)throw Error("Storage values must be serialized strings");er(i),t+=ei(i)}ea(t)}let eo=new Map,el=new Map,ed=new Set;function eu(e,t){var r;let i=JSON.stringify([(null==e||null==(r=e.packageInfo)?void 0:r.appId)||"unknown-app",t??null]);return`web-storage:${(0,ee.My)((0,Q.sc)(i))}`}function ec(){let e=Date.now();return{entries:Object.fromEntries(["/","/temp","/user"].map(t=>[t,{type:"directory",createTime:e,lastModifiedTime:e}]))}}function ep(){return n??=new Promise((e,t)=>{let r=indexedDB.open("doubao-web-sdk-files",2);r.onupgradeneeded=()=>{let e=r.result;for(let t of["storage","files"])e.objectStoreNames.contains(t)||e.createObjectStore(t)},r.onsuccess=()=>{r.result.onversionchange=()=>{r.result.close(),n=void 0},e(r.result)},r.onerror=()=>{n=void 0,t(r.error)},r.onblocked=()=>{n=void 0,t(Error("Storage database upgrade is blocked; close other app views and retry"))}})}function eh(e){return IDBKeyRange.bound([e],[e,[]])}function em(e){return new Promise((t,r)=>{e.oncomplete=()=>t(),e.onabort=()=>{let t=e.error,i=new w((null==t?void 0:t.message)??"Storage transaction failed",(null==t?void 0:t.name)==="QuotaExceededError"?208:102);i.cause=t,r(i)}})}async function eg(e,t){let r=await ep(),i=r.transaction(["storage","files"]),n=em(i);for(let[r,n]of[["storage",t.storageSnapshot],["files",t.fileSystemSnapshot.entries]]){let t=i.objectStore(r).openCursor(eh(e));t.onsuccess=()=>{let e=t.result;e&&(Object.defineProperty(n,String(e.key[1]),{value:"files"===r?Object.freeze(e.value):e.value,enumerable:!0,configurable:!0,writable:!0}),e.continue())}}if(await n,0===Object.keys(t.fileSystemSnapshot.entries).length){t.fileSystemSnapshot=ec();let i=r.transaction("files","readwrite"),n=em(i);for(let[r,n]of Object.entries(t.fileSystemSnapshot.entries))i.objectStore("files").put(n,[e,r]);await n}}function ef(e){let t=eo.get(e);if(!t){let r={storageSnapshot:{},fileSystemSnapshot:{entries:{}}};t={snapshot:r,references:0,ready:eg(e,r)},eo.set(e,t)}t.references+=1;let r=t,i=!1;return{ready:t.ready,release(){if(i)return;i=!0,r.references-=1;let t=()=>{r.references||eo.get(e)!==r||eo.delete(e)};r.ready.then(t,t)}}}function ev(e,t){let r=ef(e),i=async()=>(await r.ready,t()),n=(el.get(e)??Promise.resolve()).then(i,i);el.set(e,n);let a=()=>{el.get(e)===n&&el.delete(e),r.release()};return n.then(a,a),n}function ey(e){var t;let r=null==(t=eo.get(e))?void 0:t.snapshot;if(!r)throw Error("Application storage is not initialized");return{storageSnapshot:{...r.storageSnapshot},fileSystemSnapshot:{entries:{...r.fileSystemSnapshot.entries}}}}function eb(e){return ey(e).fileSystemSnapshot}function ew(e){return ed.add(e),()=>{ed.delete(e)}}function e_(e,t,r){let i={...r??ey(e),fileSystemNamespace:e,mutationId:t};for(let e of ed)try{e(i)}catch(e){console.error("Cannot deliver application storage update",e)}}function eS(e,t){let r={};for(let i of new Set([...Object.keys(e),...Object.keys(t)])){let n=Object.hasOwn(t,i)?t[i]:null,a=Object.hasOwn(e,i)?e[i]:void 0,s=o(a)&&o(n)&&a.type===n.type&&a.data===n.data&&a.createTime===n.createTime&&a.lastModifiedTime===n.lastModifiedTime;a===(n??void 0)||s||Object.defineProperty(r,i,{value:n,enumerable:!0})}return r}async function ex(e,t){let r=ey(e);for(let[e,i]of(t.clearStorage&&(r.storageSnapshot={}),[[r.storageSnapshot,t.storageChanges],[r.fileSystemSnapshot.entries,t.fileSystemChanges]]))for(let[t,r]of Object.entries(i??{}))null===r?delete e[t]:Object.defineProperty(e,t,{value:r,enumerable:!0,writable:!0,configurable:!0});(t.storageChanges||t.clearStorage)&&es(r.storageSnapshot),t.fileSystemChanges&&ek(r.fileSystemSnapshot,eb(e));let i=(await ep()).transaction(["storage","files"],"readwrite"),n=em(i);try{for(let[r,n]of(t.clearStorage&&i.objectStore("storage").delete(eh(e)),[["storage",t.storageChanges],["files",t.fileSystemChanges]])){let t=i.objectStore(r);for(let[i,a]of Object.entries(n??{}))null===a?t.delete([e,i]):t.put("files"===r?Object.freeze(a):a,[e,i])}}catch(e){throw i.abort(),await n.catch(()=>{}),e}await n,eo.get(e).snapshot=r,e_(e,t.mutationId,t)}function eI(e){return o(e)&&"directory"===e.type}function ek(e,t){if(!o(e)||!o(e.entries))throw Error("Invalid file snapshot");let r={user:0,temp:0};for(let[i,n]of Object.entries(e.entries)){if(!o(n)||!["file","directory"].includes(String(n.type))||!Number.isFinite(n.createTime)||0>Number(n.createTime)||!Number.isFinite(n.lastModifiedTime)||0>Number(n.lastModifiedTime)||"/"!==i&&(!/^\/(user|temp)(\/[^/]+)*$/.test(i)||i.split("/").some(e=>"."===e||".."===e||/[\\\0]/.test(e)))||"/"!==i&&!eI(e.entries[i.slice(0,i.lastIndexOf("/"))||"/"])||["/","/user","/temp"].includes(i)&&"directory"!==n.type)throw Error(`Invalid file entry: ${i}`);if("file"===n.type){if("string"!=typeof n.data)throw Error(`Invalid file data: ${i}`);if((null==t?void 0:t.entries[i])!==n&&(n.data.length%4!=0||/[^A-Za-z0-9+/=]/.test(n.data)||!/^[^=]*={0,2}$/.test(n.data)))throw Error(`Invalid base64 file: ${i}`);let e=i.startsWith("/user/")?"user":"temp";r[e]+=Math.floor(3*n.data.length/4)-(n.data.endsWith("==")?2:+!!n.data.endsWith("="))}}for(let t of["/","/user","/temp"])if(!eI(e.entries[t]))throw Error(`Missing file directory: ${t}`);if(r.user>0x3200000||r.temp>0x6400000)throw new w("total file storage size exceeded",208)}function eC(e){if(!o(e)||"doubao-web-storage"!==e.format||1!==e.version||!o(e.storageSnapshot))throw Error("存储与文件备份格式无效");es(e.storageSnapshot),ek(e.fileSystemSnapshot)}r(20303),r(99166),r(6106),r(22742),r(37553),r(62148),r(89055),r(12205),r(65850),r(65135),r(5876),r(94359),r(28016),r(38641),r(82247),r(11839),r(56109),r(63589),r(45249);var eE=r(59933),eN=r(12683);function eT(e){if(e.startsWith("/")||e.includes("\\")||e.includes("\0")||/^[a-z]:/i.test(e))throw new w("ZIP entry escapes the target directory",213);let t=[];for(let r of e.split("/"))if(r&&"."!==r)if(".."===r){if(!t.length)throw new w("ZIP entry escapes the target directory",213);t.pop()}else t.push(r);return t.join("/")}function eA(e){return Math.floor(3*e.length/4)-(e.endsWith("==")?2:+!!e.endsWith("="))}function eM(e){if(e>0xa00000)throw new w("total size limit exceeded",208)}function ej(e,t,r){let i=t.startsWith("/user/")?"/user/":"/temp/",n=("/user/"===i?50:100)*1048576,a=r;for(let[r,n]of Object.entries(e.entries))r!==t&&r.startsWith(i)&&"file"===n.type&&(a+=eA(n.data));if(a>n)throw new w("total size limit exceeded",208)}function eR(e){o(e.fileSystemSnapshot)||(e.fileSystemSnapshot={entries:{}}),o(e.fileSystemSnapshot.entries)||(e.fileSystemSnapshot.entries={});let t=Date.now();for(let i of["/","/temp","/user"]){var r;(null==(r=e.fileSystemSnapshot.entries[i])?void 0:r.type)!=="directory"&&(e.fileSystemSnapshot.entries[i]={type:"directory",createTime:t,lastModifiedTime:t})}return e.fileSystemSnapshot}function eP(e,t){let r=e[t];if("string"!=typeof r)throw new w(`${t} must be a string`,104);return r}function eL(e,t){let r=e[t];return"string"==typeof r?r:void 0}function eD(e){let t;if(0===e.length||e.includes("?")||e.includes("#")||/%(?![0-9a-f]{2})/i.test(e))throw new w("invalid applet file path",213);try{t=decodeURIComponent(e)}catch{throw new w("invalid applet file path",213)}if("."===t||".."===t||t.includes("/")||t.includes("\\")||t.includes("\0"))throw new w("invalid applet file path",213);return t}function eO(e){let t=/^appletfile:\/\/(user|temp)(?:\/(.*))?$/.exec(e);if(!t)throw new w("path must use appletfile://user or appletfile://temp",213);let r=t[1],i=t[2];if(void 0===i||0===i.length)return`/${r}`;let n=i.split("/").map(eD);return`/${r}/${n.join("/")}`}function eU(e){let t=/^data:[^,]*;base64,([A-Za-z0-9+/]*={0,2})$/.exec(e);if(!t)return;let r=t[1];if(r.length%4==1||r.endsWith("=")&&r.length%4!=0)throw new w("invalid base64 data",104);return{type:"file",data:r,createTime:0,lastModifiedTime:0}}function e$(e){let t=eO(e);if("/temp"===t||"/user"===t)return"";let r=t.lastIndexOf("/");return t.slice(0,r)}function eq(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function eB(e){let t=e.split("/").filter(Boolean),r=t.shift();if("temp"!==r&&"user"!==r)throw new w(`invalid applet file path: ${e}`,213);let i=t.map(eq).join("/");return i.length>0?`appletfile://${r}/${i}`:`appletfile://${r}`}function eF(e,t){return e.entries[eO(t)]}function eW(e,t){let r=eU(t);if(r)return r;let i=eO(t),n=e.entries[i];if(!n)throw new w(`file not found: ${i}`,203);if("file"!==n.type)throw new w(`path is a directory: ${i}`,1901001);return n}function ez(e,t){let r=eO(t),i=e.entries[r];if(!i)throw new w(`directory not found: ${r}`,203);if("directory"!==i.type)throw new w(`path is not a directory: ${r}`,1901002);return i}function eH(e,t){let r=e$(t);if(!r)throw new w(`invalid parent directory: ${t}`,213);let i=Date.now(),n="";for(let t of r.split("/").filter(Boolean)){n+=`/${t}`;let r=e.entries[n];if((null==r?void 0:r.type)==="file")throw new w(`path is not a directory: ${n}`,1901002);r||(e.entries[n]={type:"directory",createTime:i,lastModifiedTime:i})}}function eV(e){let t;try{t=atob(e)}catch{throw new w("invalid base64 data",104)}let r=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)r[e]=t.charCodeAt(e);return r}function eG(e,t){let r="string"==typeof e?e:String(e??"");return"base64"===t?eV(r):new TextEncoder().encode(r)}function eJ(e,t,r){let i=eO(t),n=Date.now(),a=e.entries[i];if((null==a?void 0:a.type)==="directory")throw new w(`path is a directory: ${i}`,1901001);ej(e,i,r.byteLength),eH(e,t),e.entries[i]={type:"file",data:function(e){let t="";for(let r=0;r<e.length;r+=1)t+=String.fromCharCode(e[r]);return btoa(t)}(r),createTime:(null==a?void 0:a.createTime)??n,lastModifiedTime:n}}function eK(e,t,r){let i=eR(e),n=eP(t,"dirPath"),a=eO(n),s=Date.now(),o=i.entries[a];if((null==o?void 0:o.type)==="directory")return{};if(o)throw new w(`path is not a directory: ${a}`,1901002);if(!0===t.recursive){let e="";for(let t of a.split("/").filter(Boolean))if(e+=`/${t}`,i.entries[e]||(i.entries[e]={type:"directory",createTime:s,lastModifiedTime:s}),"directory"!==i.entries[e].type)throw new w(`path is not a directory: ${e}`,1901002)}else{let e=e$(n);if(!e)throw new w(`invalid parent directory: ${n}`,213);let t=i.entries[e];if(!t)throw new w(`directory not found: ${e}`,203);if("directory"!==t.type)throw new w(`path is not a directory: ${e}`,1901002);i.entries[a]={type:"directory",createTime:s,lastModifiedTime:s}}return r(),{}}function eZ(e,t,r){let i=eR(e),n=eP(t,"dirPath"),a=eO(n);if("/temp"===a||"/user"===a)throw new w("cannot remove root directory",213);ez(i,n);let s=`${a}/`,o=Object.keys(i.entries).filter(e=>e.startsWith(s));if(!0!==t.recursive&&o.length>0)throw new w(`directory is not empty: ${a}`,1901001);for(let e of o)delete i.entries[e];return delete i.entries[a],r(),{}}function eX(e,t,r){let i=eR(e),n=eP(t,"filePath"),a=eO(n);return eW(i,n),delete i.entries[a],r(),{}}function eY(e,t){let r=eR(e),i=eP(t,"path"),n=eU(i),a=n?i:eO(i),s=n??r.entries[a];if(!s)throw new w(`path not found: ${a}`,203);return{size:"file"===s.type?eA(s.data):0,lastModifiedTime:s.lastModifiedTime,isDirectory:"directory"===s.type}}let eQ={"doubao.readFile":function(e,t){var r;let i=eW(eR(e),eP(t,"filePath"));return eM(eA(i.data)),{data:(r=i.data,"utf-8"===eL(t,"encoding")?new TextDecoder().decode(eV(r)):r)}},"doubao.writeFile":function(e,t,r){let i=eR(e),n=eG(t.data,eL(t,"encoding"));return eM(n.byteLength),eJ(i,eP(t,"filePath"),n),r(),{}},"doubao.appendFile":function(e,t,r){let i=eR(e),n=eP(t,"filePath"),a=eO(n),s=i.entries[a];if((null==s?void 0:s.type)==="directory")throw new w(`path is a directory: ${a}`,1901001);let o=eG(t.data,eL(t,"encoding"));eM(o.byteLength),ej(i,a,((null==s?void 0:s.type)==="file"?eA(s.data):0)+o.byteLength);let l=(null==s?void 0:s.type)==="file"?eV(s.data):new Uint8Array,d=new Uint8Array(l.length+o.length);return d.set(l),d.set(o,l.length),eJ(i,n,d),r(),{}},"doubao.access":function(e,t){let r=eR(e),i=eP(t,"path");if(!eF(r,i))throw new w(`path not found: ${i}`,203);return{}},"doubao.mkdir":eK,"doubao.rmdir":eZ,"doubao.readdir":function(e,t){let r=eR(e),i=eP(t,"dirPath");return ez(r,i),{files:function(e,t){let r=eO(t),i="/"===r?"/":`${r}/`,n=new Set;for(let t of Object.keys(e.entries)){if(t===r||!t.startsWith(i))continue;let e=t.slice(i.length).split("/")[0];e&&n.add(e)}return[...n]}(r,i)}},"doubao.unlink":eX,"doubao.stat":eY,"doubao.copyFile":function(e,t,r){let i=eR(e),n=eW(i,eP(t,"srcPath")),a=eP(t,"destPath");return ej(i,eO(a),eA(n.data)),eJ(i,a,eV(n.data)),r(),{}},"doubao.getFileInfo":function(e,t){let r=eP(t,"filePath"),{size:i}=eY(e,{path:r});if(void 0===t.digestAlgorithm)return{size:i};let n=eP(t,"digestAlgorithm").toLowerCase(),a=eW(eR(e),r),s="md5"===n?eE.Fx:"sha1"===n?eE.e8:void 0;if(!s)throw new w(`unsupported digest algorithm: ${n}`,102);return{size:i,digest:(0,ee.My)(s(eV(a.data)))}},"doubao.rename":function(e,t,r){let i=eR(e),n=eP(t,"oldPath"),a=eP(t,"newPath"),s=eO(n),o=eO(a),l=i.entries[s];if(!l)throw new w(`path not found: ${s}`,203);if("/temp"===s||"/user"===s)throw new w("cannot rename root directory",213);if(s===o)return{};if("directory"===l.type&&o.startsWith(`${s}/`))throw new w("cannot move a directory into itself",213);if(i.entries[o])throw new w(`target already exists: ${o}`,102);for(let e of(eH(i,a),Object.keys(i.entries)))if(e===s||e.startsWith(`${s}/`)){let t=o+e.slice(s.length);i.entries[t]=i.entries[e],delete i.entries[e]}return r(),{}},"doubao.truncate":function(e,t,r){let i=eR(e),n=eP(t,"filePath"),a=eW(i,n),s=t.length??0;if("number"!=typeof s||!Number.isSafeInteger(s)||s<0)throw new w("length must be a non-negative integer",104);ej(i,eO(n),s);let o=eV(a.data),l=new Uint8Array(s);return l.set(o.slice(0,s)),eJ(i,n,l),r(),{}},"doubao.saveFile":function(e,t,r){let i,n,a=eR(e),s=eP(t,"tempFilePath"),o=eU(s),l=o??eW(a,s),d=eL(t,"filePath"),u=o?(i=s.slice(5,s.indexOf(";")),`media.${({"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","audio/wav":"wav","audio/aac":"aac","audio/mp4":"mp4"})[i]??"bin"}`):"/temp"===(n=eO(s))||"/user"===n?"":n.slice(n.lastIndexOf("/")+1),c=`/user/${Date.now()}`,p=d&&d.length>0?d:eB(`${c}_${u}`);for(let e=1;!d&&a.entries[eO(p)];e++)p=eB(`${c}_${e}_${u}`);return ej(a,eO(p),eA(l.data)),eJ(a,p,eV(l.data)),o||eO(s)===eO(p)||delete a.entries[eO(s)],r(),{savedFilePath:p}},"doubao.getSavedFileList":function(e){return{fileList:Object.entries(eR(e).entries).flatMap(e=>{let[t,r]=e;return t.startsWith("/user/")&&"file"===r.type?[{filePath:eB(t),size:eA(r.data),createTime:r.createTime}]:[]})}},"doubao.removeSavedFile":function(e,t,r){var i;let n=eP(t,"filePath");return(null==(i=eF(eR(e),n))?void 0:i.type)==="directory"?eZ(e,{dirPath:n},r):eX(e,t,r)},"doubao.unzip":function(e,t,r){let i=eR(e),n=eW(i,eP(t,"zipFilePath")),a=eP(t,"targetPath"),s=eO(a),o=function(e,t){try{let r=function(e,t){let r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=e.length-22,n=Math.max(0,e.length-65557);for(;i>=n&&(0x6054b50!==r.getUint32(i,!0)||i+22+r.getUint16(i+20,!0)!==e.length);)i--;if(i<n||0!==r.getUint16(i+4,!0)||0!==r.getUint16(i+6,!0))throw Error("Invalid or multipart ZIP archive");let a=r.getUint16(i+10,!0),s=r.getUint32(i+16,!0);if(65535===a||0xffffffff===s){if(i<20||0x7064b50!==r.getUint32(i-20,!0))throw Error("Invalid ZIP64 archive");let e=Number(r.getBigUint64(i-12,!0));if(0x6064b50!==r.getUint32(e,!0))throw Error("Invalid ZIP64 directory");a=Number(r.getBigUint64(e+32,!0)),s=Number(r.getBigUint64(e+48,!0))}if(!Number.isSafeInteger(a)||a>e.length/46||!Number.isSafeInteger(s))throw Error("Invalid ZIP directory size");let o=new Map,l=0;for(let n=0;n<a;n++){if(s+46>i||0x2014b50!==r.getUint32(s,!0))throw Error("Invalid ZIP directory entry");let n=r.getUint16(s+8,!0),a=r.getUint16(s+28,!0),d=r.getUint16(s+30,!0),u=s+46+a+d+r.getUint16(s+32,!0);if(u>i||1&n)throw Error("Invalid or encrypted ZIP entry");let c=(0,eN.he)(e.subarray(s+46,s+46+a),!(2048&n));eT(c);let p=r.getUint32(s+24,!0);if(0xffffffff===p){let e=s+46+a,t=e+d;for(;e+4<=t&&1!==r.getUint16(e,!0);)e+=4+r.getUint16(e+2,!0);if(e+12>t||8>r.getUint16(e+2,!0))throw Error("Invalid ZIP64 file size");p=Number(r.getBigUint64(e+4,!0))}if(!Number.isSafeInteger(l+=p)||l>t)throw new w("ZIP expanded size exceeds the file system quota",208);o.set(c,r.getUint32(s+16,!0)),s=u}return o}(e,t),i=new Map,n=0,a=new eN.HJ(e=>{eT(e.name);let r=new eN.uZ(e.name);r.ondata=()=>{};let a=[],s=0;e.ondata=(o,l,d)=>{if(o)throw o;if((n+=l.length)>t)throw new w("ZIP expanded size exceeds the file system quota",208);if(a.push(l),s+=l.length,r.push(l,d),d){let t=new Uint8Array(s),n=0;for(let e of a)t.set(e,n),n+=e.length;i.set(e.name,{data:t,crc:r.crc>>>0})}},e.start()});a.register(eN.mM);for(let t=0;t<e.length;t+=65536)a.push(e.subarray(t,t+65536),t+65536>=e.length);if(i.size!==r.size)throw Error("ZIP entry count does not match its directory");for(let[e,t]of i)if(t.crc!==r.get(e))throw Error("ZIP entry checksum does not match");return new Map([...i].map(e=>{let[t,r]=e;return[t,r.data]}))}catch(e){if(e instanceof w)throw e;throw new w(`Unable to unzip file: ${e instanceof Error?e.message:String(e)}`,102)}}(eV(n.data),(s.startsWith("/user")?50:100)*1048576),l={...e,fileSystemSnapshot:{entries:{...i.entries}}};for(let[e,t]of(eK(l,{dirPath:a,recursive:!0},()=>{}),o)){let r=eT(e);if(!r)continue;let i=eB(`${s}/${r}`);e.endsWith("/")?eK(l,{dirPath:i,recursive:!0},()=>{}):eJ(l.fileSystemSnapshot,i,t)}return i.entries=l.fileSystemSnapshot.entries,r(),{}}},e0="doubao.__webSyncBridgePersist",e1="doubao.__webSyncBridgeUpdated";r(20789),r(62839),r(66876),r(35336);let e2="doubao.getPerformanceEntries",e3="doubao.setPerformanceBufferSize",e4="doubao.onPerformanceEntries",e6="doubao.__webPerformanceTiming",e5="__WEB_PERFORMANCE_WIDGET_IDENTITY__",e8=[e2,e3,e4];class e9{entries=[];bufferSize=30;launchStart=Date.now();launched=!1;snapshot(){return{entries:this.entries.map(e=>({...e})),bufferSize:this.bufferSize}}setBufferSize(e){if("number"!=typeof e||!Number.isInteger(e)||e<1||e>1e3)throw Error("size must be between 1 and 1000");this.bufferSize=e,this.entries=this.entries.slice(-e)}reset(){this.entries=[],this.bufferSize=30,this.launchStart=Date.now(),this.launched=!1}recordTiming(e,t){if(e.completed||!o(t))return[];let r=e.timing??={};for(let e of["create_lynx_start","layout_start","layout_end","lepus_execute_start","lepus_execute_end","parseChangesEnd"]){let i=t[e];"number"==typeof i&&Number.isFinite(i)&&i>0&&(r[e]=i)}let i=e=>{let t=r[e];return"number"==typeof t&&Number.isFinite(t)&&t>0?t:void 0},n=i("create_lynx_start"),a=i("layout_start"),s=i("layout_end");if(void 0===n||void 0===a||void 0===s||s<a||a<n)return[];e.completed=!0;let l=[],d=void 0===e.pageId?{}:{path:e.path,pageId:e.pageId};if(void 0!==e.pageId){let t=!this.launched,r=Math.min(e.startTime,n);if(t){let t=Math.min(this.launchStart,r);l.push({entryType:"navigation",name:"appLaunch",startTime:t,duration:s-t,...d,navigationStart:r,navigationType:e.navigationType})}l.push({entryType:"navigation",name:"route",startTime:r,duration:s-r,...d,navigationStart:r,navigationType:e.navigationType,referrerPath:e.referrerPath,referrerPageId:e.referrerPageId}),this.launched=!0}let u=i("lepus_execute_start"),c=i("lepus_execute_end"),p=c??i("parseChangesEnd");return void 0!==u&&void 0!==c&&c>=u&&l.push({entryType:"script",name:"evaluateScript",startTime:u,duration:c-u,moduleName:e.moduleName}),(void 0!==e.pageId||void 0!==e.widgetId)&&l.push({entryType:"render",name:"firstRender",startTime:n,duration:s-n,...d,...void 0!==p&&p>=n&&p<=s?{viewLayerReadyTime:p}:{},viewLayerRenderStartTime:a,viewLayerRenderEndTime:s,...void 0===e.widgetId?{}:{widgetId:e.widgetId,widgetInstanceId:e.widgetInstanceId,isAppColdLaunch:e.isAppColdLaunch}}),this.entries=[...this.entries,...l].slice(-this.bufferSize),l}}async function e7(e,t){try{await (null==t?void 0:t(e.params))}catch{}}let te=new Map,tt={"applet.subscribeEvent":(e,t)=>{let r=o(e.params)&&"string"==typeof e.params.eventName?e.params.eventName:"";if(r){var i;null==t||null==(i=t.events)||i.subscribe(r,t)}return _(e,{})},"applet.unsubscribeEvent":(e,t)=>{let r=o(e.params)&&"string"==typeof e.params.eventName?e.params.eventName:"";if(r){var i;null==t||null==(i=t.events)||i.unsubscribe(r)}return _(e,{})}};function tr(){var e;return null==(e=globalThis.navigator)?void 0:e.clipboard}function ti(e,t){let r=tr();if(!r||"function"!=typeof r[t])throw new w(`${e} is not supported in this browser`,103);return r}function tn(e,t){let r=o(t)&&"string"==typeof t.message?t.message:String(t),i=new w(`${e} failed: ${r}`,o(t)&&("NotAllowedError"===t.name||"SecurityError"===t.name)?106:102);return i.cause=t,i}async function ta(e){let t=ti("setClipboardData","writeText");try{await t.writeText(e)}catch(e){throw tn("setClipboardData",e)}}async function ts(){let e=ti("getClipboardData","readText");try{let t=await e.readText();if("string"==typeof t)return t}catch(e){throw tn("getClipboardData",e)}throw new w("getClipboardData failed: clipboard did not return text",102)}function to(e,t,r){let i=(null==t?void 0:t.fileSystemNamespace)??eu(null==t?void 0:t.globalProps);return ev(i,async()=>{try{var n,a;let s=eb(i),l={fileSystemNamespace:i,fileSystemSnapshot:{entries:{...s.entries}},apiResults:{"doubao.getSystemInfo":{platform:null==t||null==(a=t.globalProps)||null==(n=a.os)?void 0:n.toLowerCase()}},storageSnapshot:{},supportedAPIs:[]},d=!1,u=(0,eQ[e.name])(l,o(e.params)?e.params:{},()=>{d=!0});return d?await ex(i,{fileSystemChanges:eS(s.entries,l.fileSystemSnapshot.entries),mutationId:r}):r&&e_(i,r,{}),_(e,u)}catch(e){throw r&&e_(i,r),e}})}let tl=Object.fromEntries(Object.keys(eQ).map(e=>[e,to]));async function td(e,t){var r,i;if("string"!=typeof(null==e?void 0:e.src)||!e.src)throw Error("src must be a non-empty string");let{src:n}=e,a=await new Promise((e,r)=>{let i=new Image,a=()=>{null==t||t.removeEventListener("abort",s),i.onload=i.onerror=null},s=()=>{a(),i.removeAttribute("src"),r(null==t?void 0:t.reason)};(null==t?void 0:t.aborted)?s():(null==t||t.addEventListener("abort",s,{once:!0}),i.onload=()=>{a(),e(i)},i.onerror=()=>{a(),r(Error(`failed to load image: ${n}`))},i.src=n)}),s=null==(r=n.match(/^data:image\/([^;,]+)/i))?void 0:r[1],o=null==(i=n.match(/\.([a-zA-Z0-9]+)(?:[?#].*)?$/))?void 0:i[1];return{width:a.naturalWidth||a.width,height:a.naturalHeight||a.height,orientation:"up",path:n,type:((null==s?void 0:s.split("+")[0])??o??"").toLowerCase()}}function tu(e){return{pages:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:i;return(null==e?void 0:e.getCurrentPages())??[]}(null==e?void 0:e.navigation)}}function tc(e){return async(t,r)=>{let i=t.params;if(!i||"string"!=typeof i.url||!i.url.trim())return S(t,"invalid url",104);try{return await e(i,null==r?void 0:r.navigation)?_(t,{}):S(t,"No active Runtime to navigate",102)}catch(e){return S(t,x(e),e instanceof w?e.errNo:102)}}}let tp={"doubao.openPage":async(e,t)=>{var r;let i=e.params;if(!i||"string"!=typeof i.url||!i.url.trim()||void 0!==i.mode&&!["push","replace","navigate","pop_to"].includes(i.mode))return S(e,"url and mode must describe a valid page route",104);if(!(null==t||null==(r=t.navigation)?void 0:r.openPage))return S(e,"No active Runtime to open page",102);try{return await t.navigation.openPage(i),_(e,{})}catch(t){return S(e,x(t),t instanceof w?t.errNo:102)}},"doubao.enableAlertBeforeUnload":(e,t)=>{var r;let i=null==(r=e.params)?void 0:r.message;return"string"!=typeof i?S(e,"message must be a string",104):th(e,i,t)},"doubao.disableAlertBeforeUnload":(e,t)=>th(e,void 0,t),"doubao.getCurrentPages":{handler:(e,t)=>_(e,tu(t)),syncResult:tu},"doubao.navigateTo":tc(T),"doubao.redirectTo":tc(A),"doubao.reLaunch":tc(M),"doubao.navigateBack":(e,t)=>!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i;return(null==t?void 0:t.navigateBack(e))??!1}(e.params??{},null==t?void 0:t.navigation)?S(e,"No pages in back stack",102):_(e,{}),"doubao.exitApp":(e,t)=>!function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:i;return null==e||e.exitApp(),!!e}(null==t?void 0:t.navigation)?S(e,"No active Runtime to exit app",102):_(e,{})};function th(e,t,r){var i;return(null==r?void 0:r.containerType)==="PAGE"&&(null==(i=r.navigation)?void 0:i.setAlertBeforeUnload)?r.navigation.setAlertBeforeUnload(t,r.element)?_(e,{}):S(e,"not found page",102):S(e,"alert before unload is only supported in page container",103)}let tm=Object.fromEntries(["setStorage","getStorage","removeStorage","clearStorage","getStorageInfo"].map(e=>[`doubao.${e}`,async(t,r)=>{let i=(null==r?void 0:r.fileSystemNamespace)??eu(null==r?void 0:r.globalProps);return ev(i,async()=>{var r,n;let a=o(t.params)?t.params:{},s=ey(i).storageSnapshot,l={};switch(e){case"setStorage":{let e,t;if("string"!=typeof a.data)throw Error("data must be a serialized string");let o=(r=a.key,n=a.data,e=et(r),er(n),t=Object.prototype.hasOwnProperty.call(s,e)?s[e]:void 0,ea(en(s)-(void 0===t?0:ei(t))+ei(n)),e);await ex(i,{storageChanges:{[o]:a.data}});break}case"getStorage":let d;l={data:Object.hasOwn(s,d=et(a.key))?s[d]:void 0};break;case"removeStorage":await ex(i,{storageChanges:{[et(a.key)]:null}});break;case"clearStorage":await ex(i,{clearStorage:!0});break;case"getStorageInfo":l={keys:Object.keys(s),currentSize:Math.ceil(en(s)/1024),limitSize:10240}}return _(t,l)})}])),tg={...{"doubao.getClipboardData":{canIUse:()=>{var e;return"function"==typeof(null==(e=tr())?void 0:e.readText)},handler:async e=>_(e,{data:await ts()})},"doubao.setClipboardData":{canIUse:()=>{var e;return"function"==typeof(null==(e=tr())?void 0:e.writeText)},handler:async e=>{let{data:t}=function(e){if(!o(e)||"string"!=typeof e.data)throw new w("data must be a string",104);return{data:e.data}}(e.params);return await ta(t),_(e,{})}}},...tt,...tl,...{"doubao.getImageInfo":async e=>_(e,await td(e.params))},...tp,...tm,...{[e0]:async(e,t)=>{let r=o(e.params)?e.params:{},i=null==t?void 0:t.fileSystemNamespace;if(!i||r.fileSystemNamespace!==i)throw Error("Storage scope does not match the calling application");let n="string"==typeof r.mutationId?r.mutationId:void 0;if(void 0!==r.fileSystemOperation){let i=r.fileSystemOperation;if(!o(i)||"string"!=typeof i.name||!Object.hasOwn(eQ,i.name)||!o(i.params))throw Error("Invalid synchronous file operation");return to({...e,name:i.name,params:i.params},t,n)}let a={storageChanges:o(r.storageChanges)?r.storageChanges:void 0,clearStorage:!0===r.clearStorage,fileSystemChanges:o(r.fileSystemChanges)?r.fileSystemChanges:void 0,mutationId:n};return await ev(i,async()=>{try{await ex(i,a)}catch(e){throw e_(i,a.mutationId),e}}),_(e,{})}},...{"doubao.canIUse":{handler:(e,t)=>{let{schema:r}=e.params;return _(e,{result:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:E;return t.canIUse(e,{apiRegistry:t})}(r,null==t?void 0:t.apiRegistry)})}},"doubao.getAccountInfo":{handler:(e,t)=>{var r;return _(e,X(null==t||null==(r=t.navigation)?void 0:r.getPackageInfo(),null==t?void 0:t.globalProps))},syncResult:e=>X(Y(e),null==e?void 0:e.globalProps)},"doubao.getPackageInfo":{handler:(e,t)=>{var r;return _(e,B(null==t||null==(r=t.navigation)?void 0:r.getPackageInfo()))},syncResult:e=>B(Y(e))},"doubao.getAppBaseInfo":{handler:(e,t)=>_(e,Z(null==t?void 0:t.globalProps)),syncResult:e=>Z(null==e?void 0:e.globalProps)},"doubao.getMenuButtonBoundingClientRect":{handler:(e,t)=>_(e,R(null==t?void 0:t.globalProps)),syncResult:e=>R(null==e?void 0:e.globalProps)},"doubao.getSystemInfo":{handler:(e,t)=>_(e,J(null==t?void 0:t.globalProps)),syncResult:e=>J(null==e?void 0:e.globalProps)},"doubao.getWindowInfo":{handler:(e,t)=>_(e,F(null==t?void 0:t.globalProps)),syncResult:e=>F(null==e?void 0:e.globalProps)},"doubao.getDeviceInfo":{handler:(e,t)=>_(e,V(null==t?void 0:t.globalProps)),syncResult:e=>V(null==e?void 0:e.globalProps)},"doubao.getNetworkType":{handler:e=>_(e,K()),syncResult:K}}};E.registerMany(tg,{override:!0}),E.registerEventSources({onThemeChange:e=>{let t=matchMedia("(prefers-color-scheme: dark)"),r=()=>e({appTheme:matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"});return t.addEventListener("change",r),()=>t.removeEventListener("change",r)}},{override:!0});class tf{router;navigation;onEmpty;runtime;callers=new Map;destroyed=!1;performance=new e9;applicationLifecycle=new AbortController;nextPerformancePageId=Math.floor(1e12*Math.random());eventKey=Symbol("application events");applicationEvents;applicationEventKey;unsubscribeStorage;getApplicationEvents(){var e,t,r;let i=(null==(e=this.runtime)?void 0:e.getFileSystemNamespace())??this.eventKey;if(this.applicationEventKey!==i){let e,n;null==(t=this.applicationEvents)||t.release(),this.applicationEventKey=i,this.applicationEvents=(r=e=>{for(let t of this.callers.values())t.events.isSubscribed(e.name)&&t.send(e)},e=te.get(i)??{receivers:new Set,recent:[]},te.set(i,e),e.receivers.add(r),n=()=>{let t=Date.now();e.recent=e.recent.filter(e=>1e4>=Math.abs(t-e.timestamp))},{publish(t){for(let r of(n(),e.recent.push({message:t,timestamp:t.timestamp??Date.now()}),[...e.receivers]))r(t)},replay(t,r,i){for(let a of(n(),e.recent))a.message.name===t&&a.timestamp>=r&&i(a.message)},release(){e.receivers.delete(r),0===e.receivers.size&&te.delete(i)}})}return this.applicationEvents}constructor(e,t,r,i){this.router=e,this.navigation=t,this.onEmpty=r,this.runtime=i}get apiRegistry(){var e;return(null==(e=this.runtime)?void 0:e.apiRegistry)??E}register(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:()=>{},t=arguments.length>1?arguments[1]:void 0,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(this.destroyed)throw Error("RuntimeBridge was destroyed");let i=Symbol("caller");this.getApplicationEvents();let n=(null==t?void 0:t.apiRegistry)??this.apiRegistry;this.unsubscribeStorage??=ew(e=>{for(let t of this.callers.values())t.fileSystemNamespace===e.fileSystemNamespace&&t.events.emitPrivate(e1,e)});let a=n.createEventController((t,r)=>{e({type:"event",name:t,params:r,timestamp:Date.now()})});return this.callers.set(i,{abortController:new AbortController,send:e,options:t,events:a,main:r}),i}resolveStorageNamespace(e,t,r){var i,n,a;return(null==(i=this.runtime)?void 0:i.getFileSystemNamespace())??(null==(n=e.options)?void 0:n.fileSystemNamespace)??r??eu(t,null==(a=e.options)?void 0:a.userId)}async prepareStorage(e,t,r){let i=this.getCaller(e),n=this.resolveStorageNamespace(i,t,r);if(i.fileSystemNamespace!==n){var a;null==(a=i.storage)||a.release(),i.storage=void 0,i.fileSystemNamespace=n}i.storage??=ef(n),await i.storage.ready}createSyncBridgeData(e,t,r){var i;let n=this.getCaller(e),a=function(e,t){var r;let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:eu(e),n=arguments.length>3?arguments[3]:void 0,a=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:E;return e.getSupportedNames({apiRegistry:e})}(t);return{hostFileSystem:Object.keys(eQ).every(r=>null==t?void 0:t.canIUse(r,{globalProps:e})),fileSystemNamespace:i,...ey(i),hostStorage:!!(null==t?void 0:t.canIUse("doubao.setStorage",{globalProps:e})),apiResults:(r=null==e?void 0:e.packageInfo,(t??E).getSyncResults({globalProps:e,navigation:n,packageInfo:r})),supportedAPIs:a}}(t,(null==(i=n.options)?void 0:i.apiRegistry)??this.apiRegistry,this.resolveStorageNamespace(n,t,r),this.navigation);return a.performance=this.performance.snapshot(),n.fileSystemNamespace=a.fileSystemNamespace,a.supportedAPIs.push(...e8,e1),a}beginPerformance(e,t){var r,i,n;let a=this.getCaller(e),s=t.globalProps??{},l=o(s.__VIEW_CONTEXT__)?s.__VIEW_CONTEXT__:{},d=o(s[e5])?s[e5]:l,u="PAGE"===t.containerType,c=null==(i=this.navigation)||null==(r=i.getCurrentPages().at(-2))?void 0:r.route.split("?")[0],p=null==(n=[...this.callers.values()].findLast(e=>{var t;return(null==(t=e.performanceTrace)?void 0:t.path)===c}))?void 0:n.performanceTrace;a.performanceTrace={startTime:Date.now(),moduleName:`${t.resourceUrl}#main-thread`,...u?{path:"string"==typeof l.pageUrl?l.pageUrl:String(s.__LOCATION__??"").split("?")[0],pageId:++this.nextPerformancePageId,navigationType:s.__WEB_NAVIGATION_TYPE__??"openPage",referrerPath:null==p?void 0:p.path,referrerPageId:null==p?void 0:p.pageId}:"WIDGET"===t.containerType?{widgetId:"string"==typeof d.widgetId?d.widgetId:void 0,widgetInstanceId:"string"==typeof d.widgetInstanceId?d.widgetInstanceId:void 0,isAppColdLaunch:![...this.callers.values()].some(e=>{var t;return null==(t=e.performanceTrace)?void 0:t.completed})}:{}}}resetApplication(){this.applicationLifecycle.abort(),this.applicationLifecycle=new AbortController,this.performance.reset()}publishPerformance(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];for(let t of this.callers.values())t.events.emitPrivate(e1,{performance:this.performance.snapshot()}),e.length&&t.events.emit(e4,{entries:e})}getCaller(e){let t=this.callers.get(e);if(!t)throw Error("Caller was detached from the RuntimeBridge");return t}async handleMessage(e,t,r){var i;let n=this.getCaller(e);if(!v(t))return{routed:!1};if("applet.subscribeEvent"===t.name||"applet.unsubscribeEvent"===t.name){let e=o(t.params)?t.params:{},i="string"==typeof e.eventName?e.eventName:"",a="applet.subscribeEvent"===t.name&&!n.events.isSubscribed(i);if(tt[t.name](t,{...r,events:n.events}),"applet.subscribeEvent"===t.name&&i===e1&&(null==r?void 0:r.environment)!=="sandbox"){let e=this.resolveStorageNamespace(n,null==r?void 0:r.globalProps,n.fileSystemNamespace??(null==r?void 0:r.fileSystemNamespace));n.events.emitPrivate(i,{performance:this.performance.snapshot(),fileSystemNamespace:e,...ey(e)})}return a&&i&&"number"==typeof e.timestamp&&this.getApplicationEvents().replay(i,e.timestamp,n.send),{routed:!1}}return(null==(i=t.target)?void 0:i.scope)!=="main"||"self"!==t.target.target||!this.router||n.main?{routed:!1}:this.router.call(e,t)}async dispatch(e,t,r,i,n){var a,s,l;let d=arguments.length>5&&void 0!==arguments[5]?arguments[5]:"inline",u=this.callers.get(e);if(!u)return;let c=u.options,p={containerType:n.containerType,element:n.element},h="AppletBridgeModule"===i&&"postMessage"===t;if(h){let e=function(e,t){var r,i;if(!("object"!=typeof(r=e)||null===r||Array.isArray(r))&&"event"===r.type&&"doubao.__widgetInteraction"===r.name&&!("object"!=typeof(i=r.params)||null===i||Array.isArray(i))&&"tap"===i.type&&Number.isSafeInteger(i.sequence)&&"number"==typeof i.sequence&&i.sequence>0)return e7(e,t)}(r,null==c?void 0:c.onWidgetInteraction);if(e)return await e}let m=await this.handleMessage(e,r,n);if(m.routed)return await m.result;let g=await (null==c||null==(a=c.appletSessionMessageHandler)?void 0:a.call(c,r,p));if(null==g?void 0:g.routed)return await g.result;"iframe"!==d&&h&&b(r)&&"__bridge_ready__"===r.name&&(null==c||null==(s=c.onReady)||s.call(c));let f=h&&y(r),w="inline"===d&&"sandbox"!==n.environment;if(f&&w&&"TOOL"!==n.containerType)return u.send(r),r;let S=r=>("iframe"!==d&&"postMessage"===t&&y(r)&&this.callers.get(e)===u&&u.send(r),r);try{if(h&&v(r)&&"sandbox"!==n.environment){let e=o(r.params)?r.params:{};if(r.name===e6){let t=u.performanceTrace?this.performance.recordTiming(u.performanceTrace,e.timing):[];return t.length&&this.publishPerformance(t),S(_(r,{}))}if(r.name===e2)return S(_(r,{entries:(l=this.performance.snapshot(),l.entries.filter(t=>(void 0===e.entryType||t.entryType===e.entryType)&&(void 0===e.name||t.name===e.name)).map(e=>({...e})))}));if(r.name===e3)return this.performance.setBufferSize(e.size),this.publishPerformance(),S(_(r,{}));if("doubao.canIUse"===r.name&&e8.includes(String(e.schema)))return S(_(r,{result:!0}))}let a=this.runtime?this.runtime.nativeModulesCallHandler:null==c?void 0:c.nativeModulesCallHandler,s=await (null==a?void 0:a(t,r,i,p));if(void 0===s&&h&&b(r)&&"__bridge_ready__"!==r.name){this.callers.get(e)===u&&this.getApplicationEvents().publish(r);return}if(f){let e=void 0===s?r:s;if("sandbox"===n.environment||void 0===s&&w)return S(e);return e}let d=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0,r=e.apiRegistry??E;return(i,n,a)=>{if(("AppletJSModule"!==a||"log"!==i)&&"AppletBridgeModule"===a&&"postMessage"===i)return r.dispatch(n,e,t)}}({...n,signal:u.abortController.signal,getAppletContext:null==c?void 0:c.getAppletContext,applicationLifecycle:this.runtime?{owner:this.applicationLifecycle,signal:this.applicationLifecycle.signal}:void 0,fileSystemNamespace:this.resolveStorageNamespace(u,n.globalProps,u.fileSystemNamespace??n.fileSystemNamespace),navigation:this.navigation,apiRegistry:(null==c?void 0:c.apiRegistry)??this.apiRegistry,events:u.events,emitEvent:(e,t)=>u.events.emit(e,t)},null==c?void 0:c.onUnsupportedAPI),m=void 0===s?await d(t,r,i):s;if(h&&v(r)&&r.name===e0&&y(m)&&o(m.params)&&1!==m.params.code){let e=["Synchronous API persistence failed",m.params];a?await a("log",{level:"error",args:e},"AppletJSModule",p):console.error(...e)}return S(m)}catch(e){if("iframe"===d)throw e;return S(v(r)?I(r,e):void 0)}}handleMainBridgeMessage(e){var t;return!this.destroyed&&(null!=(t=this.router)&&!!t.handleMainBridgeMessage(e)||!!b(e)&&"__bridge_ready__"!==e.name&&(this.getApplicationEvents().publish(e),!0))}setVisible(e,t){var r;null==(r=this.callers.get(e))||r.events.setVisible(t)}unregister(e){var t,r,i,n;let a=this.callers.get(e);a&&(this.callers.delete(e),null==(t=a.storage)||t.release(),this.callers.size||(null==(i=this.unsubscribeStorage)||i.call(this),this.unsubscribeStorage=void 0),a.abortController.abort(),a.events.destroy(),null==(r=this.router)||r.cancel(e),a.main||this.destroyed||[...this.callers.values()].some(e=>!e.main)||null==(n=this.onEmpty)||n.call(this))}fail(e){var t;null==(t=this.router)||t.fail(e)}destroy(){var e,t;if(!this.destroyed)for(let r of(this.destroyed=!0,null==(e=this.applicationEvents)||e.release(),this.applicationEvents=void 0,this.applicationLifecycle.abort(),null==(t=this.router)||t.destroy(),this.callers.keys()))this.unregister(r)}}let tv=/(?:^|[.-])[a-f\d]{8,}(?=[.-]|$)/i;function ty(e){let t=new URL(e),r=t.pathname.slice(t.pathname.lastIndexOf("/")+1),i=j();return i&&!tv.test(r)&&t.searchParams.set("__doubao_resource_reload",i),t.href}function tb(e){return"localhost"===e||"::1"===e||/^127(?:\.\d{1,3}){3}$/.test(e)}function tw(e){if(!e.resourceUrl)throw Error("Container.render requires a resourceUrl");return e.resourceUrl}function t_(e){return e.containerType??"PAGE"}function tS(e){return"WIDGET"===e?"content":"fill"}function tx(e){if("function"==typeof CustomEvent)return new CustomEvent("error",{detail:{error:e}});let t=new Event("error");return Object.defineProperty(t,"detail",{value:{error:e}}),t}class tI{container;options;sandboxUrl;targetOrigin;bridge=null;caller;connected=!1;failed=!1;handshakeTimer=null;loaded=!1;loadCount=0;port=null;preparedForRender=!1;preparedContainerType=null;renderMessage=null;view=null;constructor(e){let t=new URL(e.sandboxUrl??"https://apps-web-sdk-sandbox.doubaocdn.com/sandbox");if("https:"!==t.protocol&&!("http:"===t.protocol&&tb(t.hostname)))throw Error("iframe isolation url must use HTTPS (HTTP is only allowed on localhost)");this.container=e.container,this.options=e,this.sandboxUrl=ty(t),this.targetOrigin=t.origin}get element(){return this.view}prepare(e){this.clear();try{this.createView(e),this.preparedForRender=!0}catch(e){throw this.clear(),e}}createView(e){var t,r;if(new URL((null==(t=globalThis.location)?void 0:t.href)??"http://localhost/").origin===this.targetOrigin)return this.abortRender(Error("iframe isolation requires a cross-origin sandbox URL"));if(this.view)return this.preparedContainerType!==e?this.abortRender(Error("iframe container type cannot change after preparation")):this.view;let i=document.createElement("iframe");i.className=this.options.className??"doubao-web-container-view",i.dataset.containerType=e,i.dataset.webSizing=tS(e),i.referrerPolicy="no-referrer",i.title="Doubao app content",i.sandbox.add("allow-scripts","allow-same-origin");let n=tb((null==(r=globalThis.location)?void 0:r.hostname)??"");return n&&i.setAttribute("credentialless",""),i.setAttribute("allow",n?"picture-in-picture 'none'; local-network-access 'src'; loopback-network 'src'":"picture-in-picture 'none'"),i.src=this.sandboxUrl,i.style.display="APP"===e||"TOOL"===e?"none":"block",i.style.border="0",i.style.width="100%",i.style.height="WIDGET"===e?"0px":"100%",i.addEventListener("load",()=>this.handleLoad()),this.view=i,this.preparedContainerType=e,this.container.replaceChildren(i),i}render(e){var t;this.preparedForRender||this.clear(),this.preparedForRender=!1;let r=t_(e),i=new URL(tw(e),document.baseURI).href,n=e.initData??{},a={...G(),...e.globalProps??{}};this.bridge=e.bridge??(null==(t=this.options.runtime)?void 0:t.bridge)??new tf,this.caller=e.bridgeCaller??this.bridge.register(e=>this.sendBridgeMessage(e),e.bridge||this.options.runtime?{...this.options,apiRegistry:void 0}:this.options,"APP"===r);let s=this.bridge,o=this.caller;try{let t=this.createView(r);return s.prepareStorage(o,a,this.options.fileSystemNamespace).then(()=>{var t,l,d;if(this.caller!==o)return;s.beginPerformance(o,{...e,containerType:r,globalProps:a});let u=s.createSyncBridgeData(o,a,this.options.fileSystemNamespace);this.renderMessage={type:"render",captureWidgetTap:this.options.captureWidgetTap,resourceUrl:i,resourceRoot:(null==(t=e.applicationPackage)?void 0:t.resourceRoot)??(null==(d=this.options.runtime)||null==(l=d.packageInfo)?void 0:l.resourceRoot),containerType:r,initData:n,globalProps:a,syncBridgeData:u},this.connected?this.postOrFail(this.renderMessage):this.loaded&&this.connect()}).catch(e=>{this.caller===o&&this.fail(e instanceof Error?e:Error(String(e)))}),t}catch(e){throw this.clear(),e}}clear(){var e,t;this.connected&&this.post({type:"dispose"}),this.destroyChannel(),this.caller&&(null==(t=this.bridge)||t.unregister(this.caller)),this.caller=void 0,this.bridge=null,null==(e=this.view)||e.remove(),this.view=null,this.preparedContainerType=null,this.renderMessage=null,this.connected=!1,this.failed=!1,this.loaded=!1,this.loadCount=0,this.preparedForRender=!1,this.container.replaceChildren()}setVisible(e){if(this.caller){var t;null==(t=this.bridge)||t.setVisible(this.caller,e)}}sendEvent(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.postOrFail({type:"global-event",name:e,params:t})}sendBridgeMessage(e){this.postOrFail({type:"bridge-message",message:e})}sendGlobalEvent(e,t){this.postOrFail({type:"raw-global-event",name:e,params:t})}updateData(e){this.renderMessage&&(this.renderMessage.initData=e),this.postOrFail({type:"update-data",data:e})}updateGlobalProps(e){this.renderMessage&&(this.renderMessage.globalProps={...this.renderMessage.globalProps,...e}),this.postOrFail({type:"update-global-props",props:e})}reload(){this.post({type:"reload"})}abortRender(e){var t,r;throw null==(t=(r=this.options).onError)||t.call(r,e,tx(e)),e}handleLoad(){this.failed||!this.view||((this.loadCount+=1,this.loadCount>1)?this.fail(Error("iframe navigated after the sandbox runtime loaded")):(this.loaded=!0,this.renderMessage&&this.connect()))}connect(){if(this.failed||!this.view||this.connected||this.port)return;let e=new MessageChannel;this.port=e.port1,e.port1.onmessage=e=>this.handleMessage(e),e.port1.onmessageerror=e=>this.fail(Error("iframe message could not be decoded"),e),e.port1.start(),this.handshakeTimer=setTimeout(()=>this.fail(Error("iframe sandbox handshake timed out")),1e4);let t={type:"doubao-web-sdk:connect",protocolVersion:1,sdkVersion:j()??""};try{var r;null==(r=this.view.contentWindow)||r.postMessage(t,this.targetOrigin,[e.port2])}catch(e){this.fail(e instanceof Error?e:Error(String(e)))}}handleMessage(e){var t,r,i;if(!e.data||"object"!=typeof e.data)return void this.fail(Error("iframe sandbox sent an invalid protocol message"),e);let n=e.data;if(!this.connected)return"connected"!==n.type||1!==n.protocolVersion?void this.fail(Error("iframe sandbox protocol version mismatch"),e):(this.connected=!0,this.clearHandshakeTimer(),void(this.renderMessage&&this.postOrFail(this.renderMessage)));switch(n.type){case"ready":null==(t=(r=this.options).onReady)||t.call(r);break;case"error":this.fail(Error(n.message),e);break;case"resize":(null==(i=this.renderMessage)?void 0:i.containerType)!=="WIDGET"||!Number.isFinite(n.height)||n.height<0?this.fail(Error("only Widget containers may resize the iframe"),e):this.view&&(this.view.style.height=`${n.height}px`,this.view.height=String(n.height));break;case"native-call":!Number.isSafeInteger(n.requestId)||n.requestId<=0||("AppletBridgeModule"!==n.moduleName||"postMessage"!==n.name)&&("AppletJSModule"!==n.moduleName&&"LynxConsoleModule"!==n.moduleName&&"Console"!==n.moduleName||"log"!==n.name)?this.fail(Error("iframe sandbox sent an invalid bridge call"),e):this.handleNativeCall(n);break;case"connected":this.fail(Error("iframe sandbox connected more than once"),e);break;default:this.fail(Error("iframe sandbox sent an invalid protocol message"),e)}}async handleNativeCall(e){let t;if(!this.renderMessage||!this.view)return;let r=this.bridge,i=this.caller;if(r&&i){try{t=await r.dispatch(i,e.name,e.data,e.moduleName,{containerType:this.renderMessage.containerType,element:this.view,globalProps:this.renderMessage.globalProps,fileSystemNamespace:this.renderMessage.syncBridgeData.fileSystemNamespace},"iframe")}catch(t){if(this.bridge!==r||this.caller!==i)return;this.postOrFail({type:"bridge-result",requestId:e.requestId,error:x(t)});return}this.bridge===r&&this.caller===i&&this.postOrFail({type:"bridge-result",requestId:e.requestId,result:t})}}post(e){this.connected&&this.port&&this.port.postMessage(e)}postOrFail(e){try{this.post(e)}catch(e){this.fail(e instanceof Error?e:Error(String(e)))}}fail(e){var t,r,i,n;let a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tx(e);this.failed||(this.failed=!0,this.destroyChannel(),this.caller&&(null==(n=this.bridge)||n.unregister(this.caller)),this.caller=void 0,this.bridge=null,null==(t=this.view)||t.remove(),this.view=null,this.renderMessage=null,null==(r=(i=this.options).onError)||r.call(i,e,a))}clearHandshakeTimer(){null!==this.handshakeTimer&&clearTimeout(this.handshakeTimer),this.handshakeTimer=null}destroyChannel(){var e;this.clearHandshakeTimer(),null==(e=this.port)||e.close(),this.port=null,this.connected=!1}}let tk={mode:"iframe",createContainer:e=>new tI(e)};function tC(){var e;return(null==(e=globalThis.location)?void 0:e.href)??"http://localhost/"}function tE(e){return new URL(e,tC()).toString()}function tN(e,t){if(!t)return e;let r=new URL(e,tC());return r.searchParams.set("__doubao_resource_reload",t),r.toString()}class tT{options;packages=new Map;resolveManifestUrl;resourceUrlVersion;constructor(e={}){this.options=e,this.resolveManifestUrl=e.resolveManifestUrl,this.resourceUrlVersion=e.resourceUrlVersion}configure(e){e.resolveManifestUrl&&(this.resolveManifestUrl=e.resolveManifestUrl),"resourceUrlVersion"in e&&(this.resourceUrlVersion=e.resourceUrlVersion)}async getPackageSource(e){if(arguments.length>1&&void 0!==arguments[1]&&arguments[1],!this.resolveManifestUrl)throw Error("PackageManager requires resolveManifestUrl");return{manifestUrl:await this.resolveManifestUrl({appId:e})}}cached(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};r.signal&&g(r.signal);let i=this.packages.get(e);return(!i||r.forceReload)&&(i=t(),this.packages.set(e,i),i.catch(()=>{this.packages.get(e)===i&&this.packages.delete(e)})),r.signal?f(()=>i,r.signal):i}async fetchPackage(e,t){return{manifestUrl:e,resourceRoot:t,manifest:await p(e,{fetcher:this.options.fetcher})}}async loadPackage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t.signal&&g(t.signal);let{manifestUrl:r,resourceRoot:i}=await this.getPackageSource(e,t),n=tE(r),a=await this.cached(n,()=>this.fetchPackage(n,i),t);if(e&&a.manifest.appId&&a.manifest.appId!==e)throw Error("Resolved package appId must match the requested application");return a}resolveWidget(e,t){let r=this.tryResolveWidgetFromPackage(e,t),i=e.manifest.appRuntimeEntry?h(e.manifestUrl,e.manifest.appRuntimeEntry):void 0;return{packageInfo:e,appId:e.manifest.appId,appName:(null==r?void 0:r.appName)??e.manifest.name,icon:(null==r?void 0:r.iconSrc)??e.manifest.iconSrc,appRuntimeEntry:i?tN(i,e.resourceUrlVersion??this.resourceUrlVersion):void 0,resourceUrl:(null==r?void 0:r.resourceUrl)??"",titleType:null==r?void 0:r.entry.titleType,boxType:null==r?void 0:r.entry.boxType}}preload(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.loadPackage(e,t)}setPackage(e){this.packages.set(tE(e.manifestUrl),Promise.resolve(e))}deletePackage(e){this.packages.delete(tE(e))}clearPackageCache(e){e?this.deletePackage(e):this.packages.clear()}resolveWidgetEntry(e,t){let r=e.manifest.name??t.name,i=h(e.manifestUrl,t);return{appId:e.manifest.appId,entry:t,iconSrc:e.manifest.iconSrc??u(t.icons),appName:r,resourceUrl:i?tN(i,e.resourceUrlVersion??this.resourceUrlVersion):void 0}}tryResolveWidgetFromPackage(e,t){let r=e.manifest.getOptionalWidgetEntry(t);if(r)return this.resolveWidgetEntry(e,r)}}class tA{send;ready;pendingCalls=new Map;destroyed=!1;nextCallbackId=1e6;constructor(e,t){this.send=e,this.ready=t}call(e,t){if(this.destroyed)return Promise.reject(Error("RuntimeRouter was destroyed"));let r=this.nextCallbackId++,i={...t,callbackId:r};return new Promise((n,a)=>{this.pendingCalls.set(r,{callbackId:t.callbackId,reject:a,resolve:n,caller:e}),(async()=>{try{await this.ready(),this.pendingCalls.has(r)&&this.send(i)}catch(t){let e=this.pendingCalls.get(r);if(!e)return;this.pendingCalls.delete(r),e.reject(t instanceof Error?t:Error(String(t)))}})()})}handleMainBridgeMessage(e){if(y(e)){let t=this.pendingCalls.get(e.callbackId);return!!t&&(this.pendingCalls.delete(e.callbackId),t.resolve({routed:!0,result:{...e,callbackId:t.callbackId}}),!0)}return!1}cancel(e){for(let[t,r]of this.pendingCalls)r.caller===e&&(this.pendingCalls.delete(t),r.reject(Error("Caller was detached from the RuntimeBridge")))}destroy(){this.destroyed||(this.destroyed=!0,this.fail(Error("RuntimeRouter was destroyed")))}fail(e){for(let t of this.pendingCalls.values())t.reject(e);this.pendingCalls.clear()}}let tM="onBackground",tj="onDestroy",tR="onForeground",tP="onHide",tL="onShow";function tD(e,t){let r=function(e){let{pageId:t,viewData:r}=function(e){if(!e)throw Error("route url must be a non-empty string");let t=e.indexOf("?"),r=-1===t?e:e.slice(0,t);if(!r)throw Error("route url must include a page path");let i={};return new URLSearchParams(-1===t?"":e.slice(t+1)).forEach((e,t)=>{i[t]=e}),{pageId:r,viewData:i}}(e.url),i=JSON.stringify(r);return{pageId:t,initData:{viewData:r,viewContext:{}},globalProps:{__LOCATION__:e.url,__RENDER_DATA__:i,__VIEW_CONTEXT__:{}}}}(e);return{...r,entry:t.getPageEntry(r.pageId)}}function tO(e,t){var r;let i=Object.entries((null==(r=t.initData)?void 0:r.viewData)??{}).map(e=>{let[t,r]=e;return`${encodeURIComponent(t)}=${encodeURIComponent(r)}`}).join("&");return{route:`${e}${i?`?${i}`:""}`}}function tU(e,t){return{packageInfo:t,...e}}function t$(e){return{appId:e.appId,name:e.name,iconSrc:e.iconSrc,versionName:e.versionName}}function tq(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return tU(t,t$(e))}function tB(e){if(o(e))return{...e};if("string"!=typeof e)return{};try{let t=JSON.parse(e);return o(t)?t:{}}catch{return{}}}class tF{pageHost;visible=!0;className;onError;appGlobalProps;appInitData;getRuntimeGlobalProps;configuredFileSystemNamespace;userId;runtimeKernel;packageSnapshot;packageLoading;packageSource;lifecycle=new AbortController;get packageInfo(){if(this.destroyed)throw Error("Runtime was destroyed");if(!this.packageSnapshot)throw Error("Runtime package is not loaded");return this.packageSnapshot}get manifest(){return this.packageInfo.manifest}get manifestUrl(){return this.packageInfo.manifestUrl}pageCapsule;resolvedFileSystemNamespace;appRuntime=null;appStart=null;bridge;packageManager;sandboxUrl;viewContext;appGroupId;destroyed=!1;pendingAppEvents=[];clearingAppRuntime=!1;appCallController=new AbortController;apiContextOwner={};stack=[];pendingPages=[];nextPageIndex=0;constructor(e,t=tk,r){this.sandboxUrl=e.sandboxUrl,this.packageManager=e.packageManager??new tT({resolveManifestUrl:()=>this.manifestUrl});let i=new tA(e=>this.sendAppBridgeMessage(e),async()=>{if(await this.ensureAppRuntime(),!this.appStart)throw Error("No Web entry configured for app runtime");return this.appStart.promise});this.appGroupId=e.appGroupId,this.viewContext=e.viewContext,this.pageHost=e.pageHost,this.runtimeKernel=t,"manifest"in e?(this.packageSnapshot={manifest:e.manifest,manifestUrl:String(e.manifestUrl),resourceRoot:e.resourceRoot,resourceUrlVersion:""},e.packageManager||this.packageManager.setPackage(this.packageSnapshot)):this.packageSource=e,this.pageCapsule=e.pageCapsule,this.className=e.className,this.onError=e.onError,this.appGlobalProps=e.appGlobalProps,this.appInitData=e.appInitData,this.getRuntimeGlobalProps=e.getRuntimeGlobalProps,this.configuredFileSystemNamespace=e.fileSystemNamespace,this.userId=e.userId,this.resolvedFileSystemNamespace=this.resolveFileSystemNamespace(),this.updateEmptyState(),this.bridge=new tf(i,{getCurrentPages:()=>this.getCurrentPages(),getPackageInfo:()=>this.getPackageInfo(),navigateTo:e=>this.navigateToBridgePage(e),openPage:e=>this.openBridgePage(e),redirectTo:e=>this.redirectToBridgePage(e),reLaunch:e=>this.reLaunchBridgePage(e),navigateBack:e=>this.requestBack(e),setAlertBeforeUnload:(e,t)=>{let r=this.stack.find(e=>e.element===t);return!!r&&(r.alertBeforeUnloadMessage=e,!0)},exitApp:()=>this.exitBridgeApp()},r,{apiRegistry:e.apiRegistry,getFileSystemNamespace:()=>this.fileSystemNamespace,nativeModulesCallHandler:e.nativeModulesCallHandler})}async loadPackage(){var e,t;if(this.destroyed)throw new DOMException("Runtime was destroyed","AbortError");let r=(null==(e=this.packageSource)?void 0:e.signal)?AbortSignal.any([this.lifecycle.signal,this.packageSource.signal]):this.lifecycle.signal;if(!this.packageSnapshot){if(!this.packageLoading){let e=this.packageSource,i=this.packageManager.loadPackage(e.appId,{signal:r,versionTag:e.versionTag??(null==(t=e.viewContext)?void 0:t.versionTag)}).then(e=>{g(r),this.destroyed||this.packageSnapshot||(this.packageSnapshot={...e,resourceUrlVersion:""},this.resolvedFileSystemNamespace=this.resolveFileSystemNamespace())}).catch(e=>{throw this.packageLoading===i&&(this.packageLoading=void 0),e});this.packageLoading=i}let e=this.packageLoading;await f(()=>e,r)}return g(r),this.packageInfo}get fileSystemNamespace(){return this.resolvedFileSystemNamespace}get isDestroyed(){return this.destroyed}get pages(){return this.stack.map(e=>this.toStackEntry(e))}get currentPage(){let e=this.getCurrentStackItem();return e?this.toStackEntry(e):null}setManifest(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.manifestUrl;this.clear(),this.packageSnapshot={...this.packageSnapshot,manifest:e,manifestUrl:String(r),resourceUrlVersion:(null==(t=this.packageSnapshot)?void 0:t.resourceUrlVersion)??"1"},this.packageManager.setPackage(this.packageSnapshot),this.resolvedFileSystemNamespace=this.resolveFileSystemNamespace()}async pushPage(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.packageSnapshot||await this.loadPackage(),this.pushLoadedPage(e)}async pushLoadedPage(e,t){var r,i,n;let a;if(this.destroyed)throw Error("Runtime was destroyed");if(!this.pageHost)throw Error("Opening Pages requires a Runtime pageHost");let s=this.resolvePageEntry(e),l=h(this.manifestUrl,s);if(!l)throw Error(`No Web entry configured for page entry: ${s.id}`);let d=this.lifecycle.signal;if(this.startAppRuntime(),this.appStart&&await this.appStart.promise,g(d),"all"===t)this.clearPages();else if("current"===t){let e=this.stack.pop();e&&this.removeStackItem(e,!1)}let u={...e,globalProps:{...e.globalProps,...null==(r=this.getRuntimeGlobalProps)?void 0:r.call(this)}},c=tN(l,this.packageInfo.resourceUrlVersion),p=e.pageCapsule??this.pageCapsule,m=`page-${++this.nextPageIndex}`,f=(a=tB(null==(n=u.globalProps)?void 0:n.__VIEW_CONTEXT__),{...o(u.initData)?tB(u.initData.viewContext):{},...a,viewId:m,pageName:s.id,pageUrl:s.path}),v=null,y=this.pageHost.createPage({className:this.className,runtime:this,onError:this.onError,onReady:()=>{v&&this.stack.includes(v)&&(v.isReady=!0,this.flushPageLifecycleEvents(v))}},this.runtimeKernel,()=>this.exitBridgeApp());void 0!==e.pageCapsule&&(this.pageCapsule=e.pageCapsule),this.pendingPages.push(tO(s.path,e));try{let t,r,n=y.render({resourceUrl:c,groupId:this.manifest.appId,initData:o(u.initData)?{...u.initData,viewContext:f}:{viewContext:f},globalProps:(t=null==p?void 0:p.statusBarHeight,r="number"==typeof t&&Number.isFinite(t)?{statusBarHeight:t}:{},{...u.globalProps,...r,__VIEW_CONTEXT__:f}),pageCapsule:p}),a=this.getCurrentStackItem();return a&&(null==(i=a.backPrompt)||i.abort(),this.visible&&this.sendPageLifecycleEvent(a,tP),a.page.setVisible(!1)),v={id:m,pageId:s.id,route:s.path,resourceUrl:c,entry:s,element:n,isReady:!1,options:{...e,entry:s,pageCapsule:p},pendingLifecycleEvents:[],page:y},this.stack.push(v),this.updateEmptyState(),v.page.setVisible(this.visible),this.visible&&this.sendPageLifecycleEvent(v,tL),this.sendAppEvent("onPageOpened",{viewId:v.id}),this.toStackEntry(v)}catch(e){throw y.clear(),this.updateEmptyState(),e}finally{this.pendingPages.pop()}}async replacePage(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this.packageSnapshot||await this.loadPackage(),this.destroyed)throw Error("Runtime was destroyed");return this.withPageTransition(()=>this.pushLoadedPage(e,"current"))}async reLaunchPage(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this.packageSnapshot||await this.loadPackage(),this.destroyed)throw Error("Runtime was destroyed");return this.withPageTransition(()=>this.pushLoadedPage(e,"all"))}popPage(){let e=this.stack.pop();return e?this.removeStackItem(e,!0):null}setVisible(e){if(this.destroyed||this.visible===e)return;this.visible=e;let t=this.getCurrentStackItem();t&&(t.page.setVisible(e),this.sendPageLifecycleEvent(t,e?tL:tP)),this.appRuntime&&this.sendAppEvent(e?tR:tM)}requestBack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.getCurrentStackItem();if(!t)return!1;if(1===this.stack.length){var r;return this.setVisible(!1),null==(r=this.pageHost)||r.hide(),!0}let i=()=>{if(this.destroyed||this.getCurrentStackItem()!==t)return;let r=Math.min(Math.max(1,Math.floor(e.delta??1)),this.stack.length-1);for(let e=0;e<r;e+=1)this.popPage()};if(void 0===t.alertBeforeUnloadMessage||!this.pageHost)return i(),!0;if(!t.backPrompt||t.backPrompt.signal.aborted){let e=new AbortController;t.backPrompt=e;let r=r=>{t.backPrompt===e&&(t.backPrompt=void 0,r&&!e.signal.aborted&&i())};this.pageHost.confirmBeforeUnload(t.alertBeforeUnloadMessage,e.signal).then(e=>{r(e)},()=>{r(!0)})}return!0}clear(){this.lifecycle.abort(),this.lifecycle=new AbortController,this.packageLoading=void 0,this.clearPages(),this.clearAppRuntime(),this.bridge.resetApplication(),this.packageSnapshot&&(this.packageSnapshot={...this.packageSnapshot,resourceUrlVersion:String(Number(this.packageSnapshot.resourceUrlVersion??0)+1)})}async restart(){if(this.packageSnapshot||await this.loadPackage(),this.destroyed)throw Error("Runtime was destroyed");await this.withPageTransition(async()=>{let e=this.stack.map(e=>{let{options:t}=e;return t});for(let t of(this.clear(),e))await this.pushLoadedPage(t)})}reload(){var e;null==(e=this.getCurrentStackItem())||e.page.reload()}destroy(){var e;this.destroyed||(this.destroyed=!0,this.bridge.destroy(),this.clear(),null==(e=this.pageHost)||e.destroy())}clearPages(){for(;this.stack.length>0;){let e=this.stack.pop();e&&this.removeStackItem(e,!1)}}async withPageTransition(e){let t=this.bridge.register();try{return await e()}finally{this.bridge.unregister(t)}}removeStackItem(e,t){var r;null==(r=e.backPrompt)||r.abort();let i=this.toStackEntry(e);this.sendPageLifecycleEvent(e,tj),e.page.clear();let n=this.getCurrentStackItem();return t&&n&&this.visible&&(n.page.setVisible(!0),this.sendPageLifecycleEvent(n,tL)),this.updateEmptyState(),i}async ensureAppRuntime(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.packageSnapshot||await this.loadPackage(),this.startAppRuntime(e)}startAppRuntime(){var e,t,r;let i,n,a,s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this.destroyed)throw Error("Runtime was destroyed");if(this.clearingAppRuntime)throw Error("Runtime is being cleared");if(null==(e=this.appStart)?void 0:e.error)throw this.appStart.error;if(this.appRuntime||!this.manifest.appRuntimeEntry)return;let o=h(this.manifestUrl,this.manifest.appRuntimeEntry);if(!o)throw Error("No Web entry configured for app runtime");let l=tN(o,this.packageInfo.resourceUrlVersion),d=new Promise((e,t)=>{i=e,n=t});d.catch(()=>{});let u={promise:d,resolve:i,reject:n,error:void 0};this.appStart=u;let c=e=>{var t;this.appStart!==u||this.destroyed||this.clearingAppRuntime||((null==(t=this.appRuntime)?void 0:t.isReady)||(u.error=e,u.reject(e)),this.bridge.fail(e))},p=this.appCallController.signal;try{a=function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:document.body,i=document.createElement("div");i.className="doubao-runtime-app",i.hidden=!0,i.style.display="none";let n=t.createContainer({...e,container:i});return{render:e=>(r.append(i),n.render(e)),clear(){n.clear(),i.remove()},sendEvent:n.sendEvent.bind(n),sendBridgeMessage:n.sendBridgeMessage.bind(n)}}({runtime:this,sandboxUrl:this.sandboxUrl,className:this.className,onError:(e,t)=>{var r;this.appStart!==u||this.destroyed||this.clearingAppRuntime||(c(e),null==(r=this.onError)||r.call(this,e,t))},appletSessionMessageHandler:(e,t)=>{var r;return this.appStart!==u||this.destroyed||this.clearingAppRuntime||this.bridge.handleMainBridgeMessage(e)?{routed:!0}:(null==(r=s.appletSessionMessageHandler)?void 0:r.call(s,e,t))??{routed:!1}},getAppletContext:()=>({owner:this.apiContextOwner,signal:p,source:"app",viewContext:s.viewContext??this.viewContext}),onReady:()=>{var e;let t=this.appRuntime;this.clearingAppRuntime||!t||t.container!==a||t.isReady||u.error||(t.isReady=!0,this.flushAppEvents(),u.resolve(),null==(e=s.onReady)||e.call(s))}},this.runtimeKernel,null==(t=this.pageHost)?void 0:t.container),this.appRuntime={container:a,isReady:!1,pendingEvents:[{name:this.visible?tR:tM,params:{}},...this.pendingAppEvents.splice(0)]};let e=void 0!==s.groupId?s.groupId:this.appGroupId;a.render({bridge:this.bridge,resourceUrl:l,groupId:null===e?void 0:e??this.manifest.appId,containerType:"APP",initData:this.appInitData??{},globalProps:{...tq(this.manifest,this.appGlobalProps),...null==(r=this.getRuntimeGlobalProps)?void 0:r.call(this)}})}catch(e){throw c(e instanceof Error?e:Error(String(e))),this.appRuntime=null,null==a||a.clear(),e}}clearAppRuntime(){var e;if(this.clearingAppRuntime)return;this.clearingAppRuntime=!0;let t=Error(this.destroyed?"Runtime was destroyed":"Runtime was cleared");null==(e=this.appStart)||e.reject(t),this.bridge.fail(t),this.pendingAppEvents=[];let r=this.appRuntime;(null==r?void 0:r.isReady)&&(this.visible&&r.container.sendEvent(tM),r.container.sendEvent(tj)),null==r||r.container.clear(),this.appCallController.abort(),this.appCallController=new AbortController,this.appRuntime=null,this.appStart=null,this.clearingAppRuntime=!1}sendAppEvent(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=this.appRuntime;if(!this.destroyed&&!this.clearingAppRuntime){if(!r)return void this.pendingAppEvents.push({name:e,params:t});if(!r.isReady)return void r.pendingEvents.push({name:e,params:t});r.container.sendEvent(e,t)}}sendAppBridgeMessage(e){if(!this.clearingAppRuntime){var t;null==(t=this.appRuntime)||t.container.sendBridgeMessage(e)}}flushAppEvents(){let e=this.appRuntime;if(null==e?void 0:e.isReady)for(let t of e.pendingEvents.splice(0))e.container.sendEvent(t.name,t.params)}sendPageLifecycleEvent(e,t){let r,i=(r={viewId:e.id,pageName:e.pageId,pageUrl:e.route},{viewId:e.id,eventName:JSON.stringify(r)});e.isReady?e.page.sendEvent(t,i):e.pendingLifecycleEvents.push({name:t,params:i})}flushPageLifecycleEvents(e){if(e.isReady)for(let t of e.pendingLifecycleEvents.splice(0))e.page.sendEvent(t.name,t.params)}resolvePageEntry(e){return e.entry??this.manifest.getPageEntry(e.pageId)}resolveRoutePageOptions(e){try{return tD(e,this.manifest)}catch(e){throw Object.assign(new w(e instanceof Error?e.message:String(e),104),{cause:e})}}getCurrentStackItem(){return this.stack[this.stack.length-1]??null}updateEmptyState(){var e;null==(e=this.pageHost)||e.setEmpty(0===this.stack.length)}getCurrentPages(){return[...this.stack.map(e=>tO(e.route,e.options)),...this.pendingPages]}getPackageInfo(){var e;return this.packageSnapshot?t$(this.manifest):{appId:null==(e=this.packageSource)?void 0:e.appId}}resolveFileSystemNamespace(){return void 0!==this.configuredFileSystemNamespace?this.configuredFileSystemNamespace:eu({packageInfo:this.getPackageInfo()},this.userId)}withNavigationType(e,t){return{...e,globalProps:{...e.globalProps,__WEB_NAVIGATION_TYPE__:t}}}async openBridgePage(e){this.packageSnapshot||await this.loadPackage();let t=this.resolveRoutePageOptions(e),r=this.resolvePageEntry(t),i=e.mode??"push",n=this.getCurrentStackItem(),a=e=>e.entry.path===r.path,s="replace"===i?n&&a(n)?this.stack.length-1:-1:"navigate"===i||"pop_to"===i?this.stack.findLastIndex(a):-1;if(s>=0){var o;let e=this.stack[s],r=t.globalProps??{};for(e.page.updateGlobalProps({__LOCATION__:r.__LOCATION__,__RENDER_DATA__:r.__RENDER_DATA__}),e.options={...e.options,initData:t.initData,globalProps:{...e.options.globalProps,...r}},null==(o=e.backPrompt)||o.abort();this.stack.length-1>s;)this.removeStackItem(this.stack.pop(),!1);e.page.setVisible(this.visible),n!==e&&this.visible&&this.sendPageLifecycleEvent(e,tL);let i=this.getCurrentPages();for(let e of this.stack)e.page.sendEvent(e1,{apiResults:{"doubao.getCurrentPages":{pages:i}}});this.updateEmptyState();return}"replace"===i||"pop_to"===i?await this.replacePage(t):await this.pushLoadedPage(t)}async navigateToBridgePage(e){this.packageSnapshot||await this.loadPackage(),await this.pushLoadedPage(this.withNavigationType(this.resolveRoutePageOptions(e),"navigateTo"))}async redirectToBridgePage(e){this.packageSnapshot||await this.loadPackage();let t=this.withNavigationType(this.resolveRoutePageOptions(e),"redirectTo");await this.replacePage(t)}async reLaunchBridgePage(e){this.packageSnapshot||await this.loadPackage();let t=this.withNavigationType(this.resolveRoutePageOptions(e),"reLaunch");await this.reLaunchPage(t)}exitBridgeApp(){this.clear()}toStackEntry(e){return{id:e.id,pageId:e.pageId,route:e.route,url:tO(e.route,e.options).route,resourceUrl:e.resourceUrl,entry:e.entry,element:e.element}}}class tW{kernel;autoRelease;runtimes=new Map;packageManagers=new WeakMap;nextPackageManagerId=0;constructor(e,t=!1){this.kernel=e,this.autoRelease=t}acquire(e){var t,r,i,n,a,s,o,l,d,u;let p=e.fileSystemNamespace??eu({packageInfo:{appId:e.appId}},e.userId),h=new URL(e.appRuntimeEntry,null==(t=globalThis.location)?void 0:t.href).href,m=e.packageManager;m&&!this.packageManagers.has(m)&&this.packageManagers.set(m,this.nextPackageManagerId++);let g=[m?this.packageManagers.get(m):"",String(e.sandboxUrl??""),(null==(r=e.packageInfo)?void 0:r.manifestUrl)??"",(null==(i=e.packageInfo)?void 0:i.resourceRoot)??"",e.appId,(null==(n=e.viewContext)?void 0:n.conversationId)??"",p,e.versionTag??(null==(a=e.viewContext)?void 0:a.versionTag)??"",h].join("\0"),f=this.runtimes.get(g);if(f&&!f.isDestroyed)return f;let v=new tF({packageManager:m,pageHost:e.pageHost,sandboxUrl:e.sandboxUrl,manifest:(null==(s=e.packageInfo)?void 0:s.manifest)??new c({manifestVersion:"3.0",packageName:e.appId,appId:e.appId,versionCode:"",applet:{appletId:e.appId,digest:"",appRuntimeEntry:h,pages:[]},widgets:[]}),manifestUrl:(null==(o=e.packageInfo)?void 0:o.manifestUrl)??h,resourceRoot:null==(l=e.packageInfo)?void 0:l.resourceRoot,registerPageController:!1,appGroupId:null,apiRegistry:e.apiRegistry??E,className:e.className,fileSystemNamespace:p,nativeModulesCallHandler:e.nativeModulesCallHandler,appInitData:e.appInitData,appGlobalProps:tU(e.appGlobalProps??{},{appId:e.appId}),getRuntimeGlobalProps:e.getRuntimeGlobalProps,viewContext:{appId:e.appId,conversationId:null==(d=e.viewContext)?void 0:d.conversationId,versionTag:e.versionTag??(null==(u=e.viewContext)?void 0:u.versionTag)},onError:e.onError},this.kernel??tk,this.autoRelease?()=>this.release(v):void 0);return this.runtimes.set(g,v),v}release(e){for(let[t,r]of this.runtimes)if(r===e){this.runtimes.delete(t),e.destroy();return}}destroy(){let e=[...this.runtimes.values()];for(let t of(this.runtimes.clear(),e))t.destroy()}}function tz(e,t){return class extends e{hostOptions;prepared=!1;constructor(e){super({...e,sandboxUrl:e.runtime?e.runtime.sandboxUrl:e.sandboxUrl}),this.hostOptions=e}prepare(e){super.prepare(e),this.prepared=!0}clear(){this.prepared=!1,super.clear()}render(e){var r,i,n;this.prepared||this.clear(),this.prepared=!1;let{application:a,applicationPackage:s,appRuntimeEntry:o,...l}=e,d=(null==a?void 0:a.appId)??(null==(i=l.globalProps)||null==(r=i.packageInfo)?void 0:r.appId),u=(null==a?void 0:a.appRuntimeEntry)??o,c=(null==a?void 0:a.viewContext)??(null==(n=l.globalProps)?void 0:n.__VIEW_CONTEXT__),p=this.hostOptions.runtime??(d&&u?(this.hostOptions.runtimeManager??t()).acquire({appId:d,appRuntimeEntry:u,packageInfo:s,packageManager:this.hostOptions.packageManager,sandboxUrl:this.hostOptions.sandboxUrl,apiRegistry:this.hostOptions.apiRegistry,nativeModulesCallHandler:this.hostOptions.nativeModulesCallHandler,versionTag:(null==a?void 0:a.versionTag)??(null==c?void 0:c.versionTag),viewContext:c,userId:this.hostOptions.userId,fileSystemNamespace:this.hostOptions.fileSystemNamespace}):void 0),h=null==p?void 0:p.bridge.register();try{return super.render({...l,applicationPackage:s,bridge:(null==p?void 0:p.bridge)??l.bridge})}catch(e){throw this.clear(),e}finally{h&&(null==p||p.bridge.unregister(h))}}}}new tW(void 0,!0),r(34974),r(71463),r(25907),r(92151);var tH=r(59314);let tV="embed-webview",tG="__channel_ack__",tJ=new WeakMap,tK=e=>({url:e});function tZ(e){if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}}function tX(e){return"string"==typeof e?e:JSON.stringify(e??{})}let tY=globalThis.HTMLElement??class{},tQ="region-to-decode";function t0(e){if("string"==typeof e)try{e=JSON.parse(e)}catch{return null}if(!e||"object"!=typeof e)return null;let{x:t,y:r,width:i,height:n}=e;return![t,r,i,n].every(Number.isFinite)||t<0||r<0||i<=0||n<=0?null:{x:t,y:r,width:i,height:n}}class t1{element;static observedAttributes=[];image;attributes=new MutationObserver(()=>this.update());resize;viewSize;cropStyle;constructor(e){var t;this.element=e,this.image=(null==(t=e.shadowRoot)?void 0:t.querySelector("#img"))??null,Object.defineProperty(e,tQ,{configurable:!0,get:()=>t0(e.getAttribute(tQ)),set:t=>{let r=t0(t);r?e.setAttribute(tQ,JSON.stringify(r)):e.removeAttribute(tQ)}})}connectedCallback(){this.attributes.observe(this.element,{attributes:!0,attributeFilter:[tQ,"src","mode","auto-size"]}),this.update()}clearCrop=()=>{var e;null==(e=this.cropStyle)||e.remove(),this.cropStyle=void 0};stopRendering(){var e,t,r;null==(e=this.resize)||e.disconnect(),this.resize=void 0,this.viewSize=void 0,null==(t=this.image)||t.removeEventListener("load",this.update),null==(r=this.image)||r.removeEventListener("error",this.clearCrop),this.clearCrop()}update=()=>{var e,t,r;let i=t0(this.element.getAttribute(tQ)),n=this.image;if(!i||!n)return void this.stopRendering();this.resize||(this.resize=new ResizeObserver(e=>{let[t]=e;this.viewSize=t.contentRect,this.update()}),this.resize.observe(this.element),n.addEventListener("load",this.update),n.addEventListener("error",this.clearCrop));let a=n.naturalWidth,s=n.naturalHeight,o=this.element.getAttribute("src"),l=this.element.getRootNode().host,d=o?(null==l||null==(e=l.resolveResource)?void 0:e.call(l,o))??o:o;if(!n.complete||!a||!s||n.getAttribute("src")!==d)return void this.clearCrop();let u=Math.min(i.width,a-i.x),c=Math.min(i.height,s-i.y),p=getComputedStyle(this.element),h=Number.parseFloat(p.paddingLeft)||0,m=Number.parseFloat(p.paddingTop)||0,g=(null==(t=this.viewSize)?void 0:t.width)??this.element.clientWidth-h-(Number.parseFloat(p.paddingRight)||0),f=(null==(r=this.viewSize)?void 0:r.height)??this.element.clientHeight-m-(Number.parseFloat(p.paddingBottom)||0);if(u<=0||c<=0||g<=0||f<=0)return void this.clearCrop();let v=g/u,y=f/c,b=this.element.getAttribute("mode");"aspectFit"===b?v=y=Math.min(v,y):"aspectFill"===b?v=y=Math.max(v,y):"center"===b&&(v=y=1);let w=h+(g-u*v)/2-i.x*v,_=m+(f-c*y)/2-i.y*y;this.cropStyle||(this.cropStyle=this.element.ownerDocument.createElement("style"),this.cropStyle.setAttribute("data-doubao-image-region",""),this.element.shadowRoot.append(this.cropStyle)),this.cropStyle.textContent=`#img {
|
|
1
|
+
(()=>{"use strict";var e,t,r,i,n,a,s,o,l,d,u,c,p={38114(e,t,r){let i,n,a;r(52205),r(40768),r(76235),r(15254),r(42949),r(18723),r(37891);var s=r(63159);function o(e){return"object"==typeof e&&null!==e}function l(e){var t;return"string"==typeof(null==(t=e.web)?void 0:t.entry)}function d(e,t){let r=new Map;for(let i of e){let e=t(i);e&&!r.has(e)&&r.set(e,i)}return r}function u(e){return"string"==typeof e?e||void 0:(null==e?void 0:e["3x"])||(null==e?void 0:e["2x"])||(null==e?void 0:e["1x"])}r(84086),r(21301),r(49678),r(32037),r(14104),r(66249),r(99811),r(40009),r(13035),r(13412),r(17973),r(64955),r(91016),r(23306),r(76619),r(57857),r(9975),r(93885),r(812),r(74180),r(994),r(4267),r(74678),r(55910),r(76691),r(72919);class c{raw;appEntry;pageEntries;pageIdEntryMap;pagePathEntryMap;widgetEntries;widgetEntryMap;constructor(e){var t;let r;this.raw=e,this.appEntry="string"==typeof(r=(null==(t=e.applet.web)?void 0:t.appRuntimeEntry)??e.applet.appRuntimeEntry)&&r?{entry:r}:null,this.pageEntries=e.applet.pages.filter(l),this.pageIdEntryMap=d(this.pageEntries,e=>e.id),this.pagePathEntryMap=d(this.pageEntries,e=>{var t;return(null==(t=e.path)?void 0:t.startsWith("/"))?e.path:void 0}),this.widgetEntries=e.widgets,this.widgetEntryMap=d(this.widgetEntries,e=>e.widgetId)}get appId(){return"string"==typeof this.raw.appId?this.raw.appId:void 0}get name(){return this.raw.applet.name}get iconSrc(){return u(this.raw.applet.icons)}get versionName(){return this.raw.versionName||this.raw.versionTag||this.raw.versionCode||void 0}get pages(){return this.getPageEntries()}get widgets(){return this.getWidgetEntries()}get appRuntimeEntry(){return this.appEntry}getPageEntries(){return[...this.pageEntries]}getWidgetEntries(){return[...this.widgetEntries]}getOptionalWidgetEntry(e){return e?this.widgetEntryMap.get(e):this.widgetEntries[0]}getPageEntry(e){let t=e?e.startsWith("/")?this.pagePathEntryMap.get(e):this.pageIdEntryMap.get(e):this.pageEntries[0];if(!t)throw Error(e?`Unknown pages entry: ${e}`:"No pages entries in Web manifest");return t}getWidgetEntry(e){let t=this.getOptionalWidgetEntry(e);if(!t)throw Error(e?`Unknown widgets entry: ${e}`:"No widgets entries in Web manifest");return t}}async function p(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.fetcher??fetch,i=await r(e,{cache:"no-store",headers:{Accept:"application/json"}});if(!i.ok)throw Error(`Failed to load Web manifest: ${i.status} ${i.statusText}`);let n=await i.json();if(!o(n))throw Error("Invalid Web manifest: expected a JSON object");return new c(n)}function h(e,t,r){var i,n;let a="item"in t?t.item:t,s="id"in a||"widgetId"in a?"string"==typeof(null==(i=a.web)?void 0:i.entry)?a.web.entry:void 0:a.entry;if(!s)return;let o=new URL(e,r??(null==(n=globalThis.location)?void 0:n.href)??"http://localhost/");return o.pathname=o.pathname.replace(/\/base\/manifest\.json$/,"/"),new URL(s,o).toString()}function m(){let e=Error("Widget host call was cancelled");return e.name="AbortError",e}function g(e){if(e.aborted)throw m()}function f(e,t){return g(t),new Promise((r,i)=>{let n=!1,a=e=>{n||(n=!0,t.removeEventListener("abort",s),e())},s=()=>a(()=>i(m()));t.addEventListener("abort",s,{once:!0}),Promise.resolve().then(e).then(e=>a(()=>r(e)),e=>a(()=>i(e)))})}function v(e){return(null==e?void 0:e.type)==="call"}function y(e){return(null==e?void 0:e.type)==="callback"}function b(e){return(null==e?void 0:e.type)==="event"}class w extends Error{errNo;errMsg;constructor(e,t,r=e){super(e),this.errNo=t,this.errMsg=r,Object.setPrototypeOf(this,new.target.prototype),this.name="BridgeAPIError"}}function _(e,t){return{type:"callback",callbackId:e.callbackId,params:{code:1,data:t}}}function S(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:t;return{type:"callback",callbackId:e.callbackId,params:{code:0,msg:t,errNo:r,errMsg:i}}}function x(e){return e instanceof Error?e.message:String(e)}function I(e,t){return t instanceof w?S(e,t.message,t.errNo,t.errMsg):S(e,x(t))}r(67548),r(70954),r(98803),r(79162),r(15385),r(39342),r(69152),r(61955),r(82689),r(84847),r(16285),r(20602),r(33307),r(94341),r(7270),r(44997),r(50364),r(79780),r(80372),r(72498),r(37928),r(25597),r(92321);class k{registry=new Map;eventSources=new Map;eventSourceCleanups=new Map;eventSourceRetainCounts=new Map;eventControllers=new Set;handlers={};constructor(e){e&&this.registerMany(e)}register(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!r.override&&this.registry.has(e))throw Error(`Bridge API handler ${e} is already registered`);let i=this.registry.get(e),n="function"==typeof t?{handler:t,canIUse:!0}:{...t,canIUse:t.canIUse??!0};return this.registry.set(e,n),this.handlers[e]=n.handler,()=>{if(this.registry.get(e)===n){if(i){this.registry.set(e,i),this.handlers[e]=i.handler;return}this.registry.delete(e),delete this.handlers[e]}}}registerMany(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=[];try{for(let[i,n]of Object.entries(e))r.push(this.register(i,n,t))}catch(e){for(let e of r.reverse())e();throw e}return()=>{for(let e of r.reverse())e()}}get(e){var t;return null==(t=this.registry.get(e))?void 0:t.handler}getSyncResults(e){let t={};for(let[r,i]of this.registry)i.syncResult&&this.canIUse(r,e)&&(t[r]="function"==typeof i.syncResult?i.syncResult({...e,apiRegistry:this}):i.syncResult);return t}registerEventSource(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!r.override&&this.eventSources.has(e))throw Error(`Bridge event source ${e} is already registered`);let i=this.eventSources.get(e),n="function"==typeof t?{source:t}:t;return this.stopEventSource(e),this.eventSources.set(e,n),(this.eventSourceRetainCounts.get(e)??0)>0&&this.startEventSource(e,n),()=>{if(this.eventSources.get(e)===n){if(this.stopEventSource(e),i){this.eventSources.set(e,i),(this.eventSourceRetainCounts.get(e)??0)>0&&this.startEventSource(e,i);return}this.eventSources.delete(e)}}}registerEventSources(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=[];try{for(let[i,n]of Object.entries(e))r.push(this.registerEventSource(i,n,t))}catch(e){for(let e of r.reverse())e();throw e}return()=>{for(let e of r.reverse())e()}}canIUse(e,t){let r=this.registry.get(e);if(r)return"function"==typeof r.canIUse?r.canIUse({...t,apiRegistry:this}):r.canIUse;let i=this.eventSources.get(e);return!!i&&("function"==typeof i.canIUse?i.canIUse({...t,apiRegistry:this}):i.canIUse??!0)}dispatch(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;if(!v(e))return;let i={...t,apiRegistry:this};if(this.canIUse(e.name,i))return function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!v(e))return;let i=t[e.name];if(!i)return S(e,`API ${e.name} is not implemented in Doubao Web SDK`);try{let t=i(e,r);if(t instanceof Promise)return t.catch(t=>I(e,t));return t??S(e,`API ${e.name} is not implemented in Doubao Web SDK`)}catch(t){return I(e,t)}}(e,this.handlers,i);let n=this.registry.has(e.name)?103:-1;if(!r)return S(e,`API ${e.name} is not implemented in Doubao Web SDK`,n);try{let t=r(e.name);return t instanceof Promise?t.then(()=>S(e,`API ${e.name} is not implemented in Doubao Web SDK`,n)).catch(t=>I(e,t)):S(e,`API ${e.name} is not implemented in Doubao Web SDK`,n)}catch(t){return I(e,t)}}getSupportedNames(e){return[...new Set([...this.registry.keys(),...this.eventSources.keys()])].filter(t=>this.canIUse(t,e))}emitEvent(e,t){let r=!1;for(let i of this.eventControllers)r=i.emit(e,t)||r;return r}createEventController(e){return new C(this,e)}fork(){let e=new k(this.getRegistrations());return e.registerEventSources(this.getEventSources()),e}getRegistrations(){return Object.fromEntries(this.registry)}getEventSources(){return Object.fromEntries(this.eventSources)}attachEventController(e){return this.eventControllers.add(e),()=>{this.eventControllers.delete(e)}}retainEventSource(e){let t=this.eventSourceRetainCounts.get(e)??0;if(this.eventSourceRetainCounts.set(e,t+1),t>0)return;let r=this.eventSources.get(e);r&&this.startEventSource(e,r)}releaseEventSource(e){let t=this.eventSourceRetainCounts.get(e)??0;if(t<=1){this.eventSourceRetainCounts.delete(e),this.stopEventSource(e);return}this.eventSourceRetainCounts.set(e,t-1)}notifyEventSubscription(e,t,r){var i,n;null==(n=this.eventSources.get(e))||null==(i=n.onSubscribe)||i.call(n,t,r)}startEventSource(e,t){this.stopEventSource(e);let r=t.source(t=>{this.emitEvent(e,t)});"function"==typeof r&&this.eventSourceCleanups.set(e,r)}stopEventSource(e){var t;null==(t=this.eventSourceCleanups.get(e))||t(),this.eventSourceCleanups.delete(e)}}class C{apiRegistry;dispatch;cleanupRegistry;subscribedEventNames=new Set;cleanups=new Set;destroyed=!1;visible=!0;visibilityListeners=new Set;constructor(e,t){this.apiRegistry=e,this.dispatch=t,this.cleanupRegistry=this.apiRegistry.attachEventController(this)}subscribe(e,t){this.destroyed||this.subscribedEventNames.has(e)||(this.subscribedEventNames.add(e),this.apiRegistry.retainEventSource(e),this.apiRegistry.notifyEventSubscription(e,this,t))}unsubscribe(e){this.subscribedEventNames.delete(e)&&this.apiRegistry.releaseEventSource(e)}isSubscribed(e){return this.subscribedEventNames.has(e)}emit(e,t){return!!this.isSubscribed(e)&&this.emitPrivate(e,t)}emitPrivate(e,t){return!this.destroyed&&(this.dispatch(e,t),!0)}setVisible(e){for(let t of(this.visible=e,this.visibilityListeners))t(e)}onVisibilityChange(e){return e(this.visible),this.visibilityListeners.add(e),()=>this.visibilityListeners.delete(e)}onDestroy(e){return this.destroyed?(e(),()=>{}):(this.cleanups.add(e),()=>this.cleanups.delete(e))}destroy(){if(!this.destroyed){for(let e of(this.destroyed=!0,this.cleanups))try{e()}catch(e){console.error("Failed to clean up bridge API resources",e)}for(let e of(this.cleanups.clear(),this.visibilityListeners.clear(),this.subscribedEventNames))this.apiRegistry.releaseEventSource(e);this.subscribedEventNames.clear(),this.cleanupRegistry()}}}let E=new k;function N(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:i;return null==e?void 0:e.getPackageInfo()}async function T(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i;return await (null==t?void 0:t.navigateTo(e)),!!t}async function A(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i;return await (null==t?void 0:t.redirectTo(e)),!!t}async function M(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i;return await (null==t?void 0:t.reLaunch(e)),!!t}function j(){return"0.8.0-rc.11"}function R(e){var t;let{screenWidth:r,statusBarHeight:i}=e??(null==(t=globalThis.lynx)?void 0:t.__globalProps),n=Math.round(i)+4,a=Math.round(r)-12;return{bottom:n+36,height:36,left:a-84,right:a,top:n,width:84}}function P(){return(navigator.language||"zh-CN").replace(/-/g,"_")}function L(){var e,t,r;return(null==(t=(r=window).matchMedia)||null==(e=t.call(r,"(prefers-color-scheme: dark)"))?void 0:e.matches)?"dark":"light"}function D(){return"string"==typeof DoubaoAppsSDKVersion?DoubaoAppsSDKVersion:j()??""}function O(){return navigator.userAgentData}function U(){var e;let t=null==(e=O())?void 0:e.brands,r=null==t?void 0:t.find(e=>{let{brand:t}=e;return!/not.a.brand/i.test(t)});if(null==r?void 0:r.brand)return r.brand;let i=navigator.userAgent??"";return/edg\//i.test(i)?"Microsoft Edge":/chrome|crios/i.test(i)?"Chrome":/firefox|fxios/i.test(i)?"Firefox":/safari/i.test(i)?"Safari":"Browser"}function $(){var e,t;let r=null==(e=O())?void 0:e.brands,i=null==r?void 0:r.find(e=>{let{brand:t}=e;return!/not.a.brand/i.test(t)});if(null==i?void 0:i.version)return i.version;let n=navigator.userAgent??"";return(null==(t=/(?:edg|chrome|crios|firefox|fxios|version)\/([\d.]+)/i.exec(n))?void 0:t[1])??void 0}function q(){var e;let t=navigator.userAgent??"",r=navigator.platform??"",i=(null==(e=O())?void 0:e.platform)??"",n=`${i} ${r} ${t}`,a=navigator.maxTouchPoints??0;return/android/i.test(n)?{platform:"android",brand:"Android"}:/iphone/i.test(n)?{platform:"ios",brand:"iPhone"}:/ipad/i.test(n)||/mac/i.test(r)&&a>1?{platform:"ios",brand:"iPad"}:/mac/i.test(n)?{platform:"mac",brand:"Mac"}:/win/i.test(n)?{platform:"windows",brand:"Windows"}:/linux/i.test(n)?{platform:"linux",brand:"Linux"}:{platform:"web",brand:"Browser"}}function B(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:N();return{appId:(null==e?void 0:e.appId)??"",name:(null==e?void 0:e.name)??"",iconSrc:null==e?void 0:e.iconSrc}}function F(e){var t,r,i,n,a;if((null==e?void 0:e.containerWidth)!==void 0){let{density:t=1,screenWidth:r=0,screenHeight:i=0,containerWidth:n=0,containerHeight:a=0,statusBarHeight:s=0,topHeight:o=s,safeArea:l={}}=e,{marginTop:d=0,marginBottom:u=0,marginLeft:c=0,marginRight:p=0}=l;return{pixelRatio:t,screenWidth:r,screenHeight:i,windowWidth:n,windowHeight:a,statusBarHeight:s,screenTop:o,safeArea:{left:c,right:n-p,top:d,bottom:a-u,width:n-c-p,height:a-d-u}}}let s=Math.round((null==(n=window.visualViewport)?void 0:n.width)??window.innerWidth??0),o=Math.round((null==(a=window.visualViewport)?void 0:a.height)??window.innerHeight??0),l=window.devicePixelRatio??1,d=Math.round((null==(t=window.screen)?void 0:t.width)??s),u=Math.round((null==(r=window.screen)?void 0:r.height)??o),c=Math.round((null==(i=window.visualViewport)?void 0:i.offsetTop)??0);return{pixelRatio:l,screenWidth:d,screenHeight:u,windowWidth:s,windowHeight:o,statusBarHeight:c,safeArea:{left:0,right:s,top:c,bottom:o,width:s,height:Math.max(0,o-c)},screenTop:c}}function W(){return q().platform}function z(){var e,t,r,i,n;let a=navigator.userAgent??"",s=W();return"android"===s?null==(e=/android\s+([\d.]+)/i.exec(a))?void 0:e[1]:"ios"===s?null==(r=/(?:iphone os|cpu os)\s+([\d_]+)/i.exec(a))||null==(t=r[1])?void 0:t.replace(/_/g,"."):"mac"===s?null==(n=/mac os x\s+([\d_]+)/i.exec(a))||null==(i=n[1])?void 0:i.replace(/_/g,"."):void 0}function H(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:W();return"android"===e?"Android":"ios"===e?"iOS":"mac"===e?"macOS":"windows"===e?"Windows":"linux"===e?"Linux":"Web"}function V(e){let t;if((null==e?void 0:e.deviceModel)!==void 0){let t=e.os??e.devicePlatform??"";return{abi:e.abi,deviceAbi:e.deviceAbi,cpuType:e.cpuType,benchmarkLevel:"number"==typeof e.benchmarkLevel?e.benchmarkLevel:-1,brand:e.deviceBrand??"",model:e.deviceModel??e.deviceType??"",system:e.osVersion?`${t} ${e.osVersion}`:t,platform:(e.platform??t).toLowerCase(),memorySize:null==e.memorySize?"":String(e.memorySize)}}let r=q(),i=navigator.platform||W();return{abi:i,deviceAbi:i,benchmarkLevel:-1,brand:r.brand,model:function(){let e=navigator.userAgent??"",t=W();if("android"===t){var r,i;return(null==(i=/android\s+[\d.]+;\s*([^;)]+)/i.exec(e))||null==(r=i[1])?void 0:r.trim())||"Android"}return"ios"===t?q().brand:"mac"===t||"windows"===t||"linux"===t?navigator.platform||q().brand:U()}(),system:function(){let e=W(),t=z();if("web"!==e){let r=H(e);return t?`${r} ${t}`:r}let r=$(),i=U();return r?`${i} ${r}`:"Web"}(),platform:r.platform,cpuType:i,memorySize:"number"==typeof(t=navigator.deviceMemory)&&Number.isFinite(t)?String(Math.round(1024*t)):""}}function G(){let e=V(),t=F(),r=t.windowWidth>t.windowHeight;return{os:H(e.platform),platform:e.platform,osVersion:z(),deviceBrand:e.brand,language:P(),deviceModel:e.model,deviceType:e.model,deviceAbi:e.deviceAbi,cpuType:e.cpuType,memorySize:e.memorySize,benchmarkLevel:e.benchmarkLevel,appVersion:$(),appTheme:L(),channel:"release",screenOrientation:+!!r,isLandscape:+!!r,abi:e.abi}}function J(e){var t,r,i;let n,a=F(e),s=V(e);return{...a,brand:s.brand,model:s.model,language:(null==e||null==(t=e.language)?void 0:t.replace(/-/g,"_"))??P(),version:(null==e?void 0:e.appVersion)??$(),system:s.system,platform:(null==e||null==(r=e.os)?void 0:r.toLowerCase())??s.platform,SDKVersion:D(),theme:(null==e?void 0:e.appTheme)??L(),benchmarkLevel:s.benchmarkLevel,enableDebug:(null==e?void 0:e.channel)==="debug",deviceOrientation:(i=a.windowWidth>a.windowHeight,!0===(n=(null==e?void 0:e.isLandscape)??(null==e?void 0:e.screenOrientation))||1===n||"string"==typeof n&&n.toLowerCase().includes("landscape")?"landscape":!1===n||0===n||"string"==typeof n&&n.toLowerCase().includes("portrait")?"portrait":i?"landscape":"portrait"),abi:s.abi}}function K(){let e={isConnected:!1!==navigator.onLine,networkType:!1===navigator.onLine?"none":"unknown",hasSystemProxy:!1,weakNet:!1};return{networkType:e.networkType,signalStrength:e.signalStrength,hasSystemProxy:e.hasSystemProxy??!1,weakNet:e.weakNet??!1}}function Z(e){return{SDKVersion:D(),enableDebug:(null==e?void 0:e.channel)==="debug",host:{appId:(null==e?void 0:e.appName)??""},language:(null==e?void 0:e.language)??P(),version:(null==e?void 0:e.appVersion)??$(),theme:(null==e?void 0:e.appTheme)??L()}}function X(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:N(),t=arguments.length>1?arguments[1]:void 0;return{miniProgram:{appId:B(e).appId,envVersion:(null==t?void 0:t.channel)==="debug"?"develop":"release",version:(null==e?void 0:e.versionName)??""}}}function Y(e){var t;return(null==e||null==(t=e.navigation)?void 0:t.getPackageInfo())??(null==e?void 0:e.packageInfo)}E.handlers,r(31178),r(32085),r(12021);var Q=r(95550),ee=r(66013);r(46455);function et(e){if("string"!=typeof e)throw Error("key must be a string");if(0===e.length)throw Error("key must not be empty");if(e.length>1024)throw Error("key length must be less than or equal to 1024");return e}function er(e){if(ei(e)>1048576)throw Error("data size must be less than or equal to 1048576 bytes")}function ei(e){return new TextEncoder().encode(e).byteLength}function en(e){return Object.values(e).reduce((e,t)=>e+ei(t),0)}function ea(e){if(e>0xa00000)throw new w("total storage size exceeded",1600002)}function es(e){if(!o(e)||Array.isArray(e))throw Error("Storage snapshot must be an object");let t=0;for(let[r,i]of Object.entries(e)){if(et(r),"string"!=typeof i)throw Error("Storage values must be serialized strings");er(i),t+=ei(i)}ea(t)}let eo=new Map,el=new Map,ed=new Set;function eu(e,t){var r;let i=JSON.stringify([(null==e||null==(r=e.packageInfo)?void 0:r.appId)||"unknown-app",t??null]);return`web-storage:${(0,ee.My)((0,Q.sc)(i))}`}function ec(){let e=Date.now();return{entries:Object.fromEntries(["/","/temp","/user"].map(t=>[t,{type:"directory",createTime:e,lastModifiedTime:e}]))}}function ep(){return n??=new Promise((e,t)=>{let r=indexedDB.open("doubao-web-sdk-files",2);r.onupgradeneeded=()=>{let e=r.result;for(let t of["storage","files"])e.objectStoreNames.contains(t)||e.createObjectStore(t)},r.onsuccess=()=>{r.result.onversionchange=()=>{r.result.close(),n=void 0},e(r.result)},r.onerror=()=>{n=void 0,t(r.error)},r.onblocked=()=>{n=void 0,t(Error("Storage database upgrade is blocked; close other app views and retry"))}})}function eh(e){return IDBKeyRange.bound([e],[e,[]])}function em(e){return new Promise((t,r)=>{e.oncomplete=()=>t(),e.onabort=()=>{let t=e.error,i=new w((null==t?void 0:t.message)??"Storage transaction failed",(null==t?void 0:t.name)==="QuotaExceededError"?208:102);i.cause=t,r(i)}})}async function eg(e,t){let r=await ep(),i=r.transaction(["storage","files"]),n=em(i);for(let[r,n]of[["storage",t.storageSnapshot],["files",t.fileSystemSnapshot.entries]]){let t=i.objectStore(r).openCursor(eh(e));t.onsuccess=()=>{let e=t.result;e&&(Object.defineProperty(n,String(e.key[1]),{value:"files"===r?Object.freeze(e.value):e.value,enumerable:!0,configurable:!0,writable:!0}),e.continue())}}if(await n,0===Object.keys(t.fileSystemSnapshot.entries).length){t.fileSystemSnapshot=ec();let i=r.transaction("files","readwrite"),n=em(i);for(let[r,n]of Object.entries(t.fileSystemSnapshot.entries))i.objectStore("files").put(n,[e,r]);await n}}function ef(e){let t=eo.get(e);if(!t){let r={storageSnapshot:{},fileSystemSnapshot:{entries:{}}};t={snapshot:r,references:0,ready:eg(e,r)},eo.set(e,t)}t.references+=1;let r=t,i=!1;return{ready:t.ready,release(){if(i)return;i=!0,r.references-=1;let t=()=>{r.references||eo.get(e)!==r||eo.delete(e)};r.ready.then(t,t)}}}function ev(e,t){let r=ef(e),i=async()=>(await r.ready,t()),n=(el.get(e)??Promise.resolve()).then(i,i);el.set(e,n);let a=()=>{el.get(e)===n&&el.delete(e),r.release()};return n.then(a,a),n}function ey(e){var t;let r=null==(t=eo.get(e))?void 0:t.snapshot;if(!r)throw Error("Application storage is not initialized");return{storageSnapshot:{...r.storageSnapshot},fileSystemSnapshot:{entries:{...r.fileSystemSnapshot.entries}}}}function eb(e){return ey(e).fileSystemSnapshot}function ew(e){return ed.add(e),()=>{ed.delete(e)}}function e_(e,t,r){let i={...r??ey(e),fileSystemNamespace:e,mutationId:t};for(let e of ed)try{e(i)}catch(e){console.error("Cannot deliver application storage update",e)}}function eS(e,t){let r={};for(let i of new Set([...Object.keys(e),...Object.keys(t)])){let n=Object.hasOwn(t,i)?t[i]:null,a=Object.hasOwn(e,i)?e[i]:void 0,s=o(a)&&o(n)&&a.type===n.type&&a.data===n.data&&a.createTime===n.createTime&&a.lastModifiedTime===n.lastModifiedTime;a===(n??void 0)||s||Object.defineProperty(r,i,{value:n,enumerable:!0})}return r}async function ex(e,t){let r=ey(e);for(let[e,i]of(t.clearStorage&&(r.storageSnapshot={}),[[r.storageSnapshot,t.storageChanges],[r.fileSystemSnapshot.entries,t.fileSystemChanges]]))for(let[t,r]of Object.entries(i??{}))null===r?delete e[t]:Object.defineProperty(e,t,{value:r,enumerable:!0,writable:!0,configurable:!0});(t.storageChanges||t.clearStorage)&&es(r.storageSnapshot),t.fileSystemChanges&&ek(r.fileSystemSnapshot,eb(e));let i=(await ep()).transaction(["storage","files"],"readwrite"),n=em(i);try{for(let[r,n]of(t.clearStorage&&i.objectStore("storage").delete(eh(e)),[["storage",t.storageChanges],["files",t.fileSystemChanges]])){let t=i.objectStore(r);for(let[i,a]of Object.entries(n??{}))null===a?t.delete([e,i]):t.put("files"===r?Object.freeze(a):a,[e,i])}}catch(e){throw i.abort(),await n.catch(()=>{}),e}await n,eo.get(e).snapshot=r,e_(e,t.mutationId,t)}function eI(e){return o(e)&&"directory"===e.type}function ek(e,t){if(!o(e)||!o(e.entries))throw Error("Invalid file snapshot");let r={user:0,temp:0};for(let[i,n]of Object.entries(e.entries)){if(!o(n)||!["file","directory"].includes(String(n.type))||!Number.isFinite(n.createTime)||0>Number(n.createTime)||!Number.isFinite(n.lastModifiedTime)||0>Number(n.lastModifiedTime)||"/"!==i&&(!/^\/(user|temp)(\/[^/]+)*$/.test(i)||i.split("/").some(e=>"."===e||".."===e||/[\\\0]/.test(e)))||"/"!==i&&!eI(e.entries[i.slice(0,i.lastIndexOf("/"))||"/"])||["/","/user","/temp"].includes(i)&&"directory"!==n.type)throw Error(`Invalid file entry: ${i}`);if("file"===n.type){if("string"!=typeof n.data)throw Error(`Invalid file data: ${i}`);if((null==t?void 0:t.entries[i])!==n&&(n.data.length%4!=0||/[^A-Za-z0-9+/=]/.test(n.data)||!/^[^=]*={0,2}$/.test(n.data)))throw Error(`Invalid base64 file: ${i}`);let e=i.startsWith("/user/")?"user":"temp";r[e]+=Math.floor(3*n.data.length/4)-(n.data.endsWith("==")?2:+!!n.data.endsWith("="))}}for(let t of["/","/user","/temp"])if(!eI(e.entries[t]))throw Error(`Missing file directory: ${t}`);if(r.user>0x3200000||r.temp>0x6400000)throw new w("total file storage size exceeded",208)}function eC(e){if(!o(e)||"doubao-web-storage"!==e.format||1!==e.version||!o(e.storageSnapshot))throw Error("存储与文件备份格式无效");es(e.storageSnapshot),ek(e.fileSystemSnapshot)}r(20303),r(99166),r(6106),r(22742),r(37553),r(62148),r(89055),r(12205),r(65850),r(65135),r(5876),r(94359),r(28016),r(38641),r(82247),r(11839),r(56109),r(63589),r(45249);var eE=r(59933),eN=r(12683);function eT(e){if(e.startsWith("/")||e.includes("\\")||e.includes("\0")||/^[a-z]:/i.test(e))throw new w("ZIP entry escapes the target directory",213);let t=[];for(let r of e.split("/"))if(r&&"."!==r)if(".."===r){if(!t.length)throw new w("ZIP entry escapes the target directory",213);t.pop()}else t.push(r);return t.join("/")}function eA(e){return Math.floor(3*e.length/4)-(e.endsWith("==")?2:+!!e.endsWith("="))}function eM(e){if(e>0xa00000)throw new w("total size limit exceeded",208)}function ej(e,t,r){let i=t.startsWith("/user/")?"/user/":"/temp/",n=("/user/"===i?50:100)*1048576,a=r;for(let[r,n]of Object.entries(e.entries))r!==t&&r.startsWith(i)&&"file"===n.type&&(a+=eA(n.data));if(a>n)throw new w("total size limit exceeded",208)}function eR(e){o(e.fileSystemSnapshot)||(e.fileSystemSnapshot={entries:{}}),o(e.fileSystemSnapshot.entries)||(e.fileSystemSnapshot.entries={});let t=Date.now();for(let i of["/","/temp","/user"]){var r;(null==(r=e.fileSystemSnapshot.entries[i])?void 0:r.type)!=="directory"&&(e.fileSystemSnapshot.entries[i]={type:"directory",createTime:t,lastModifiedTime:t})}return e.fileSystemSnapshot}function eP(e,t){let r=e[t];if("string"!=typeof r)throw new w(`${t} must be a string`,104);return r}function eL(e,t){let r=e[t];return"string"==typeof r?r:void 0}function eD(e){let t;if(0===e.length||e.includes("?")||e.includes("#")||/%(?![0-9a-f]{2})/i.test(e))throw new w("invalid applet file path",213);try{t=decodeURIComponent(e)}catch{throw new w("invalid applet file path",213)}if("."===t||".."===t||t.includes("/")||t.includes("\\")||t.includes("\0"))throw new w("invalid applet file path",213);return t}function eO(e){let t=/^appletfile:\/\/(user|temp)(?:\/(.*))?$/.exec(e);if(!t)throw new w("path must use appletfile://user or appletfile://temp",213);let r=t[1],i=t[2];if(void 0===i||0===i.length)return`/${r}`;let n=i.split("/").map(eD);return`/${r}/${n.join("/")}`}function eU(e){let t=/^data:[^,]*;base64,([A-Za-z0-9+/]*={0,2})$/.exec(e);if(!t)return;let r=t[1];if(r.length%4==1||r.endsWith("=")&&r.length%4!=0)throw new w("invalid base64 data",104);return{type:"file",data:r,createTime:0,lastModifiedTime:0}}function e$(e){let t=eO(e);if("/temp"===t||"/user"===t)return"";let r=t.lastIndexOf("/");return t.slice(0,r)}function eq(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function eB(e){let t=e.split("/").filter(Boolean),r=t.shift();if("temp"!==r&&"user"!==r)throw new w(`invalid applet file path: ${e}`,213);let i=t.map(eq).join("/");return i.length>0?`appletfile://${r}/${i}`:`appletfile://${r}`}function eF(e,t){return e.entries[eO(t)]}function eW(e,t){let r=eU(t);if(r)return r;let i=eO(t),n=e.entries[i];if(!n)throw new w(`file not found: ${i}`,203);if("file"!==n.type)throw new w(`path is a directory: ${i}`,1901001);return n}function ez(e,t){let r=eO(t),i=e.entries[r];if(!i)throw new w(`directory not found: ${r}`,203);if("directory"!==i.type)throw new w(`path is not a directory: ${r}`,1901002);return i}function eH(e,t){let r=e$(t);if(!r)throw new w(`invalid parent directory: ${t}`,213);let i=Date.now(),n="";for(let t of r.split("/").filter(Boolean)){n+=`/${t}`;let r=e.entries[n];if((null==r?void 0:r.type)==="file")throw new w(`path is not a directory: ${n}`,1901002);r||(e.entries[n]={type:"directory",createTime:i,lastModifiedTime:i})}}function eV(e){let t;try{t=atob(e)}catch{throw new w("invalid base64 data",104)}let r=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)r[e]=t.charCodeAt(e);return r}function eG(e,t){let r="string"==typeof e?e:String(e??"");return"base64"===t?eV(r):new TextEncoder().encode(r)}function eJ(e,t,r){let i=eO(t),n=Date.now(),a=e.entries[i];if((null==a?void 0:a.type)==="directory")throw new w(`path is a directory: ${i}`,1901001);ej(e,i,r.byteLength),eH(e,t),e.entries[i]={type:"file",data:function(e){let t="";for(let r=0;r<e.length;r+=1)t+=String.fromCharCode(e[r]);return btoa(t)}(r),createTime:(null==a?void 0:a.createTime)??n,lastModifiedTime:n}}function eK(e,t,r){let i=eR(e),n=eP(t,"dirPath"),a=eO(n),s=Date.now(),o=i.entries[a];if((null==o?void 0:o.type)==="directory")return{};if(o)throw new w(`path is not a directory: ${a}`,1901002);if(!0===t.recursive){let e="";for(let t of a.split("/").filter(Boolean))if(e+=`/${t}`,i.entries[e]||(i.entries[e]={type:"directory",createTime:s,lastModifiedTime:s}),"directory"!==i.entries[e].type)throw new w(`path is not a directory: ${e}`,1901002)}else{let e=e$(n);if(!e)throw new w(`invalid parent directory: ${n}`,213);let t=i.entries[e];if(!t)throw new w(`directory not found: ${e}`,203);if("directory"!==t.type)throw new w(`path is not a directory: ${e}`,1901002);i.entries[a]={type:"directory",createTime:s,lastModifiedTime:s}}return r(),{}}function eZ(e,t,r){let i=eR(e),n=eP(t,"dirPath"),a=eO(n);if("/temp"===a||"/user"===a)throw new w("cannot remove root directory",213);ez(i,n);let s=`${a}/`,o=Object.keys(i.entries).filter(e=>e.startsWith(s));if(!0!==t.recursive&&o.length>0)throw new w(`directory is not empty: ${a}`,1901001);for(let e of o)delete i.entries[e];return delete i.entries[a],r(),{}}function eX(e,t,r){let i=eR(e),n=eP(t,"filePath"),a=eO(n);return eW(i,n),delete i.entries[a],r(),{}}function eY(e,t){let r=eR(e),i=eP(t,"path"),n=eU(i),a=n?i:eO(i),s=n??r.entries[a];if(!s)throw new w(`path not found: ${a}`,203);return{size:"file"===s.type?eA(s.data):0,lastModifiedTime:s.lastModifiedTime,isDirectory:"directory"===s.type}}let eQ={"doubao.readFile":function(e,t){var r;let i=eW(eR(e),eP(t,"filePath"));return eM(eA(i.data)),{data:(r=i.data,"utf-8"===eL(t,"encoding")?new TextDecoder().decode(eV(r)):r)}},"doubao.writeFile":function(e,t,r){let i=eR(e),n=eG(t.data,eL(t,"encoding"));return eM(n.byteLength),eJ(i,eP(t,"filePath"),n),r(),{}},"doubao.appendFile":function(e,t,r){let i=eR(e),n=eP(t,"filePath"),a=eO(n),s=i.entries[a];if((null==s?void 0:s.type)==="directory")throw new w(`path is a directory: ${a}`,1901001);let o=eG(t.data,eL(t,"encoding"));eM(o.byteLength),ej(i,a,((null==s?void 0:s.type)==="file"?eA(s.data):0)+o.byteLength);let l=(null==s?void 0:s.type)==="file"?eV(s.data):new Uint8Array,d=new Uint8Array(l.length+o.length);return d.set(l),d.set(o,l.length),eJ(i,n,d),r(),{}},"doubao.access":function(e,t){let r=eR(e),i=eP(t,"path");if(!eF(r,i))throw new w(`path not found: ${i}`,203);return{}},"doubao.mkdir":eK,"doubao.rmdir":eZ,"doubao.readdir":function(e,t){let r=eR(e),i=eP(t,"dirPath");return ez(r,i),{files:function(e,t){let r=eO(t),i="/"===r?"/":`${r}/`,n=new Set;for(let t of Object.keys(e.entries)){if(t===r||!t.startsWith(i))continue;let e=t.slice(i.length).split("/")[0];e&&n.add(e)}return[...n]}(r,i)}},"doubao.unlink":eX,"doubao.stat":eY,"doubao.copyFile":function(e,t,r){let i=eR(e),n=eW(i,eP(t,"srcPath")),a=eP(t,"destPath");return ej(i,eO(a),eA(n.data)),eJ(i,a,eV(n.data)),r(),{}},"doubao.getFileInfo":function(e,t){let r=eP(t,"filePath"),{size:i}=eY(e,{path:r});if(void 0===t.digestAlgorithm)return{size:i};let n=eP(t,"digestAlgorithm").toLowerCase(),a=eW(eR(e),r),s="md5"===n?eE.Fx:"sha1"===n?eE.e8:void 0;if(!s)throw new w(`unsupported digest algorithm: ${n}`,102);return{size:i,digest:(0,ee.My)(s(eV(a.data)))}},"doubao.rename":function(e,t,r){let i=eR(e),n=eP(t,"oldPath"),a=eP(t,"newPath"),s=eO(n),o=eO(a),l=i.entries[s];if(!l)throw new w(`path not found: ${s}`,203);if("/temp"===s||"/user"===s)throw new w("cannot rename root directory",213);if(s===o)return{};if("directory"===l.type&&o.startsWith(`${s}/`))throw new w("cannot move a directory into itself",213);if(i.entries[o])throw new w(`target already exists: ${o}`,102);for(let e of(eH(i,a),Object.keys(i.entries)))if(e===s||e.startsWith(`${s}/`)){let t=o+e.slice(s.length);i.entries[t]=i.entries[e],delete i.entries[e]}return r(),{}},"doubao.truncate":function(e,t,r){let i=eR(e),n=eP(t,"filePath"),a=eW(i,n),s=t.length??0;if("number"!=typeof s||!Number.isSafeInteger(s)||s<0)throw new w("length must be a non-negative integer",104);ej(i,eO(n),s);let o=eV(a.data),l=new Uint8Array(s);return l.set(o.slice(0,s)),eJ(i,n,l),r(),{}},"doubao.saveFile":function(e,t,r){let i,n,a=eR(e),s=eP(t,"tempFilePath"),o=eU(s),l=o??eW(a,s),d=eL(t,"filePath"),u=o?(i=s.slice(5,s.indexOf(";")),`media.${({"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","audio/wav":"wav","audio/aac":"aac","audio/mp4":"mp4"})[i]??"bin"}`):"/temp"===(n=eO(s))||"/user"===n?"":n.slice(n.lastIndexOf("/")+1),c=`/user/${Date.now()}`,p=d&&d.length>0?d:eB(`${c}_${u}`);for(let e=1;!d&&a.entries[eO(p)];e++)p=eB(`${c}_${e}_${u}`);return ej(a,eO(p),eA(l.data)),eJ(a,p,eV(l.data)),o||eO(s)===eO(p)||delete a.entries[eO(s)],r(),{savedFilePath:p}},"doubao.getSavedFileList":function(e){return{fileList:Object.entries(eR(e).entries).flatMap(e=>{let[t,r]=e;return t.startsWith("/user/")&&"file"===r.type?[{filePath:eB(t),size:eA(r.data),createTime:r.createTime}]:[]})}},"doubao.removeSavedFile":function(e,t,r){var i;let n=eP(t,"filePath");return(null==(i=eF(eR(e),n))?void 0:i.type)==="directory"?eZ(e,{dirPath:n},r):eX(e,t,r)},"doubao.unzip":function(e,t,r){let i=eR(e),n=eW(i,eP(t,"zipFilePath")),a=eP(t,"targetPath"),s=eO(a),o=function(e,t){try{let r=function(e,t){let r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=e.length-22,n=Math.max(0,e.length-65557);for(;i>=n&&(0x6054b50!==r.getUint32(i,!0)||i+22+r.getUint16(i+20,!0)!==e.length);)i--;if(i<n||0!==r.getUint16(i+4,!0)||0!==r.getUint16(i+6,!0))throw Error("Invalid or multipart ZIP archive");let a=r.getUint16(i+10,!0),s=r.getUint32(i+16,!0);if(65535===a||0xffffffff===s){if(i<20||0x7064b50!==r.getUint32(i-20,!0))throw Error("Invalid ZIP64 archive");let e=Number(r.getBigUint64(i-12,!0));if(0x6064b50!==r.getUint32(e,!0))throw Error("Invalid ZIP64 directory");a=Number(r.getBigUint64(e+32,!0)),s=Number(r.getBigUint64(e+48,!0))}if(!Number.isSafeInteger(a)||a>e.length/46||!Number.isSafeInteger(s))throw Error("Invalid ZIP directory size");let o=new Map,l=0;for(let n=0;n<a;n++){if(s+46>i||0x2014b50!==r.getUint32(s,!0))throw Error("Invalid ZIP directory entry");let n=r.getUint16(s+8,!0),a=r.getUint16(s+28,!0),d=r.getUint16(s+30,!0),u=s+46+a+d+r.getUint16(s+32,!0);if(u>i||1&n)throw Error("Invalid or encrypted ZIP entry");let c=(0,eN.he)(e.subarray(s+46,s+46+a),!(2048&n));eT(c);let p=r.getUint32(s+24,!0);if(0xffffffff===p){let e=s+46+a,t=e+d;for(;e+4<=t&&1!==r.getUint16(e,!0);)e+=4+r.getUint16(e+2,!0);if(e+12>t||8>r.getUint16(e+2,!0))throw Error("Invalid ZIP64 file size");p=Number(r.getBigUint64(e+4,!0))}if(!Number.isSafeInteger(l+=p)||l>t)throw new w("ZIP expanded size exceeds the file system quota",208);o.set(c,r.getUint32(s+16,!0)),s=u}return o}(e,t),i=new Map,n=0,a=new eN.HJ(e=>{eT(e.name);let r=new eN.uZ(e.name);r.ondata=()=>{};let a=[],s=0;e.ondata=(o,l,d)=>{if(o)throw o;if((n+=l.length)>t)throw new w("ZIP expanded size exceeds the file system quota",208);if(a.push(l),s+=l.length,r.push(l,d),d){let t=new Uint8Array(s),n=0;for(let e of a)t.set(e,n),n+=e.length;i.set(e.name,{data:t,crc:r.crc>>>0})}},e.start()});a.register(eN.mM);for(let t=0;t<e.length;t+=65536)a.push(e.subarray(t,t+65536),t+65536>=e.length);if(i.size!==r.size)throw Error("ZIP entry count does not match its directory");for(let[e,t]of i)if(t.crc!==r.get(e))throw Error("ZIP entry checksum does not match");return new Map([...i].map(e=>{let[t,r]=e;return[t,r.data]}))}catch(e){if(e instanceof w)throw e;throw new w(`Unable to unzip file: ${e instanceof Error?e.message:String(e)}`,102)}}(eV(n.data),(s.startsWith("/user")?50:100)*1048576),l={...e,fileSystemSnapshot:{entries:{...i.entries}}};for(let[e,t]of(eK(l,{dirPath:a,recursive:!0},()=>{}),o)){let r=eT(e);if(!r)continue;let i=eB(`${s}/${r}`);e.endsWith("/")?eK(l,{dirPath:i,recursive:!0},()=>{}):eJ(l.fileSystemSnapshot,i,t)}return i.entries=l.fileSystemSnapshot.entries,r(),{}}},e0="doubao.__webSyncBridgePersist",e1="doubao.__webSyncBridgeUpdated";r(20789),r(62839),r(66876),r(35336);let e2="doubao.getPerformanceEntries",e3="doubao.setPerformanceBufferSize",e4="doubao.onPerformanceEntries",e6="doubao.__webPerformanceTiming",e5="__WEB_PERFORMANCE_WIDGET_IDENTITY__",e8=[e2,e3,e4];class e9{entries=[];bufferSize=30;launchStart=Date.now();launched=!1;snapshot(){return{entries:this.entries.map(e=>({...e})),bufferSize:this.bufferSize}}setBufferSize(e){if("number"!=typeof e||!Number.isInteger(e)||e<1||e>1e3)throw Error("size must be between 1 and 1000");this.bufferSize=e,this.entries=this.entries.slice(-e)}reset(){this.entries=[],this.bufferSize=30,this.launchStart=Date.now(),this.launched=!1}recordTiming(e,t){if(e.completed||!o(t))return[];let r=e.timing??={};for(let e of["create_lynx_start","layout_start","layout_end","lepus_execute_start","lepus_execute_end","parseChangesEnd"]){let i=t[e];"number"==typeof i&&Number.isFinite(i)&&i>0&&(r[e]=i)}let i=e=>{let t=r[e];return"number"==typeof t&&Number.isFinite(t)&&t>0?t:void 0},n=i("create_lynx_start"),a=i("layout_start"),s=i("layout_end");if(void 0===n||void 0===a||void 0===s||s<a||a<n)return[];e.completed=!0;let l=[],d=void 0===e.pageId?{}:{path:e.path,pageId:e.pageId};if(void 0!==e.pageId){let t=!this.launched,r=Math.min(e.startTime,n);if(t){let t=Math.min(this.launchStart,r);l.push({entryType:"navigation",name:"appLaunch",startTime:t,duration:s-t,...d,navigationStart:r,navigationType:e.navigationType})}l.push({entryType:"navigation",name:"route",startTime:r,duration:s-r,...d,navigationStart:r,navigationType:e.navigationType,referrerPath:e.referrerPath,referrerPageId:e.referrerPageId}),this.launched=!0}let u=i("lepus_execute_start"),c=i("lepus_execute_end"),p=c??i("parseChangesEnd");return void 0!==u&&void 0!==c&&c>=u&&l.push({entryType:"script",name:"evaluateScript",startTime:u,duration:c-u,moduleName:e.moduleName}),(void 0!==e.pageId||void 0!==e.widgetId)&&l.push({entryType:"render",name:"firstRender",startTime:n,duration:s-n,...d,...void 0!==p&&p>=n&&p<=s?{viewLayerReadyTime:p}:{},viewLayerRenderStartTime:a,viewLayerRenderEndTime:s,...void 0===e.widgetId?{}:{widgetId:e.widgetId,widgetInstanceId:e.widgetInstanceId,isAppColdLaunch:e.isAppColdLaunch}}),this.entries=[...this.entries,...l].slice(-this.bufferSize),l}}async function e7(e,t){try{await (null==t?void 0:t(e.params))}catch{}}let te=new Map,tt={"applet.subscribeEvent":(e,t)=>{let r=o(e.params)&&"string"==typeof e.params.eventName?e.params.eventName:"";if(r){var i;null==t||null==(i=t.events)||i.subscribe(r,t)}return _(e,{})},"applet.unsubscribeEvent":(e,t)=>{let r=o(e.params)&&"string"==typeof e.params.eventName?e.params.eventName:"";if(r){var i;null==t||null==(i=t.events)||i.unsubscribe(r)}return _(e,{})}};function tr(){var e;return null==(e=globalThis.navigator)?void 0:e.clipboard}function ti(e,t){let r=tr();if(!r||"function"!=typeof r[t])throw new w(`${e} is not supported in this browser`,103);return r}function tn(e,t){let r=o(t)&&"string"==typeof t.message?t.message:String(t),i=new w(`${e} failed: ${r}`,o(t)&&("NotAllowedError"===t.name||"SecurityError"===t.name)?106:102);return i.cause=t,i}async function ta(e){let t=ti("setClipboardData","writeText");try{await t.writeText(e)}catch(e){throw tn("setClipboardData",e)}}async function ts(){let e=ti("getClipboardData","readText");try{let t=await e.readText();if("string"==typeof t)return t}catch(e){throw tn("getClipboardData",e)}throw new w("getClipboardData failed: clipboard did not return text",102)}function to(e,t,r){let i=(null==t?void 0:t.fileSystemNamespace)??eu(null==t?void 0:t.globalProps);return ev(i,async()=>{try{var n,a;let s=eb(i),l={fileSystemNamespace:i,fileSystemSnapshot:{entries:{...s.entries}},apiResults:{"doubao.getSystemInfo":{platform:null==t||null==(a=t.globalProps)||null==(n=a.os)?void 0:n.toLowerCase()}},storageSnapshot:{},supportedAPIs:[]},d=!1,u=(0,eQ[e.name])(l,o(e.params)?e.params:{},()=>{d=!0});return d?await ex(i,{fileSystemChanges:eS(s.entries,l.fileSystemSnapshot.entries),mutationId:r}):r&&e_(i,r,{}),_(e,u)}catch(e){throw r&&e_(i,r),e}})}let tl=Object.fromEntries(Object.keys(eQ).map(e=>[e,to]));async function td(e,t){var r,i;if("string"!=typeof(null==e?void 0:e.src)||!e.src)throw Error("src must be a non-empty string");let{src:n}=e,a=await new Promise((e,r)=>{let i=new Image,a=()=>{null==t||t.removeEventListener("abort",s),i.onload=i.onerror=null},s=()=>{a(),i.removeAttribute("src"),r(null==t?void 0:t.reason)};(null==t?void 0:t.aborted)?s():(null==t||t.addEventListener("abort",s,{once:!0}),i.onload=()=>{a(),e(i)},i.onerror=()=>{a(),r(Error(`failed to load image: ${n}`))},i.src=n)}),s=null==(r=n.match(/^data:image\/([^;,]+)/i))?void 0:r[1],o=null==(i=n.match(/\.([a-zA-Z0-9]+)(?:[?#].*)?$/))?void 0:i[1];return{width:a.naturalWidth||a.width,height:a.naturalHeight||a.height,orientation:"up",path:n,type:((null==s?void 0:s.split("+")[0])??o??"").toLowerCase()}}function tu(e){return{pages:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:i;return(null==e?void 0:e.getCurrentPages())??[]}(null==e?void 0:e.navigation)}}function tc(e){return async(t,r)=>{let i=t.params;if(!i||"string"!=typeof i.url||!i.url.trim())return S(t,"invalid url",104);try{return await e(i,null==r?void 0:r.navigation)?_(t,{}):S(t,"No active Runtime to navigate",102)}catch(e){return S(t,x(e),e instanceof w?e.errNo:102)}}}let tp={"doubao.openPage":async(e,t)=>{var r;let i=e.params;if(!i||"string"!=typeof i.url||!i.url.trim()||void 0!==i.mode&&!["push","replace","navigate","pop_to"].includes(i.mode))return S(e,"url and mode must describe a valid page route",104);if(!(null==t||null==(r=t.navigation)?void 0:r.openPage))return S(e,"No active Runtime to open page",102);try{return await t.navigation.openPage(i),_(e,{})}catch(t){return S(e,x(t),t instanceof w?t.errNo:102)}},"doubao.enableAlertBeforeUnload":(e,t)=>{var r;let i=null==(r=e.params)?void 0:r.message;return"string"!=typeof i?S(e,"message must be a string",104):th(e,i,t)},"doubao.disableAlertBeforeUnload":(e,t)=>th(e,void 0,t),"doubao.getCurrentPages":{handler:(e,t)=>_(e,tu(t)),syncResult:tu},"doubao.navigateTo":tc(T),"doubao.redirectTo":tc(A),"doubao.reLaunch":tc(M),"doubao.navigateBack":(e,t)=>!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i;return(null==t?void 0:t.navigateBack(e))??!1}(e.params??{},null==t?void 0:t.navigation)?S(e,"No pages in back stack",102):_(e,{}),"doubao.exitApp":(e,t)=>!function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:i;return null==e||e.exitApp(),!!e}(null==t?void 0:t.navigation)?S(e,"No active Runtime to exit app",102):_(e,{})};function th(e,t,r){var i;return(null==r?void 0:r.containerType)==="PAGE"&&(null==(i=r.navigation)?void 0:i.setAlertBeforeUnload)?r.navigation.setAlertBeforeUnload(t,r.element)?_(e,{}):S(e,"not found page",102):S(e,"alert before unload is only supported in page container",103)}let tm=Object.fromEntries(["setStorage","getStorage","removeStorage","clearStorage","getStorageInfo"].map(e=>[`doubao.${e}`,async(t,r)=>{let i=(null==r?void 0:r.fileSystemNamespace)??eu(null==r?void 0:r.globalProps);return ev(i,async()=>{var r,n;let a=o(t.params)?t.params:{},s=ey(i).storageSnapshot,l={};switch(e){case"setStorage":{let e,t;if("string"!=typeof a.data)throw Error("data must be a serialized string");let o=(r=a.key,n=a.data,e=et(r),er(n),t=Object.prototype.hasOwnProperty.call(s,e)?s[e]:void 0,ea(en(s)-(void 0===t?0:ei(t))+ei(n)),e);await ex(i,{storageChanges:{[o]:a.data}});break}case"getStorage":let d;l={data:Object.hasOwn(s,d=et(a.key))?s[d]:void 0};break;case"removeStorage":await ex(i,{storageChanges:{[et(a.key)]:null}});break;case"clearStorage":await ex(i,{clearStorage:!0});break;case"getStorageInfo":l={keys:Object.keys(s),currentSize:Math.ceil(en(s)/1024),limitSize:10240}}return _(t,l)})}])),tg={...{"doubao.getClipboardData":{canIUse:()=>{var e;return"function"==typeof(null==(e=tr())?void 0:e.readText)},handler:async e=>_(e,{data:await ts()})},"doubao.setClipboardData":{canIUse:()=>{var e;return"function"==typeof(null==(e=tr())?void 0:e.writeText)},handler:async e=>{let{data:t}=function(e){if(!o(e)||"string"!=typeof e.data)throw new w("data must be a string",104);return{data:e.data}}(e.params);return await ta(t),_(e,{})}}},...tt,...tl,...{"doubao.getImageInfo":async e=>_(e,await td(e.params))},...tp,...tm,...{[e0]:async(e,t)=>{let r=o(e.params)?e.params:{},i=null==t?void 0:t.fileSystemNamespace;if(!i||r.fileSystemNamespace!==i)throw Error("Storage scope does not match the calling application");let n="string"==typeof r.mutationId?r.mutationId:void 0;if(void 0!==r.fileSystemOperation){let i=r.fileSystemOperation;if(!o(i)||"string"!=typeof i.name||!Object.hasOwn(eQ,i.name)||!o(i.params))throw Error("Invalid synchronous file operation");return to({...e,name:i.name,params:i.params},t,n)}let a={storageChanges:o(r.storageChanges)?r.storageChanges:void 0,clearStorage:!0===r.clearStorage,fileSystemChanges:o(r.fileSystemChanges)?r.fileSystemChanges:void 0,mutationId:n};return await ev(i,async()=>{try{await ex(i,a)}catch(e){throw e_(i,a.mutationId),e}}),_(e,{})}},...{"doubao.canIUse":{handler:(e,t)=>{let{schema:r}=e.params;return _(e,{result:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:E;return t.canIUse(e,{apiRegistry:t})}(r,null==t?void 0:t.apiRegistry)})}},"doubao.getAccountInfo":{handler:(e,t)=>{var r;return _(e,X(null==t||null==(r=t.navigation)?void 0:r.getPackageInfo(),null==t?void 0:t.globalProps))},syncResult:e=>X(Y(e),null==e?void 0:e.globalProps)},"doubao.getPackageInfo":{handler:(e,t)=>{var r;return _(e,B(null==t||null==(r=t.navigation)?void 0:r.getPackageInfo()))},syncResult:e=>B(Y(e))},"doubao.getAppBaseInfo":{handler:(e,t)=>_(e,Z(null==t?void 0:t.globalProps)),syncResult:e=>Z(null==e?void 0:e.globalProps)},"doubao.getMenuButtonBoundingClientRect":{handler:(e,t)=>_(e,R(null==t?void 0:t.globalProps)),syncResult:e=>R(null==e?void 0:e.globalProps)},"doubao.getSystemInfo":{handler:(e,t)=>_(e,J(null==t?void 0:t.globalProps)),syncResult:e=>J(null==e?void 0:e.globalProps)},"doubao.getWindowInfo":{handler:(e,t)=>_(e,F(null==t?void 0:t.globalProps)),syncResult:e=>F(null==e?void 0:e.globalProps)},"doubao.getDeviceInfo":{handler:(e,t)=>_(e,V(null==t?void 0:t.globalProps)),syncResult:e=>V(null==e?void 0:e.globalProps)},"doubao.getNetworkType":{handler:e=>_(e,K()),syncResult:K}}};E.registerMany(tg,{override:!0}),E.registerEventSources({onThemeChange:e=>{let t=matchMedia("(prefers-color-scheme: dark)"),r=()=>e({appTheme:matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"});return t.addEventListener("change",r),()=>t.removeEventListener("change",r)}},{override:!0});class tf{router;navigation;onEmpty;runtime;callers=new Map;destroyed=!1;performance=new e9;applicationLifecycle=new AbortController;nextPerformancePageId=Math.floor(1e12*Math.random());eventKey=Symbol("application events");applicationEvents;applicationEventKey;unsubscribeStorage;getApplicationEvents(){var e,t,r;let i=(null==(e=this.runtime)?void 0:e.getFileSystemNamespace())??this.eventKey;if(this.applicationEventKey!==i){let e,n;null==(t=this.applicationEvents)||t.release(),this.applicationEventKey=i,this.applicationEvents=(r=e=>{for(let t of this.callers.values())t.events.isSubscribed(e.name)&&t.send(e)},e=te.get(i)??{receivers:new Set,recent:[]},te.set(i,e),e.receivers.add(r),n=()=>{let t=Date.now();e.recent=e.recent.filter(e=>1e4>=Math.abs(t-e.timestamp))},{publish(t){for(let r of(n(),e.recent.push({message:t,timestamp:t.timestamp??Date.now()}),[...e.receivers]))r(t)},replay(t,r,i){for(let a of(n(),e.recent))a.message.name===t&&a.timestamp>=r&&i(a.message)},release(){e.receivers.delete(r),0===e.receivers.size&&te.delete(i)}})}return this.applicationEvents}constructor(e,t,r,i){this.router=e,this.navigation=t,this.onEmpty=r,this.runtime=i}get apiRegistry(){var e;return(null==(e=this.runtime)?void 0:e.apiRegistry)??E}register(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:()=>{},t=arguments.length>1?arguments[1]:void 0,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(this.destroyed)throw Error("RuntimeBridge was destroyed");let i=Symbol("caller");this.getApplicationEvents();let n=(null==t?void 0:t.apiRegistry)??this.apiRegistry;this.unsubscribeStorage??=ew(e=>{for(let t of this.callers.values())t.fileSystemNamespace===e.fileSystemNamespace&&t.events.emitPrivate(e1,e)});let a=n.createEventController((t,r)=>{e({type:"event",name:t,params:r,timestamp:Date.now()})});return this.callers.set(i,{abortController:new AbortController,send:e,options:t,events:a,main:r}),i}resolveStorageNamespace(e,t,r){var i,n,a;return(null==(i=this.runtime)?void 0:i.getFileSystemNamespace())??(null==(n=e.options)?void 0:n.fileSystemNamespace)??r??eu(t,null==(a=e.options)?void 0:a.userId)}async prepareStorage(e,t,r){let i=this.getCaller(e),n=this.resolveStorageNamespace(i,t,r);if(i.fileSystemNamespace!==n){var a;null==(a=i.storage)||a.release(),i.storage=void 0,i.fileSystemNamespace=n}i.storage??=ef(n),await i.storage.ready}createSyncBridgeData(e,t,r){var i;let n=this.getCaller(e),a=function(e,t){var r;let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:eu(e),n=arguments.length>3?arguments[3]:void 0,a=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:E;return e.getSupportedNames({apiRegistry:e})}(t);return{hostFileSystem:Object.keys(eQ).every(r=>null==t?void 0:t.canIUse(r,{globalProps:e})),fileSystemNamespace:i,...ey(i),hostStorage:!!(null==t?void 0:t.canIUse("doubao.setStorage",{globalProps:e})),apiResults:(r=null==e?void 0:e.packageInfo,(t??E).getSyncResults({globalProps:e,navigation:n,packageInfo:r})),supportedAPIs:a}}(t,(null==(i=n.options)?void 0:i.apiRegistry)??this.apiRegistry,this.resolveStorageNamespace(n,t,r),this.navigation);return a.performance=this.performance.snapshot(),n.fileSystemNamespace=a.fileSystemNamespace,a.supportedAPIs.push(...e8,e1),a}beginPerformance(e,t){var r,i,n;let a=this.getCaller(e),s=t.globalProps??{},l=o(s.__VIEW_CONTEXT__)?s.__VIEW_CONTEXT__:{},d=o(s[e5])?s[e5]:l,u="PAGE"===t.containerType,c=null==(i=this.navigation)||null==(r=i.getCurrentPages().at(-2))?void 0:r.route.split("?")[0],p=null==(n=[...this.callers.values()].findLast(e=>{var t;return(null==(t=e.performanceTrace)?void 0:t.path)===c}))?void 0:n.performanceTrace;a.performanceTrace={startTime:Date.now(),moduleName:`${t.resourceUrl}#main-thread`,...u?{path:"string"==typeof l.pageUrl?l.pageUrl:String(s.__LOCATION__??"").split("?")[0],pageId:++this.nextPerformancePageId,navigationType:s.__WEB_NAVIGATION_TYPE__??"openPage",referrerPath:null==p?void 0:p.path,referrerPageId:null==p?void 0:p.pageId}:"WIDGET"===t.containerType?{widgetId:"string"==typeof d.widgetId?d.widgetId:void 0,widgetInstanceId:"string"==typeof d.widgetInstanceId?d.widgetInstanceId:void 0,isAppColdLaunch:![...this.callers.values()].some(e=>{var t;return null==(t=e.performanceTrace)?void 0:t.completed})}:{}}}resetApplication(){this.applicationLifecycle.abort(),this.applicationLifecycle=new AbortController,this.performance.reset()}publishPerformance(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];for(let t of this.callers.values())t.events.emitPrivate(e1,{performance:this.performance.snapshot()}),e.length&&t.events.emit(e4,{entries:e})}getCaller(e){let t=this.callers.get(e);if(!t)throw Error("Caller was detached from the RuntimeBridge");return t}async handleMessage(e,t,r){var i;let n=this.getCaller(e);if(!v(t))return{routed:!1};if("applet.subscribeEvent"===t.name||"applet.unsubscribeEvent"===t.name){let e=o(t.params)?t.params:{},i="string"==typeof e.eventName?e.eventName:"",a="applet.subscribeEvent"===t.name&&!n.events.isSubscribed(i);if(tt[t.name](t,{...r,events:n.events}),"applet.subscribeEvent"===t.name&&i===e1&&(null==r?void 0:r.environment)!=="sandbox"){let e=this.resolveStorageNamespace(n,null==r?void 0:r.globalProps,n.fileSystemNamespace??(null==r?void 0:r.fileSystemNamespace));n.events.emitPrivate(i,{performance:this.performance.snapshot(),fileSystemNamespace:e,...ey(e)})}return a&&i&&"number"==typeof e.timestamp&&this.getApplicationEvents().replay(i,e.timestamp,n.send),{routed:!1}}return(null==(i=t.target)?void 0:i.scope)!=="main"||"self"!==t.target.target||!this.router||n.main?{routed:!1}:this.router.call(e,t)}async dispatch(e,t,r,i,n){var a,s,l;let d=arguments.length>5&&void 0!==arguments[5]?arguments[5]:"inline",u=this.callers.get(e);if(!u)return;let c=u.options,p={containerType:n.containerType,element:n.element},h="AppletBridgeModule"===i&&"postMessage"===t;if(h){let e=function(e,t){var r,i;if(!("object"!=typeof(r=e)||null===r||Array.isArray(r))&&"event"===r.type&&"doubao.__widgetInteraction"===r.name&&!("object"!=typeof(i=r.params)||null===i||Array.isArray(i))&&"tap"===i.type&&Number.isSafeInteger(i.sequence)&&"number"==typeof i.sequence&&i.sequence>0)return e7(e,t)}(r,null==c?void 0:c.onWidgetInteraction);if(e)return await e}let m=await this.handleMessage(e,r,n);if(m.routed)return await m.result;let g=await (null==c||null==(a=c.appletSessionMessageHandler)?void 0:a.call(c,r,p));if(null==g?void 0:g.routed)return await g.result;"iframe"!==d&&h&&b(r)&&"__bridge_ready__"===r.name&&(null==c||null==(s=c.onReady)||s.call(c));let f=h&&y(r),w="inline"===d&&"sandbox"!==n.environment;if(f&&w&&"TOOL"!==n.containerType)return u.send(r),r;let S=r=>("iframe"!==d&&"postMessage"===t&&y(r)&&this.callers.get(e)===u&&u.send(r),r);try{if(h&&v(r)&&"sandbox"!==n.environment){let e=o(r.params)?r.params:{};if(r.name===e6){let t=u.performanceTrace?this.performance.recordTiming(u.performanceTrace,e.timing):[];return t.length&&this.publishPerformance(t),S(_(r,{}))}if(r.name===e2)return S(_(r,{entries:(l=this.performance.snapshot(),l.entries.filter(t=>(void 0===e.entryType||t.entryType===e.entryType)&&(void 0===e.name||t.name===e.name)).map(e=>({...e})))}));if(r.name===e3)return this.performance.setBufferSize(e.size),this.publishPerformance(),S(_(r,{}));if("doubao.canIUse"===r.name&&e8.includes(String(e.schema)))return S(_(r,{result:!0}))}let a=this.runtime?this.runtime.nativeModulesCallHandler:null==c?void 0:c.nativeModulesCallHandler,s=await (null==a?void 0:a(t,r,i,p));if(void 0===s&&h&&b(r)&&"__bridge_ready__"!==r.name){this.callers.get(e)===u&&this.getApplicationEvents().publish(r);return}if(f){let e=void 0===s?r:s;if("sandbox"===n.environment||void 0===s&&w)return S(e);return e}let d=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0,r=e.apiRegistry??E;return(i,n,a)=>{if(("AppletJSModule"!==a||"log"!==i)&&"AppletBridgeModule"===a&&"postMessage"===i)return r.dispatch(n,e,t)}}({...n,signal:u.abortController.signal,getAppletContext:null==c?void 0:c.getAppletContext,applicationLifecycle:this.runtime?{owner:this.applicationLifecycle,signal:this.applicationLifecycle.signal}:void 0,fileSystemNamespace:this.resolveStorageNamespace(u,n.globalProps,u.fileSystemNamespace??n.fileSystemNamespace),navigation:this.navigation,apiRegistry:(null==c?void 0:c.apiRegistry)??this.apiRegistry,events:u.events,emitEvent:(e,t)=>u.events.emit(e,t)},null==c?void 0:c.onUnsupportedAPI),m=void 0===s?await d(t,r,i):s;if(h&&v(r)&&r.name===e0&&y(m)&&o(m.params)&&1!==m.params.code){let e=["Synchronous API persistence failed",m.params];a?await a("log",{level:"error",args:e},"AppletJSModule",p):console.error(...e)}return S(m)}catch(e){if("iframe"===d)throw e;return S(v(r)?I(r,e):void 0)}}handleMainBridgeMessage(e){var t;return!this.destroyed&&(null!=(t=this.router)&&!!t.handleMainBridgeMessage(e)||!!b(e)&&"__bridge_ready__"!==e.name&&(this.getApplicationEvents().publish(e),!0))}setVisible(e,t){var r;null==(r=this.callers.get(e))||r.events.setVisible(t)}unregister(e){var t,r,i,n;let a=this.callers.get(e);a&&(this.callers.delete(e),null==(t=a.storage)||t.release(),this.callers.size||(null==(i=this.unsubscribeStorage)||i.call(this),this.unsubscribeStorage=void 0),a.abortController.abort(),a.events.destroy(),null==(r=this.router)||r.cancel(e),a.main||this.destroyed||[...this.callers.values()].some(e=>!e.main)||null==(n=this.onEmpty)||n.call(this))}fail(e){var t;null==(t=this.router)||t.fail(e)}destroy(){var e,t;if(!this.destroyed)for(let r of(this.destroyed=!0,null==(e=this.applicationEvents)||e.release(),this.applicationEvents=void 0,this.applicationLifecycle.abort(),null==(t=this.router)||t.destroy(),this.callers.keys()))this.unregister(r)}}let tv=/(?:^|[.-])[a-f\d]{8,}(?=[.-]|$)/i;function ty(e){let t=new URL(e),r=t.pathname.slice(t.pathname.lastIndexOf("/")+1),i=j();return i&&!tv.test(r)&&t.searchParams.set("__doubao_resource_reload",i),t.href}function tb(e){return"localhost"===e||"::1"===e||/^127(?:\.\d{1,3}){3}$/.test(e)}function tw(e){if(!e.resourceUrl)throw Error("Container.render requires a resourceUrl");return e.resourceUrl}function t_(e){return e.containerType??"PAGE"}function tS(e){return"WIDGET"===e?"content":"fill"}function tx(e){if("function"==typeof CustomEvent)return new CustomEvent("error",{detail:{error:e}});let t=new Event("error");return Object.defineProperty(t,"detail",{value:{error:e}}),t}class tI{container;options;sandboxUrl;targetOrigin;bridge=null;caller;connected=!1;failed=!1;handshakeTimer=null;loaded=!1;loadCount=0;port=null;preparedForRender=!1;preparedContainerType=null;renderMessage=null;view=null;constructor(e){let t=new URL(e.sandboxUrl??"https://apps-web-sdk-sandbox.doubaocdn.com/sandbox");if("https:"!==t.protocol&&!("http:"===t.protocol&&tb(t.hostname)))throw Error("iframe isolation url must use HTTPS (HTTP is only allowed on localhost)");this.container=e.container,this.options=e,this.sandboxUrl=ty(t),this.targetOrigin=t.origin}get element(){return this.view}prepare(e){this.clear();try{this.createView(e),this.preparedForRender=!0}catch(e){throw this.clear(),e}}createView(e){var t,r;if(new URL((null==(t=globalThis.location)?void 0:t.href)??"http://localhost/").origin===this.targetOrigin)return this.abortRender(Error("iframe isolation requires a cross-origin sandbox URL"));if(this.view)return this.preparedContainerType!==e?this.abortRender(Error("iframe container type cannot change after preparation")):this.view;let i=document.createElement("iframe");i.className=this.options.className??"doubao-web-container-view",i.dataset.containerType=e,i.dataset.webSizing=tS(e),i.referrerPolicy="no-referrer",i.title="Doubao app content",i.sandbox.add("allow-scripts","allow-same-origin");let n=tb((null==(r=globalThis.location)?void 0:r.hostname)??"");return n&&i.setAttribute("credentialless",""),i.setAttribute("allow",n?"picture-in-picture 'none'; local-network-access 'src'; loopback-network 'src'":"picture-in-picture 'none'"),i.src=this.sandboxUrl,i.style.display="APP"===e||"TOOL"===e?"none":"block",i.style.border="0",i.style.width="100%",i.style.height="WIDGET"===e?"0px":"100%",i.addEventListener("load",()=>this.handleLoad()),this.view=i,this.preparedContainerType=e,this.container.replaceChildren(i),i}render(e){var t;this.preparedForRender||this.clear(),this.preparedForRender=!1;let r=t_(e),i=new URL(tw(e),document.baseURI).href,n=e.initData??{},a={...G(),...e.globalProps??{}};this.bridge=e.bridge??(null==(t=this.options.runtime)?void 0:t.bridge)??new tf,this.caller=e.bridgeCaller??this.bridge.register(e=>this.sendBridgeMessage(e),e.bridge||this.options.runtime?{...this.options,apiRegistry:void 0}:this.options,"APP"===r);let s=this.bridge,o=this.caller;try{let t=this.createView(r);return s.prepareStorage(o,a,this.options.fileSystemNamespace).then(()=>{var t,l,d;if(this.caller!==o)return;s.beginPerformance(o,{...e,containerType:r,globalProps:a});let u=s.createSyncBridgeData(o,a,this.options.fileSystemNamespace);this.renderMessage={type:"render",captureWidgetTap:this.options.captureWidgetTap,resourceUrl:i,resourceRoot:(null==(t=e.applicationPackage)?void 0:t.resourceRoot)??(null==(d=this.options.runtime)||null==(l=d.packageInfo)?void 0:l.resourceRoot),containerType:r,initData:n,globalProps:a,syncBridgeData:u},this.connected?this.postOrFail(this.renderMessage):this.loaded&&this.connect()}).catch(e=>{this.caller===o&&this.fail(e instanceof Error?e:Error(String(e)))}),t}catch(e){throw this.clear(),e}}clear(){var e,t;this.connected&&this.post({type:"dispose"}),this.destroyChannel(),this.caller&&(null==(t=this.bridge)||t.unregister(this.caller)),this.caller=void 0,this.bridge=null,null==(e=this.view)||e.remove(),this.view=null,this.preparedContainerType=null,this.renderMessage=null,this.connected=!1,this.failed=!1,this.loaded=!1,this.loadCount=0,this.preparedForRender=!1,this.container.replaceChildren()}setVisible(e){if(this.caller){var t;null==(t=this.bridge)||t.setVisible(this.caller,e)}}sendEvent(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.postOrFail({type:"global-event",name:e,params:t})}sendBridgeMessage(e){this.postOrFail({type:"bridge-message",message:e})}sendGlobalEvent(e,t){this.postOrFail({type:"raw-global-event",name:e,params:t})}updateData(e){this.renderMessage&&(this.renderMessage.initData=e),this.postOrFail({type:"update-data",data:e})}updateGlobalProps(e){this.renderMessage&&(this.renderMessage.globalProps={...this.renderMessage.globalProps,...e}),this.postOrFail({type:"update-global-props",props:e})}reload(){this.post({type:"reload"})}abortRender(e){var t,r;throw null==(t=(r=this.options).onError)||t.call(r,e,tx(e)),e}handleLoad(){this.failed||!this.view||((this.loadCount+=1,this.loadCount>1)?this.fail(Error("iframe navigated after the sandbox runtime loaded")):(this.loaded=!0,this.renderMessage&&this.connect()))}connect(){if(this.failed||!this.view||this.connected||this.port)return;let e=new MessageChannel;this.port=e.port1,e.port1.onmessage=e=>this.handleMessage(e),e.port1.onmessageerror=e=>this.fail(Error("iframe message could not be decoded"),e),e.port1.start(),this.handshakeTimer=setTimeout(()=>this.fail(Error("iframe sandbox handshake timed out")),1e4);let t={type:"doubao-web-sdk:connect",protocolVersion:1,sdkVersion:j()??""};try{var r;null==(r=this.view.contentWindow)||r.postMessage(t,this.targetOrigin,[e.port2])}catch(e){this.fail(e instanceof Error?e:Error(String(e)))}}handleMessage(e){var t,r,i;if(!e.data||"object"!=typeof e.data)return void this.fail(Error("iframe sandbox sent an invalid protocol message"),e);let n=e.data;if(!this.connected)return"connected"!==n.type||1!==n.protocolVersion?void this.fail(Error("iframe sandbox protocol version mismatch"),e):(this.connected=!0,this.clearHandshakeTimer(),void(this.renderMessage&&this.postOrFail(this.renderMessage)));switch(n.type){case"ready":null==(t=(r=this.options).onReady)||t.call(r);break;case"error":this.fail(Error(n.message),e);break;case"resize":(null==(i=this.renderMessage)?void 0:i.containerType)!=="WIDGET"||!Number.isFinite(n.height)||n.height<0?this.fail(Error("only Widget containers may resize the iframe"),e):this.view&&(this.view.style.height=`${n.height}px`,this.view.height=String(n.height));break;case"native-call":!Number.isSafeInteger(n.requestId)||n.requestId<=0||("AppletBridgeModule"!==n.moduleName||"postMessage"!==n.name)&&("AppletJSModule"!==n.moduleName&&"LynxConsoleModule"!==n.moduleName&&"Console"!==n.moduleName||"log"!==n.name)?this.fail(Error("iframe sandbox sent an invalid bridge call"),e):this.handleNativeCall(n);break;case"connected":this.fail(Error("iframe sandbox connected more than once"),e);break;default:this.fail(Error("iframe sandbox sent an invalid protocol message"),e)}}async handleNativeCall(e){let t;if(!this.renderMessage||!this.view)return;let r=this.bridge,i=this.caller;if(r&&i){try{t=await r.dispatch(i,e.name,e.data,e.moduleName,{containerType:this.renderMessage.containerType,element:this.view,globalProps:this.renderMessage.globalProps,fileSystemNamespace:this.renderMessage.syncBridgeData.fileSystemNamespace},"iframe")}catch(t){if(this.bridge!==r||this.caller!==i)return;this.postOrFail({type:"bridge-result",requestId:e.requestId,error:x(t)});return}this.bridge===r&&this.caller===i&&this.postOrFail({type:"bridge-result",requestId:e.requestId,result:t})}}post(e){this.connected&&this.port&&this.port.postMessage(e)}postOrFail(e){try{this.post(e)}catch(e){this.fail(e instanceof Error?e:Error(String(e)))}}fail(e){var t,r,i,n;let a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tx(e);this.failed||(this.failed=!0,this.destroyChannel(),this.caller&&(null==(n=this.bridge)||n.unregister(this.caller)),this.caller=void 0,this.bridge=null,null==(t=this.view)||t.remove(),this.view=null,this.renderMessage=null,null==(r=(i=this.options).onError)||r.call(i,e,a))}clearHandshakeTimer(){null!==this.handshakeTimer&&clearTimeout(this.handshakeTimer),this.handshakeTimer=null}destroyChannel(){var e;this.clearHandshakeTimer(),null==(e=this.port)||e.close(),this.port=null,this.connected=!1}}let tk={mode:"iframe",createContainer:e=>new tI(e)};function tC(){var e;return(null==(e=globalThis.location)?void 0:e.href)??"http://localhost/"}function tE(e){return new URL(e,tC()).toString()}function tN(e,t){if(!t)return e;let r=new URL(e,tC());return r.searchParams.set("__doubao_resource_reload",t),r.toString()}class tT{options;packages=new Map;resolveManifestUrl;resourceUrlVersion;constructor(e={}){this.options=e,this.resolveManifestUrl=e.resolveManifestUrl,this.resourceUrlVersion=e.resourceUrlVersion}configure(e){e.resolveManifestUrl&&(this.resolveManifestUrl=e.resolveManifestUrl),"resourceUrlVersion"in e&&(this.resourceUrlVersion=e.resourceUrlVersion)}async getPackageSource(e){if(arguments.length>1&&void 0!==arguments[1]&&arguments[1],!this.resolveManifestUrl)throw Error("PackageManager requires resolveManifestUrl");return{manifestUrl:await this.resolveManifestUrl({appId:e})}}cached(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};r.signal&&g(r.signal);let i=this.packages.get(e);return(!i||r.forceReload)&&(i=t(),this.packages.set(e,i),i.catch(()=>{this.packages.get(e)===i&&this.packages.delete(e)})),r.signal?f(()=>i,r.signal):i}async fetchPackage(e,t){return{manifestUrl:e,resourceRoot:t,manifest:await p(e,{fetcher:this.options.fetcher})}}async loadPackage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t.signal&&g(t.signal);let{manifestUrl:r,resourceRoot:i}=await this.getPackageSource(e,t),n=tE(r),a=await this.cached(n,()=>this.fetchPackage(n,i),t);if(e&&a.manifest.appId&&a.manifest.appId!==e)throw Error("Resolved package appId must match the requested application");return a}resolveWidget(e,t){let r=this.tryResolveWidgetFromPackage(e,t),i=e.manifest.appRuntimeEntry?h(e.manifestUrl,e.manifest.appRuntimeEntry):void 0;return{packageInfo:e,appId:e.manifest.appId,appName:(null==r?void 0:r.appName)??e.manifest.name,icon:(null==r?void 0:r.iconSrc)??e.manifest.iconSrc,appRuntimeEntry:i?tN(i,e.resourceUrlVersion??this.resourceUrlVersion):void 0,resourceUrl:(null==r?void 0:r.resourceUrl)??"",titleType:null==r?void 0:r.entry.titleType,boxType:null==r?void 0:r.entry.boxType}}preload(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.loadPackage(e,t)}setPackage(e){this.packages.set(tE(e.manifestUrl),Promise.resolve(e))}deletePackage(e){this.packages.delete(tE(e))}clearPackageCache(e){e?this.deletePackage(e):this.packages.clear()}resolveWidgetEntry(e,t){let r=e.manifest.name??t.name,i=h(e.manifestUrl,t);return{appId:e.manifest.appId,entry:t,iconSrc:e.manifest.iconSrc??u(t.icons),appName:r,resourceUrl:i?tN(i,e.resourceUrlVersion??this.resourceUrlVersion):void 0}}tryResolveWidgetFromPackage(e,t){let r=e.manifest.getOptionalWidgetEntry(t);if(r)return this.resolveWidgetEntry(e,r)}}class tA{send;ready;pendingCalls=new Map;destroyed=!1;nextCallbackId=1e6;constructor(e,t){this.send=e,this.ready=t}call(e,t){if(this.destroyed)return Promise.reject(Error("RuntimeRouter was destroyed"));let r=this.nextCallbackId++,i={...t,callbackId:r};return new Promise((n,a)=>{this.pendingCalls.set(r,{callbackId:t.callbackId,reject:a,resolve:n,caller:e}),(async()=>{try{await this.ready(),this.pendingCalls.has(r)&&this.send(i)}catch(t){let e=this.pendingCalls.get(r);if(!e)return;this.pendingCalls.delete(r),e.reject(t instanceof Error?t:Error(String(t)))}})()})}handleMainBridgeMessage(e){if(y(e)){let t=this.pendingCalls.get(e.callbackId);return!!t&&(this.pendingCalls.delete(e.callbackId),t.resolve({routed:!0,result:{...e,callbackId:t.callbackId}}),!0)}return!1}cancel(e){for(let[t,r]of this.pendingCalls)r.caller===e&&(this.pendingCalls.delete(t),r.reject(Error("Caller was detached from the RuntimeBridge")))}destroy(){this.destroyed||(this.destroyed=!0,this.fail(Error("RuntimeRouter was destroyed")))}fail(e){for(let t of this.pendingCalls.values())t.reject(e);this.pendingCalls.clear()}}let tM="onBackground",tj="onDestroy",tR="onForeground",tP="onHide",tL="onShow";function tD(e,t){let r=function(e){let{pageId:t,viewData:r}=function(e){if(!e)throw Error("route url must be a non-empty string");let t=e.indexOf("?"),r=-1===t?e:e.slice(0,t);if(!r)throw Error("route url must include a page path");let i={};return new URLSearchParams(-1===t?"":e.slice(t+1)).forEach((e,t)=>{i[t]=e}),{pageId:r,viewData:i}}(e.url),i=JSON.stringify(r);return{pageId:t,initData:{viewData:r,viewContext:{}},globalProps:{__LOCATION__:e.url,__RENDER_DATA__:i,__VIEW_CONTEXT__:{}}}}(e);return{...r,entry:t.getPageEntry(r.pageId)}}function tO(e,t){var r;let i=Object.entries((null==(r=t.initData)?void 0:r.viewData)??{}).map(e=>{let[t,r]=e;return`${encodeURIComponent(t)}=${encodeURIComponent(r)}`}).join("&");return{route:`${e}${i?`?${i}`:""}`}}function tU(e,t){return{packageInfo:t,...e}}function t$(e){return{appId:e.appId,name:e.name,iconSrc:e.iconSrc,versionName:e.versionName}}function tq(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return tU(t,t$(e))}function tB(e){if(o(e))return{...e};if("string"!=typeof e)return{};try{let t=JSON.parse(e);return o(t)?t:{}}catch{return{}}}class tF{pageHost;visible=!0;className;onError;appGlobalProps;appInitData;getRuntimeGlobalProps;configuredFileSystemNamespace;userId;runtimeKernel;packageSnapshot;packageLoading;packageSource;lifecycle=new AbortController;get packageInfo(){if(this.destroyed)throw Error("Runtime was destroyed");if(!this.packageSnapshot)throw Error("Runtime package is not loaded");return this.packageSnapshot}get manifest(){return this.packageInfo.manifest}get manifestUrl(){return this.packageInfo.manifestUrl}pageCapsule;resolvedFileSystemNamespace;appRuntime=null;appStart=null;bridge;packageManager;sandboxUrl;viewContext;appGroupId;destroyed=!1;pendingAppEvents=[];clearingAppRuntime=!1;appCallController=new AbortController;apiContextOwner={};stack=[];pendingPages=[];nextPageIndex=0;constructor(e,t=tk,r){this.sandboxUrl=e.sandboxUrl,this.packageManager=e.packageManager??new tT({resolveManifestUrl:()=>this.manifestUrl});let i=new tA(e=>this.sendAppBridgeMessage(e),async()=>{if(await this.ensureAppRuntime(),!this.appStart)throw Error("No Web entry configured for app runtime");return this.appStart.promise});this.appGroupId=e.appGroupId,this.viewContext=e.viewContext,this.pageHost=e.pageHost,this.runtimeKernel=t,"manifest"in e?(this.packageSnapshot={manifest:e.manifest,manifestUrl:String(e.manifestUrl),resourceRoot:e.resourceRoot,resourceUrlVersion:""},e.packageManager||this.packageManager.setPackage(this.packageSnapshot)):this.packageSource=e,this.pageCapsule=e.pageCapsule,this.className=e.className,this.onError=e.onError,this.appGlobalProps=e.appGlobalProps,this.appInitData=e.appInitData,this.getRuntimeGlobalProps=e.getRuntimeGlobalProps,this.configuredFileSystemNamespace=e.fileSystemNamespace,this.userId=e.userId,this.resolvedFileSystemNamespace=this.resolveFileSystemNamespace(),this.updateEmptyState(),this.bridge=new tf(i,{getCurrentPages:()=>this.getCurrentPages(),getPackageInfo:()=>this.getPackageInfo(),navigateTo:e=>this.navigateToBridgePage(e),openPage:e=>this.openBridgePage(e),redirectTo:e=>this.redirectToBridgePage(e),reLaunch:e=>this.reLaunchBridgePage(e),navigateBack:e=>this.requestBack(e),setAlertBeforeUnload:(e,t)=>{let r=this.stack.find(e=>e.element===t);return!!r&&(r.alertBeforeUnloadMessage=e,!0)},exitApp:()=>this.exitBridgeApp()},r,{apiRegistry:e.apiRegistry,getFileSystemNamespace:()=>this.fileSystemNamespace,nativeModulesCallHandler:e.nativeModulesCallHandler})}async loadPackage(){var e,t;if(this.destroyed)throw new DOMException("Runtime was destroyed","AbortError");let r=(null==(e=this.packageSource)?void 0:e.signal)?AbortSignal.any([this.lifecycle.signal,this.packageSource.signal]):this.lifecycle.signal;if(!this.packageSnapshot){if(!this.packageLoading){let e=this.packageSource,i=this.packageManager.loadPackage(e.appId,{signal:r,versionTag:e.versionTag??(null==(t=e.viewContext)?void 0:t.versionTag)}).then(e=>{g(r),this.destroyed||this.packageSnapshot||(this.packageSnapshot={...e,resourceUrlVersion:""},this.resolvedFileSystemNamespace=this.resolveFileSystemNamespace())}).catch(e=>{throw this.packageLoading===i&&(this.packageLoading=void 0),e});this.packageLoading=i}let e=this.packageLoading;await f(()=>e,r)}return g(r),this.packageInfo}get fileSystemNamespace(){return this.resolvedFileSystemNamespace}get isDestroyed(){return this.destroyed}get pages(){return this.stack.map(e=>this.toStackEntry(e))}get currentPage(){let e=this.getCurrentStackItem();return e?this.toStackEntry(e):null}setManifest(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.manifestUrl;this.clear(),this.packageSnapshot={...this.packageSnapshot,manifest:e,manifestUrl:String(r),resourceUrlVersion:(null==(t=this.packageSnapshot)?void 0:t.resourceUrlVersion)??"1"},this.packageManager.setPackage(this.packageSnapshot),this.resolvedFileSystemNamespace=this.resolveFileSystemNamespace()}async pushPage(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.packageSnapshot||await this.loadPackage(),this.pushLoadedPage(e)}async pushLoadedPage(e,t){var r,i,n;let a;if(this.destroyed)throw Error("Runtime was destroyed");if(!this.pageHost)throw Error("Opening Pages requires a Runtime pageHost");let s=this.resolvePageEntry(e),l=h(this.manifestUrl,s);if(!l)throw Error(`No Web entry configured for page entry: ${s.id}`);let d=this.lifecycle.signal;if(this.startAppRuntime(),this.appStart&&await this.appStart.promise,g(d),"all"===t)this.clearPages();else if("current"===t){let e=this.stack.pop();e&&this.removeStackItem(e,!1)}let u={...e,globalProps:{...e.globalProps,...null==(r=this.getRuntimeGlobalProps)?void 0:r.call(this)}},c=tN(l,this.packageInfo.resourceUrlVersion),p=e.pageCapsule??this.pageCapsule,m=`page-${++this.nextPageIndex}`,f=(a=tB(null==(n=u.globalProps)?void 0:n.__VIEW_CONTEXT__),{...o(u.initData)?tB(u.initData.viewContext):{},...a,viewId:m,pageName:s.id,pageUrl:s.path}),v=null,y=this.pageHost.createPage({className:this.className,runtime:this,onError:this.onError,onReady:()=>{v&&this.stack.includes(v)&&(v.isReady=!0,this.flushPageLifecycleEvents(v))}},this.runtimeKernel,()=>this.exitBridgeApp());void 0!==e.pageCapsule&&(this.pageCapsule=e.pageCapsule),this.pendingPages.push(tO(s.path,e));try{let t,r,n=y.render({resourceUrl:c,groupId:this.manifest.appId,initData:o(u.initData)?{...u.initData,viewContext:f}:{viewContext:f},globalProps:(t=null==p?void 0:p.statusBarHeight,r="number"==typeof t&&Number.isFinite(t)?{statusBarHeight:t}:{},{...u.globalProps,...r,__VIEW_CONTEXT__:f}),pageCapsule:p}),a=this.getCurrentStackItem();return a&&(null==(i=a.backPrompt)||i.abort(),this.visible&&this.sendPageLifecycleEvent(a,tP),a.page.setVisible(!1)),v={id:m,pageId:s.id,route:s.path,resourceUrl:c,entry:s,element:n,isReady:!1,options:{...e,entry:s,pageCapsule:p},pendingLifecycleEvents:[],page:y},this.stack.push(v),this.updateEmptyState(),v.page.setVisible(this.visible),this.visible&&this.sendPageLifecycleEvent(v,tL),this.sendAppEvent("onPageOpened",{viewId:v.id}),this.toStackEntry(v)}catch(e){throw y.clear(),this.updateEmptyState(),e}finally{this.pendingPages.pop()}}async replacePage(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this.packageSnapshot||await this.loadPackage(),this.destroyed)throw Error("Runtime was destroyed");return this.withPageTransition(()=>this.pushLoadedPage(e,"current"))}async reLaunchPage(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this.packageSnapshot||await this.loadPackage(),this.destroyed)throw Error("Runtime was destroyed");return this.withPageTransition(()=>this.pushLoadedPage(e,"all"))}popPage(){let e=this.stack.pop();return e?this.removeStackItem(e,!0):null}setVisible(e){if(this.destroyed||this.visible===e)return;this.visible=e;let t=this.getCurrentStackItem();t&&(t.page.setVisible(e),this.sendPageLifecycleEvent(t,e?tL:tP)),this.appRuntime&&this.sendAppEvent(e?tR:tM)}requestBack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.getCurrentStackItem();if(!t)return!1;if(1===this.stack.length){var r;return this.setVisible(!1),null==(r=this.pageHost)||r.hide(),!0}let i=()=>{if(this.destroyed||this.getCurrentStackItem()!==t)return;let r=Math.min(Math.max(1,Math.floor(e.delta??1)),this.stack.length-1);for(let e=0;e<r;e+=1)this.popPage()};if(void 0===t.alertBeforeUnloadMessage||!this.pageHost)return i(),!0;if(!t.backPrompt||t.backPrompt.signal.aborted){let e=new AbortController;t.backPrompt=e;let r=r=>{t.backPrompt===e&&(t.backPrompt=void 0,r&&!e.signal.aborted&&i())};this.pageHost.confirmBeforeUnload(t.alertBeforeUnloadMessage,e.signal).then(e=>{r(e)},()=>{r(!0)})}return!0}clear(){this.lifecycle.abort(),this.lifecycle=new AbortController,this.packageLoading=void 0,this.clearPages(),this.clearAppRuntime(),this.bridge.resetApplication(),this.packageSnapshot&&(this.packageSnapshot={...this.packageSnapshot,resourceUrlVersion:String(Number(this.packageSnapshot.resourceUrlVersion??0)+1)})}async restart(){if(this.packageSnapshot||await this.loadPackage(),this.destroyed)throw Error("Runtime was destroyed");await this.withPageTransition(async()=>{let e=this.stack.map(e=>{let{options:t}=e;return t});for(let t of(this.clear(),e))await this.pushLoadedPage(t)})}reload(){var e;null==(e=this.getCurrentStackItem())||e.page.reload()}destroy(){var e;this.destroyed||(this.destroyed=!0,this.bridge.destroy(),this.clear(),null==(e=this.pageHost)||e.destroy())}clearPages(){for(;this.stack.length>0;){let e=this.stack.pop();e&&this.removeStackItem(e,!1)}}async withPageTransition(e){let t=this.bridge.register();try{return await e()}finally{this.bridge.unregister(t)}}removeStackItem(e,t){var r;null==(r=e.backPrompt)||r.abort();let i=this.toStackEntry(e);this.sendPageLifecycleEvent(e,tj),e.page.clear();let n=this.getCurrentStackItem();return t&&n&&this.visible&&(n.page.setVisible(!0),this.sendPageLifecycleEvent(n,tL)),this.updateEmptyState(),i}async ensureAppRuntime(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.packageSnapshot||await this.loadPackage(),this.startAppRuntime(e)}startAppRuntime(){var e,t,r;let i,n,a,s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this.destroyed)throw Error("Runtime was destroyed");if(this.clearingAppRuntime)throw Error("Runtime is being cleared");if(null==(e=this.appStart)?void 0:e.error)throw this.appStart.error;if(this.appRuntime||!this.manifest.appRuntimeEntry)return;let o=h(this.manifestUrl,this.manifest.appRuntimeEntry);if(!o)throw Error("No Web entry configured for app runtime");let l=tN(o,this.packageInfo.resourceUrlVersion),d=new Promise((e,t)=>{i=e,n=t});d.catch(()=>{});let u={promise:d,resolve:i,reject:n,error:void 0};this.appStart=u;let c=e=>{var t;this.appStart!==u||this.destroyed||this.clearingAppRuntime||((null==(t=this.appRuntime)?void 0:t.isReady)||(u.error=e,u.reject(e)),this.bridge.fail(e))},p=this.appCallController.signal;try{a=function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:document.body,i=document.createElement("div");i.className="doubao-runtime-app",i.hidden=!0,i.style.display="none";let n=t.createContainer({...e,container:i});return{render:e=>(r.append(i),n.render(e)),clear(){n.clear(),i.remove()},sendEvent:n.sendEvent.bind(n),sendBridgeMessage:n.sendBridgeMessage.bind(n)}}({runtime:this,sandboxUrl:this.sandboxUrl,className:this.className,onError:(e,t)=>{var r;this.appStart!==u||this.destroyed||this.clearingAppRuntime||(c(e),null==(r=this.onError)||r.call(this,e,t))},appletSessionMessageHandler:(e,t)=>{var r;return this.appStart!==u||this.destroyed||this.clearingAppRuntime||this.bridge.handleMainBridgeMessage(e)?{routed:!0}:(null==(r=s.appletSessionMessageHandler)?void 0:r.call(s,e,t))??{routed:!1}},getAppletContext:()=>({owner:this.apiContextOwner,signal:p,source:"app",viewContext:s.viewContext??this.viewContext}),onReady:()=>{var e;let t=this.appRuntime;this.clearingAppRuntime||!t||t.container!==a||t.isReady||u.error||(t.isReady=!0,this.flushAppEvents(),u.resolve(),null==(e=s.onReady)||e.call(s))}},this.runtimeKernel,null==(t=this.pageHost)?void 0:t.container),this.appRuntime={container:a,isReady:!1,pendingEvents:[{name:this.visible?tR:tM,params:{}},...this.pendingAppEvents.splice(0)]};let e=void 0!==s.groupId?s.groupId:this.appGroupId;a.render({bridge:this.bridge,resourceUrl:l,groupId:null===e?void 0:e??this.manifest.appId,containerType:"APP",initData:this.appInitData??{},globalProps:{...tq(this.manifest,this.appGlobalProps),...null==(r=this.getRuntimeGlobalProps)?void 0:r.call(this)}})}catch(e){throw c(e instanceof Error?e:Error(String(e))),this.appRuntime=null,null==a||a.clear(),e}}clearAppRuntime(){var e;if(this.clearingAppRuntime)return;this.clearingAppRuntime=!0;let t=Error(this.destroyed?"Runtime was destroyed":"Runtime was cleared");null==(e=this.appStart)||e.reject(t),this.bridge.fail(t),this.pendingAppEvents=[];let r=this.appRuntime;(null==r?void 0:r.isReady)&&(this.visible&&r.container.sendEvent(tM),r.container.sendEvent(tj)),null==r||r.container.clear(),this.appCallController.abort(),this.appCallController=new AbortController,this.appRuntime=null,this.appStart=null,this.clearingAppRuntime=!1}sendAppEvent(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=this.appRuntime;if(!this.destroyed&&!this.clearingAppRuntime){if(!r)return void this.pendingAppEvents.push({name:e,params:t});if(!r.isReady)return void r.pendingEvents.push({name:e,params:t});r.container.sendEvent(e,t)}}sendAppBridgeMessage(e){if(!this.clearingAppRuntime){var t;null==(t=this.appRuntime)||t.container.sendBridgeMessage(e)}}flushAppEvents(){let e=this.appRuntime;if(null==e?void 0:e.isReady)for(let t of e.pendingEvents.splice(0))e.container.sendEvent(t.name,t.params)}sendPageLifecycleEvent(e,t){let r,i=(r={viewId:e.id,pageName:e.pageId,pageUrl:e.route},{viewId:e.id,eventName:JSON.stringify(r)});e.isReady?e.page.sendEvent(t,i):e.pendingLifecycleEvents.push({name:t,params:i})}flushPageLifecycleEvents(e){if(e.isReady)for(let t of e.pendingLifecycleEvents.splice(0))e.page.sendEvent(t.name,t.params)}resolvePageEntry(e){return e.entry??this.manifest.getPageEntry(e.pageId)}resolveRoutePageOptions(e){try{return tD(e,this.manifest)}catch(e){throw Object.assign(new w(e instanceof Error?e.message:String(e),104),{cause:e})}}getCurrentStackItem(){return this.stack[this.stack.length-1]??null}updateEmptyState(){var e;null==(e=this.pageHost)||e.setEmpty(0===this.stack.length)}getCurrentPages(){return[...this.stack.map(e=>tO(e.route,e.options)),...this.pendingPages]}getPackageInfo(){var e;return this.packageSnapshot?t$(this.manifest):{appId:null==(e=this.packageSource)?void 0:e.appId}}resolveFileSystemNamespace(){return void 0!==this.configuredFileSystemNamespace?this.configuredFileSystemNamespace:eu({packageInfo:this.getPackageInfo()},this.userId)}withNavigationType(e,t){return{...e,globalProps:{...e.globalProps,__WEB_NAVIGATION_TYPE__:t}}}async openBridgePage(e){this.packageSnapshot||await this.loadPackage();let t=this.resolveRoutePageOptions(e),r=this.resolvePageEntry(t),i=e.mode??"push",n=this.getCurrentStackItem(),a=e=>e.entry.path===r.path,s="replace"===i?n&&a(n)?this.stack.length-1:-1:"navigate"===i||"pop_to"===i?this.stack.findLastIndex(a):-1;if(s>=0){var o;let e=this.stack[s],r=t.globalProps??{};for(e.page.updateGlobalProps({__LOCATION__:r.__LOCATION__,__RENDER_DATA__:r.__RENDER_DATA__}),e.options={...e.options,initData:t.initData,globalProps:{...e.options.globalProps,...r}},null==(o=e.backPrompt)||o.abort();this.stack.length-1>s;)this.removeStackItem(this.stack.pop(),!1);e.page.setVisible(this.visible),n!==e&&this.visible&&this.sendPageLifecycleEvent(e,tL);let i=this.getCurrentPages();for(let e of this.stack)e.page.sendEvent(e1,{apiResults:{"doubao.getCurrentPages":{pages:i}}});this.updateEmptyState();return}"replace"===i||"pop_to"===i?await this.replacePage(t):await this.pushLoadedPage(t)}async navigateToBridgePage(e){this.packageSnapshot||await this.loadPackage(),await this.pushLoadedPage(this.withNavigationType(this.resolveRoutePageOptions(e),"navigateTo"))}async redirectToBridgePage(e){this.packageSnapshot||await this.loadPackage();let t=this.withNavigationType(this.resolveRoutePageOptions(e),"redirectTo");await this.replacePage(t)}async reLaunchBridgePage(e){this.packageSnapshot||await this.loadPackage();let t=this.withNavigationType(this.resolveRoutePageOptions(e),"reLaunch");await this.reLaunchPage(t)}exitBridgeApp(){this.clear()}toStackEntry(e){return{id:e.id,pageId:e.pageId,route:e.route,url:tO(e.route,e.options).route,resourceUrl:e.resourceUrl,entry:e.entry,element:e.element}}}class tW{kernel;autoRelease;runtimes=new Map;packageManagers=new WeakMap;nextPackageManagerId=0;constructor(e,t=!1){this.kernel=e,this.autoRelease=t}acquire(e){var t,r,i,n,a,s,o,l,d,u;let p=e.fileSystemNamespace??eu({packageInfo:{appId:e.appId}},e.userId),h=new URL(e.appRuntimeEntry,null==(t=globalThis.location)?void 0:t.href).href,m=e.packageManager;m&&!this.packageManagers.has(m)&&this.packageManagers.set(m,this.nextPackageManagerId++);let g=[m?this.packageManagers.get(m):"",String(e.sandboxUrl??""),(null==(r=e.packageInfo)?void 0:r.manifestUrl)??"",(null==(i=e.packageInfo)?void 0:i.resourceRoot)??"",e.appId,(null==(n=e.viewContext)?void 0:n.conversationId)??"",p,e.versionTag??(null==(a=e.viewContext)?void 0:a.versionTag)??"",h].join("\0"),f=this.runtimes.get(g);if(f&&!f.isDestroyed)return f;let v=new tF({packageManager:m,pageHost:e.pageHost,sandboxUrl:e.sandboxUrl,manifest:(null==(s=e.packageInfo)?void 0:s.manifest)??new c({manifestVersion:"3.0",packageName:e.appId,appId:e.appId,versionCode:"",applet:{appletId:e.appId,digest:"",appRuntimeEntry:h,pages:[]},widgets:[]}),manifestUrl:(null==(o=e.packageInfo)?void 0:o.manifestUrl)??h,resourceRoot:null==(l=e.packageInfo)?void 0:l.resourceRoot,registerPageController:!1,appGroupId:null,apiRegistry:e.apiRegistry??E,className:e.className,fileSystemNamespace:p,nativeModulesCallHandler:e.nativeModulesCallHandler,appInitData:e.appInitData,appGlobalProps:tU(e.appGlobalProps??{},{appId:e.appId}),getRuntimeGlobalProps:e.getRuntimeGlobalProps,viewContext:{appId:e.appId,conversationId:null==(d=e.viewContext)?void 0:d.conversationId,versionTag:e.versionTag??(null==(u=e.viewContext)?void 0:u.versionTag)},onError:e.onError},this.kernel??tk,this.autoRelease?()=>this.release(v):void 0);return this.runtimes.set(g,v),v}release(e){for(let[t,r]of this.runtimes)if(r===e){this.runtimes.delete(t),e.destroy();return}}destroy(){let e=[...this.runtimes.values()];for(let t of(this.runtimes.clear(),e))t.destroy()}}function tz(e,t){return class extends e{hostOptions;prepared=!1;constructor(e){super({...e,sandboxUrl:e.runtime?e.runtime.sandboxUrl:e.sandboxUrl}),this.hostOptions=e}prepare(e){super.prepare(e),this.prepared=!0}clear(){this.prepared=!1,super.clear()}render(e){var r,i,n;this.prepared||this.clear(),this.prepared=!1;let{application:a,applicationPackage:s,appRuntimeEntry:o,...l}=e,d=(null==a?void 0:a.appId)??(null==(i=l.globalProps)||null==(r=i.packageInfo)?void 0:r.appId),u=(null==a?void 0:a.appRuntimeEntry)??o,c=(null==a?void 0:a.viewContext)??(null==(n=l.globalProps)?void 0:n.__VIEW_CONTEXT__),p=this.hostOptions.runtime??(d&&u?(this.hostOptions.runtimeManager??t()).acquire({appId:d,appRuntimeEntry:u,packageInfo:s,packageManager:this.hostOptions.packageManager,sandboxUrl:this.hostOptions.sandboxUrl,apiRegistry:this.hostOptions.apiRegistry,nativeModulesCallHandler:this.hostOptions.nativeModulesCallHandler,versionTag:(null==a?void 0:a.versionTag)??(null==c?void 0:c.versionTag),viewContext:c,userId:this.hostOptions.userId,fileSystemNamespace:this.hostOptions.fileSystemNamespace}):void 0),h=null==p?void 0:p.bridge.register();try{return super.render({...l,applicationPackage:s,bridge:(null==p?void 0:p.bridge)??l.bridge})}catch(e){throw this.clear(),e}finally{h&&(null==p||p.bridge.unregister(h))}}}}new tW(void 0,!0),r(34974),r(71463),r(25907),r(92151);var tH=r(59314);let tV="embed-webview",tG="__channel_ack__",tJ=new WeakMap,tK=e=>({url:e});function tZ(e){if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}}function tX(e){return"string"==typeof e?e:JSON.stringify(e??{})}let tY=globalThis.HTMLElement??class{},tQ="region-to-decode";function t0(e){if("string"==typeof e)try{e=JSON.parse(e)}catch{return null}if(!e||"object"!=typeof e)return null;let{x:t,y:r,width:i,height:n}=e;return![t,r,i,n].every(Number.isFinite)||t<0||r<0||i<=0||n<=0?null:{x:t,y:r,width:i,height:n}}class t1{element;static observedAttributes=[];image;attributes=new MutationObserver(()=>this.update());resize;viewSize;cropStyle;constructor(e){var t;this.element=e,this.image=(null==(t=e.shadowRoot)?void 0:t.querySelector("#img"))??null,Object.defineProperty(e,tQ,{configurable:!0,get:()=>t0(e.getAttribute(tQ)),set:t=>{let r=t0(t);r?e.setAttribute(tQ,JSON.stringify(r)):e.removeAttribute(tQ)}})}connectedCallback(){this.attributes.observe(this.element,{attributes:!0,attributeFilter:[tQ,"src","mode","auto-size"]}),this.update()}clearCrop=()=>{var e;null==(e=this.cropStyle)||e.remove(),this.cropStyle=void 0};stopRendering(){var e,t,r;null==(e=this.resize)||e.disconnect(),this.resize=void 0,this.viewSize=void 0,null==(t=this.image)||t.removeEventListener("load",this.update),null==(r=this.image)||r.removeEventListener("error",this.clearCrop),this.clearCrop()}update=()=>{var e,t,r;let i=t0(this.element.getAttribute(tQ)),n=this.image;if(!i||!n)return void this.stopRendering();this.resize||(this.resize=new ResizeObserver(e=>{let[t]=e;this.viewSize=t.contentRect,this.update()}),this.resize.observe(this.element),n.addEventListener("load",this.update),n.addEventListener("error",this.clearCrop));let a=n.naturalWidth,s=n.naturalHeight,o=this.element.getAttribute("src"),l=this.element.getRootNode().host,d=o?(null==l||null==(e=l.resolveResource)?void 0:e.call(l,o))??o:o;if(!n.complete||!a||!s||n.getAttribute("src")!==d)return void this.clearCrop();let u=Math.min(i.width,a-i.x),c=Math.min(i.height,s-i.y),p=getComputedStyle(this.element),h=Number.parseFloat(p.paddingLeft)||0,m=Number.parseFloat(p.paddingTop)||0,g=(null==(t=this.viewSize)?void 0:t.width)??this.element.clientWidth-h-(Number.parseFloat(p.paddingRight)||0),f=(null==(r=this.viewSize)?void 0:r.height)??this.element.clientHeight-m-(Number.parseFloat(p.paddingBottom)||0);if(u<=0||c<=0||g<=0||f<=0)return void this.clearCrop();let v=g/u,y=f/c,b=this.element.getAttribute("mode");"aspectFit"===b?v=y=Math.min(v,y):"aspectFill"===b?v=y=Math.max(v,y):"center"===b&&(v=y=1);let w=h+(g-u*v)/2-i.x*v,_=m+(f-c*y)/2-i.y*y;this.cropStyle||(this.cropStyle=this.element.ownerDocument.createElement("style"),this.cropStyle.setAttribute("data-doubao-image-region",""),this.element.shadowRoot.append(this.cropStyle)),this.cropStyle.textContent=`#img {
|
|
2
2
|
position: absolute !important;
|
|
3
3
|
margin: 0 !important;
|
|
4
4
|
padding: 0 !important;
|
package/dist/cli/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"node:module";import{logger as o}from"@rsbuild/core";import e from"chalk";import{Option as a,program as r}from"commander";import{package_namespaceObject as t,dev as n,cliLogger as p,deploy as i,build as c,analyze as s}from"../277~0.js";import{selectDevServerHost as d}from"../427~0.js";function l(){if(!process.env.NODE_ENV){let o=process.argv[2];process.env.NODE_ENV=["build","package","deploy","analyze","perf"].includes(o)?"production":"development"}p.greet(`Doubao Apps SDK v${t.rE}`)}async function m(o){let{devtools:e,host:a,...r}=o,t={...r,host:!0===a?await d():a};return e?{...t,debugDriver:"devtools"}:t}function u(o){return o.option("--app-id <appId>","application ID provided by the platform").option("-c --config <config>","specify the configuration file, can be a relative or absolute path").option("--env-mode <mode>","specify the env mode to load the `.env.[mode]` file"),o}function v(t=process.cwd(),p={},d="0.8.0-rc.
|
|
1
|
+
import"node:module";import{logger as o}from"@rsbuild/core";import e from"chalk";import{Option as a,program as r}from"commander";import{package_namespaceObject as t,dev as n,cliLogger as p,deploy as i,build as c,analyze as s}from"../277~0.js";import{selectDevServerHost as d}from"../427~0.js";function l(){if(!process.env.NODE_ENV){let o=process.argv[2];process.env.NODE_ENV=["build","package","deploy","analyze","perf"].includes(o)?"production":"development"}p.greet(`Doubao Apps SDK v${t.rE}`)}async function m(o){let{devtools:e,host:a,...r}=o,t={...r,host:!0===a?await d():a};return e?{...t,debugDriver:"devtools"}:t}function u(o){return o.option("--app-id <appId>","application ID provided by the platform").option("-c --config <config>","specify the configuration file, can be a relative or absolute path").option("--env-mode <mode>","specify the env mode to load the `.env.[mode]` file"),o}function v(t=process.cwd(),p={},d="0.8.0-rc.11"){r.name("doubao").usage("<command> [options]").version(d),u(r.command("dev")).description("starting the dev server...").option("--host [host]","listen hostname or IP; omit value to select an address interactively").option("--devtools","use DevTools debug driver").action(async e=>{try{await n(await m(e))}catch(e){o.error("Failed to dev"),o.error(e),process.exit(1)}}),u(r.command("build")).description("starting build the applet").option("-a --archive","Archive all package",!1).addOption(Object.assign(new a("--channel <string>","Need channel name"),{short:"-ch",flags:"-ch --channel <string>"})).action(async e=>{try{await c(e)}catch(e){o.error("Failed to build"),o.error(e),process.exit(1)}}),u(r.command("analyze")).description("analyze the applet package").action(async a=>{try{await s(a)}catch(a){o.error(e.red("Failed to analyze")),o.error(a),process.exit(1)}}),u(r.command("deploy")).option("--token <token>","developer open build token for Doubao Apps Platform deploy").option("--app-name, --appName <appName>","app name for Doubao Apps Platform deploy").option("--app-icon, --appIcon <appIcon>","app icon for Doubao Apps Platform deploy").option("--version-tag, --versionTag <versionTag>","version tag for Doubao Apps Platform deploy").description("build and upload the app package").action(async a=>{try{await i({...a,build:!0})}catch(a){o.error(e.red("Failed to deploy")),o.error(a),process.exit(1)}}),r.parse()}export{l as prepareCli,v as runCli};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|