@doubao-dev/kit 0.8.0-rc.2 → 0.8.0-rc.4
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 +50 -49
- 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/chrome-devtools/entrypoints/devtools_app/devtools_app.js +24 -23
- package/dist/assets/web-sdk-debugger/chrome-devtools/panels/wsd-debug/WsdDebug.js +50 -49
- package/dist/assets/web-sdk-debugger/chrome-devtools/panels/wsd-debug/WsdDebugMeta.js +60 -59
- package/dist/assets/web-sdk-debugger/index.html +1 -1
- package/dist/assets/web-sdk-debugger/static/css/index.0f12233d1a.css +1 -0
- package/dist/assets/web-sdk-debugger/static/js/{275.41701d029c.js → 131.bff806410a.js} +31 -31
- package/dist/assets/web-sdk-debugger/static/js/{index.84ba26caa4.js → index.a101f5ffde.js} +8 -7
- package/dist/builder/loader/components-loader/index.js +2 -2
- package/dist/cli/index.js +1 -1
- package/dist/sdk.d.ts +8 -0
- package/dist/sdk.js +35 -34
- package/package.json +1 -1
- package/dist/assets/web-sdk-debugger/static/css/index.c3e710420d.css +0 -1
- /package/dist/assets/web-sdk-debugger/static/js/{275.41701d029c.js.LICENSE.txt → 131.bff806410a.js.LICENSE.txt} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(()=>{"use strict";var e,t,r,i,n,a,s,o,l,d,u,c,p={23556(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 R(){return"0.8.0-rc.2"}function j(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 O(){return"string"==typeof DoubaoAppsSDKVersion?DoubaoAppsSDKVersion:R()??""}function D(){return navigator.userAgentData}function U(){var e;let t=null==(e=D())?void 0:e.brands,r=null==t?void 0:t.find(e=>{let{brand:t}=e;return!/not.a.brand/i.test(t)});if(null==r?void 0:r.brand)return r.brand;let i=navigator.userAgent??"";return/edg\//i.test(i)?"Microsoft Edge":/chrome|crios/i.test(i)?"Chrome":/firefox|fxios/i.test(i)?"Firefox":/safari/i.test(i)?"Safari":"Browser"}function q(){var e,t;let r=null==(e=D())?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 $(){var e;let t=navigator.userAgent??"",r=navigator.platform??"",i=(null==(e=D())?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 z(){return $().platform}function W(){var e,t,r,i,n;let a=navigator.userAgent??"",s=z();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]:z();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=$(),i=navigator.platform||z();return{abi:i,deviceAbi:i,benchmarkLevel:-1,brand:r.brand,model:function(){let e=navigator.userAgent??"",t=z();if("android"===t){var r,i;return(null==(i=/android\s+[\d.]+;\s*([^;)]+)/i.exec(e))||null==(r=i[1])?void 0:r.trim())||"Android"}return"ios"===t?$().brand:"mac"===t||"windows"===t||"linux"===t?navigator.platform||$().brand:U()}(),system:function(){let e=z(),t=W();if("web"!==e){let r=H(e);return t?`${r} ${t}`:r}let r=q(),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:W(),deviceBrand:e.brand,language:P(),deviceModel:e.model,deviceType:e.model,deviceAbi:e.deviceAbi,cpuType:e.cpuType,memorySize:e.memorySize,benchmarkLevel:e.benchmarkLevel,appVersion:q(),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)??q(),system:s.system,platform:(null==e||null==(r=e.os)?void 0:r.toLowerCase())??s.platform,SDKVersion:O(),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:O(),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)??q(),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 eR(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 ej(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 eO(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 eD(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(eO);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 eq(e){let t=eD(e);if("/temp"===t||"/user"===t)return"";let r=t.lastIndexOf("/");return t.slice(0,r)}function e$(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(e$).join("/");return i.length>0?`appletfile://${r}/${i}`:`appletfile://${r}`}function eF(e,t){return e.entries[eD(t)]}function ez(e,t){let r=eU(t);if(r)return r;let i=eD(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 eW(e,t){let r=eD(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=eq(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=eD(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);eR(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=ej(e),n=eP(t,"dirPath"),a=eD(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=eq(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=ej(e),n=eP(t,"dirPath"),a=eD(n);if("/temp"===a||"/user"===a)throw new w("cannot remove root directory",213);eW(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=ej(e),n=eP(t,"filePath"),a=eD(n);return ez(i,n),delete i.entries[a],r(),{}}function eY(e,t){let r=ej(e),i=eP(t,"path"),n=eU(i),a=n?i:eD(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=ez(ej(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=ej(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=ej(e),n=eP(t,"filePath"),a=eD(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),eR(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=ej(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=ej(e),i=eP(t,"dirPath");return eW(r,i),{files:function(e,t){let r=eD(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=ej(e),n=ez(i,eP(t,"srcPath")),a=eP(t,"destPath");return eR(i,eD(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=ez(ej(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=ej(e),n=eP(t,"oldPath"),a=eP(t,"newPath"),s=eD(n),o=eD(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=ej(e),n=eP(t,"filePath"),a=ez(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);eR(i,eD(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=ej(e),s=eP(t,"tempFilePath"),o=eU(s),l=o??ez(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=eD(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[eD(p)];e++)p=eB(`${c}_${e}_${u}`);return eR(a,eD(p),eA(l.data)),eJ(a,p,eV(l.data)),o||eD(s)===eD(p)||delete a.entries[eD(s)],r(),{savedFilePath:p}},"doubao.getSavedFileList":function(e){return{fileList:Object.entries(ej(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(ej(e),n))?void 0:i.type)==="directory"?eZ(e,{dirPath:n},r):eX(e,t,r)},"doubao.unzip":function(e,t,r){let i=ej(e),n=ez(i,eP(t,"zipFilePath")),a=eP(t,"targetPath"),s=eD(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",e5="doubao.__webPerformanceTiming",e6="__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,j(null==t?void 0:t.globalProps)),syncResult:e=>j(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[e6])?s[e6]: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===e5){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=R();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:R()??""};try{var r;null==(r=this.view.contentWindow)||r.postMessage(t,this.targetOrigin,[e.port2])}catch(e){this.fail(e instanceof Error?e:Error(String(e)))}}handleMessage(e){var t,r,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",tR="onDestroy",tj="onForeground",tP="onHide",tL="onShow";function tO(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 tD(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 tq(e){return{appId:e.appId,name:e.name,iconSrc:e.iconSrc,versionName:e.versionName}}function t$(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return tU(t,tq(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(tD(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?tj: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,tR),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?tj: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:{...t$(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(tR)),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 tO(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=>tD(e.route,e.options)),...this.pendingPages]}getPackageInfo(){var e;return this.packageSnapshot?tq(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:tD(e.route,e.options).route,resourceUrl:e.resourceUrl,entry:e.entry,element:e.element}}}class tz{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 tW(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 tz(void 0,!0),r(26812),r(51724),r(25907),r(92151);var tH=r(89302);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={23556(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 R(){return"0.8.0-rc.4"}function j(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 O(){return"string"==typeof DoubaoAppsSDKVersion?DoubaoAppsSDKVersion:R()??""}function D(){return navigator.userAgentData}function U(){var e;let t=null==(e=D())?void 0:e.brands,r=null==t?void 0:t.find(e=>{let{brand:t}=e;return!/not.a.brand/i.test(t)});if(null==r?void 0:r.brand)return r.brand;let i=navigator.userAgent??"";return/edg\//i.test(i)?"Microsoft Edge":/chrome|crios/i.test(i)?"Chrome":/firefox|fxios/i.test(i)?"Firefox":/safari/i.test(i)?"Safari":"Browser"}function q(){var e,t;let r=null==(e=D())?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 $(){var e;let t=navigator.userAgent??"",r=navigator.platform??"",i=(null==(e=D())?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 z(){return $().platform}function W(){var e,t,r,i,n;let a=navigator.userAgent??"",s=z();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]:z();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=$(),i=navigator.platform||z();return{abi:i,deviceAbi:i,benchmarkLevel:-1,brand:r.brand,model:function(){let e=navigator.userAgent??"",t=z();if("android"===t){var r,i;return(null==(i=/android\s+[\d.]+;\s*([^;)]+)/i.exec(e))||null==(r=i[1])?void 0:r.trim())||"Android"}return"ios"===t?$().brand:"mac"===t||"windows"===t||"linux"===t?navigator.platform||$().brand:U()}(),system:function(){let e=z(),t=W();if("web"!==e){let r=H(e);return t?`${r} ${t}`:r}let r=q(),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:W(),deviceBrand:e.brand,language:P(),deviceModel:e.model,deviceType:e.model,deviceAbi:e.deviceAbi,cpuType:e.cpuType,memorySize:e.memorySize,benchmarkLevel:e.benchmarkLevel,appVersion:q(),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)??q(),system:s.system,platform:(null==e||null==(r=e.os)?void 0:r.toLowerCase())??s.platform,SDKVersion:O(),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:O(),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)??q(),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 eR(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 ej(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 eO(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 eD(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(eO);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 eq(e){let t=eD(e);if("/temp"===t||"/user"===t)return"";let r=t.lastIndexOf("/");return t.slice(0,r)}function e$(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(e$).join("/");return i.length>0?`appletfile://${r}/${i}`:`appletfile://${r}`}function eF(e,t){return e.entries[eD(t)]}function ez(e,t){let r=eU(t);if(r)return r;let i=eD(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 eW(e,t){let r=eD(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=eq(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=eD(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);eR(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=ej(e),n=eP(t,"dirPath"),a=eD(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=eq(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=ej(e),n=eP(t,"dirPath"),a=eD(n);if("/temp"===a||"/user"===a)throw new w("cannot remove root directory",213);eW(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=ej(e),n=eP(t,"filePath"),a=eD(n);return ez(i,n),delete i.entries[a],r(),{}}function eY(e,t){let r=ej(e),i=eP(t,"path"),n=eU(i),a=n?i:eD(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=ez(ej(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=ej(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=ej(e),n=eP(t,"filePath"),a=eD(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),eR(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=ej(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=ej(e),i=eP(t,"dirPath");return eW(r,i),{files:function(e,t){let r=eD(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=ej(e),n=ez(i,eP(t,"srcPath")),a=eP(t,"destPath");return eR(i,eD(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=ez(ej(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=ej(e),n=eP(t,"oldPath"),a=eP(t,"newPath"),s=eD(n),o=eD(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=ej(e),n=eP(t,"filePath"),a=ez(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);eR(i,eD(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=ej(e),s=eP(t,"tempFilePath"),o=eU(s),l=o??ez(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=eD(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[eD(p)];e++)p=eB(`${c}_${e}_${u}`);return eR(a,eD(p),eA(l.data)),eJ(a,p,eV(l.data)),o||eD(s)===eD(p)||delete a.entries[eD(s)],r(),{savedFilePath:p}},"doubao.getSavedFileList":function(e){return{fileList:Object.entries(ej(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(ej(e),n))?void 0:i.type)==="directory"?eZ(e,{dirPath:n},r):eX(e,t,r)},"doubao.unzip":function(e,t,r){let i=ej(e),n=ez(i,eP(t,"zipFilePath")),a=eP(t,"targetPath"),s=eD(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,j(null==t?void 0:t.globalProps)),syncResult:e=>j(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=R();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:R()??""};try{var r;null==(r=this.view.contentWindow)||r.postMessage(t,this.targetOrigin,[e.port2])}catch(e){this.fail(e instanceof Error?e:Error(String(e)))}}handleMessage(e){var t,r,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",tR="onDestroy",tj="onForeground",tP="onHide",tL="onShow";function tO(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 tD(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 tq(e){return{appId:e.appId,name:e.name,iconSrc:e.iconSrc,versionName:e.versionName}}function t$(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return tU(t,tq(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(tD(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?tj: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,tR),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?tj: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:{...t$(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(tR)),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 tO(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=>tD(e.route,e.options)),...this.pendingPages]}getPackageInfo(){var e;return this.packageSnapshot?tq(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:tD(e.route,e.options).route,resourceUrl:e.resourceUrl,entry:e.entry,element:e.element}}}class tz{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 tW(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 tz(void 0,!0),r(26812),r(51724),r(25907),r(92151);var tH=r(89302);let tV="embed-webview",tG="__channel_ack__",tJ=new WeakMap,tK=e=>({url:e});function tZ(e){if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}}function tX(e){return"string"==typeof e?e:JSON.stringify(e??{})}let tY=globalThis.HTMLElement??class{},tQ="region-to-decode";function t0(e){if("string"==typeof e)try{e=JSON.parse(e)}catch{return null}if(!e||"object"!=typeof e)return null;let{x:t,y:r,width:i,height:n}=e;return![t,r,i,n].every(Number.isFinite)||t<0||r<0||i<=0||n<=0?null:{x:t,y:r,width:i,height:n}}class t1{element;static observedAttributes=[];image;attributes=new MutationObserver(()=>this.update());resize;viewSize;cropStyle;constructor(e){var t;this.element=e,this.image=(null==(t=e.shadowRoot)?void 0:t.querySelector("#img"))??null,Object.defineProperty(e,tQ,{configurable:!0,get:()=>t0(e.getAttribute(tQ)),set:t=>{let r=t0(t);r?e.setAttribute(tQ,JSON.stringify(r)):e.removeAttribute(tQ)}})}connectedCallback(){this.attributes.observe(this.element,{attributes:!0,attributeFilter:[tQ,"src","mode","auto-size"]}),this.update()}clearCrop=()=>{var e;null==(e=this.cropStyle)||e.remove(),this.cropStyle=void 0};stopRendering(){var e,t,r;null==(e=this.resize)||e.disconnect(),this.resize=void 0,this.viewSize=void 0,null==(t=this.image)||t.removeEventListener("load",this.update),null==(r=this.image)||r.removeEventListener("error",this.clearCrop),this.clearCrop()}update=()=>{var e,t,r;let i=t0(this.element.getAttribute(tQ)),n=this.image;if(!i||!n)return void this.stopRendering();this.resize||(this.resize=new ResizeObserver(e=>{let[t]=e;this.viewSize=t.contentRect,this.update()}),this.resize.observe(this.element),n.addEventListener("load",this.update),n.addEventListener("error",this.clearCrop));let a=n.naturalWidth,s=n.naturalHeight,o=this.element.getAttribute("src"),l=this.element.getRootNode().host,d=o?(null==l||null==(e=l.resolveResource)?void 0:e.call(l,o))??o:o;if(!n.complete||!a||!s||n.getAttribute("src")!==d)return void this.clearCrop();let u=Math.min(i.width,a-i.x),c=Math.min(i.height,s-i.y),p=getComputedStyle(this.element),h=Number.parseFloat(p.paddingLeft)||0,m=Number.parseFloat(p.paddingTop)||0,g=(null==(t=this.viewSize)?void 0:t.width)??this.element.clientWidth-h-(Number.parseFloat(p.paddingRight)||0),f=(null==(r=this.viewSize)?void 0:r.height)??this.element.clientHeight-m-(Number.parseFloat(p.paddingBottom)||0);if(u<=0||c<=0||g<=0||f<=0)return void this.clearCrop();let v=g/u,y=f/c,b=this.element.getAttribute("mode");"aspectFit"===b?v=y=Math.min(v,y):"aspectFill"===b?v=y=Math.max(v,y):"center"===b&&(v=y=1);let w=h+(g-u*v)/2-i.x*v,_=m+(f-c*y)/2-i.y*y;this.cropStyle||(this.cropStyle=this.element.ownerDocument.createElement("style"),this.cropStyle.setAttribute("data-doubao-image-region",""),this.element.shadowRoot.append(this.cropStyle)),this.cropStyle.textContent=`#img {
|
|
2
2
|
position: absolute !important;
|
|
3
3
|
margin: 0 !important;
|
|
4
4
|
padding: 0 !important;
|
|
@@ -16,17 +16,17 @@
|
|
|
16
16
|
object-fit: fill !important;
|
|
17
17
|
clip-path: inset(${i.y*y}px ${(a-i.x-u)*v}px
|
|
18
18
|
${(s-i.y-c)*y}px ${i.x*v}px) !important;
|
|
19
|
-
}`};dispose(){this.attributes.disconnect(),this.stopRendering()}}let t2=new Set;var t3=r(37474);let t4=new WeakMap;function t5(e,t,r){let i=new Map;for(let n of t){let t=Reflect.get(e,n);i.set(n,Object.getOwnPropertyDescriptor(e,n)),Object.defineProperty(e,n,{configurable:!0,writable:!0,value(){for(var e=arguments.length,i=Array(e),n=0;n<e;n++)i[n]=arguments[n];return r(),Reflect.apply(t,this,i)}})}return()=>{for(let[t,r]of i)r?Object.defineProperty(e,t,r):Reflect.deleteProperty(e,t)}}class t6{element;placeholder=document.createComment("map-marker");parent;cleanupElement;constructor(e){this.element=e;let t=e.parentNode;if(!t)throw Error("Web Map Marker requires a component parent");this.parent=t;let r=t4.get(t);if(!r){let e=new Set;r={portals:e,cleanup:t5(t,["appendChild","insertBefore","removeChild","replaceChild","append","prepend","replaceChildren"],()=>{for(let t of e)t.restore()})},t4.set(t,r)}r.portals.add(this),this.cleanupElement=t5(e,["remove","replaceWith","before","after"],()=>{for(let e of r.portals)e.restore()})}get connected(){return this.element.parentNode===this.parent?this.element.isConnected:this.placeholder.isConnected}mount(e){if(this.element.parentNode!==e){if(this.element.parentNode!==this.parent)throw Error("Web Map Marker component parent changed");Node.prototype.insertBefore.call(this.parent,this.placeholder,this.element),e.appendChild(this.element)}}restore(){this.placeholder.parentNode===this.parent&&Node.prototype.replaceChild.call(this.parent,this.element,this.placeholder)}destroy(){this.restore(),this.cleanupElement();let e=t4.get(this.parent);null==e||e.portals.delete(this),(null==e?void 0:e.portals.size)===0&&(e.cleanup(),t4.delete(this.parent))}}class t8{element;namespace;map;onError;onClick;content=document.createElement("div");portal;originalStyles=new Map;styleObserver=new MutationObserver(()=>this.syncZIndex());marker;defaultZIndex;positionKey;optionsKey;waitingForPosition=!1;syncing=!1;disposed=!1;constructor(e,t,r,i,n){this.element=e,this.namespace=t,this.map=r,this.onError=i,this.onClick=n,this.portal=new t6(e),this.content.style.cssText="width:0;height:0;overflow:visible;",this.styleObserver.observe(e,{attributes:!0,attributeFilter:["style","class"]})}get connected(){return this.portal.connected}sync(e){if(!this.disposed&&!this.syncing){this.syncing=!0;try{if(!e.position&&!e.containerPosition){var t;this.portal.restore(),null==(t=this.marker)||t.destroy(),this.marker=void 0,this.optionsKey=void 0,this.positionKey=void 0,this.waitingForPosition=!0,this.style("visibility","hidden");return}this.waitingForPosition&&(this.style("visibility",this.originalStyles.get("visibility")??""),this.waitingForPosition=!1),this.style("position","relative"),"inline"===getComputedStyle(this.element).display&&this.style("display","inline-block"),this.element.style.width||this.style("width","max-content"),this.style("transform",`translate(${-100*e.anchor[0]}%, ${-100*e.anchor[1]}%)`);let r="amap"===this.namespace.getProvider(),i={content:this.content,containerPosition:e.containerPosition?[e.containerPosition.x,e.containerPosition.y]:null,anchor:r?"top-left":0,angle:e.rotation,opacity:e.alpha,clickable:e.clickable,draggable:e.draggable,bubble:!e.clickable,animation:e.animate??(r?{scale:{from:1,to:1,duration:0}}:null)},n=JSON.stringify(e.position);this.marker&&n===this.positionKey||(i.position=e.position&&[e.position.longitude,e.position.latitude]),this.portal.mount(this.content);let a=JSON.stringify(e);if(this.marker&&this.optionsKey===a)return void this.syncZIndex();this.optionsKey=a,this.marker?this.marker.setOptions(i):(this.marker=new this.namespace.Marker(i),this.defaultZIndex=this.marker.getzIndex(),this.marker.on("click",this.onClick)),this.syncZIndex(),this.marker.getMap()!==this.map&&this.marker.setMap(this.map),this.positionKey=n}catch(e){this.onError(e)}finally{this.syncing=!1}}}syncZIndex(){if(this.marker&&!this.disposed)try{let e=Number.parseInt(getComputedStyle(this.element).zIndex,10),t=Number.isFinite(e)?e:this.defaultZIndex;void 0!==t&&t!==this.marker.getzIndex()&&this.marker.setzIndex(t)}catch(e){this.onError(e)}}style(e,t){this.originalStyles.has(e)||this.originalStyles.set(e,this.element.style.getPropertyValue(e)),this.element.style.getPropertyValue(e)!==t&&this.element.style.setProperty(e,t)}destroy(){var e;if(!this.disposed)for(let[t,r]of(this.disposed=!0,this.styleObserver.disconnect(),this.portal.destroy(),null==(e=this.marker)||e.destroy(),this.originalStyles))this.element.style.setProperty(t,r)}}let t9=e=>{let{longitude:t,latitude:r}=e;return[t,r]};function t7(e,t,r,i,n){let a=new Set(t.map(e=>{let{id:t}=e;return t}));for(let[t,r]of e)a.has(t)||(r.destroy(),e.delete(t));for(let a of t)try{let t=r(a),n=e.get(a.id);if(n){let{id:e,...r}=t;n.setOptions(r)}else e.set(a.id,i(t,a))}catch(e){n(e)}}class re{namespace;map;onError;onPolylineClick;polylines=new Map;polygons=new Map;circles=new Map;arcs=new Map;routeLabels=new Map;warnings=new Set;constructor(e,t,r,i){this.namespace=e,this.map=t,this.onError=r,this.onPolylineClick=i}warn(e){this.warnings.has(e)||(this.warnings.add(e),this.onError(Error(`Web Map 暂不支持 ${e}`)))}add(e){e.on("warning",e=>{this.onError(e.error??Error(e.reason??e.feature??"Web Map 覆盖物降级"))});try{return this.map.add(e),e}catch(t){throw e.destroy(),t}}sync(e){var t;let r=function(e){let t=new Map,r=new Set;for(let n of e){var i;if(!n.id.startsWith("__doubao_polyline_arrow__:"))continue;let a=null==(i=n.edgeTextureAssets)?void 0:i.find(e=>{let{id:t}=e;return"__doubao_polyline_arrow_texture__"===t});if(a)try{let i=decodeURIComponent(n.id.slice(26));e.some(e=>e.id===i)&&(t.set(i,{iconPath:a.url}),r.add(n))}catch{}}return e.filter(e=>!r.has(e)).map(e=>({...e,arrow:t.get(e.id)??e.arrow}))}(e.polyline??[]),i=this.namespace.supports("Polyline.edgeTexture").supported,n=this.namespace.supports("RouteLabel").supported;!i&&r.some(e=>{var t,r;return(null==(t=e.edgeTexture)?void 0:t.length)||(null==(r=e.edgeTextureAssets)?void 0:r.length)})&&this.warn("当前图商的 polyline 纹理"),!n&&(null==(t=e.routeLabel)?void 0:t.length)&&this.warn("当前图商的 routeLabel"),r.some(e=>e.collideDetection)&&this.warn("polyline POI 碰撞避让"),t7(this.polylines,r,e=>{var t;return{id:e.id,path:e.points.map(t9),strokeColors:e.edgeColor??[],arrow:e.arrow??null,edgeTexture:i?e.edgeTexture??[]:[],edgeTextureAssets:i?e.edgeTextureAssets??[]:[],strokeColor:(null==(t=e.edgeColor)?void 0:t[0])??"#0066ff",strokeWeight:e.width??2,strokeStyle:e.dottedLine?"dashed":"solid",lineCap:"line_cap_round"===e.lineCapType?"round":"butt",lineJoin:"line_join_round"===e.lineJoinType?"round":"line_join_miter"===e.lineJoinType?"miter":"bevel",zIndex:e.zIndex??0}},(e,t)=>{let r=new this.namespace.Polyline(e);return r.on("click",()=>this.onPolylineClick(t.id)),this.add(r)},this.onError),t7(this.polygons,e.polygons??[],e=>({id:e.id,path:e.points.map(t9),fillColor:e.fillColor,strokeColor:e.strokeColor,strokeWeight:e.strokeWidth,strokeStyle:e.dottedLine?"dashed":"solid",zIndex:e.zIndex}),e=>{let t=new this.namespace.Polygon(e);return this.add(t)},this.onError),t7(this.circles,e.circles??[],e=>({id:e.id,center:t9(e.center),radius:e.radius,fillColor:e.fillColor,strokeColor:e.strokeColor,strokeWeight:e.strokeWidth,zIndex:e.zIndex}),e=>{let t=new this.namespace.Circle(e);return this.add(t)},this.onError),t7(this.arcs,e.arcs??[],e=>({id:e.id,path:[t9(e.start),t9(e.mid??e.middle),t9(e.end)],strokeColor:e.color??"#0066ff",strokeWeight:e.width??2,zIndex:e.zIndex}),e=>{let t=new this.namespace.Arc(e);return this.add(t)},this.onError),t7(this.routeLabels,n?e.routeLabel??[]:[],e=>({id:e.id,path:e.points.map(t9),text:e.text,textColor:e.textColor??"#000000",fontSize:e.fontSize??12,fontWeight:e.fontWeight??"normal",borderColor:e.borderColor??"#cccccc",borderWidth:e.borderWidth??0,zIndex:e.zIndex??0}),e=>this.add(new this.namespace.RouteLabel(e)),this.onError)}destroy(){for(let e of[this.polylines,this.polygons,this.circles,this.arcs,this.routeLabels]){for(let t of e.values())t.destroy();e.clear()}}}let rt={baidu:{provider:"baidu",security:{baidu:{serviceHost:"https://api.doubao-dev.com/_BMapService/"}}},amap:{provider:"amap",key:{amap:"f57928bd7156da61d512795ec5c0c968"},security:{amap:{serviceHost:"https://api.doubao-dev.com/_AMapService"}}}},rr=new WeakMap,ri=new WeakMap,rn=new WeakMap,ra=new WeakMap;function rs(e,t,r){if(t in r)return r[t];let i=e.getAttribute(t);if(i)try{return JSON.parse(i)}catch{return}}function ro(e,t,r){let i=Number(e.getAttribute(t));return Number.isFinite(i)&&e.hasAttribute(t)?i:r}function rl(e,t,r){let i=e.getAttribute(t);return null===i?r:"false"!==i&&"0"!==i}function rd(e){let{longitude:t,latitude:r}=e;return[t,r]}function ru(e){return{longitude:e.lng,latitude:e.lat}}function rc(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};e.dispatchEvent(new CustomEvent(t,{detail:r,bubbles:!1}))}function rp(e,t){let r=t instanceof Error?t:Error(String(t));console.error("[Doubao Map]",r.message),e.dispatchEvent(new CustomEvent("error",{detail:{error:r}}))}function rh(e){return rr.get(e)??{}}function rm(e){return ri.get(e)??{}}function rg(e){let t=ra.get(e);if(t)return t;let r=e.closest("map");return r?rn.get(r):void 0}class rf{element;map;namespace;syncingMarkers=!1;overlays;markers=new Map;cleanupTileLoad;surface;resize;sizeFrame=0;loading=!1;initializationBlocked=!1;disposed=!1;ready=!1;lastAttributes="";lastOverlays="";lastStyle="";lastLogoPosition="";warnings=new Set;constructor(e){var t;if(this.element=e,rn.set(e,this),this.installMethods(),"inline"===getComputedStyle(e).display&&(e.style.display="block"),"static"===getComputedStyle(e).position&&(e.style.position="relative"),e.style.overflow="hidden",this.resize="function"==typeof ResizeObserver?new ResizeObserver(()=>this.initialize()):void 0,null==(t=this.resize)||t.observe(e),!this.resize){let e=()=>{this.disposed||this.map||this.loading||this.initializationBlocked||(this.initialize(),this.sizeFrame=requestAnimationFrame(e))};this.sizeFrame=requestAnimationFrame(e)}this.initialize()}warn(e){this.warnings.has(e)||(this.warnings.add(e),rp(this.element,Error(`Web Map 暂不支持 ${e}`)))}getMapConfig(){let e=rs(this.element,"extra-params",rh(this.element));return rt[(null==e?void 0:e.useAliMap)===!0?"amap":"baidu"]}initialize(){var e;if(this.disposed||this.loading||this.initializationBlocked||this.map||this.element.clientWidth<=0||this.element.clientHeight<=0)return;let t=this.getMapConfig(),r=(null==(e=this.element.ownerDocument.location)?void 0:e.hostname)??"";if("baidu"===t.provider&&(tb(r)||"[::1]"===r||r.endsWith(".localhost"))){this.initializationBlocked=!0,rp(this.element,Error("当前豆包百度地图账号未授权本地域名,请使用获准域名的 sandbox 调试地图。"));return}this.loading=!0;let i=document.createElement("div");i.dataset.doubaoMapSurface="",i.style.cssText="position:absolute;inset:0;width:100%;height:100%;",this.element.prepend(i),this.surface=i,Promise.resolve().then(()=>t3.H3.load(t)).then(e=>{this.disposed||this.createMap(e,i)}).catch(e=>{this.disposed||rp(this.element,e),i.remove(),this.surface=void 0}).finally(()=>{this.loading=!1})}createMap(e,t){let r=this.element,i=rs(r,"center",rh(r)),n=rs(r,"scale-range",rh(r));try{let a=new e.Map(t,{center:i&&rd(i),zoom:ro(r,"scale",16),zooms:n??[3,20],rotation:ro(r,"rotate",0),logoPosition:r.getAttribute("logo-position")||"bottom-left",eventContext:!0,enableNativeInteraction:rl(r,"native-interaction-enabled",!0),showScale:rl(r,"enable-scale-controls",!1),zoomEnable:rl(r,"enable-scale",!0),dragEnable:rl(r,"enable-drag",!0),rotateEnable:rl(r,"enable-rotate",!1)});this.map=a,this.namespace=e,this.overlays=new re(e,a,e=>rp(r,e),e=>rc(r,"clickpolyline",{id:e}));let s=!1,o=()=>{this.disposed||s||(s=!0,rc(r,"maptileload"))};if("baidu"===e.getProvider()){let e=a.getNative();e.addEventListener("firsttileloaded",o),this.cleanupTileLoad=()=>e.removeEventListener("firsttileloaded",o)}let l=()=>{this.disposed||this.ready||(this.ready=!0,rc(r,"mapload"),"amap"===e.getProvider()&&o(),this.update(!0))};a.on("complete",l),a.on("click",e=>{e.lnglat&&rc(r,"clickmap",{point:ru(e.lnglat)})}),a.on("error",e=>rp(r,e)),a.on("warning",e=>{rp(r,Error(e.reason??e.feature??"Web Map 能力降级"))});let d=(e,t,i)=>{if(!a.isReady())return;let n=t.context,s=(null==n?void 0:n.bounds)??a.getBounds();rc(r,"regionchange",{type:(null==n?void 0:n.phase)??e,...i?{causedBy:i}:{},center:ru((null==n?void 0:n.center)??a.getCenter()),scale:(null==n?void 0:n.zoom)??a.getZoom(),rotate:(null==n?void 0:n.rotation)??a.getRotation(),region:{southwest:ru(s.getSouthWest()),northeast:ru(s.getNorthEast())}})};a.on("movestart",e=>d("begin",e,"drag")),a.on("moveend",e=>d("end",e,"drag")),a.on("zoomstart",e=>d("begin",e,"scale")),a.on("zoomend",e=>d("end",e,"scale")),"baidu"!==e.getProvider()&&(a.on("rotatestart",e=>d("begin",e)),a.on("rotateend",e=>d("end",e))),a.isReady()&&l()}catch(e){var a,s,o;null==(a=this.cleanupTileLoad)||a.call(this),null==(s=this.overlays)||s.destroy(),null==(o=this.map)||o.destroy(),this.map=void 0,t.remove(),rp(r,e)}}update(){var e,t;let r=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!this.ready||!this.map||this.disposed)return;let i=this.element,n=this.map,a=rh(i),s=JSON.stringify({center:rs(i,"center",a),scale:i.getAttribute("scale"),scales:rs(i,"scale-range",a),rotate:i.getAttribute("rotate"),showScale:i.getAttribute("enable-scale-controls"),enableScale:i.getAttribute("enable-scale"),enableDrag:i.getAttribute("enable-drag"),enableRotate:i.getAttribute("enable-rotate"),nativeInteraction:i.getAttribute("native-interaction-enabled")});if(r||s!==this.lastAttributes){this.lastAttributes=s;try{let e=rs(i,"scale-range",a);e&&n.setZooms(e);let t=rs(i,"center",a);t?n.setZoomAndCenter(ro(i,"scale",16),rd(t)):n.setZoom(ro(i,"scale",16)),n.setRotation(ro(i,"rotate",0)),n.setShowScale(rl(i,"enable-scale-controls",!1)),n.setNativeInteractionEnabled(rl(i,"native-interaction-enabled",!0)),n.setStatus({zoomEnable:rl(i,"enable-scale",!0),dragEnable:rl(i,"enable-drag",!0),rotateEnable:rl(i,"enable-rotate",!1)})}catch(e){rp(i,e)}}let o=i.getAttribute("map-style")||"normal-light";if(o!==this.lastStyle){this.lastStyle=o;try{n.setMapStyle((null==(e=this.namespace)?void 0:e.getProvider())==="baidu"?{styleId:o}:o)}catch(e){rp(i,e)}}rl(i,"enable-tilt",!1)&&this.warn("地图倾斜");let l=i.getAttribute("logo-position")||"bottom-left";if(l!==this.lastLogoPosition){this.lastLogoPosition=l;try{n.setLogoPosition(l)}catch(e){rp(i,e)}}let d={polyline:rs(i,"polyline",a),polygons:rs(i,"polygons",a),circles:rs(i,"circles",a),arcs:rs(i,"arcs",a),routeLabel:rs(i,"route-label",a)},u=JSON.stringify(d);(r||u!==this.lastOverlays)&&(this.lastOverlays=u,null==(t=this.overlays)||t.sync(d)),this.updateMarkers()}updateMarkers(){let e=this.map,t=this.namespace;if((null==e?void 0:e.isReady())&&t&&!this.syncingMarkers){this.syncingMarkers=!0;try{let r=new Set([...this.element.querySelectorAll("map-marker")].filter(e=>e.closest("map")===this.element));for(let[e,t]of this.markers)r.has(e)&&t.connected||(r.delete(e),t.destroy(),this.markers.delete(e),ra.delete(e));for(let i of r){let r=rm(i);rl(i,"enable-collide-with-poi",!1)&&this.warn("marker POI 碰撞避让");let n=rs(i,"container-position",r),a=rl(i,"enable-drag",!1),s=!n&&"amap"===t.getProvider();a&&!s&&this.warn(n?"固定屏幕位置的 marker 拖动":"百度自定义内容 marker 拖动");let o=rl(i,"enable-click",!0);a&&!o&&this.warn("关闭点击时的 marker 拖动");let l=this.markers.get(i);l||(l=new t8(i,t,e,e=>rp(this.element,e),()=>rc(i,"clickmarker")),this.markers.set(i,l),ra.set(i,this)),l.sync({position:rs(i,"position",r),containerPosition:n,anchor:rs(i,"anchor",r)??[.5,1],rotation:ro(i,"rotation",0),alpha:ro(i,"alpha",1),clickable:o,draggable:a&&s&&o,animate:rs(i,"animate",r)})}}finally{this.syncingMarkers=!1}}}getMap(){var e;if(!(null==(e=this.map)?void 0:e.isReady()))throw Error("Web Map 尚未加载完成");return this.map}installMethods(){Object.assign(this.element,{setCenter:e=>{let{center:t,animated:r,duration:i}=e;return this.getMap().setCenter(rd(t),!1===r,i)},getCenter:()=>ru(this.getMap().getCenter()),setScale:e=>{let{scale:t,animated:r,duration:i}=e;return this.getMap().setZoom(t,!1===r,i)},getScale:()=>({scale:this.getMap().getZoom()}),getBound:()=>{let e=this.getMap().getBounds();return{southwest:ru(e.getSouthWest()),northeast:ru(e.getNorthEast())}},setBound:e=>{let{southwest:t,northeast:r,animated:i,duration:n}=e;return this.getMap().setBounds([t.longitude,t.latitude,r.longitude,r.latitude],!1===i,void 0,n)},fitPoints:e=>{let{points:t,padding:r=[0,0,0,0],animated:i,duration:n}=e;return this.getMap().setFitView(t.map(rd),!1===i,[r[2]??0,r[3]??0,r[0]??0,r[1]??0],void 0,n)},setAnchor:e=>{let{position:t}=e;return this.getMap().setAnchor([t.x,t.y])},latLngToPx:e=>{let{latLng:t}=e,r=this.getMap().lngLatToContainer(rd(t));return{x:r.x,y:r.y}},pxToLatLng:e=>{let{x:t,y:r}=e;return{latLng:ru(this.getMap().containerToLngLat([t,r]))}}})}dispose(){var e,t,r,i,n;if(!this.disposed){for(let[r,i]of(this.disposed=!0,null==(e=this.resize)||e.disconnect(),cancelAnimationFrame(this.sizeFrame),null==(t=this.cleanupTileLoad)||t.call(this),this.markers))ra.delete(r),i.destroy();this.markers.clear(),null==(r=this.overlays)||r.destroy(),null==(i=this.map)||i.destroy(),null==(n=this.surface)||n.remove(),rn.delete(this.element)}}}class rv{element;static observedAttributes=[];constructor(e){this.element=e}forwardLinkEvent=e=>{this.element.dispatchEvent(new CustomEvent("link",{detail:e.detail,bubbles:!0,composed:!0}))};connectedCallback(){this.element.addEventListener("bindlink",this.forwardLinkEvent);let e=this.element.markdownStyle??{};this.element.markdownStyle={...e,link:{...e.link,textDecoration:"none"},orderedList:{...e.orderedList,paddingLeft:0},unorderedList:{...e.unorderedList,paddingLeft:0}}}}function ry(e){var t;null==(t=e.registerPlugin)||t.call(e,rv)}let rb="x-video-engine",rw=globalThis.HTMLElement??class{};if("object"!=typeof customElements||customElements.get(tV)||customElements.define(tV,class e extends tY{static observedAttributes=["src"];#e=null;#t=null;#r=!1;messageOrigin;connectedCallback(){this.#r=!0,this.style.display||(this.style.display="block"),this.#i(),this.#n()}disconnectedCallback(){var e;this.#r=!1,this.#a(),null==(e=this.#e)||e.remove(),this.#e=null,window.removeEventListener("message",this.#s)}attributeChangedCallback(e){"src"===e&&this.#r&&this.#n()}get src(){return this.getAttribute("src")}set src(e){null===e?this.removeAttribute("src"):this.setAttribute("src",e)}reload(){this.#n(!0)}postMessage(e){let t=o(e)?e.data:void 0;this.#o({type:"event",name:"message",params:{data:t},timestamp:Date.now()})}eval(e){let t=o(e)&&"string"==typeof e.func?e.func:"";if(t)try{if(this.messageOrigin){var r,i;null==(i=this.#e)||null==(r=i.contentWindow)||r.postMessage({type:"__doubao_web_view_eval__",code:t},this.messageOrigin);return}let e=this.#l();null==e||e.eval(t)}catch{}}onGoBack(){return{consumed:!1}}#i(){if(this.#e)return this.#e;let e=this.shadowRoot??this.attachShadow({mode:"open"}),t=document.createElement("iframe");return t.style.cssText="display:block;width:100%;height:100%;border:none;",t.addEventListener("load",this.#d),t.addEventListener("error",this.#u),e.replaceChildren(t),this.#e=t,window.addEventListener("message",this.#s),t}#n(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.#i(),r=this.getAttribute("src");if(!r)return;let i=tK(r);this.messageOrigin="window"===i.messageTransport?new URL(i.url,document.baseURI).origin:void 0,(e||t.getAttribute("src")!==i.url)&&(this.#a(),t.toggleAttribute("credentialless",!0===i.credentialless),t.src=i.url)}#a(){var e;null==(e=this.#t)||e.close(),this.#t=null}#l(){try{var e;let t=(null==(e=this.#e)?void 0:e.contentWindow)??null;return null==t||t.document,t}catch{return null}}#d=()=>{this.messageOrigin||(this.#c(),this.#p(),this.#h()),this.#m("load",{url:this.getAttribute("src")??""})};#u=()=>{this.#m("error",{errorMsg:`Failed to load ${this.getAttribute("src")??""}`,errorCode:-1})};#s=e=>{if(!this.#e||e.source!==this.#e.contentWindow||this.messageOrigin&&e.origin!==this.messageOrigin||e.data===tG)return;let t=tZ(e.data);this.#g(t)||this.#f(tX(e.data))};#c(){var e;this.#a();let t=null==(e=this.#e)?void 0:e.contentWindow;if(!t)return;let r=new MessageChannel;r.port1.onmessage=e=>{e.data!==tG&&this.#g(tZ(e.data))},this.#t=r.port1,t.postMessage("__channel_init__","*",[r.port2])}#p(){let e=this.#l();e&&!e.AppletBridgeModule&&(e.AppletBridgeModule={postMessage:e=>(this.#g(tZ(e)),Promise.resolve({})),postMessageSync:e=>{let t=tZ(e);return v(t)?S(t,"Sync AppletBridgeModule APIs are not supported in Doubao Web SDK web-view"):void 0}})}#h(){let e=this.#l();e&&this.#f(JSON.stringify({type:"__doubao_web_view_set_title__",title:e.document.title||""}))}#g(e){if(o(e)&&"event"===e.type)return"__bridge_ready__"===e.name;if(!v(e))return!1;if("doubao.postMessage"===e.name){let t=o(e.params)?e.params.data:void 0;return this.#f(tX(t)),this.#o(_(e,{})),!0}return this.#v(e),!0}async #v(e){let t=function(e){let t=e;for(;t;){if(t instanceof Element){let e=tJ.get(t);if(e)return e}let e=t.parentNode;t=e instanceof ShadowRoot?e.host:e}}(this);if(!t)return void this.#o(S(e,`API ${e.name} is not available in this web-view host`));let r=await t(e);this.#o(r??S(e,`API ${e.name} is not implemented in Doubao Web SDK`))}#o(e){var t,r,i;let n=JSON.stringify(e);if(this.messageOrigin){null==(i=this.#e)||null==(r=i.contentWindow)||r.postMessage({type:"__doubao_web_view_message__",payload:n},this.messageOrigin);return}if(this.#t)return void this.#t.postMessage(n);let a=this.#l();null==a||null==(t=a.onWebViewMessage)||t.call(a,n)}#f(e){this.#m("message",{msg:e,data:e})}#m(e,t){for(let r of[e,`bind${e}`])this.dispatchEvent(new CustomEvent(r,{bubbles:!0,composed:!0,detail:t}))}}),"object"==typeof customElements&&!a){let e=customElements.get("x-markdown");e?(ry(e),a=Promise.resolve()):a=customElements.whenDefined("x-markdown").then(e=>{ry(e)})}if("object"!=typeof customElements||customElements.get(rb)||customElements.define(rb,class e extends rw{static observedAttributes=["play-url","video-model","vid","auto-prepare","initial-time","objectfit","muted","loop","volume","speed"];video=null;prepared=!1;firstFrame=!1;stopped=!0;playbackState=-1;playRequest=0;connectedCallback(){if(this.video)return;let e=this.shadowRoot??this.attachShadow({mode:"open"}),t=document.createElement("style");t.textContent=":host{display:block;width:100%;height:100%}video{display:block;width:100%;height:100%}";let r=document.createElement("video");this.video=r,r.playsInline=!0,e.replaceChildren(t,r);let i=(e,t)=>r.addEventListener(e,e=>{e.stopPropagation(),this.video===r&&this.isConnected&&t()});i("loadedmetadata",()=>{r.currentTime=this.numberAttribute("initial-time",0)/1e3}),i("canplay",()=>this.notifyPrepared()),i("loadeddata",()=>{this.firstFrame||(this.firstFrame=!0,this.emit("firstframe"))}),i("playing",()=>{this.stopped=!1,this.setPlaybackState(1)}),i("pause",()=>this.setPlaybackState(2*!this.stopped)),i("seeked",()=>this.emit("seek")),i("timeupdate",()=>this.emit("timeupdate",{current:1e3*r.currentTime,total:Number.isFinite(r.duration)?1e3*r.duration:0})),i("ended",()=>{this.stopped=!0,this.setPlaybackState(0),this.emit("completion")}),i("error",()=>{var e,t;return this.reportError((null==(e=r.error)?void 0:e.message)||"Video resource could not be played",null==(t=r.error)?void 0:t.code)}),document.addEventListener("visibilitychange",this.handleVisibility),this.syncAttributes(),this.syncSource()}disconnectedCallback(){var e;let t=this.video;this.video=null,this.playRequest++,document.removeEventListener("visibilitychange",this.handleVisibility),t&&(t.pause(),t.removeAttribute("src"),t.load()),null==(e=this.shadowRoot)||e.replaceChildren()}attributeChangedCallback(e,t,r){this.video&&t!==r&&(["play-url","video-model","vid"].includes(e)?this.syncSource():(this.syncAttributes(),"auto-prepare"!==e||this.booleanAttribute("auto-prepare",!0)||(this.video.preload="none")))}booleanAttribute(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.getAttribute(e);return null===r?t:"false"!==r&&"0"!==r}numberAttribute(e,t){let r=this.getAttribute(e),i=null===r||""===r.trim()?0/0:Number(r);return Number.isFinite(i)&&i>=0?i:t}syncAttributes(){let e=this.video;e.muted=this.booleanAttribute("muted"),e.loop=this.booleanAttribute("loop"),e.volume=Math.min(1,this.numberAttribute("volume",1));try{e.playbackRate=this.numberAttribute("speed",1)||1,e.defaultPlaybackRate=e.playbackRate}catch(e){this.reportError(String(e))}let t=this.getAttribute("objectfit")??"contain";e.style.objectFit=["contain","cover","fill"].includes(t)?t:"contain",this.booleanAttribute("auto-prepare",!0)&&(e.preload="auto",e.controls=!0)}syncSource(){let e=this.video,t=this.getAttribute("play-url")||"";t&&e.getAttribute("src")===t||(this.playRequest++,this.prepared=this.firstFrame=!1,this.stopped=!0,this.playbackState=-1,e.pause(),e.preload=this.booleanAttribute("auto-prepare",!0)?"auto":"none",e.controls="auto"===e.preload,t?e.src=t:e.removeAttribute("src"),e.load(),queueMicrotask(()=>{this.isConnected&&this.video===e&&(this.getAttribute("play-url")||"")===t&&(t?this.emit("redirect"):(this.getAttribute("video-model")||this.getAttribute("vid"))&&this.reportError("Web VideoEngine requires play-url; video-model and vid are not supported"))}))}notifyPrepared(){var e;this.prepared||(null==(e=this.video)?void 0:e.preload)!=="auto"||(this.prepared=!0,this.emit("canplay"))}emit(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:"error"!==e}))}setPlaybackState(e){this.playbackState!==e&&(this.playbackState=e,this.emit("playbackstatechanged",{playbackState:e}))}reportError(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;this.emit("error",{errorCode:t,errorMsg:e})}getMedia(){var e;if(!(null==(e=this.video)?void 0:e.getAttribute("src")))throw Error("Web VideoEngine requires play-url");return this.video}handleVisibility=()=>{var e;document.hidden&&this.booleanAttribute("pause-on-hide")&&(null==(e=this.video)?void 0:e.getAttribute("src"))&&this.pause()};prepare(){let e=this.getMedia();e.preload="auto",e.controls=!0,this.prepared=!1,e.readyState>=3?queueMicrotask(()=>{this.video===e&&this.notifyPrepared()}):e.load()}play(){let e=this.getMedia();this.stopped=!1;let t=++this.playRequest;e.play().catch(r=>{this.video===e&&t===this.playRequest&&this.reportError(String(r))})}pause(){let e=this.getMedia();this.playRequest++,this.stopped=!1,e.pause(),this.setPlaybackState(2)}stop(){let e=this.getMedia();this.playRequest++,this.stopped=!0,e.pause(),e.currentTime=0,this.setPlaybackState(0)}seek(e){if(!e||!Number.isFinite(e.position)||e.position<0)throw Error("seek.position must be a non-negative number in milliseconds");let t=this.getMedia(),r=Math.min(e.position/1e3,Number.isFinite(t.duration)?t.duration:1/0);e.play||this.pause(),t.currentTime===r?queueMicrotask(()=>{this.video===t&&this.emit("seek")}):t.currentTime=r,e.play&&this.play()}getDuration(){let e=this.getMedia().duration;if(!Number.isFinite(e))throw Error("Video duration is not available yet");return{duration:1e3*e}}}),"object"==typeof customElements)for(let e of["x-image","filter-image"]){if(t2.has(e))continue;t2.add(e);let t=e=>{if(!(tQ in e.prototype)){var t;null==(t=e.registerPlugin)||t.call(e,t1)}},r=customElements.get(e);r?t(r):customElements.whenDefined(e).then(t)}if("object"==typeof document&&"object"==typeof customElements){let e=document.createElement("map").constructor.prototype;for(let t of["center","scale-range","polyline","polygons","circles","arcs","route-label","extra-params"])t in e||Object.defineProperty(e,t,{configurable:!0,get(){return rh(this)[t]},set(e){var r;let i=rr.get(this)??{};i[t]=e,rr.set(this,i),null==(r=rn.get(this))||r.update()}});!function(){if(customElements.get("map-marker"))return;class e extends HTMLElement{static observedAttributes=["position","anchor","alpha","rotation","enable-click","enable-drag","animate","container-position"];connectedCallback(){queueMicrotask(()=>{var e;return null==(e=rg(this))?void 0:e.updateMarkers()})}attributeChangedCallback(){var e;null==(e=rg(this))||e.updateMarkers()}refreshMarker(){var e;null==(e=rg(this))||e.updateMarkers()}}for(let t of["position","anchor","animate","container-position"])Object.defineProperty(e.prototype,t,{configurable:!0,get(){return rm(this)[t]},set(e){var r;let i=ri.get(this)??{};i[t]=e,ri.set(this,i),null==(r=rg(this))||r.updateMarkers()}});customElements.define("map-marker",e)}()}function r_(e,t){if(e&&"event"===t.type&&t.name===e1&&o(t.params)){var r;null==(r=e.sendSyncBridgeUpdate)||r.call(e,t),o(t.params.globalProps)&&(e.globalProps={...e.globalProps,...t.params.globalProps})}"function"==typeof(null==e?void 0:e.sendGlobalEvent)&&e.sendGlobalEvent("__APPLET_BRIDGE__",[t])}class rS{container;className;options;runtimeContext;bridge=null;caller;cleanupWidgetTapCapture=null;cleanupWebMapHost=null;view=null;constructor(e,t={environment:"direct"}){let r=e.container;if(!r)throw Error("Container requires a container element");this.container=r,this.className=e.className??"doubao-web-container-view",this.options=e,this.runtimeContext=t}get element(){return this.view}prepare(){this.clear()}render(e){var t,r,i,n;this.clear();let a=Date.now(),s=document.createElement("lynx-view"),l="sandbox"===this.runtimeContext.environment?this.runtimeContext.resourceRoot:(null==(t=e.applicationPackage)?void 0:t.resourceRoot)??(null==(i=this.options.runtime)||null==(r=i.packageInfo)?void 0:r.resourceRoot);l&&(s.resolveResource=e=>{let t=e.startsWith("/base/")?e.slice(1):e;return t?new URL(t,l).href:t}),s.injectStyleRules=['[doubao-component="popup"] > .popup-container { top: 0; left: 0; z-index: 1000; }'];let d=t_(e),u=tS(d);s.className=this.className,e.groupId&&s.setAttribute("lynx-group-id",e.groupId),s.dataset.containerType=d,s.dataset.webSizing=u,s.style.display="APP"===d||"TOOL"===d?"none":"block",s.style.width="100%",s.style.height="content"===u?"auto":"100%","content"===u&&s.setAttribute("height","auto"),s.initData=e.initData??{};let c={...G(),...e.globalProps??{}};this.bridge=e.bridge??(null==(n=this.options.runtime)?void 0:n.bridge)??new tf,this.caller=e.bridgeCaller??this.bridge.register(e=>r_(s,e),e.bridge||this.options.runtime?{...this.options,apiRegistry:void 0}:this.options,"APP"===d);let p=this.bridge,h=this.caller;this.view=s;let m=()=>{var t,r,i,n,l;let m,g,f,v,b,w,_,S,x,I,k,C,E,N,T,A,M;if(this.view!==s)return;"direct"===this.runtimeContext.environment&&p.beginPerformance(h,{...e,containerType:d,globalProps:c});let R="sandbox"===this.runtimeContext.environment?this.runtimeContext.syncBridgeData:p.createSyncBridgeData(h,c,this.options.fileSystemNamespace);t=this.runtimeContext.environment,m=new URL("./__doubao_web_sdk_native_modules/",(null==(r=globalThis.document)?void 0:r.baseURI)??(null==(i=globalThis.location)?void 0:i.href)??"http://localhost/").href,g=ty(new URL("applet-bridge-module.js",m)),f=ty(new URL("applet-js-module.js",m)),w={AppletBridgeModule:((b=new URLSearchParams((v=new URL(g)).hash.slice(1))).set("__doubao_sync_bridge",JSON.stringify({...R,fileSystemSnapshot:ec(),storageSnapshot:{}})),v.hash=b.toString(),v.href),AppletJSModule:f},"direct"===t&&(w.LynxConsoleModule=ty(new URL("console-module.js",m)),"APP"===d&&(w.LynxDevToolSetModule=f)),s.nativeModulesMap=w,(0,tH.B)(s),s.napiModulesMap={...s.napiModulesMap,WebSyncBridge:s.nativeModulesMap.AppletBridgeModule};let j=s.onNapiModulesCall;s.onNapiModulesCall=(e,t,r,i,n)=>("WebSyncBridge"===r&&"subscribeSyncUpdates"===e&&(s.sendSyncBridgeUpdate=n,s.sendSyncBridgeUpdate({type:"event",name:e1,params:R,timestamp:Date.now()})),null==j?void 0:j(e,t,r,i,n)),s.globalProps={...c,__DOUBAO_WEB_SDK_SYNC_BRIDGE__:R};let P={containerType:d,element:s,globalProps:c,fileSystemNamespace:R.fileSystemNamespace,environment:this.runtimeContext.environment};s.onNativeModulesCall=(e,t,r)=>p.dispatch(h,e,t,r,P),n=async e=>{let t=await p.dispatch(h,"postMessage",e,"AppletBridgeModule",P);return y(t)?t:void 0},tJ.set(s,n),s.transformVW=!0,s.transformVH="content"!==u,s.transformREM=!1,s.addEventListener("timing",e=>{let t=e.detail;o(t)&&"number"==typeof t.create_lynx_start&&Number.isFinite(t.create_lynx_start)&&t.create_lynx_start>0&&(a=t.create_lynx_start),p.dispatch(h,"postMessage",{type:"call",name:e5,params:{timing:{create_lynx_start:a,...o(t)?t:{}}},callbackId:0},"AppletBridgeModule",P)}),s.addEventListener("error",e=>{var t,r;let i;null==(t=(r=this.options).onError)||t.call(r,(null==(i=e.detail)?void 0:i.error)instanceof Error?i.error:Error(String((null==i?void 0:i.error)??i??"Unknown Container runtime error")),e)}),"WIDGET"===d&&this.options.captureWidgetTap&&(this.cleanupWidgetTapCapture=(l=this.options.onWidgetInteraction,_=0,S=e=>{e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();var t={sequence:_+=1,type:"tap"};try{Promise.resolve(null==l?void 0:l(t)).catch(()=>void 0)}catch{}},s.addEventListener("click",S,!0),()=>s.removeEventListener("click",S,!0))),s.url=tw(e),this.container.replaceChildren(s),this.cleanupWebMapHost=(I=new Map,k=new Set,C=[],E=0,N=!1,T=e=>{for(let t of e.querySelectorAll("*"))"map"!==t.localName||rn.has(t)||k.add(new rf(t)),t.shadowRoot&&A(t.shadowRoot);for(let e of k)e.element.isConnected||(e.dispose(),k.delete(e))},A=e=>{if(I.has(e)||N)return;let t=new MutationObserver(t=>{if(!(t.some(e=>{let t=e.target;return t instanceof Element&&t.closest("[data-doubao-map-surface]")})&&t.every(e=>e.target instanceof Element&&e.target.closest("[data-doubao-map-surface]"))))for(let i of(T(e),t)){let e=i.target,t=e instanceof Element?e.closest("map"):null;if(t){var r;null==(r=rn.get(t))||r.update()}}});t.observe(e,{childList:!0,subtree:!0,attributes:!0}),I.set(e,t),T(e)},(M=()=>{if(N)return;let e=s.shadowRoot??s;if(A(e),s.shadowRoot&&x!==e)for(let t of(x=e,[0,16,100,500,2e3,1e4]))C.push(setTimeout(()=>{N||T(e)},t));else s.shadowRoot||(E=requestAnimationFrame(M))})(),()=>{for(let e of(N=!0,cancelAnimationFrame(E),C))clearTimeout(e);for(let e of I.values())e.disconnect();for(let e of k)e.dispose()})};return"sandbox"===this.runtimeContext.environment?m():p.prepareStorage(h,c,this.options.fileSystemNamespace).then(m).catch(e=>{if(this.view===s){var t,r;null==(t=(r=this.options).onError)||t.call(r,e,new Event("error"))}}),s}clear(){var e,t,r,i;null==(e=this.cleanupWebMapHost)||e.call(this),this.cleanupWebMapHost=null,null==(t=this.cleanupWidgetTapCapture)||t.call(this),this.cleanupWidgetTapCapture=null,this.caller&&(null==(i=this.bridge)||i.unregister(this.caller)),this.caller=void 0,this.bridge=null,null==(r=this.view)||r.remove(),this.view=null,this.container.replaceChildren()}setVisible(e){if(this.caller){var t;null==(t=this.bridge)||t.setVisible(this.caller,e)}}sendEvent(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t=this.view,r_(t,{type:"event",name:e,params:r,timestamp:Date.now()})}sendBridgeMessage(e){r_(this.view,e)}sendGlobalEvent(e,t){var r,i;null==(i=this.view)||null==(r=i.sendGlobalEvent)||r.call(i,e,t)}updateData(e){var t,r;null==(r=this.view)||null==(t=r.updateData)||t.call(r,e)}updateGlobalProps(e){this.view&&(this.view.globalProps={...this.view.globalProps,...e})}reload(){var e,t;null==(t=this.view)||null==(e=t.reload)||e.call(t)}}let rx=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
19
|
+
}`};dispose(){this.attributes.disconnect(),this.stopRendering()}}let t2=new Set;var t3=r(94763);let t4=new WeakMap;function t6(e,t,r){let i=new Map;for(let n of t){let t=Reflect.get(e,n);i.set(n,Object.getOwnPropertyDescriptor(e,n)),Object.defineProperty(e,n,{configurable:!0,writable:!0,value(){for(var e=arguments.length,i=Array(e),n=0;n<e;n++)i[n]=arguments[n];return r(),Reflect.apply(t,this,i)}})}return()=>{for(let[t,r]of i)r?Object.defineProperty(e,t,r):Reflect.deleteProperty(e,t)}}class t5{element;placeholder=document.createComment("map-marker");parent;cleanupElement;constructor(e){this.element=e;let t=e.parentNode;if(!t)throw Error("Web Map Marker requires a component parent");this.parent=t;let r=t4.get(t);if(!r){let e=new Set;r={portals:e,cleanup:t6(t,["appendChild","insertBefore","removeChild","replaceChild","append","prepend","replaceChildren"],()=>{for(let t of e)t.restore()})},t4.set(t,r)}r.portals.add(this),this.cleanupElement=t6(e,["remove","replaceWith","before","after"],()=>{for(let e of r.portals)e.restore()})}get connected(){return this.element.parentNode===this.parent?this.element.isConnected:this.placeholder.isConnected}mount(e){if(this.element.parentNode!==e){if(this.element.parentNode!==this.parent)throw Error("Web Map Marker component parent changed");Node.prototype.insertBefore.call(this.parent,this.placeholder,this.element),e.appendChild(this.element)}}restore(){this.placeholder.parentNode===this.parent&&Node.prototype.replaceChild.call(this.parent,this.element,this.placeholder)}destroy(){this.restore(),this.cleanupElement();let e=t4.get(this.parent);null==e||e.portals.delete(this),(null==e?void 0:e.portals.size)===0&&(e.cleanup(),t4.delete(this.parent))}}class t8{element;namespace;map;onError;onClick;content=document.createElement("div");portal;originalStyles=new Map;styleObserver=new MutationObserver(()=>this.syncZIndex());marker;defaultZIndex;positionKey;optionsKey;waitingForPosition=!1;syncing=!1;disposed=!1;constructor(e,t,r,i,n){this.element=e,this.namespace=t,this.map=r,this.onError=i,this.onClick=n,this.portal=new t5(e),this.content.style.cssText="width:0;height:0;overflow:visible;",this.styleObserver.observe(e,{attributes:!0,attributeFilter:["style","class"]})}get connected(){return this.portal.connected}sync(e){if(!this.disposed&&!this.syncing){this.syncing=!0;try{if(!e.position&&!e.containerPosition){var t;this.portal.restore(),null==(t=this.marker)||t.destroy(),this.marker=void 0,this.optionsKey=void 0,this.positionKey=void 0,this.waitingForPosition=!0,this.style("visibility","hidden");return}this.waitingForPosition&&(this.style("visibility",this.originalStyles.get("visibility")??""),this.waitingForPosition=!1),this.style("position","relative"),"inline"===getComputedStyle(this.element).display&&this.style("display","inline-block"),this.element.style.width||this.style("width","max-content"),this.style("transform",`translate(${-100*e.anchor[0]}%, ${-100*e.anchor[1]}%)`);let r="amap"===this.namespace.getProvider(),i={content:this.content,containerPosition:e.containerPosition?[e.containerPosition.x,e.containerPosition.y]:null,anchor:r?"top-left":0,angle:e.rotation,opacity:e.alpha,clickable:e.clickable,draggable:e.draggable,bubble:!e.clickable,animation:e.animate??(r?{scale:{from:1,to:1,duration:0}}:null)},n=JSON.stringify(e.position);this.marker&&n===this.positionKey||(i.position=e.position&&[e.position.longitude,e.position.latitude]),this.portal.mount(this.content);let a=JSON.stringify(e);if(this.marker&&this.optionsKey===a)return void this.syncZIndex();this.optionsKey=a,this.marker?this.marker.setOptions(i):(this.marker=new this.namespace.Marker(i),this.defaultZIndex=this.marker.getzIndex(),this.marker.on("click",this.onClick)),this.syncZIndex(),this.marker.getMap()!==this.map&&this.marker.setMap(this.map),this.positionKey=n}catch(e){this.onError(e)}finally{this.syncing=!1}}}syncZIndex(){if(this.marker&&!this.disposed)try{let e=Number.parseInt(getComputedStyle(this.element).zIndex,10),t=Number.isFinite(e)?e:this.defaultZIndex;void 0!==t&&t!==this.marker.getzIndex()&&this.marker.setzIndex(t)}catch(e){this.onError(e)}}style(e,t){this.originalStyles.has(e)||this.originalStyles.set(e,this.element.style.getPropertyValue(e)),this.element.style.getPropertyValue(e)!==t&&this.element.style.setProperty(e,t)}destroy(){var e;if(!this.disposed)for(let[t,r]of(this.disposed=!0,this.styleObserver.disconnect(),this.portal.destroy(),null==(e=this.marker)||e.destroy(),this.originalStyles))this.element.style.setProperty(t,r)}}let t9=e=>{let{longitude:t,latitude:r}=e;return[t,r]};function t7(e,t,r,i,n){let a=new Set(t.map(e=>{let{id:t}=e;return t}));for(let[t,r]of e)a.has(t)||(r.destroy(),e.delete(t));for(let a of t)try{let t=r(a),n=e.get(a.id);if(n){let{id:e,...r}=t;n.setOptions(r)}else e.set(a.id,i(t,a))}catch(e){n(e)}}class re{namespace;map;onError;onPolylineClick;polylines=new Map;polygons=new Map;circles=new Map;arcs=new Map;routeLabels=new Map;warnings=new Set;constructor(e,t,r,i){this.namespace=e,this.map=t,this.onError=r,this.onPolylineClick=i}warn(e){this.warnings.has(e)||(this.warnings.add(e),this.onError(Error(`Web Map 暂不支持 ${e}`)))}add(e){e.on("warning",e=>{this.onError(e.error??Error(e.reason??e.feature??"Web Map 覆盖物降级"))});try{return this.map.add(e),e}catch(t){throw e.destroy(),t}}sync(e){var t;let r=function(e){let t=new Map,r=new Set;for(let n of e){var i;if(!n.id.startsWith("__doubao_polyline_arrow__:"))continue;let a=null==(i=n.edgeTextureAssets)?void 0:i.find(e=>{let{id:t}=e;return"__doubao_polyline_arrow_texture__"===t});if(a)try{let i=decodeURIComponent(n.id.slice(26));e.some(e=>e.id===i)&&(t.set(i,{iconPath:a.url}),r.add(n))}catch{}}return e.filter(e=>!r.has(e)).map(e=>({...e,arrow:t.get(e.id)??e.arrow}))}(e.polyline??[]),i=this.namespace.supports("Polyline.edgeTexture").supported,n=this.namespace.supports("RouteLabel").supported;!i&&r.some(e=>{var t,r;return(null==(t=e.edgeTexture)?void 0:t.length)||(null==(r=e.edgeTextureAssets)?void 0:r.length)})&&this.warn("当前图商的 polyline 纹理"),!n&&(null==(t=e.routeLabel)?void 0:t.length)&&this.warn("当前图商的 routeLabel"),r.some(e=>e.collideDetection)&&this.warn("polyline POI 碰撞避让"),t7(this.polylines,r,e=>{var t;return{id:e.id,path:e.points.map(t9),strokeColors:e.edgeColor??[],arrow:e.arrow??null,edgeTexture:i?e.edgeTexture??[]:[],edgeTextureAssets:i?e.edgeTextureAssets??[]:[],strokeColor:(null==(t=e.edgeColor)?void 0:t[0])??"#0066ff",strokeWeight:e.width??2,strokeStyle:e.dottedLine?"dashed":"solid",lineCap:"line_cap_round"===e.lineCapType?"round":"butt",lineJoin:"line_join_round"===e.lineJoinType?"round":"line_join_miter"===e.lineJoinType?"miter":"bevel",zIndex:e.zIndex??0}},(e,t)=>{let r=new this.namespace.Polyline(e);return r.on("click",()=>this.onPolylineClick(t.id)),this.add(r)},this.onError),t7(this.polygons,e.polygons??[],e=>({id:e.id,path:e.points.map(t9),fillColor:e.fillColor,strokeColor:e.strokeColor,strokeWeight:e.strokeWidth,strokeStyle:e.dottedLine?"dashed":"solid",zIndex:e.zIndex}),e=>{let t=new this.namespace.Polygon(e);return this.add(t)},this.onError),t7(this.circles,e.circles??[],e=>({id:e.id,center:t9(e.center),radius:e.radius,fillColor:e.fillColor,strokeColor:e.strokeColor,strokeWeight:e.strokeWidth,zIndex:e.zIndex}),e=>{let t=new this.namespace.Circle(e);return this.add(t)},this.onError),t7(this.arcs,e.arcs??[],e=>({id:e.id,path:[t9(e.start),t9(e.mid??e.middle),t9(e.end)],strokeColor:e.color??"#0066ff",strokeWeight:e.width??2,zIndex:e.zIndex}),e=>{let t=new this.namespace.Arc(e);return this.add(t)},this.onError),t7(this.routeLabels,n?e.routeLabel??[]:[],e=>({id:e.id,path:e.points.map(t9),text:e.text,textColor:e.textColor??"#000000",fontSize:e.fontSize??12,fontWeight:e.fontWeight??"normal",borderColor:e.borderColor??"#cccccc",borderWidth:e.borderWidth??0,zIndex:e.zIndex??0}),e=>this.add(new this.namespace.RouteLabel(e)),this.onError)}destroy(){for(let e of[this.polylines,this.polygons,this.circles,this.arcs,this.routeLabels]){for(let t of e.values())t.destroy();e.clear()}}}let rt={baidu:{provider:"baidu",security:{baidu:{serviceHost:"https://api.doubao-dev.com/_BMapService/"}}},amap:{provider:"amap",key:{amap:"f57928bd7156da61d512795ec5c0c968"},security:{amap:{serviceHost:"https://api.doubao-dev.com/_AMapService"}}}},rr=new WeakMap,ri=new WeakMap,rn=new WeakMap,ra=new WeakMap;function rs(e,t,r){if(t in r)return r[t];let i=e.getAttribute(t);if(i)try{return JSON.parse(i)}catch{return}}function ro(e,t,r){let i=Number(e.getAttribute(t));return Number.isFinite(i)&&e.hasAttribute(t)?i:r}function rl(e,t,r){let i=e.getAttribute(t);return null===i?r:"false"!==i&&"0"!==i}function rd(e){let{longitude:t,latitude:r}=e;return[t,r]}function ru(e){return{longitude:e.lng,latitude:e.lat}}function rc(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};e.dispatchEvent(new CustomEvent(t,{detail:r,bubbles:!1}))}function rp(e,t){let r=t instanceof Error?t:Error(String(t));console.error("[Doubao Map]",r.message),e.dispatchEvent(new CustomEvent("error",{detail:{error:r}}))}function rh(e){return rr.get(e)??{}}function rm(e){return ri.get(e)??{}}function rg(e){let t=ra.get(e);if(t)return t;let r=e.closest("map");return r?rn.get(r):void 0}class rf{element;map;namespace;syncingMarkers=!1;overlays;markers=new Map;cleanupTileLoad;surface;resize;sizeFrame=0;loading=!1;initializationBlocked=!1;disposed=!1;ready=!1;lastAttributes="";lastOverlays="";lastStyle="";lastLogoPosition="";warnings=new Set;constructor(e){var t;if(this.element=e,rn.set(e,this),this.installMethods(),"inline"===getComputedStyle(e).display&&(e.style.display="block"),"static"===getComputedStyle(e).position&&(e.style.position="relative"),e.style.overflow="hidden",this.resize="function"==typeof ResizeObserver?new ResizeObserver(()=>this.initialize()):void 0,null==(t=this.resize)||t.observe(e),!this.resize){let e=()=>{this.disposed||this.map||this.loading||this.initializationBlocked||(this.initialize(),this.sizeFrame=requestAnimationFrame(e))};this.sizeFrame=requestAnimationFrame(e)}this.initialize()}warn(e){this.warnings.has(e)||(this.warnings.add(e),rp(this.element,Error(`Web Map 暂不支持 ${e}`)))}getMapConfig(){let e=rs(this.element,"extra-params",rh(this.element));return rt[(null==e?void 0:e.useAliMap)===!0?"amap":"baidu"]}initialize(){var e;if(this.disposed||this.loading||this.initializationBlocked||this.map||this.element.clientWidth<=0||this.element.clientHeight<=0)return;let t=this.getMapConfig(),r=(null==(e=this.element.ownerDocument.location)?void 0:e.hostname)??"";if("baidu"===t.provider&&(tb(r)||"[::1]"===r||r.endsWith(".localhost"))){this.initializationBlocked=!0,rp(this.element,Error("当前豆包百度地图账号未授权本地域名,请使用获准域名的 sandbox 调试地图。"));return}this.loading=!0;let i=document.createElement("div");i.dataset.doubaoMapSurface="",i.style.cssText="position:absolute;inset:0;width:100%;height:100%;",this.element.prepend(i),this.surface=i,Promise.resolve().then(()=>t3.H3.load(t)).then(e=>{this.disposed||this.createMap(e,i)}).catch(e=>{this.disposed||rp(this.element,e),i.remove(),this.surface=void 0}).finally(()=>{this.loading=!1})}createMap(e,t){let r=this.element,i=rs(r,"center",rh(r)),n=rs(r,"scale-range",rh(r));try{let a=new e.Map(t,{center:i&&rd(i),zoom:ro(r,"scale",16),zooms:n??[3,20],rotation:ro(r,"rotate",0),logoPosition:r.getAttribute("logo-position")||"bottom-left",eventContext:!0,enableNativeInteraction:rl(r,"native-interaction-enabled",!0),showScale:rl(r,"enable-scale-controls",!1),zoomEnable:rl(r,"enable-scale",!0),dragEnable:rl(r,"enable-drag",!0),rotateEnable:rl(r,"enable-rotate",!1)});this.map=a,this.namespace=e,this.overlays=new re(e,a,e=>rp(r,e),e=>rc(r,"clickpolyline",{id:e}));let s=!1,o=()=>{this.disposed||s||(s=!0,rc(r,"maptileload"))};if("baidu"===e.getProvider()){let e=a.getNative();e.addEventListener("firsttileloaded",o),this.cleanupTileLoad=()=>e.removeEventListener("firsttileloaded",o)}let l=()=>{this.disposed||this.ready||(this.ready=!0,rc(r,"mapload"),"amap"===e.getProvider()&&o(),this.update(!0))};a.on("complete",l),a.on("click",e=>{e.lnglat&&rc(r,"clickmap",{point:ru(e.lnglat)})}),a.on("error",e=>rp(r,e)),a.on("warning",e=>{rp(r,Error(e.reason??e.feature??"Web Map 能力降级"))});let d=(e,t,i)=>{if(!a.isReady())return;let n=t.context,s=(null==n?void 0:n.bounds)??a.getBounds();rc(r,"regionchange",{type:(null==n?void 0:n.phase)??e,...i?{causedBy:i}:{},center:ru((null==n?void 0:n.center)??a.getCenter()),scale:(null==n?void 0:n.zoom)??a.getZoom(),rotate:(null==n?void 0:n.rotation)??a.getRotation(),region:{southwest:ru(s.getSouthWest()),northeast:ru(s.getNorthEast())}})};a.on("movestart",e=>d("begin",e,"drag")),a.on("moveend",e=>d("end",e,"drag")),a.on("zoomstart",e=>d("begin",e,"scale")),a.on("zoomend",e=>d("end",e,"scale")),"baidu"!==e.getProvider()&&(a.on("rotatestart",e=>d("begin",e)),a.on("rotateend",e=>d("end",e))),a.isReady()&&l()}catch(e){var a,s,o;null==(a=this.cleanupTileLoad)||a.call(this),null==(s=this.overlays)||s.destroy(),null==(o=this.map)||o.destroy(),this.map=void 0,t.remove(),rp(r,e)}}update(){var e,t;let r=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!this.ready||!this.map||this.disposed)return;let i=this.element,n=this.map,a=rh(i),s=JSON.stringify({center:rs(i,"center",a),scale:i.getAttribute("scale"),scales:rs(i,"scale-range",a),rotate:i.getAttribute("rotate"),showScale:i.getAttribute("enable-scale-controls"),enableScale:i.getAttribute("enable-scale"),enableDrag:i.getAttribute("enable-drag"),enableRotate:i.getAttribute("enable-rotate"),nativeInteraction:i.getAttribute("native-interaction-enabled")});if(r||s!==this.lastAttributes){this.lastAttributes=s;try{let e=rs(i,"scale-range",a);e&&n.setZooms(e);let t=rs(i,"center",a);t?n.setZoomAndCenter(ro(i,"scale",16),rd(t)):n.setZoom(ro(i,"scale",16)),n.setRotation(ro(i,"rotate",0)),n.setShowScale(rl(i,"enable-scale-controls",!1)),n.setNativeInteractionEnabled(rl(i,"native-interaction-enabled",!0)),n.setStatus({zoomEnable:rl(i,"enable-scale",!0),dragEnable:rl(i,"enable-drag",!0),rotateEnable:rl(i,"enable-rotate",!1)})}catch(e){rp(i,e)}}let o=i.getAttribute("map-style")||"normal-light";if(o!==this.lastStyle){this.lastStyle=o;try{n.setMapStyle((null==(e=this.namespace)?void 0:e.getProvider())==="baidu"?{styleId:o}:o)}catch(e){rp(i,e)}}rl(i,"enable-tilt",!1)&&this.warn("地图倾斜");let l=i.getAttribute("logo-position")||"bottom-left";if(l!==this.lastLogoPosition){this.lastLogoPosition=l;try{n.setLogoPosition(l)}catch(e){rp(i,e)}}let d={polyline:rs(i,"polyline",a),polygons:rs(i,"polygons",a),circles:rs(i,"circles",a),arcs:rs(i,"arcs",a),routeLabel:rs(i,"route-label",a)},u=JSON.stringify(d);(r||u!==this.lastOverlays)&&(this.lastOverlays=u,null==(t=this.overlays)||t.sync(d)),this.updateMarkers()}updateMarkers(){let e=this.map,t=this.namespace;if((null==e?void 0:e.isReady())&&t&&!this.syncingMarkers){this.syncingMarkers=!0;try{let r=new Set([...this.element.querySelectorAll("map-marker")].filter(e=>e.closest("map")===this.element));for(let[e,t]of this.markers)r.has(e)&&t.connected||(r.delete(e),t.destroy(),this.markers.delete(e),ra.delete(e));for(let i of r){let r=rm(i);rl(i,"enable-collide-with-poi",!1)&&this.warn("marker POI 碰撞避让");let n=rs(i,"container-position",r),a=rl(i,"enable-drag",!1),s=!n&&"amap"===t.getProvider();a&&!s&&this.warn(n?"固定屏幕位置的 marker 拖动":"百度自定义内容 marker 拖动");let o=rl(i,"enable-click",!0);a&&!o&&this.warn("关闭点击时的 marker 拖动");let l=this.markers.get(i);l||(l=new t8(i,t,e,e=>rp(this.element,e),()=>rc(i,"clickmarker")),this.markers.set(i,l),ra.set(i,this)),l.sync({position:rs(i,"position",r),containerPosition:n,anchor:rs(i,"anchor",r)??[.5,1],rotation:ro(i,"rotation",0),alpha:ro(i,"alpha",1),clickable:o,draggable:a&&s&&o,animate:rs(i,"animate",r)})}}finally{this.syncingMarkers=!1}}}getMap(){var e;if(!(null==(e=this.map)?void 0:e.isReady()))throw Error("Web Map 尚未加载完成");return this.map}installMethods(){Object.assign(this.element,{setCenter:e=>{let{center:t,animated:r,duration:i}=e;return this.getMap().setCenter(rd(t),!1===r,i)},getCenter:()=>ru(this.getMap().getCenter()),setScale:e=>{let{scale:t,animated:r,duration:i}=e;return this.getMap().setZoom(t,!1===r,i)},getScale:()=>({scale:this.getMap().getZoom()}),getBound:()=>{let e=this.getMap().getBounds();return{southwest:ru(e.getSouthWest()),northeast:ru(e.getNorthEast())}},setBound:e=>{let{southwest:t,northeast:r,animated:i,duration:n}=e;return this.getMap().setBounds([t.longitude,t.latitude,r.longitude,r.latitude],!1===i,void 0,n)},fitPoints:e=>{let{points:t,padding:r=[0,0,0,0],animated:i,duration:n}=e;return this.getMap().setFitView(t.map(rd),!1===i,[r[2]??0,r[3]??0,r[0]??0,r[1]??0],void 0,n)},setAnchor:e=>{let{position:t}=e;return this.getMap().setAnchor([t.x,t.y])},latLngToPx:e=>{let{latLng:t}=e,r=this.getMap().lngLatToContainer(rd(t));return{x:r.x,y:r.y}},pxToLatLng:e=>{let{x:t,y:r}=e;return{latLng:ru(this.getMap().containerToLngLat([t,r]))}}})}dispose(){var e,t,r,i,n;if(!this.disposed){for(let[r,i]of(this.disposed=!0,null==(e=this.resize)||e.disconnect(),cancelAnimationFrame(this.sizeFrame),null==(t=this.cleanupTileLoad)||t.call(this),this.markers))ra.delete(r),i.destroy();this.markers.clear(),null==(r=this.overlays)||r.destroy(),null==(i=this.map)||i.destroy(),null==(n=this.surface)||n.remove(),rn.delete(this.element)}}}class rv{element;static observedAttributes=[];constructor(e){this.element=e}forwardLinkEvent=e=>{this.element.dispatchEvent(new CustomEvent("link",{detail:e.detail,bubbles:!0,composed:!0}))};connectedCallback(){this.element.addEventListener("bindlink",this.forwardLinkEvent);let e=this.element.markdownStyle??{};this.element.markdownStyle={...e,link:{...e.link,textDecoration:"none"},orderedList:{...e.orderedList,paddingLeft:0},unorderedList:{...e.unorderedList,paddingLeft:0}}}}function ry(e){var t;null==(t=e.registerPlugin)||t.call(e,rv)}let rb="x-video-engine",rw=globalThis.HTMLElement??class{};if("object"!=typeof customElements||customElements.get(tV)||customElements.define(tV,class e extends tY{static observedAttributes=["src"];#e=null;#t=null;#r=!1;messageOrigin;connectedCallback(){this.#r=!0,this.style.display||(this.style.display="block"),this.#i(),this.#n()}disconnectedCallback(){var e;this.#r=!1,this.#a(),null==(e=this.#e)||e.remove(),this.#e=null,window.removeEventListener("message",this.#s)}attributeChangedCallback(e){"src"===e&&this.#r&&this.#n()}get src(){return this.getAttribute("src")}set src(e){null===e?this.removeAttribute("src"):this.setAttribute("src",e)}reload(){this.#n(!0)}postMessage(e){let t=o(e)?e.data:void 0;this.#o({type:"event",name:"message",params:{data:t},timestamp:Date.now()})}eval(e){let t=o(e)&&"string"==typeof e.func?e.func:"";if(t)try{if(this.messageOrigin){var r,i;null==(i=this.#e)||null==(r=i.contentWindow)||r.postMessage({type:"__doubao_web_view_eval__",code:t},this.messageOrigin);return}let e=this.#l();null==e||e.eval(t)}catch{}}onGoBack(){return{consumed:!1}}#i(){if(this.#e)return this.#e;let e=this.shadowRoot??this.attachShadow({mode:"open"}),t=document.createElement("iframe");return t.style.cssText="display:block;width:100%;height:100%;border:none;",t.addEventListener("load",this.#d),t.addEventListener("error",this.#u),e.replaceChildren(t),this.#e=t,window.addEventListener("message",this.#s),t}#n(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.#i(),r=this.getAttribute("src");if(!r)return;let i=tK(r);this.messageOrigin="window"===i.messageTransport?new URL(i.url,document.baseURI).origin:void 0,(e||t.getAttribute("src")!==i.url)&&(this.#a(),t.toggleAttribute("credentialless",!0===i.credentialless),t.src=i.url)}#a(){var e;null==(e=this.#t)||e.close(),this.#t=null}#l(){try{var e;let t=(null==(e=this.#e)?void 0:e.contentWindow)??null;return null==t||t.document,t}catch{return null}}#d=()=>{this.messageOrigin||(this.#c(),this.#p(),this.#h()),this.#m("load",{url:this.getAttribute("src")??""})};#u=()=>{this.#m("error",{errorMsg:`Failed to load ${this.getAttribute("src")??""}`,errorCode:-1})};#s=e=>{if(!this.#e||e.source!==this.#e.contentWindow||this.messageOrigin&&e.origin!==this.messageOrigin||e.data===tG)return;let t=tZ(e.data);this.#g(t)||this.#f(tX(e.data))};#c(){var e;this.#a();let t=null==(e=this.#e)?void 0:e.contentWindow;if(!t)return;let r=new MessageChannel;r.port1.onmessage=e=>{e.data!==tG&&this.#g(tZ(e.data))},this.#t=r.port1,t.postMessage("__channel_init__","*",[r.port2])}#p(){let e=this.#l();e&&!e.AppletBridgeModule&&(e.AppletBridgeModule={postMessage:e=>(this.#g(tZ(e)),Promise.resolve({})),postMessageSync:e=>{let t=tZ(e);return v(t)?S(t,"Sync AppletBridgeModule APIs are not supported in Doubao Web SDK web-view"):void 0}})}#h(){let e=this.#l();e&&this.#f(JSON.stringify({type:"__doubao_web_view_set_title__",title:e.document.title||""}))}#g(e){if(o(e)&&"event"===e.type)return"__bridge_ready__"===e.name;if(!v(e))return!1;if("doubao.postMessage"===e.name){let t=o(e.params)?e.params.data:void 0;return this.#f(tX(t)),this.#o(_(e,{})),!0}return this.#v(e),!0}async #v(e){let t=function(e){let t=e;for(;t;){if(t instanceof Element){let e=tJ.get(t);if(e)return e}let e=t.parentNode;t=e instanceof ShadowRoot?e.host:e}}(this);if(!t)return void this.#o(S(e,`API ${e.name} is not available in this web-view host`));let r=await t(e);this.#o(r??S(e,`API ${e.name} is not implemented in Doubao Web SDK`))}#o(e){var t,r,i;let n=JSON.stringify(e);if(this.messageOrigin){null==(i=this.#e)||null==(r=i.contentWindow)||r.postMessage({type:"__doubao_web_view_message__",payload:n},this.messageOrigin);return}if(this.#t)return void this.#t.postMessage(n);let a=this.#l();null==a||null==(t=a.onWebViewMessage)||t.call(a,n)}#f(e){this.#m("message",{msg:e,data:e})}#m(e,t){for(let r of[e,`bind${e}`])this.dispatchEvent(new CustomEvent(r,{bubbles:!0,composed:!0,detail:t}))}}),"object"==typeof customElements&&!a){let e=customElements.get("x-markdown");e?(ry(e),a=Promise.resolve()):a=customElements.whenDefined("x-markdown").then(e=>{ry(e)})}if("object"!=typeof customElements||customElements.get(rb)||customElements.define(rb,class e extends rw{static observedAttributes=["play-url","video-model","vid","auto-prepare","initial-time","objectfit","muted","loop","volume","speed"];video=null;prepared=!1;firstFrame=!1;stopped=!0;playbackState=-1;playRequest=0;connectedCallback(){if(this.video)return;let e=this.shadowRoot??this.attachShadow({mode:"open"}),t=document.createElement("style");t.textContent=":host{display:block;width:100%;height:100%}video{display:block;width:100%;height:100%}";let r=document.createElement("video");this.video=r,r.playsInline=!0,e.replaceChildren(t,r);let i=(e,t)=>r.addEventListener(e,e=>{e.stopPropagation(),this.video===r&&this.isConnected&&t()});i("loadedmetadata",()=>{r.currentTime=this.numberAttribute("initial-time",0)/1e3}),i("canplay",()=>this.notifyPrepared()),i("loadeddata",()=>{this.firstFrame||(this.firstFrame=!0,this.emit("firstframe"))}),i("playing",()=>{this.stopped=!1,this.setPlaybackState(1)}),i("pause",()=>this.setPlaybackState(2*!this.stopped)),i("seeked",()=>this.emit("seek")),i("timeupdate",()=>this.emit("timeupdate",{current:1e3*r.currentTime,total:Number.isFinite(r.duration)?1e3*r.duration:0})),i("ended",()=>{this.stopped=!0,this.setPlaybackState(0),this.emit("completion")}),i("error",()=>{var e,t;return this.reportError((null==(e=r.error)?void 0:e.message)||"Video resource could not be played",null==(t=r.error)?void 0:t.code)}),document.addEventListener("visibilitychange",this.handleVisibility),this.syncAttributes(),this.syncSource()}disconnectedCallback(){var e;let t=this.video;this.video=null,this.playRequest++,document.removeEventListener("visibilitychange",this.handleVisibility),t&&(t.pause(),t.removeAttribute("src"),t.load()),null==(e=this.shadowRoot)||e.replaceChildren()}attributeChangedCallback(e,t,r){this.video&&t!==r&&(["play-url","video-model","vid"].includes(e)?this.syncSource():(this.syncAttributes(),"auto-prepare"!==e||this.booleanAttribute("auto-prepare",!0)||(this.video.preload="none")))}booleanAttribute(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.getAttribute(e);return null===r?t:"false"!==r&&"0"!==r}numberAttribute(e,t){let r=this.getAttribute(e),i=null===r||""===r.trim()?0/0:Number(r);return Number.isFinite(i)&&i>=0?i:t}syncAttributes(){let e=this.video;e.muted=this.booleanAttribute("muted"),e.loop=this.booleanAttribute("loop"),e.volume=Math.min(1,this.numberAttribute("volume",1));try{e.playbackRate=this.numberAttribute("speed",1)||1,e.defaultPlaybackRate=e.playbackRate}catch(e){this.reportError(String(e))}let t=this.getAttribute("objectfit")??"contain";e.style.objectFit=["contain","cover","fill"].includes(t)?t:"contain",this.booleanAttribute("auto-prepare",!0)&&(e.preload="auto",e.controls=!0)}syncSource(){let e=this.video,t=this.getAttribute("play-url")||"";t&&e.getAttribute("src")===t||(this.playRequest++,this.prepared=this.firstFrame=!1,this.stopped=!0,this.playbackState=-1,e.pause(),e.preload=this.booleanAttribute("auto-prepare",!0)?"auto":"none",e.controls="auto"===e.preload,t?e.src=t:e.removeAttribute("src"),e.load(),queueMicrotask(()=>{this.isConnected&&this.video===e&&(this.getAttribute("play-url")||"")===t&&(t?this.emit("redirect"):(this.getAttribute("video-model")||this.getAttribute("vid"))&&this.reportError("Web VideoEngine requires play-url; video-model and vid are not supported"))}))}notifyPrepared(){var e;this.prepared||(null==(e=this.video)?void 0:e.preload)!=="auto"||(this.prepared=!0,this.emit("canplay"))}emit(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:"error"!==e}))}setPlaybackState(e){this.playbackState!==e&&(this.playbackState=e,this.emit("playbackstatechanged",{playbackState:e}))}reportError(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;this.emit("error",{errorCode:t,errorMsg:e})}getMedia(){var e;if(!(null==(e=this.video)?void 0:e.getAttribute("src")))throw Error("Web VideoEngine requires play-url");return this.video}handleVisibility=()=>{var e;document.hidden&&this.booleanAttribute("pause-on-hide")&&(null==(e=this.video)?void 0:e.getAttribute("src"))&&this.pause()};prepare(){let e=this.getMedia();e.preload="auto",e.controls=!0,this.prepared=!1,e.readyState>=3?queueMicrotask(()=>{this.video===e&&this.notifyPrepared()}):e.load()}play(){let e=this.getMedia();this.stopped=!1;let t=++this.playRequest;e.play().catch(r=>{this.video===e&&t===this.playRequest&&this.reportError(String(r))})}pause(){let e=this.getMedia();this.playRequest++,this.stopped=!1,e.pause(),this.setPlaybackState(2)}stop(){let e=this.getMedia();this.playRequest++,this.stopped=!0,e.pause(),e.currentTime=0,this.setPlaybackState(0)}seek(e){if(!e||!Number.isFinite(e.position)||e.position<0)throw Error("seek.position must be a non-negative number in milliseconds");let t=this.getMedia(),r=Math.min(e.position/1e3,Number.isFinite(t.duration)?t.duration:1/0);e.play||this.pause(),t.currentTime===r?queueMicrotask(()=>{this.video===t&&this.emit("seek")}):t.currentTime=r,e.play&&this.play()}getDuration(){let e=this.getMedia().duration;if(!Number.isFinite(e))throw Error("Video duration is not available yet");return{duration:1e3*e}}}),"object"==typeof customElements)for(let e of["x-image","filter-image"]){if(t2.has(e))continue;t2.add(e);let t=e=>{if(!(tQ in e.prototype)){var t;null==(t=e.registerPlugin)||t.call(e,t1)}},r=customElements.get(e);r?t(r):customElements.whenDefined(e).then(t)}if("object"==typeof document&&"object"==typeof customElements){let e=document.createElement("map").constructor.prototype;for(let t of["center","scale-range","polyline","polygons","circles","arcs","route-label","extra-params"])t in e||Object.defineProperty(e,t,{configurable:!0,get(){return rh(this)[t]},set(e){var r;let i=rr.get(this)??{};i[t]=e,rr.set(this,i),null==(r=rn.get(this))||r.update()}});!function(){if(customElements.get("map-marker"))return;class e extends HTMLElement{static observedAttributes=["position","anchor","alpha","rotation","enable-click","enable-drag","animate","container-position"];connectedCallback(){queueMicrotask(()=>{var e;return null==(e=rg(this))?void 0:e.updateMarkers()})}attributeChangedCallback(){var e;null==(e=rg(this))||e.updateMarkers()}refreshMarker(){var e;null==(e=rg(this))||e.updateMarkers()}}for(let t of["position","anchor","animate","container-position"])Object.defineProperty(e.prototype,t,{configurable:!0,get(){return rm(this)[t]},set(e){var r;let i=ri.get(this)??{};i[t]=e,ri.set(this,i),null==(r=rg(this))||r.updateMarkers()}});customElements.define("map-marker",e)}()}function r_(e,t){if(e&&"event"===t.type&&t.name===e1&&o(t.params)){var r;null==(r=e.sendSyncBridgeUpdate)||r.call(e,t),o(t.params.globalProps)&&(e.globalProps={...e.globalProps,...t.params.globalProps})}"function"==typeof(null==e?void 0:e.sendGlobalEvent)&&e.sendGlobalEvent("__APPLET_BRIDGE__",[t])}class rS{container;className;options;runtimeContext;bridge=null;caller;cleanupWidgetTapCapture=null;cleanupWebMapHost=null;view=null;constructor(e,t={environment:"direct"}){let r=e.container;if(!r)throw Error("Container requires a container element");this.container=r,this.className=e.className??"doubao-web-container-view",this.options=e,this.runtimeContext=t}get element(){return this.view}prepare(){this.clear()}render(e){var t,r,i,n;this.clear();let a=Date.now(),s=document.createElement("lynx-view"),l="sandbox"===this.runtimeContext.environment?this.runtimeContext.resourceRoot:(null==(t=e.applicationPackage)?void 0:t.resourceRoot)??(null==(i=this.options.runtime)||null==(r=i.packageInfo)?void 0:r.resourceRoot);l&&(s.resolveResource=e=>{let t=e.startsWith("/base/")?e.slice(1):e;return t?new URL(t,l).href:t}),s.injectStyleRules=['[doubao-component="popup"] > .popup-container { top: 0; left: 0; z-index: 1000; }'];let d=t_(e),u=tS(d);s.className=this.className,e.groupId&&s.setAttribute("lynx-group-id",e.groupId),s.dataset.containerType=d,s.dataset.webSizing=u,s.style.display="APP"===d||"TOOL"===d?"none":"block",s.style.width="100%",s.style.height="content"===u?"auto":"100%","content"===u&&s.setAttribute("height","auto"),s.initData=e.initData??{};let c={...G(),...e.globalProps??{}};this.bridge=e.bridge??(null==(n=this.options.runtime)?void 0:n.bridge)??new tf,this.caller=e.bridgeCaller??this.bridge.register(e=>r_(s,e),e.bridge||this.options.runtime?{...this.options,apiRegistry:void 0}:this.options,"APP"===d);let p=this.bridge,h=this.caller;this.view=s;let m=()=>{var t,r,i,n,l;let m,g,f,v,b,w,_,S,x,I,k,C,E,N,T,A,M;if(this.view!==s)return;"direct"===this.runtimeContext.environment&&p.beginPerformance(h,{...e,containerType:d,globalProps:c});let R="sandbox"===this.runtimeContext.environment?this.runtimeContext.syncBridgeData:p.createSyncBridgeData(h,c,this.options.fileSystemNamespace);t=this.runtimeContext.environment,m=new URL("./__doubao_web_sdk_native_modules/",(null==(r=globalThis.document)?void 0:r.baseURI)??(null==(i=globalThis.location)?void 0:i.href)??"http://localhost/").href,g=ty(new URL("applet-bridge-module.js",m)),f=ty(new URL("applet-js-module.js",m)),w={AppletBridgeModule:((b=new URLSearchParams((v=new URL(g)).hash.slice(1))).set("__doubao_sync_bridge",JSON.stringify({...R,fileSystemSnapshot:ec(),storageSnapshot:{}})),v.hash=b.toString(),v.href),AppletJSModule:f},"direct"===t&&(w.LynxConsoleModule=ty(new URL("console-module.js",m)),"APP"===d&&(w.LynxDevToolSetModule=f)),s.nativeModulesMap=w,(0,tH.B)(s),s.napiModulesMap={...s.napiModulesMap,WebSyncBridge:s.nativeModulesMap.AppletBridgeModule};let j=s.onNapiModulesCall;s.onNapiModulesCall=(e,t,r,i,n)=>("WebSyncBridge"===r&&"subscribeSyncUpdates"===e&&(s.sendSyncBridgeUpdate=n,s.sendSyncBridgeUpdate({type:"event",name:e1,params:R,timestamp:Date.now()})),null==j?void 0:j(e,t,r,i,n)),s.globalProps={...c,__DOUBAO_WEB_SDK_SYNC_BRIDGE__:R};let P={containerType:d,element:s,globalProps:c,fileSystemNamespace:R.fileSystemNamespace,environment:this.runtimeContext.environment};s.onNativeModulesCall=(e,t,r)=>p.dispatch(h,e,t,r,P),n=async e=>{let t=await p.dispatch(h,"postMessage",e,"AppletBridgeModule",P);return y(t)?t:void 0},tJ.set(s,n),s.transformVW=!0,s.transformVH="content"!==u,s.transformREM=!1,s.addEventListener("timing",e=>{let t=e.detail;o(t)&&"number"==typeof t.create_lynx_start&&Number.isFinite(t.create_lynx_start)&&t.create_lynx_start>0&&(a=t.create_lynx_start),p.dispatch(h,"postMessage",{type:"call",name:e6,params:{timing:{create_lynx_start:a,...o(t)?t:{}}},callbackId:0},"AppletBridgeModule",P)}),s.addEventListener("error",e=>{var t,r;let i;null==(t=(r=this.options).onError)||t.call(r,(null==(i=e.detail)?void 0:i.error)instanceof Error?i.error:Error(String((null==i?void 0:i.error)??i??"Unknown Container runtime error")),e)}),"WIDGET"===d&&this.options.captureWidgetTap&&(this.cleanupWidgetTapCapture=(l=this.options.onWidgetInteraction,_=0,S=e=>{e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();var t={sequence:_+=1,type:"tap"};try{Promise.resolve(null==l?void 0:l(t)).catch(()=>void 0)}catch{}},s.addEventListener("click",S,!0),()=>s.removeEventListener("click",S,!0))),s.url=tw(e),this.container.replaceChildren(s),this.cleanupWebMapHost=(I=new Map,k=new Set,C=[],E=0,N=!1,T=e=>{for(let t of e.querySelectorAll("*"))"map"!==t.localName||rn.has(t)||k.add(new rf(t)),t.shadowRoot&&A(t.shadowRoot);for(let e of k)e.element.isConnected||(e.dispose(),k.delete(e))},A=e=>{if(I.has(e)||N)return;let t=new MutationObserver(t=>{if(!(t.some(e=>{let t=e.target;return t instanceof Element&&t.closest("[data-doubao-map-surface]")})&&t.every(e=>e.target instanceof Element&&e.target.closest("[data-doubao-map-surface]"))))for(let i of(T(e),t)){let e=i.target,t=e instanceof Element?e.closest("map"):null;if(t){var r;null==(r=rn.get(t))||r.update()}}});t.observe(e,{childList:!0,subtree:!0,attributes:!0}),I.set(e,t),T(e)},(M=()=>{if(N)return;let e=s.shadowRoot??s;if(A(e),s.shadowRoot&&x!==e)for(let t of(x=e,[0,16,100,500,2e3,1e4]))C.push(setTimeout(()=>{N||T(e)},t));else s.shadowRoot||(E=requestAnimationFrame(M))})(),()=>{for(let e of(N=!0,cancelAnimationFrame(E),C))clearTimeout(e);for(let e of I.values())e.disconnect();for(let e of k)e.dispose()})};return"sandbox"===this.runtimeContext.environment?m():p.prepareStorage(h,c,this.options.fileSystemNamespace).then(m).catch(e=>{if(this.view===s){var t,r;null==(t=(r=this.options).onError)||t.call(r,e,new Event("error"))}}),s}clear(){var e,t,r,i;null==(e=this.cleanupWebMapHost)||e.call(this),this.cleanupWebMapHost=null,null==(t=this.cleanupWidgetTapCapture)||t.call(this),this.cleanupWidgetTapCapture=null,this.caller&&(null==(i=this.bridge)||i.unregister(this.caller)),this.caller=void 0,this.bridge=null,null==(r=this.view)||r.remove(),this.view=null,this.container.replaceChildren()}setVisible(e){if(this.caller){var t;null==(t=this.bridge)||t.setVisible(this.caller,e)}}sendEvent(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t=this.view,r_(t,{type:"event",name:e,params:r,timestamp:Date.now()})}sendBridgeMessage(e){r_(this.view,e)}sendGlobalEvent(e,t){var r,i;null==(i=this.view)||null==(r=i.sendGlobalEvent)||r.call(i,e,t)}updateData(e){var t,r;null==(r=this.view)||null==(t=r.updateData)||t.call(r,e)}updateGlobalProps(e){this.view&&(this.view.globalProps={...this.view.globalProps,...e})}reload(){var e,t;null==(t=this.view)||null==(e=t.reload)||e.call(t)}}let rx=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
20
20
|
<path d="M3.74902 7.91113C4.90234 7.91131 5.83691 8.84664 5.83691 10C5.83674 11.1532 4.90223 12.0877 3.74902 12.0879C2.59566 12.0879 1.66033 11.1533 1.66016 10C1.66016 8.84653 2.59555 7.91113 3.74902 7.91113ZM9.99805 7.91113C11.1514 7.91131 12.0859 8.84664 12.0859 10C12.0858 11.1532 11.1513 12.0877 9.99805 12.0879C8.84469 12.0879 7.90936 11.1533 7.90918 10C7.90918 8.84653 8.84458 7.91113 9.99805 7.91113ZM16.249 7.91113C17.4023 7.91131 18.3369 8.84664 18.3369 10C18.3367 11.1532 17.4022 12.0877 16.249 12.0879C15.0957 12.0879 14.1603 11.1533 14.1602 10C14.1602 8.84653 15.0956 7.91113 16.249 7.91113Z" fill="black"/>
|
|
21
21
|
</svg>`,rI=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
22
22
|
<path d="M9.99622 18.176C8.86678 18.176 7.8086 17.9623 6.82166 17.5348C5.83472 17.1126 4.96653 16.5267 4.21709 15.7773C3.46765 15.0331 2.87919 14.1676 2.45169 13.1806C2.02947 12.1884 1.81836 11.1276 1.81836 9.99817C1.81836 8.86873 2.02947 7.81055 2.45169 6.82361C2.87919 5.8314 3.46765 4.96057 4.21709 4.21113C4.96653 3.46169 5.83472 2.87586 6.82166 2.45364C7.8086 2.03142 8.86678 1.82031 9.99622 1.82031C11.1257 1.82031 12.1838 2.03142 13.1708 2.45364C14.163 2.87586 15.0338 3.46169 15.7833 4.21113C16.5327 4.96057 17.1185 5.8314 17.5408 6.82361C17.9682 7.81055 18.182 8.86873 18.182 9.99817C18.182 11.1276 17.9682 12.1884 17.5408 13.1806C17.1185 14.1676 16.5327 15.0331 15.7833 15.7773C15.0338 16.5267 14.163 17.1126 13.1708 17.5348C12.1838 17.9623 11.1257 18.176 9.99622 18.176ZM9.99622 16.561C10.904 16.561 11.7537 16.3895 12.5454 16.0465C13.337 15.7087 14.0337 15.239 14.6354 14.6373C15.2423 14.0356 15.7147 13.339 16.0524 12.5473C16.3902 11.7557 16.5591 10.9059 16.5591 9.99817C16.5591 9.0904 16.3902 8.24068 16.0524 7.44902C15.7147 6.65208 15.2423 5.95542 14.6354 5.35904C14.0337 4.75738 13.337 4.28766 12.5454 3.94988C11.7537 3.60683 10.904 3.4353 9.99622 3.4353C9.09373 3.4353 8.24401 3.60683 7.44707 3.94988C6.65541 4.28766 5.95875 4.75738 5.35708 5.35904C4.75542 5.95542 4.28306 6.65208 3.94001 7.44902C3.60224 8.24068 3.43335 9.0904 3.43335 9.99817C3.43335 10.9059 3.60224 11.7557 3.94001 12.5473C4.28306 13.339 4.75542 14.0356 5.35708 14.6373C5.95875 15.239 6.65541 15.7087 7.44707 16.0465C8.24401 16.3895 9.09373 16.561 9.99622 16.561ZM10.0041 13.0856C9.43414 13.0856 8.91164 12.9458 8.43665 12.6661C7.96693 12.3863 7.59221 12.0116 7.31249 11.5419C7.03277 11.0722 6.89291 10.5523 6.89291 9.98234C6.89291 9.41234 7.03277 8.89248 7.31249 8.42277C7.59221 7.95305 7.96693 7.57833 8.43665 7.29861C8.91164 7.01361 9.43414 6.87111 10.0041 6.87111C10.5741 6.87111 11.0914 7.01361 11.5558 7.29861C12.0255 7.57833 12.4002 7.95305 12.68 8.42277C12.9597 8.89248 13.0995 9.41234 13.0995 9.98234C13.0995 10.5523 12.9597 11.0722 12.68 11.5419C12.4002 12.0116 12.0255 12.3863 11.5558 12.6661C11.0914 12.9458 10.5741 13.0856 10.0041 13.0856Z" fill="black"/>
|
|
23
|
-
</svg>`,rk="doubao-apps-page",rC={body:`${rk}__body`,capsule:`${rk}__capsule`,capsuleAction:`${rk}__capsule-action`,capsuleCloseIcon:`${rk}__capsule-close-icon`,capsuleMoreIcon:`${rk}__capsule-more-icon`,root:rk};class rE{host;options;runtimeKernel;container=null;root=null;constructor(e,t){if(!e.container)throw Error("Page requires a container element");this.host=e.container,this.options=e,this.runtimeKernel=t}get element(){var e;return(null==(e=this.container)?void 0:e.element)??null}render(e){var t,r;let i;this.clear();let n=document.createElement("div");n.className=rC.root,void 0!==(i=null==(t=e.pageCapsule)?void 0:t.statusBarHeight)&&n.style.setProperty("--doubao-page-capsule-top",`${i+4}px`);let a=document.createElement("div");a.className=rC.body,n.append(a,this.createCapsule()),this.host.replaceChildren(n),this.root=n;try{return this.container=this.runtimeKernel.createContainer({...this.options,sandboxUrl:this.options.runtime?this.options.runtime.sandboxUrl:this.options.sandboxUrl,container:a,className:this.options.className,onError:this.options.onError,onReady:this.options.onReady}),this.container.render({bridge:null==(r=this.options.runtime)?void 0:r.bridge,resourceUrl:function(e){if(!e.resourceUrl)throw Error("Page.render requires a resourceUrl");return e.resourceUrl}(e),groupId:e.groupId,containerType:"PAGE",initData:e.initData,globalProps:e.globalProps})}catch(e){throw this.clear(),e}}clear(){var e,t;null==(e=this.container)||e.clear(),this.container=null,null==(t=this.root)||t.remove(),this.root=null,this.host.replaceChildren()}setVisible(e){var t,r;null==(r=this.container)||null==(t=r.setVisible)||t.call(r,e)}sendEvent(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};null==(t=this.container)||t.sendEvent(e,r)}reload(){var e;null==(e=this.container)||e.reload()}updateGlobalProps(e){var t;if(!(null==(t=this.container)?void 0:t.updateGlobalProps))throw Error("Page container does not support updating global props");this.container.updateGlobalProps(e)}dispatchCapsuleEvent(e,t){t.stopPropagation(),this.host.dispatchEvent(new CustomEvent(e,{bubbles:!0}))}createCapsuleSvg(e){let t=document.createElement("template");t.innerHTML=e.trim();let r=t.content.firstElementChild;if(!r||"svg"!==r.tagName.toLowerCase())throw Error("Invalid Page capsule icon SVG");return r}createCapsuleAction(e,t,r,i){let n=this.createCapsuleSvg(r);return n.classList.add(rC.capsuleAction,e),n.setAttribute("role","button"),n.setAttribute("aria-label",t),n.setAttribute("tabindex","0"),n.setAttribute("focusable","true"),n.addEventListener("click",e=>{this.dispatchCapsuleEvent(i,e)}),n.addEventListener("keydown",e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),this.dispatchCapsuleEvent(i,e))}),n}createCapsuleMoreIcon(){return this.createCapsuleAction(rC.capsuleMoreIcon,"More",rx,"doubao:page-capsule-more")}createCapsuleCloseIcon(){return this.createCapsuleAction(rC.capsuleCloseIcon,"Close app",rI,"doubao:page-capsule-close")}createCapsule(){let e=document.createElement("div");return e.className=rC.capsule,e.style.display="flex",e.style.flexDirection="row",e.setAttribute("role","group"),e.setAttribute("aria-label","Page actions"),e.append(this.createCapsuleMoreIcon(),this.createCapsuleCloseIcon()),e}}let rN=/\{\{\s*([^{}\s]+)\s*\}\}/g;function rT(e){return"string"==typeof e?e:JSON.stringify(e)}function rA(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={...e.input||{},...function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={};for(let[i,n]of Object.entries(e.variables||{}))Object.prototype.hasOwnProperty.call(t,i)?r[i]=t[i]:null!==n&&(r[i]=n);return{...r,...t}}(e,t)};if("page"===e.type){let t=function(e,t){var r;let i=new Set(Array.from(e.url.matchAll(rN),e=>e[1])),n=(r=e.url,r.replace(rN,(e,r)=>{if(!Object.prototype.hasOwnProperty.call(t,r))return e;let i=rT(t[r]);return void 0===i?e:encodeURIComponent(i)})),a=n.indexOf("#"),s=a<0?n:n.slice(0,a),o=a<0?"":n.slice(a),l=s.indexOf("?"),d=new Set(new URLSearchParams(l<0?"":s.slice(l+1)).keys()),u=new URLSearchParams;for(let[e,r]of Object.entries(t)){if(i.has(e)||d.has(e))continue;let t=rT(r);void 0!==t&&u.set(e,t)}let c=u.toString();if(!c)return n;let p=l<0?"?":s.endsWith("?")||s.endsWith("&")?"":"&";return`${s}${p}${c}${o}`}(e,r);return{type:"page",unresolvedVariables:function(e){let t=new Set;for(let r of e.matchAll(rN))t.add(r[1]);return Array.from(t)}(t),url:t}}return"widget"===e.type?{type:"widget",id:e.id,resolvedInput:r,botId:e.botId}:{type:"tool",id:e.id,resolvedInput:r}}function rM(e){var t;let{addProtocolToBareHost:r=!1,allowRootRelative:i=!1,defaultProtocol:n="http"}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(/^https?:\/\//i.test(e))return e;if(e.startsWith("//"))return`${rj(n,e.slice(2))}:${e}`;if(i&&e.startsWith("/"))return e;return/^(?:\[[^\]]+\]|[a-z0-9.-]+):\d+(?:[/?#]|$)/i.test(e)||r&&(t=e,/^(?:\[[^\]]+\]|[a-z0-9.-]+)(?:[/?#]|$)/i.test(t))?`${rj(n,e)}://${e}`:e}function rR(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=String(e??"").trim();if(!r)return;let i=rM(r,t);try{let e=t.baseUrl?new URL(i,t.baseUrl):new URL(i);if("http:"!==e.protocol&&"https:"!==e.protocol)return;return e.toString()}catch{return}}function rj(e,t){return"function"==typeof e?e(t):e}function rP(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}var rL=r(70851);function rO(e,t){if(e.appId&&t&&e.appId!==t)throw Error("Resolved Widget appId must match the trusted Widget identity");return t??e.appId}let rD="__doubao_apps__expired-widget",rU="doubao-apps-widget",rq=1,r$={body:`${rU}__body`,default:`${rU}--default`,floatingHeader:`${rU}--floating-header`,embedded:`${rU}--embedded`,header:`${rU}__header`,icon:`${rU}__icon`,placeholder:`${rU}__placeholder`,placeholderContent:`${rU}__placeholder-content`,root:rU,title:`${rU}__title`};class rB{container;options;runtimeKernel;identity;viewContext;root=null;body=null;title=null;icon=null;runtimeContainer=null;runtimeFallbackOptions={};apiContextOwner={};appTheme;hostCallController=null;constructor(e,t){var r,i;let n,a,s,l,d,u;if(!e.container)throw Error("Widget requires a container element");if(!e.runtime)throw Error("Widget requires a Runtime");this.container=e.container,this.options=e,this.runtimeKernel=t,this.appTheme="light"===(n=o(r=e.globalProps)?r.appTheme:void 0)||"dark"===n?n:void 0,this.identity=(i=`widget-${rq++}`,a=e.viewContext,s=e.appId??(null==a?void 0:a.appId),l=e.widgetId??(null==a?void 0:a.widgetId),d=(null==a?void 0:a.widgetInstanceId)??i,u=a?{...a,appId:s??a.appId,widgetId:l,widgetInstanceId:d}:void 0,{appId:s,versionTag:null==a?void 0:a.versionTag,viewContext:u,widgetId:l,widgetInstanceId:d}),this.viewContext=this.identity.viewContext}get element(){var e;return(null==(e=this.runtimeContainer)?void 0:e.element)??this.root}setAppTheme(e){var t;this.appTheme=e,this.root&&(this.root.dataset.appTheme=e),null==(t=this.runtimeContainer)||t.sendEvent("onThemeChange",{appTheme:e})}async render(){var e;this.clear(),this.hostCallController=new AbortController;let t=this.hostCallController.signal;try{await f(()=>this.options.runtime.loadPackage(),t)}catch(e){if(g(t),o(e)&&"AbortError"===e.name)throw e;return this.renderFallback()}if(g(t),"iframe"===(e={identity:this.identity,mode:this.runtimeKernel.mode}).mode&&e.identity.widgetId!==rD&&e.identity.appId&&e.identity.widgetId)try{this.prepareIframeRuntime()}catch{return this.renderFallback()}let r=function(e){let t;g(e.signal);let{packageInfo:r,packageManager:i}=e.options.runtime,{manifest:n}=r;if(rO(e.identity,n.appId),e.identity.widgetId===rD){var a,s;let t;return{kind:"expired",options:{appName:n.name??e.identity.appId,icon:n.iconSrc,placeholderText:"string"==typeof(t=null==(a=e.options.initData)||null==(s=a.viewData)?void 0:s.title)&&t.trim().length>0?t:void 0}}}try{let n=i.resolveWidget(r,e.identity.widgetId);if(g(e.signal),t={appName:n.appName,icon:n.icon},!n.resourceUrl)return{kind:"fallback",options:t};return{kind:"runtime",options:{appId:rO(e.identity,n.appId),boxType:n.boxType,...t,resourceUrl:n.resourceUrl,renderMode:n.renderMode??"standard",titleType:n.titleType??2*(!1===n.showHeader)}}}catch{return g(e.signal),{kind:"fallback",options:t}}}({identity:this.identity,mode:this.runtimeKernel.mode,options:this.options,signal:t});if("expired"===r.kind)return this.renderPlaceholderCard(r.options);if("fallback"===r.kind)return this.renderFallback(r.options);try{return this.renderResource(r.options)}catch{return g(t),this.renderFallback({appName:r.options.appName,icon:r.options.icon})}}getShellClassName(e){let{boxType:t,floatingHeader:r,renderMode:i}=e,n="embedded"===i;return(0,rL.$)(r$.root,{[r$.default]:4!==t&&!n,[r$.floatingHeader]:r,[r$.embedded]:n},this.options.className)}renderShell(e){var t;let r=document.createElement("section");r.className=this.getShellClassName(e),this.appTheme&&(r.dataset.appTheme=this.appTheme);let i="number"==typeof(t=this.options.contentMaxWidth)&&Number.isFinite(t)?`${t}px`:"string"==typeof t&&t.trim().length>0?t:void 0;i&&(r.style.maxWidth=i);let n=document.createElement("div");n.className=r$.body;let a=null;if(e.showHeader){(a=document.createElement("header")).className=r$.header,a.hidden="iframe"===this.runtimeKernel.mode;let e=document.createElement("img");e.alt="",e.className=r$.icon,e.height=16,e.width=16;let t=document.createElement("div");t.className=r$.title,a.append(e,t),r.append(a),this.icon=e,this.title=t}return r.append(n),this.container.replaceChildren(r),this.root=r,this.body=n,this.updateHeader(e.appName,e.icon),{body:n,header:a,root:r}}renderPlaceholderCard(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.clear();let{body:t,header:r,root:i}=this.renderShell({appName:e.appName??this.identity.widgetId??this.identity.appId??"",icon:e.icon,renderMode:"standard",showHeader:!0});r&&(r.hidden=!1);let n=document.createElement("div");n.className=r$.placeholder;let a=document.createElement("div");return a.className=r$.placeholderContent,a.textContent=e.placeholderText??this.options.fallbackText??"",n.append(a),t.append(n),i}renderFallback(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.renderPlaceholderCard({...e,placeholderText:this.options.fallbackText})}handleRuntimeError(e,t,r){try{var i,n;null==(i=(n=this.options).onError)||i.call(n,e,t)}finally{this.renderFallback({appName:r.appName,icon:r.icon})}}renderResource(e){var t,r;let i={...this.options.globalProps,__GEN_UI_DATA__:this.options.genUIData??(null==(t=this.options.globalProps)?void 0:t.__GEN_UI_DATA__),appTheme:this.appTheme,[e6]:{widgetId:this.identity.widgetId,widgetInstanceId:this.identity.widgetInstanceId},packageInfo:{...null==(r=this.options.globalProps)?void 0:r.packageInfo,appId:e.appId,iconSrc:e.icon,name:e.appName}};this.runtimeFallbackOptions={appName:e.appName,icon:e.icon};let{body:n,root:a}=this.updateOrRenderResourceShell(e);return"iframe"===this.runtimeKernel.mode&&(a.style.background="transparent",a.style.borderWidth="0"),this.runtimeContainer??=this.createRuntimeContainer(n),this.runtimeContainer.render({bridge:this.options.runtime.bridge,containerType:"WIDGET",resourceUrl:e.resourceUrl,initData:this.options.initData,globalProps:{...i,__VIEW_CONTEXT__:this.viewContext??{}}})}createRuntimeContainer(e){var t,r;let i=(null==(t=this.viewContext)||null==(r=t.shareInfo)?void 0:r.mode)==="share_page";return this.runtimeKernel.createContainer({...this.options,getAppletContext:()=>({owner:this.options.invocationOwner??this.apiContextOwner,signal:this.getHostCallSignal(),source:"widget",viewContext:this.viewContext}),sandboxUrl:this.options.runtime.sandboxUrl,captureWidgetTap:i||void 0,container:e,onUnsupportedAPI:this.options.onUnsupportedAPI,onError:(e,t)=>{this.handleRuntimeError(e,t,this.runtimeFallbackOptions)},onReady:()=>{var e,t,r;null==(e=this.root)||e.style.removeProperty("background"),null==(t=this.root)||t.style.removeProperty("border-width"),(null==(r=this.title)?void 0:r.parentElement)&&(this.title.parentElement.hidden=!1)},onWidgetInteraction:i&&this.options.onWidgetInteraction?e=>this.handleWidgetInteraction(e):void 0})}prepareIframeRuntime(){let{body:e,root:t}=this.renderShell({renderMode:"standard",showHeader:!0});t.style.background="transparent",t.style.borderWidth="0",this.runtimeFallbackOptions={},this.runtimeContainer=this.createRuntimeContainer(e),this.runtimeContainer.prepare("WIDGET")}updateOrRenderResourceShell(e){var t,r,i;let n={appName:e.appName,boxType:e.boxType,floatingHeader:1===e.titleType,icon:e.icon,renderMode:e.renderMode,showHeader:"embedded"!==e.renderMode&&2!==e.titleType};return this.root&&this.body?(this.root.className=this.getShellClassName(n),n.showHeader||(null==(i=this.title)||null==(r=i.parentElement)||r.remove(),this.icon=null,this.title=null),this.updateHeader(e.appName,e.icon),{body:this.body,header:(null==(t=this.title)?void 0:t.parentElement)??null,root:this.root}):this.renderShell(n)}clear(){var e,t,r;null==(e=this.hostCallController)||e.abort(),this.hostCallController=null,this.apiContextOwner={},null==(t=this.runtimeContainer)||t.clear(),this.runtimeContainer=null,this.runtimeFallbackOptions={},null==(r=this.root)||r.remove(),this.root=null,this.body=null,this.title=null,this.icon=null,this.container.replaceChildren()}updateData(e){var t;this.options.initData=e,null==(t=this.runtimeContainer)||t.updateData(e)}reload(){var e;null==(e=this.runtimeContainer)||e.reload()}destroy(){this.clear()}getHostCallSignal(){if(this.hostCallController)return this.hostCallController.signal;let e=new AbortController;return e.abort(),e.signal}async handleWidgetInteraction(e){let t=this.options.onWidgetInteraction;if(!t)return;let r=this.getHostCallSignal();g(r),await t(e),g(r)}updateHeader(e,t){this.title&&(this.title.textContent=e??""),this.icon&&(t?(this.icon.src=t,this.icon.hidden=!1):(this.icon.removeAttribute("src"),this.icon.hidden=!0))}}let rF={mode:"inline",createContainer:e=>new rS(e)},rz=new tz(rF,!0);class rW{options;emptyState;cleanupEmptyState;constructor(e){this.options=e}get container(){return this.options.container}hide(){var e,t;null==(e=(t=this.options).onHide)||e.call(t)}async confirmBeforeUnload(e,t){return(null==t||!t.aborted)&&(this.options.confirmBeforeUnload?this.options.confirmBeforeUnload(e,t):window.confirm(e))}createPage(e,t,r){let i=document.createElement("div");i.className="doubao-runtime-page",Object.assign(i.style,{display:"block",width:"100%",height:"100%"}),i.addEventListener("doubao:page-capsule-close",e=>{e.stopPropagation(),r()});let n=this.container,a=new rE({...e,container:i},t);return{render:e=>(n.append(i),a.render(e)),setVisible(e){i.style.display=e?"block":"none",a.setVisible(e)},clear(){a.clear(),i.remove()},sendEvent:a.sendEvent.bind(a),updateGlobalProps:a.updateGlobalProps.bind(a),reload:a.reload.bind(a)}}setEmpty(e){let t=this.options.mountEmptyState;!this.emptyState&&t&&(this.emptyState=document.createElement("div"),this.emptyState.className="doubao-runtime-empty",this.container.append(this.emptyState),this.cleanupEmptyState=t(this.emptyState)??void 0),this.emptyState&&(this.emptyState.hidden=!e)}destroy(){var e,t;null==(e=this.cleanupEmptyState)||e.call(this),this.cleanupEmptyState=void 0,null==(t=this.emptyState)||t.remove(),this.emptyState=void 0}}function rH(e,t,r){let i=(null==r?void 0:r.fileSystemNamespace)??eu(null==r?void 0:r.globalProps);return ev(i,async()=>{let r=eb(i);eJ(r,e,t),await ex(i,{fileSystemChanges:eS(eb(i).entries,r.entries)})})}async function rV(e,t){if(!e.startsWith("appletfile:"))return e;let r=(null==t?void 0:t.fileSystemNamespace)??eu(null==t?void 0:t.globalProps);return ev(r,()=>{var t;let i=eb(r).entries[eD(e)];if(!i)throw new w(`file not found: ${e}`,203);if("file"!==i.type)throw new w(`path is a directory: ${e}`,1901001);let n=null==(t=e.split(".").pop())?void 0:t.toLowerCase();return`data:${({png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",wav:"audio/wav",mp3:"audio/mpeg",m4a:"audio/mp4",ogg:"audio/ogg",flac:"audio/flac",aac:"audio/aac",mp4:"audio/mp4"})[n??""]??"application/octet-stream"};base64,${i.data}`})}class rG extends tW(rS,()=>rz){}class rJ extends rB{constructor(e){super(e,rF)}}class rK extends tF{constructor(e){super(e,rF)}}var rZ=r(75541);function rX(e){return"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=9999}function rY(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0}function rQ(e,t){let r=t.trim();r&&!e.includes(r)&&e.push(r)}function r0(e){let t=[];return!function e(t,r,i){if(!("object"!=typeof t||null===t||i.has(t))){if(i.add(t),Array.isArray(t))return void t.forEach(t=>e(t,r,i));if(rP(t))for(let[n,a]of Object.entries(t))"response_headers"===n.toLowerCase()&&function(e,t){if(rP(e)){for(let[r,i]of Object.entries(e))if("x-tt-logid"===r.toLowerCase()&&"string"==typeof i)return void rQ(t,i)}}(a,r),"log_ids"===n.toLowerCase()&&function(e,t){if("string"==typeof e)return rQ(t,e);if(Array.isArray(e))for(let r of e)"string"==typeof r&&rQ(t,r)}(a,r),e(a,r,i)}}(e,t,new WeakSet),t}function r1(e,t){if(!e.startsWith("sslocal://"))return{url:e};let r=new URL(e).searchParams,i=r.get("app_id"),n=r.get("path"),a=r.get("query"),s=r.get("route_mode")??void 0;if(!t)throw Error("当前调试应用缺少 AppID");if(i!==t)throw Error(`任务目标应用 ${i} 与当前应用 ${t} 不一致`);if(!n)throw Error("任务目标缺少 path");if(void 0!==s&&"navigate"!==s&&"redirect"!==s&&"relaunch"!==s)throw Error(`不支持的任务导航模式: ${s}`);return{url:a?`${n}?${a}`:n,routeMode:s}}function r2(e){return rP(e)?rP(e.viewData)?e:{...e,viewData:e}:{viewData:{}}}function r3(e){if("string"==typeof e&&e.trim())try{return JSON.parse(e)}catch{return}}function r4(e){if(rP(e))return e;let t=r3(e);return rP(t)?t:void 0}function r5(e){if("string"==typeof e)return e;try{return JSON.stringify(e??{})}catch{return"{}"}}function r6(e){return e instanceof Error?e.message:String(e)}function r8(e){let t=null==e?void 0:e.toLowerCase();switch(t){case"agent":case"api":case"mcp":case"card":case"resource":case"runtime":case"debug":return t;case"tool":return"agent";default:return"runtime"}}function r9(e){let[t,...r]=e.trim().split(":"),i=t.replace(/_/g," ").trim().split(/\s+/).filter(Boolean).map(r7).join(" ");return 0===r.length?i||e:`${i}: ${r.join(":").trim()}`}function r7(e){let t=function(e){switch(e.toLowerCase()){case"api":return"API";case"mcp":return"MCP";case"sse":return"SSE";case"ack":return"ACK";case"http":return"HTTP";case"json":return"JSON";case"id":return"ID";default:return""}}(e);if(t)return t;if(/^[A-Z0-9]+$/.test(e))return e;let r=e.toLowerCase();return`${r.slice(0,1).toUpperCase()}${r.slice(1)}`}r(78872),r(60972);let ie=new Set(["local_mcp_missing","local_mcp_tools_load_failed","simulator_chat_fetch_failed","simulator_query_failed","stream_error","tool_executor_missing","tool_result_submit_failed"]),it={query:0,"tool-call":10,"tool-result":20,"agent-processing":25,card:30,"agent-response":40,error:50};function ir(e,t){return{category:"api",detail:{query:t},key:"query",phase:"request",payload:{event:"query",query:t},source:e,sources:[e],title:"Query"}}function ii(e,t){let r=e.steps.get(t.key);if(!r)return void e.steps.set(t.key,t);let i=function(e,t){if("error"===t.phase)return!0;if(e.key.startsWith("card:")){let r=il(e.source.payload);return ia(il(t.source.payload))>ia(r)}return!1}(r,t),n=i?t:r,a=i?r:t;e.steps.set(t.key,{...r,category:"error"===t.phase?t.category:n.category,detail:ih(n.detail,a.detail),phase:"error"===t.phase?t.phase:n.phase,payload:ih(n.payload,a.payload),source:n.source,sources:[...new Map([...r.sources,...t.sources].map(e=>[e.id,e])).values()],title:"error"===t.phase||i?t.title:r.title})}function ia(e){return"simulator_card_render_failed"===e||"simulator_card_runtime_error"===e||"simulator_card_render_skipped"===e?3:"simulator_card_rendered"===e?2:+("card_delta"===e)}function is(e){let t=iv([...e.steps.values()]);return t.map((r,i)=>{var n,a,s,o,l,d,u;let c,p,h,m,g,f,v,y,b,w,_;return n=r,a=e,s=t,o=i,y=im(n.sources.flatMap(r0)),b=im(n.sources.map(e=>e.payload.request_id||"")),_=void 0===(w=(l=n,d=s,u=o,c=l.payload.elapsed_ms??l.detail.elapsed_ms,h=(null==(p=l.key.startsWith("agent-processing:")?d.slice(u+1).find(e=>/^(tool-call|card|error):/.test(e.key)||"agent-response"===e.key):d[u+1])?void 0:p.source.timestamp)??l.source.timestamp,m=Number.isFinite(l.source.timestamp)&&Number.isFinite(h)?Math.max(0,h-l.source.timestamp):void 0,f=(g=l.key.startsWith("tool-call:")?l.key.replace("tool-call:","tool-result:"):l.key.startsWith("tool-result:")?l.key.replace("tool-result:","tool-call:"):void 0)?d.find(e=>e.key===g):void 0,void 0!==(v=l.key.startsWith("tool-call:")&&f?f.payload.elapsed_ms??f.detail.elapsed_ms:void 0)?v:l.key.startsWith("tool-result:")&&f?void 0:void 0!==c?void 0===m?c:Math.max(c,m):m))?n.detail:{...n.detail,elapsed_ms:w},{id:n.source.id,order:n.source.order,timestamp:n.source.timestamp,display:{category:n.category,detail:_,phase:n.phase,title:n.title},payload:{request_id:1===b.length?b[0]:void 0,request_ids:b.length>1?b:void 0,...n.payload,trace_id:a.id,run_status:a.status,elapsed_ms:w,log_ids:y.length>0?y:void 0}}})}function io(e,t){let r=ig(t.payload),i=r?e.runs.find(e=>e.id===r):void 0;if(!i){if(!r)return;i={id:r,order:t.order??e.runs.length,startedAt:t.timestamp,steps:new Map},e.runs.push(i)}return i.startedAt=Math.min(i.startedAt,t.timestamp),i.order=Math.min(i.order,t.order??i.order),i}function il(e){return e.event||""}function id(e,t){return iu(e)||[ig(e)||t.id,e.tool_name||"unknown-tool"].filter(Boolean).join(":")}function iu(e){return e.tool_call_id||""}function ic(e){let t=e.tool_name||iu(e);return t?`: ${t}`:""}function ip(e){let t={};for(let[r,i]of Object.entries(e))null!=i&&""!==i&&(t[r]=i);return t}function ih(e,t){return Object.fromEntries([...Object.entries(t),...Object.entries(e).filter(e=>{let[,t]=e;return void 0!==t})])}function im(e){return[...new Set(e.filter(e=>!!e))]}function ig(e){var t;return e.trace_id||(null==(t=e.trace)?void 0:t.trace_id)||""}function iv(e){return[...e].sort((e,t)=>e.source.timestamp-t.source.timestamp||(e.source.order??0)-(t.source.order??0)||it[e.key.split(":")[0]]-it[t.key.split(":")[0]]||e.key.localeCompare(t.key))}function iy(e,t){return e.startedAt-t.startedAt||e.order-t.order||e.id.localeCompare(t.id)}function ib(e,t){return e.timestamp-t.timestamp||(e.order??0)-(t.order??0)||e.id.localeCompare(t.id)}function iw(e){try{return i_(e,2)}catch{var t=e;if("string"==typeof t){let e=t.trim();if(!e)return"";try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}if(void 0===t)return"";try{return JSON.stringify(t,null,2)}catch{return String(t)}}}function i_(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=new WeakSet;return JSON.stringify(e,(e,t)=>{if(t instanceof Error)return{name:t.name,message:t.message,stack:t.stack};if("function"==typeof t)return`[Function ${t.name||"anonymous"}]`;if("object"==typeof t&&null!==t){if(r.has(t))return"[Circular]";r.add(t)}return t},t)}function iS(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=Date.now();return{stored_at:new Date(r).toISOString(),stored_at_ms:r,snapshot:ix(e,t),debug_snapshot:ix(e,{...t,debug:!0,includeRuntimeRoot:!1})}}function ix(e){var t,r;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=i.debug&&!i.traceId?(t=e,r=!1!==i.includeRuntimeRoot,rP(t)&&!r&&rP(t.runtime_snapshot)?{...t,runtime_snapshot:ik(t.runtime_snapshot,!1)}:t):function(e,t){var r;if(!rP(e))return e;let i=rP(e.simulator)?e.simulator:{},n=Array.isArray(i.messages)?i.messages.filter(e=>iC(e,t.traceId)):void 0,a=Array.isArray(i.tool_calls)?i.tool_calls.filter(e=>iC(e,t.traceId)):void 0,s=ik(e.runtime_snapshot,!1!==t.includeRuntimeRoot);return{...iR(e,["exported_at","client_id","command_id","context","render_targets"]),runtime_snapshot:rP(s)?s:void 0,simulator:rP(e.simulator)?{...iR(i,["stream_status","active_request_id","active_reply_message_id"]),error:i.error?iM(i.error):void 0,selected_card:i.selected_card?iA(i.selected_card):void 0,answer_finish:i.answer_finish?rP(r=i.answer_finish)?iR(r,["messageId","status","finishReason","usage","createdAtMs"]):r:void 0,messages:null==n?void 0:n.map(iE),tool_calls:null==a?void 0:a.map(iT),trace_events:Array.isArray(i.trace_events)?iI(i.trace_events,{debug:t.debug,messages:n,traceId:t.traceId}):void 0}:void 0,widget_runtime_trace_events:Array.isArray(e.widget_runtime_trace_events)?iI(e.widget_runtime_trace_events,{debug:t.debug,traceId:t.traceId}):void 0,page_runtime_trace_events:Array.isArray(e.page_runtime_trace_events)?iI(e.page_runtime_trace_events,{debug:t.debug,traceId:t.traceId}):void 0,runtime_console:rP(e.runtime_console)?e.runtime_console:void 0}}(e,i),a=r0(e);return a.length>0&&rP(n)?{...n,log_ids:a}:n}function iI(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(t.debug&&!t.traceId)return e;if(t.debug){var r,i;return r=e,(i=t.traceId)?r.filter(e=>ig(e.payload)===i):r}let n=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r={runs:[]};for(let t of[...e].sort(ib))!function(e,t){var r,i;let n=t.payload,a=il(n);if("tool_result_report_started"===a){let r=io(e,t);if(!r)return;ii(r,function(e){let t=e.payload,r=ip({tool_call_id:iu(t),tool_name:t.tool_name});return{category:"agent",detail:r,key:`agent-processing:${id(t,e)}`,phase:"request",payload:{event:"agent_processing",...r},source:e,sources:[e],title:`Agent Processing${ic(t)}`}}(t));return}if(!((r=a).startsWith("tool_result_report_")||"tool_result_ack"===r)){if("simulator_chat_fetch_started"===a){let r=function(e){var t,r,i;return e.query||(null==(t=e.request)?void 0:t.query)||(null==(i=e.request)||null==(r=i.message)?void 0:r.content)||""}(n);if(!r)return;let i=io(e,t);if(!i)return;ii(i,ir(t,r));return}if("tool_call"===a||"local_mcp_call_started"===a){let r=io(e,t);if(!r)return;ii(r,function(e){let t=e.payload,r=ip({tool_call_id:iu(t),tool_name:t.tool_name,arguments:t.arguments,arguments_json:t.arguments_json});return{category:"agent",detail:r,key:`tool-call:${id(t,e)}`,phase:"request",payload:{event:"tool_call",...r},source:e,sources:[e],title:`Tool Call${ic(t)}`}}(t));return}if("local_mcp_call_succeeded"===a||"local_mcp_call_failed"===a){let r=io(e,t);if(!r)return;ii(r,function(e){let t=e.payload,r="local_mcp_call_failed"===il(t),i=t.result??t.structured_result??r3(t.structured_result_json)??t.structured_result_json,n=t.raw_mcp_result??r3(t.raw_mcp_result_json)??t.raw_mcp_result_json,a=t.raw_result_text===t.raw_mcp_result_json?void 0:t.raw_result_text,s=ip({tool_call_id:iu(t),tool_name:t.tool_name,status:t.status,result:i,raw_result_text:a,raw_mcp_result:n,elapsed_ms:t.elapsed_ms,error:t.error});return{category:"mcp",detail:s,key:`tool-result:${id(t,e)}`,phase:r?"error":"response",payload:{event:r?"tool_result_failed":"tool_result",...s},source:e,sources:[e],title:`${r?"Tool Result Failed":"Tool Result"}${ic(t)}`}}(t));return}if("card_delta"===(i=a)||"simulator_card_rendered"===i||"simulator_card_render_failed"===i||"simulator_card_runtime_error"===i||"simulator_card_render_skipped"===i){let r=io(e,t);if(!r)return;ii(r,function(e){var t,r;let i=e.payload,n=il(i),a="error"in i||n.endsWith("_failed")||n.endsWith("_error"),s=ip({card_id:i.card_id,widget_id:i.widget_id,card_type:i.card_type,entity_id:i.entity_id,source_tool_call_id:i.source_tool_call_id,elapsed_ms:i.elapsed_ms,error:i.error,summary:i.summary});return{category:"card",detail:s,key:`card:${t=i,r=e,t.card_id||t.source_tool_call_id||[ig(t)||r.id,t.widget_id||r.id].filter(Boolean).join(":")}`,phase:a?"error":"response",payload:{event:a?"card_render_failed":"card_delta"===n?"card_received":"card_rendered",...s},source:e,sources:[e],title:a?"Card Render Failed":"card_delta"===n?"Card Received":"Card Rendered"}}(t));return}if(function(e,t){let r=e.phase,i=e.status;return ie.has(t)||"error"===r||t.endsWith("_failed")||t.endsWith("_missing")||t.endsWith("_aborted")||t.endsWith("_error")||"failed"===i||"error"===i||"number"==typeof i&&i>=400}(n,a)){let r=io(e,t);if(!r)return;ii(r,function(e){var t,r;let i=e.payload,n=i.detail??{},a=i.event_count??n.event_count,s=ip({elapsed_ms:i.elapsed_ms??n.elapsed_ms,endpoint:i.endpoint??n.endpoint,error:i.error??n.error,event_count:a,message:i.message??n.message,reason:i.reason??n.reason,status:i.status??n.status,summary:i.summary??n.summary??("simulator_chat_sse_read_failed"===il(i)&&0===a?"对话流未收到任何事件,未触发 MCP tool 与 tool/report;请结合 log_id 排查生成或下发 tool_call 前的服务端/链路异常。":void 0),response:i.response??n.response,response_text:i.response_text??n.response_text});return{category:(null==(t=e.display)?void 0:t.category)||"runtime",detail:s,key:`error:${e.id}`,phase:"error",payload:{event:il(i)||"trace_error",...s},source:e,sources:[e],title:(null==(r=e.display)?void 0:r.title)||i.title||"Trace Error"}}(t))}}}(r,t);for(let e of t)!function(e,t){var r,i,n,a,s;let o=(i=t,{id:`trace-message-${i.messageId}`,timestamp:i.createdAtMs,payload:ip({message_id:i.messageId,request_id:i.requestId,trace_id:i.traceId})}),l=io(e,o);if(!l)return;let d=(null==(r=t.blocks)?void 0:r.some(e=>"image"===e.type))??!1,u=t.text.trim()||(d?"[图片]":"");"assistant"===t.role&&t.status&&(n=l,a=t.status,s=t.createdAtMs,void 0!==n.statusUpdatedAt&&s<n.statusUpdatedAt||(n.status=a,n.statusUpdatedAt=s)),"user"===t.role&&u&&!l.steps.has("query")&&ii(l,ir(o,u)),"assistant"===t.role&&t.text.trim()&&ii(l,function(e,t){let r=iv([...e.steps.values()]).at(-1),i=Math.max(t.createdAtMs,((null==r?void 0:r.source.timestamp)??t.createdAtMs)+.1),n={id:`trace-agent-response-${t.messageId}`,order:(null==r?void 0:r.source.order)===void 0?void 0:r.source.order+.1,timestamp:i,payload:ip({message_id:t.messageId,request_id:t.requestId,trace_id:t.traceId})};return{category:"agent",detail:{text:t.text},key:"agent-response",phase:"finish",payload:{event:"agent_response",message_id:t.messageId,text:t.text},source:n,sources:[n],title:"Agent Response"}}(l,t))}(r,e);return r}(e,t.messages);return(t.traceId?n.runs.filter(e=>e.id===t.traceId):n.runs).sort(iy).flatMap(is)}(e,t)}function ik(e,t){if(!rP(e)||t)return e;let{root:r,...i}=e;return i}function iC(e,t){if(!t)return!0;if(!rP(e))return!1;let r=rP(e.trace)?e.trace:{};return e.traceId===t||r.trace_id===t}function iE(e){return rP(e)?{...iR(e,["messageId","localMessageId","requestId","traceId","role","contentType","status","createdAtMs"]),text:"string"==typeof e.text?ij(e.text):void 0,blocks:Array.isArray(e.blocks)?e.blocks.map(iN):void 0,toolCalls:Array.isArray(e.toolCalls)?e.toolCalls:void 0,toolResults:Array.isArray(e.toolResults)?e.toolResults:void 0}:e}function iN(e){return rP(e)?"card"===e.type?{...iR(e,["blockId","type"]),card:iA(e.card)}:"image"===e.type&&rP(e.image)?{...iR(e,["blockId","type"]),image:iR(e.image,["resource_uri","mime_type","size_bytes","width","height","sha256","name"])}:{...iR(e,["blockId","type"]),text:"string"==typeof e.text?ij(e.text):void 0}:e}function iT(e){return rP(e)?{...iR(e,["requestId","runId","replyMessageId","toolCallId","toolName","serverId","appKey","status","createdAtMs","updatedAtMs","requiresUserApproval","timeoutMs","deadlineMs","progress","message","resultSummary","structuredResultSummary","isMiniApp"]),arguments:e.arguments,argumentsJson:void 0===e.arguments&&e.argumentsJson?e.argumentsJson:void 0,error:e.error?iM(e.error):void 0}:e}function iA(e){return rP(e)?iR(e,["reply_message_id","block_id","card_id","widget_id","card_type","app_id","entity_id","title","fallback_text"]):e}function iM(e){return rP(e)?iR(e,["code","message","user_message","retryable","stage","details","name","stack"]):e}function iR(e,t){let r={};for(let i of t)void 0!==e[i]&&(r[i]=e[i]);return r}function ij(e){return e.length>1e3?`${e.slice(0,1e3)}...`:e}let iP=[1e3,2e3,4e3,8e3,16e3];class iL{clientId=crypto.randomUUID();socket;status="disconnected";listeners=new Set;retryTimer;retryIndex=0;sandboxSnapshot;snapshot;sentRuntime;snapshotErrorReported=!1;subscribe(e){return this.listeners.add(e),e({type:"status",status:this.status}),void 0!==this.sandboxSnapshot&&e({type:"sandbox",data:this.sandboxSnapshot}),()=>{this.listeners.delete(e)}}start(){this.stop(),this.retryIndex=0,this.connect()}stop(){clearTimeout(this.retryTimer),this.retryTimer=void 0;let e=this.socket;this.socket=void 0,null==e||e.close(),this.sandboxSnapshot=void 0,this.setStatus("disconnected")}emit(e){for(let t of this.listeners)t(e)}setStatus(e){this.status!==e&&(this.status=e,this.emit({type:"status",status:e}))}connect(){let e;this.setStatus(this.retryIndex?"reconnecting":"connecting");let t=new URL("/__wsd_connection",window.location.href);t.protocol="https:"===t.protocol?"wss:":"ws:",t.searchParams.set("clientId",this.clientId);let r=new WebSocket(t);this.socket=r,r.onopen=()=>{this.socket===r&&(e=Date.now(),this.sentRuntime=void 0,this.sendSnapshot(),this.setStatus("connected"))},r.onmessage=e=>{let t;if(this.socket===r){try{t=JSON.parse(e.data)}catch{r.close(4e3,"Invalid debugger message");return}if(rP(t))if("control"===t.type){let e=function(e){if(!rP(e)||"string"!=typeof e.commandId)return null;if("render_page"===e.type&&"string"==typeof e.url)return{commandId:e.commandId,type:e.type,url:e.url};if("render_widget"===e.type&&"string"==typeof e.widgetId&&rP(e.structuredContent))return{commandId:e.commandId,type:e.type,widgetId:e.widgetId,structuredContent:e.structuredContent};if("set_viewport"===e.type&&rX(e.width)&&rX(e.height))return{commandId:e.commandId,type:e.type,width:e.width,height:e.height};if("submit_chat_query"===e.type&&"string"==typeof e.query&&e.query.trim())return{commandId:e.commandId,type:e.type,query:e.query.trim()};if("cancel_chat_query"===e.type)return{commandId:e.commandId,type:e.type};if("execute_sandbox_tool_call"===e.type){var t;let r="object"==typeof(t=e.toolCall)&&(null==t?void 0:t.tool_call)?t:void 0;return r?{commandId:e.commandId,toolCall:r,type:e.type}:null}if("get_computed_style"===e.type&&"string"==typeof e.uid)return void 0===e.properties||Array.isArray(e.properties)&&e.properties.every(e=>"string"==typeof e)?{commandId:e.commandId,type:e.type,uid:e.uid,properties:e.properties}:null;if("take_snapshot"===e.type&&("current"===e.target||"page"===e.target||"widget"===e.target))return{commandId:e.commandId,type:e.type,target:e.target};if("get_element_rect"===e.type&&"string"==typeof e.uid)return{commandId:e.commandId,type:e.type,uid:e.uid};if("take_screenshot"===e.type){let t=e.format??"png",r=e.quality;return void 0!==e.uid&&"string"!=typeof e.uid||"png"!==t&&"jpeg"!==t&&"webp"!==t||void 0!==r&&("number"!=typeof r||!Number.isFinite(r)||r<0||r>100)?null:{commandId:e.commandId,type:e.type,format:t,uid:"string"==typeof e.uid?e.uid:void 0,quality:"number"==typeof r?r:void 0}}return"scroll_to"===e.type?(void 0===e.uid||"string"==typeof e.uid&&e.uid.trim())&&(void 0===e.x||rY(e.x))&&(void 0===e.y||rY(e.y))?{commandId:e.commandId,type:e.type,uid:"string"==typeof e.uid?e.uid:void 0,x:"number"==typeof e.x?e.x:void 0,y:"number"==typeof e.y?e.y:void 0}:null:null}(t.data);e&&this.emit({type:"control",data:e})}else"sandbox"===t.type&&(this.sandboxSnapshot=t.data,this.emit({type:"sandbox",data:t.data}))}},r.onclose=t=>{if(this.socket!==r)return;this.socket=void 0,this.sandboxSnapshot=void 0,void 0!==e&&Date.now()-e>=3e4&&(this.retryIndex=0);let i=iP[this.retryIndex++];void 0===i||1008===t.code||1009===t.code?this.setStatus("disconnected"):(this.setStatus("reconnecting"),this.retryTimer=setTimeout(()=>this.connect(),i))}}send(e){var t;if(new TextEncoder().encode(e).byteLength>0xa00000)throw Error("本地调试消息超过 10MiB,无法发送");if((null==(t=this.socket)?void 0:t.readyState)!==WebSocket.OPEN)throw Error("本地调试服务未连接");if(this.socket.bufferedAmount>0xa00000)throw this.socket.close(4e3,"Debugger connection is too slow"),Error("本地调试服务发送缓冲区已满");this.socket.send(e)}async reportResult(e){this.send(JSON.stringify({type:"control_result",data:e}))}async clearSandboxLogs(){this.send(JSON.stringify({type:"clear_sandbox_logs"}))}publishSnapshot(e,t){this.snapshot={payload:e,runtime:t},this.sendSnapshot()}sendSnapshot(){var e;if(!this.snapshot||(null==(e=this.socket)?void 0:e.readyState)!==WebSocket.OPEN)return;let{payload:t,runtime:r}=this.snapshot;try{let e=iS(t,{includeRuntimeRoot:r!==this.sentRuntime});this.send(i_({type:"snapshot",data:e})),this.sentRuntime=r,this.snapshotErrorReported=!1}catch(e){this.snapshotErrorReported||console.warn("调试快照上传失败,控制连接保持可用:",e),this.snapshotErrorReported=!0}}}var iO=r(64865),iD=r(11855);function iU(e){return"string"==typeof e&&/^[\da-f]{8}-(?:[\da-f]{4}-){3}[\da-f]{12}$/i.test(e)}function iq(e){return`${e.uuid.toLowerCase()}-${e.major}-${e.minor}`}function i$(e){if("boolean"!=typeof e.rangingAvailable||"boolean"!=typeof e.locationAuthorized||!Array.isArray(e.beacons))throw Error("Beacon 测距、系统定位授权需为布尔值,广播需为数组");let t=new Set;for(let r of e.beacons){if(!r||!iU(r.uuid)||![r.major,r.minor].every(e=>Number.isInteger(e)&&e>=0&&e<=65535)||![0,1,2,3].includes(r.proximity)||!Number.isFinite(r.accuracy)||r.accuracy<-1||!Number.isInteger(r.rssi)||r.rssi<-127||r.rssi>20)throw Error("Beacon 需包含完整 UUID、0–65535 major/minor、0–3 proximity、accuracy 米和整数 rssi dBm");let e=iq(r);if(t.has(e))throw Error("Beacon UUID/major/minor 组合不能重复");t.add(e)}}function iB(e){return Object.freeze({...e,beacons:Object.freeze(e.beacons.map(e=>Object.freeze({...e})))})}let iF={rangingAvailable:!0,locationAuthorized:!0,beacons:[{uuid:"00000000-0000-0000-0000-000000000000",major:1,minor:2,proximity:2,accuracy:1.2,rssi:-55},{uuid:"99999999-9999-9999-9999-999999999999",major:3,minor:4,proximity:3,accuracy:5,rssi:-75}]};function iz(e){let t=e.trim().replace(/^\{|\}$/g,"").replaceAll("-","").toLowerCase();if(/^[\da-f]+$/.test(t)){if(4===t.length||8===t.length)return`${t.padStart(8,"0")}-0000-1000-8000-00805f9b34fb`;if(32===t.length)return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}}function iW(e){return"string"==typeof e&&/^(?:[A-Za-z\d+/]{4})*(?:[A-Za-z\d+/]{2}==|[A-Za-z\d+/]{3}=)?$/.test(e)}function iH(e){if("boolean"!=typeof e.available||"boolean"!=typeof e.enabled||"boolean"!=typeof e.authorized||!Array.isArray(e.devices))throw Error("蓝牙硬件、开关和授权需为布尔值,设备列表需为数组");let t=new Set;for(let r of e.devices){if(!r||"string"!=typeof r.deviceId||!r.deviceId.trim()||"string"!=typeof r.name||void 0!==r.localName&&"string"!=typeof r.localName||!Number.isInteger(r.RSSI)||r.RSSI<-127||r.RSSI>20||"boolean"!=typeof r.connectable||!Array.isArray(r.advertisServiceUUIDs)||r.advertisServiceUUIDs.some(e=>"string"!=typeof e||!iz(e))||void 0!==r.advertisData&&!iW(r.advertisData)||void 0!==r.serviceData&&(!r.serviceData||"object"!=typeof r.serviceData||Array.isArray(r.serviceData)||Object.entries(r.serviceData).some(e=>{let[t,r]=e;return!iz(t)||!iW(r)})))throw Error("设备需包含 deviceId、name、RSSI、connectable 和服务 UUID 数组;广播数据使用 Base64");if(t.has(r.deviceId.toLowerCase()))throw Error("蓝牙 deviceId 不能重复");if(t.add(r.deviceId.toLowerCase()),void 0!==r.paired&&"boolean"!=typeof r.paired||void 0!==r.pin&&!iW(r.pin)||void 0!==r.connectionDelayMs&&(!Number.isInteger(r.connectionDelayMs)||r.connectionDelayMs<0||r.connectionDelayMs>6e4)||void 0!==r.maxMTU&&(!Number.isInteger(r.maxMTU)||r.maxMTU<23||r.maxMTU>517))throw Error("配对状态需为布尔值,PIN 使用 Base64;连接延迟为 0–60000 ms、MTU 为 23–517");if(void 0!==r.services){if(!Array.isArray(r.services))throw Error("BLE 服务需为数组");let e=new Set;for(let t of r.services){let r="string"==typeof(null==t?void 0:t.uuid)?iz(t.uuid):void 0;if(!r||e.has(r)||"boolean"!=typeof t.isPrimary||!Array.isArray(t.characteristics))throw Error("BLE 服务需包含唯一 UUID、isPrimary 和特征数组");e.add(r);let i=new Set;for(let e of t.characteristics){let t="string"==typeof(null==e?void 0:e.uuid)?iz(e.uuid):void 0;if(!t||i.has(t)||!iW(e.value)||!e.properties||["read","write","writeNoResponse","notify","indicate"].some(t=>"boolean"!=typeof e.properties[t]))throw Error("BLE 特征需包含唯一 UUID、Base64 value 和 read/write/writeNoResponse/notify/indicate 布尔属性");i.add(t)}}}}}function iV(e){return Object.freeze({...e,devices:Object.freeze(e.devices.map(e=>Object.freeze({...e,advertisServiceUUIDs:Object.freeze([...e.advertisServiceUUIDs]),...e.serviceData?{serviceData:Object.freeze({...e.serviceData})}:{},...e.services?{services:Object.freeze(e.services.map(e=>Object.freeze({...e,characteristics:Object.freeze(e.characteristics.map(e=>Object.freeze({...e,properties:Object.freeze({...e.properties})})))})))}:{}})))})}let iG={available:!0,enabled:!0,authorized:!0,devices:[{deviceId:"12:34:56:78:9A:BC",name:"Virtual BLE Sensor",localName:"Virtual Sensor",RSSI:-55,connectable:!0,advertisData:"AQIDBA==",advertisServiceUUIDs:["180F"],serviceData:{"180F":"ZA=="},paired:!1,pin:"MDAwMDAw",maxMTU:247,services:[{uuid:"FFF0",isPrimary:!0,characteristics:[{uuid:"FFF1",properties:{read:!0,write:!0,writeNoResponse:!0,notify:!0,indicate:!0},value:"ZA=="}]}]},{deviceId:"12:34:56:78:9A:BD",name:"Virtual Heart Rate",RSSI:-70,connectable:!0,advertisServiceUUIDs:["180D"]}]},iJ=["wifi","2g","3g","4g","5g","unknown","none"],iK=["request","upload","download","socket"],iZ={enabled:!1,request:"",upload:"",download:"",socket:""};function iX(e,t){try{var r,i;let n=null==(r=e.trim().match(/^[a-z][\da-z+.-]*:\/\/([^/?#]*)/i))?void 0:r[1];if(!n||/[\s\\]/.test(n))return;let a=new URL(e.trim());if(a.protocol!==("socket"===t?"wss:":"https:")||a.hostname.includes("*"))return;let s=null==(i=n.slice(n.lastIndexOf("@")+1).match(/:(\d+)$/))?void 0:i[1];if(void 0!==s&&(1>Number(s)||Number(s)>65535))return;return`${a.protocol}//${a.hostname}${void 0===s?"":`:${Number(s)}`}`}catch{return}}function iY(e){return e.split(/[\s,]+/).filter(Boolean)}function iQ(e){return Object.freeze({...e,...e.domainPolicy?{domainPolicy:Object.freeze({...e.domainPolicy})}:{}})}let i0={networkType:"wifi",signalStrength:-55,hasSystemProxy:!1};function i1(e){if(!iJ.includes(e.networkType)||!Number.isInteger(e.signalStrength)||e.signalStrength<-126||e.signalStrength>-1||"boolean"!=typeof e.hasSystemProxy)throw Error("网络制式必须为预设值,Wi-Fi 信号为 -126 至 -1 的整数 dBm,代理状态为布尔值");let t=e.domainPolicy;if(void 0!==t&&(!t||"boolean"!=typeof t.enabled||iK.some(e=>"string"!=typeof t[e]||t.enabled&&iY(t[e]).some(t=>!iX(t,e)))))throw Error("域名白名单使用 HTTPS 地址,Socket 使用 WSS 地址;不支持通配符")}let i2=["not determined","full","denied","restricted"],i3=[...i2,"limited","add only"],i4=[...i2,"read only","write only"],i5=[...i2,"provisional"],i6=["not determined","authorized","denied"],i8=[...i2,"partial"],i9=["not determined","denied","restricted","foreground precise","foreground approximate","background precise","background approximate"];function i7(e){if(void 0!==e.healthData){let t=e.healthData;if("boolean"!=typeof t.requestCompleted||!t.readStatus||"object"!=typeof t.readStatus||Array.isArray(t.readStatus)||Object.entries(t.readStatus).some(e=>{let[t,r]=e;return!t.trim()||![-1,0,1,2].includes(r)}))throw Error("健康数据配置需包含流程结果和读取状态(-1、0、1、2)")}if(void 0!==e.theme&&"light"!==e.theme&&"dark"!==e.theme||"boolean"!=typeof e.locationEnabled||"boolean"!=typeof e.locationReducedAccuracy||void 0!==e.bluetoothAuthorization&&!i8.includes(e.bluetoothAuthorization)||void 0!==e.locationAuthorization&&!i9.includes(e.locationAuthorization)||void 0!==e.contacts&&!i2.includes(e.contacts)||!i2.includes(e.camera)||!i2.includes(e.microphone)||!i3.includes(e.album)||!i4.includes(e.phoneCalendar)||!i5.includes(e.notification)||!i6.includes(e.notificationAlert)||!i6.includes(e.notificationBadge)||!i6.includes(e.notificationSound))throw Error("系统开关需为布尔值,授权状态必须为对应权限的预设值")}function ne(e){return Object.freeze({...e,...e.healthData?{healthData:Object.freeze({...e.healthData,readStatus:Object.freeze({...e.healthData.readStatus})})}:{}})}let nt={locationEnabled:!0,locationReducedAccuracy:!1,contacts:"not determined",camera:"not determined",microphone:"not determined",album:"not determined",phoneCalendar:"not determined",notification:"not determined",notificationAlert:"not determined",notificationBadge:"not determined",notificationSound:"not determined"},nr=Object.freeze({accelerometer:Object.freeze({x:0,y:0,z:9.80665}),gyroscope:Object.freeze({x:0,y:0,z:0})}),ni=["system","storage","battery","network","location","bluetooth","sensors","screen","audio","accessibility","calendar","communication"],nn="doubao-debugger-open-hardware-settings";function na(e){window.dispatchEvent(new CustomEvent(nn,{detail:e}))}function ns(e){var t;return JSON.stringify([e.ssid,(null==(t=e.bssid)?void 0:t.toLowerCase())??""])}function no(e){if("boolean"!=typeof e.available||"boolean"!=typeof e.enabled||"string"!=typeof e.connectedNetworkKey||!Array.isArray(e.networks))throw Error("Wi-Fi 开关、连接标识和网络列表格式错误");let t=new Set;for(let r of e.networks){if(!r||"string"!=typeof r.ssid||!r.ssid.trim()||"string"!=typeof r.password||void 0!==r.bssid&&("string"!=typeof r.bssid||!/^(?:[\da-f]{2}:){5}[\da-f]{2}$/i.test(r.bssid))||void 0!==r.secure&&"boolean"!=typeof r.secure||void 0!==r.signalStrength&&(!Number.isFinite(r.signalStrength)||r.signalStrength<0||r.signalStrength>100)||void 0!==r.frequency&&(!Number.isInteger(r.frequency)||r.frequency<=0))throw Error("网络需包含 ssid、password;BSSID 使用 MAC 地址,信号强度为 0–100,频率为正整数 MHz");let e=ns(r);if(t.has(e))throw Error("SSID 和 BSSID 组合不能重复");t.add(e)}if(e.connectedNetworkKey&&!t.has(e.connectedNetworkKey))throw Error("当前连接必须来自虚拟网络列表")}function nl(e){return Object.freeze({...e,networks:Object.freeze(e.networks.map(e=>Object.freeze({...e})))})}function nd(e){if("boolean"!=typeof e.available||![e.alpha,e.beta,e.gamma].every(Number.isFinite))throw Error("设备方向必须为有限弧度数值,可用性必须为布尔值")}let nu=["high","medium","low","unreliable","no-contact"];function nc(e){if("boolean"!=typeof e.available)throw Error("传感器可用性必须为布尔值")}function np(e){if(!Number.isInteger(e.level)||e.level<0||e.level>100||"boolean"!=typeof e.isCharging||"boolean"!=typeof e.isLowPowerModeEnabled)throw Error("电量必须为 0 至 100 的整数,充电和省电模式必须为布尔值")}function nh(e){if("boolean"!=typeof e.available||!Number.isFinite(e.direction)||e.direction<0||e.direction>360||!nu.includes(e.accuracy))throw Error("罗盘方向必须为 0 至 360 度,精度必须为预设值")}function nm(e,t,r){try{let t=localStorage.getItem(e);if(t){let e=JSON.parse(t);return r(e),Object.freeze({...e})}}catch{}return Object.freeze({...t})}let ng="doubao-debugger-virtual-battery",nf="doubao-debugger-virtual-accelerometer",nv="doubao-debugger-virtual-gyroscope",ny="doubao-debugger-virtual-compass",nb="doubao-debugger-virtual-device-motion",nw="doubao-debugger-virtual-wifi",n_="doubao-debugger-virtual-network",nS="doubao-debugger-virtual-bluetooth",nx="doubao-debugger-virtual-beacon",nI="doubao-debugger-virtual-system",nk="doubao-debugger-virtual-screen",nC="doubao-debugger-virtual-keyboard",nE="doubao-debugger-virtual-accessibility",nN="doubao-debugger-virtual-communication",nT={phoneAvailable:!0,phoneOpenSucceeds:!0,smsAvailable:!0,smsOpenSucceeds:!0,smsSendSucceeds:!0};function nA(e){if(Object.keys(nT).some(t=>"boolean"!=typeof e[t]))throw Error("电话和短信能力、打开结果及发送结果必须为布尔值")}let nM={available:!0,androidEnabled:!1,touchExplorationEnabled:!1,voiceOverRunning:!1,switchControlRunning:!1};function nR(e){if(Object.keys(nM).some(t=>"boolean"!=typeof e[t]))throw Error("无障碍服务与辅助功能开关必须为布尔值")}function nj(e){if(!Number.isFinite(e.height)||e.height<0||e.height>1e3)throw Error("键盘高度必须为 0 至 1000 的有限数值")}function nP(e){if(!Number.isFinite(e.brightness)||e.brightness<0||e.brightness>1||"boolean"!=typeof e.recording)throw Error("亮度必须为 0 至 1 的有限数值,录屏状态需为布尔值")}let nL=new class{network=iQ(nm(n_,i0,i1));effectiveBluetooth;effectiveBeacon;communication=nm(nN,nT,nA);accessibility=nm(nE,nM,nR);keyboard=nm(nC,{height:300},nj);screen=nm(nk,{brightness:1,recording:!1},nP);system=ne(nm(nI,nt,i7));beacon=iB(nm(nx,iF,i$));bluetooth=iV(nm(nS,iG,iH));battery=nm(ng,{isCharging:!1,isLowPowerModeEnabled:!1,level:100},np);accelerometer=nm(nf,{available:!0},nc);gyroscope=nm(nv,{available:!0},nc);motionSample=nr;compass=nm(ny,{available:!0,direction:0,accuracy:"high"},nh);listeners=new Map;wifi=nl(nm(nw,{available:!0,enabled:!0,connectedNetworkKey:"",networks:[{ssid:"wifi-name",bssid:"10:20:30:40:50:60",password:"wifi-password",secure:!0,signalStrength:88,frequency:2462},{ssid:"guest-wifi",bssid:"10:20:30:40:50:61",password:"",secure:!1,signalStrength:50,frequency:5180}]},no));deviceMotion=nm(nb,{available:!0,alpha:0,beta:0,gamma:0},nd);getBattery=()=>this.battery;getGyroscope=()=>({available:this.gyroscope.available,...this.motionSample.gyroscope});getAccelerometer=()=>({available:this.accelerometer.available,...this.motionSample.accelerometer});getCompass=()=>this.compass;getDeviceMotion=()=>this.deviceMotion;getWifi=()=>this.wifi;getNetwork=()=>this.network;getBluetooth=()=>{let e=this.system.bluetoothAuthorization;return void 0===e?this.bluetooth:this.effectiveBluetooth??=iV({...this.bluetooth,authorized:"full"===e})};getBeacon=()=>{let e=this.system.locationAuthorization;return void 0===e?this.beacon:this.effectiveBeacon??=iB({...this.beacon,locationAuthorized:e.startsWith("foreground ")||e.startsWith("background ")})};getSystem=()=>this.system;getScreen=()=>this.screen;getKeyboard=()=>this.keyboard;getAccessibility=()=>this.accessibility;getCommunication=()=>this.communication;setCommunication(e){nA(e),this.communication=Object.freeze({...e}),this.persist(nN,this.communication)}setNetwork(e){i1(e),this.network=iQ(e),this.persistAndNotify(n_,this.network,"network")}setAccessibility(e){nR(e),this.accessibility=Object.freeze({...e}),this.persist(nE,this.accessibility)}setKeyboard(e){nj(e),this.keyboard=Object.freeze({...e}),this.persistAndNotify(nC,this.keyboard,"keyboard")}setScreen(e){nP(e),this.screen=Object.freeze({...e}),this.persistAndNotify(nk,this.screen,"screen")}setSystem(e){i7(e);let t=this.system;this.system=ne(e);let r=t.bluetoothAuthorization!==e.bluetoothAuthorization,i=t.locationAuthorization!==e.locationAuthorization;r&&(this.effectiveBluetooth=void 0),i&&(this.effectiveBeacon=void 0),this.persist(nI,this.system),r&&this.notify("bluetooth"),i&&this.notify("beacon"),(i||t.locationEnabled!==e.locationEnabled||t.locationReducedAccuracy!==e.locationReducedAccuracy)&&this.notify("location"),t.theme!==e.theme&&this.notify("theme"),this.notify("system")}setBeacon(e){i$(e);let t=e.locationAuthorized!==this.getBeacon().locationAuthorized;t&&(this.system=Object.freeze({...this.system,locationAuthorization:void 0}),this.persist(nI,this.system)),this.effectiveBeacon=void 0,this.beacon=iB(e),this.persistAndNotify(nx,this.beacon,"beacon"),t&&this.notify("location")}setBluetooth(e){iH(e),e.authorized!==this.getBluetooth().authorized&&(this.system=Object.freeze({...this.system,bluetoothAuthorization:void 0}),this.persist(nI,this.system)),this.effectiveBluetooth=void 0,this.bluetooth=iV(e),this.persistAndNotify(nS,this.bluetooth,"bluetooth")}subscribe=(e,t)=>{let r=this.listeners.get(e)??new Set;return this.listeners.set(e,r),r.add(t),()=>r.delete(t)};setMotionSample(e){this.motionSample=Object.freeze({accelerometer:Object.freeze({...e.accelerometer}),gyroscope:Object.freeze({...e.gyroscope})})}setAccelerometer(e){nc(e),this.accelerometer=Object.freeze({available:e.available}),this.persist(nf,this.accelerometer)}setGyroscope(e){nc(e),this.gyroscope=Object.freeze({available:e.available}),this.persist(nv,this.gyroscope)}setCompass(e){nh(e),this.compass=Object.freeze({...e}),this.persist(ny,this.compass)}setDeviceMotion(e){nd(e),this.deviceMotion=Object.freeze({...e}),this.persist(nb,this.deviceMotion)}setWifi(e){no(e),this.wifi=nl(e),this.persistAndNotify(nw,this.wifi,"wifi")}setBattery(e){np(e),(e.level!==this.battery.level||e.isCharging!==this.battery.isCharging||e.isLowPowerModeEnabled!==this.battery.isLowPowerModeEnabled)&&(this.battery=Object.freeze({...e}),this.persistAndNotify(ng,this.battery,"battery"))}persistAndNotify(e,t,r){this.persist(e,t),this.notify(r)}notify(e){for(let t of this.listeners.get(e)??[])t()}persist(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch{}}},nO="network unavailable (simulator offline)";function nD(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;return"none"!==e.getNetwork().networkType}function nU(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;if(!nD(e))throw Error(nO)}function nq(e){return!/^(?:appletfile|data|blob):/i.test(e)}function n$(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nL,r=nD(t);return t.subscribe("network",()=>{let i=nD(t),n=r&&!i;r=i,n&&e()})}async function nB(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nL;nU(t);let r=new AbortController,i=n$(()=>r.abort(Error(nO)),t),n=()=>{},a=new Promise((e,t)=>{n=()=>t(r.signal.reason),r.signal.addEventListener("abort",n,{once:!0})});try{return await Promise.race([e(r.signal),a])}finally{i(),r.signal.removeEventListener("abort",n)}}function nF(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:nL,i=r.getNetwork().domainPolicy;if(!(null==i?void 0:i.enabled))return;let n=iX(e,t);if(!n||!iY(i[t]).some(e=>iX(e,t)===n)){if("upload"===t)throw new w("uploadFile:fail url not in domain list",121901);throw new w(`${t} domain is not in whitelist${n?"":" (HTTPS/WSS required)"}`,"download"===t?-1:110)}}function nz(e){return e instanceof Map?Array.from(e.entries(),e=>{let[t,r]=e;return[String(t),r]}):!e||"object"!=typeof e||Array.isArray(e)||e instanceof ArrayBuffer?void 0:Object.entries(e)}function nW(e){return e.map(e=>{let[t,r]=e;return`${encodeURIComponent(t)}=${encodeURIComponent(null===r?"null":r&&"object"==typeof r?JSON.stringify(r)??String(r):String(r))}`}).join("&")}function nH(e){let t=new Uint8Array(e),r="";for(let e=0;e<t.length;e+=32768)r+=String.fromCharCode(...t.subarray(e,e+32768));return btoa(r)}function nV(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"json";if("arraybuffer"===t)return e;let r=new TextDecoder().decode(e);if("string"===t||0===r.length)return r;try{return JSON.parse(r)}catch{return nH(e)}}function nG(e){let t={};return e.forEach((e,r)=>{t[r]=e}),t}function nJ(e){var t;let r;if("string"!=typeof e.method&&void 0!==e.method)throw new w("method must be a string",104);let i=(e.method??"GET").trim().toUpperCase();if(!["GET","POST","PUT","DELETE","HEAD","OPTIONS"].includes(i))throw new w(`Unsupported request method: ${i}`,104);if("string"!=typeof e.url||0===e.url.trim().length)throw new w("url must be a non-empty string",104);let n=e.url,a=((r=new Headers(e.header)).has("content-type")||r.set("content-type","application/json"),r);return{body:"GET"!==i&&"HEAD"!==i?function(e,t){if(null!=e){if("string"==typeof e||e instanceof ArrayBuffer)return e;if(t.includes("application/x-www-form-urlencoded")){let t=nz(e);if(t)return nW(t)}return t.includes("application/json")||"object"==typeof e?JSON.stringify(e):String(e)}}(e.data,(null==(t=a.get("content-type"))?void 0:t.toLowerCase())??""):void 0,headers:nG(a),method:i,url:"GET"===i?function(e,t){let r=nz(t);if(!(null==r?void 0:r.length))return e;let i=e.indexOf("#"),n=-1===i?"":e.slice(i),a=-1===i?e:e.slice(0,i),s=a.endsWith("?")||a.endsWith("&")?"":a.includes("?")?"&":"?";return`${a}${s}${nW(r)}${n}`}(n,e.data):n}}async function nK(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nJ(e);return nF(t.url,"request"),nB(async r=>{let i=await fetch(t.url,{signal:r,body:t.body,headers:t.headers,method:t.method}),n=nV(await i.arrayBuffer(),e.dataType);return{statusCode:i.status,header:nG(i.headers),data:n}})}let nZ="/__web_artifacts/base/manifest.json",nX="/app_developer";function nY(e){return!e.debugHidden}r(95600);let nQ={chat:"chat","image-upload":"images/upload","tool-report":"tool/report"};function n0(e){let t=rM(String(e??nX).trim(),{addProtocolToBareHost:!0,allowRootRelative:!0,defaultProtocol:n1}).replace(/\/+$/,"");if(t.startsWith("/"))return t;try{let e=new URL(t);if(""===e.pathname||"/"===e.pathname)return e.pathname="/app_developer",e.toString().replace(/\/+$/,"")}catch{}return t}function n1(e){return/^(localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|\[::1\])(?::|\/|$)/i.test(e)?"http":"https"}function n2(e){var t;let r="function"==typeof(null==(t=globalThis.crypto)?void 0:t.randomUUID)?globalThis.crypto.randomUUID().replace(/-/g,""):Math.random().toString(36).slice(2);return`${e}_${Date.now().toString(36)}${r.slice(0,10)}`}function n3(e,t){return`${n0(e)}/api/simulator/${nQ[t]}`}function n4(e){if(e.type&&!e.type.startsWith("image/"))throw Error("仅支持图片文件");if(e.size>0xa00000)throw Error("图片不能超过 10 MiB")}var n5=r(75585);let n6=["ack","message_start","text_delta","tool_call","tool_status","card_delta","content_block","stream_error","message_finish","reply_finish","answer_finish","trace_event","heartbeat"];async function n8(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=e.getReader(),n=new TextDecoder,a={...r,fallbackSeq:0},s=(0,n5.C)({onEvent:e=>{let r=function(e,t){var r,i,n;let a,s,o,l,d,u,c=void 0===(l=r3(r=e.data))&&r.trim()?r:l,p=rP(c)?{...c,event:c.event||e.event}:{event:e.event||"message",data:c},{eventType:h,payload:m}=function(e){var t;for(let t of n6){let r=e[t];if(rP(r))return{eventType:t,payload:r};if("content_block"===t&&Array.isArray(r))return{eventType:t,payload:{content_block:r}}}return{eventType:"string"==typeof(t=e.event)&&t?t.toLowerCase():"message",payload:e}}(p),g=rP(m)?m:{},f="number"==typeof p.sequence&&Number.isFinite(p.sequence)?p.sequence:t.fallbackSeq+=1,v=e.id||("string"==typeof p.id?p.id:"")||`evt_${f.toString().padStart(4,"0")}`,y=function(e,t,r){let i=("string"==typeof e.request_id?e.request_id:"")||("ack"===r&&"string"==typeof t.request_id?t.request_id:"");if("ack"===r&&!i)throw Error("Invalid simulator SSE ACK: missing request_id");return i||("string"==typeof e.id?e.id:"")}(p,g,h),b=("string"==typeof p.reply_message_id?p.reply_message_id:"")||("string"==typeof g.message_id?g.message_id:"")||t.replyMessageId;return{event_id:v,event_type:h,seq:f,request_id:y,query_message_id:("string"==typeof p.query_message_id?p.query_message_id:"")||("string"==typeof g.query_message_id?g.query_message_id:""),reply_message_id:b,created_at_ms:"number"==typeof p.timestamp_ms&&Number.isFinite(p.timestamp_ms)?p.timestamp_ms:Date.now(),received_at_ms:Date.now(),trace:(d=rP(p.trace)?p.trace:{},{trace_id:"string"==typeof(u=t.trace??{}).trace_id?u.trace_id:"string"==typeof d.trace_id?d.trace_id:n2("trace"),span_id:"string"==typeof d.span_id?d.span_id:n2("span_sse"),parent_span_id:"string"==typeof d.parent_span_id?d.parent_span_id:"string"==typeof u.span_id?u.span_id:void 0,component:"string"==typeof d.component?d.component:"app_developer_simulator",stage:"string"==typeof d.stage?d.stage:h,sampled:"boolean"==typeof d.sampled?d.sampled:"boolean"!=typeof u.sampled||u.sampled,baggage:{...rP(u.baggage)?u.baggage:{},...rP(d.baggage)?d.baggage:{}}}),payload:(i=g,0===(o=Array.isArray(s=rP(a=null==(n=t.trace)?void 0:n.baggage)?a.log_ids:void 0)?s.filter(e=>"string"==typeof e&&e.trim().length>0):"string"==typeof s&&s.trim()?[s]:[]).length||void 0!==i.log_ids?i:{...i,log_ids:o})}}(e,a);r.reply_message_id&&(a.replyMessageId=r.reply_message_id),t(r)}});for(;;){let{done:e,value:t}=await i.read();if(t&&s.feed(n.decode(t,{stream:!e})),e)break}let o=n.decode();o&&s.feed(o),s.feed("\n\n")}let n9="x-tt-logid";class n7 extends Error{responseDebug;constructor(e,t){super(e),this.responseDebug=t,this.name="SimulatorHttpError"}}function ae(e){return e.headers.get(n9)}function at(e){let t={},r=ae(e);return r&&(t[n9]=r),t}function ar(e){return rP(e.trace)?e.trace:{}}async function ai(e,t){let r=ae(t),i=at(t),n=await t.text().catch(()=>""),a={status:t.status,status_text:t.statusText,response_headers:Object.keys(i).length>0?i:void 0,log_ids:r?[r]:void 0,response_text:n};return new n7(`${e}: ${t.status} ${t.statusText}`,a)}function an(e){return e instanceof n7?e.responseDebug:void 0}function aa(e,t,r){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},n=arguments.length>4?arguments[4]:void 0,a=ar(e),s=Date.now();return{event_id:n2("evt_client_debug"),event_type:"debug",seq:0,request_id:"string"==typeof e.idempotency_key?e.idempotency_key:"client_debug",created_at_ms:s,received_at_ms:s,trace:{trace_id:"string"==typeof a.trace_id?a.trace_id:n2("trace"),component:"string"==typeof a.component?a.component:"simulator_web_tester",stage:"string"==typeof a.stage?a.stage:"query",sampled:"boolean"!=typeof a.sampled||a.sampled,baggage:n??(rP(a.baggage)?a.baggage:{})},payload:{event:t,category:"api",elapsed_ms:Date.now()-r,...i}}}async function as(e){var t;let{endpoint:r,fetcher:i,file:n,signal:a}=e;n4(n);let s=new FormData;s.append("image",n);let o=await (i??fetch)(n3(r,"image-upload"),{method:"POST",headers:{Accept:"application/json"},body:s,signal:a});if(!o.ok)throw await ai("Simulator image upload failed",o);let l=await o.json();if(0!==l.code)throw new n7(l.message||`Simulator image upload failed with code ${l.code}`,{response_body:l,log_ids:l.log_id?[l.log_id]:void 0});let d=null==(t=l.data)?void 0:t.image;if(!(null==d?void 0:d.resource_uri))throw new n7("Simulator image upload response is missing image.resource_uri",{response_body:l,log_ids:l.log_id?[l.log_id]:void 0});return d}async function ao(e){let t,{endpoint:r,fetcher:i,onEvent:n,onSubmitted:a,request:s,signal:o}=e,l=Date.now(),d=n3(r,"chat");n(aa(s,"simulator_chat_fetch_started",l,{endpoint:"chat",phase:"request",request:s,request_json:r5(s),url:d}));let u=setTimeout(()=>{n(aa(s,"simulator_chat_fetch_waiting_for_headers",l,{endpoint:"chat",phase:"wait",url:d,wait_ms:5e3}))},5e3);try{let e=(i??fetch)(d,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(s),signal:o});null==a||a(),t=await e}catch(e){throw clearTimeout(u),n(aa(s,"simulator_chat_fetch_failed",l,{endpoint:"chat",phase:"error",url:d,error:r6(e)})),e}clearTimeout(u);let c=ae(t),p=at(t),h=ar(s),m={...rP(h.baggage)?h.baggage:{}};if(c&&(m[n9]=c,m.log_ids=[c]),n(aa(s,"simulator_chat_headers_received",l,{event:"simulator_chat_response_meta",endpoint:"chat",phase:"response",status:t.status,status_text:t.statusText,log_ids:c?[c]:void 0,response_headers:Object.keys(p).length>0?p:void 0},m)),!t.ok){let e=await ai("Simulator query failed",t);throw n(aa(s,"simulator_chat_fetch_failed",l,{endpoint:"chat",phase:"error",error:e.message,...e.responseDebug},m)),e}if(!t.body)throw Error("Simulator query response has no SSE body");let g=0,f=!1,v=setTimeout(()=>{f||n(aa(s,"simulator_chat_sse_waiting_for_first_event",l,{endpoint:"chat",wait_ms:5e3},m))},5e3);try{await n8(t.body,e=>{g+=1,f||(f=!0,clearTimeout(v)),n(e)},{trace:{...h,baggage:m}})}catch(e){throw clearTimeout(v),n(aa(s,"simulator_chat_sse_read_failed",l,{endpoint:"chat",phase:"error",event_count:g,error:r6(e)},m)),e}clearTimeout(v)}async function al(e){let{endpoint:t,fetcher:r,result:i,signal:n}=e,a=await (r??fetch)(n3(t,"tool-report"),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(i),signal:n});if(!a.ok)throw await ai("Simulator tool result failed",a);let s=await ad(a),o=ae(a);return{...s,response_headers:o?{...rP(s.response_headers)?s.response_headers:{},[n9]:o}:s.response_headers,log_ids:o?[o]:s.log_ids}}async function ad(e){let t=await e.text().catch(()=>"");if(!t.trim())return{};try{let e=JSON.parse(t);return rP(e)?e:{response_body:e}}catch{return{response_text:t}}}let au={label:"Request",tone:"request"},ac={label:"Response",tone:"response"},ap={simulator_query_prepare_started:{debugOnly:!0,title:"Query Prepare Started"},simulator_query_mcp_resolved:{debugOnly:!0,title:"MCP Ready"},simulator_query_aborted:{title:"Query Aborted"},simulator_query_failed:{title:"Query Failed"},simulator_query_cancel_requested:{title:"Query Cancel Requested"},simulator_chat_fetch_started:{badge:au,title:"Chat"},simulator_chat_fetch_waiting_for_headers:{title:"Chat Waiting"},simulator_chat_response_meta:{badge:ac,title:"Chat"},simulator_chat_fetch_failed:{badge:ac,title:"Chat Failed"},simulator_chat_sse_waiting_for_first_event:{title:"Chat Waiting"},simulator_chat_sse_read_failed:{title:"Chat Stream Failed"},simulator_query_stream_returned:{title:"Chat Complete"},local_mcp_tools_load_started:{badge:au,debugOnly:!0,title:"MCP Load"},local_mcp_tools_loaded:{badge:ac,debugOnly:!0,title:"MCP Load"},local_mcp_tools_load_failed:{badge:ac,title:"MCP Load Failed"},local_mcp_missing:{title:"MCP Missing"},local_mcp_call_started:{badge:au,title:e=>`MCP Tool${e}`},local_mcp_call_succeeded:{badge:ac,title:e=>`MCP Tool${e}`},local_mcp_call_failed:{badge:ac,title:e=>`MCP Tool Failed${e}`},tool_result_report_started:{badge:au,title:e=>`Report Tool Result${e}`},tool_result_report_response_received:{badge:ac,title:e=>`Report Tool Result${e}`},tool_result_report_failed:{badge:ac,title:e=>`Report Tool Result Failed${e}`},tool_result_ack:{title:"Report ACK"},tool_result_submit_skipped:{title:e=>`Report Tool Result Skipped${e}`},tool_result_submit_failed:{badge:ac,title:e=>`Report Tool Result Failed${e}`},tool_executor_missing:{title:e=>`Tool Executor Missing${e}`},tool_call_ignored:{title:e=>`Tool Call Ignored${e}`},tool_call_event_skipped:{title:e=>`Tool Call Skipped${e}`},tool_call_request_id_mismatch:{title:e=>`Tool Call Request Mismatch${e}`},tool_call_server_id_fallback:{title:e=>`Tool Call Server Fallback${e}`},simulator_card_rendered:{title:"Card Rendered"},simulator_card_render_skipped:{title:"Card Render Skipped"},simulator_card_render_failed:{title:"Card Render Failed"},simulator_card_runtime_error:{title:"Card Render Failed"},simulator_manifest_load_started:{badge:au,debugOnly:!0,title:"Manifest Load"},simulator_manifest_loaded:{badge:ac,debugOnly:!0,title:"Manifest Load"},simulator_manifest_load_failed:{badge:ac,title:"Manifest Load Failed"},simulator_manifest_fetch_started:{badge:au,debugOnly:!0,title:"Manifest Fetch"},simulator_manifest_fetch_succeeded:{badge:ac,debugOnly:!0,title:"Manifest Fetch"},simulator_manifest_fetch_failed:{badge:ac,title:"Manifest Fetch Failed"},simulator_manifest_missing:{title:"Manifest Missing"},simulator_skill_load_started:{badge:au,debugOnly:!0,title:"Skill Load"},simulator_skill_loaded:{badge:ac,debugOnly:!0,title:"Skill Load"},simulator_skill_empty:{badge:ac,debugOnly:!0,title:"Skill Empty"},simulator_skill_load_failed:{badge:ac,title:"Skill Load Failed"},simulator_skill_fetch_started:{badge:au,debugOnly:!0,title:"Skill Fetch"},simulator_skill_fetch_succeeded:{badge:ac,debugOnly:!0,title:"Skill Fetch"},simulator_skill_fetch_failed:{badge:ac,title:"Skill Fetch Failed"},simulator_skill_missing:{title:"Skill Missing"},simulator_resources_check_started:{debugOnly:!0,title:"Resource Check Started"},simulator_resources_check_completed:{debugOnly:!0,title:"Resource Check Completed"},simulator_resource_reload_completed:{title:"Resource Reloaded"}};function ah(e){if(!rP(e))return;let t=am(e);return{category:t.category,debugOnly:t.debugOnly,detail:t.detail,leftBadges:t.transportBadge?[t.transportBadge]:void 0,phase:t.phase,title:t.title}}function am(e){var t,r;let i=e.event||"",n=ap[i],a=e.detail??e.data??e,s=e.title?r9(e.title):function(e,t){var r;let i=null==(r=ap[e])?void 0:r.title;if("function"==typeof i){let e;return i((e=t.tool_name||t.tool_call_id)?`: ${e}`:"")}return i||(e?r9(e):"Agent Trace Event")}(i,e),o=e.category?r8(e.category):(t=i).startsWith("local_mcp_")?"mcp":t.startsWith("tool_result_report_")||"tool_result_ack"===t?"api":t.startsWith("tool_result_")||t.startsWith("tool_call_")||"tool_executor_missing"===t?"agent":t.startsWith("simulator_card_")?"card":t.startsWith("simulator_manifest_")||t.startsWith("simulator_skill_")||t.startsWith("simulator_resource_")||t.startsWith("simulator_resources_")?"resource":t.startsWith("simulator_chat_")?"api":t.startsWith("simulator_query_")?"agent":"runtime",l=e.phase||("local_mcp_missing"===(r=i)?"error":/(started|starting)$/.test(r)?"request":/(completed|loaded|resolved|received|returned|succeeded|rendered)$/.test(r)?"response":/(failed|error|aborted|rejected)$/.test(r)?"error":/(empty|skipped|ignored|mismatch|fallback|cancel_requested)$/.test(r)?"status":"tool_result_ack"===r?"ack":"event");return{category:o,debugOnly:(null==n?void 0:n.debugOnly)===!0,detail:a,eventName:i,phase:l,title:s,transportBadge:null==n?void 0:n.badge}}function ag(e){return e.blocks.some(e=>"card"===e.type&&"permission_apply"===e.card.card_type)}function af(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{messages:r,streamStatus:i}=e.getState().simulator,n=function(e,t){let r=t?e.findIndex(e=>e.messageId===t):e.findLastIndex(ag);if(-1===r)return;let i=e[r];if(ag(i))for(let t=r-1;t>=0;t--){let r=e[t],n="user"===r.role?r.blocks.filter(e=>"image"===e.type).map(e=>e.image):[];if("user"===r.role&&(r.text.trim()||n.length>0))return{followUpContent:r.followUpContent,images:n.length>0?n:void 0,messageIds:[r.messageId,i.messageId],query:r.text.trim()}}}(r,t.grantingMessageId);if(!n)return{status:"not_found"};if("streaming"===i)return{status:"streaming"};e.removeSimulatorMessages(n.messageIds);let a=t.noLogin?{noLogin:!0}:{};return{completion:n.followUpContent?e.sendSimulatorFollowUpMessage(n.followUpContent,a):e.sendSimulatorQuery(n.query,{images:n.images,...a}),status:"started",target:n}}function av(e){if(!rP(e))return;let t="string"==typeof e.grantingName?e.grantingName:"";if(t){var r;let i;return{grantingName:t,permissionStatus:"string"==typeof e.permissionStatus?e.permissionStatus:"pending",priorityLevel:"number"==typeof e.priorityLevel?e.priorityLevel:0,relatedData:{...i=r4(r=e.relatedData)??(rP(r)?r:{}),bizLoginDescription:"string"==typeof i.bizLoginDescription?i.bizLoginDescription:"",bizPrivacyContent:"string"==typeof i.bizPrivacyContent?i.bizPrivacyContent:"",mobileMask:"string"==typeof i.mobileMask?i.mobileMask:"",privacyURL:"string"==typeof i.privacyURL?i.privacyURL:"",scopeDescription:"string"==typeof i.scopeDescription?i.scopeDescription:"",scopeName:"string"==typeof i.scopeName?i.scopeName:"",termsOfServiceURL:"string"==typeof i.termsOfServiceURL?i.termsOfServiceURL:""},required:!1!==e.required}}}function ay(e){let t=r4(e);if(!t)return;let r=Array.isArray(t.grantingList)?t.grantingList.map(av).filter(e=>!!e):[];if(0!==r.length)return{cardStatus:"string"==typeof t.cardStatus?t.cardStatus:"unexpired",doubaoAppletIcon:"string"==typeof t.doubaoAppletIcon?t.doubaoAppletIcon:"",doubaoAppletKey:"string"==typeof t.doubaoAppletKey?t.doubaoAppletKey:"",doubaoAppletName:"string"==typeof t.doubaoAppletName&&t.doubaoAppletName?t.doubaoAppletName:"应用插件",doubaoAppletVersion:"string"==typeof t.doubaoAppletVersion?t.doubaoAppletVersion:"",grantingList:r,raw:t}}function ab(e){var t;switch(null==(t=e.grantingList[0])?void 0:t.grantingName){case"permission":return"权限申请";case"privacy":return"隐私协议提示";default:return"登录授权"}}let aw="miniapp_packet_10066";function a_(e,t,r,i,n){let a=e.find(e=>e.messageId===t);return a?i&&!a.requestId||n&&!a.traceId?e.map(e=>e===a?{...e,requestId:e.requestId||i,traceId:e.traceId||n}:e):e:[...e,{messageId:t,requestId:i,traceId:n,role:"assistant",contentType:"mixed",text:"",blocks:[],status:"streaming",createdAtMs:r}]}function aS(e,t,r){return e.map(e=>e.messageId===t?r(e):e)}function ax(e,t,r,i){let n={blockId:t,type:"card",card:r};if("replace"===i){let i=r.card_id,a=e.map(e=>e.blockId===t||"card"===e.type&&i&&e.card.card_id===i?n:e);return a.some(e=>e===n)?a:[...e,n]}return e.some(e=>e.blockId===t)?e.map(e=>e.blockId===t?n:e):[...e,n]}function aI(e,t,r){let i=!1,n=!1,a=e.map(e=>{let a=!1,s=e.blocks.map(e=>{if("card"!==e.type||e.card.card_id!==t)return e;i=!0;let s=r(e.card);return s?(n=!0,a=!0,{...e,card:s}):e});return a?{...e,blocks:s}:e});return{messages:n?a:e,found:i,updated:n}}function ak(e){return"debug"===e.event_type?e.payload.data??e.payload:e.payload}function aC(e){let t=e.payload.tool_name||e.payload.tool_call_id,r=e.payload.status;switch(e.event_type){case"ack":return"Chat ACK";case"tool_call":return`Tool Call${t?`: ${t}`:""}`;case"tool_status":return`Tool Status${t?`: ${t}`:""}${r?` (${r})`:""}`;case"card_delta":return"Card Received";case"answer_finish":return"Answer Finished";case"message_finish":return"Message Finished";case"reply_finish":return"Reply Finished";case"stream_error":return"Stream Error";case"trace_event":return r9(e.payload.title||"Agent Trace");case"heartbeat":return"Heartbeat";default:return r9(e.event_type)}}function aE(e){let t=e.payload.category;if(t)return r8(t);switch(e.event_type){case"tool_call":case"tool_status":case"trace_event":default:return"agent";case"card_delta":return"card";case"debug":return"debug"}}function aN(e){switch(e){case"ack":return"accepted";case"message_start":return"message_start";case"text_delta":return"text_delta";case"tool_call":return"request";case"tool_status":return"response";case"card_delta":return"card_delta";case"message_finish":case"reply_finish":case"answer_finish":return"finish";case"stream_error":return"error";case"trace_event":return"trace";default:return e}}function aT(e){return"u">typeof DOMException&&e instanceof DOMException?"AbortError"===e.name:e instanceof Error&&"AbortError"===e.name}function aA(e,t){if(rP(e)&&"code"in e&&"message"in e)return e;let r=rP(e)&&rP(e.responseDebug)?e.responseDebug:void 0,i=r4(null==r?void 0:r.response_text),n="string"==typeof(null==i?void 0:i.message)&&i.message.trim()?i.message.trim():"string"==typeof(null==r?void 0:r.response_text)&&r.response_text.trim()?r.response_text.trim():"";return{code:("string"==typeof(null==i?void 0:i.code)||"number"==typeof(null==i?void 0:i.code)?String(i.code):void 0)??"INTERNAL_ERROR",message:n||r6(e),retryable:!1,stage:t,details:r?{response:r,response_body:i}:void 0}}function aM(e,t){if(e||t)return{...e,...t}}function aR(e,t){var r;let i=(null==(r=e.traceEvents.at(-1))?void 0:r.order)??e.traceEvents.length;return{...e,traceEvents:[...e.traceEvents,{...t,order:i+1}].slice(-200)}}function aj(e,t,r){var i;let n=function(e){let t=rP(e.card)?e.card:{},r=rP(t.state)?t.state:{},i=e.card_id,n=r.widget_id;if("update_state"!==e.op||"miniapp_history_refresh"!==t.card_type||"fixed_style"!==r.refresh_to||!i||!n)return;let a=r.url||r.schema,s=r.title,o=r.detailText;return{cardId:i,state:r,widgetData:{url:a,title:s,detailText:o},widgetId:n}}(t);if(n){let t=aI(e.messages,n.cardId,e=>{let t=e.state??{};if("fixed"!==t.lifecycle_state)return{...e,render_data:{viewData:n.widgetData},widget_id:n.widgetId,state:{...t,...n.state,lifecycle_state:"fixed"}}});return{state:{...e,messages:t.messages},cardRefresh:{cardId:n.cardId,status:t.updated?"updated":t.found?"already_fixed":"not_found"}}}let a=function(e){let t=e.card;if(!rP(t)||t.card_type!==aw)return;let r=e.card_id||t.card_id,i=r4(t.props_json),n=rP(null==i?void 0:i._meta)?i._meta:void 0,a=rP(t.render_data)?t.render_data:void 0,s=rP(null==a?void 0:a.ext)?a.ext:void 0;if(!r||!i||!n||!a||!s||!0!==n.skip_response_validate||"2"!==a.packet_type||"1"!==s._auth_request||"none"!==s.auth_require||"1"!==s.from_mcp||"1"!==s.is_mini_app||"string"!=typeof i.direct_return)return;let o=r4(i.direct_return);if((null==o?void 0:o.mcp_channel)==="flow_miniapp"&&Array.isArray(o.chunk_messages))for(let t of o.chunk_messages){if(!rP(t)||!0!==t.IsFinish||2!==t.MessageType||1005!==t.ContentType||"string"!=typeof t.Content)continue;let i=r4(t.Content);if((null==i?void 0:i.command_type)==="require_location"&&rP(i.require_location))return{cardId:r,appKey:s.app_key,sourceToolCallId:e.source_tool_call_id,toolName:s.tool_name}}}((null==r?void 0:r.payload)??{});if(a&&r)return{state:e,locationDirective:{...a,requestId:r.request_id,queryMessageId:r.query_message_id,replyMessageId:r.reply_message_id??e.activeReplyMessageId}};let s=(null==r?void 0:r.reply_message_id)??e.activeReplyMessageId,o=function(e){var t,r;let i,n=e.card;if(!rP(n))return{};let a=r4(n.props_json)??{},s=function(e){let t,r;if(e.card_type!==aw)return;let i=r4(e.props_json)||r4(e.render_data_json)||(rP(e.render_data)?r4(e.render_data.content_for_display):void 0)||{};return i.permission_data||((r=(Array.isArray(null==(t=rP(i.structuredContent)?i.structuredContent:void 0)?void 0:t.entity_list)?t.entity_list:[]).find(e=>rP(e)&&(Array.isArray(e.grantingList)||rP(e._meta)&&!0===e._meta.is_permission)))&&rP(r)?JSON.stringify(r):void 0)}(n),o=ay(s),l=rP(a.extra)?a.extra:{},d=Object.keys(a).length>0?(i=r4(a.widget_data))?{viewData:i}:rP(a.viewData)?{viewData:a.viewData}:{viewData:a}:void 0,u={...rP(n.source)?n.source:{},tool_call_id:e.source_tool_call_id||(null==(t=n.source)?void 0:t.tool_call_id),entity_ids:Array.isArray(e.source_entity_ids)?e.source_entity_ids:null==(r=n.source)?void 0:r.entity_ids};return{...{card_id:e.card_id,widget_id:e.widget_id,card_type:e.card_type,app_id:e.app_id},...n,widget_id:a.widget_id||n.widget_id||e.widget_id,app_id:a.applet_id||n.app_id||e.app_id,entity_id:a.entity_id||n.entity_id,source:u,card_type:o?"permission_apply":n.card_type||e.card_type,fallback_text:o?n.fallback_text||"需要授权后继续":n.fallback_text,render_data:o?{grantingData:o,permissionData:s}:d||n.render_data,title:o?n.title||ab(o):n.title,debug:{...rP(n.debug)?n.debug:{},props_json:n.props_json,output_template:l["doubao/outputTemplate"]}}}(t),l=t.block_id||o.card_id||(i=`card_${(null==r?void 0:r.seq)??0}`,o.card_id||o.title||i),d=t.op||"append";if("append"!==d&&"replace"!==d)return{state:e};if(o.card_id){let t=aI(e.messages,o.card_id,e=>{let t,i,n,a;return r?o:(t=aM(e.state,o.state),i=aM(e.source,o.source),n=aM(e.debug,o.debug),a=Object.fromEntries(Object.entries(o).filter(e=>{let[,t]=e;return void 0!==t})),{...e,...a,state:t,source:i,debug:n})});if(t.found)return{state:{...e,messages:t.messages},cardRefresh:{cardId:o.card_id,status:"updated"}}}if(!s)return{state:e};let u=a_(e.messages,s,(null==r?void 0:r.created_at_ms)??Date.now(),null==r?void 0:r.request_id,null==r?void 0:r.trace.trace_id);return{state:{...e,messages:aS(u,s,e=>({...e,contentType:"mixed",blocks:ax(e.blocks,l,o,d)}))}}}function aP(e,t){let r="completed"===t?"completed":"cancelled"===t?"interrupted":"failed";return e.map(e=>"assistant"===e.role&&"streaming"===e.status?{...e,status:r}:e)}function aL(e,t,r){return{...e,toolCalls:e.toolCalls.map(e=>e.toolCallId===t?{...e,...r}:e)}}function aO(e,t){let r={tool_call_id:t.toolCallId,tool_name:t.toolName,arguments_summary:t.arguments&&Object.keys(t.arguments).length>0?t.arguments:void 0,status:t.status},i=e.findIndex(e=>e.tool_call_id===t.toolCallId);return i<0?[...e,r]:e.map((e,t)=>t===i?r:e)}var aD=r(33680);function aU(e,t){var r,i;return null==e||null==(i=e.tools)||null==(r=i[t])?void 0:r.output}function aq(e,t,r){if(!rP(e)||!Array.isArray(e.structuredContent))return e;let i=aU(t,r);if(!i||"entities"!==i.kind)return e;if(!e.structuredContent.every(rP))throw Error(`Tool "${r}" structuredContent items must be objects`);return{...e,structuredContent:{entities:e.structuredContent.map(e=>({...e,entity_type:r}))}}}function a$(e,t){let r;if(!rP(e)||!Array.isArray(e.content))throw Error("MCP tool result must be an object with a content array");let i=void 0===(r=e.structuredContent)?{}:r,n=r5(e),a=e.content.filter(rP).map(e=>"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"),s=!0===e.isError;return{status:s?"failed":"succeeded",result:i,error:s?{code:t.businessErrorCode,message:rP(i)&&"string"==typeof i.message?i.message:a||n,retryable:!1,stage:"tool_execute",details:rP(i)?i:{structuredContent:i}}:void 0,raw_result_text:a,raw_mcp_result_json:n,miniapp:{is_mini_app:!0,mcp_channel:"flow_miniapp"},debug:{source:t.source,protocol:t.protocol,mcp_output:e}}}let aB="client_tool",aF="__bridge_ready__",az="lynxview";function aW(e,t){null==e||e({category:"mcp",source:"client_tool",...t})}class aH{runtimeUrl;container;errorListeners=new Set;host;messageListeners=new Set;view=null;constructor(e,t){this.runtimeUrl=e,this.host=function(){var e;if(!(null==(e=globalThis.document)?void 0:e.body))throw Error("Client Tool LynxView runtime requires document.body");let t=document.createElement("div");return t.dataset.doubaoClientToolRuntime="true",t.style.display="none",document.body.append(t),t}(),this.container=new rG({className:"doubao-client-tool-runtime-view",container:this.host,nativeModulesCallHandler:this.handleNativeModulesCall,onError:e=>this.emitError(e),onReady:()=>this.emitMessage({type:"event",name:aF})}),this.view=this.container.render({containerType:"TOOL",globalProps:t,initData:{},resourceUrl:e}),this.view.style.display="none"}addEventListener(e,t){"message"===e?this.messageListeners.add(t):this.errorListeners.add(t)}removeEventListener(e,t){"message"===e?this.messageListeners.delete(t):this.errorListeners.delete(t)}postMessage(e){this.container.sendGlobalEvent("__APPLET_BRIDGE__",[e])}terminate(){this.messageListeners.clear(),this.errorListeners.clear(),this.container.clear(),this.host.remove(),this.view=null}handleNativeModulesCall=(e,t,r)=>{if("AppletBridgeModule"===r&&"postMessage"===e&&rP(t)&&aG(t))return this.emitMessage(t),t};emitMessage(e){let t={data:e};for(let e of this.messageListeners)e(t)}emitError(e){let t=new ErrorEvent("error",{error:e,message:e.message});for(let e of this.errorListeners)e(t)}}function aV(e){return Object.assign(Error(e),{name:"AbortError"})}function aG(e){return"callback"===e.type&&"number"==typeof e.callbackId}class aJ{runtimeUrl;runtime;onTraceEvent;callbackId=1;ready=!1;readyPromise;rejectReady;resolveReady;pendingCallbacks=new Map;constructor(e,t,r){this.runtimeUrl=e,this.runtime=t,this.onTraceEvent=r,this.runtime.addEventListener("message",this.handleMessage),this.runtime.addEventListener("error",this.handleError)}async invokeTool(e){await this.ensureReady(e.signal);let{signal:t,...r}=e;return this.call("applet.invokeTool",r,{signal:t})}dispose(){var e;let t=Error("Client Tool runtime was disposed");for(let r of(this.runtime.removeEventListener("message",this.handleMessage),this.runtime.removeEventListener("error",this.handleError),this.runtime.terminate(),null==(e=this.rejectReady)||e.call(this,t),this.pendingCallbacks.values()))r.reject(t);this.pendingCallbacks.clear()}ensureReady(e){if(null==e?void 0:e.aborted)return Promise.reject(aV("Client Tool call aborted"));if(this.ready)return Promise.resolve();let t=this.readyPromise??(this.readyPromise=new Promise((e,t)=>{this.resolveReady=e,this.rejectReady=t}));return e?new Promise((r,i)=>{let n=()=>{e.removeEventListener("abort",n),i(aV("Client Tool call aborted"))};e.addEventListener("abort",n,{once:!0}),t.then(()=>{e.removeEventListener("abort",n),r()},t=>{e.removeEventListener("abort",n),i(t)}),e.aborted&&n()}):t}call(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=this.callbackId;return this.callbackId+=1,new Promise((n,a)=>{let{signal:s}=r;if(null==s?void 0:s.aborted)return void a(aV("Client Tool call aborted"));let o=()=>{null==s||s.removeEventListener("abort",l)},l=()=>{this.pendingCallbacks.delete(i),a(aV("Client Tool call aborted"))};null==s||s.addEventListener("abort",l,{once:!0}),this.pendingCallbacks.set(i,{reject:e=>{o(),a(e)},resolve:e=>{o(),n(e)}}),this.runtime.postMessage({type:"call",name:e,params:t,callbackId:i,target:{scope:"main",target:"self"}})})}handleMessage=e=>{var t;let r,i=rP(r="string"==typeof e.data?r3(e.data):e.data)?r:void 0;if(!i)return;if("event"===i.type&&i.name===aF){this.ready=!0,null==(t=this.resolveReady)||t.call(this),aW(this.onTraceEvent,{event:"client_tool_runtime_ready",runtime_url:this.runtimeUrl});return}if(!aG(i))return;let n=this.pendingCallbacks.get(i.callbackId);if(n){this.pendingCallbacks.delete(i.callbackId);try{n.resolve(function(e){let t=rP(e.params)?e.params:{};if(1===t.code)return t.data;throw Error("string"==typeof t.msg&&t.msg||`Client Tool runtime callback failed with code ${String(t.code)}`)}(i))}catch(e){n.reject(e)}}};handleError=e=>{var t;let r=Error(e.message||"Client Tool runtime failed");for(let e of(null==(t=this.rejectReady)||t.call(this,r),this.pendingCallbacks.values()))e.reject(r);this.pendingCallbacks.clear()}}function aK(e,t,r){return{status:"failed",result:{error:t},error:{code:e,message:t,retryable:r,stage:"tool_execute"},raw_result_text:t,miniapp:{is_mini_app:!0,mcp_channel:"flow_miniapp"},debug:{source:"client_tool",protocol:az}}}let aZ="simulator_web_tester";function aX(e){if(!e.trim())throw Error("Client Tool simulator manifest requires raw_manifest_yaml");let t=(0,aD.qg)(e);if(!rP(t))throw Error("Client Tool raw_manifest_yaml must contain a YAML object");return t}function aY(e){var t,r,i,n;let a=e.simulatorManifest||e.options.manifest||{},s=a.entities??(a.raw_manifest_yaml?aX(a.raw_manifest_yaml).entities:void 0),o=(t=e.messages,r=e.toolCalls,i=e.historyMaxTurns,n=s,t.slice(-Math.max(0,2*i)).flatMap(e=>{var t,i;let a,s,o=(t=e,a=r.filter(e=>e.replyMessageId===t.messageId&&["succeeded","failed","timeout","cancelled","rejected"].includes(e.status)).map(e=>{var t;let r=e.resultSummary?e.resultSummary:(null==(t=e.error)?void 0:t.message)?e.error.message:e.message;return{tool_call_id:e.toolCallId,tool_name:e.toolName,result_summary:r,structured_summary:e.structuredResultSummary,is_mini_app:e.isMiniApp}}),[...new Map([...t.toolResults??[],...a].map(e=>[e.tool_call_id,e])).values()]),l=a0(e.blocks.flatMap(e=>"image"===e.type?[e.image]:[]));return[{role:"assistant"===e.role?"ASSISTANT":"USER",content:(s=(i=e).text?i.text:i.blocks.filter(e=>"text"===e.type).map(e=>e.text).join(""))||e.blocks.map(e=>{var t;return"image"===e.type?e.image.name?`[图片:${e.image.name}]`:"[图片]":"card"===e.type?(t=e.card).fallback_text||t.title||t.card_type||t.card_id||"卡片":e.text}).filter(Boolean).join("\n"),parts:l.length>0?l:void 0},...o.map(e=>{var t;let r;return{role:"TOOL",content:rP(r=e.structured_summary)&&Array.isArray(r.entities)?JSON.stringify({...e,result_summary:(null==(t=r4(e.result_summary))?void 0:t.structuredContent)?void 0:e.result_summary,structured_summary:{entities:r.entities.filter(rP).map(e=>{var t;return function e(t,r){return Array.isArray(t)?t.map(t=>e(t,r.items??{})):rP(t)?Object.fromEntries(Object.entries(r.properties??{}).flatMap(r=>{let[i,n]=r;return rP(n)&&!1!==n.llm_visible&&i in t?[[i,e(t[i],n)]]:[]})):t}(e,{properties:null==n||null==(t=n[e.entity_type])?void 0:t.schema})})}}):JSON.stringify(e)}})]})),l=aQ(e.messages),d=a.app_key||"",u=e.options.appKey||e.simulatorAppKey||d||e.manifestAppId||"web-sdk-debugger",c=e.options.appName||e.simulatorAppName||e.manifestAppName||u,p=(e.options.skills??e.simulatorSkills??[]).map(e=>e.content),h=e.options.mcpServers??e.simulatorMcpServers,m=function(e,t){let r=e.raw_manifest_yaml||"",i=t.find(e=>e.server_id===aB&&e.tools.length>0);if(!i||!e.tools||null!=e.mcp_server)return r;let n=aX(r);return null!=n.mcp_server?r:(0,aD.As)({...n,mcp_server:{end_point:i.server_id,description:i.description||i.name}})}(a,h);return{app_id:u,scene:"miniapp_simulator_web_tester",history_messages:o,card_snapshots:l,trace:{trace_id:e.traceId,component:aZ,stage:"query",sampled:!0},client:{platform:"web",locale:"zh-CN",timezone:function(){try{return new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"Asia/Shanghai"}}()},ext:{web_tester:"true",stateless_context:"client_history",skill_source:p.length>0?"local_file":"none",no_login:e.options.noLogin?"true":void 0},max_step:e.options.maxStep??e.simulatorMaxStep??20,protocol_version:"v2",idempotency_key:e.idempotencyKey,mini_apps:[{app_key:u,app_name:c,skills:p,manifest:{app_key:u,app_name:c,raw_manifest_yaml:m},mcp_servers:h.map(e=>({server_id:e.server_id,name:e.name,description:e.description||"",tools:e.tools.map(e=>({name:e.name,description:e.description||"",input_schema_json:r5(e.input_schema_json)}))}))}],web_capabilities:{supports_debug_event:!0}}}function aQ(e){let t=new Map;for(let r of e)for(let e of r.blocks){if("card"!==e.type)continue;let r=function(e){var t,r,i;let n=r4(null==(t=e.debug)?void 0:t.props_json),a=e.card_id,s=(null==n?void 0:n.applet_id)||e.app_id,o=(null==n?void 0:n.entity_id)||e.entity_id;if(a&&s)return{card_id:a,app_key:s,business_entity_ids:o?[o]:void 0,lifecycle_state:(null==(r=e.state)?void 0:r.lifecycle_state)==="fixed"||(null==(i=e.state)?void 0:i.lifecycle_state)===2?2:1,refresh_key:e.refresh_key}}(e.card);r&&t.set(r.card_id,r)}return[...t.values()]}function a0(e){return e.map(e=>({type:"image",image:{resource_uri:e.resource_uri}}))}function a1(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"tool_execute",i=arguments.length>3?arguments[3]:void 0;return{code:e,message:t,user_message:t,retryable:!1,stage:r,details:i}}async function a2(e){let t,r,i,n,a,s,{executor:o,input:l,record:d,signal:u}=e,c=(t=void 0===d.deadlineMs?void 0:d.deadlineMs-Date.now(),r=d.timeoutMs,void 0===(i=void 0===t?r:void 0===r?t:Math.min(t,r))?void 0:Math.max(0,i)),p=a1("TOOL_EXEC_CANCELLED","Tool execution cancelled"),h=void 0===c?void 0:new AbortController,m=(null==h?void 0:h.signal)??u;if(null==u?void 0:u.aborted)throw p;if(h&&u){let e=()=>{h.abort()};u.addEventListener("abort",e,{once:!0}),a=()=>u.removeEventListener("abort",e)}let g=[Promise.resolve(o({...l,signal:m}))];if(void 0!==c&&h){let e=a1("TOOL_EXEC_TIMEOUT",`Tool execution timed out after ${c}ms`);g.push(new Promise((t,r)=>{n=setTimeout(()=>{h.abort(),r(e)},c)}))}u&&g.push(new Promise((e,t)=>{let r=()=>{t(p)};u.addEventListener("abort",r,{once:!0}),s=()=>u.removeEventListener("abort",r)}));try{return await Promise.race(g)}finally{n&&clearTimeout(n),null==a||a(),null==s||s()}}function a3(e){return e?String(e):nZ}function a4(e,t,r){return r?{type:e,message:t,error:r}:{type:e,message:t}}let a5={simulator_manifest_load_failed:"Manifest",simulator_skill_load_failed:"Skill",local_mcp_tools_load_failed:"MCP",simulator_chat_fetch_failed:"对话接口"};function a6(e){return new Set(e.flatMap(e=>e.blocks.flatMap(e=>"image"===e.type&&e.image.previewUrl?[e.image.previewUrl]:[])))}function a8(e,t){return e?{kind:"pages",item:e,routeUrl:t}:null}function a9(e,t){if(!t)return null;try{return a8(tO({url:t},e).entry,t)}catch{return null}}function a7(e){var t,r;return e.raw_result_text||(null==(t=e.error)?void 0:t.message)||(void 0===(r=e.result)?"":"string"==typeof r?r.slice(0,1e3):r5(r).slice(0,1e3))||e.status}function se(e,t){return e.app_key||e.appKey||e.appId||e.packageName||t}function st(e,t){var r;return e.name||e.appName||e.app_name||(null==(r=e.applet)?void 0:r.name)||t}function sr(e,t){let r=e.applet??{},i=t.applet??{},n=r.tools??[],a=i.tools??[],s=new Map,o=t.name||t.appName||t.app_name||i.name||"";if(a.length>0)for(let e of[...n,...a])e.id&&s.set(e.id,e);return{...e,manifest_version:t.manifest_version??e.manifest_version,app_key:t.app_key??e.app_key,name:t.name??e.name,appName:t.appName??e.appName,app_name:t.app_name??e.app_name,mcp_server:t.mcp_server??e.mcp_server,tools:t.tools??e.tools,entities:t.entities??e.entities,tool_card_binding:t.tool_card_binding??e.tool_card_binding,raw_manifest_yaml:t.raw_manifest_yaml??e.raw_manifest_yaml,applet:{...r,name:o||r.name,tools:a.length>0?[...s.values()]:n}}}class si{fetcher;simulatorFetcher;historyMaxTurns;simulatorAppKey;simulatorAppName;simulatorSkills;simulatorManifest;simulatorMaxStep;simulatorMcpServers;simulatorMcpServerProvider;simulatorToolExecutor;sandboxToolCallExecutions=new Map;listeners=new Set;activeSimulatorRun=null;lastResolvedSimulatorMcpServers=[];receivedSimulatorLocationDirectiveCardIds=new Set;resourceUrlVersion;hasSimulatorManifestStateValue=!1;simulatorManifestStateValue;simulatorManifestStatePromise;simulatorRunSeq=0;destroyed=!1;state;constructor(e={}){let t=a3(e.manifestUrl);this.fetcher=e.fetcher,this.simulatorFetcher=e.simulatorFetch,this.historyMaxTurns=e.historyMaxTurns??6,this.simulatorAppKey=e.appKey,this.simulatorAppName=e.appName,this.simulatorSkills=e.skills,this.simulatorManifest=e.simulatorManifest,this.simulatorMaxStep=e.maxStep,"function"==typeof e.mcpServers?(this.simulatorMcpServers=[],this.simulatorMcpServerProvider=e.mcpServers):this.simulatorMcpServers=e.mcpServers??[],this.simulatorToolExecutor=e.toolExecutor,this.state={manifestUrl:t,manifest:new c({manifestVersion:"3.0",packageName:"",appId:"",versionCode:"",applet:{appletId:"",appRuntimeEntry:"",digest:"",pages:[]},widgets:[]}),pages:[],widgets:[],pageSelection:null,widgetSelection:null,simulator:{endpoint:n0(e.simulatorEndpoint),messages:[],streamStatus:"idle",toolCalls:[],traceEvents:[]},status:a4("idle","Idle")}}clearSimulatorManifestStateValue(){this.hasSimulatorManifestStateValue=!1,this.simulatorManifestStateValue=void 0,this.simulatorManifestStatePromise=void 0}takeSimulatorManifestStateValue(){if(!this.hasSimulatorManifestStateValue)return{found:!1,value:void 0};let e=this.simulatorManifestStateValue;return this.clearSimulatorManifestStateValue(),{found:!0,value:e}}async loadSimulatorManifestForState(){if(void 0!==this.simulatorManifest)return"function"!=typeof this.simulatorManifest?this.simulatorManifest:this.hasSimulatorManifestStateValue?this.simulatorManifestStateValue:(this.simulatorManifestStatePromise||(this.simulatorManifestStatePromise=Promise.resolve(this.simulatorManifest()).then(e=>(this.hasSimulatorManifestStateValue=!0,this.simulatorManifestStateValue=e,e)).finally(()=>{this.simulatorManifestStatePromise=void 0})),this.simulatorManifestStatePromise)}async mergeSimulatorManifestForState(e){if(void 0===this.simulatorManifest)return e;try{let t=await this.loadSimulatorManifestForState();if(!t)return e;return new c(sr(e.raw,t))}catch(t){return console.warn("[web-sdk-debugger] Failed to merge simulator manifest for debug state",t),e}}async loadManifest(e){this.assertActive();let t=this.state.manifestUrl,r=a3(e??this.state.manifestUrl);this.setState({...this.state,manifestUrl:r,resourceUrlVersion:this.resourceUrlVersion,status:a4("loading",`Loading manifest ${r}`)});try{var i,n,a,s,o,l;let e,t,d,u,c,h=await p(r,{fetcher:this.fetcher}),m=await this.mergeSimulatorManifestForState(h),g=m.pages,f=m.widgets,v=a9(m,null==(i=this.state.pageSelection)?void 0:i.routeUrl)??(s=m,o=g,l=this.state.pageSelection,e=o.filter(nY),t=null==l?void 0:l.item.path,d=function(e,t){if(t)try{return e.getPageEntry(t)}catch{return}}(s,s.raw.applet.appletEntry),a8((t?e.find(e=>e.path===t):void 0)??(d&&nY(d)?d:void 0)??e.find(e=>"index"===e.id||"/pages/index"===e.path||"/pages/index/index"===e.path)??e[0])),y=(n=this.state.widgetSelection,u=f.filter(nY),(a=((c=null==n?void 0:n.item.widgetId)?u.find(e=>e.widgetId===c):void 0)??u[0])?{kind:"widgets",item:a}:null);return this.setState({...this.state,manifestUrl:r,manifest:m,pages:g,widgets:f,resourceUrlVersion:this.resourceUrlVersion,pageSelection:v,widgetSelection:y,status:a4("ready",v||y?`Loaded manifest ${r}`:`Manifest has no entries ${r}`)}),this.state}catch(r){let e=r instanceof Error?r:Error(String(r));throw this.setState({...this.state,manifestUrl:t,status:a4("error",`Load failed: ${e.message}`,e)}),e}}navigateToPage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.assertActive();try{let r=a9(this.state.manifest,e);if(!r)throw Error(`Unknown pages route: ${e}`);this.setState({...this.state,pageSelection:{...r,routeMode:t.routeMode},status:a4("ready",`Navigated page ${r.item.path}`)})}catch(t){let e=t instanceof Error?t:Error(String(t));throw this.setState({...this.state,status:a4("error",e.message,e)}),e}}selectWidget(e){this.assertActive();let t=this.state.widgets.find(t=>t.widgetId===e);if(!t){let t=Error(`Unknown widgets entry: ${e}`);throw this.setState({...this.state,status:a4("error",t.message,t)}),t}this.setState({...this.state,widgetSelection:{kind:"widgets",item:t},status:a4("ready",`Selected widget ${t.widgetId}`)})}async reloadResources(){if(this.assertActive(),"streaming"===this.state.simulator.streamStatus)throw Error("Cannot refresh card resources while simulator query is streaming");let e=this.state.manifestUrl,t=n2("reload");this.resourceUrlVersion=t,this.clearSimulatorManifestStateValue();let r=await this.loadManifest(e);return void 0!==this.simulatorSkills&&await this.resolveSimulatorSkillsForQuery(t,{}),this.appendSimulatorDebugEvent({category:"resource",event:"simulator_resource_reload_completed",manifest_url:e,resource_url_version:t,summary:"Card resources refreshed"}),r}async sendSimulatorQuery(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.assertActive();let r=e.trim(),i=(t.images??[]).filter(e=>e.resource_uri);if(r||0!==i.length)return this.sendSimulatorChat({kind:"message",queryText:r},t)}sendSimulatorFollowUpMessage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise((r,i)=>{let n=Error("Simulator follow-up message was cancelled before submission");this.sendSimulatorChat({kind:"follow_up",content:e},t,r,()=>i(n)).then(()=>i(n),i)})}async sendSimulatorChat(e,t,r,i){this.assertActive(),this.cancelSimulatorQuery();let n=n2("local_msg"),a=n2("idem"),s=n2("trace"),o=Date.now(),l=this.state.simulator,d=this.state.manifest.raw,u="message"===e.kind?(t.images??[]).filter(e=>e.resource_uri):[],c="message"===e.kind?{messageId:n,localMessageId:n,traceId:s,role:"user",contentType:u.length>0?"mixed":"text",text:e.queryText,blocks:[...u.map(e=>({blockId:n2("block_image"),type:"image",image:e})),...e.queryText?[{blockId:n2("block_text"),type:"text",text:e.queryText}]:[]],status:"completed",createdAtMs:o}:void 0,p=this.createSimulatorRun(s);p.onCancelledBeforeSubmission=i,this.activeSimulatorRun=p,this.setState({...this.state,simulator:{...l,activeRequestId:void 0,activeReplyMessageId:void 0,error:void 0,locationDirective:void 0,messages:c?[...l.messages,c]:l.messages,streamStatus:"streaming"}}),this.appendSimulatorDebugEvent({event:"simulator_query_prepare_started",trace_id:s,previous_active_request_id:l.activeRequestId,previous_stream_status:l.streamStatus,history_message_count:l.messages.length,query_preview:"message"===e.kind?e.queryText.slice(0,80)||"[图片]":"send_follow_up_message",image_count:u.length});try{var h,m;let i,u=await this.resolveSimulatorManifestForQuery(s,t,d,p.streamAbortController.signal),c=se(u,this.state.manifest.appId),g=st(u,this.state.manifest.name);if(!this.isSimulatorRunCurrent(p))return;let f=await this.resolveSimulatorSkillsForQuery(s,t,p.streamAbortController.signal);if(!this.isSimulatorRunCurrent(p))return;let v={signal:p.streamAbortController.signal,trace:{trace_id:s,component:"web_sdk_debugger",stage:"query_prepare",sampled:!0},appKey:t.appKey||this.simulatorAppKey||c,appName:t.appName||this.simulatorAppName||g,manifest:u},y=this.simulatorMcpServerProvider?await this.simulatorMcpServerProvider(v):this.simulatorMcpServers;if(this.lastResolvedSimulatorMcpServers=y,!this.isSimulatorRunCurrent(p))return;this.appendSimulatorDebugEvent({event:"simulator_query_mcp_resolved",trace_id:s,elapsed_ms:Date.now()-o,mcp_server_count:y.length,mcp_servers:y.map(e=>({server_id:e.server_id,tool_count:e.tools.length,tools:e.tools.map(e=>e.name)}))});let b={historyMaxTurns:this.historyMaxTurns,idempotencyKey:a,localMessageId:n,manifestAppId:this.state.manifest.appId,manifestAppName:g,messages:l.messages,toolCalls:l.toolCalls,options:t,simulatorAppKey:this.simulatorAppKey,simulatorAppName:this.simulatorAppName,simulatorSkills:f,simulatorManifest:u,simulatorMaxStep:this.simulatorMaxStep,simulatorMcpServers:y,traceId:s},w="message"===e.kind?(h={...b,queryText:e.queryText},i=a0(h.options.images??[]),{...aY(h),message:{role:"USER",content:h.queryText,local_message_id:h.localMessageId,parts:i.length>0?i:void 0}}):(m={...b,content:e.content},{...aY(m),input_event:{event_type:"send_follow_up_message",params:{content:m.content},local_message_id:m.localMessageId}});if(await ao({endpoint:this.state.simulator.endpoint,fetcher:this.simulatorFetcher,onSubmitted:()=>{p.onCancelledBeforeSubmission=void 0,null==r||r()},request:w,signal:p.streamAbortController.signal,onEvent:t=>this.handleSimulatorEvent(t,p,"follow_up"===e.kind?e.content:void 0)}),!this.isSimulatorRunCurrent(p))return;"streaming"===this.state.simulator.streamStatus&&this.setState({...this.state,simulator:{...this.state.simulator,activeRequestId:void 0,streamStatus:"completed"}}),this.appendSimulatorDebugEvent({event:"simulator_query_stream_returned",trace_id:s,elapsed_ms:Date.now()-o,stream_status:this.state.simulator.streamStatus,active_request_id:this.state.simulator.activeRequestId})}catch(i){if(aT(i))return void this.appendSimulatorDebugEvent({event:"simulator_query_aborted",trace_id:s,elapsed_ms:Date.now()-o,stream_status:this.state.simulator.streamStatus});if(!this.isSimulatorRunCurrent(p))return;let e=aA(i,"query_stream"),t=this.getSimulatorQueryFailureDiagnosis(s,i),r=t?{...e,message:t.summary,user_message:t.summary,details:{...e.details,diagnosis:t,original_error:e.message}}:e;throw this.appendSimulatorDebugEvent({event:"simulator_query_failed",trace_id:s,elapsed_ms:Date.now()-o,error:r}),this.setState({...this.state,simulator:{...this.state.simulator,activeRequestId:void 0,error:r,streamStatus:"error"}}),i}finally{this.finishSimulatorStream(p)}}pushMessages(e){if(this.assertActive(),!Array.isArray(e))throw Error("Messages must be an array");if(0===e.length)return;let t=structuredClone(e).map(e=>{let t=(e.blocks??[]).map(e=>({...e,blockId:e.blockId??n2("block"),..."card"===e.type?{card:{...e.card,card_id:e.card.card_id??n2("card")}}:{}}));return{...e,messageId:e.messageId??n2("message"),createdAtMs:e.createdAtMs??Date.now(),text:e.text??"",contentType:e.contentType??(t.some(e=>"text"!==e.type)?"mixed":"text"),blocks:t}}),r=new Set(this.state.simulator.messages.map(e=>e.messageId));for(let e of t){if(r.has(e.messageId))throw Error(`Duplicate messageId: ${e.messageId}`);r.add(e.messageId)}this.updateSimulatorState(e=>({...e,messages:[...e.messages,...t]}))}removeSimulatorMessages(e){this.assertActive();let t=new Set(e.filter(Boolean));if(0===t.size)return;let r=a6(this.state.simulator.messages.filter(e=>t.has(e.messageId)));this.updateSimulatorState(e=>({...e,activeReplyMessageId:e.activeReplyMessageId&&t.has(e.activeReplyMessageId)?void 0:e.activeReplyMessageId,messages:e.messages.filter(e=>!t.has(e.messageId)),selectedCard:e.selectedCard&&t.has(e.selectedCard.reply_message_id)?void 0:e.selectedCard})),queueMicrotask(()=>{let e=a6(this.state.simulator.messages);for(let t of r)e.has(t)||URL.revokeObjectURL(t)})}applySimulatorCardDelta(e){this.assertActive(),this.updateSimulatorState(t=>aj(t,rP(e.card_delta)?e.card_delta:e).state)}consumeSimulatorLocationDirective(e){this.assertActive(),this.updateSimulatorState(t=>{var r;return(null==(r=t.locationDirective)?void 0:r.cardId)===e?{...t,locationDirective:void 0}:t})}cancelSimulatorQuery(){this.assertActive();let e=this.state.simulator.activeRequestId,t=this.activeSimulatorRun;t&&(this.appendSimulatorDebugEvent({event:"simulator_query_cancel_requested",request_id:e,trace_id:t.traceId,stream_status:this.state.simulator.streamStatus}),this.abortSimulatorRun(t)),"streaming"===this.state.simulator.streamStatus&&this.setState({...this.state,simulator:{...this.state.simulator,activeRequestId:void 0,activeReplyMessageId:void 0,toolCalls:this.state.simulator.toolCalls.map(t=>e&&t.requestId===e&&"running"===t.status?{...t,status:"cancelled",updatedAtMs:Date.now()}:t),streamStatus:"cancelled"}})}async callSimulatorTool(e){if(this.assertActive(),!this.simulatorToolExecutor)throw Error("No local simulator tool executor is configured");let t=e.toolName.trim();if(!t)throw Error("toolName must be a non-empty string");let r=n2("req_tool"),i=n2("reply_tool"),n=n2("tool_call"),a=n2("trace"),s={trace_id:a,component:"web_sdk_debugger",stage:"direct_tool_call",sampled:!0},o=Date.now(),l=await this.resolveDirectToolCallServerId(t,e.serverId,s),d={requestId:r,replyMessageId:i,toolCallId:n,toolName:t,serverId:l,appKey:this.simulatorAppKey||se(this.state.manifest.raw,this.state.manifest.appId)||void 0,arguments:e.params,argumentsJson:e.params?function(e){try{return JSON.stringify(e??{})}catch{return""}}(e.params):void 0,status:"running",createdAtMs:o,updatedAtMs:o,trace:s,timeoutMs:e.timeoutMs};this.updateSimulatorState(e=>({...e,toolCalls:[...e.toolCalls,d]})),this.appendSimulatorDebugEvent({event:"direct_tool_call_started",request_id:r,trace_id:a,tool_call_id:n,tool_name:t,server_id:l,arguments:e.params,arguments_json:d.argumentsJson});let u=Date.now(),c=await this.runSimulatorToolCall(d);return this.updateToolCall(n,{status:c.status,updatedAtMs:Date.now(),error:c.error,resultSummary:a7(c),structuredResultSummary:c.result,isMiniApp:c.miniapp&&"boolean"==typeof c.miniapp.is_mini_app?c.miniapp.is_mini_app:void 0}),this.appendSimulatorDebugEvent({event:"direct_tool_call_completed",request_id:r,trace_id:a,tool_call_id:n,tool_name:t,server_id:l,status:c.status,elapsed_ms:Date.now()-u,result:c.result,error:c.error,raw_result_text:c.raw_result_text}),c}executeSandboxToolCall(e){this.assertActive();let t=`${e.request_id}\0${e.tool_call.tool_call_id}`,r=this.sandboxToolCallExecutions.get(t);if(r)return r;let i=this.executeSandboxToolCallOnce(e);return this.sandboxToolCallExecutions.set(t,i),i}async submitToolResult(e,t){let r,i,n,a;this.assertActive();let s=Date.now(),o=(i=void 0===e.result?e.error?{error:e.error.message}:{}:e.result,n=e.raw_mcp_result_json,a=e.raw_result_text||r5(e.error?{error:e.error.message,detail:e.error}:i),{request_id:e.requestId,tool_call_id:e.toolCallId,server_id:e.serverId,tool_name:e.toolName,status:function(e){switch(e){case"succeeded":return"SUCCESS";case"timeout":return"TIMEOUT";case"cancelled":return"CANCELLED";case"rejected":return"REJECTED";default:return"FAILED"}}(e.status),app_key:e.appKey,result:{tool_call_id:e.toolCallId,content:a,structured_json:r5(i)},raw_result_text:a,raw_mcp_result_json:n||"",miniapp:e.miniapp,timing:e.timing,trace:{trace_id:e.trace.trace_id,component:aZ,stage:"tool_report",sampled:e.trace.sampled??!0},ext:{reported_by:aZ}});this.appendSimulatorDebugEvent({event:"tool_result_report_started",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,server_id:e.serverId,status:o.status,report_request:o,endpoint:this.state.simulator.endpoint});try{r=await al({endpoint:this.state.simulator.endpoint,fetcher:this.simulatorFetcher,result:o,signal:t})}catch(r){let t=an(r);throw this.appendSimulatorDebugEvent({event:"tool_result_report_failed",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,elapsed_ms:Date.now()-s,error:r6(r),response:t}),r}this.appendSimulatorDebugEvent({event:"tool_result_report_response_received",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,elapsed_ms:Date.now()-s,response:r});let l=function(e){let t=e.code,r=!1===e.accepted,i=void 0!==t&&0!==t&&"0"!==t;if(!r&&!i)return;let n="string"==typeof e.message&&e.message?e.message:i?`Simulator tool result rejected with code ${String(t)}`:"Simulator tool result was not accepted",a=r0(e)[0];return a1("TOOL_RESULT_REJECTED",a?`${n} (x-tt-logid: ${a})`:n,"tool_result_submit",{gateway_response:e,gateway_code:i?t:void 0,gateway_accepted:!r&&void 0,"x-tt-logid":a})}(r);if(this.appendSimulatorDebugEvent({event:"tool_result_ack",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,accepted:r.accepted,next_action:r.next_action,error:l,response:r}),l)throw l;return r}selectSimulatorCard(e){this.assertActive(),this.updateSimulatorState(t=>({...t,selectedCard:e}))}updateSimulatorWidget(e){var t,r,i;let n,a,s;if(this.assertActive(),"string"!=typeof e.widgetInstanceId||!e.widgetInstanceId.trim())return{status:"invalid_params",message:"widgetInstanceId must be a non-empty string"};if(void 0!==e.widgetId&&("string"!=typeof e.widgetId||!e.widgetId.trim()))return{status:"invalid_params",message:"widgetId must be a non-empty string when provided"};if(void 0!==e.reloadWidget&&"boolean"!=typeof e.reloadWidget)return{status:"invalid_params",message:"reloadWidget must be a boolean"};let o=void 0!==e.toolResult;if(void 0!==e.widgetData===o)return{status:"invalid_params",message:"widgetData and toolResult must be exclusive"};let l=this.state.simulator.messages.flatMap(e=>e.blocks).find(t=>"card"===t.type&&t.card.card_id===e.widgetInstanceId);if(!l||"card"!==l.type)return{status:"not_found",message:`Widget instance ${e.widgetInstanceId} was not found`};let d=e.widgetId??l.card.widget_id;if(d!==l.card.widget_id&&(o||!1===e.reloadWidget))return{status:"invalid_params",message:"Changing widgetId requires widgetData and reloadWidget"};if("__doubao_apps__expired-widget"!==d&&!this.state.widgets.some(e=>e.widgetId===d))return{status:"not_found",message:`Widget ${d} was not found`};let u=e.toolResult,c=null==(t=l.card.source)?void 0:t.tool_call_id;if(o){if(!rP(u)||void 0!==u.content&&(!Array.isArray(u.content)||!u.content.every(rP))||void 0!==u.isError&&"boolean"!=typeof u.isError||!rP(u.structuredContent)||!Array.isArray(u.structuredContent.entities)||!u.structuredContent.entities.length||!u.structuredContent.entities.every(rP))return{status:"invalid_params",message:"toolResult must contain structuredContent.entities"};let e=rP(null==(r=l.card.render_data)?void 0:r.viewData)?l.card.render_data.viewData:l.card.render_data,t=u.structuredContent.entities.filter(t=>{var r;let i=null==(r=this.state.manifest.raw.entities)?void 0:r[t.entity_type];if(!i||!Object.values(i.tool_card_binding??{}).includes(d))return!1;let n=Object.keys(i.schema??{}).find(e=>{var t;return(null==(t=i.schema[e])?void 0:t.is_entity_id)===!0});return n&&void 0!==t[n]&&((null==e?void 0:e[n])===void 0||t[n]===e[n])});if(1!==t.length)return{status:"invalid_params",message:"toolResult must identify one entity for the current Widget"};let o=this.state.simulator.toolCalls.find(e=>e.toolCallId===c),p=this.state.simulator.messages.flatMap(e=>e.toolResults??[]).find(e=>e.tool_call_id===c);if(!c||!o&&!p)return{status:"not_found",message:"The Widget Tool result was not found in conversation history"};n=t[0],a=null==(i=u.content)?void 0:i.map(e=>"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"),this.state.simulator.messages.slice(-Math.max(0,2*this.historyMaxTurns)).some(e=>{var t;return e.messageId===(null==o?void 0:o.replyMessageId)||(null==(t=e.toolResults)?void 0:t.some(e=>e.tool_call_id===c))})||(s={tool_call_id:c,tool_name:(null==o?void 0:o.toolName)??p.tool_name,result_summary:a,structured_summary:u.structuredContent,is_mini_app:(null==o?void 0:o.isMiniApp)??(null==p?void 0:p.is_mini_app)})}else try{let t="string"==typeof e.widgetData?JSON.parse(e.widgetData):void 0;if(!rP(t))throw Error("Invalid Widget data");n=t}catch{return{status:"invalid_widget_data",message:"widgetData must be a JSON object"}}let p=aI(this.state.simulator.messages,e.widgetInstanceId,t=>({...t,widget_id:d,refresh_key:!1===e.reloadWidget?t.refresh_key:n2("refresh"),render_data:n}));return this.updateSimulatorState(e=>({...e,messages:u?p.messages.map((e,t)=>{var r;let i=null==(r=e.toolResults)?void 0:r.map(e=>e.tool_call_id===c?{...e,result_summary:a,structured_summary:u.structuredContent}:e);return{...e,toolResults:s&&t===p.messages.length-1?[...i??[],s]:i}}):p.messages,toolCalls:u?e.toolCalls.map(e=>e.toolCallId===c?{...e,resultSummary:a,structuredResultSummary:u.structuredContent,updatedAtMs:Date.now()}:e):e.toolCalls})),{status:"updated"}}appendSimulatorTraceEvent(e){this.assertActive(),this.appendSimulatorDebugEvent(e)}async approveSimulatorToolCall(e){this.assertActive();let t=this.getSimulatorToolCall(e);if(!this.simulatorToolExecutor)throw Error("No local simulator tool executor is configured");if("pending_approval"!==t.status)return;let r=this.getSimulatorToolCallRun(t);if(void 0!==t.runId&&!r)return void this.cancelStaleSimulatorToolCall(t);let i={...t,status:"running",updatedAtMs:Date.now()};null==r||r.pendingApprovalToolCallIds.delete(e),this.updateToolCall(e,{status:i.status,updatedAtMs:i.updatedAtMs}),await this.executeSimulatorToolCall(i,r)}async rejectSimulatorToolCall(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Tool call rejected by user";this.assertActive();let r=this.getSimulatorToolCall(e);if("pending_approval"!==r.status)return;let i=this.getSimulatorToolCallRun(r);if(void 0!==r.runId&&!i)return void this.cancelStaleSimulatorToolCall(r);let n=this.createToolExecutorInput(r),a=a1("TOOL_EXEC_REJECTED",t),s=Date.now();null==i||i.pendingApprovalToolCallIds.delete(e);try{await this.submitExecutedToolResult(n,{status:"rejected",error:a},s,null==i?void 0:i.streamAbortController.signal),this.updateToolCall(e,{status:"rejected",updatedAtMs:Date.now(),error:a,resultSummary:t})}catch(n){if(i&&!this.isSimulatorRunCurrent(i))return void this.appendSimulatorDebugEvent({event:"tool_result_submit_skipped",request_id:r.requestId,trace_id:r.trace.trace_id,tool_call_id:r.toolCallId,tool_name:r.toolName,reason:"stale_or_cancelled_run"});let t=aA(n,"tool_result_submit");throw this.appendSimulatorDebugEvent({event:"tool_result_submit_failed",trace_id:r.trace.trace_id,tool_call_id:e,summary:r6(n)}),this.updateToolCall(e,{status:"failed",updatedAtMs:Date.now(),error:t}),n}finally{i&&this.releaseSimulatorRun(i)}}getState(){return this.state}subscribe(e){return this.assertActive(),this.listeners.add(e),()=>{this.listeners.delete(e)}}getResourceUrl(e){return(this.assertActive(),e)?h(this.state.manifestUrl,e)??null:null}destroy(){var e,t;if(!this.destroyed){for(let r of(this.cancelSimulatorQuery(),null==(t=this.simulatorToolExecutor)||null==(e=t.dispose)||e.call(t),a6(this.state.simulator.messages)))URL.revokeObjectURL(r);this.destroyed=!0,this.sandboxToolCallExecutions.clear(),this.listeners.clear()}}createSimulatorRun(e){return{id:this.simulatorRunSeq+=1,traceId:e,streamAbortController:new AbortController,streamDone:!1,cancelled:!1,pendingApprovalToolCallIds:new Set,toolAbortControllers:new Set}}isSimulatorRunCurrent(e){return!this.destroyed&&this.activeSimulatorRun===e&&!e.cancelled}abortSimulatorRun(e){var t;for(let r of(e.cancelled=!0,null==(t=e.onCancelledBeforeSubmission)||t.call(e),e.onCancelledBeforeSubmission=void 0,e.streamAbortController.abort(),e.toolAbortControllers))r.abort();this.activeSimulatorRun===e&&(this.activeSimulatorRun=null)}finishSimulatorStream(e){e.streamDone=!0,this.releaseSimulatorRun(e)}releaseSimulatorRun(e){this.activeSimulatorRun===e&&(e.cancelled||e.streamDone&&0===e.pendingApprovalToolCallIds.size&&0===e.toolAbortControllers.size)&&(this.activeSimulatorRun=null)}handleSimulatorEvent(e,t,r){let i="tool_call"===e.event_type;if(!this.isSimulatorRunCurrent(t)){i&&this.appendSimulatorDebugEvent({event:"tool_call_event_skipped",request_id:e.request_id,trace_id:e.trace.trace_id,tool_call_id:e.payload.tool_call_id||"",tool_name:e.payload.tool_name||"",reason:"stale_or_cancelled_run",summary:"Tool call event arrived after its simulator run was cancelled and was not executed"});return}let n=this.state.simulator.activeRequestId;if(n&&e.request_id!==n&&"ack"!==e.event_type&&"debug"!==e.event_type){if(!i&&"tool_status"!==e.event_type)return;this.appendSimulatorDebugEvent({event:"tool_call_request_id_mismatch",request_id:e.request_id,active_request_id:n,trace_id:e.trace.trace_id,tool_call_id:e.payload.tool_call_id||"",tool_name:e.payload.tool_name||"",event_type:e.event_type,summary:"Tool call event request_id differs from the acknowledged request_id"})}let{state:a,toolCall:s,cardRefresh:o,locationDirective:l}=function(e,t,r){var i,n,a,s,o,l,d,u,c,p,h,m;let g,f,v,y,b,w,_,S,x={...e,activeReplyMessageId:t.reply_message_id??e.activeReplyMessageId},I=!function(e){switch(e.event_type){case"ack":case"tool_call":case"tool_status":case"card_delta":case"content_block":case"answer_finish":case"message_finish":case"reply_finish":case"stream_error":case"trace_event":case"debug":return!0;default:return!1}}(t)?x:aR(x,(S=t.received_at_ms??Date.now(),{display:"debug"===(i=t).event_type?ah(i.payload)??{category:"debug",detail:ak(i),phase:"event",title:"Debug"}:{category:aE(i),detail:ak(i),phase:aN(i.event_type),title:aC(i)},id:t.event_id,timestamp:S,payload:(n=t,a=S,g=aE(n),f=aN(n.event_type),v={event:n.event_type,category:g,phase:f,received_at_ms:a,server_timestamp_ms:n.created_at_ms,title:aC(n),detail:ak(n),trace:n.trace},"debug"===n.event_type?{...v,event:n.payload.event||"debug",title:r9(n.payload.title||n.payload.event||"Debug Event"),summary:n.payload.summary,elapsed_ms:n.payload.elapsed_ms,redaction_level:n.payload.redaction_level}:"heartbeat"===n.event_type?{...v,server_time_ms:n.payload.server_time_ms,message:n.payload.message}:"answer_finish"===n.event_type?{...v,status:n.payload.status,finish_reason:n.payload.finish_reason,usage:n.payload.usage}:{...v,...n.payload})}));switch(t.event_type){case"ack":return{state:function(e,t,r){let i=t.payload.local_message_id,n=t.payload.query_message_id,a=t.payload.message_id,s=rP(t.payload.query_message)?t.payload.query_message:void 0,o=(null==s?void 0:s.content)||"",l=e.messages;if(i&&n){let e=l.find(e=>e.localMessageId===i);e?l=l.map(t=>t===e?{...t,messageId:n,followUpContent:r}:t):o&&(l=[...l,{messageId:n,localMessageId:i,requestId:t.request_id,traceId:t.trace.trace_id,followUpContent:r,role:"user",contentType:"text",text:o,blocks:[{blockId:`block_text_${n}`,type:"text",text:o}],status:"completed",createdAtMs:t.created_at_ms}])}return{...e,activeRequestId:t.request_id,activeReplyMessageId:a||e.activeReplyMessageId,messages:l}}(I,t,r.followUpContent)};case"message_start":return{state:(s=I,y=(o=t).payload.message_id||o.reply_message_id||n2("reply"),{...s,activeReplyMessageId:y,messages:a_(s.messages,y,o.created_at_ms,o.request_id,o.trace.trace_id)})};case"text_delta":return{state:function(e,t){let r=t.reply_message_id??e.activeReplyMessageId;if(!r)return e;let i=t.payload.block_id||`block_text_${t.seq}`,n=t.payload.delta||"",a=t.payload.op||"append";if("append"!==a&&"replace"!==a)return e;let s=a_(e.messages,r,t.created_at_ms,t.request_id,t.trace.trace_id);return{...e,messages:aS(s,r,e=>({...e,text:"replace"===a?n:`${e.text}${n}`,blocks:function(e,t,r,i){if(!e.find(e=>"text"===e.type&&e.blockId===t)){let n=e[e.length-1];return"append"===i&&(null==n?void 0:n.type)==="text"?e.map(e=>e===n?{...e,text:`${e.text}${r}`}:e):[...e,{blockId:t,type:"text",text:r}]}return e.map(e=>"text"===e.type&&e.blockId===t?{...e,text:"replace"===i?r:`${e.text}${r}`}:e)}(e.blocks,i,n,a)}))}}(I,t)};case"card_delta":return aj(I,t.payload,t);case"content_block":return{state:function(e,t){let r=t.reply_message_id??e.activeReplyMessageId;if(!r)return e;let i=function(e,t){for(let[r,i]of(Array.isArray(e.content_block)?e.content_block:Array.isArray(e.contentBlock)?e.contentBlock:[]).entries()){let n=function(e){if(!rP(e))return;let t=rP(e.content)?e.content:e,r=rP(t.permission_apply_block)?t.permission_apply_block:rP(t.permissionApplyBlock)?t.permissionApplyBlock:void 0;return r?("string"==typeof r.permission_data?r.permission_data:"")||("string"==typeof r.permissionData?r.permissionData:""):""}(i),a=ay(n);if(!a)continue;let s=(rP(i)&&"string"==typeof i.block_id?i.block_id:"")||(rP(i)&&"string"==typeof i.blockId?i.blockId:"")||`permission_apply_${t.seq}_${r}`;return{blockId:s,card:{card_id:s,card_type:"permission_apply",fallback_text:"需要授权后继续",render_data:{grantingData:a,permissionData:n},title:ab(a)},op:e.op||"append"}}}(t.payload,t);if(!i||"append"!==i.op&&"replace"!==i.op)return e;let n=a_(e.messages,r,t.created_at_ms,t.request_id,t.trace.trace_id);return{...e,messages:aS(n,r,e=>({...e,contentType:"mixed",blocks:ax(e.blocks,i.blockId,i.card,i.op)}))}}(I,t)};case"tool_call":return function(e,t,r){let i=t.payload.tool_call_id,n=t.payload.tool_name,a=t.payload.server_id||"",s=t.payload.arguments_json||"",o=t.reply_message_id??e.activeReplyMessageId??n2("reply");if(!i||!n)return{state:aR(e,{id:n2("trace"),timestamp:Date.now(),payload:{event:"tool_call_ignored",request_id:t.request_id,trace_id:t.trace.trace_id,tool_call_id:i,tool_name:n,reason:i?"missing_tool_name":"missing_tool_call_id",tool_call_payload:t.payload,summary:"Tool call event is missing required fields and cannot be executed"}})};let l=t.payload.requires_user_approval??!1,d=l?"pending_approval":r.hasToolExecutor?"running":"pending",u={requestId:t.request_id,runId:r.runId,replyMessageId:o,toolCallId:i,toolName:n,serverId:a,appKey:t.payload.app_key,arguments:rP(t.payload.arguments)?t.payload.arguments:r4(s),argumentsJson:s,mcpHeaders:function(e){if(!rP(e))return;let t=Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1]));return Object.keys(t).length>0?t:void 0}(t.payload.headers),status:d,createdAtMs:t.created_at_ms,updatedAtMs:t.created_at_ms,trace:t.trace,requiresUserApproval:l,timeoutMs:t.payload.timeout_ms,deadlineMs:t.payload.deadline_ms},c=aS(a_(e.messages,o,t.created_at_ms,t.request_id,t.trace.trace_id),o,e=>({...e,toolCalls:aO(e.toolCalls??[],u)})),p={...e,messages:c,toolCalls:[...e.toolCalls.filter(e=>e.toolCallId!==i),u]};return r.hasToolExecutor?{state:p,toolCall:u}:{state:aR(p,{id:n2("trace"),timestamp:Date.now(),payload:{event:"tool_executor_missing",request_id:u.requestId,trace_id:u.trace.trace_id,tool_call_id:i,tool_name:n,summary:"No local simulator tool executor is configured"}})}}(I,t,r);case"tool_status":return{state:function(e,t){let r=t.payload.tool_call_id,i=function(e){switch(e){case"SUCCESS":return"succeeded";case"FAILED":return"failed";case"RUNNING":return"running";case"TIMEOUT":return"timeout";case"CANCELLED":return"cancelled";case"REJECTED":return"rejected";default:return""}}(t.payload.status||"");if(!r||!i)return e;let n=t.payload.progress,a=t.payload.message,s=t.payload.error?aA(t.payload.error,"tool_execute"):void 0,o=aL(e,r,{status:i,updatedAtMs:t.created_at_ms,progress:n,message:a,error:s}),l=o.toolCalls.find(e=>e.toolCallId===r);return l?{...o,messages:aS(o.messages,l.replyMessageId,e=>({...e,toolCalls:aO(e.toolCalls??[],l)}))}:o}(I,t)};case"trace_event":case"debug":default:return{state:I};case"heartbeat":return{state:(l=I,d=t,{...l,lastHeartbeatMs:d.payload.server_time_ms??d.created_at_ms})};case"answer_finish":return{state:(u=I,c=t,{...u,answerFinish:{messageId:c.reply_message_id,status:c.payload.status,finishReason:c.payload.finish_reason,usage:rP(c.payload.usage)?c.payload.usage:void 0,createdAtMs:c.created_at_ms,trace:c.trace,payload:c.payload}})};case"message_finish":return{state:function(e,t){let r=t.payload.message_id||t.reply_message_id;if(!r)return e;let i=t.payload.status||"completed";return{...e,messages:aS(e.messages,r,e=>({...e,status:function(e){switch(e){case"completed":case"finished":default:return"completed";case"cancelled":case"interrupted":return"interrupted";case"failed":case"error":return"failed"}}(i)}))}}(I,t)};case"reply_finish":return{state:(p=I,w="completed"===(b=t.payload.status||"completed")||"finished"===b?"completed":"cancelled"===b?"cancelled":"error",{...p,activeRequestId:void 0,activeReplyMessageId:void 0,messages:aP(p.messages,w),streamStatus:w})};case"stream_error":return{state:(h=I,_=aA((m=t).payload.error??m.payload,m.payload.stage||"stream"),{...h,activeRequestId:void 0,error:_,messages:aP(h.messages,"error"),streamStatus:"error"})}}}(this.state.simulator,e,{followUpContent:r,hasToolExecutor:!!this.simulatorToolExecutor,runId:t.id}),d=l&&!this.receivedSimulatorLocationDirectiveCardIds.has(l.cardId)?l:void 0;if(d&&this.receivedSimulatorLocationDirectiveCardIds.add(d.cardId),this.updateSimulatorState(()=>d?{...a,locationDirective:d}:a),d?this.appendSimulatorDebugEvent({category:"card",event:"simulator_location_directive_received",card_id:d.cardId,request_id:d.requestId,source_tool_call_id:d.sourceToolCallId,tool_name:d.toolName,trace_id:e.trace.trace_id}):l&&this.appendSimulatorDebugEvent({category:"card",event:"simulator_location_directive_loop_prevented",card_id:l.cardId,reason:"duplicate_card_id",request_id:l.requestId,tool_name:l.toolName,trace_id:e.trace.trace_id}),(null==o?void 0:o.status)==="not_found"&&this.appendSimulatorDebugEvent({category:"card",event:"simulator_history_card_refresh_skipped",reason:"card_not_found",request_id:e.request_id,trace_id:e.trace.trace_id,card_id:o.cardId}),s){let e=this.withFallbackToolCallServerId(s);e.requiresUserApproval?t.pendingApprovalToolCallIds.add(e.toolCallId):this.executeSimulatorToolCall(e,t)}}async executeSandboxToolCallOnce(e){let t=e.tool_call,r=Date.now(),i={trace_id:`bridge_${e.request_id}`,component:"sandbox_bridge",stage:"calltool_execute",sampled:!0},n={appKey:t.app_key,arguments:JSON.parse(t.arguments_json),argumentsJson:t.arguments_json,createdAtMs:r,deadlineMs:t.deadline_ms,mcpHeaders:t.headers,replyMessageId:`bridge_reply_${e.request_id}`,requestId:e.request_id,serverId:t.server_id,status:"running",timeoutMs:t.timeout_ms,toolCallId:t.tool_call_id,toolName:t.tool_name,trace:i,updatedAtMs:r};this.updateSimulatorState(e=>({...e,toolCalls:[...e.toolCalls,n]})),this.appendSimulatorDebugEvent({event:"sandbox_tool_call_started",request_id:n.requestId,trace_id:i.trace_id,tool_call_id:n.toolCallId,app_key:n.appKey,server_id:n.serverId,tool_name:n.toolName,arguments_json:n.argumentsJson,deadline_ms:n.deadlineMs,timeout_ms:n.timeoutMs});let a=Date.now(),s=t.deadline_ms<=a?{status:"timeout",error:a1("TOOL_EXEC_TIMEOUT","Sandbox tool call deadline has expired")}:await this.runSimulatorToolCall(n),o=this.createToolExecutorInput(n);try{await this.submitSandboxToolResultWithRetry(o,s,a)}catch(t){let e=aA(t,"tool_result_submit");throw this.updateToolCall(n.toolCallId,{error:e,resultSummary:e.message,status:"failed",updatedAtMs:Date.now()}),t}return this.updateToolCall(n.toolCallId,{error:s.error,isMiniApp:s.miniapp&&"boolean"==typeof s.miniapp.is_mini_app?s.miniapp.is_mini_app:void 0,resultSummary:a7(s),status:s.status,structuredResultSummary:s.result,updatedAtMs:Date.now()}),this.appendSimulatorDebugEvent({event:"sandbox_tool_call_reported",request_id:n.requestId,trace_id:i.trace_id,tool_call_id:n.toolCallId,app_key:n.appKey,server_id:n.serverId,tool_name:n.toolName,status:s.status,elapsed_ms:Date.now()-a,raw_mcp_result_json:s.raw_mcp_result_json}),{reported:!0,requestId:n.requestId,toolCallId:n.toolCallId}}withFallbackToolCallServerId(e){var t,r;if(e.serverId)return e;let i=this.lastResolvedSimulatorMcpServers,n=(null==(t=i.find(t=>t.tools.some(t=>t.name===e.toolName)))?void 0:t.server_id)||(null==(r=i[0])?void 0:r.server_id)||"local_mcp";return this.appendSimulatorDebugEvent({event:"tool_call_server_id_fallback",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,server_id:n,summary:"Tool call event has no server_id; falling back to a locally resolved MCP server"}),this.updateToolCall(e.toolCallId,{serverId:n}),{...e,serverId:n}}async runSimulatorToolCall(e,t){if(!this.simulatorToolExecutor){let e=a1("TOOL_EXECUTOR_UNAVAILABLE","No local simulator tool executor is configured");return{error:e,result:{error:e.message},status:"failed"}}try{return await a2({executor:this.simulatorToolExecutor,input:this.createToolExecutorInput(e),record:e,signal:t})}catch(t){let e=aA(t,"tool_execute");return{status:"TOOL_EXEC_TIMEOUT"===e.code?"timeout":"TOOL_EXEC_CANCELLED"===e.code||aT(t)?"cancelled":"failed",error:e}}}async executeSimulatorToolCall(e,t){if(t&&!this.isSimulatorRunCurrent(t))return;let r=Date.now(),i=this.createToolExecutorInput(e),n=t?new AbortController:void 0;t&&n&&t.toolAbortControllers.add(n);let a=await this.runSimulatorToolCall(e,null==n?void 0:n.signal);try{if(t&&!this.isSimulatorRunCurrent(t))return void this.appendSimulatorDebugEvent({event:"tool_result_submit_skipped",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,reason:"stale_or_cancelled_run"});if(await this.submitExecutedToolResult(i,a,r,null==n?void 0:n.signal),t&&!this.isSimulatorRunCurrent(t))return;this.updateToolCall(e.toolCallId,{status:a.status,updatedAtMs:Date.now(),error:a.error,resultSummary:a7(a),structuredResultSummary:a.result,isMiniApp:a.miniapp&&"boolean"==typeof a.miniapp.is_mini_app?a.miniapp.is_mini_app:void 0})}catch(i){if(t&&!this.isSimulatorRunCurrent(t))return void this.appendSimulatorDebugEvent({event:"tool_result_submit_skipped",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,reason:"stale_or_cancelled_run"});let r=aA(i,"tool_result_submit");this.appendSimulatorDebugEvent({event:"tool_result_submit_failed",trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,summary:r6(i),error:r}),this.updateToolCall(e.toolCallId,{status:"failed",updatedAtMs:Date.now(),error:r}),this.failActiveSimulatorStream(r)}finally{t&&n&&(t.toolAbortControllers.delete(n),this.releaseSimulatorRun(t))}}uploadSimulatorImage(e,t){return this.assertActive(),as({endpoint:this.state.simulator.endpoint,fetcher:this.simulatorFetcher,file:e,signal:t})}createToolExecutorInput(e){let t={trace_id:e.trace.trace_id,span_id:n2("span_tool_execute"),parent_span_id:e.trace.span_id,component:"local_mcp",stage:"tool_execute",sampled:e.trace.sampled};return{requestId:e.requestId,replyMessageId:e.replyMessageId,toolCallId:e.toolCallId,toolName:e.toolName,serverId:e.serverId,appKey:e.appKey||this.simulatorAppKey||se(this.state.manifest.raw,this.state.manifest.appId)||void 0,arguments:e.arguments,argumentsJson:e.argumentsJson,headers:e.mcpHeaders,manifest:this.state.manifest.raw,timeoutMs:e.timeoutMs,deadlineMs:e.deadlineMs,trace:t}}async resolveSimulatorManifestForQuery(e,t,r,i){let n=Date.now(),a=void 0!==t.manifest,s=a?"query_option":void 0===this.simulatorManifest?"loaded_manifest":"debugger_option";this.appendSimulatorDebugEvent({event:"simulator_manifest_load_started",trace_id:e,source:s});try{let o=a?{found:!1,value:void 0}:this.takeSimulatorManifestStateValue(),l=a?t.manifest:o.found?o.value:"function"==typeof this.simulatorManifest?await this.simulatorManifest(i):this.simulatorManifest,d=l?sr(r,l):r;return this.appendSimulatorDebugEvent({event:"simulator_manifest_loaded",trace_id:e,elapsed_ms:Date.now()-n,source:s,manifest:d}),d}catch(t){return i.throwIfAborted(),this.appendSimulatorDebugEvent({event:"simulator_manifest_load_failed",trace_id:e,elapsed_ms:Date.now()-n,error:r6(t),source:s}),r}}async resolveSimulatorSkillsForQuery(e,t,r){let i=Date.now(),n=void 0===t.skills?"debugger_option":"query_option";this.appendSimulatorDebugEvent({event:"simulator_skill_load_started",trace_id:e,source:n});try{let a=t.skills??("function"==typeof this.simulatorSkills?await this.simulatorSkills(r):this.simulatorSkills)??[];return this.appendSimulatorDebugEvent({event:a.length>0?"simulator_skill_loaded":"simulator_skill_empty",trace_id:e,elapsed_ms:Date.now()-i,skills_length:a.reduce((e,t)=>e+t.content.length,0),skill_paths:a.map(e=>e.relativePath),source:n}),a}catch(t){return null==r||r.throwIfAborted(),this.appendSimulatorDebugEvent({event:"simulator_skill_load_failed",trace_id:e,elapsed_ms:Date.now()-i,error:r6(t),source:n}),[]}}async resolveDirectToolCallServerId(e,t,r){var i;let n=null==t?void 0:t.trim();if(n)return n;let a=this.state.manifest.raw,s=this.simulatorAppKey||se(a,this.state.manifest.appId),o=this.simulatorAppName||st(a,this.state.manifest.name),l=this.simulatorMcpServerProvider?await this.simulatorMcpServerProvider({trace:r,appKey:s,appName:o,manifest:a}):this.simulatorMcpServers,d=l.find(t=>t.tools.some(t=>t.name===e));return(null==d?void 0:d.server_id)??(null==(i=l[0])?void 0:i.server_id)??"local_mcp"}getSimulatorToolCall(e){let t=this.state.simulator.toolCalls.find(t=>t.toolCallId===e);if(!t)throw Error(`Unknown simulator tool call: ${e}`);return t}getSimulatorToolCallRun(e){let t=this.activeSimulatorRun;if(t&&this.isSimulatorRunCurrent(t))return void 0===e.runId||e.runId===t.id?t:void 0}cancelStaleSimulatorToolCall(e){let t=a1("TOOL_EXEC_CANCELLED","Tool call cancelled because its simulator run is no longer active");this.appendSimulatorDebugEvent({event:"tool_result_submit_skipped",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,reason:"stale_or_cancelled_run"}),this.updateToolCall(e.toolCallId,{status:"cancelled",updatedAtMs:Date.now(),error:t,resultSummary:t.message})}async submitSandboxToolResultWithRetry(e,t,r){let i;for(let n=1;n<=2;n+=1)try{await this.submitExecutedToolResult(e,t,r,void 0,n);return}catch(t){if(i=t,2===n||void 0!==e.deadlineMs&&Date.now()>=e.deadlineMs)throw t;this.appendSimulatorDebugEvent({event:"sandbox_tool_result_report_retry",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,attempt:n+1,error:r6(t)})}throw i}async submitExecutedToolResult(e,t,r,i){let n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1,a=Date.now();await this.submitToolResult({...e,...t,timing:{started_at_ms:r,ended_at_ms:a,duration_ms:a-r,attempt:n}},i)}updateToolCall(e,t){this.updateSimulatorState(r=>aL(r,e,t))}failActiveSimulatorStream(e){this.activeSimulatorRun&&this.abortSimulatorRun(this.activeSimulatorRun),this.updateSimulatorState(t=>({...t,activeRequestId:void 0,activeReplyMessageId:void 0,error:e,messages:t.messages.map(e=>"assistant"===e.role&&"streaming"===e.status?{...e,status:"failed"}:e),streamStatus:"error"}))}getSimulatorQueryFailureDiagnosis(e,t){let r=new Set;for(let t of this.state.simulator.traceEvents){let i=t.payload,n=a5["string"==typeof i.event?i.event:""];n&&function(e){var t;return e.trace_id||(null==(t=e.trace)?void 0:t.trace_id)||""}(i)===e&&"Failed to fetch"===(i.error||"")&&r.add(n)}if(r.size>=3)return{code:"DEBUG_SERVER_UNREACHABLE",confidence:"high",failed_services:[...r],summary:"调试 Dev Server 或本机网络不可达",suggestion:"检查调试 Dev Server 是否运行,以及浏览器能否访问当前调试端口。"};let i=an(t),n="number"==typeof(null==i?void 0:i.status)?i.status:void 0;return 404===n?{code:"SIMULATOR_ENDPOINT_NOT_FOUND",confidence:"high",status:n,summary:"模拟器接口未配置或路由不存在",suggestion:"检查 simulator、manifest、skill 或 MCP 的接口地址与代理路由。"}:void 0!==n&&n>=500?{code:"SIMULATOR_ENDPOINT_SERVER_ERROR",confidence:"high",status:n,summary:`模拟器接口服务异常(HTTP ${n})`,suggestion:"接口已可达,但服务端或其上游依赖异常;请查看响应内容和服务端日志。"}:"Failed to fetch"===r6(t)?{code:"SIMULATOR_ENDPOINT_UNREACHABLE",confidence:"unknown",summary:"无法连接模拟器接口",suggestion:"可能是接口服务未启动、端口不可达、浏览器网络异常或 CORS 被拦截。"}:void 0}appendSimulatorDebugEvent(e){let t=r0(e),r={display:ah(e),id:n2("trace"),timestamp:Date.now(),payload:function(e,t){if(!rP(e))return{};let r=am(e);return{...e,category:r.category,detail:r.detail,phase:r.phase,title:r.title,log_ids:t.length>0?t:void 0}}(e,t)};this.updateSimulatorState(e=>{var t;return{...e,traceEvents:[...e.traceEvents,{...r,order:((null==(t=e.traceEvents.at(-1))?void 0:t.order)??e.traceEvents.length)+1}].slice(-200)}})}updateSimulatorState(e){this.setState({...this.state,simulator:e(this.state.simulator)})}setState(e){for(let t of(this.state=e,this.listeners))t(this.state)}assertActive(){if(this.destroyed)throw Error("WebSdkDebugger has been destroyed")}}function sn(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;return e.getSystem().theme??("function"==typeof matchMedia&&matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light")}function sa(e,t){let r="function"==typeof matchMedia?matchMedia("(prefers-color-scheme: dark)"):void 0,i=e.subscribe("theme",t);return null==r||r.addEventListener("change",t),()=>{i(),null==r||r.removeEventListener("change",t)}}let ss="iphone-13",so=[{key:ss,label:"iPhone 13",width:390,height:844,density:3,radius:47,homeIndicator:!0,statusBarHeight:47,safeArea:{top:47,bottom:34,left:0,right:0}},{key:"iphone-17-pro-max",label:"iPhone 17 Pro Max",width:440,height:956,density:3,radius:55,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-17-pro",label:"iPhone 17 Pro",width:402,height:874,density:3,radius:50,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-17",label:"iPhone 17",width:402,height:874,density:3,radius:50,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-air",label:"iPhone Air",width:420,height:912,density:3,radius:52,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16-pro-max",label:"iPhone 16 Pro Max",width:440,height:956,density:3,radius:55,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16-pro",label:"iPhone 16 Pro",width:402,height:874,density:3,radius:50,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16-plus",label:"iPhone 16 Plus",width:430,height:932,density:3,radius:55,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16",label:"iPhone 16",width:393,height:852,density:3,radius:47,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16e",label:"iPhone 16e",width:390,height:844,density:3,radius:44,homeIndicator:!0,statusBarHeight:47,safeArea:{top:47,bottom:34,left:0,right:0}},{key:"iphone-15-pro-max",label:"iPhone 15 Pro Max",width:430,height:932,density:3,radius:55,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-15",label:"iPhone 15",width:393,height:852,density:3,radius:47,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-14-plus",label:"iPhone 14 Plus",width:428,height:926,density:3,radius:47,homeIndicator:!0,statusBarHeight:47,safeArea:{top:47,bottom:34,left:0,right:0}},{key:"iphone-13-mini",label:"iPhone 13 mini",width:375,height:812,density:3,radius:44,homeIndicator:!0,statusBarHeight:50,safeArea:{top:50,bottom:34,left:0,right:0}},{key:"iphone-se",label:"iPhone SE",width:375,height:667,density:2,radius:0,homeIndicator:!1,statusBarHeight:20,safeArea:{top:20,bottom:0,left:0,right:0}},{key:"pixel-8-pro",label:"Pixel 8 Pro",width:448,height:998,density:3,radius:30,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"pixel-8",label:"Pixel 8",width:412,height:915,density:2.625,radius:28,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"pixel-7",label:"Pixel 7",width:412,height:915,density:2.625,radius:28,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"galaxy-s24",label:"Galaxy S24",width:360,height:780,density:3,radius:32,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"galaxy-s24-ultra",label:"Galaxy S24 Ultra",width:384,height:854,density:3.75,radius:18,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"galaxy-z-fold-5-cover",label:"Galaxy Z Fold 5 Cover",width:344,height:882,density:3,radius:30,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"galaxy-z-fold-5-inner",label:"Galaxy Z Fold 5 Inner",width:690,height:829,density:2.625,radius:24,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"ipad-mini",label:"iPad mini",width:744,height:1133,density:2,radius:18,homeIndicator:!0,statusBarHeight:24,safeArea:{top:24,bottom:20,left:0,right:0}},{key:"ipad-pro-11",label:'iPad Pro 11"',width:834,height:1194,density:2,radius:18,homeIndicator:!0,statusBarHeight:24,safeArea:{top:24,bottom:20,left:0,right:0}}],sl=[{key:"100",label:"100%",scale:1},{key:"85",label:"85%",scale:.85},{key:"75",label:"75%",scale:.75},{key:"50",label:"50%",scale:.5},{key:"fit",label:"自适应",scale:.88}],sd={key:"mobile-393",label:"393px",width:393,density:3};function su(e){let t=/^custom-([1-9]\d{0,3})x([1-9]\d{0,3})$/.exec(e);if(t){let r=Number(t[1]),i=Number(t[2]);return{key:e,label:`自定义 ${r} \xd7 ${i}`,width:r,height:i,density:1,radius:0,homeIndicator:!1,statusBarHeight:0,safeArea:{top:0,bottom:0,left:0,right:0}}}return so.find(t=>t.key===e)??so.find(e=>e.key===ss)??so[0]}let sc="devtools_web";function sp(e){return e.key.startsWith("iphone")||e.key.startsWith("ipad")}function sh(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:so["0"],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=sp(e);return{debugger:"web-sdk",channel:"debug",appTheme:sn(),density:e.density,screenWidth:e.width,screenHeight:e.height,containerWidth:e.width,containerHeight:e.height,statusBarHeight:e.statusBarHeight,safeArea:{marginTop:e.safeArea.top,marginBottom:e.safeArea.bottom,marginLeft:e.safeArea.left,marginRight:e.safeArea.right},topHeight:e.safeArea.top,bottomHeight:e.safeArea.bottom,devicePlatform:r?"iOS":"Android",os:r?"iOS":"Android",osVersion:"",deviceBrand:sp(e)?"Apple":e.key.startsWith("galaxy-")?"Samsung":e.key.startsWith("pixel-")?"Google":"Browser",deviceModel:e.label,screenOrientation:e.width>e.height?"landscape":"portrait",isLandscape:e.width>e.height,...t,platform:sc}}function sm(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:sd,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return{...sh(e.device??so["0"]),density:e.density,deviceModel:`Widget preview ${e.label}`,...t,platform:sc}}function sg(e,t){try{let e=t.trim()?JSON.parse(t):{};if(rP(e))return e;throw Error("expected a JSON object")}catch(t){throw Error(`${e}: ${t.message}`)}}function sf(e){let{name:t,readSample:r}=e,i=`doubao.on${t}Change`,n="DeviceMotion"===t?"DeviceMotionListening":t,a=`${"DeviceMotion"===t?"device motion":t.toLowerCase()} is not available`,s=new WeakMap;return{[`doubao.start${n}`]:{handler:(e,t)=>{var n,o;let l,d=(null==(n=e.params)?void 0:n.interval)??"normal";if(!["normal","ui","game"].includes(d))throw new w("invalid interval",104);if(!r().available)throw new w(a,103);let u=null==t?void 0:t.events;if(!u)throw new w("sensor event controller is unavailable",102);null==(o=s.get(u))||o();let c="game"===d?20:"ui"===d?62.5:200,p=!1,h=()=>{void 0!==l&&(clearInterval(l),l=void 0),s.delete(u),p=!0},m=u.onDestroy(h);if(p)throw new w("sensor event controller is destroyed",102);return s.set(u,()=>{h(),m()}),l=setInterval(()=>{let{available:e,params:t}=r();e&&u.emit(i,t)},c),_(e,{})}},[`doubao.stop${n}`]:{handler:(e,t)=>{if(null==t?void 0:t.events){var r;null==(r=s.get(t.events))||r()}return _(e,{})}}}}function sv(e){return{[`doubao.on${e}Change`]:()=>{}}}function sy(e){let{name:t,getSample:r}=e;return sf({name:t,readSample:()=>{let{available:e,x:t,y:i,z:n}=r();return{available:e,params:{x:t,y:i,z:n,timestamp:Math.round(1e6*performance.now())}}}})}let sb="wsd:runtime-console",sw=new WeakMap;function s_(e,t){if(!e.dispatchEvent(new CustomEvent(sb,{cancelable:!0,detail:t})))return;let r=sw.get(e)??[];r.push(t),sw.set(e,r)}class sS{state={interruption:"none",volumeFactor:1};listeners=new Set;getSnapshot=()=>this.state;subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));setInterruption(e){this.update({...this.state,interruption:e})}setVolumeFactor(e){this.update({...this.state,volumeFactor:Number.isFinite(e)?Math.max(0,Math.min(1,e)):1})}update(e){if(this.state.interruption!==e.interruption||this.state.volumeFactor!==e.volumeFactor)for(let t of(this.state=e,this.listeners))t()}}let sx=new sS,sI=new sS,sk="doubao.onInnerAudioContextStateChange",sC=()=>"function"==typeof Audio;class sE extends Error{errCode;constructor(e,t){super(t),this.errCode=e}}class sN{audioId;appletId;context;onEvent;clampPlaybackRate;focus;audio;cleanup=[];destroyed=!1;pendingStart=!0;errorReported=!1;playVersion=0;playRequested=!1;interrupted=!1;unsubscribeFocus;unsubscribeNetwork;state={src:"",startTime:0,autoplay:!1,loop:!1,volume:1,playbackRate:1,currentTime:0,duration:0,paused:!0,buffered:0};constructor(e,t,r,i,n=!0,a){this.audioId=e,this.appletId=t,this.context=r,this.onEvent=i,this.clampPlaybackRate=n,this.focus=a,this.unsubscribeFocus=null==a?void 0:a.subscribe(()=>this.focusChanged())}focusChanged(){var e,t;let r=null==(e=this.focus)?void 0:e.getSnapshot().interruption;if(this.audio&&this.applyOptions(this.audio),"none"===r){this.interrupted&&(this.interrupted=!1,this.play().catch(e=>{this.playbackFailed(e instanceof Error?e.message:"inner audio play failed")}));return}let i=!this.state.paused||this.playRequested;"forced"===r?this.interrupted=!1:i&&(this.interrupted=!0),i&&(++this.playVersion,this.playRequested=!1,this.state.paused=!0,null==(t=this.audio)||t.pause())}snapshot(){let e=this.audio;return e&&(this.state.currentTime=Number.isFinite(e.currentTime)?e.currentTime:0,this.state.duration=Number.isFinite(e.duration)?e.duration:0,this.state.buffered=e.buffered.length?e.buffered.end(e.buffered.length-1):0),{audioId:this.audioId,...this.state}}emit(e,t){var r;if(!this.destroyed){if(this.onEvent)return void this.onEvent(e,this.snapshot(),t);null==(r=this.context.events)||r.emitPrivate(sk,{audioId:this.audioId,appletId:this.appletId,eventName:e,state:this.snapshot(),...t?{errCode:t.errCode,errMsg:t.message}:{}})}}update(e){for(let t of["src","startTime","autoplay","loop","volume","playbackRate"]){let r=e[t];if(void 0!==r&&("src"===t&&"string"!=typeof r||("autoplay"===t||"loop"===t)&&"boolean"!=typeof r||["startTime","volume","playbackRate"].includes(t)&&("number"!=typeof r||!Number.isFinite(r))))throw new sE(-2012,"inner audio params are invalid")}let t={...this.state};"string"==typeof e.src&&(t.src=e.src.trim()),"number"==typeof e.startTime&&(t.startTime=Math.max(0,e.startTime)),"number"==typeof e.volume&&(t.volume=Math.max(0,Math.min(1,e.volume))),"number"==typeof e.playbackRate&&(t.playbackRate=this.clampPlaybackRate?Math.max(.5,Math.min(2,e.playbackRate)):e.playbackRate),"boolean"==typeof e.autoplay&&(t.autoplay=e.autoplay),"boolean"==typeof e.loop&&(t.loop=e.loop);let r=t.src!==this.state.src;if(r&&(this.release(),Object.assign(t,{currentTime:0,duration:0,buffered:0,paused:!0}),this.pendingStart=!0),this.state=t,this.audio&&this.applyOptions(this.audio),r&&t.autoplay||!0===e.autoplay)return this.play()}applyOptions(e){var t;e.loop=this.state.loop;let r=(null==(t=this.focus)?void 0:t.getSnapshot().volumeFactor)??1;e.volume=this.state.volume*r,e.playbackRate=this.state.playbackRate}async play(){if(!this.state.src)throw new sE(-2003,"inner audio src is empty");if(this.focus&&"none"!==this.focus.getSnapshot().interruption)throw new sE(-2009,"inner audio playback is interrupted");if(nq(this.state.src)&&!nD())throw new sE(-2007,nO);let e=++this.playVersion;if(this.errorReported=!1,this.interrupted=!1,!this.audio){let t;this.playRequested=!0;try{if(!this.state.src.startsWith("appletfile:")&&!/^https?:\/\//i.test(this.state.src))throw Error("unsupported audio source");if(t=await rV(this.state.src,this.context),this.destroyed||e!==this.playVersion)return;this.state.src.startsWith("appletfile:")||new URL(t)}catch{if(this.destroyed||e!==this.playVersion)return;throw this.playRequested=!1,new sE(-2004,"inner audio src is invalid")}let r=new Audio;this.audio=r,this.applyOptions(r);let i=(e,t)=>{r.addEventListener(e,t),this.cleanup.push(()=>r.removeEventListener(e,t))};for(let e of(i("canplay",()=>{this.pendingStart&&(this.pendingStart=!1,this.state.startTime>0&&(r.currentTime=Math.min(this.state.startTime,Number.isFinite(r.duration)?r.duration:this.state.startTime))),this.emit("canplay")}),i("playing",()=>{this.focus&&"none"!==this.focus.getSnapshot().interruption?r.pause():(this.playRequested=!1,this.state.paused=!1,this.emit("play"))}),i("pause",()=>{r.ended||(this.state.paused=!0,this.emit("pause"))}),i("ended",()=>{this.playRequested=!1,this.state.paused=!0,this.pendingStart=!0,this.emit("ended")}),["waiting","timeupdate","seeking","seeked"]))i(e,()=>this.emit(e));i("error",()=>{var e;this.playRequested=!1,this.state.paused=!0,this.playbackFailed((null==(e=r.error)?void 0:e.message)||"inner audio play failed")}),nq(this.state.src)&&(this.unsubscribeNetwork=n$(()=>{this.release(),this.state.paused=!0,this.playbackFailed(nO)})),r.preload="auto",r.src=t,r.load()}let t=this.audio;this.playRequested=!0,t.play().catch(r=>{this.audio!==t||this.destroyed||e!==this.playVersion||r instanceof DOMException&&"AbortError"===r.name||(this.state.paused=!0,this.playRequested=!1,this.playbackFailed(r instanceof Error?r.message:"inner audio play failed"))})}playbackFailed(e){this.errorReported||(this.errorReported=!0,this.emit("error",new sE(-2007,e)))}pause(){var e;this.interrupted=!1,this.playRequested=!1,++this.playVersion,this.state.paused=!0,null==(e=this.audio)||e.pause()}stop(){this.release(),this.state.currentTime=0,this.state.paused=!0,this.pendingStart=!0,this.emit("stop")}seek(e){if("number"!=typeof e||!Number.isFinite(e)||e<0)throw new sE(-2012,"invalid seek position");if(!this.audio)throw new sE(-2005,"inner audio player unavailable");try{this.pendingStart=!1,this.audio.currentTime=Math.min(e,Number.isFinite(this.audio.duration)?this.audio.duration:e)}catch{throw new sE(-2006,"inner audio seek failed")}}release(){var e;for(let t of(null==(e=this.unsubscribeNetwork)||e.call(this),this.unsubscribeNetwork=void 0,this.interrupted=!1,this.playRequested=!1,++this.playVersion,this.cleanup.splice(0)))t();let t=this.audio;this.audio=void 0,t&&(t.pause(),t.removeAttribute("src"),t.load())}destroy(){var e;this.destroyed||(this.release(),null==(e=this.unsubscribeFocus)||e.call(this),this.unsubscribeFocus=void 0,this.state.paused=!0,this.state.currentTime=0,this.emit("destroy"),this.destroyed=!0)}}let sT="doubao.onBackgroundAudioManagerStateChange",sA=()=>"function"==typeof Audio,sM=["title","epname","singer","coverImgUrl","webUrl"],sR=["play","pause","stop","seekto","previoustrack","nexttrack"];function sj(e){return e instanceof sE?{errCode:({[-2003]:-1001,[-2004]:-1002,[-2005]:-1004,[-2006]:-1003,[-2007]:-1002,[-2009]:-2001,[-2012]:-1007})[e.errCode]??e.errCode,errMsg:e.message.replaceAll("inner audio","background audio")}:{errCode:-1002,errMsg:e instanceof Error?e.message:"background audio play failed"}}let sP=new class{focus;player;appletId="";owner;unbind;metadata={};state=Object.freeze({paused:!0,playbackRate:1});listeners=new Set;callers=new Map;ownsMediaSession=!1;stopped=!0;mediaMetadataKey;constructor(e=sI){this.focus=e}getSnapshot=()=>this.state;subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));attach(e){var t,r,i,n;let a=(null==(t=e.navigation)?void 0:t.getPackageInfo().appId)??(null==(i=e.globalProps)||null==(r=i.packageInfo)?void 0:r.appId);if("string"!=typeof a||!a)throw new sE(-1008,"background audio appletId is empty");if(null==(n=e.applicationLifecycle)?void 0:n.signal.aborted)throw new sE(-1008,"background audio runtime is unavailable");let s=e.events;s&&!this.callers.has(s)&&(this.callers.set(s,a),s.onDestroy(()=>this.callers.delete(s)));let o=e.applicationLifecycle,l=(null==o?void 0:o.owner)??s;if(!l||!sA())throw new sE(-1004,"background audio player unavailable");if(!this.player||this.appletId!==a){this.reset(),this.appletId=a,this.owner=l,this.player=new sN("background",a,e,(e,t,r)=>{"destroy"!==e&&this.publish(e,t,r&&sj(r))},!1,this.focus);let t=()=>{this.owner===l&&this.reset()};o?(o.signal.addEventListener("abort",t,{once:!0}),this.unbind=()=>o.signal.removeEventListener("abort",t)):this.unbind=null==s?void 0:s.onDestroy(t),this.refresh()}}update(e){var t;for(let t of sM)if(void 0!==e[t]&&"string"!=typeof e[t])throw new sE(-1007,"background audio params are invalid");if(void 0!==e.playbackRate&&("number"!=typeof e.playbackRate||!Number.isFinite(e.playbackRate)||e.playbackRate<=0))throw new sE(-1007,"background audio params are invalid");for(let r of(null==(t=this.player)||t.update({src:e.src,startTime:e.startTime,playbackRate:e.playbackRate}),sM))"string"==typeof e[r]&&(this.metadata[r]=e[r]);this.refresh(),this.updateMediaSession()}async control(e,t){if(!this.player)throw new sE(-1004,"background audio player unavailable");switch(e){case"play":this.installMediaSession(),await this.player.play();break;case"pause":this.player.pause();break;case"stop":this.player.stop();break;case"seek":{if(!this.state.src)return;let e="number"==typeof t&&Number.isFinite(t)?Math.max(0,t):0;this.player.seek(e);break}case"prev":case"next":this.publish(e);break;default:throw new sE(-1006,"background audio action is invalid")}this.refresh(),this.updateMediaSession()}refresh(e){var t;let r=e??(null==(t=this.player)?void 0:t.snapshot());for(let e of(this.state=Object.freeze({...this.metadata,...r?{src:r.src,startTime:r.startTime,currentTime:r.currentTime,duration:r.duration,paused:r.paused,buffered:r.buffered,playbackRate:r.playbackRate}:{paused:!0,playbackRate:1}}),this.listeners))e()}publish(e,t,r){for(let[i,n]of("play"===e&&(this.stopped=!1),("stop"===e||"ended"===e)&&(this.stopped=!0),this.refresh(t),this.updateMediaSession(),this.callers))n===this.appletId&&i.emitPrivate(sT,{appletId:n,eventName:e,state:this.state,...r})}installMediaSession(){let e=navigator.mediaSession;if(e&&!this.ownsMediaSession)for(let t of(this.ownsMediaSession=!0,sR))try{e.setActionHandler(t,async e=>{try{await this.control("seekto"===t?"seek":"previoustrack"===t?"prev":"nexttrack"===t?"next":t,e.seekTime)}catch(e){this.publish("error",void 0,sj(e))}})}catch{}}updateMediaSession(){let e=navigator.mediaSession;if(e&&this.ownsMediaSession)try{let r=JSON.stringify([this.state.title,this.state.singer,this.state.epname,this.state.coverImgUrl]);if("function"==typeof MediaMetadata&&r!==this.mediaMetadataKey&&(e.metadata=new MediaMetadata({title:this.state.title,artist:this.state.singer,album:this.state.epname,artwork:this.state.coverImgUrl&&/^https?:\/\//i.test(this.state.coverImgUrl)?[{src:this.state.coverImgUrl}]:[]})),this.mediaMetadataKey=r,e.playbackState=this.stopped?"none":this.state.paused?"paused":"playing",this.state.duration&&this.state.duration>0){var t;null==(t=e.setPositionState)||t.call(e,{duration:this.state.duration,position:Math.min(this.state.duration,this.state.currentTime??0),playbackRate:this.state.playbackRate??1})}}catch{}}reset(){var e,t,r;null==(e=this.unbind)||e.call(this),this.unbind=void 0;let i=this.player;if(this.player=void 0,i&&(!this.stopped&&this.state.src&&this.publish("stop",{...i.snapshot(),currentTime:0,paused:!0}),i.destroy()),this.metadata={},this.owner=void 0,this.appletId="",this.ownsMediaSession&&navigator.mediaSession){for(let e of sR)try{navigator.mediaSession.setActionHandler(e,null)}catch{}navigator.mediaSession.metadata=null,navigator.mediaSession.playbackState="none";try{null==(t=(r=navigator.mediaSession).setPositionState)||t.call(r)}catch{}}this.ownsMediaSession=!1,this.stopped=!0,this.mediaMetadataKey=void 0,this.refresh()}},sL=new class{hardware;beacons=new Map;filters=[];unwatch;unregisterOwner;constructor(e=nL){this.hardware=e}start(e,t){if(!this.hardware.getBeacon().rangingAvailable)throw new w("beacon ranging is not available",116);if(!Array.isArray(e.uuids)||!e.uuids.length||e.uuids.some(e=>"string"!=typeof e||!iU(e))||void 0!==e.ignoreBluetoothAvailable&&"boolean"!=typeof e.ignoreBluetoothAvailable)throw new w("invalid or empty uuids",104);if(!this.hardware.getBeacon().locationAuthorized)throw new w("location permission denied",106);let r=this.hardware.getBluetooth();if(!r.authorized)throw new w("bluetooth permission denied",106);if(!r.available||!r.enabled)throw new w("bluetooth is unavailable or powered off",116);this.stop(),this.filters=e.uuids.map(e=>e.toLowerCase()),this.beacons.clear();let i=null==t?void 0:t.events;if(i){let e=!1;if(this.unregisterOwner=i.onDestroy(()=>{e=!0,this.stop()}),e)throw new w("beacon context is destroyed",102)}let n=()=>this.capture(),a=this.hardware.subscribe("beacon",n),s=this.hardware.subscribe("bluetooth",n);this.unwatch=()=>{a(),s()},this.capture()}capture(){let e=this.hardware.getBluetooth(),t=this.hardware.getBeacon();if(e.available&&e.enabled&&e.authorized&&t.locationAuthorized&&t.rangingAvailable)for(let e of t.beacons)this.filters.includes(e.uuid.toLowerCase())&&this.beacons.set(iq(e),{...e,uuid:e.uuid.toLowerCase()})}stop(){var e,t;null==(e=this.unwatch)||e.call(this),this.unwatch=void 0,null==(t=this.unregisterOwner)||t.call(this),this.unregisterOwner=void 0}get(){if(!this.hardware.getBluetooth().authorized||!this.hardware.getBeacon().locationAuthorized)throw new w("beacon permission denied",106);return{beacons:[...this.beacons.values()].sort((e,t)=>iq(e).localeCompare(iq(t)))}}},sO="doubao.onBLEConnectionStateChange";function sD(e,t){let r=e[t];if("string"!=typeof r||!r.trim())throw new w(`invalid ${t}`,104);return r}class sU{hardware;events;connections=new Map;pending=new Map;constructor(e,t){this.hardware=e,this.events=t}closeAll(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0];for(let e of[...this.pending.values()])e(new w("bluetooth connection closed",114));for(let t of[...this.connections.keys()])this.disconnect(t,e)}observe(e){if(!e.available||!e.enabled||!e.authorized)return void this.closeAll();for(let[t,r]of this.connections){let i=e.devices.find(e=>e.deviceId===t);if(!i){this.disconnect(t);continue}for(let e of i.services??[])for(let i of e.characteristics){let n=this.key(e.uuid,i.uuid),a=r.notifications.get(n);void 0!==a&&a!==i.value&&(r.notifications.set(n,i.value),this.publishValue(t,e.uuid,i.uuid,i.value))}}}device(e){let t=sD(e,"deviceId"),r=this.hardware.getBluetooth().devices.find(e=>e.deviceId.toLowerCase()===t.toLowerCase());if(!r)throw new w("bluetooth device not found",116);return r}connection(e){let t=this.connections.get(e.deviceId);if(!t)throw new w("ble connection not found",116);return t}uuid(e,t){let r=iz(sD(e,t));if(!r)throw new w(`invalid ${t} UUID`,104);return r}key(e,t){return`${iz(e)}|${iz(t)}`}target(e){var t;let r=this.device(e),i=this.connection(r),n=this.uuid(e,"serviceId"),a=this.uuid(e,"characteristicId"),s=null==(t=r.services)?void 0:t.find(e=>iz(e.uuid)===n);if(!s)throw new w("ble service not found",116);let o=s.characteristics.find(e=>iz(e.uuid)===a);if(!o)throw new w("ble characteristic not found",116);return{device:r,connection:i,service:s,characteristic:o}}publishValue(e,t,r,i){this.events.emit("doubao.onBLECharacteristicValueChange",{deviceId:e,serviceId:iz(t),characteristicId:iz(r),value:i})}disconnect(e){var t;let r=!(arguments.length>1)||void 0===arguments[1]||arguments[1];null==(t=this.pending.get(e))||t(new w("bluetooth connection closed",114)),this.connections.delete(e)&&r&&this.events.emit(sO,{deviceId:e,connected:!1})}connect(e){let t=this.device(e),r=this.hardware.getBluetooth();if(!r.available||!r.enabled)throw new w("bluetooth adapter is disabled",116);if(this.connections.has(t.deviceId)||this.pending.has(t.deviceId))throw new w("ble already connected or pending",118);if(void 0!==e.timeout&&("number"!=typeof e.timeout||!Number.isFinite(e.timeout)||e.timeout<=0))throw new w("invalid timeout",104);if(!t.connectable)throw new w("createBLEConnection failed",102);let i=t.connectionDelayMs??0,n=void 0===e.timeout?void 0:e.timeout;return new Promise((e,r)=>{let a=setTimeout(()=>{if(this.pending.delete(t.deviceId),void 0!==n&&n<i)return void r(new w("createBLEConnection timeout",115));let a=this.hardware.getBluetooth().devices.find(e=>e.deviceId===t.deviceId);(null==a?void 0:a.connectable)?(this.connections.set(t.deviceId,{mtu:23,notifications:new Map}),this.events.emit(sO,{deviceId:t.deviceId,connected:!0}),e()):r(new w("bluetooth device not found",116))},void 0===n?i:Math.min(i,n));this.pending.set(t.deviceId,e=>{clearTimeout(a),this.pending.delete(t.deviceId),r(e)})})}handle(e,t){switch(e){case"createBLEConnection":return this.connect(t);case"closeBLEConnection":{let e=this.device(t);if(!this.connections.has(e.deviceId)&&!this.pending.has(e.deviceId))throw new w("ble connection not found",116);this.disconnect(e.deviceId);return}case"getConnectedBluetoothDevices":{if(!Array.isArray(t.services)||t.services.some(e=>"string"!=typeof e||!iz(e)))throw new w("invalid services",104);let e=new Set(t.services.map(e=>iz(e)));return{devices:this.hardware.getBluetooth().devices.filter(t=>{var r;return this.connections.has(t.deviceId)&&(null==(r=t.services)?void 0:r.some(t=>e.has(iz(t.uuid))))}).map(e=>{let{deviceId:t,name:r}=e;return{deviceId:t,name:r}})}}case"makeBluetoothPair":{let e,r=this.device(t),i=sD(t,"pin");try{e=atob(i.replace(/\s/g,""))}catch{throw new w("invalid pin",104)}if(void 0!==t.timeout&&("number"!=typeof t.timeout||!Number.isFinite(t.timeout)||t.timeout<=0))throw new w("invalid timeout",104);if(r.paired)return;if(e!==atob(r.pin??"MDAwMDAw"))throw new w("bluetooth pair failed",102);let n=this.hardware.getBluetooth();this.hardware.setBluetooth({...n,devices:n.devices.map(e=>e===r?{...e,paired:!0}:e)});return}case"isBluetoothDevicePaired":if(!this.device(t).paired)throw new w("bluetooth device is not paired",116);return;case"getBLEDeviceServices":{let e=this.device(t);return this.connection(e),{services:(e.services??[]).map(e=>({uuid:iz(e.uuid),isPrimary:e.isPrimary}))}}case"getBLEDeviceCharacteristics":{var r;let e=this.device(t);this.connection(e);let i=this.uuid(t,"serviceId"),n=null==(r=e.services)?void 0:r.find(e=>iz(e.uuid)===i);if(!n)throw new w("ble service not found",116);return{characteristics:n.characteristics.map(e=>{let{uuid:t,properties:r}=e;return{uuid:iz(t),properties:{...r,writeDefault:r.write}}})}}case"getBLEDeviceRSSI":{let e=this.device(t);return this.connection(e),{RSSI:e.RSSI}}case"getBLEMTU":return{mtu:this.connection(this.device(t)).mtu};case"setBLEMTU":{let e=this.device(t),r=this.connection(e);if(!Number.isInteger(t.mtu)||t.mtu<23||t.mtu>517)throw new w("mtu must be an integer between 23 and 517",104);return r.mtu=Math.min(e.maxMTU??247,t.mtu),{mtu:r.mtu}}case"readBLECharacteristicValue":{let{device:e,service:r,characteristic:i}=this.target(t);if(!i.properties.read)throw new w("read characteristic failed",102);this.publishValue(e.deviceId,r.uuid,i.uuid,i.value);return}case"notifyBLECharacteristicValueChange":{if("boolean"!=typeof t.state||void 0!==t.type&&"string"!=typeof t.type)throw new w("invalid notification parameters",104);let{connection:e,service:r,characteristic:i}=this.target(t),n=(t.type||"indication").toLowerCase();if(t.state&&!("notification"===n?i.properties.notify:"indication"===n&&i.properties.indicate))throw new w("ble characteristic does not support notify type",103);let a=this.key(r.uuid,i.uuid);t.state?e.notifications.set(a,i.value):e.notifications.delete(a);return}case"writeBLECharacteristicValue":{if(!iW(t.value)||void 0!==t.writeType&&("string"!=typeof t.writeType||!["write","writeNoResponse"].includes(t.writeType)))throw new w("invalid characteristic value or writeType",104);let{device:e,service:r,characteristic:i}=this.target(t);if(!("string"==typeof t.writeType&&"writenoresponse"===t.writeType.toLowerCase()?i.properties.writeNoResponse:i.properties.write))throw new w("ble characteristic does not support write type",103);let n=this.hardware.getBluetooth(),a=t.value;this.hardware.setBluetooth({...n,devices:n.devices.map(t=>{var n;return t===e?{...t,services:null==(n=t.services)?void 0:n.map(e=>e===r?{...e,characteristics:e.characteristics.map(e=>e===i?{...e,value:a}:e)}:e)}:t})});return}}}}let sq="doubao.onBluetoothAdapterStateChange",s$="doubao.onBluetoothDeviceFound",sB=new class{hardware;clients=new WeakMap;released=new WeakSet;constructor(e=nL){this.hardware=e}client(e,t){var r;if(!e||this.released.has(e))throw new w("bluetooth context is unavailable",102);let i=this.clients.get(e);if(i)return(null==t?void 0:t.globalProps)&&(i.platform="Android"===t.globalProps.os?"Android":"iOS"),i;let n=i={events:e,platform:(null==t||null==(r=t.globalProps)?void 0:r.os)==="Android"?"Android":"iOS",opened:!1,discovering:!1,devices:new Map,unwatch:()=>{},gatt:new sU(this.hardware,e)};if(this.clients.set(e,n),e.onDestroy(()=>{this.released.add(e),this.stopTimer(n),n.unwatch(),n.devices.clear(),n.gatt.closeAll(!1),this.clients.delete(e)}),this.released.has(e))throw new w("bluetooth context is destroyed",102);let a=this.hardware.getBluetooth();return n.unwatch=this.hardware.subscribe("bluetooth",()=>{let e=this.hardware.getBluetooth();if(e===a)return;let t=e.available!==a.available||e.enabled!==a.enabled||e.authorized!==a.authorized;n.gatt.observe(e),a=e,t&&(this.available()||(this.stopTimer(n),n.discovering=!1),n.opened&&this.publishState(n,this.available()))}),n}available(){let e=this.hardware.getBluetooth();return e.available&&e.enabled&&e.authorized}requireOpened(e){if(this.requirePermission(),!e.opened)throw new w("bluetooth adapter is not initialized",116)}requirePermission(){if(!this.hardware.getBluetooth().authorized)throw new w("bluetooth permission denied",106)}requireAvailable(){if(this.requirePermission(),!this.hardware.getBluetooth().available)throw new w("bluetooth is unsupported",103);if(!this.available())throw new w("bluetooth adapter is unavailable or powered off",116)}publishState(e,t){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i={available:t,discovering:e.discovering},n=JSON.stringify(i);(r||n!==e.lastState)&&(e.lastState=n,e.events.emit(sq,i))}wake(e,t){let r=this.client(e,t);this.publishState(r,this.available(),!0)}open(e){this.requireAvailable(),e.opened=!0,this.publishState(e,!0)}close(e){this.requirePermission(),this.stopTimer(e),e.opened=!1,e.discovering=!1,e.gatt.closeAll(),e.devices.clear(),this.publishState(e,!1,!0)}state(e){this.requireOpened(e);let t=this.available();return{available:t,discovering:t&&e.discovering}}startDiscovery(e,t){if(this.requireOpened(e),e.discovering)throw new w("bluetooth discovery already started",118);this.requireAvailable();let{services:r,interval:i,allowDuplicatesKey:n}=t,a=t.powerLevel??"medium";if(void 0!==n&&"boolean"!=typeof n||void 0!==i&&!Number.isInteger(i)||"string"!=typeof a||!["low","medium","high"].includes(a.toLowerCase())||void 0!==r&&(!Array.isArray(r)||r.some(e=>"string"!=typeof e||!iz(e))))throw new w("invalid Bluetooth discovery parameters",104);let s=(null==r?void 0:r.map(iz))??[];this.stopTimer(e),e.devices.clear(),e.discovering=!0,e.timer=setInterval(()=>{if(this.available())for(let t of this.hardware.getBluetooth().devices){if(s.length&&!t.advertisServiceUUIDs.some(e=>s.includes(iz(e))))continue;let r=e.devices.get(t.deviceId);e.devices.set(t.deviceId,t),(n||JSON.stringify(r&&this.snapshot(r))!==JSON.stringify(this.snapshot(t)))&&e.events.emit(s$,{devices:[this.snapshot(t)]})}},Math.max(i??500,100)),this.publishState(e,!0)}stopDiscovery(e){this.requireOpened(e),e.discovering&&(this.stopTimer(e),e.discovering=!1,this.publishState(e,e.opened&&this.available()))}devices(e){return this.requireOpened(e),[...e.devices.values()].sort((e,t)=>e.deviceId.localeCompare(t.deviceId)).map(e=>this.snapshot(e))}snapshot(e){let{deviceId:t,name:r,localName:i,RSSI:n,connectable:a,advertisData:s,advertisServiceUUIDs:o,serviceData:l}=e;return{deviceId:t,name:r,localName:i,RSSI:n,connectable:a,advertisData:s,advertisServiceUUIDs:o,serviceData:l}}gatt(e,t,r){if("iOS"===e.platform&&["makeBluetoothPair","isBluetoothDevicePaired"].includes(t))throw new w(`${t} is not supported on iOS`,103);return this.requireOpened(e),e.gatt.handle(t,r)}stopTimer(e){void 0!==e.timer&&(clearInterval(e.timer),e.timer=void 0)}},sF=new Map,sz={"scope.userLocation":{description:"将使用你的位置信息,用于提供定位及位置相关服务。",title:"申请获取你的位置信息"},"scope.userFuzzyLocation":{description:"将使用你的大致位置信息,用于提供位置相关服务。",title:"申请获取你的模糊位置信息"},"scope.userLocationBackground":{description:"将在应用插件进入后台后继续使用你的位置信息。",title:"申请获取你的后台位置信息"},"scope.record":{description:"将使用你的麦克风,用于录制音频内容或进行语音输入。",title:"申请获取你的麦克风权限"},"scope.bluetooth":{description:"将使用你的蓝牙,用于发现和连接附近设备。",title:"申请获取你的蓝牙权限"},"scope.camera":{description:"将使用你的相机,用于拍摄照片或视频。",title:"申请获取你的相机权限"},"scope.addPhoneContact":{description:"将使用你的通讯录,用于添加或更新联系人。",title:"申请获取你的通讯录读写权限"},"scope.addPhoneCalendar":{description:"将使用你的日历,用于添加或更新日程。",title:"申请获取你的日历读写权限"}};function sW(e,t){return`${e||"unknown-app"}:${t}`}function sH(e){return sz[e]??{description:"需要获得你的授权后才能继续使用此功能。",title:`申请获取你的${e.replace(/^scope\./,"")||"相关"}权限`}}function sV(e){let t=sW(e,"");return Object.fromEntries([...sF].filter(e=>{let[r]=e;return r.startsWith(t)}).map(e=>{let[r,i]=e;return[r.slice(t.length),"granted"===i]}))}function sG(e,t,r){sF.set(sW(e,t),r)}async function sJ(e){let{appId:t,appIcon:r,appName:i,presenter:n,scope:a,signal:s,skipDialogIfDenied:o=!1}=e;if(null==s?void 0:s.aborted)return!1;let l=t||"unknown-app",d=sF.get(sW(l,a));if("granted"===d)return!0;if("denied"===d&&o)return!1;if(!n){let e="denied"!==d;return sG(l,a,e?"granted":"denied"),e}let u=await n({appId:l,appIcon:r,appName:i||"应用插件",scope:a,signal:s,...sH(a)});return(null==s||!s.aborted)&&(sG(l,a,u?"granted":"denied"),u)}let sK="doubao-debugger-virtual-calendar",sZ={accountAvailable:!0,writeSucceeds:!0,timeZone:"Asia/Shanghai"};function sX(e){if("boolean"!=typeof e.accountAvailable||"boolean"!=typeof e.writeSucceeds||"string"!=typeof e.timeZone)throw Error("日历账户和写入结果需为布尔值,时区需为 IANA 时区名称");new Intl.DateTimeFormat("en",{timeZone:e.timeZone}).format(0)}let sY=new class{settings=Object.freeze({...sZ});events=Object.freeze([]);listeners=new Set;constructor(){try{let e=JSON.parse(localStorage.getItem(sK)??"null");if(!e||(sX(e.settings),!Array.isArray(e.events)||e.events.some(e=>!e||"string"!=typeof e.id||"string"!=typeof e.appId||"string"!=typeof e.title||!Number.isFinite(e.startTime)||!Number.isFinite(e.endTime))))return;this.settings=Object.freeze({...e.settings}),this.events=Object.freeze(e.events.map(e=>Object.freeze({...e})))}catch{}}getSettings=()=>this.settings;getEvents=()=>this.events;subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));setSettings(e){sX(e),this.commit(Object.freeze({...e}),this.events)}clear(){this.commit(this.settings,Object.freeze([]))}write(e,t){if(!this.settings.accountAvailable)throw Error("no writable calendar account");if(!this.settings.writeSucceeds)throw Error("calendar store error");let r=Object.freeze({...e,id:`calendar-${Date.now()}-${this.events.length+1}`,appId:t,timeZone:this.settings.timeZone}),i=[...this.events,r];this.commit(this.settings,Object.freeze(i))}commit(e,t){for(let r of(localStorage.setItem(sK,JSON.stringify({settings:e,events:t})),this.settings=e,this.events=t,this.listeners))r()}};function sQ(e){return e??document.body}async function s0(e,t){var r;let i,n=sQ(t),a=new CustomEvent("doubao:multi-media-broadcast",{bubbles:!0,composed:!0,detail:e});n.dispatchEvent(a),window.dispatchEvent(new CustomEvent("doubao:multi-media-broadcast",{detail:e}));let s=(r=e.mediaId,i=Array.from(sQ(t).querySelectorAll("audio,video")),r?i.filter(e=>e.id===r||e.dataset.mediaId===r):i);return await Promise.all(s.map(t=>"play"===e.action?t.play():Promise.resolve(t.pause()))),{affected:s.length}}let s1=0,s2="x-web-sdk-file-transfer";function s3(e){return null==e?"":"object"==typeof e?JSON.stringify(e):String(e)}function s4(e,t){return new Promise((r,i)=>{let n=new Image;/^https?:/.test(e)&&(n.crossOrigin="anonymous");let a=()=>{null==t||t.removeEventListener("abort",s),n.onload=n.onerror=null},s=()=>{a(),n.removeAttribute("src"),i(null==t?void 0:t.reason)};(null==t?void 0:t.aborted)?s():(null==t||t.addEventListener("abort",s,{once:!0}),n.onload=()=>{a(),r(n)},n.onerror=()=>{a(),i(Error(`failed to load image: ${e}`))},n.src=e)})}async function s5(e,t){if("string"!=typeof e.src||!e.src)throw new w("src must be a non-empty string",104);let r=await rV(e.src,t),i=await (nq(r)?nB(e=>s4(r,e)):s4(r)),n=document.createElement("canvas"),a=(e.compressedWidth??0)>0&&(e.compressedHeight??0)>0,s=a?e.compressedWidth:i.naturalWidth||i.width,o=a?e.compressedHeight:i.naturalHeight||i.height;n.width=s,n.height=o;let l=n.getContext("2d");if(!l)throw Error("canvas 2d context is not available");return l.drawImage(i,0,0,s,o),{tempFilePath:n.toDataURL("image/jpeg",Math.min(100,Math.max(0,e.quality??80))/100)}}async function s6(e,t){var r;if("string"!=typeof e.filePath||!e.filePath)throw new w("filePath must be a non-empty string",104);let i=await rV(e.filePath,t);if(/^https?:/i.test(i))throw new w("filePath must refer to a local image",104);let n=nL.getSystem().album;if("denied"===n||"restricted"===n)throw new w("photo album write permission denied",106);let a=new AbortController,s=null==t||null==(r=t.events)?void 0:r.onDestroy(()=>a.abort(new w("image save view was destroyed",114)));try{try{await s4(i,a.signal)}catch(t){if(a.signal.aborted)throw t;let e=new w("cannot decode image",102);throw e.cause=t,e}if(a.signal.aborted)throw a.signal.reason}finally{null==s||s()}let o=document.createElement("a");o.href=i,o.download=e.filePath.split("/").pop()||"image",o.style.display="none",document.body.append(o);try{o.click()}finally{o.remove()}}function s8(){var e;let t=document.activeElement;for(;null==t||null==(e=t.shadowRoot)?void 0:e.activeElement;)t=t.shadowRoot.activeElement;return t}function s9(e,t){for(;e;){if(t.contains(e))return!0;let r=e.getRootNode();e=r instanceof ShadowRoot?r.host:null}return!1}let s7={enableHighAccuracy:!0,maximumAge:0,timeout:1e4};function oe(){return{browserAuthorization:"unknown",message:"未配置",tone:"muted",userAuthorization:"unknown"}}function ot(e){let{longitude:t,latitude:r}=e;if(!Number.isFinite(t)||!Number.isFinite(r)||t<-180||t>180||r<-90||r>90)throw Error("Invalid location coordinates")}function or(e,t){var r,i,n,a;if(ot({latitude:t,longitude:e}),e<72.004||e>137.8347||t<.8293||t>55.8271)return{latitude:t,longitude:e};let s=-100+2*(r=e-105)+3*(i=t-35)+.2*i*i+.1*r*i+.2*Math.sqrt(Math.abs(r))+(20*Math.sin(6*r*Math.PI)+20*Math.sin(2*r*Math.PI))*2/3+(20*Math.sin(i*Math.PI)+40*Math.sin(i/3*Math.PI))*2/3+(160*Math.sin(i/12*Math.PI)+320*Math.sin(i*Math.PI/30))*2/3,o=300+(n=e-105)+2*(a=t-35)+.1*n*n+.1*n*a+.1*Math.sqrt(Math.abs(n))+(20*Math.sin(6*n*Math.PI)+20*Math.sin(2*n*Math.PI))*2/3+(20*Math.sin(n*Math.PI)+40*Math.sin(n/3*Math.PI))*2/3+(150*Math.sin(n/12*Math.PI)+300*Math.sin(n/30*Math.PI))*2/3,l=t/180*Math.PI,d=Math.sin(l),u=Math.sqrt(d=1-.006693421622965943*d*d);return{latitude:t+(s=180*s/(6335552.717000426/(d*u)*Math.PI)),longitude:e+(o=180*o/(6378245/u*Math.cos(l)*Math.PI))}}let oi=new class{browserAuthorization="unknown";browserLocation;browserWatchId;locationListeners=new Set;locationUpdateRequests=new Map;manualLocation;pendingBrowserRequest;revision=0;snapshot=oe();snapshotListeners=new Set;updatesActive=!1;updateCoordinateType="gcj02";pendingBrowserOptions="";userAuthorization="unknown";watchRevision=0;getSnapshot=()=>this.snapshot;subscribe=e=>(this.snapshotListeners.add(e),()=>this.snapshotListeners.delete(e));subscribeLocation=e=>(this.locationListeners.add(e),()=>this.locationListeners.delete(e));isLocationScope(e){return"scope.userLocation"===e||"scope.userFuzzyLocation"===e||"scope.userLocationBackground"===e}updateUserAuthorization(e){this.userAuthorization=e?"granted":"denied",this.updateSnapshot({userAuthorization:this.userAuthorization}),!e&&this.locationUpdateRequests.size>0&&(this.stopLocationUpdates(),this.emitLocation({status:"user_unauthorized"}))}async requestLocation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:s7;return"granted"!==this.userAuthorization?{status:"user_unauthorized"}:this.requestLocationForHostDirective(e)}async requestLocationForHostDirective(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:s7,t=this.getConfiguredLocation();return t||("denied"===this.browserAuthorization?this.createBrowserUnauthorizedResult():this.locateWithBrowser(e))}async requestBrowserLocation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:s7;this.manualLocation=void 0,this.clearBrowserWatch();let t=await this.locateWithBrowser(e);return"success"===t.status&&!this.manualLocation&&this.updatesActive&&this.startBrowserWatch(e),t}setManualLocation(e){ot(e),this.revision+=1,this.pendingBrowserRequest=void 0,this.clearBrowserWatch(),this.manualLocation={...e,wgs84:function(e,t){let r={longitude:e,latitude:t};for(let i=0;i<8;i++){let i=or(r.longitude,r.latitude),n=i.longitude-e,a=i.latitude-t;if(r={longitude:r.longitude-n,latitude:r.latitude-a},1e-8>Math.max(Math.abs(n),Math.abs(a)))break}return r}(e.longitude,e.latitude),accuracy:0,source:"manual",speed:0,timestamp:Date.now()},this.browserAuthorization="granted",this.updateSnapshot({...e,browserAuthorization:"granted",errorMessage:void 0,message:"已配置(手动坐标)",source:"manual",tone:"success",updatedAtMs:Date.now()}),this.updatesActive&&this.emitLocation({location:this.manualLocation,status:"success"})}setConfigurationError(e){this.updateSnapshot({errorMessage:e,message:"定位失败",tone:"error",updatedAtMs:Date.now()})}get isUpdating(){return this.updatesActive}async startLocationUpdates(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:s7,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{type:r="gcj02",signal:i,authorize:n}=t;if(null==i?void 0:i.aborted)throw new DOMException("Location updates were stopped","AbortError");this.releaseLocationUpdate(i);let a={active:!1,stop:()=>this.releaseLocationUpdate(i)};this.locationUpdateRequests.set(i,a),null==i||i.addEventListener("abort",a.stop,{once:!0});let s=()=>{if(this.locationUpdateRequests.get(i)!==a)throw new DOMException("Location updates were stopped","AbortError")};try{if(n&&await n(),s(),"granted"!==this.userAuthorization){let e={status:"user_unauthorized"};return this.releaseLocationUpdate(i),this.emitLocation(e),e}if(this.updateCoordinateType=r,a.active=!0,this.updatesActive=!0,this.manualLocation)this.emitLocation({status:"success",location:{...this.manualLocation,timestamp:Date.now()}});else{var o;if("u"<typeof navigator||"function"!=typeof(null==(o=navigator.geolocation)?void 0:o.watchPosition))return this.releaseLocationUpdate(i),this.handleBrowserError(Error("Geolocation is not available in the current browser"));try{this.startBrowserWatch(e)}catch(e){return this.releaseLocationUpdate(i),this.handleBrowserError(e)}}return s(),{status:"success"}}catch(e){throw this.locationUpdateRequests.get(i)===a&&this.releaseLocationUpdate(i),e}}stopLocationUpdates(){for(let e of this.locationUpdateRequests.keys())this.releaseLocationUpdate(e);this.updatesActive=!1,this.clearBrowserWatch()}releaseLocationUpdate(e){let t=this.locationUpdateRequests.get(e);t&&(this.locationUpdateRequests.delete(e),null==e||e.removeEventListener("abort",t.stop),this.updatesActive=[...this.locationUpdateRequests.values()].some(e=>e.active),this.updatesActive||this.clearBrowserWatch())}createBusinessLocationInfo(e){let t=function(){try{return new Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{return""}}();return{latitude:e.latitude,longitude:e.longitude,city:"",city_code:"",client_time_zone:t,country:"",country_code:"",district:"",impr_time:String(Math.floor(Date.now()/1e3)),province:"",region:"",time_zone:t,town:""}}reset(){this.revision+=1,this.stopLocationUpdates(),this.browserAuthorization="unknown",this.browserLocation=void 0,this.manualLocation=void 0,this.pendingBrowserRequest=void 0,this.pendingBrowserOptions="",this.updateCoordinateType="gcj02",this.userAuthorization="unknown",this.snapshot=oe(),this.emitSnapshot()}getConfiguredLocation(){return this.manualLocation?{location:{...this.manualLocation,timestamp:Date.now()},status:"success"}:"granted"===this.browserAuthorization&&this.browserLocation&&Date.now()-this.browserLocation.timestamp<=6e4?{location:this.browserLocation,status:"success"}:void 0}locateWithBrowser(e){let t=JSON.stringify(e);if(this.pendingBrowserRequest&&this.pendingBrowserOptions===t)return this.pendingBrowserRequest;this.pendingBrowserOptions=t;let r=++this.revision;this.browserAuthorization="pending",this.updateSnapshot({browserAuthorization:"pending",errorMessage:void 0,latitude:void 0,longitude:void 0,message:"定位中...",source:"browser",tone:"pending",updatedAtMs:Date.now()});let i=this.getBrowserPosition(e).then(e=>{let t=this.toBrowserLocation(e);return r===this.revision&&(this.browserAuthorization="granted",this.browserLocation=t,this.updateSnapshot({browserAuthorization:"granted",errorMessage:void 0,latitude:t.latitude,longitude:t.longitude,message:"已配置(浏览器定位)",source:"browser",tone:"success",updatedAtMs:Date.now()})),{location:t,status:"success"}}).catch(e=>this.handleBrowserError(e,r)).finally(()=>{this.pendingBrowserRequest===i&&(this.pendingBrowserRequest=void 0)});return this.pendingBrowserRequest=i,i}getBrowserPosition(e){let t="u"<typeof navigator?void 0:navigator.geolocation;return t?new Promise((r,i)=>{t.getCurrentPosition(r,i,{...e,maximumAge:0})}):Promise.reject(Error("Geolocation is not available in the current browser"))}toBrowserLocation(e){return{...or(e.coords.longitude,e.coords.latitude),wgs84:{latitude:e.coords.latitude,longitude:e.coords.longitude},accuracy:e.coords.accuracy??0,altitude:e.coords.altitude??void 0,altitudeAccuracy:e.coords.altitudeAccuracy??void 0,heading:e.coords.heading??void 0,source:"browser",speed:e.coords.speed??0,timestamp:e.timestamp||Date.now()}}handleBrowserError(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.revision,r=e&&"object"==typeof e&&"code"in e&&"number"==typeof e.code?e.code:void 0,i=1===r?"denied":"unknown",n=function(e){switch(e&&"object"==typeof e&&"code"in e&&"number"==typeof e.code?e.code:void 0){case 1:return"浏览器或系统已拒绝定位权限,请允许位置访问后重试,或手动配置坐标";case 2:return"暂时无法获取浏览器位置,请检查设备定位服务后重试";case 3:return"获取浏览器位置超时,请重试";default:return e instanceof Error&&e.message.includes("not available")?"当前浏览器不支持定位,请手动配置坐标":"获取浏览器位置失败,请重试"}}(e),a={code:r,message:n,status:"browser_unauthorized"};return console.error("Browser geolocation failed",e),t===this.revision&&(this.browserAuthorization=i,this.browserLocation=void 0,this.updateSnapshot({browserAuthorization:i,errorMessage:n,latitude:void 0,longitude:void 0,message:1===r?"定位权限已拒绝(浏览器或系统)":"定位失败",source:"browser",tone:"error",updatedAtMs:Date.now()}),this.updatesActive&&(this.emitLocation(a),1===r&&this.stopLocationUpdates())),a}createBrowserUnauthorizedResult(){return{code:1,message:this.snapshot.errorMessage||"浏览器未授权定位,请在模拟器顶部“设置 → 定位”配置位置",status:"browser_unauthorized"}}startBrowserWatch(e){this.clearBrowserWatch();let t=++this.watchRevision,r="u"<typeof navigator?void 0:navigator.geolocation;r?this.browserWatchId=r.watchPosition(e=>{if(t!==this.watchRevision||!this.updatesActive)return;let r=this.toBrowserLocation(e);this.browserAuthorization="granted",this.browserLocation=r,this.updateSnapshot({browserAuthorization:"granted",errorMessage:void 0,latitude:r.latitude,longitude:r.longitude,message:"已配置(浏览器定位)",source:"browser",tone:"success",updatedAtMs:Date.now()}),this.emitLocation({location:r,status:"success"})},e=>{t===this.watchRevision&&this.updatesActive&&this.handleBrowserError(e)},e):this.handleBrowserError(Error("Geolocation is not available in the current browser"))}clearBrowserWatch(){if(this.watchRevision+=1,void 0===this.browserWatchId)return;let e="u"<typeof navigator?void 0:navigator.geolocation;null==e||e.clearWatch(this.browserWatchId),this.browserWatchId=void 0}updateSnapshot(e){this.snapshot={...this.snapshot,...e,browserAuthorization:this.browserAuthorization,userAuthorization:this.userAuthorization},this.emitSnapshot()}emitSnapshot(){for(let e of this.snapshotListeners)e()}emitLocation(e){for(let t of("success"===e.status&&"wgs84"===this.updateCoordinateType&&e.location.wgs84&&(e={status:"success",location:{...e.location,...e.location.wgs84}}),this.locationListeners))t(e)}},on="location_api_not_implemented";function oa(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{enableHighAccuracy:0!==e.mode,maximumAge:0,timeout:"number"==typeof e.timeoutMs&&Number.isFinite(e.timeoutMs)&&e.timeoutMs>0?e.timeoutMs:3e4}}function os(e,t,r,i){let n=S(e,r,t);return n.params.data={errMsg:r,...void 0===i?{}:{errCode:i}},n}function oo(e,t){let r="user_unauthorized"===t.status,i=!r&&1===t.code;if(r||i){let t=r?107:106;return os(e,t,r?"user permission denied":"system permission denied",t)}let n=3===t.code;return os(e,n?115:102,n?"location_timeout":"location_fail",n?115:102)}function ol(e){return e.getSystem().locationEnabled?e.getBeacon().locationAuthorized?void 0:"location_permission_denied":"location_service_disabled"}async function od(e,t,r,i){var n;let a=await sJ({appId:(null==r||null==(n=r.navigation)?void 0:n.getPackageInfo().appId)??e.appId,appIcon:e.appIcon,appName:e.appName,presenter:e.showSimulatorPermission,scope:"scope.userLocation",skipDialogIfDenied:!0,signal:i});return(null==i?void 0:i.aborted)||t.updateUserAuthorization(a),a}let ou=new Set,oc=new WeakSet,op=0;function oh(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL,t=e.getNetwork();return{isConnected:"none"!==t.networkType,networkType:t.networkType,signalStrength:"wifi"===t.networkType?t.signalStrength:void 0,hasSystemProxy:t.hasSystemProxy,weakNet:"wifi"===t.networkType?t.signalStrength<=-80:void 0}}function om(){return{timestamp:performance.now()/1e3,wallTime:Date.now()/1e3}}function og(e){for(let t of ou)try{t(e)}catch(e){console.error("Failed to record doubao.request in Chrome DevTools",e)}}function of(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nL,i=oh(r),n=(null==e||null==(t=e.globalProps)?void 0:t.os)==="iOS";return{networkType:i.networkType,networkAvailable:i.isConnected,...n?{}:{signalStrength:i.signalStrength,weakNet:i.weakNet},hasSystemProxy:i.hasSystemProxy??!1}}r(13546);let ov="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",oy=new Uint8Array(256);for(let e=0;e<ov.length;e++)oy[ov.charCodeAt(e)]=e;function ob(e){let t=new Uint8Array(e),r=t.length,i="";for(let e=0;e<r;e+=3)i+=ov[t[e]>>2],i+=ov[(3&t[e])<<4|t[e+1]>>4],i+=ov[(15&t[e+1])<<2|t[e+2]>>6],i+=ov[63&t[e+2]];return r%3==2?i=`${i.substring(0,i.length-1)}=`:r%3==1&&(i=`${i.substring(0,i.length-2)}==`),i}let ow="doubao.onRecorderStateChange",o_=0,oS=new Set([8e3,11025,12e3,16e3,22050,24e3,32e3,44100,48e3]),ox=`class CaptureProcessor extends AudioWorkletProcessor {
|
|
23
|
+
</svg>`,rk="doubao-apps-page",rC={body:`${rk}__body`,capsule:`${rk}__capsule`,capsuleAction:`${rk}__capsule-action`,capsuleCloseIcon:`${rk}__capsule-close-icon`,capsuleMoreIcon:`${rk}__capsule-more-icon`,root:rk};class rE{host;options;runtimeKernel;container=null;root=null;constructor(e,t){if(!e.container)throw Error("Page requires a container element");this.host=e.container,this.options=e,this.runtimeKernel=t}get element(){var e;return(null==(e=this.container)?void 0:e.element)??null}render(e){var t,r;let i;this.clear();let n=document.createElement("div");n.className=rC.root,void 0!==(i=null==(t=e.pageCapsule)?void 0:t.statusBarHeight)&&n.style.setProperty("--doubao-page-capsule-top",`${i+4}px`);let a=document.createElement("div");a.className=rC.body,n.append(a,this.createCapsule()),this.host.replaceChildren(n),this.root=n;try{return this.container=this.runtimeKernel.createContainer({...this.options,sandboxUrl:this.options.runtime?this.options.runtime.sandboxUrl:this.options.sandboxUrl,container:a,className:this.options.className,onError:this.options.onError,onReady:this.options.onReady}),this.container.render({bridge:null==(r=this.options.runtime)?void 0:r.bridge,resourceUrl:function(e){if(!e.resourceUrl)throw Error("Page.render requires a resourceUrl");return e.resourceUrl}(e),groupId:e.groupId,containerType:"PAGE",initData:e.initData,globalProps:e.globalProps})}catch(e){throw this.clear(),e}}clear(){var e,t;null==(e=this.container)||e.clear(),this.container=null,null==(t=this.root)||t.remove(),this.root=null,this.host.replaceChildren()}setVisible(e){var t,r;null==(r=this.container)||null==(t=r.setVisible)||t.call(r,e)}sendEvent(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};null==(t=this.container)||t.sendEvent(e,r)}reload(){var e;null==(e=this.container)||e.reload()}updateGlobalProps(e){var t;if(!(null==(t=this.container)?void 0:t.updateGlobalProps))throw Error("Page container does not support updating global props");this.container.updateGlobalProps(e)}dispatchCapsuleEvent(e,t){t.stopPropagation(),this.host.dispatchEvent(new CustomEvent(e,{bubbles:!0}))}createCapsuleSvg(e){let t=document.createElement("template");t.innerHTML=e.trim();let r=t.content.firstElementChild;if(!r||"svg"!==r.tagName.toLowerCase())throw Error("Invalid Page capsule icon SVG");return r}createCapsuleAction(e,t,r,i){let n=this.createCapsuleSvg(r);return n.classList.add(rC.capsuleAction,e),n.setAttribute("role","button"),n.setAttribute("aria-label",t),n.setAttribute("tabindex","0"),n.setAttribute("focusable","true"),n.addEventListener("click",e=>{this.dispatchCapsuleEvent(i,e)}),n.addEventListener("keydown",e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),this.dispatchCapsuleEvent(i,e))}),n}createCapsuleMoreIcon(){return this.createCapsuleAction(rC.capsuleMoreIcon,"More",rx,"doubao:page-capsule-more")}createCapsuleCloseIcon(){return this.createCapsuleAction(rC.capsuleCloseIcon,"Close app",rI,"doubao:page-capsule-close")}createCapsule(){let e=document.createElement("div");return e.className=rC.capsule,e.style.display="flex",e.style.flexDirection="row",e.setAttribute("role","group"),e.setAttribute("aria-label","Page actions"),e.append(this.createCapsuleMoreIcon(),this.createCapsuleCloseIcon()),e}}let rN=/\{\{\s*([^{}\s]+)\s*\}\}/g;function rT(e){return"string"==typeof e?e:JSON.stringify(e)}function rA(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={...e.input||{},...function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={};for(let[i,n]of Object.entries(e.variables||{}))Object.prototype.hasOwnProperty.call(t,i)?r[i]=t[i]:null!==n&&(r[i]=n);return{...r,...t}}(e,t)};if("page"===e.type){let t=function(e,t){var r;let i=new Set(Array.from(e.url.matchAll(rN),e=>e[1])),n=(r=e.url,r.replace(rN,(e,r)=>{if(!Object.prototype.hasOwnProperty.call(t,r))return e;let i=rT(t[r]);return void 0===i?e:encodeURIComponent(i)})),a=n.indexOf("#"),s=a<0?n:n.slice(0,a),o=a<0?"":n.slice(a),l=s.indexOf("?"),d=new Set(new URLSearchParams(l<0?"":s.slice(l+1)).keys()),u=new URLSearchParams;for(let[e,r]of Object.entries(t)){if(i.has(e)||d.has(e))continue;let t=rT(r);void 0!==t&&u.set(e,t)}let c=u.toString();if(!c)return n;let p=l<0?"?":s.endsWith("?")||s.endsWith("&")?"":"&";return`${s}${p}${c}${o}`}(e,r);return{type:"page",unresolvedVariables:function(e){let t=new Set;for(let r of e.matchAll(rN))t.add(r[1]);return Array.from(t)}(t),url:t}}return"widget"===e.type?{type:"widget",id:e.id,resolvedInput:r,botId:e.botId}:{type:"tool",id:e.id,resolvedInput:r}}function rM(e){var t;let{addProtocolToBareHost:r=!1,allowRootRelative:i=!1,defaultProtocol:n="http"}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(/^https?:\/\//i.test(e))return e;if(e.startsWith("//"))return`${rj(n,e.slice(2))}:${e}`;if(i&&e.startsWith("/"))return e;return/^(?:\[[^\]]+\]|[a-z0-9.-]+):\d+(?:[/?#]|$)/i.test(e)||r&&(t=e,/^(?:\[[^\]]+\]|[a-z0-9.-]+)(?:[/?#]|$)/i.test(t))?`${rj(n,e)}://${e}`:e}function rR(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=String(e??"").trim();if(!r)return;let i=rM(r,t);try{let e=t.baseUrl?new URL(i,t.baseUrl):new URL(i);if("http:"!==e.protocol&&"https:"!==e.protocol)return;return e.toString()}catch{return}}function rj(e,t){return"function"==typeof e?e(t):e}function rP(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}var rL=r(70851);function rO(e,t){if(e.appId&&t&&e.appId!==t)throw Error("Resolved Widget appId must match the trusted Widget identity");return t??e.appId}let rD="__doubao_apps__expired-widget",rU="doubao-apps-widget",rq=1,r$={body:`${rU}__body`,default:`${rU}--default`,floatingHeader:`${rU}--floating-header`,embedded:`${rU}--embedded`,header:`${rU}__header`,icon:`${rU}__icon`,placeholder:`${rU}__placeholder`,placeholderContent:`${rU}__placeholder-content`,root:rU,title:`${rU}__title`};class rB{container;options;runtimeKernel;identity;viewContext;root=null;body=null;title=null;icon=null;runtimeContainer=null;runtimeFallbackOptions={};apiContextOwner={};appTheme;hostCallController=null;constructor(e,t){var r,i;let n,a,s,l,d,u;if(!e.container)throw Error("Widget requires a container element");if(!e.runtime)throw Error("Widget requires a Runtime");this.container=e.container,this.options=e,this.runtimeKernel=t,this.appTheme="light"===(n=o(r=e.globalProps)?r.appTheme:void 0)||"dark"===n?n:void 0,this.identity=(i=`widget-${rq++}`,a=e.viewContext,s=e.appId??(null==a?void 0:a.appId),l=e.widgetId??(null==a?void 0:a.widgetId),d=(null==a?void 0:a.widgetInstanceId)??i,u=a?{...a,appId:s??a.appId,widgetId:l,widgetInstanceId:d}:void 0,{appId:s,versionTag:null==a?void 0:a.versionTag,viewContext:u,widgetId:l,widgetInstanceId:d}),this.viewContext=this.identity.viewContext}get element(){var e;return(null==(e=this.runtimeContainer)?void 0:e.element)??this.root}setAppTheme(e){var t;this.appTheme=e,this.root&&(this.root.dataset.appTheme=e),null==(t=this.runtimeContainer)||t.sendEvent("onThemeChange",{appTheme:e})}async render(){var e;this.clear(),this.hostCallController=new AbortController;let t=this.hostCallController.signal;try{await f(()=>this.options.runtime.loadPackage(),t)}catch(e){if(g(t),o(e)&&"AbortError"===e.name)throw e;return this.renderFallback()}if(g(t),"iframe"===(e={identity:this.identity,mode:this.runtimeKernel.mode}).mode&&e.identity.widgetId!==rD&&e.identity.appId&&e.identity.widgetId)try{this.prepareIframeRuntime()}catch{return this.renderFallback()}let r=function(e){let t;g(e.signal);let{packageInfo:r,packageManager:i}=e.options.runtime,{manifest:n}=r;if(rO(e.identity,n.appId),e.identity.widgetId===rD){var a,s;let t;return{kind:"expired",options:{appName:n.name??e.identity.appId,icon:n.iconSrc,placeholderText:"string"==typeof(t=null==(a=e.options.initData)||null==(s=a.viewData)?void 0:s.title)&&t.trim().length>0?t:void 0}}}try{let n=i.resolveWidget(r,e.identity.widgetId);if(g(e.signal),t={appName:n.appName,icon:n.icon},!n.resourceUrl)return{kind:"fallback",options:t};return{kind:"runtime",options:{appId:rO(e.identity,n.appId),boxType:n.boxType,...t,resourceUrl:n.resourceUrl,renderMode:n.renderMode??"standard",titleType:n.titleType??2*(!1===n.showHeader)}}}catch{return g(e.signal),{kind:"fallback",options:t}}}({identity:this.identity,mode:this.runtimeKernel.mode,options:this.options,signal:t});if("expired"===r.kind)return this.renderPlaceholderCard(r.options);if("fallback"===r.kind)return this.renderFallback(r.options);try{return this.renderResource(r.options)}catch{return g(t),this.renderFallback({appName:r.options.appName,icon:r.options.icon})}}getShellClassName(e){let{boxType:t,floatingHeader:r,renderMode:i}=e,n="embedded"===i;return(0,rL.$)(r$.root,{[r$.default]:4!==t&&!n,[r$.floatingHeader]:r,[r$.embedded]:n},this.options.className)}renderShell(e){var t;let r=document.createElement("section");r.className=this.getShellClassName(e),this.appTheme&&(r.dataset.appTheme=this.appTheme);let i="number"==typeof(t=this.options.contentMaxWidth)&&Number.isFinite(t)?`${t}px`:"string"==typeof t&&t.trim().length>0?t:void 0;i&&(r.style.maxWidth=i);let n=document.createElement("div");n.className=r$.body;let a=null;if(e.showHeader){(a=document.createElement("header")).className=r$.header,a.hidden="iframe"===this.runtimeKernel.mode;let e=document.createElement("img");e.alt="",e.className=r$.icon,e.height=16,e.width=16;let t=document.createElement("div");t.className=r$.title,a.append(e,t),r.append(a),this.icon=e,this.title=t}return r.append(n),this.container.replaceChildren(r),this.root=r,this.body=n,this.updateHeader(e.appName,e.icon),{body:n,header:a,root:r}}renderPlaceholderCard(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.clear();let{body:t,header:r,root:i}=this.renderShell({appName:e.appName??this.identity.widgetId??this.identity.appId??"",icon:e.icon,renderMode:"standard",showHeader:!0});r&&(r.hidden=!1);let n=document.createElement("div");n.className=r$.placeholder;let a=document.createElement("div");return a.className=r$.placeholderContent,a.textContent=e.placeholderText??this.options.fallbackText??"",n.append(a),t.append(n),i}renderFallback(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.renderPlaceholderCard({...e,placeholderText:this.options.fallbackText})}handleRuntimeError(e,t,r){try{var i,n;null==(i=(n=this.options).onError)||i.call(n,e,t)}finally{this.renderFallback({appName:r.appName,icon:r.icon})}}renderResource(e){var t,r;let i={...this.options.globalProps,__GEN_UI_DATA__:this.options.genUIData??(null==(t=this.options.globalProps)?void 0:t.__GEN_UI_DATA__),appTheme:this.appTheme,[e5]:{widgetId:this.identity.widgetId,widgetInstanceId:this.identity.widgetInstanceId},packageInfo:{...null==(r=this.options.globalProps)?void 0:r.packageInfo,appId:e.appId,iconSrc:e.icon,name:e.appName}};this.runtimeFallbackOptions={appName:e.appName,icon:e.icon};let{body:n,root:a}=this.updateOrRenderResourceShell(e);return"iframe"===this.runtimeKernel.mode&&(a.style.background="transparent",a.style.borderWidth="0"),this.runtimeContainer??=this.createRuntimeContainer(n),this.runtimeContainer.render({bridge:this.options.runtime.bridge,containerType:"WIDGET",resourceUrl:e.resourceUrl,initData:this.options.initData,globalProps:{...i,__VIEW_CONTEXT__:this.viewContext??{}}})}createRuntimeContainer(e){var t,r;let i=(null==(t=this.viewContext)||null==(r=t.shareInfo)?void 0:r.mode)==="share_page";return this.runtimeKernel.createContainer({...this.options,getAppletContext:()=>({owner:this.options.invocationOwner??this.apiContextOwner,signal:this.getHostCallSignal(),source:"widget",viewContext:this.viewContext}),sandboxUrl:this.options.runtime.sandboxUrl,captureWidgetTap:i||void 0,container:e,onUnsupportedAPI:this.options.onUnsupportedAPI,onError:(e,t)=>{this.handleRuntimeError(e,t,this.runtimeFallbackOptions)},onReady:()=>{var e,t,r;null==(e=this.root)||e.style.removeProperty("background"),null==(t=this.root)||t.style.removeProperty("border-width"),(null==(r=this.title)?void 0:r.parentElement)&&(this.title.parentElement.hidden=!1)},onWidgetInteraction:i&&this.options.onWidgetInteraction?e=>this.handleWidgetInteraction(e):void 0})}prepareIframeRuntime(){let{body:e,root:t}=this.renderShell({renderMode:"standard",showHeader:!0});t.style.background="transparent",t.style.borderWidth="0",this.runtimeFallbackOptions={},this.runtimeContainer=this.createRuntimeContainer(e),this.runtimeContainer.prepare("WIDGET")}updateOrRenderResourceShell(e){var t,r,i;let n={appName:e.appName,boxType:e.boxType,floatingHeader:1===e.titleType,icon:e.icon,renderMode:e.renderMode,showHeader:"embedded"!==e.renderMode&&2!==e.titleType};return this.root&&this.body?(this.root.className=this.getShellClassName(n),n.showHeader||(null==(i=this.title)||null==(r=i.parentElement)||r.remove(),this.icon=null,this.title=null),this.updateHeader(e.appName,e.icon),{body:this.body,header:(null==(t=this.title)?void 0:t.parentElement)??null,root:this.root}):this.renderShell(n)}clear(){var e,t,r;null==(e=this.hostCallController)||e.abort(),this.hostCallController=null,this.apiContextOwner={},null==(t=this.runtimeContainer)||t.clear(),this.runtimeContainer=null,this.runtimeFallbackOptions={},null==(r=this.root)||r.remove(),this.root=null,this.body=null,this.title=null,this.icon=null,this.container.replaceChildren()}updateData(e){var t;this.options.initData=e,null==(t=this.runtimeContainer)||t.updateData(e)}reload(){var e;null==(e=this.runtimeContainer)||e.reload()}destroy(){this.clear()}getHostCallSignal(){if(this.hostCallController)return this.hostCallController.signal;let e=new AbortController;return e.abort(),e.signal}async handleWidgetInteraction(e){let t=this.options.onWidgetInteraction;if(!t)return;let r=this.getHostCallSignal();g(r),await t(e),g(r)}updateHeader(e,t){this.title&&(this.title.textContent=e??""),this.icon&&(t?(this.icon.src=t,this.icon.hidden=!1):(this.icon.removeAttribute("src"),this.icon.hidden=!0))}}let rF={mode:"inline",createContainer:e=>new rS(e)},rz=new tz(rF,!0);class rW{options;emptyState;cleanupEmptyState;constructor(e){this.options=e}get container(){return this.options.container}hide(){var e,t;null==(e=(t=this.options).onHide)||e.call(t)}async confirmBeforeUnload(e,t){return(null==t||!t.aborted)&&(this.options.confirmBeforeUnload?this.options.confirmBeforeUnload(e,t):window.confirm(e))}createPage(e,t,r){let i=document.createElement("div");i.className="doubao-runtime-page",Object.assign(i.style,{display:"block",width:"100%",height:"100%"}),i.addEventListener("doubao:page-capsule-close",e=>{e.stopPropagation(),r()});let n=this.container,a=new rE({...e,container:i},t);return{render:e=>(n.append(i),a.render(e)),setVisible(e){i.style.display=e?"block":"none",a.setVisible(e)},clear(){a.clear(),i.remove()},sendEvent:a.sendEvent.bind(a),updateGlobalProps:a.updateGlobalProps.bind(a),reload:a.reload.bind(a)}}setEmpty(e){let t=this.options.mountEmptyState;!this.emptyState&&t&&(this.emptyState=document.createElement("div"),this.emptyState.className="doubao-runtime-empty",this.container.append(this.emptyState),this.cleanupEmptyState=t(this.emptyState)??void 0),this.emptyState&&(this.emptyState.hidden=!e)}destroy(){var e,t;null==(e=this.cleanupEmptyState)||e.call(this),this.cleanupEmptyState=void 0,null==(t=this.emptyState)||t.remove(),this.emptyState=void 0}}function rH(e,t,r){let i=(null==r?void 0:r.fileSystemNamespace)??eu(null==r?void 0:r.globalProps);return ev(i,async()=>{let r=eb(i);eJ(r,e,t),await ex(i,{fileSystemChanges:eS(eb(i).entries,r.entries)})})}async function rV(e,t){if(!e.startsWith("appletfile:"))return e;let r=(null==t?void 0:t.fileSystemNamespace)??eu(null==t?void 0:t.globalProps);return ev(r,()=>{var t;let i=eb(r).entries[eD(e)];if(!i)throw new w(`file not found: ${e}`,203);if("file"!==i.type)throw new w(`path is a directory: ${e}`,1901001);let n=null==(t=e.split(".").pop())?void 0:t.toLowerCase();return`data:${({png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",wav:"audio/wav",mp3:"audio/mpeg",m4a:"audio/mp4",ogg:"audio/ogg",flac:"audio/flac",aac:"audio/aac",mp4:"audio/mp4"})[n??""]??"application/octet-stream"};base64,${i.data}`})}class rG extends tW(rS,()=>rz){}class rJ extends rB{constructor(e){super(e,rF)}}class rK extends tF{constructor(e){super(e,rF)}}var rZ=r(75541);function rX(e){return"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=9999}function rY(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0}function rQ(e,t){let r=t.trim();r&&!e.includes(r)&&e.push(r)}function r0(e){let t=[];return!function e(t,r,i){if(!("object"!=typeof t||null===t||i.has(t))){if(i.add(t),Array.isArray(t))return void t.forEach(t=>e(t,r,i));if(rP(t))for(let[n,a]of Object.entries(t))"response_headers"===n.toLowerCase()&&function(e,t){if(rP(e)){for(let[r,i]of Object.entries(e))if("x-tt-logid"===r.toLowerCase()&&"string"==typeof i)return void rQ(t,i)}}(a,r),"log_ids"===n.toLowerCase()&&function(e,t){if("string"==typeof e)return rQ(t,e);if(Array.isArray(e))for(let r of e)"string"==typeof r&&rQ(t,r)}(a,r),e(a,r,i)}}(e,t,new WeakSet),t}function r1(e,t){if(!e.startsWith("sslocal://"))return{url:e};let r=new URL(e).searchParams,i=r.get("app_id"),n=r.get("path"),a=r.get("query"),s=r.get("route_mode")??void 0;if(!t)throw Error("当前调试应用缺少 AppID");if(i!==t)throw Error(`任务目标应用 ${i} 与当前应用 ${t} 不一致`);if(!n)throw Error("任务目标缺少 path");if(void 0!==s&&"navigate"!==s&&"redirect"!==s&&"relaunch"!==s)throw Error(`不支持的任务导航模式: ${s}`);return{url:a?`${n}?${a}`:n,routeMode:s}}function r2(e){return rP(e)?rP(e.viewData)?e:{...e,viewData:e}:{viewData:{}}}function r3(e){if("string"==typeof e&&e.trim())try{return JSON.parse(e)}catch{return}}function r4(e){if(rP(e))return e;let t=r3(e);return rP(t)?t:void 0}function r6(e){if("string"==typeof e)return e;try{return JSON.stringify(e??{})}catch{return"{}"}}function r5(e){return e instanceof Error?e.message:String(e)}function r8(e){let t=null==e?void 0:e.toLowerCase();switch(t){case"agent":case"api":case"mcp":case"card":case"resource":case"runtime":case"debug":return t;case"tool":return"agent";default:return"runtime"}}function r9(e){let[t,...r]=e.trim().split(":"),i=t.replace(/_/g," ").trim().split(/\s+/).filter(Boolean).map(r7).join(" ");return 0===r.length?i||e:`${i}: ${r.join(":").trim()}`}function r7(e){let t=function(e){switch(e.toLowerCase()){case"api":return"API";case"mcp":return"MCP";case"sse":return"SSE";case"ack":return"ACK";case"http":return"HTTP";case"json":return"JSON";case"id":return"ID";default:return""}}(e);if(t)return t;if(/^[A-Z0-9]+$/.test(e))return e;let r=e.toLowerCase();return`${r.slice(0,1).toUpperCase()}${r.slice(1)}`}r(78872),r(60972);let ie=new Set(["local_mcp_missing","local_mcp_tools_load_failed","simulator_chat_fetch_failed","simulator_query_failed","stream_error","tool_executor_missing","tool_result_submit_failed"]),it={query:0,"tool-call":10,"tool-result":20,"agent-processing":25,card:30,"agent-response":40,error:50};function ir(e,t){return{category:"api",detail:{query:t},key:"query",phase:"request",payload:{event:"query",query:t},source:e,sources:[e],title:"Query"}}function ii(e,t){let r=e.steps.get(t.key);if(!r)return void e.steps.set(t.key,t);let i=function(e,t){if("error"===t.phase)return!0;if(e.key.startsWith("card:")){let r=il(e.source.payload);return ia(il(t.source.payload))>ia(r)}return!1}(r,t),n=i?t:r,a=i?r:t;e.steps.set(t.key,{...r,category:"error"===t.phase?t.category:n.category,detail:ih(n.detail,a.detail),phase:"error"===t.phase?t.phase:n.phase,payload:ih(n.payload,a.payload),source:n.source,sources:[...new Map([...r.sources,...t.sources].map(e=>[e.id,e])).values()],title:"error"===t.phase||i?t.title:r.title})}function ia(e){return"simulator_card_render_failed"===e||"simulator_card_runtime_error"===e||"simulator_card_render_skipped"===e?3:"simulator_card_rendered"===e?2:+("card_delta"===e)}function is(e){let t=iv([...e.steps.values()]);return t.map((r,i)=>{var n,a,s,o,l,d,u;let c,p,h,m,g,f,v,y,b,w,_;return n=r,a=e,s=t,o=i,y=im(n.sources.flatMap(r0)),b=im(n.sources.map(e=>e.payload.request_id||"")),_=void 0===(w=(l=n,d=s,u=o,c=l.payload.elapsed_ms??l.detail.elapsed_ms,h=(null==(p=l.key.startsWith("agent-processing:")?d.slice(u+1).find(e=>/^(tool-call|card|error):/.test(e.key)||"agent-response"===e.key):d[u+1])?void 0:p.source.timestamp)??l.source.timestamp,m=Number.isFinite(l.source.timestamp)&&Number.isFinite(h)?Math.max(0,h-l.source.timestamp):void 0,f=(g=l.key.startsWith("tool-call:")?l.key.replace("tool-call:","tool-result:"):l.key.startsWith("tool-result:")?l.key.replace("tool-result:","tool-call:"):void 0)?d.find(e=>e.key===g):void 0,void 0!==(v=l.key.startsWith("tool-call:")&&f?f.payload.elapsed_ms??f.detail.elapsed_ms:void 0)?v:l.key.startsWith("tool-result:")&&f?void 0:void 0!==c?void 0===m?c:Math.max(c,m):m))?n.detail:{...n.detail,elapsed_ms:w},{id:n.source.id,order:n.source.order,timestamp:n.source.timestamp,display:{category:n.category,detail:_,phase:n.phase,title:n.title},payload:{request_id:1===b.length?b[0]:void 0,request_ids:b.length>1?b:void 0,...n.payload,trace_id:a.id,run_status:a.status,elapsed_ms:w,log_ids:y.length>0?y:void 0}}})}function io(e,t){let r=ig(t.payload),i=r?e.runs.find(e=>e.id===r):void 0;if(!i){if(!r)return;i={id:r,order:t.order??e.runs.length,startedAt:t.timestamp,steps:new Map},e.runs.push(i)}return i.startedAt=Math.min(i.startedAt,t.timestamp),i.order=Math.min(i.order,t.order??i.order),i}function il(e){return e.event||""}function id(e,t){return iu(e)||[ig(e)||t.id,e.tool_name||"unknown-tool"].filter(Boolean).join(":")}function iu(e){return e.tool_call_id||""}function ic(e){let t=e.tool_name||iu(e);return t?`: ${t}`:""}function ip(e){let t={};for(let[r,i]of Object.entries(e))null!=i&&""!==i&&(t[r]=i);return t}function ih(e,t){return Object.fromEntries([...Object.entries(t),...Object.entries(e).filter(e=>{let[,t]=e;return void 0!==t})])}function im(e){return[...new Set(e.filter(e=>!!e))]}function ig(e){var t;return e.trace_id||(null==(t=e.trace)?void 0:t.trace_id)||""}function iv(e){return[...e].sort((e,t)=>e.source.timestamp-t.source.timestamp||(e.source.order??0)-(t.source.order??0)||it[e.key.split(":")[0]]-it[t.key.split(":")[0]]||e.key.localeCompare(t.key))}function iy(e,t){return e.startedAt-t.startedAt||e.order-t.order||e.id.localeCompare(t.id)}function ib(e,t){return e.timestamp-t.timestamp||(e.order??0)-(t.order??0)||e.id.localeCompare(t.id)}function iw(e){try{return i_(e,2)}catch{var t=e;if("string"==typeof t){let e=t.trim();if(!e)return"";try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}if(void 0===t)return"";try{return JSON.stringify(t,null,2)}catch{return String(t)}}}function i_(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=new WeakSet;return JSON.stringify(e,(e,t)=>{if(t instanceof Error)return{name:t.name,message:t.message,stack:t.stack};if("function"==typeof t)return`[Function ${t.name||"anonymous"}]`;if("object"==typeof t&&null!==t){if(r.has(t))return"[Circular]";r.add(t)}return t},t)}function iS(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=Date.now();return{stored_at:new Date(r).toISOString(),stored_at_ms:r,snapshot:ix(e,t),debug_snapshot:ix(e,{...t,debug:!0,includeRuntimeRoot:!1})}}function ix(e){var t,r;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=i.debug&&!i.traceId?(t=e,r=!1!==i.includeRuntimeRoot,rP(t)&&!r&&rP(t.runtime_snapshot)?{...t,runtime_snapshot:ik(t.runtime_snapshot,!1)}:t):function(e,t){var r;if(!rP(e))return e;let i=rP(e.simulator)?e.simulator:{},n=Array.isArray(i.messages)?i.messages.filter(e=>iC(e,t.traceId)):void 0,a=Array.isArray(i.tool_calls)?i.tool_calls.filter(e=>iC(e,t.traceId)):void 0,s=ik(e.runtime_snapshot,!1!==t.includeRuntimeRoot);return{...iR(e,["exported_at","client_id","command_id","context","render_targets"]),runtime_snapshot:rP(s)?s:void 0,simulator:rP(e.simulator)?{...iR(i,["stream_status","active_request_id","active_reply_message_id"]),error:i.error?iM(i.error):void 0,selected_card:i.selected_card?iA(i.selected_card):void 0,answer_finish:i.answer_finish?rP(r=i.answer_finish)?iR(r,["messageId","status","finishReason","usage","createdAtMs"]):r:void 0,messages:null==n?void 0:n.map(iE),tool_calls:null==a?void 0:a.map(iT),trace_events:Array.isArray(i.trace_events)?iI(i.trace_events,{debug:t.debug,messages:n,traceId:t.traceId}):void 0}:void 0,widget_runtime_trace_events:Array.isArray(e.widget_runtime_trace_events)?iI(e.widget_runtime_trace_events,{debug:t.debug,traceId:t.traceId}):void 0,page_runtime_trace_events:Array.isArray(e.page_runtime_trace_events)?iI(e.page_runtime_trace_events,{debug:t.debug,traceId:t.traceId}):void 0,runtime_console:rP(e.runtime_console)?e.runtime_console:void 0}}(e,i),a=r0(e);return a.length>0&&rP(n)?{...n,log_ids:a}:n}function iI(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(t.debug&&!t.traceId)return e;if(t.debug){var r,i;return r=e,(i=t.traceId)?r.filter(e=>ig(e.payload)===i):r}let n=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r={runs:[]};for(let t of[...e].sort(ib))!function(e,t){var r,i;let n=t.payload,a=il(n);if("tool_result_report_started"===a){let r=io(e,t);if(!r)return;ii(r,function(e){let t=e.payload,r=ip({tool_call_id:iu(t),tool_name:t.tool_name});return{category:"agent",detail:r,key:`agent-processing:${id(t,e)}`,phase:"request",payload:{event:"agent_processing",...r},source:e,sources:[e],title:`Agent Processing${ic(t)}`}}(t));return}if(!((r=a).startsWith("tool_result_report_")||"tool_result_ack"===r)){if("simulator_chat_fetch_started"===a){let r=function(e){var t,r,i;return e.query||(null==(t=e.request)?void 0:t.query)||(null==(i=e.request)||null==(r=i.message)?void 0:r.content)||""}(n);if(!r)return;let i=io(e,t);if(!i)return;ii(i,ir(t,r));return}if("tool_call"===a||"local_mcp_call_started"===a){let r=io(e,t);if(!r)return;ii(r,function(e){let t=e.payload,r=ip({tool_call_id:iu(t),tool_name:t.tool_name,arguments:t.arguments,arguments_json:t.arguments_json});return{category:"agent",detail:r,key:`tool-call:${id(t,e)}`,phase:"request",payload:{event:"tool_call",...r},source:e,sources:[e],title:`Tool Call${ic(t)}`}}(t));return}if("local_mcp_call_succeeded"===a||"local_mcp_call_failed"===a){let r=io(e,t);if(!r)return;ii(r,function(e){let t=e.payload,r="local_mcp_call_failed"===il(t),i=t.result??t.structured_result??r3(t.structured_result_json)??t.structured_result_json,n=t.raw_mcp_result??r3(t.raw_mcp_result_json)??t.raw_mcp_result_json,a=t.raw_result_text===t.raw_mcp_result_json?void 0:t.raw_result_text,s=ip({tool_call_id:iu(t),tool_name:t.tool_name,status:t.status,result:i,raw_result_text:a,raw_mcp_result:n,elapsed_ms:t.elapsed_ms,error:t.error});return{category:"mcp",detail:s,key:`tool-result:${id(t,e)}`,phase:r?"error":"response",payload:{event:r?"tool_result_failed":"tool_result",...s},source:e,sources:[e],title:`${r?"Tool Result Failed":"Tool Result"}${ic(t)}`}}(t));return}if("card_delta"===(i=a)||"simulator_card_rendered"===i||"simulator_card_render_failed"===i||"simulator_card_runtime_error"===i||"simulator_card_render_skipped"===i){let r=io(e,t);if(!r)return;ii(r,function(e){var t,r;let i=e.payload,n=il(i),a="error"in i||n.endsWith("_failed")||n.endsWith("_error"),s=ip({card_id:i.card_id,widget_id:i.widget_id,card_type:i.card_type,entity_id:i.entity_id,source_tool_call_id:i.source_tool_call_id,elapsed_ms:i.elapsed_ms,error:i.error,summary:i.summary});return{category:"card",detail:s,key:`card:${t=i,r=e,t.card_id||t.source_tool_call_id||[ig(t)||r.id,t.widget_id||r.id].filter(Boolean).join(":")}`,phase:a?"error":"response",payload:{event:a?"card_render_failed":"card_delta"===n?"card_received":"card_rendered",...s},source:e,sources:[e],title:a?"Card Render Failed":"card_delta"===n?"Card Received":"Card Rendered"}}(t));return}if(function(e,t){let r=e.phase,i=e.status;return ie.has(t)||"error"===r||t.endsWith("_failed")||t.endsWith("_missing")||t.endsWith("_aborted")||t.endsWith("_error")||"failed"===i||"error"===i||"number"==typeof i&&i>=400}(n,a)){let r=io(e,t);if(!r)return;ii(r,function(e){var t,r;let i=e.payload,n=i.detail??{},a=i.event_count??n.event_count,s=ip({elapsed_ms:i.elapsed_ms??n.elapsed_ms,endpoint:i.endpoint??n.endpoint,error:i.error??n.error,event_count:a,message:i.message??n.message,reason:i.reason??n.reason,status:i.status??n.status,summary:i.summary??n.summary??("simulator_chat_sse_read_failed"===il(i)&&0===a?"对话流未收到任何事件,未触发 MCP tool 与 tool/report;请结合 log_id 排查生成或下发 tool_call 前的服务端/链路异常。":void 0),response:i.response??n.response,response_text:i.response_text??n.response_text});return{category:(null==(t=e.display)?void 0:t.category)||"runtime",detail:s,key:`error:${e.id}`,phase:"error",payload:{event:il(i)||"trace_error",...s},source:e,sources:[e],title:(null==(r=e.display)?void 0:r.title)||i.title||"Trace Error"}}(t))}}}(r,t);for(let e of t)!function(e,t){var r,i,n,a,s;let o=(i=t,{id:`trace-message-${i.messageId}`,timestamp:i.createdAtMs,payload:ip({message_id:i.messageId,request_id:i.requestId,trace_id:i.traceId})}),l=io(e,o);if(!l)return;let d=(null==(r=t.blocks)?void 0:r.some(e=>"image"===e.type))??!1,u=t.text.trim()||(d?"[图片]":"");"assistant"===t.role&&t.status&&(n=l,a=t.status,s=t.createdAtMs,void 0!==n.statusUpdatedAt&&s<n.statusUpdatedAt||(n.status=a,n.statusUpdatedAt=s)),"user"===t.role&&u&&!l.steps.has("query")&&ii(l,ir(o,u)),"assistant"===t.role&&t.text.trim()&&ii(l,function(e,t){let r=iv([...e.steps.values()]).at(-1),i=Math.max(t.createdAtMs,((null==r?void 0:r.source.timestamp)??t.createdAtMs)+.1),n={id:`trace-agent-response-${t.messageId}`,order:(null==r?void 0:r.source.order)===void 0?void 0:r.source.order+.1,timestamp:i,payload:ip({message_id:t.messageId,request_id:t.requestId,trace_id:t.traceId})};return{category:"agent",detail:{text:t.text},key:"agent-response",phase:"finish",payload:{event:"agent_response",message_id:t.messageId,text:t.text},source:n,sources:[n],title:"Agent Response"}}(l,t))}(r,e);return r}(e,t.messages);return(t.traceId?n.runs.filter(e=>e.id===t.traceId):n.runs).sort(iy).flatMap(is)}(e,t)}function ik(e,t){if(!rP(e)||t)return e;let{root:r,...i}=e;return i}function iC(e,t){if(!t)return!0;if(!rP(e))return!1;let r=rP(e.trace)?e.trace:{};return e.traceId===t||r.trace_id===t}function iE(e){return rP(e)?{...iR(e,["messageId","localMessageId","requestId","traceId","role","contentType","status","createdAtMs"]),text:"string"==typeof e.text?ij(e.text):void 0,blocks:Array.isArray(e.blocks)?e.blocks.map(iN):void 0,toolCalls:Array.isArray(e.toolCalls)?e.toolCalls:void 0,toolResults:Array.isArray(e.toolResults)?e.toolResults:void 0}:e}function iN(e){return rP(e)?"card"===e.type?{...iR(e,["blockId","type"]),card:iA(e.card)}:"image"===e.type&&rP(e.image)?{...iR(e,["blockId","type"]),image:iR(e.image,["resource_uri","mime_type","size_bytes","width","height","sha256","name"])}:{...iR(e,["blockId","type"]),text:"string"==typeof e.text?ij(e.text):void 0}:e}function iT(e){return rP(e)?{...iR(e,["requestId","runId","replyMessageId","toolCallId","toolName","serverId","appKey","status","createdAtMs","updatedAtMs","requiresUserApproval","timeoutMs","deadlineMs","progress","message","resultSummary","structuredResultSummary","isMiniApp"]),arguments:e.arguments,argumentsJson:void 0===e.arguments&&e.argumentsJson?e.argumentsJson:void 0,error:e.error?iM(e.error):void 0}:e}function iA(e){return rP(e)?iR(e,["reply_message_id","block_id","card_id","widget_id","card_type","app_id","entity_id","title","fallback_text"]):e}function iM(e){return rP(e)?iR(e,["code","message","user_message","retryable","stage","details","name","stack"]):e}function iR(e,t){let r={};for(let i of t)void 0!==e[i]&&(r[i]=e[i]);return r}function ij(e){return e.length>1e3?`${e.slice(0,1e3)}...`:e}let iP=[1e3,2e3,4e3,8e3,16e3];class iL{clientId=crypto.randomUUID();socket;status="disconnected";listeners=new Set;retryTimer;retryIndex=0;sandboxSnapshot;snapshot;sentRuntime;snapshotErrorReported=!1;subscribe(e){return this.listeners.add(e),e({type:"status",status:this.status}),void 0!==this.sandboxSnapshot&&e({type:"sandbox",data:this.sandboxSnapshot}),()=>{this.listeners.delete(e)}}start(){this.stop(),this.retryIndex=0,this.connect()}stop(){clearTimeout(this.retryTimer),this.retryTimer=void 0;let e=this.socket;this.socket=void 0,null==e||e.close(),this.sandboxSnapshot=void 0,this.setStatus("disconnected")}emit(e){for(let t of this.listeners)t(e)}setStatus(e){this.status!==e&&(this.status=e,this.emit({type:"status",status:e}))}connect(){let e;this.setStatus(this.retryIndex?"reconnecting":"connecting");let t=new URL("/__wsd_connection",window.location.href);t.protocol="https:"===t.protocol?"wss:":"ws:",t.searchParams.set("clientId",this.clientId);let r=new WebSocket(t);this.socket=r,r.onopen=()=>{this.socket===r&&(e=Date.now(),this.sentRuntime=void 0,this.sendSnapshot(),this.setStatus("connected"))},r.onmessage=e=>{let t;if(this.socket===r){try{t=JSON.parse(e.data)}catch{r.close(4e3,"Invalid debugger message");return}if(rP(t))if("control"===t.type){let e=function(e){if(!rP(e)||"string"!=typeof e.commandId)return null;if("render_page"===e.type&&"string"==typeof e.url)return{commandId:e.commandId,type:e.type,url:e.url};if("render_widget"===e.type&&"string"==typeof e.widgetId&&rP(e.structuredContent))return{commandId:e.commandId,type:e.type,widgetId:e.widgetId,structuredContent:e.structuredContent};if("set_viewport"===e.type&&rX(e.width)&&rX(e.height))return{commandId:e.commandId,type:e.type,width:e.width,height:e.height};if("submit_chat_query"===e.type&&"string"==typeof e.query&&e.query.trim())return{commandId:e.commandId,type:e.type,query:e.query.trim()};if("cancel_chat_query"===e.type)return{commandId:e.commandId,type:e.type};if("execute_sandbox_tool_call"===e.type){var t;let r="object"==typeof(t=e.toolCall)&&(null==t?void 0:t.tool_call)?t:void 0;return r?{commandId:e.commandId,toolCall:r,type:e.type}:null}if("get_computed_style"===e.type&&"string"==typeof e.uid)return void 0===e.properties||Array.isArray(e.properties)&&e.properties.every(e=>"string"==typeof e)?{commandId:e.commandId,type:e.type,uid:e.uid,properties:e.properties}:null;if("take_snapshot"===e.type&&("current"===e.target||"page"===e.target||"widget"===e.target))return{commandId:e.commandId,type:e.type,target:e.target};if("get_element_rect"===e.type&&"string"==typeof e.uid)return{commandId:e.commandId,type:e.type,uid:e.uid};if("take_screenshot"===e.type){let t=e.format??"png",r=e.quality;return void 0!==e.uid&&"string"!=typeof e.uid||"png"!==t&&"jpeg"!==t&&"webp"!==t||void 0!==r&&("number"!=typeof r||!Number.isFinite(r)||r<0||r>100)?null:{commandId:e.commandId,type:e.type,format:t,uid:"string"==typeof e.uid?e.uid:void 0,quality:"number"==typeof r?r:void 0}}return"scroll_to"===e.type?(void 0===e.uid||"string"==typeof e.uid&&e.uid.trim())&&(void 0===e.x||rY(e.x))&&(void 0===e.y||rY(e.y))?{commandId:e.commandId,type:e.type,uid:"string"==typeof e.uid?e.uid:void 0,x:"number"==typeof e.x?e.x:void 0,y:"number"==typeof e.y?e.y:void 0}:null:null}(t.data);e&&this.emit({type:"control",data:e})}else"sandbox"===t.type&&(this.sandboxSnapshot=t.data,this.emit({type:"sandbox",data:t.data}))}},r.onclose=t=>{if(this.socket!==r)return;this.socket=void 0,this.sandboxSnapshot=void 0,void 0!==e&&Date.now()-e>=3e4&&(this.retryIndex=0);let i=iP[this.retryIndex++];void 0===i||1008===t.code||1009===t.code?this.setStatus("disconnected"):(this.setStatus("reconnecting"),this.retryTimer=setTimeout(()=>this.connect(),i))}}send(e){var t;if(new TextEncoder().encode(e).byteLength>0xa00000)throw Error("本地调试消息超过 10MiB,无法发送");if((null==(t=this.socket)?void 0:t.readyState)!==WebSocket.OPEN)throw Error("本地调试服务未连接");if(this.socket.bufferedAmount>0xa00000)throw this.socket.close(4e3,"Debugger connection is too slow"),Error("本地调试服务发送缓冲区已满");this.socket.send(e)}async reportResult(e){this.send(JSON.stringify({type:"control_result",data:e}))}async clearSandboxLogs(){this.send(JSON.stringify({type:"clear_sandbox_logs"}))}publishSnapshot(e,t){this.snapshot={payload:e,runtime:t},this.sendSnapshot()}sendSnapshot(){var e;if(!this.snapshot||(null==(e=this.socket)?void 0:e.readyState)!==WebSocket.OPEN)return;let{payload:t,runtime:r}=this.snapshot;try{let e=iS(t,{includeRuntimeRoot:r!==this.sentRuntime});this.send(i_({type:"snapshot",data:e})),this.sentRuntime=r,this.snapshotErrorReported=!1}catch(e){this.snapshotErrorReported||console.warn("调试快照上传失败,控制连接保持可用:",e),this.snapshotErrorReported=!0}}}var iO=r(64865),iD=r(11855);function iU(e){return"string"==typeof e&&/^[\da-f]{8}-(?:[\da-f]{4}-){3}[\da-f]{12}$/i.test(e)}function iq(e){return`${e.uuid.toLowerCase()}-${e.major}-${e.minor}`}function i$(e){if("boolean"!=typeof e.rangingAvailable||"boolean"!=typeof e.locationAuthorized||!Array.isArray(e.beacons))throw Error("Beacon 测距、系统定位授权需为布尔值,广播需为数组");let t=new Set;for(let r of e.beacons){if(!r||!iU(r.uuid)||![r.major,r.minor].every(e=>Number.isInteger(e)&&e>=0&&e<=65535)||![0,1,2,3].includes(r.proximity)||!Number.isFinite(r.accuracy)||r.accuracy<-1||!Number.isInteger(r.rssi)||r.rssi<-127||r.rssi>20)throw Error("Beacon 需包含完整 UUID、0–65535 major/minor、0–3 proximity、accuracy 米和整数 rssi dBm");let e=iq(r);if(t.has(e))throw Error("Beacon UUID/major/minor 组合不能重复");t.add(e)}}function iB(e){return Object.freeze({...e,beacons:Object.freeze(e.beacons.map(e=>Object.freeze({...e})))})}let iF={rangingAvailable:!0,locationAuthorized:!0,beacons:[{uuid:"00000000-0000-0000-0000-000000000000",major:1,minor:2,proximity:2,accuracy:1.2,rssi:-55},{uuid:"99999999-9999-9999-9999-999999999999",major:3,minor:4,proximity:3,accuracy:5,rssi:-75}]};function iz(e){let t=e.trim().replace(/^\{|\}$/g,"").replaceAll("-","").toLowerCase();if(/^[\da-f]+$/.test(t)){if(4===t.length||8===t.length)return`${t.padStart(8,"0")}-0000-1000-8000-00805f9b34fb`;if(32===t.length)return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}}function iW(e){return"string"==typeof e&&/^(?:[A-Za-z\d+/]{4})*(?:[A-Za-z\d+/]{2}==|[A-Za-z\d+/]{3}=)?$/.test(e)}function iH(e){if("boolean"!=typeof e.available||"boolean"!=typeof e.enabled||"boolean"!=typeof e.authorized||!Array.isArray(e.devices))throw Error("蓝牙硬件、开关和授权需为布尔值,设备列表需为数组");let t=new Set;for(let r of e.devices){if(!r||"string"!=typeof r.deviceId||!r.deviceId.trim()||"string"!=typeof r.name||void 0!==r.localName&&"string"!=typeof r.localName||!Number.isInteger(r.RSSI)||r.RSSI<-127||r.RSSI>20||"boolean"!=typeof r.connectable||!Array.isArray(r.advertisServiceUUIDs)||r.advertisServiceUUIDs.some(e=>"string"!=typeof e||!iz(e))||void 0!==r.advertisData&&!iW(r.advertisData)||void 0!==r.serviceData&&(!r.serviceData||"object"!=typeof r.serviceData||Array.isArray(r.serviceData)||Object.entries(r.serviceData).some(e=>{let[t,r]=e;return!iz(t)||!iW(r)})))throw Error("设备需包含 deviceId、name、RSSI、connectable 和服务 UUID 数组;广播数据使用 Base64");if(t.has(r.deviceId.toLowerCase()))throw Error("蓝牙 deviceId 不能重复");if(t.add(r.deviceId.toLowerCase()),void 0!==r.paired&&"boolean"!=typeof r.paired||void 0!==r.pin&&!iW(r.pin)||void 0!==r.connectionDelayMs&&(!Number.isInteger(r.connectionDelayMs)||r.connectionDelayMs<0||r.connectionDelayMs>6e4)||void 0!==r.maxMTU&&(!Number.isInteger(r.maxMTU)||r.maxMTU<23||r.maxMTU>517))throw Error("配对状态需为布尔值,PIN 使用 Base64;连接延迟为 0–60000 ms、MTU 为 23–517");if(void 0!==r.services){if(!Array.isArray(r.services))throw Error("BLE 服务需为数组");let e=new Set;for(let t of r.services){let r="string"==typeof(null==t?void 0:t.uuid)?iz(t.uuid):void 0;if(!r||e.has(r)||"boolean"!=typeof t.isPrimary||!Array.isArray(t.characteristics))throw Error("BLE 服务需包含唯一 UUID、isPrimary 和特征数组");e.add(r);let i=new Set;for(let e of t.characteristics){let t="string"==typeof(null==e?void 0:e.uuid)?iz(e.uuid):void 0;if(!t||i.has(t)||!iW(e.value)||!e.properties||["read","write","writeNoResponse","notify","indicate"].some(t=>"boolean"!=typeof e.properties[t]))throw Error("BLE 特征需包含唯一 UUID、Base64 value 和 read/write/writeNoResponse/notify/indicate 布尔属性");i.add(t)}}}}}function iV(e){return Object.freeze({...e,devices:Object.freeze(e.devices.map(e=>Object.freeze({...e,advertisServiceUUIDs:Object.freeze([...e.advertisServiceUUIDs]),...e.serviceData?{serviceData:Object.freeze({...e.serviceData})}:{},...e.services?{services:Object.freeze(e.services.map(e=>Object.freeze({...e,characteristics:Object.freeze(e.characteristics.map(e=>Object.freeze({...e,properties:Object.freeze({...e.properties})})))})))}:{}})))})}let iG={available:!0,enabled:!0,authorized:!0,devices:[{deviceId:"12:34:56:78:9A:BC",name:"Virtual BLE Sensor",localName:"Virtual Sensor",RSSI:-55,connectable:!0,advertisData:"AQIDBA==",advertisServiceUUIDs:["180F"],serviceData:{"180F":"ZA=="},paired:!1,pin:"MDAwMDAw",maxMTU:247,services:[{uuid:"FFF0",isPrimary:!0,characteristics:[{uuid:"FFF1",properties:{read:!0,write:!0,writeNoResponse:!0,notify:!0,indicate:!0},value:"ZA=="}]}]},{deviceId:"12:34:56:78:9A:BD",name:"Virtual Heart Rate",RSSI:-70,connectable:!0,advertisServiceUUIDs:["180D"]}]},iJ=["wifi","2g","3g","4g","5g","unknown","none"],iK=["request","upload","download","socket"],iZ={enabled:!1,request:"",upload:"",download:"",socket:""};function iX(e,t){try{var r,i;let n=null==(r=e.trim().match(/^[a-z][\da-z+.-]*:\/\/([^/?#]*)/i))?void 0:r[1];if(!n||/[\s\\]/.test(n))return;let a=new URL(e.trim());if(a.protocol!==("socket"===t?"wss:":"https:")||a.hostname.includes("*"))return;let s=null==(i=n.slice(n.lastIndexOf("@")+1).match(/:(\d+)$/))?void 0:i[1];if(void 0!==s&&(1>Number(s)||Number(s)>65535))return;return`${a.protocol}//${a.hostname}${void 0===s?"":`:${Number(s)}`}`}catch{return}}function iY(e){return e.split(/[\s,]+/).filter(Boolean)}function iQ(e){return Object.freeze({...e,...e.domainPolicy?{domainPolicy:Object.freeze({...e.domainPolicy})}:{}})}let i0={networkType:"wifi",signalStrength:-55,hasSystemProxy:!1};function i1(e){if(!iJ.includes(e.networkType)||!Number.isInteger(e.signalStrength)||e.signalStrength<-126||e.signalStrength>-1||"boolean"!=typeof e.hasSystemProxy)throw Error("网络制式必须为预设值,Wi-Fi 信号为 -126 至 -1 的整数 dBm,代理状态为布尔值");let t=e.domainPolicy;if(void 0!==t&&(!t||"boolean"!=typeof t.enabled||iK.some(e=>"string"!=typeof t[e]||t.enabled&&iY(t[e]).some(t=>!iX(t,e)))))throw Error("域名白名单使用 HTTPS 地址,Socket 使用 WSS 地址;不支持通配符")}let i2=["not determined","full","denied","restricted"],i3=[...i2,"limited","add only"],i4=[...i2,"read only","write only"],i6=[...i2,"provisional"],i5=["not determined","authorized","denied"],i8=[...i2,"partial"],i9=["not determined","denied","restricted","foreground precise","foreground approximate","background precise","background approximate"];function i7(e){if(void 0!==e.healthData){let t=e.healthData;if("boolean"!=typeof t.requestCompleted||!t.readStatus||"object"!=typeof t.readStatus||Array.isArray(t.readStatus)||Object.entries(t.readStatus).some(e=>{let[t,r]=e;return!t.trim()||![-1,0,1,2].includes(r)}))throw Error("健康数据配置需包含流程结果和读取状态(-1、0、1、2)")}if(void 0!==e.theme&&"light"!==e.theme&&"dark"!==e.theme||"boolean"!=typeof e.locationEnabled||"boolean"!=typeof e.locationReducedAccuracy||void 0!==e.bluetoothAuthorization&&!i8.includes(e.bluetoothAuthorization)||void 0!==e.locationAuthorization&&!i9.includes(e.locationAuthorization)||void 0!==e.contacts&&!i2.includes(e.contacts)||!i2.includes(e.camera)||!i2.includes(e.microphone)||!i3.includes(e.album)||!i4.includes(e.phoneCalendar)||!i6.includes(e.notification)||!i5.includes(e.notificationAlert)||!i5.includes(e.notificationBadge)||!i5.includes(e.notificationSound))throw Error("系统开关需为布尔值,授权状态必须为对应权限的预设值")}function ne(e){return Object.freeze({...e,...e.healthData?{healthData:Object.freeze({...e.healthData,readStatus:Object.freeze({...e.healthData.readStatus})})}:{}})}let nt={locationEnabled:!0,locationReducedAccuracy:!1,contacts:"not determined",camera:"not determined",microphone:"not determined",album:"not determined",phoneCalendar:"not determined",notification:"not determined",notificationAlert:"not determined",notificationBadge:"not determined",notificationSound:"not determined"},nr=Object.freeze({accelerometer:Object.freeze({x:0,y:0,z:9.80665}),gyroscope:Object.freeze({x:0,y:0,z:0})}),ni=["system","storage","battery","network","location","bluetooth","sensors","screen","audio","accessibility","calendar","communication"],nn="doubao-debugger-open-hardware-settings";function na(e){window.dispatchEvent(new CustomEvent(nn,{detail:e}))}function ns(e){var t;return JSON.stringify([e.ssid,(null==(t=e.bssid)?void 0:t.toLowerCase())??""])}function no(e){if("boolean"!=typeof e.available||"boolean"!=typeof e.enabled||"string"!=typeof e.connectedNetworkKey||!Array.isArray(e.networks))throw Error("Wi-Fi 开关、连接标识和网络列表格式错误");let t=new Set;for(let r of e.networks){if(!r||"string"!=typeof r.ssid||!r.ssid.trim()||"string"!=typeof r.password||void 0!==r.bssid&&("string"!=typeof r.bssid||!/^(?:[\da-f]{2}:){5}[\da-f]{2}$/i.test(r.bssid))||void 0!==r.secure&&"boolean"!=typeof r.secure||void 0!==r.signalStrength&&(!Number.isFinite(r.signalStrength)||r.signalStrength<0||r.signalStrength>100)||void 0!==r.frequency&&(!Number.isInteger(r.frequency)||r.frequency<=0))throw Error("网络需包含 ssid、password;BSSID 使用 MAC 地址,信号强度为 0–100,频率为正整数 MHz");let e=ns(r);if(t.has(e))throw Error("SSID 和 BSSID 组合不能重复");t.add(e)}if(e.connectedNetworkKey&&!t.has(e.connectedNetworkKey))throw Error("当前连接必须来自虚拟网络列表")}function nl(e){return Object.freeze({...e,networks:Object.freeze(e.networks.map(e=>Object.freeze({...e})))})}function nd(e){if("boolean"!=typeof e.available||![e.alpha,e.beta,e.gamma].every(Number.isFinite))throw Error("设备方向必须为有限弧度数值,可用性必须为布尔值")}let nu=["high","medium","low","unreliable","no-contact"];function nc(e){if("boolean"!=typeof e.available)throw Error("传感器可用性必须为布尔值")}function np(e){if(!Number.isInteger(e.level)||e.level<0||e.level>100||"boolean"!=typeof e.isCharging||"boolean"!=typeof e.isLowPowerModeEnabled)throw Error("电量必须为 0 至 100 的整数,充电和省电模式必须为布尔值")}function nh(e){if("boolean"!=typeof e.available||!Number.isFinite(e.direction)||e.direction<0||e.direction>360||!nu.includes(e.accuracy))throw Error("罗盘方向必须为 0 至 360 度,精度必须为预设值")}function nm(e,t,r){try{let t=localStorage.getItem(e);if(t){let e=JSON.parse(t);return r(e),Object.freeze({...e})}}catch{}return Object.freeze({...t})}let ng="doubao-debugger-virtual-battery",nf="doubao-debugger-virtual-accelerometer",nv="doubao-debugger-virtual-gyroscope",ny="doubao-debugger-virtual-compass",nb="doubao-debugger-virtual-device-motion",nw="doubao-debugger-virtual-wifi",n_="doubao-debugger-virtual-network",nS="doubao-debugger-virtual-bluetooth",nx="doubao-debugger-virtual-beacon",nI="doubao-debugger-virtual-system",nk="doubao-debugger-virtual-screen",nC="doubao-debugger-virtual-keyboard",nE="doubao-debugger-virtual-accessibility",nN="doubao-debugger-virtual-communication",nT={phoneAvailable:!0,phoneOpenSucceeds:!0,smsAvailable:!0,smsOpenSucceeds:!0,smsSendSucceeds:!0};function nA(e){if(Object.keys(nT).some(t=>"boolean"!=typeof e[t]))throw Error("电话和短信能力、打开结果及发送结果必须为布尔值")}let nM={available:!0,androidEnabled:!1,touchExplorationEnabled:!1,voiceOverRunning:!1,switchControlRunning:!1};function nR(e){if(Object.keys(nM).some(t=>"boolean"!=typeof e[t]))throw Error("无障碍服务与辅助功能开关必须为布尔值")}function nj(e){if(!Number.isFinite(e.height)||e.height<0||e.height>1e3)throw Error("键盘高度必须为 0 至 1000 的有限数值")}function nP(e){if(!Number.isFinite(e.brightness)||e.brightness<0||e.brightness>1||"boolean"!=typeof e.recording)throw Error("亮度必须为 0 至 1 的有限数值,录屏状态需为布尔值")}let nL=new class{network=iQ(nm(n_,i0,i1));effectiveBluetooth;effectiveBeacon;communication=nm(nN,nT,nA);accessibility=nm(nE,nM,nR);keyboard=nm(nC,{height:300},nj);screen=nm(nk,{brightness:1,recording:!1},nP);system=ne(nm(nI,nt,i7));beacon=iB(nm(nx,iF,i$));bluetooth=iV(nm(nS,iG,iH));battery=nm(ng,{isCharging:!1,isLowPowerModeEnabled:!1,level:100},np);accelerometer=nm(nf,{available:!0},nc);gyroscope=nm(nv,{available:!0},nc);motionSample=nr;compass=nm(ny,{available:!0,direction:0,accuracy:"high"},nh);listeners=new Map;wifi=nl(nm(nw,{available:!0,enabled:!0,connectedNetworkKey:"",networks:[{ssid:"wifi-name",bssid:"10:20:30:40:50:60",password:"wifi-password",secure:!0,signalStrength:88,frequency:2462},{ssid:"guest-wifi",bssid:"10:20:30:40:50:61",password:"",secure:!1,signalStrength:50,frequency:5180}]},no));deviceMotion=nm(nb,{available:!0,alpha:0,beta:0,gamma:0},nd);getBattery=()=>this.battery;getGyroscope=()=>({available:this.gyroscope.available,...this.motionSample.gyroscope});getAccelerometer=()=>({available:this.accelerometer.available,...this.motionSample.accelerometer});getCompass=()=>this.compass;getDeviceMotion=()=>this.deviceMotion;getWifi=()=>this.wifi;getNetwork=()=>this.network;getBluetooth=()=>{let e=this.system.bluetoothAuthorization;return void 0===e?this.bluetooth:this.effectiveBluetooth??=iV({...this.bluetooth,authorized:"full"===e})};getBeacon=()=>{let e=this.system.locationAuthorization;return void 0===e?this.beacon:this.effectiveBeacon??=iB({...this.beacon,locationAuthorized:e.startsWith("foreground ")||e.startsWith("background ")})};getSystem=()=>this.system;getScreen=()=>this.screen;getKeyboard=()=>this.keyboard;getAccessibility=()=>this.accessibility;getCommunication=()=>this.communication;setCommunication(e){nA(e),this.communication=Object.freeze({...e}),this.persist(nN,this.communication)}setNetwork(e){i1(e),this.network=iQ(e),this.persistAndNotify(n_,this.network,"network")}setAccessibility(e){nR(e),this.accessibility=Object.freeze({...e}),this.persist(nE,this.accessibility)}setKeyboard(e){nj(e),this.keyboard=Object.freeze({...e}),this.persistAndNotify(nC,this.keyboard,"keyboard")}setScreen(e){nP(e),this.screen=Object.freeze({...e}),this.persistAndNotify(nk,this.screen,"screen")}setSystem(e){i7(e);let t=this.system;this.system=ne(e);let r=t.bluetoothAuthorization!==e.bluetoothAuthorization,i=t.locationAuthorization!==e.locationAuthorization;r&&(this.effectiveBluetooth=void 0),i&&(this.effectiveBeacon=void 0),this.persist(nI,this.system),r&&this.notify("bluetooth"),i&&this.notify("beacon"),(i||t.locationEnabled!==e.locationEnabled||t.locationReducedAccuracy!==e.locationReducedAccuracy)&&this.notify("location"),t.theme!==e.theme&&this.notify("theme"),this.notify("system")}setBeacon(e){i$(e);let t=e.locationAuthorized!==this.getBeacon().locationAuthorized;t&&(this.system=Object.freeze({...this.system,locationAuthorization:void 0}),this.persist(nI,this.system)),this.effectiveBeacon=void 0,this.beacon=iB(e),this.persistAndNotify(nx,this.beacon,"beacon"),t&&this.notify("location")}setBluetooth(e){iH(e),e.authorized!==this.getBluetooth().authorized&&(this.system=Object.freeze({...this.system,bluetoothAuthorization:void 0}),this.persist(nI,this.system)),this.effectiveBluetooth=void 0,this.bluetooth=iV(e),this.persistAndNotify(nS,this.bluetooth,"bluetooth")}subscribe=(e,t)=>{let r=this.listeners.get(e)??new Set;return this.listeners.set(e,r),r.add(t),()=>r.delete(t)};setMotionSample(e){this.motionSample=Object.freeze({accelerometer:Object.freeze({...e.accelerometer}),gyroscope:Object.freeze({...e.gyroscope})})}setAccelerometer(e){nc(e),this.accelerometer=Object.freeze({available:e.available}),this.persist(nf,this.accelerometer)}setGyroscope(e){nc(e),this.gyroscope=Object.freeze({available:e.available}),this.persist(nv,this.gyroscope)}setCompass(e){nh(e),this.compass=Object.freeze({...e}),this.persist(ny,this.compass)}setDeviceMotion(e){nd(e),this.deviceMotion=Object.freeze({...e}),this.persist(nb,this.deviceMotion)}setWifi(e){no(e),this.wifi=nl(e),this.persistAndNotify(nw,this.wifi,"wifi")}setBattery(e){np(e),(e.level!==this.battery.level||e.isCharging!==this.battery.isCharging||e.isLowPowerModeEnabled!==this.battery.isLowPowerModeEnabled)&&(this.battery=Object.freeze({...e}),this.persistAndNotify(ng,this.battery,"battery"))}persistAndNotify(e,t,r){this.persist(e,t),this.notify(r)}notify(e){for(let t of this.listeners.get(e)??[])t()}persist(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch{}}},nO="network unavailable (simulator offline)";function nD(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;return"none"!==e.getNetwork().networkType}function nU(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;if(!nD(e))throw Error(nO)}function nq(e){return!/^(?:appletfile|data|blob):/i.test(e)}function n$(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nL,r=nD(t);return t.subscribe("network",()=>{let i=nD(t),n=r&&!i;r=i,n&&e()})}async function nB(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nL;nU(t);let r=new AbortController,i=n$(()=>r.abort(Error(nO)),t),n=()=>{},a=new Promise((e,t)=>{n=()=>t(r.signal.reason),r.signal.addEventListener("abort",n,{once:!0})});try{return await Promise.race([e(r.signal),a])}finally{i(),r.signal.removeEventListener("abort",n)}}function nF(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:nL,i=r.getNetwork().domainPolicy;if(!(null==i?void 0:i.enabled))return;let n=iX(e,t);if(!n||!iY(i[t]).some(e=>iX(e,t)===n)){if("upload"===t)throw new w("uploadFile:fail url not in domain list",121901);throw new w(`${t} domain is not in whitelist${n?"":" (HTTPS/WSS required)"}`,"download"===t?-1:110)}}function nz(e){return e instanceof Map?Array.from(e.entries(),e=>{let[t,r]=e;return[String(t),r]}):!e||"object"!=typeof e||Array.isArray(e)||e instanceof ArrayBuffer?void 0:Object.entries(e)}function nW(e){return e.map(e=>{let[t,r]=e;return`${encodeURIComponent(t)}=${encodeURIComponent(null===r?"null":r&&"object"==typeof r?JSON.stringify(r)??String(r):String(r))}`}).join("&")}function nH(e){let t=new Uint8Array(e),r="";for(let e=0;e<t.length;e+=32768)r+=String.fromCharCode(...t.subarray(e,e+32768));return btoa(r)}function nV(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"json";if("arraybuffer"===t)return e;let r=new TextDecoder().decode(e);if("string"===t||0===r.length)return r;try{return JSON.parse(r)}catch{return nH(e)}}function nG(e){let t={};return e.forEach((e,r)=>{t[r]=e}),t}function nJ(e){var t;let r;if("string"!=typeof e.method&&void 0!==e.method)throw new w("method must be a string",104);let i=(e.method??"GET").trim().toUpperCase();if(!["GET","POST","PUT","DELETE","HEAD","OPTIONS"].includes(i))throw new w(`Unsupported request method: ${i}`,104);if("string"!=typeof e.url||0===e.url.trim().length)throw new w("url must be a non-empty string",104);let n=e.url,a=((r=new Headers(e.header)).has("content-type")||r.set("content-type","application/json"),r);return{body:"GET"!==i&&"HEAD"!==i?function(e,t){if(null!=e){if("string"==typeof e||e instanceof ArrayBuffer)return e;if(t.includes("application/x-www-form-urlencoded")){let t=nz(e);if(t)return nW(t)}return t.includes("application/json")||"object"==typeof e?JSON.stringify(e):String(e)}}(e.data,(null==(t=a.get("content-type"))?void 0:t.toLowerCase())??""):void 0,headers:nG(a),method:i,url:"GET"===i?function(e,t){let r=nz(t);if(!(null==r?void 0:r.length))return e;let i=e.indexOf("#"),n=-1===i?"":e.slice(i),a=-1===i?e:e.slice(0,i),s=a.endsWith("?")||a.endsWith("&")?"":a.includes("?")?"&":"?";return`${a}${s}${nW(r)}${n}`}(n,e.data):n}}async function nK(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nJ(e);return nF(t.url,"request"),nB(async r=>{let i=await fetch(t.url,{signal:r,body:t.body,headers:t.headers,method:t.method}),n=nV(await i.arrayBuffer(),e.dataType);return{statusCode:i.status,header:nG(i.headers),data:n}})}let nZ="/__web_artifacts/base/manifest.json",nX="/app_developer";function nY(e){return!e.debugHidden}r(95600);let nQ={chat:"chat","image-upload":"images/upload","tool-report":"tool/report"};function n0(e){let t=rM(String(e??nX).trim(),{addProtocolToBareHost:!0,allowRootRelative:!0,defaultProtocol:n1}).replace(/\/+$/,"");if(t.startsWith("/"))return t;try{let e=new URL(t);if(""===e.pathname||"/"===e.pathname)return e.pathname="/app_developer",e.toString().replace(/\/+$/,"")}catch{}return t}function n1(e){return/^(localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|\[::1\])(?::|\/|$)/i.test(e)?"http":"https"}function n2(e){var t;let r="function"==typeof(null==(t=globalThis.crypto)?void 0:t.randomUUID)?globalThis.crypto.randomUUID().replace(/-/g,""):Math.random().toString(36).slice(2);return`${e}_${Date.now().toString(36)}${r.slice(0,10)}`}function n3(e,t){return`${n0(e)}/api/simulator/${nQ[t]}`}function n4(e){if(e.type&&!e.type.startsWith("image/"))throw Error("仅支持图片文件");if(e.size>0xa00000)throw Error("图片不能超过 10 MiB")}var n6=r(75585);let n5=["ack","message_start","text_delta","tool_call","tool_status","card_delta","content_block","stream_error","message_finish","reply_finish","answer_finish","trace_event","heartbeat"];async function n8(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=e.getReader(),n=new TextDecoder,a={...r,fallbackSeq:0},s=(0,n6.C)({onEvent:e=>{let r=function(e,t){var r,i,n;let a,s,o,l,d,u,c=void 0===(l=r3(r=e.data))&&r.trim()?r:l,p=rP(c)?{...c,event:c.event||e.event}:{event:e.event||"message",data:c},{eventType:h,payload:m}=function(e){var t;for(let t of n5){let r=e[t];if(rP(r))return{eventType:t,payload:r};if("content_block"===t&&Array.isArray(r))return{eventType:t,payload:{content_block:r}}}return{eventType:"string"==typeof(t=e.event)&&t?t.toLowerCase():"message",payload:e}}(p),g=rP(m)?m:{},f="number"==typeof p.sequence&&Number.isFinite(p.sequence)?p.sequence:t.fallbackSeq+=1,v=e.id||("string"==typeof p.id?p.id:"")||`evt_${f.toString().padStart(4,"0")}`,y=function(e,t,r){let i=("string"==typeof e.request_id?e.request_id:"")||("ack"===r&&"string"==typeof t.request_id?t.request_id:"");if("ack"===r&&!i)throw Error("Invalid simulator SSE ACK: missing request_id");return i||("string"==typeof e.id?e.id:"")}(p,g,h),b=("string"==typeof p.reply_message_id?p.reply_message_id:"")||("string"==typeof g.message_id?g.message_id:"")||t.replyMessageId;return{event_id:v,event_type:h,seq:f,request_id:y,query_message_id:("string"==typeof p.query_message_id?p.query_message_id:"")||("string"==typeof g.query_message_id?g.query_message_id:""),reply_message_id:b,created_at_ms:"number"==typeof p.timestamp_ms&&Number.isFinite(p.timestamp_ms)?p.timestamp_ms:Date.now(),received_at_ms:Date.now(),trace:(d=rP(p.trace)?p.trace:{},{trace_id:"string"==typeof(u=t.trace??{}).trace_id?u.trace_id:"string"==typeof d.trace_id?d.trace_id:n2("trace"),span_id:"string"==typeof d.span_id?d.span_id:n2("span_sse"),parent_span_id:"string"==typeof d.parent_span_id?d.parent_span_id:"string"==typeof u.span_id?u.span_id:void 0,component:"string"==typeof d.component?d.component:"app_developer_simulator",stage:"string"==typeof d.stage?d.stage:h,sampled:"boolean"==typeof d.sampled?d.sampled:"boolean"!=typeof u.sampled||u.sampled,baggage:{...rP(u.baggage)?u.baggage:{},...rP(d.baggage)?d.baggage:{}}}),payload:(i=g,0===(o=Array.isArray(s=rP(a=null==(n=t.trace)?void 0:n.baggage)?a.log_ids:void 0)?s.filter(e=>"string"==typeof e&&e.trim().length>0):"string"==typeof s&&s.trim()?[s]:[]).length||void 0!==i.log_ids?i:{...i,log_ids:o})}}(e,a);r.reply_message_id&&(a.replyMessageId=r.reply_message_id),t(r)}});for(;;){let{done:e,value:t}=await i.read();if(t&&s.feed(n.decode(t,{stream:!e})),e)break}let o=n.decode();o&&s.feed(o),s.feed("\n\n")}let n9="x-tt-logid";class n7 extends Error{responseDebug;constructor(e,t){super(e),this.responseDebug=t,this.name="SimulatorHttpError"}}function ae(e){return e.headers.get(n9)}function at(e){let t={},r=ae(e);return r&&(t[n9]=r),t}function ar(e){return rP(e.trace)?e.trace:{}}async function ai(e,t){let r=ae(t),i=at(t),n=await t.text().catch(()=>""),a={status:t.status,status_text:t.statusText,response_headers:Object.keys(i).length>0?i:void 0,log_ids:r?[r]:void 0,response_text:n};return new n7(`${e}: ${t.status} ${t.statusText}`,a)}function an(e){return e instanceof n7?e.responseDebug:void 0}function aa(e,t,r){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},n=arguments.length>4?arguments[4]:void 0,a=ar(e),s=Date.now();return{event_id:n2("evt_client_debug"),event_type:"debug",seq:0,request_id:"string"==typeof e.idempotency_key?e.idempotency_key:"client_debug",created_at_ms:s,received_at_ms:s,trace:{trace_id:"string"==typeof a.trace_id?a.trace_id:n2("trace"),component:"string"==typeof a.component?a.component:"simulator_web_tester",stage:"string"==typeof a.stage?a.stage:"query",sampled:"boolean"!=typeof a.sampled||a.sampled,baggage:n??(rP(a.baggage)?a.baggage:{})},payload:{event:t,category:"api",elapsed_ms:Date.now()-r,...i}}}async function as(e){var t;let{endpoint:r,fetcher:i,file:n,signal:a}=e;n4(n);let s=new FormData;s.append("image",n);let o=await (i??fetch)(n3(r,"image-upload"),{method:"POST",headers:{Accept:"application/json"},body:s,signal:a});if(!o.ok)throw await ai("Simulator image upload failed",o);let l=await o.json();if(0!==l.code)throw new n7(l.message||`Simulator image upload failed with code ${l.code}`,{response_body:l,log_ids:l.log_id?[l.log_id]:void 0});let d=null==(t=l.data)?void 0:t.image;if(!(null==d?void 0:d.resource_uri))throw new n7("Simulator image upload response is missing image.resource_uri",{response_body:l,log_ids:l.log_id?[l.log_id]:void 0});return d}async function ao(e){let t,{endpoint:r,fetcher:i,onEvent:n,onSubmitted:a,request:s,signal:o}=e,l=Date.now(),d=n3(r,"chat");n(aa(s,"simulator_chat_fetch_started",l,{endpoint:"chat",phase:"request",request:s,request_json:r6(s),url:d}));let u=setTimeout(()=>{n(aa(s,"simulator_chat_fetch_waiting_for_headers",l,{endpoint:"chat",phase:"wait",url:d,wait_ms:5e3}))},5e3);try{let e=(i??fetch)(d,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(s),signal:o});null==a||a(),t=await e}catch(e){throw clearTimeout(u),n(aa(s,"simulator_chat_fetch_failed",l,{endpoint:"chat",phase:"error",url:d,error:r5(e)})),e}clearTimeout(u);let c=ae(t),p=at(t),h=ar(s),m={...rP(h.baggage)?h.baggage:{}};if(c&&(m[n9]=c,m.log_ids=[c]),n(aa(s,"simulator_chat_headers_received",l,{event:"simulator_chat_response_meta",endpoint:"chat",phase:"response",status:t.status,status_text:t.statusText,log_ids:c?[c]:void 0,response_headers:Object.keys(p).length>0?p:void 0},m)),!t.ok){let e=await ai("Simulator query failed",t);throw n(aa(s,"simulator_chat_fetch_failed",l,{endpoint:"chat",phase:"error",error:e.message,...e.responseDebug},m)),e}if(!t.body)throw Error("Simulator query response has no SSE body");let g=0,f=!1,v=setTimeout(()=>{f||n(aa(s,"simulator_chat_sse_waiting_for_first_event",l,{endpoint:"chat",wait_ms:5e3},m))},5e3);try{await n8(t.body,e=>{g+=1,f||(f=!0,clearTimeout(v)),n(e)},{trace:{...h,baggage:m}})}catch(e){throw clearTimeout(v),n(aa(s,"simulator_chat_sse_read_failed",l,{endpoint:"chat",phase:"error",event_count:g,error:r5(e)},m)),e}clearTimeout(v)}async function al(e){let{endpoint:t,fetcher:r,result:i,signal:n}=e,a=await (r??fetch)(n3(t,"tool-report"),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(i),signal:n});if(!a.ok)throw await ai("Simulator tool result failed",a);let s=await ad(a),o=ae(a);return{...s,response_headers:o?{...rP(s.response_headers)?s.response_headers:{},[n9]:o}:s.response_headers,log_ids:o?[o]:s.log_ids}}async function ad(e){let t=await e.text().catch(()=>"");if(!t.trim())return{};try{let e=JSON.parse(t);return rP(e)?e:{response_body:e}}catch{return{response_text:t}}}let au={label:"Request",tone:"request"},ac={label:"Response",tone:"response"},ap={simulator_query_prepare_started:{debugOnly:!0,title:"Query Prepare Started"},simulator_query_mcp_resolved:{debugOnly:!0,title:"MCP Ready"},simulator_query_aborted:{title:"Query Aborted"},simulator_query_failed:{title:"Query Failed"},simulator_query_cancel_requested:{title:"Query Cancel Requested"},simulator_chat_fetch_started:{badge:au,title:"Chat"},simulator_chat_fetch_waiting_for_headers:{title:"Chat Waiting"},simulator_chat_response_meta:{badge:ac,title:"Chat"},simulator_chat_fetch_failed:{badge:ac,title:"Chat Failed"},simulator_chat_sse_waiting_for_first_event:{title:"Chat Waiting"},simulator_chat_sse_read_failed:{title:"Chat Stream Failed"},simulator_query_stream_returned:{title:"Chat Complete"},local_mcp_tools_load_started:{badge:au,debugOnly:!0,title:"MCP Load"},local_mcp_tools_loaded:{badge:ac,debugOnly:!0,title:"MCP Load"},local_mcp_tools_load_failed:{badge:ac,title:"MCP Load Failed"},local_mcp_missing:{title:"MCP Missing"},local_mcp_call_started:{badge:au,title:e=>`MCP Tool${e}`},local_mcp_call_succeeded:{badge:ac,title:e=>`MCP Tool${e}`},local_mcp_call_failed:{badge:ac,title:e=>`MCP Tool Failed${e}`},tool_result_report_started:{badge:au,title:e=>`Report Tool Result${e}`},tool_result_report_response_received:{badge:ac,title:e=>`Report Tool Result${e}`},tool_result_report_failed:{badge:ac,title:e=>`Report Tool Result Failed${e}`},tool_result_ack:{title:"Report ACK"},tool_result_submit_skipped:{title:e=>`Report Tool Result Skipped${e}`},tool_result_submit_failed:{badge:ac,title:e=>`Report Tool Result Failed${e}`},tool_executor_missing:{title:e=>`Tool Executor Missing${e}`},tool_call_ignored:{title:e=>`Tool Call Ignored${e}`},tool_call_event_skipped:{title:e=>`Tool Call Skipped${e}`},tool_call_request_id_mismatch:{title:e=>`Tool Call Request Mismatch${e}`},tool_call_server_id_fallback:{title:e=>`Tool Call Server Fallback${e}`},simulator_card_rendered:{title:"Card Rendered"},simulator_card_render_skipped:{title:"Card Render Skipped"},simulator_card_render_failed:{title:"Card Render Failed"},simulator_card_runtime_error:{title:"Card Render Failed"},simulator_manifest_load_started:{badge:au,debugOnly:!0,title:"Manifest Load"},simulator_manifest_loaded:{badge:ac,debugOnly:!0,title:"Manifest Load"},simulator_manifest_load_failed:{badge:ac,title:"Manifest Load Failed"},simulator_manifest_fetch_started:{badge:au,debugOnly:!0,title:"Manifest Fetch"},simulator_manifest_fetch_succeeded:{badge:ac,debugOnly:!0,title:"Manifest Fetch"},simulator_manifest_fetch_failed:{badge:ac,title:"Manifest Fetch Failed"},simulator_manifest_missing:{title:"Manifest Missing"},simulator_skill_load_started:{badge:au,debugOnly:!0,title:"Skill Load"},simulator_skill_loaded:{badge:ac,debugOnly:!0,title:"Skill Load"},simulator_skill_empty:{badge:ac,debugOnly:!0,title:"Skill Empty"},simulator_skill_load_failed:{badge:ac,title:"Skill Load Failed"},simulator_skill_fetch_started:{badge:au,debugOnly:!0,title:"Skill Fetch"},simulator_skill_fetch_succeeded:{badge:ac,debugOnly:!0,title:"Skill Fetch"},simulator_skill_fetch_failed:{badge:ac,title:"Skill Fetch Failed"},simulator_skill_missing:{title:"Skill Missing"},simulator_resources_check_started:{debugOnly:!0,title:"Resource Check Started"},simulator_resources_check_completed:{debugOnly:!0,title:"Resource Check Completed"},simulator_resource_reload_completed:{title:"Resource Reloaded"}};function ah(e){if(!rP(e))return;let t=am(e);return{category:t.category,debugOnly:t.debugOnly,detail:t.detail,leftBadges:t.transportBadge?[t.transportBadge]:void 0,phase:t.phase,title:t.title}}function am(e){var t,r;let i=e.event||"",n=ap[i],a=e.detail??e.data??e,s=e.title?r9(e.title):function(e,t){var r;let i=null==(r=ap[e])?void 0:r.title;if("function"==typeof i){let e;return i((e=t.tool_name||t.tool_call_id)?`: ${e}`:"")}return i||(e?r9(e):"Agent Trace Event")}(i,e),o=e.category?r8(e.category):(t=i).startsWith("local_mcp_")?"mcp":t.startsWith("tool_result_report_")||"tool_result_ack"===t?"api":t.startsWith("tool_result_")||t.startsWith("tool_call_")||"tool_executor_missing"===t?"agent":t.startsWith("simulator_card_")?"card":t.startsWith("simulator_manifest_")||t.startsWith("simulator_skill_")||t.startsWith("simulator_resource_")||t.startsWith("simulator_resources_")?"resource":t.startsWith("simulator_chat_")?"api":t.startsWith("simulator_query_")?"agent":"runtime",l=e.phase||("local_mcp_missing"===(r=i)?"error":/(started|starting)$/.test(r)?"request":/(completed|loaded|resolved|received|returned|succeeded|rendered)$/.test(r)?"response":/(failed|error|aborted|rejected)$/.test(r)?"error":/(empty|skipped|ignored|mismatch|fallback|cancel_requested)$/.test(r)?"status":"tool_result_ack"===r?"ack":"event");return{category:o,debugOnly:(null==n?void 0:n.debugOnly)===!0,detail:a,eventName:i,phase:l,title:s,transportBadge:null==n?void 0:n.badge}}function ag(e){return e.blocks.some(e=>"card"===e.type&&"permission_apply"===e.card.card_type)}function af(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{messages:r,streamStatus:i}=e.getState().simulator,n=function(e,t){let r=t?e.findIndex(e=>e.messageId===t):e.findLastIndex(ag);if(-1===r)return;let i=e[r];if(ag(i))for(let t=r-1;t>=0;t--){let r=e[t],n="user"===r.role?r.blocks.filter(e=>"image"===e.type).map(e=>e.image):[];if("user"===r.role&&(r.text.trim()||n.length>0))return{followUpContent:r.followUpContent,images:n.length>0?n:void 0,messageIds:[r.messageId,i.messageId],query:r.text.trim()}}}(r,t.grantingMessageId);if(!n)return{status:"not_found"};if("streaming"===i)return{status:"streaming"};e.removeSimulatorMessages(n.messageIds);let a=t.noLogin?{noLogin:!0}:{};return{completion:n.followUpContent?e.sendSimulatorFollowUpMessage(n.followUpContent,a):e.sendSimulatorQuery(n.query,{images:n.images,...a}),status:"started",target:n}}function av(e){if(!rP(e))return;let t="string"==typeof e.grantingName?e.grantingName:"";if(t){var r;let i;return{grantingName:t,permissionStatus:"string"==typeof e.permissionStatus?e.permissionStatus:"pending",priorityLevel:"number"==typeof e.priorityLevel?e.priorityLevel:0,relatedData:{...i=r4(r=e.relatedData)??(rP(r)?r:{}),bizLoginDescription:"string"==typeof i.bizLoginDescription?i.bizLoginDescription:"",bizPrivacyContent:"string"==typeof i.bizPrivacyContent?i.bizPrivacyContent:"",mobileMask:"string"==typeof i.mobileMask?i.mobileMask:"",privacyURL:"string"==typeof i.privacyURL?i.privacyURL:"",scopeDescription:"string"==typeof i.scopeDescription?i.scopeDescription:"",scopeName:"string"==typeof i.scopeName?i.scopeName:"",termsOfServiceURL:"string"==typeof i.termsOfServiceURL?i.termsOfServiceURL:""},required:!1!==e.required}}}function ay(e){let t=r4(e);if(!t)return;let r=Array.isArray(t.grantingList)?t.grantingList.map(av).filter(e=>!!e):[];if(0!==r.length)return{cardStatus:"string"==typeof t.cardStatus?t.cardStatus:"unexpired",doubaoAppletIcon:"string"==typeof t.doubaoAppletIcon?t.doubaoAppletIcon:"",doubaoAppletKey:"string"==typeof t.doubaoAppletKey?t.doubaoAppletKey:"",doubaoAppletName:"string"==typeof t.doubaoAppletName&&t.doubaoAppletName?t.doubaoAppletName:"应用插件",doubaoAppletVersion:"string"==typeof t.doubaoAppletVersion?t.doubaoAppletVersion:"",grantingList:r,raw:t}}function ab(e){var t;switch(null==(t=e.grantingList[0])?void 0:t.grantingName){case"permission":return"权限申请";case"privacy":return"隐私协议提示";default:return"登录授权"}}let aw="miniapp_packet_10066";function a_(e,t,r,i,n){let a=e.find(e=>e.messageId===t);return a?i&&!a.requestId||n&&!a.traceId?e.map(e=>e===a?{...e,requestId:e.requestId||i,traceId:e.traceId||n}:e):e:[...e,{messageId:t,requestId:i,traceId:n,role:"assistant",contentType:"mixed",text:"",blocks:[],status:"streaming",createdAtMs:r}]}function aS(e,t,r){return e.map(e=>e.messageId===t?r(e):e)}function ax(e,t,r,i){let n={blockId:t,type:"card",card:r};if("replace"===i){let i=r.card_id,a=e.map(e=>e.blockId===t||"card"===e.type&&i&&e.card.card_id===i?n:e);return a.some(e=>e===n)?a:[...e,n]}return e.some(e=>e.blockId===t)?e.map(e=>e.blockId===t?n:e):[...e,n]}function aI(e,t,r){let i=!1,n=!1,a=e.map(e=>{let a=!1,s=e.blocks.map(e=>{if("card"!==e.type||e.card.card_id!==t)return e;i=!0;let s=r(e.card);return s?(n=!0,a=!0,{...e,card:s}):e});return a?{...e,blocks:s}:e});return{messages:n?a:e,found:i,updated:n}}function ak(e){return"debug"===e.event_type?e.payload.data??e.payload:e.payload}function aC(e){let t=e.payload.tool_name||e.payload.tool_call_id,r=e.payload.status;switch(e.event_type){case"ack":return"Chat ACK";case"tool_call":return`Tool Call${t?`: ${t}`:""}`;case"tool_status":return`Tool Status${t?`: ${t}`:""}${r?` (${r})`:""}`;case"card_delta":return"Card Received";case"answer_finish":return"Answer Finished";case"message_finish":return"Message Finished";case"reply_finish":return"Reply Finished";case"stream_error":return"Stream Error";case"trace_event":return r9(e.payload.title||"Agent Trace");case"heartbeat":return"Heartbeat";default:return r9(e.event_type)}}function aE(e){let t=e.payload.category;if(t)return r8(t);switch(e.event_type){case"tool_call":case"tool_status":case"trace_event":default:return"agent";case"card_delta":return"card";case"debug":return"debug"}}function aN(e){switch(e){case"ack":return"accepted";case"message_start":return"message_start";case"text_delta":return"text_delta";case"tool_call":return"request";case"tool_status":return"response";case"card_delta":return"card_delta";case"message_finish":case"reply_finish":case"answer_finish":return"finish";case"stream_error":return"error";case"trace_event":return"trace";default:return e}}function aT(e){return"u">typeof DOMException&&e instanceof DOMException?"AbortError"===e.name:e instanceof Error&&"AbortError"===e.name}function aA(e,t){if(rP(e)&&"code"in e&&"message"in e)return e;let r=rP(e)&&rP(e.responseDebug)?e.responseDebug:void 0,i=r4(null==r?void 0:r.response_text),n="string"==typeof(null==i?void 0:i.message)&&i.message.trim()?i.message.trim():"string"==typeof(null==r?void 0:r.response_text)&&r.response_text.trim()?r.response_text.trim():"";return{code:("string"==typeof(null==i?void 0:i.code)||"number"==typeof(null==i?void 0:i.code)?String(i.code):void 0)??"INTERNAL_ERROR",message:n||r5(e),retryable:!1,stage:t,details:r?{response:r,response_body:i}:void 0}}function aM(e,t){if(e||t)return{...e,...t}}function aR(e,t){var r;let i=(null==(r=e.traceEvents.at(-1))?void 0:r.order)??e.traceEvents.length;return{...e,traceEvents:[...e.traceEvents,{...t,order:i+1}].slice(-200)}}function aj(e,t,r){var i;let n=function(e){let t=rP(e.card)?e.card:{},r=rP(t.state)?t.state:{},i=e.card_id,n=r.widget_id;if("update_state"!==e.op||"miniapp_history_refresh"!==t.card_type||"fixed_style"!==r.refresh_to||!i||!n)return;let a=r.url||r.schema,s=r.title,o=r.detailText;return{cardId:i,state:r,widgetData:{url:a,title:s,detailText:o},widgetId:n}}(t);if(n){let t=aI(e.messages,n.cardId,e=>{let t=e.state??{};if("fixed"!==t.lifecycle_state)return{...e,render_data:{viewData:n.widgetData},widget_id:n.widgetId,state:{...t,...n.state,lifecycle_state:"fixed"}}});return{state:{...e,messages:t.messages},cardRefresh:{cardId:n.cardId,status:t.updated?"updated":t.found?"already_fixed":"not_found"}}}let a=function(e){let t=e.card;if(!rP(t)||t.card_type!==aw)return;let r=e.card_id||t.card_id,i=r4(t.props_json),n=rP(null==i?void 0:i._meta)?i._meta:void 0,a=rP(t.render_data)?t.render_data:void 0,s=rP(null==a?void 0:a.ext)?a.ext:void 0;if(!r||!i||!n||!a||!s||!0!==n.skip_response_validate||"2"!==a.packet_type||"1"!==s._auth_request||"none"!==s.auth_require||"1"!==s.from_mcp||"1"!==s.is_mini_app||"string"!=typeof i.direct_return)return;let o=r4(i.direct_return);if((null==o?void 0:o.mcp_channel)==="flow_miniapp"&&Array.isArray(o.chunk_messages))for(let t of o.chunk_messages){if(!rP(t)||!0!==t.IsFinish||2!==t.MessageType||1005!==t.ContentType||"string"!=typeof t.Content)continue;let i=r4(t.Content);if((null==i?void 0:i.command_type)==="require_location"&&rP(i.require_location))return{cardId:r,appKey:s.app_key,sourceToolCallId:e.source_tool_call_id,toolName:s.tool_name}}}((null==r?void 0:r.payload)??{});if(a&&r)return{state:e,locationDirective:{...a,requestId:r.request_id,queryMessageId:r.query_message_id,replyMessageId:r.reply_message_id??e.activeReplyMessageId}};let s=(null==r?void 0:r.reply_message_id)??e.activeReplyMessageId,o=function(e){var t,r;let i,n=e.card;if(!rP(n))return{};let a=r4(n.props_json)??{},s=function(e){let t,r;if(e.card_type!==aw)return;let i=r4(e.props_json)||r4(e.render_data_json)||(rP(e.render_data)?r4(e.render_data.content_for_display):void 0)||{};return i.permission_data||((r=(Array.isArray(null==(t=rP(i.structuredContent)?i.structuredContent:void 0)?void 0:t.entity_list)?t.entity_list:[]).find(e=>rP(e)&&(Array.isArray(e.grantingList)||rP(e._meta)&&!0===e._meta.is_permission)))&&rP(r)?JSON.stringify(r):void 0)}(n),o=ay(s),l=rP(a.extra)?a.extra:{},d=Object.keys(a).length>0?(i=r4(a.widget_data))?{viewData:i}:rP(a.viewData)?{viewData:a.viewData}:{viewData:a}:void 0,u={...rP(n.source)?n.source:{},tool_call_id:e.source_tool_call_id||(null==(t=n.source)?void 0:t.tool_call_id),entity_ids:Array.isArray(e.source_entity_ids)?e.source_entity_ids:null==(r=n.source)?void 0:r.entity_ids};return{...{card_id:e.card_id,widget_id:e.widget_id,card_type:e.card_type,app_id:e.app_id},...n,widget_id:a.widget_id||n.widget_id||e.widget_id,app_id:a.applet_id||n.app_id||e.app_id,entity_id:a.entity_id||n.entity_id,source:u,card_type:o?"permission_apply":n.card_type||e.card_type,fallback_text:o?n.fallback_text||"需要授权后继续":n.fallback_text,render_data:o?{grantingData:o,permissionData:s}:d||n.render_data,title:o?n.title||ab(o):n.title,debug:{...rP(n.debug)?n.debug:{},props_json:n.props_json,output_template:l["doubao/outputTemplate"]}}}(t),l=t.block_id||o.card_id||(i=`card_${(null==r?void 0:r.seq)??0}`,o.card_id||o.title||i),d=t.op||"append";if("append"!==d&&"replace"!==d)return{state:e};if(o.card_id){let t=aI(e.messages,o.card_id,e=>{let t,i,n,a;return r?o:(t=aM(e.state,o.state),i=aM(e.source,o.source),n=aM(e.debug,o.debug),a=Object.fromEntries(Object.entries(o).filter(e=>{let[,t]=e;return void 0!==t})),{...e,...a,state:t,source:i,debug:n})});if(t.found)return{state:{...e,messages:t.messages},cardRefresh:{cardId:o.card_id,status:"updated"}}}if(!s)return{state:e};let u=a_(e.messages,s,(null==r?void 0:r.created_at_ms)??Date.now(),null==r?void 0:r.request_id,null==r?void 0:r.trace.trace_id);return{state:{...e,messages:aS(u,s,e=>({...e,contentType:"mixed",blocks:ax(e.blocks,l,o,d)}))}}}function aP(e,t){let r="completed"===t?"completed":"cancelled"===t?"interrupted":"failed";return e.map(e=>"assistant"===e.role&&"streaming"===e.status?{...e,status:r}:e)}function aL(e,t,r){return{...e,toolCalls:e.toolCalls.map(e=>e.toolCallId===t?{...e,...r}:e)}}function aO(e,t){let r={tool_call_id:t.toolCallId,tool_name:t.toolName,arguments_summary:t.arguments&&Object.keys(t.arguments).length>0?t.arguments:void 0,status:t.status},i=e.findIndex(e=>e.tool_call_id===t.toolCallId);return i<0?[...e,r]:e.map((e,t)=>t===i?r:e)}var aD=r(33680);function aU(e,t){var r,i;return null==e||null==(i=e.tools)||null==(r=i[t])?void 0:r.output}function aq(e,t,r){if(!rP(e)||!Array.isArray(e.structuredContent))return e;let i=aU(t,r);if(!i||"entities"!==i.kind)return e;if(!e.structuredContent.every(rP))throw Error(`Tool "${r}" structuredContent items must be objects`);return{...e,structuredContent:{entities:e.structuredContent.map(e=>({...e,entity_type:r}))}}}function a$(e,t){let r;if(!rP(e)||!Array.isArray(e.content))throw Error("MCP tool result must be an object with a content array");let i=void 0===(r=e.structuredContent)?{}:r,n=r6(e),a=e.content.filter(rP).map(e=>"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"),s=!0===e.isError;return{status:s?"failed":"succeeded",result:i,error:s?{code:t.businessErrorCode,message:rP(i)&&"string"==typeof i.message?i.message:a||n,retryable:!1,stage:"tool_execute",details:rP(i)?i:{structuredContent:i}}:void 0,raw_result_text:a,raw_mcp_result_json:n,miniapp:{is_mini_app:!0,mcp_channel:"flow_miniapp"},debug:{source:t.source,protocol:t.protocol,mcp_output:e}}}let aB="client_tool",aF="__bridge_ready__",az="lynxview";function aW(e,t){null==e||e({category:"mcp",source:"client_tool",...t})}class aH{runtimeUrl;container;errorListeners=new Set;host;messageListeners=new Set;view=null;constructor(e,t){this.runtimeUrl=e,this.host=function(){var e;if(!(null==(e=globalThis.document)?void 0:e.body))throw Error("Client Tool LynxView runtime requires document.body");let t=document.createElement("div");return t.dataset.doubaoClientToolRuntime="true",t.style.display="none",document.body.append(t),t}(),this.container=new rG({className:"doubao-client-tool-runtime-view",container:this.host,nativeModulesCallHandler:this.handleNativeModulesCall,onError:e=>this.emitError(e),onReady:()=>this.emitMessage({type:"event",name:aF})}),this.view=this.container.render({containerType:"TOOL",globalProps:t,initData:{},resourceUrl:e}),this.view.style.display="none"}addEventListener(e,t){"message"===e?this.messageListeners.add(t):this.errorListeners.add(t)}removeEventListener(e,t){"message"===e?this.messageListeners.delete(t):this.errorListeners.delete(t)}postMessage(e){this.container.sendGlobalEvent("__APPLET_BRIDGE__",[e])}terminate(){this.messageListeners.clear(),this.errorListeners.clear(),this.container.clear(),this.host.remove(),this.view=null}handleNativeModulesCall=(e,t,r)=>{if("AppletBridgeModule"===r&&"postMessage"===e&&rP(t)&&aG(t))return this.emitMessage(t),t};emitMessage(e){let t={data:e};for(let e of this.messageListeners)e(t)}emitError(e){let t=new ErrorEvent("error",{error:e,message:e.message});for(let e of this.errorListeners)e(t)}}function aV(e){return Object.assign(Error(e),{name:"AbortError"})}function aG(e){return"callback"===e.type&&"number"==typeof e.callbackId}class aJ{runtimeUrl;runtime;onTraceEvent;callbackId=1;ready=!1;readyPromise;rejectReady;resolveReady;pendingCallbacks=new Map;constructor(e,t,r){this.runtimeUrl=e,this.runtime=t,this.onTraceEvent=r,this.runtime.addEventListener("message",this.handleMessage),this.runtime.addEventListener("error",this.handleError)}async invokeTool(e){await this.ensureReady(e.signal);let{signal:t,...r}=e;return this.call("applet.invokeTool",r,{signal:t})}dispose(){var e;let t=Error("Client Tool runtime was disposed");for(let r of(this.runtime.removeEventListener("message",this.handleMessage),this.runtime.removeEventListener("error",this.handleError),this.runtime.terminate(),null==(e=this.rejectReady)||e.call(this,t),this.pendingCallbacks.values()))r.reject(t);this.pendingCallbacks.clear()}ensureReady(e){if(null==e?void 0:e.aborted)return Promise.reject(aV("Client Tool call aborted"));if(this.ready)return Promise.resolve();let t=this.readyPromise??(this.readyPromise=new Promise((e,t)=>{this.resolveReady=e,this.rejectReady=t}));return e?new Promise((r,i)=>{let n=()=>{e.removeEventListener("abort",n),i(aV("Client Tool call aborted"))};e.addEventListener("abort",n,{once:!0}),t.then(()=>{e.removeEventListener("abort",n),r()},t=>{e.removeEventListener("abort",n),i(t)}),e.aborted&&n()}):t}call(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=this.callbackId;return this.callbackId+=1,new Promise((n,a)=>{let{signal:s}=r;if(null==s?void 0:s.aborted)return void a(aV("Client Tool call aborted"));let o=()=>{null==s||s.removeEventListener("abort",l)},l=()=>{this.pendingCallbacks.delete(i),a(aV("Client Tool call aborted"))};null==s||s.addEventListener("abort",l,{once:!0}),this.pendingCallbacks.set(i,{reject:e=>{o(),a(e)},resolve:e=>{o(),n(e)}}),this.runtime.postMessage({type:"call",name:e,params:t,callbackId:i,target:{scope:"main",target:"self"}})})}handleMessage=e=>{var t;let r,i=rP(r="string"==typeof e.data?r3(e.data):e.data)?r:void 0;if(!i)return;if("event"===i.type&&i.name===aF){this.ready=!0,null==(t=this.resolveReady)||t.call(this),aW(this.onTraceEvent,{event:"client_tool_runtime_ready",runtime_url:this.runtimeUrl});return}if(!aG(i))return;let n=this.pendingCallbacks.get(i.callbackId);if(n){this.pendingCallbacks.delete(i.callbackId);try{n.resolve(function(e){let t=rP(e.params)?e.params:{};if(1===t.code)return t.data;throw Error("string"==typeof t.msg&&t.msg||`Client Tool runtime callback failed with code ${String(t.code)}`)}(i))}catch(e){n.reject(e)}}};handleError=e=>{var t;let r=Error(e.message||"Client Tool runtime failed");for(let e of(null==(t=this.rejectReady)||t.call(this,r),this.pendingCallbacks.values()))e.reject(r);this.pendingCallbacks.clear()}}function aK(e,t,r){return{status:"failed",result:{error:t},error:{code:e,message:t,retryable:r,stage:"tool_execute"},raw_result_text:t,miniapp:{is_mini_app:!0,mcp_channel:"flow_miniapp"},debug:{source:"client_tool",protocol:az}}}let aZ="simulator_web_tester";function aX(e){if(!e.trim())throw Error("Client Tool simulator manifest requires raw_manifest_yaml");let t=(0,aD.qg)(e);if(!rP(t))throw Error("Client Tool raw_manifest_yaml must contain a YAML object");return t}function aY(e){var t,r,i,n;let a=e.simulatorManifest||e.options.manifest||{},s=a.entities??(a.raw_manifest_yaml?aX(a.raw_manifest_yaml).entities:void 0),o=(t=e.messages,r=e.toolCalls,i=e.historyMaxTurns,n=s,t.slice(-Math.max(0,2*i)).flatMap(e=>{var t,i;let a,s,o=(t=e,a=r.filter(e=>e.replyMessageId===t.messageId&&["succeeded","failed","timeout","cancelled","rejected"].includes(e.status)).map(e=>{var t;let r=e.resultSummary?e.resultSummary:(null==(t=e.error)?void 0:t.message)?e.error.message:e.message;return{tool_call_id:e.toolCallId,tool_name:e.toolName,result_summary:r,structured_summary:e.structuredResultSummary,is_mini_app:e.isMiniApp}}),[...new Map([...t.toolResults??[],...a].map(e=>[e.tool_call_id,e])).values()]),l=a0(e.blocks.flatMap(e=>"image"===e.type?[e.image]:[]));return[{role:"assistant"===e.role?"ASSISTANT":"USER",content:(s=(i=e).text?i.text:i.blocks.filter(e=>"text"===e.type).map(e=>e.text).join(""))||e.blocks.map(e=>{var t;return"image"===e.type?e.image.name?`[图片:${e.image.name}]`:"[图片]":"card"===e.type?(t=e.card).fallback_text||t.title||t.card_type||t.card_id||"卡片":e.text}).filter(Boolean).join("\n"),parts:l.length>0?l:void 0},...o.map(e=>{var t;let r;return{role:"TOOL",content:rP(r=e.structured_summary)&&Array.isArray(r.entities)?JSON.stringify({...e,result_summary:(null==(t=r4(e.result_summary))?void 0:t.structuredContent)?void 0:e.result_summary,structured_summary:{entities:r.entities.filter(rP).map(e=>{var t;return function e(t,r){return Array.isArray(t)?t.map(t=>e(t,r.items??{})):rP(t)?Object.fromEntries(Object.entries(r.properties??{}).flatMap(r=>{let[i,n]=r;return rP(n)&&!1!==n.llm_visible&&i in t?[[i,e(t[i],n)]]:[]})):t}(e,{properties:null==n||null==(t=n[e.entity_type])?void 0:t.schema})})}}):JSON.stringify(e)}})]})),l=aQ(e.messages),d=a.app_key||"",u=e.options.appKey||e.simulatorAppKey||d||e.manifestAppId||"web-sdk-debugger",c=e.options.appName||e.simulatorAppName||e.manifestAppName||u,p=(e.options.skills??e.simulatorSkills??[]).map(e=>e.content),h=e.options.mcpServers??e.simulatorMcpServers,m=function(e,t){let r=e.raw_manifest_yaml||"",i=t.find(e=>e.server_id===aB&&e.tools.length>0);if(!i||!e.tools||null!=e.mcp_server)return r;let n=aX(r);return null!=n.mcp_server?r:(0,aD.As)({...n,mcp_server:{end_point:i.server_id,description:i.description||i.name}})}(a,h);return{app_id:u,scene:"miniapp_simulator_web_tester",history_messages:o,card_snapshots:l,trace:{trace_id:e.traceId,component:aZ,stage:"query",sampled:!0},client:{platform:"web",locale:"zh-CN",timezone:function(){try{return new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"Asia/Shanghai"}}()},ext:{web_tester:"true",stateless_context:"client_history",skill_source:p.length>0?"local_file":"none",no_login:e.options.noLogin?"true":void 0},max_step:e.options.maxStep??e.simulatorMaxStep??20,protocol_version:"v2",idempotency_key:e.idempotencyKey,mini_apps:[{app_key:u,app_name:c,skills:p,manifest:{app_key:u,app_name:c,raw_manifest_yaml:m},mcp_servers:h.map(e=>({server_id:e.server_id,name:e.name,description:e.description||"",tools:e.tools.map(e=>({name:e.name,description:e.description||"",input_schema_json:r6(e.input_schema_json)}))}))}],web_capabilities:{supports_debug_event:!0}}}function aQ(e){let t=new Map;for(let r of e)for(let e of r.blocks){if("card"!==e.type)continue;let r=function(e){var t,r,i;let n=r4(null==(t=e.debug)?void 0:t.props_json),a=e.card_id,s=(null==n?void 0:n.applet_id)||e.app_id,o=(null==n?void 0:n.entity_id)||e.entity_id;if(a&&s)return{card_id:a,app_key:s,business_entity_ids:o?[o]:void 0,lifecycle_state:(null==(r=e.state)?void 0:r.lifecycle_state)==="fixed"||(null==(i=e.state)?void 0:i.lifecycle_state)===2?2:1,refresh_key:e.refresh_key}}(e.card);r&&t.set(r.card_id,r)}return[...t.values()]}function a0(e){return e.map(e=>({type:"image",image:{resource_uri:e.resource_uri}}))}function a1(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"tool_execute",i=arguments.length>3?arguments[3]:void 0;return{code:e,message:t,user_message:t,retryable:!1,stage:r,details:i}}async function a2(e){let t,r,i,n,a,s,{executor:o,input:l,record:d,signal:u}=e,c=(t=void 0===d.deadlineMs?void 0:d.deadlineMs-Date.now(),r=d.timeoutMs,void 0===(i=void 0===t?r:void 0===r?t:Math.min(t,r))?void 0:Math.max(0,i)),p=a1("TOOL_EXEC_CANCELLED","Tool execution cancelled"),h=void 0===c?void 0:new AbortController,m=(null==h?void 0:h.signal)??u;if(null==u?void 0:u.aborted)throw p;if(h&&u){let e=()=>{h.abort()};u.addEventListener("abort",e,{once:!0}),a=()=>u.removeEventListener("abort",e)}let g=[Promise.resolve(o({...l,signal:m}))];if(void 0!==c&&h){let e=a1("TOOL_EXEC_TIMEOUT",`Tool execution timed out after ${c}ms`);g.push(new Promise((t,r)=>{n=setTimeout(()=>{h.abort(),r(e)},c)}))}u&&g.push(new Promise((e,t)=>{let r=()=>{t(p)};u.addEventListener("abort",r,{once:!0}),s=()=>u.removeEventListener("abort",r)}));try{return await Promise.race(g)}finally{n&&clearTimeout(n),null==a||a(),null==s||s()}}function a3(e){return e?String(e):nZ}function a4(e,t,r){return r?{type:e,message:t,error:r}:{type:e,message:t}}let a6={simulator_manifest_load_failed:"Manifest",simulator_skill_load_failed:"Skill",local_mcp_tools_load_failed:"MCP",simulator_chat_fetch_failed:"对话接口"};function a5(e){return new Set(e.flatMap(e=>e.blocks.flatMap(e=>"image"===e.type&&e.image.previewUrl?[e.image.previewUrl]:[])))}function a8(e,t){return e?{kind:"pages",item:e,routeUrl:t}:null}function a9(e,t){if(!t)return null;try{return a8(tO({url:t},e).entry,t)}catch{return null}}function a7(e){var t,r;return e.raw_result_text||(null==(t=e.error)?void 0:t.message)||(void 0===(r=e.result)?"":"string"==typeof r?r.slice(0,1e3):r6(r).slice(0,1e3))||e.status}function se(e,t){return e.app_key||e.appKey||e.appId||e.packageName||t}function st(e,t){var r;return e.name||e.appName||e.app_name||(null==(r=e.applet)?void 0:r.name)||t}function sr(e,t){let r=e.applet??{},i=t.applet??{},n=r.tools??[],a=i.tools??[],s=new Map,o=t.name||t.appName||t.app_name||i.name||"";if(a.length>0)for(let e of[...n,...a])e.id&&s.set(e.id,e);return{...e,manifest_version:t.manifest_version??e.manifest_version,app_key:t.app_key??e.app_key,name:t.name??e.name,appName:t.appName??e.appName,app_name:t.app_name??e.app_name,mcp_server:t.mcp_server??e.mcp_server,tools:t.tools??e.tools,entities:t.entities??e.entities,tool_card_binding:t.tool_card_binding??e.tool_card_binding,raw_manifest_yaml:t.raw_manifest_yaml??e.raw_manifest_yaml,applet:{...r,name:o||r.name,tools:a.length>0?[...s.values()]:n}}}class si{fetcher;simulatorFetcher;historyMaxTurns;simulatorAppKey;simulatorAppName;simulatorSkills;simulatorManifest;simulatorMaxStep;simulatorMcpServers;simulatorMcpServerProvider;simulatorToolExecutor;sandboxToolCallExecutions=new Map;listeners=new Set;activeSimulatorRun=null;lastResolvedSimulatorMcpServers=[];receivedSimulatorLocationDirectiveCardIds=new Set;resourceUrlVersion;hasSimulatorManifestStateValue=!1;simulatorManifestStateValue;simulatorManifestStatePromise;simulatorRunSeq=0;destroyed=!1;state;constructor(e={}){let t=a3(e.manifestUrl);this.fetcher=e.fetcher,this.simulatorFetcher=e.simulatorFetch,this.historyMaxTurns=e.historyMaxTurns??6,this.simulatorAppKey=e.appKey,this.simulatorAppName=e.appName,this.simulatorSkills=e.skills,this.simulatorManifest=e.simulatorManifest,this.simulatorMaxStep=e.maxStep,"function"==typeof e.mcpServers?(this.simulatorMcpServers=[],this.simulatorMcpServerProvider=e.mcpServers):this.simulatorMcpServers=e.mcpServers??[],this.simulatorToolExecutor=e.toolExecutor,this.state={manifestUrl:t,manifest:new c({manifestVersion:"3.0",packageName:"",appId:"",versionCode:"",applet:{appletId:"",appRuntimeEntry:"",digest:"",pages:[]},widgets:[]}),pages:[],widgets:[],pageSelection:null,widgetSelection:null,simulator:{endpoint:n0(e.simulatorEndpoint),messages:[],streamStatus:"idle",toolCalls:[],traceEvents:[]},status:a4("idle","Idle")}}clearSimulatorManifestStateValue(){this.hasSimulatorManifestStateValue=!1,this.simulatorManifestStateValue=void 0,this.simulatorManifestStatePromise=void 0}takeSimulatorManifestStateValue(){if(!this.hasSimulatorManifestStateValue)return{found:!1,value:void 0};let e=this.simulatorManifestStateValue;return this.clearSimulatorManifestStateValue(),{found:!0,value:e}}async loadSimulatorManifestForState(){if(void 0!==this.simulatorManifest)return"function"!=typeof this.simulatorManifest?this.simulatorManifest:this.hasSimulatorManifestStateValue?this.simulatorManifestStateValue:(this.simulatorManifestStatePromise||(this.simulatorManifestStatePromise=Promise.resolve(this.simulatorManifest()).then(e=>(this.hasSimulatorManifestStateValue=!0,this.simulatorManifestStateValue=e,e)).finally(()=>{this.simulatorManifestStatePromise=void 0})),this.simulatorManifestStatePromise)}async mergeSimulatorManifestForState(e){if(void 0===this.simulatorManifest)return e;try{let t=await this.loadSimulatorManifestForState();if(!t)return e;return new c(sr(e.raw,t))}catch(t){return console.warn("[web-sdk-debugger] Failed to merge simulator manifest for debug state",t),e}}async loadManifest(e){this.assertActive();let t=this.state.manifestUrl,r=a3(e??this.state.manifestUrl);this.setState({...this.state,manifestUrl:r,resourceUrlVersion:this.resourceUrlVersion,status:a4("loading",`Loading manifest ${r}`)});try{var i,n,a,s,o,l;let e,t,d,u,c,h=await p(r,{fetcher:this.fetcher}),m=await this.mergeSimulatorManifestForState(h),g=m.pages,f=m.widgets,v=a9(m,null==(i=this.state.pageSelection)?void 0:i.routeUrl)??(s=m,o=g,l=this.state.pageSelection,e=o.filter(nY),t=null==l?void 0:l.item.path,d=function(e,t){if(t)try{return e.getPageEntry(t)}catch{return}}(s,s.raw.applet.appletEntry),a8((t?e.find(e=>e.path===t):void 0)??(d&&nY(d)?d:void 0)??e.find(e=>"index"===e.id||"/pages/index"===e.path||"/pages/index/index"===e.path)??e[0])),y=(n=this.state.widgetSelection,u=f.filter(nY),(a=((c=null==n?void 0:n.item.widgetId)?u.find(e=>e.widgetId===c):void 0)??u[0])?{kind:"widgets",item:a}:null);return this.setState({...this.state,manifestUrl:r,manifest:m,pages:g,widgets:f,resourceUrlVersion:this.resourceUrlVersion,pageSelection:v,widgetSelection:y,status:a4("ready",v||y?`Loaded manifest ${r}`:`Manifest has no entries ${r}`)}),this.state}catch(r){let e=r instanceof Error?r:Error(String(r));throw this.setState({...this.state,manifestUrl:t,status:a4("error",`Load failed: ${e.message}`,e)}),e}}navigateToPage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.assertActive();try{let r=a9(this.state.manifest,e);if(!r)throw Error(`Unknown pages route: ${e}`);this.setState({...this.state,pageSelection:{...r,routeMode:t.routeMode},status:a4("ready",`Navigated page ${r.item.path}`)})}catch(t){let e=t instanceof Error?t:Error(String(t));throw this.setState({...this.state,status:a4("error",e.message,e)}),e}}selectWidget(e){this.assertActive();let t=this.state.widgets.find(t=>t.widgetId===e);if(!t){let t=Error(`Unknown widgets entry: ${e}`);throw this.setState({...this.state,status:a4("error",t.message,t)}),t}this.setState({...this.state,widgetSelection:{kind:"widgets",item:t},status:a4("ready",`Selected widget ${t.widgetId}`)})}async reloadResources(){if(this.assertActive(),"streaming"===this.state.simulator.streamStatus)throw Error("Cannot refresh card resources while simulator query is streaming");let e=this.state.manifestUrl,t=n2("reload");this.resourceUrlVersion=t,this.clearSimulatorManifestStateValue();let r=await this.loadManifest(e);return void 0!==this.simulatorSkills&&await this.resolveSimulatorSkillsForQuery(t,{}),this.appendSimulatorDebugEvent({category:"resource",event:"simulator_resource_reload_completed",manifest_url:e,resource_url_version:t,summary:"Card resources refreshed"}),r}async sendSimulatorQuery(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.assertActive();let r=e.trim(),i=(t.images??[]).filter(e=>e.resource_uri);if(r||0!==i.length)return this.sendSimulatorChat({kind:"message",queryText:r},t)}sendSimulatorFollowUpMessage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise((r,i)=>{let n=Error("Simulator follow-up message was cancelled before submission");this.sendSimulatorChat({kind:"follow_up",content:e},t,r,()=>i(n)).then(()=>i(n),i)})}async sendSimulatorChat(e,t,r,i){this.assertActive(),this.cancelSimulatorQuery();let n=n2("local_msg"),a=n2("idem"),s=n2("trace"),o=Date.now(),l=this.state.simulator,d=this.state.manifest.raw,u="message"===e.kind?(t.images??[]).filter(e=>e.resource_uri):[],c="message"===e.kind?{messageId:n,localMessageId:n,traceId:s,role:"user",contentType:u.length>0?"mixed":"text",text:e.queryText,blocks:[...u.map(e=>({blockId:n2("block_image"),type:"image",image:e})),...e.queryText?[{blockId:n2("block_text"),type:"text",text:e.queryText}]:[]],status:"completed",createdAtMs:o}:void 0,p=this.createSimulatorRun(s);p.onCancelledBeforeSubmission=i,this.activeSimulatorRun=p,this.setState({...this.state,simulator:{...l,activeRequestId:void 0,activeReplyMessageId:void 0,error:void 0,locationDirective:void 0,messages:c?[...l.messages,c]:l.messages,streamStatus:"streaming"}}),this.appendSimulatorDebugEvent({event:"simulator_query_prepare_started",trace_id:s,previous_active_request_id:l.activeRequestId,previous_stream_status:l.streamStatus,history_message_count:l.messages.length,query_preview:"message"===e.kind?e.queryText.slice(0,80)||"[图片]":"send_follow_up_message",image_count:u.length});try{var h,m;let i,u=await this.resolveSimulatorManifestForQuery(s,t,d,p.streamAbortController.signal),c=se(u,this.state.manifest.appId),g=st(u,this.state.manifest.name);if(!this.isSimulatorRunCurrent(p))return;let f=await this.resolveSimulatorSkillsForQuery(s,t,p.streamAbortController.signal);if(!this.isSimulatorRunCurrent(p))return;let v={signal:p.streamAbortController.signal,trace:{trace_id:s,component:"web_sdk_debugger",stage:"query_prepare",sampled:!0},appKey:t.appKey||this.simulatorAppKey||c,appName:t.appName||this.simulatorAppName||g,manifest:u},y=this.simulatorMcpServerProvider?await this.simulatorMcpServerProvider(v):this.simulatorMcpServers;if(this.lastResolvedSimulatorMcpServers=y,!this.isSimulatorRunCurrent(p))return;this.appendSimulatorDebugEvent({event:"simulator_query_mcp_resolved",trace_id:s,elapsed_ms:Date.now()-o,mcp_server_count:y.length,mcp_servers:y.map(e=>({server_id:e.server_id,tool_count:e.tools.length,tools:e.tools.map(e=>e.name)}))});let b={historyMaxTurns:this.historyMaxTurns,idempotencyKey:a,localMessageId:n,manifestAppId:this.state.manifest.appId,manifestAppName:g,messages:l.messages,toolCalls:l.toolCalls,options:t,simulatorAppKey:this.simulatorAppKey,simulatorAppName:this.simulatorAppName,simulatorSkills:f,simulatorManifest:u,simulatorMaxStep:this.simulatorMaxStep,simulatorMcpServers:y,traceId:s},w="message"===e.kind?(h={...b,queryText:e.queryText},i=a0(h.options.images??[]),{...aY(h),message:{role:"USER",content:h.queryText,local_message_id:h.localMessageId,parts:i.length>0?i:void 0}}):(m={...b,content:e.content},{...aY(m),input_event:{event_type:"send_follow_up_message",params:{content:m.content},local_message_id:m.localMessageId}});if(await ao({endpoint:this.state.simulator.endpoint,fetcher:this.simulatorFetcher,onSubmitted:()=>{p.onCancelledBeforeSubmission=void 0,null==r||r()},request:w,signal:p.streamAbortController.signal,onEvent:t=>this.handleSimulatorEvent(t,p,"follow_up"===e.kind?e.content:void 0)}),!this.isSimulatorRunCurrent(p))return;"streaming"===this.state.simulator.streamStatus&&this.setState({...this.state,simulator:{...this.state.simulator,activeRequestId:void 0,streamStatus:"completed"}}),this.appendSimulatorDebugEvent({event:"simulator_query_stream_returned",trace_id:s,elapsed_ms:Date.now()-o,stream_status:this.state.simulator.streamStatus,active_request_id:this.state.simulator.activeRequestId})}catch(i){if(aT(i))return void this.appendSimulatorDebugEvent({event:"simulator_query_aborted",trace_id:s,elapsed_ms:Date.now()-o,stream_status:this.state.simulator.streamStatus});if(!this.isSimulatorRunCurrent(p))return;let e=aA(i,"query_stream"),t=this.getSimulatorQueryFailureDiagnosis(s,i),r=t?{...e,message:t.summary,user_message:t.summary,details:{...e.details,diagnosis:t,original_error:e.message}}:e;throw this.appendSimulatorDebugEvent({event:"simulator_query_failed",trace_id:s,elapsed_ms:Date.now()-o,error:r}),this.setState({...this.state,simulator:{...this.state.simulator,activeRequestId:void 0,error:r,streamStatus:"error"}}),i}finally{this.finishSimulatorStream(p)}}pushMessages(e){if(this.assertActive(),!Array.isArray(e))throw Error("Messages must be an array");if(0===e.length)return;let t=structuredClone(e).map(e=>{let t=(e.blocks??[]).map(e=>({...e,blockId:e.blockId??n2("block"),..."card"===e.type?{card:{...e.card,card_id:e.card.card_id??n2("card")}}:{}}));return{...e,messageId:e.messageId??n2("message"),createdAtMs:e.createdAtMs??Date.now(),text:e.text??"",contentType:e.contentType??(t.some(e=>"text"!==e.type)?"mixed":"text"),blocks:t}}),r=new Set(this.state.simulator.messages.map(e=>e.messageId));for(let e of t){if(r.has(e.messageId))throw Error(`Duplicate messageId: ${e.messageId}`);r.add(e.messageId)}this.updateSimulatorState(e=>({...e,messages:[...e.messages,...t]}))}removeSimulatorMessages(e){this.assertActive();let t=new Set(e.filter(Boolean));if(0===t.size)return;let r=a5(this.state.simulator.messages.filter(e=>t.has(e.messageId)));this.updateSimulatorState(e=>({...e,activeReplyMessageId:e.activeReplyMessageId&&t.has(e.activeReplyMessageId)?void 0:e.activeReplyMessageId,messages:e.messages.filter(e=>!t.has(e.messageId)),selectedCard:e.selectedCard&&t.has(e.selectedCard.reply_message_id)?void 0:e.selectedCard})),queueMicrotask(()=>{let e=a5(this.state.simulator.messages);for(let t of r)e.has(t)||URL.revokeObjectURL(t)})}applySimulatorCardDelta(e){this.assertActive(),this.updateSimulatorState(t=>aj(t,rP(e.card_delta)?e.card_delta:e).state)}consumeSimulatorLocationDirective(e){this.assertActive(),this.updateSimulatorState(t=>{var r;return(null==(r=t.locationDirective)?void 0:r.cardId)===e?{...t,locationDirective:void 0}:t})}cancelSimulatorQuery(){this.assertActive();let e=this.state.simulator.activeRequestId,t=this.activeSimulatorRun;t&&(this.appendSimulatorDebugEvent({event:"simulator_query_cancel_requested",request_id:e,trace_id:t.traceId,stream_status:this.state.simulator.streamStatus}),this.abortSimulatorRun(t)),"streaming"===this.state.simulator.streamStatus&&this.setState({...this.state,simulator:{...this.state.simulator,activeRequestId:void 0,activeReplyMessageId:void 0,toolCalls:this.state.simulator.toolCalls.map(t=>e&&t.requestId===e&&"running"===t.status?{...t,status:"cancelled",updatedAtMs:Date.now()}:t),streamStatus:"cancelled"}})}async callSimulatorTool(e){if(this.assertActive(),!this.simulatorToolExecutor)throw Error("No local simulator tool executor is configured");let t=e.toolName.trim();if(!t)throw Error("toolName must be a non-empty string");let r=n2("req_tool"),i=n2("reply_tool"),n=n2("tool_call"),a=n2("trace"),s={trace_id:a,component:"web_sdk_debugger",stage:"direct_tool_call",sampled:!0},o=Date.now(),l=await this.resolveDirectToolCallServerId(t,e.serverId,s),d={requestId:r,replyMessageId:i,toolCallId:n,toolName:t,serverId:l,appKey:this.simulatorAppKey||se(this.state.manifest.raw,this.state.manifest.appId)||void 0,arguments:e.params,argumentsJson:e.params?function(e){try{return JSON.stringify(e??{})}catch{return""}}(e.params):void 0,status:"running",createdAtMs:o,updatedAtMs:o,trace:s,timeoutMs:e.timeoutMs};this.updateSimulatorState(e=>({...e,toolCalls:[...e.toolCalls,d]})),this.appendSimulatorDebugEvent({event:"direct_tool_call_started",request_id:r,trace_id:a,tool_call_id:n,tool_name:t,server_id:l,arguments:e.params,arguments_json:d.argumentsJson});let u=Date.now(),c=await this.runSimulatorToolCall(d);return this.updateToolCall(n,{status:c.status,updatedAtMs:Date.now(),error:c.error,resultSummary:a7(c),structuredResultSummary:c.result,isMiniApp:c.miniapp&&"boolean"==typeof c.miniapp.is_mini_app?c.miniapp.is_mini_app:void 0}),this.appendSimulatorDebugEvent({event:"direct_tool_call_completed",request_id:r,trace_id:a,tool_call_id:n,tool_name:t,server_id:l,status:c.status,elapsed_ms:Date.now()-u,result:c.result,error:c.error,raw_result_text:c.raw_result_text}),c}executeSandboxToolCall(e){this.assertActive();let t=`${e.request_id}\0${e.tool_call.tool_call_id}`,r=this.sandboxToolCallExecutions.get(t);if(r)return r;let i=this.executeSandboxToolCallOnce(e);return this.sandboxToolCallExecutions.set(t,i),i}async submitToolResult(e,t){let r,i,n,a;this.assertActive();let s=Date.now(),o=(i=void 0===e.result?e.error?{error:e.error.message}:{}:e.result,n=e.raw_mcp_result_json,a=e.raw_result_text||r6(e.error?{error:e.error.message,detail:e.error}:i),{request_id:e.requestId,tool_call_id:e.toolCallId,server_id:e.serverId,tool_name:e.toolName,status:function(e){switch(e){case"succeeded":return"SUCCESS";case"timeout":return"TIMEOUT";case"cancelled":return"CANCELLED";case"rejected":return"REJECTED";default:return"FAILED"}}(e.status),app_key:e.appKey,result:{tool_call_id:e.toolCallId,content:a,structured_json:r6(i)},raw_result_text:a,raw_mcp_result_json:n||"",miniapp:e.miniapp,timing:e.timing,trace:{trace_id:e.trace.trace_id,component:aZ,stage:"tool_report",sampled:e.trace.sampled??!0},ext:{reported_by:aZ}});this.appendSimulatorDebugEvent({event:"tool_result_report_started",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,server_id:e.serverId,status:o.status,report_request:o,endpoint:this.state.simulator.endpoint});try{r=await al({endpoint:this.state.simulator.endpoint,fetcher:this.simulatorFetcher,result:o,signal:t})}catch(r){let t=an(r);throw this.appendSimulatorDebugEvent({event:"tool_result_report_failed",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,elapsed_ms:Date.now()-s,error:r5(r),response:t}),r}this.appendSimulatorDebugEvent({event:"tool_result_report_response_received",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,elapsed_ms:Date.now()-s,response:r});let l=function(e){let t=e.code,r=!1===e.accepted,i=void 0!==t&&0!==t&&"0"!==t;if(!r&&!i)return;let n="string"==typeof e.message&&e.message?e.message:i?`Simulator tool result rejected with code ${String(t)}`:"Simulator tool result was not accepted",a=r0(e)[0];return a1("TOOL_RESULT_REJECTED",a?`${n} (x-tt-logid: ${a})`:n,"tool_result_submit",{gateway_response:e,gateway_code:i?t:void 0,gateway_accepted:!r&&void 0,"x-tt-logid":a})}(r);if(this.appendSimulatorDebugEvent({event:"tool_result_ack",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,accepted:r.accepted,next_action:r.next_action,error:l,response:r}),l)throw l;return r}selectSimulatorCard(e){this.assertActive(),this.updateSimulatorState(t=>({...t,selectedCard:e}))}updateSimulatorWidget(e){var t,r,i;let n,a,s;if(this.assertActive(),"string"!=typeof e.widgetInstanceId||!e.widgetInstanceId.trim())return{status:"invalid_params",message:"widgetInstanceId must be a non-empty string"};if(void 0!==e.widgetId&&("string"!=typeof e.widgetId||!e.widgetId.trim()))return{status:"invalid_params",message:"widgetId must be a non-empty string when provided"};if(void 0!==e.reloadWidget&&"boolean"!=typeof e.reloadWidget)return{status:"invalid_params",message:"reloadWidget must be a boolean"};let o=void 0!==e.toolResult;if(void 0!==e.widgetData===o)return{status:"invalid_params",message:"widgetData and toolResult must be exclusive"};let l=this.state.simulator.messages.flatMap(e=>e.blocks).find(t=>"card"===t.type&&t.card.card_id===e.widgetInstanceId);if(!l||"card"!==l.type)return{status:"not_found",message:`Widget instance ${e.widgetInstanceId} was not found`};let d=e.widgetId??l.card.widget_id;if(d!==l.card.widget_id&&(o||!1===e.reloadWidget))return{status:"invalid_params",message:"Changing widgetId requires widgetData and reloadWidget"};if("__doubao_apps__expired-widget"!==d&&!this.state.widgets.some(e=>e.widgetId===d))return{status:"not_found",message:`Widget ${d} was not found`};let u=e.toolResult,c=null==(t=l.card.source)?void 0:t.tool_call_id;if(o){if(!rP(u)||void 0!==u.content&&(!Array.isArray(u.content)||!u.content.every(rP))||void 0!==u.isError&&"boolean"!=typeof u.isError||!rP(u.structuredContent)||!Array.isArray(u.structuredContent.entities)||!u.structuredContent.entities.length||!u.structuredContent.entities.every(rP))return{status:"invalid_params",message:"toolResult must contain structuredContent.entities"};let e=rP(null==(r=l.card.render_data)?void 0:r.viewData)?l.card.render_data.viewData:l.card.render_data,t=u.structuredContent.entities.filter(t=>{var r;let i=null==(r=this.state.manifest.raw.entities)?void 0:r[t.entity_type];if(!i||!Object.values(i.tool_card_binding??{}).includes(d))return!1;let n=Object.keys(i.schema??{}).find(e=>{var t;return(null==(t=i.schema[e])?void 0:t.is_entity_id)===!0});return n&&void 0!==t[n]&&((null==e?void 0:e[n])===void 0||t[n]===e[n])});if(1!==t.length)return{status:"invalid_params",message:"toolResult must identify one entity for the current Widget"};let o=this.state.simulator.toolCalls.find(e=>e.toolCallId===c),p=this.state.simulator.messages.flatMap(e=>e.toolResults??[]).find(e=>e.tool_call_id===c);if(!c||!o&&!p)return{status:"not_found",message:"The Widget Tool result was not found in conversation history"};n=t[0],a=null==(i=u.content)?void 0:i.map(e=>"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"),this.state.simulator.messages.slice(-Math.max(0,2*this.historyMaxTurns)).some(e=>{var t;return e.messageId===(null==o?void 0:o.replyMessageId)||(null==(t=e.toolResults)?void 0:t.some(e=>e.tool_call_id===c))})||(s={tool_call_id:c,tool_name:(null==o?void 0:o.toolName)??p.tool_name,result_summary:a,structured_summary:u.structuredContent,is_mini_app:(null==o?void 0:o.isMiniApp)??(null==p?void 0:p.is_mini_app)})}else try{let t="string"==typeof e.widgetData?JSON.parse(e.widgetData):void 0;if(!rP(t))throw Error("Invalid Widget data");n=t}catch{return{status:"invalid_widget_data",message:"widgetData must be a JSON object"}}let p=aI(this.state.simulator.messages,e.widgetInstanceId,t=>({...t,widget_id:d,refresh_key:!1===e.reloadWidget?t.refresh_key:n2("refresh"),render_data:n}));return this.updateSimulatorState(e=>({...e,messages:u?p.messages.map((e,t)=>{var r;let i=null==(r=e.toolResults)?void 0:r.map(e=>e.tool_call_id===c?{...e,result_summary:a,structured_summary:u.structuredContent}:e);return{...e,toolResults:s&&t===p.messages.length-1?[...i??[],s]:i}}):p.messages,toolCalls:u?e.toolCalls.map(e=>e.toolCallId===c?{...e,resultSummary:a,structuredResultSummary:u.structuredContent,updatedAtMs:Date.now()}:e):e.toolCalls})),{status:"updated"}}appendSimulatorTraceEvent(e){this.assertActive(),this.appendSimulatorDebugEvent(e)}async approveSimulatorToolCall(e){this.assertActive();let t=this.getSimulatorToolCall(e);if(!this.simulatorToolExecutor)throw Error("No local simulator tool executor is configured");if("pending_approval"!==t.status)return;let r=this.getSimulatorToolCallRun(t);if(void 0!==t.runId&&!r)return void this.cancelStaleSimulatorToolCall(t);let i={...t,status:"running",updatedAtMs:Date.now()};null==r||r.pendingApprovalToolCallIds.delete(e),this.updateToolCall(e,{status:i.status,updatedAtMs:i.updatedAtMs}),await this.executeSimulatorToolCall(i,r)}async rejectSimulatorToolCall(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Tool call rejected by user";this.assertActive();let r=this.getSimulatorToolCall(e);if("pending_approval"!==r.status)return;let i=this.getSimulatorToolCallRun(r);if(void 0!==r.runId&&!i)return void this.cancelStaleSimulatorToolCall(r);let n=this.createToolExecutorInput(r),a=a1("TOOL_EXEC_REJECTED",t),s=Date.now();null==i||i.pendingApprovalToolCallIds.delete(e);try{await this.submitExecutedToolResult(n,{status:"rejected",error:a},s,null==i?void 0:i.streamAbortController.signal),this.updateToolCall(e,{status:"rejected",updatedAtMs:Date.now(),error:a,resultSummary:t})}catch(n){if(i&&!this.isSimulatorRunCurrent(i))return void this.appendSimulatorDebugEvent({event:"tool_result_submit_skipped",request_id:r.requestId,trace_id:r.trace.trace_id,tool_call_id:r.toolCallId,tool_name:r.toolName,reason:"stale_or_cancelled_run"});let t=aA(n,"tool_result_submit");throw this.appendSimulatorDebugEvent({event:"tool_result_submit_failed",trace_id:r.trace.trace_id,tool_call_id:e,summary:r5(n)}),this.updateToolCall(e,{status:"failed",updatedAtMs:Date.now(),error:t}),n}finally{i&&this.releaseSimulatorRun(i)}}getState(){return this.state}subscribe(e){return this.assertActive(),this.listeners.add(e),()=>{this.listeners.delete(e)}}getResourceUrl(e){return(this.assertActive(),e)?h(this.state.manifestUrl,e)??null:null}destroy(){var e,t;if(!this.destroyed){for(let r of(this.cancelSimulatorQuery(),null==(t=this.simulatorToolExecutor)||null==(e=t.dispose)||e.call(t),a5(this.state.simulator.messages)))URL.revokeObjectURL(r);this.destroyed=!0,this.sandboxToolCallExecutions.clear(),this.listeners.clear()}}createSimulatorRun(e){return{id:this.simulatorRunSeq+=1,traceId:e,streamAbortController:new AbortController,streamDone:!1,cancelled:!1,pendingApprovalToolCallIds:new Set,toolAbortControllers:new Set}}isSimulatorRunCurrent(e){return!this.destroyed&&this.activeSimulatorRun===e&&!e.cancelled}abortSimulatorRun(e){var t;for(let r of(e.cancelled=!0,null==(t=e.onCancelledBeforeSubmission)||t.call(e),e.onCancelledBeforeSubmission=void 0,e.streamAbortController.abort(),e.toolAbortControllers))r.abort();this.activeSimulatorRun===e&&(this.activeSimulatorRun=null)}finishSimulatorStream(e){e.streamDone=!0,this.releaseSimulatorRun(e)}releaseSimulatorRun(e){this.activeSimulatorRun===e&&(e.cancelled||e.streamDone&&0===e.pendingApprovalToolCallIds.size&&0===e.toolAbortControllers.size)&&(this.activeSimulatorRun=null)}handleSimulatorEvent(e,t,r){let i="tool_call"===e.event_type;if(!this.isSimulatorRunCurrent(t)){i&&this.appendSimulatorDebugEvent({event:"tool_call_event_skipped",request_id:e.request_id,trace_id:e.trace.trace_id,tool_call_id:e.payload.tool_call_id||"",tool_name:e.payload.tool_name||"",reason:"stale_or_cancelled_run",summary:"Tool call event arrived after its simulator run was cancelled and was not executed"});return}let n=this.state.simulator.activeRequestId;if(n&&e.request_id!==n&&"ack"!==e.event_type&&"debug"!==e.event_type){if(!i&&"tool_status"!==e.event_type)return;this.appendSimulatorDebugEvent({event:"tool_call_request_id_mismatch",request_id:e.request_id,active_request_id:n,trace_id:e.trace.trace_id,tool_call_id:e.payload.tool_call_id||"",tool_name:e.payload.tool_name||"",event_type:e.event_type,summary:"Tool call event request_id differs from the acknowledged request_id"})}let{state:a,toolCall:s,cardRefresh:o,locationDirective:l}=function(e,t,r){var i,n,a,s,o,l,d,u,c,p,h,m;let g,f,v,y,b,w,_,S,x={...e,activeReplyMessageId:t.reply_message_id??e.activeReplyMessageId},I=!function(e){switch(e.event_type){case"ack":case"tool_call":case"tool_status":case"card_delta":case"content_block":case"answer_finish":case"message_finish":case"reply_finish":case"stream_error":case"trace_event":case"debug":return!0;default:return!1}}(t)?x:aR(x,(S=t.received_at_ms??Date.now(),{display:"debug"===(i=t).event_type?ah(i.payload)??{category:"debug",detail:ak(i),phase:"event",title:"Debug"}:{category:aE(i),detail:ak(i),phase:aN(i.event_type),title:aC(i)},id:t.event_id,timestamp:S,payload:(n=t,a=S,g=aE(n),f=aN(n.event_type),v={event:n.event_type,category:g,phase:f,received_at_ms:a,server_timestamp_ms:n.created_at_ms,title:aC(n),detail:ak(n),trace:n.trace},"debug"===n.event_type?{...v,event:n.payload.event||"debug",title:r9(n.payload.title||n.payload.event||"Debug Event"),summary:n.payload.summary,elapsed_ms:n.payload.elapsed_ms,redaction_level:n.payload.redaction_level}:"heartbeat"===n.event_type?{...v,server_time_ms:n.payload.server_time_ms,message:n.payload.message}:"answer_finish"===n.event_type?{...v,status:n.payload.status,finish_reason:n.payload.finish_reason,usage:n.payload.usage}:{...v,...n.payload})}));switch(t.event_type){case"ack":return{state:function(e,t,r){let i=t.payload.local_message_id,n=t.payload.query_message_id,a=t.payload.message_id,s=rP(t.payload.query_message)?t.payload.query_message:void 0,o=(null==s?void 0:s.content)||"",l=e.messages;if(i&&n){let e=l.find(e=>e.localMessageId===i);e?l=l.map(t=>t===e?{...t,messageId:n,followUpContent:r}:t):o&&(l=[...l,{messageId:n,localMessageId:i,requestId:t.request_id,traceId:t.trace.trace_id,followUpContent:r,role:"user",contentType:"text",text:o,blocks:[{blockId:`block_text_${n}`,type:"text",text:o}],status:"completed",createdAtMs:t.created_at_ms}])}return{...e,activeRequestId:t.request_id,activeReplyMessageId:a||e.activeReplyMessageId,messages:l}}(I,t,r.followUpContent)};case"message_start":return{state:(s=I,y=(o=t).payload.message_id||o.reply_message_id||n2("reply"),{...s,activeReplyMessageId:y,messages:a_(s.messages,y,o.created_at_ms,o.request_id,o.trace.trace_id)})};case"text_delta":return{state:function(e,t){let r=t.reply_message_id??e.activeReplyMessageId;if(!r)return e;let i=t.payload.block_id||`block_text_${t.seq}`,n=t.payload.delta||"",a=t.payload.op||"append";if("append"!==a&&"replace"!==a)return e;let s=a_(e.messages,r,t.created_at_ms,t.request_id,t.trace.trace_id);return{...e,messages:aS(s,r,e=>({...e,text:"replace"===a?n:`${e.text}${n}`,blocks:function(e,t,r,i){if(!e.find(e=>"text"===e.type&&e.blockId===t)){let n=e[e.length-1];return"append"===i&&(null==n?void 0:n.type)==="text"?e.map(e=>e===n?{...e,text:`${e.text}${r}`}:e):[...e,{blockId:t,type:"text",text:r}]}return e.map(e=>"text"===e.type&&e.blockId===t?{...e,text:"replace"===i?r:`${e.text}${r}`}:e)}(e.blocks,i,n,a)}))}}(I,t)};case"card_delta":return aj(I,t.payload,t);case"content_block":return{state:function(e,t){let r=t.reply_message_id??e.activeReplyMessageId;if(!r)return e;let i=function(e,t){for(let[r,i]of(Array.isArray(e.content_block)?e.content_block:Array.isArray(e.contentBlock)?e.contentBlock:[]).entries()){let n=function(e){if(!rP(e))return;let t=rP(e.content)?e.content:e,r=rP(t.permission_apply_block)?t.permission_apply_block:rP(t.permissionApplyBlock)?t.permissionApplyBlock:void 0;return r?("string"==typeof r.permission_data?r.permission_data:"")||("string"==typeof r.permissionData?r.permissionData:""):""}(i),a=ay(n);if(!a)continue;let s=(rP(i)&&"string"==typeof i.block_id?i.block_id:"")||(rP(i)&&"string"==typeof i.blockId?i.blockId:"")||`permission_apply_${t.seq}_${r}`;return{blockId:s,card:{card_id:s,card_type:"permission_apply",fallback_text:"需要授权后继续",render_data:{grantingData:a,permissionData:n},title:ab(a)},op:e.op||"append"}}}(t.payload,t);if(!i||"append"!==i.op&&"replace"!==i.op)return e;let n=a_(e.messages,r,t.created_at_ms,t.request_id,t.trace.trace_id);return{...e,messages:aS(n,r,e=>({...e,contentType:"mixed",blocks:ax(e.blocks,i.blockId,i.card,i.op)}))}}(I,t)};case"tool_call":return function(e,t,r){let i=t.payload.tool_call_id,n=t.payload.tool_name,a=t.payload.server_id||"",s=t.payload.arguments_json||"",o=t.reply_message_id??e.activeReplyMessageId??n2("reply");if(!i||!n)return{state:aR(e,{id:n2("trace"),timestamp:Date.now(),payload:{event:"tool_call_ignored",request_id:t.request_id,trace_id:t.trace.trace_id,tool_call_id:i,tool_name:n,reason:i?"missing_tool_name":"missing_tool_call_id",tool_call_payload:t.payload,summary:"Tool call event is missing required fields and cannot be executed"}})};let l=t.payload.requires_user_approval??!1,d=l?"pending_approval":r.hasToolExecutor?"running":"pending",u={requestId:t.request_id,runId:r.runId,replyMessageId:o,toolCallId:i,toolName:n,serverId:a,appKey:t.payload.app_key,arguments:rP(t.payload.arguments)?t.payload.arguments:r4(s),argumentsJson:s,mcpHeaders:function(e){if(!rP(e))return;let t=Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1]));return Object.keys(t).length>0?t:void 0}(t.payload.headers),status:d,createdAtMs:t.created_at_ms,updatedAtMs:t.created_at_ms,trace:t.trace,requiresUserApproval:l,timeoutMs:t.payload.timeout_ms,deadlineMs:t.payload.deadline_ms},c=aS(a_(e.messages,o,t.created_at_ms,t.request_id,t.trace.trace_id),o,e=>({...e,toolCalls:aO(e.toolCalls??[],u)})),p={...e,messages:c,toolCalls:[...e.toolCalls.filter(e=>e.toolCallId!==i),u]};return r.hasToolExecutor?{state:p,toolCall:u}:{state:aR(p,{id:n2("trace"),timestamp:Date.now(),payload:{event:"tool_executor_missing",request_id:u.requestId,trace_id:u.trace.trace_id,tool_call_id:i,tool_name:n,summary:"No local simulator tool executor is configured"}})}}(I,t,r);case"tool_status":return{state:function(e,t){let r=t.payload.tool_call_id,i=function(e){switch(e){case"SUCCESS":return"succeeded";case"FAILED":return"failed";case"RUNNING":return"running";case"TIMEOUT":return"timeout";case"CANCELLED":return"cancelled";case"REJECTED":return"rejected";default:return""}}(t.payload.status||"");if(!r||!i)return e;let n=t.payload.progress,a=t.payload.message,s=t.payload.error?aA(t.payload.error,"tool_execute"):void 0,o=aL(e,r,{status:i,updatedAtMs:t.created_at_ms,progress:n,message:a,error:s}),l=o.toolCalls.find(e=>e.toolCallId===r);return l?{...o,messages:aS(o.messages,l.replyMessageId,e=>({...e,toolCalls:aO(e.toolCalls??[],l)}))}:o}(I,t)};case"trace_event":case"debug":default:return{state:I};case"heartbeat":return{state:(l=I,d=t,{...l,lastHeartbeatMs:d.payload.server_time_ms??d.created_at_ms})};case"answer_finish":return{state:(u=I,c=t,{...u,answerFinish:{messageId:c.reply_message_id,status:c.payload.status,finishReason:c.payload.finish_reason,usage:rP(c.payload.usage)?c.payload.usage:void 0,createdAtMs:c.created_at_ms,trace:c.trace,payload:c.payload}})};case"message_finish":return{state:function(e,t){let r=t.payload.message_id||t.reply_message_id;if(!r)return e;let i=t.payload.status||"completed";return{...e,messages:aS(e.messages,r,e=>({...e,status:function(e){switch(e){case"completed":case"finished":default:return"completed";case"cancelled":case"interrupted":return"interrupted";case"failed":case"error":return"failed"}}(i)}))}}(I,t)};case"reply_finish":return{state:(p=I,w="completed"===(b=t.payload.status||"completed")||"finished"===b?"completed":"cancelled"===b?"cancelled":"error",{...p,activeRequestId:void 0,activeReplyMessageId:void 0,messages:aP(p.messages,w),streamStatus:w})};case"stream_error":return{state:(h=I,_=aA((m=t).payload.error??m.payload,m.payload.stage||"stream"),{...h,activeRequestId:void 0,error:_,messages:aP(h.messages,"error"),streamStatus:"error"})}}}(this.state.simulator,e,{followUpContent:r,hasToolExecutor:!!this.simulatorToolExecutor,runId:t.id}),d=l&&!this.receivedSimulatorLocationDirectiveCardIds.has(l.cardId)?l:void 0;if(d&&this.receivedSimulatorLocationDirectiveCardIds.add(d.cardId),this.updateSimulatorState(()=>d?{...a,locationDirective:d}:a),d?this.appendSimulatorDebugEvent({category:"card",event:"simulator_location_directive_received",card_id:d.cardId,request_id:d.requestId,source_tool_call_id:d.sourceToolCallId,tool_name:d.toolName,trace_id:e.trace.trace_id}):l&&this.appendSimulatorDebugEvent({category:"card",event:"simulator_location_directive_loop_prevented",card_id:l.cardId,reason:"duplicate_card_id",request_id:l.requestId,tool_name:l.toolName,trace_id:e.trace.trace_id}),(null==o?void 0:o.status)==="not_found"&&this.appendSimulatorDebugEvent({category:"card",event:"simulator_history_card_refresh_skipped",reason:"card_not_found",request_id:e.request_id,trace_id:e.trace.trace_id,card_id:o.cardId}),s){let e=this.withFallbackToolCallServerId(s);e.requiresUserApproval?t.pendingApprovalToolCallIds.add(e.toolCallId):this.executeSimulatorToolCall(e,t)}}async executeSandboxToolCallOnce(e){let t=e.tool_call,r=Date.now(),i={trace_id:`bridge_${e.request_id}`,component:"sandbox_bridge",stage:"calltool_execute",sampled:!0},n={appKey:t.app_key,arguments:JSON.parse(t.arguments_json),argumentsJson:t.arguments_json,createdAtMs:r,deadlineMs:t.deadline_ms,mcpHeaders:t.headers,replyMessageId:`bridge_reply_${e.request_id}`,requestId:e.request_id,serverId:t.server_id,status:"running",timeoutMs:t.timeout_ms,toolCallId:t.tool_call_id,toolName:t.tool_name,trace:i,updatedAtMs:r};this.updateSimulatorState(e=>({...e,toolCalls:[...e.toolCalls,n]})),this.appendSimulatorDebugEvent({event:"sandbox_tool_call_started",request_id:n.requestId,trace_id:i.trace_id,tool_call_id:n.toolCallId,app_key:n.appKey,server_id:n.serverId,tool_name:n.toolName,arguments_json:n.argumentsJson,deadline_ms:n.deadlineMs,timeout_ms:n.timeoutMs});let a=Date.now(),s=t.deadline_ms<=a?{status:"timeout",error:a1("TOOL_EXEC_TIMEOUT","Sandbox tool call deadline has expired")}:await this.runSimulatorToolCall(n),o=this.createToolExecutorInput(n);try{await this.submitSandboxToolResultWithRetry(o,s,a)}catch(t){let e=aA(t,"tool_result_submit");throw this.updateToolCall(n.toolCallId,{error:e,resultSummary:e.message,status:"failed",updatedAtMs:Date.now()}),t}return this.updateToolCall(n.toolCallId,{error:s.error,isMiniApp:s.miniapp&&"boolean"==typeof s.miniapp.is_mini_app?s.miniapp.is_mini_app:void 0,resultSummary:a7(s),status:s.status,structuredResultSummary:s.result,updatedAtMs:Date.now()}),this.appendSimulatorDebugEvent({event:"sandbox_tool_call_reported",request_id:n.requestId,trace_id:i.trace_id,tool_call_id:n.toolCallId,app_key:n.appKey,server_id:n.serverId,tool_name:n.toolName,status:s.status,elapsed_ms:Date.now()-a,raw_mcp_result_json:s.raw_mcp_result_json}),{reported:!0,requestId:n.requestId,toolCallId:n.toolCallId}}withFallbackToolCallServerId(e){var t,r;if(e.serverId)return e;let i=this.lastResolvedSimulatorMcpServers,n=(null==(t=i.find(t=>t.tools.some(t=>t.name===e.toolName)))?void 0:t.server_id)||(null==(r=i[0])?void 0:r.server_id)||"local_mcp";return this.appendSimulatorDebugEvent({event:"tool_call_server_id_fallback",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,server_id:n,summary:"Tool call event has no server_id; falling back to a locally resolved MCP server"}),this.updateToolCall(e.toolCallId,{serverId:n}),{...e,serverId:n}}async runSimulatorToolCall(e,t){if(!this.simulatorToolExecutor){let e=a1("TOOL_EXECUTOR_UNAVAILABLE","No local simulator tool executor is configured");return{error:e,result:{error:e.message},status:"failed"}}try{return await a2({executor:this.simulatorToolExecutor,input:this.createToolExecutorInput(e),record:e,signal:t})}catch(t){let e=aA(t,"tool_execute");return{status:"TOOL_EXEC_TIMEOUT"===e.code?"timeout":"TOOL_EXEC_CANCELLED"===e.code||aT(t)?"cancelled":"failed",error:e}}}async executeSimulatorToolCall(e,t){if(t&&!this.isSimulatorRunCurrent(t))return;let r=Date.now(),i=this.createToolExecutorInput(e),n=t?new AbortController:void 0;t&&n&&t.toolAbortControllers.add(n);let a=await this.runSimulatorToolCall(e,null==n?void 0:n.signal);try{if(t&&!this.isSimulatorRunCurrent(t))return void this.appendSimulatorDebugEvent({event:"tool_result_submit_skipped",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,reason:"stale_or_cancelled_run"});if(await this.submitExecutedToolResult(i,a,r,null==n?void 0:n.signal),t&&!this.isSimulatorRunCurrent(t))return;this.updateToolCall(e.toolCallId,{status:a.status,updatedAtMs:Date.now(),error:a.error,resultSummary:a7(a),structuredResultSummary:a.result,isMiniApp:a.miniapp&&"boolean"==typeof a.miniapp.is_mini_app?a.miniapp.is_mini_app:void 0})}catch(i){if(t&&!this.isSimulatorRunCurrent(t))return void this.appendSimulatorDebugEvent({event:"tool_result_submit_skipped",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,reason:"stale_or_cancelled_run"});let r=aA(i,"tool_result_submit");this.appendSimulatorDebugEvent({event:"tool_result_submit_failed",trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,summary:r5(i),error:r}),this.updateToolCall(e.toolCallId,{status:"failed",updatedAtMs:Date.now(),error:r}),this.failActiveSimulatorStream(r)}finally{t&&n&&(t.toolAbortControllers.delete(n),this.releaseSimulatorRun(t))}}uploadSimulatorImage(e,t){return this.assertActive(),as({endpoint:this.state.simulator.endpoint,fetcher:this.simulatorFetcher,file:e,signal:t})}createToolExecutorInput(e){let t={trace_id:e.trace.trace_id,span_id:n2("span_tool_execute"),parent_span_id:e.trace.span_id,component:"local_mcp",stage:"tool_execute",sampled:e.trace.sampled};return{requestId:e.requestId,replyMessageId:e.replyMessageId,toolCallId:e.toolCallId,toolName:e.toolName,serverId:e.serverId,appKey:e.appKey||this.simulatorAppKey||se(this.state.manifest.raw,this.state.manifest.appId)||void 0,arguments:e.arguments,argumentsJson:e.argumentsJson,headers:e.mcpHeaders,manifest:this.state.manifest.raw,timeoutMs:e.timeoutMs,deadlineMs:e.deadlineMs,trace:t}}async resolveSimulatorManifestForQuery(e,t,r,i){let n=Date.now(),a=void 0!==t.manifest,s=a?"query_option":void 0===this.simulatorManifest?"loaded_manifest":"debugger_option";this.appendSimulatorDebugEvent({event:"simulator_manifest_load_started",trace_id:e,source:s});try{let o=a?{found:!1,value:void 0}:this.takeSimulatorManifestStateValue(),l=a?t.manifest:o.found?o.value:"function"==typeof this.simulatorManifest?await this.simulatorManifest(i):this.simulatorManifest,d=l?sr(r,l):r;return this.appendSimulatorDebugEvent({event:"simulator_manifest_loaded",trace_id:e,elapsed_ms:Date.now()-n,source:s,manifest:d}),d}catch(t){return i.throwIfAborted(),this.appendSimulatorDebugEvent({event:"simulator_manifest_load_failed",trace_id:e,elapsed_ms:Date.now()-n,error:r5(t),source:s}),r}}async resolveSimulatorSkillsForQuery(e,t,r){let i=Date.now(),n=void 0===t.skills?"debugger_option":"query_option";this.appendSimulatorDebugEvent({event:"simulator_skill_load_started",trace_id:e,source:n});try{let a=t.skills??("function"==typeof this.simulatorSkills?await this.simulatorSkills(r):this.simulatorSkills)??[];return this.appendSimulatorDebugEvent({event:a.length>0?"simulator_skill_loaded":"simulator_skill_empty",trace_id:e,elapsed_ms:Date.now()-i,skills_length:a.reduce((e,t)=>e+t.content.length,0),skill_paths:a.map(e=>e.relativePath),source:n}),a}catch(t){return null==r||r.throwIfAborted(),this.appendSimulatorDebugEvent({event:"simulator_skill_load_failed",trace_id:e,elapsed_ms:Date.now()-i,error:r5(t),source:n}),[]}}async resolveDirectToolCallServerId(e,t,r){var i;let n=null==t?void 0:t.trim();if(n)return n;let a=this.state.manifest.raw,s=this.simulatorAppKey||se(a,this.state.manifest.appId),o=this.simulatorAppName||st(a,this.state.manifest.name),l=this.simulatorMcpServerProvider?await this.simulatorMcpServerProvider({trace:r,appKey:s,appName:o,manifest:a}):this.simulatorMcpServers,d=l.find(t=>t.tools.some(t=>t.name===e));return(null==d?void 0:d.server_id)??(null==(i=l[0])?void 0:i.server_id)??"local_mcp"}getSimulatorToolCall(e){let t=this.state.simulator.toolCalls.find(t=>t.toolCallId===e);if(!t)throw Error(`Unknown simulator tool call: ${e}`);return t}getSimulatorToolCallRun(e){let t=this.activeSimulatorRun;if(t&&this.isSimulatorRunCurrent(t))return void 0===e.runId||e.runId===t.id?t:void 0}cancelStaleSimulatorToolCall(e){let t=a1("TOOL_EXEC_CANCELLED","Tool call cancelled because its simulator run is no longer active");this.appendSimulatorDebugEvent({event:"tool_result_submit_skipped",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,reason:"stale_or_cancelled_run"}),this.updateToolCall(e.toolCallId,{status:"cancelled",updatedAtMs:Date.now(),error:t,resultSummary:t.message})}async submitSandboxToolResultWithRetry(e,t,r){let i;for(let n=1;n<=2;n+=1)try{await this.submitExecutedToolResult(e,t,r,void 0,n);return}catch(t){if(i=t,2===n||void 0!==e.deadlineMs&&Date.now()>=e.deadlineMs)throw t;this.appendSimulatorDebugEvent({event:"sandbox_tool_result_report_retry",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,attempt:n+1,error:r5(t)})}throw i}async submitExecutedToolResult(e,t,r,i){let n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1,a=Date.now();await this.submitToolResult({...e,...t,timing:{started_at_ms:r,ended_at_ms:a,duration_ms:a-r,attempt:n}},i)}updateToolCall(e,t){this.updateSimulatorState(r=>aL(r,e,t))}failActiveSimulatorStream(e){this.activeSimulatorRun&&this.abortSimulatorRun(this.activeSimulatorRun),this.updateSimulatorState(t=>({...t,activeRequestId:void 0,activeReplyMessageId:void 0,error:e,messages:t.messages.map(e=>"assistant"===e.role&&"streaming"===e.status?{...e,status:"failed"}:e),streamStatus:"error"}))}getSimulatorQueryFailureDiagnosis(e,t){let r=new Set;for(let t of this.state.simulator.traceEvents){let i=t.payload,n=a6["string"==typeof i.event?i.event:""];n&&function(e){var t;return e.trace_id||(null==(t=e.trace)?void 0:t.trace_id)||""}(i)===e&&"Failed to fetch"===(i.error||"")&&r.add(n)}if(r.size>=3)return{code:"DEBUG_SERVER_UNREACHABLE",confidence:"high",failed_services:[...r],summary:"调试 Dev Server 或本机网络不可达",suggestion:"检查调试 Dev Server 是否运行,以及浏览器能否访问当前调试端口。"};let i=an(t),n="number"==typeof(null==i?void 0:i.status)?i.status:void 0;return 404===n?{code:"SIMULATOR_ENDPOINT_NOT_FOUND",confidence:"high",status:n,summary:"模拟器接口未配置或路由不存在",suggestion:"检查 simulator、manifest、skill 或 MCP 的接口地址与代理路由。"}:void 0!==n&&n>=500?{code:"SIMULATOR_ENDPOINT_SERVER_ERROR",confidence:"high",status:n,summary:`模拟器接口服务异常(HTTP ${n})`,suggestion:"接口已可达,但服务端或其上游依赖异常;请查看响应内容和服务端日志。"}:"Failed to fetch"===r5(t)?{code:"SIMULATOR_ENDPOINT_UNREACHABLE",confidence:"unknown",summary:"无法连接模拟器接口",suggestion:"可能是接口服务未启动、端口不可达、浏览器网络异常或 CORS 被拦截。"}:void 0}appendSimulatorDebugEvent(e){let t=r0(e),r={display:ah(e),id:n2("trace"),timestamp:Date.now(),payload:function(e,t){if(!rP(e))return{};let r=am(e);return{...e,category:r.category,detail:r.detail,phase:r.phase,title:r.title,log_ids:t.length>0?t:void 0}}(e,t)};this.updateSimulatorState(e=>{var t;return{...e,traceEvents:[...e.traceEvents,{...r,order:((null==(t=e.traceEvents.at(-1))?void 0:t.order)??e.traceEvents.length)+1}].slice(-200)}})}updateSimulatorState(e){this.setState({...this.state,simulator:e(this.state.simulator)})}setState(e){for(let t of(this.state=e,this.listeners))t(this.state)}assertActive(){if(this.destroyed)throw Error("WebSdkDebugger has been destroyed")}}function sn(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;return e.getSystem().theme??("function"==typeof matchMedia&&matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light")}function sa(e,t){let r="function"==typeof matchMedia?matchMedia("(prefers-color-scheme: dark)"):void 0,i=e.subscribe("theme",t);return null==r||r.addEventListener("change",t),()=>{i(),null==r||r.removeEventListener("change",t)}}let ss="iphone-13",so=[{key:ss,label:"iPhone 13",width:390,height:844,density:3,radius:47,homeIndicator:!0,statusBarHeight:47,safeArea:{top:47,bottom:34,left:0,right:0}},{key:"iphone-17-pro-max",label:"iPhone 17 Pro Max",width:440,height:956,density:3,radius:55,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-17-pro",label:"iPhone 17 Pro",width:402,height:874,density:3,radius:50,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-17",label:"iPhone 17",width:402,height:874,density:3,radius:50,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-air",label:"iPhone Air",width:420,height:912,density:3,radius:52,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16-pro-max",label:"iPhone 16 Pro Max",width:440,height:956,density:3,radius:55,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16-pro",label:"iPhone 16 Pro",width:402,height:874,density:3,radius:50,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16-plus",label:"iPhone 16 Plus",width:430,height:932,density:3,radius:55,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16",label:"iPhone 16",width:393,height:852,density:3,radius:47,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16e",label:"iPhone 16e",width:390,height:844,density:3,radius:44,homeIndicator:!0,statusBarHeight:47,safeArea:{top:47,bottom:34,left:0,right:0}},{key:"iphone-15-pro-max",label:"iPhone 15 Pro Max",width:430,height:932,density:3,radius:55,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-15",label:"iPhone 15",width:393,height:852,density:3,radius:47,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-14-plus",label:"iPhone 14 Plus",width:428,height:926,density:3,radius:47,homeIndicator:!0,statusBarHeight:47,safeArea:{top:47,bottom:34,left:0,right:0}},{key:"iphone-13-mini",label:"iPhone 13 mini",width:375,height:812,density:3,radius:44,homeIndicator:!0,statusBarHeight:50,safeArea:{top:50,bottom:34,left:0,right:0}},{key:"iphone-se",label:"iPhone SE",width:375,height:667,density:2,radius:0,homeIndicator:!1,statusBarHeight:20,safeArea:{top:20,bottom:0,left:0,right:0}},{key:"pixel-8-pro",label:"Pixel 8 Pro",width:448,height:998,density:3,radius:30,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"pixel-8",label:"Pixel 8",width:412,height:915,density:2.625,radius:28,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"pixel-7",label:"Pixel 7",width:412,height:915,density:2.625,radius:28,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"galaxy-s24",label:"Galaxy S24",width:360,height:780,density:3,radius:32,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"galaxy-s24-ultra",label:"Galaxy S24 Ultra",width:384,height:854,density:3.75,radius:18,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"galaxy-z-fold-5-cover",label:"Galaxy Z Fold 5 Cover",width:344,height:882,density:3,radius:30,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"galaxy-z-fold-5-inner",label:"Galaxy Z Fold 5 Inner",width:690,height:829,density:2.625,radius:24,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"ipad-mini",label:"iPad mini",width:744,height:1133,density:2,radius:18,homeIndicator:!0,statusBarHeight:24,safeArea:{top:24,bottom:20,left:0,right:0}},{key:"ipad-pro-11",label:'iPad Pro 11"',width:834,height:1194,density:2,radius:18,homeIndicator:!0,statusBarHeight:24,safeArea:{top:24,bottom:20,left:0,right:0}}],sl=[{key:"100",label:"100%",scale:1},{key:"85",label:"85%",scale:.85},{key:"75",label:"75%",scale:.75},{key:"50",label:"50%",scale:.5},{key:"fit",label:"自适应",scale:.88}],sd={key:"mobile-393",label:"393px",width:393,density:3};function su(e){let t=/^custom-([1-9]\d{0,3})x([1-9]\d{0,3})$/.exec(e);if(t){let r=Number(t[1]),i=Number(t[2]);return{key:e,label:`自定义 ${r} \xd7 ${i}`,width:r,height:i,density:1,radius:0,homeIndicator:!1,statusBarHeight:0,safeArea:{top:0,bottom:0,left:0,right:0}}}return so.find(t=>t.key===e)??so.find(e=>e.key===ss)??so[0]}let sc="devtools_web";function sp(e){return e.key.startsWith("iphone")||e.key.startsWith("ipad")}function sh(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:so["0"],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=sp(e);return{debugger:"web-sdk",channel:"debug",appTheme:sn(),density:e.density,screenWidth:e.width,screenHeight:e.height,containerWidth:e.width,containerHeight:e.height,statusBarHeight:e.statusBarHeight,safeArea:{marginTop:e.safeArea.top,marginBottom:e.safeArea.bottom,marginLeft:e.safeArea.left,marginRight:e.safeArea.right},topHeight:e.safeArea.top,bottomHeight:e.safeArea.bottom,devicePlatform:r?"iOS":"Android",os:r?"iOS":"Android",osVersion:"",deviceBrand:sp(e)?"Apple":e.key.startsWith("galaxy-")?"Samsung":e.key.startsWith("pixel-")?"Google":"Browser",deviceModel:e.label,screenOrientation:e.width>e.height?"landscape":"portrait",isLandscape:e.width>e.height,...t,platform:sc}}function sm(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:sd,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return{...sh(e.device??so["0"]),density:e.density,deviceModel:`Widget preview ${e.label}`,...t,platform:sc}}function sg(e,t){try{let e=t.trim()?JSON.parse(t):{};if(rP(e))return e;throw Error("expected a JSON object")}catch(t){throw Error(`${e}: ${t.message}`)}}function sf(e){let{name:t,readSample:r}=e,i=`doubao.on${t}Change`,n="DeviceMotion"===t?"DeviceMotionListening":t,a=`${"DeviceMotion"===t?"device motion":t.toLowerCase()} is not available`,s=new WeakMap;return{[`doubao.start${n}`]:{handler:(e,t)=>{var n,o;let l,d=(null==(n=e.params)?void 0:n.interval)??"normal";if(!["normal","ui","game"].includes(d))throw new w("invalid interval",104);if(!r().available)throw new w(a,103);let u=null==t?void 0:t.events;if(!u)throw new w("sensor event controller is unavailable",102);null==(o=s.get(u))||o();let c="game"===d?20:"ui"===d?62.5:200,p=!1,h=()=>{void 0!==l&&(clearInterval(l),l=void 0),s.delete(u),p=!0},m=u.onDestroy(h);if(p)throw new w("sensor event controller is destroyed",102);return s.set(u,()=>{h(),m()}),l=setInterval(()=>{let{available:e,params:t}=r();e&&u.emit(i,t)},c),_(e,{})}},[`doubao.stop${n}`]:{handler:(e,t)=>{if(null==t?void 0:t.events){var r;null==(r=s.get(t.events))||r()}return _(e,{})}}}}function sv(e){return{[`doubao.on${e}Change`]:()=>{}}}function sy(e){let{name:t,getSample:r}=e;return sf({name:t,readSample:()=>{let{available:e,x:t,y:i,z:n}=r();return{available:e,params:{x:t,y:i,z:n,timestamp:Math.round(1e6*performance.now())}}}})}let sb="wsd:runtime-console",sw=new WeakMap;function s_(e,t){if(!e.dispatchEvent(new CustomEvent(sb,{cancelable:!0,detail:t})))return;let r=sw.get(e)??[];r.push(t),sw.set(e,r)}class sS{state={interruption:"none",volumeFactor:1};listeners=new Set;getSnapshot=()=>this.state;subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));setInterruption(e){this.update({...this.state,interruption:e})}setVolumeFactor(e){this.update({...this.state,volumeFactor:Number.isFinite(e)?Math.max(0,Math.min(1,e)):1})}update(e){if(this.state.interruption!==e.interruption||this.state.volumeFactor!==e.volumeFactor)for(let t of(this.state=e,this.listeners))t()}}let sx=new sS,sI=new sS,sk="doubao.onInnerAudioContextStateChange",sC=()=>"function"==typeof Audio;class sE extends Error{errCode;constructor(e,t){super(t),this.errCode=e}}class sN{audioId;appletId;context;onEvent;clampPlaybackRate;focus;audio;cleanup=[];destroyed=!1;pendingStart=!0;errorReported=!1;playVersion=0;playRequested=!1;interrupted=!1;unsubscribeFocus;unsubscribeNetwork;state={src:"",startTime:0,autoplay:!1,loop:!1,volume:1,playbackRate:1,currentTime:0,duration:0,paused:!0,buffered:0};constructor(e,t,r,i,n=!0,a){this.audioId=e,this.appletId=t,this.context=r,this.onEvent=i,this.clampPlaybackRate=n,this.focus=a,this.unsubscribeFocus=null==a?void 0:a.subscribe(()=>this.focusChanged())}focusChanged(){var e,t;let r=null==(e=this.focus)?void 0:e.getSnapshot().interruption;if(this.audio&&this.applyOptions(this.audio),"none"===r){this.interrupted&&(this.interrupted=!1,this.play().catch(e=>{this.playbackFailed(e instanceof Error?e.message:"inner audio play failed")}));return}let i=!this.state.paused||this.playRequested;"forced"===r?this.interrupted=!1:i&&(this.interrupted=!0),i&&(++this.playVersion,this.playRequested=!1,this.state.paused=!0,null==(t=this.audio)||t.pause())}snapshot(){let e=this.audio;return e&&(this.state.currentTime=Number.isFinite(e.currentTime)?e.currentTime:0,this.state.duration=Number.isFinite(e.duration)?e.duration:0,this.state.buffered=e.buffered.length?e.buffered.end(e.buffered.length-1):0),{audioId:this.audioId,...this.state}}emit(e,t){var r;if(!this.destroyed){if(this.onEvent)return void this.onEvent(e,this.snapshot(),t);null==(r=this.context.events)||r.emitPrivate(sk,{audioId:this.audioId,appletId:this.appletId,eventName:e,state:this.snapshot(),...t?{errCode:t.errCode,errMsg:t.message}:{}})}}update(e){for(let t of["src","startTime","autoplay","loop","volume","playbackRate"]){let r=e[t];if(void 0!==r&&("src"===t&&"string"!=typeof r||("autoplay"===t||"loop"===t)&&"boolean"!=typeof r||["startTime","volume","playbackRate"].includes(t)&&("number"!=typeof r||!Number.isFinite(r))))throw new sE(-2012,"inner audio params are invalid")}let t={...this.state};"string"==typeof e.src&&(t.src=e.src.trim()),"number"==typeof e.startTime&&(t.startTime=Math.max(0,e.startTime)),"number"==typeof e.volume&&(t.volume=Math.max(0,Math.min(1,e.volume))),"number"==typeof e.playbackRate&&(t.playbackRate=this.clampPlaybackRate?Math.max(.5,Math.min(2,e.playbackRate)):e.playbackRate),"boolean"==typeof e.autoplay&&(t.autoplay=e.autoplay),"boolean"==typeof e.loop&&(t.loop=e.loop);let r=t.src!==this.state.src;if(r&&(this.release(),Object.assign(t,{currentTime:0,duration:0,buffered:0,paused:!0}),this.pendingStart=!0),this.state=t,this.audio&&this.applyOptions(this.audio),r&&t.autoplay||!0===e.autoplay)return this.play()}applyOptions(e){var t;e.loop=this.state.loop;let r=(null==(t=this.focus)?void 0:t.getSnapshot().volumeFactor)??1;e.volume=this.state.volume*r,e.playbackRate=this.state.playbackRate}async play(){if(!this.state.src)throw new sE(-2003,"inner audio src is empty");if(this.focus&&"none"!==this.focus.getSnapshot().interruption)throw new sE(-2009,"inner audio playback is interrupted");if(nq(this.state.src)&&!nD())throw new sE(-2007,nO);let e=++this.playVersion;if(this.errorReported=!1,this.interrupted=!1,!this.audio){let t;this.playRequested=!0;try{if(!this.state.src.startsWith("appletfile:")&&!/^https?:\/\//i.test(this.state.src))throw Error("unsupported audio source");if(t=await rV(this.state.src,this.context),this.destroyed||e!==this.playVersion)return;this.state.src.startsWith("appletfile:")||new URL(t)}catch{if(this.destroyed||e!==this.playVersion)return;throw this.playRequested=!1,new sE(-2004,"inner audio src is invalid")}let r=new Audio;this.audio=r,this.applyOptions(r);let i=(e,t)=>{r.addEventListener(e,t),this.cleanup.push(()=>r.removeEventListener(e,t))};for(let e of(i("canplay",()=>{this.pendingStart&&(this.pendingStart=!1,this.state.startTime>0&&(r.currentTime=Math.min(this.state.startTime,Number.isFinite(r.duration)?r.duration:this.state.startTime))),this.emit("canplay")}),i("playing",()=>{this.focus&&"none"!==this.focus.getSnapshot().interruption?r.pause():(this.playRequested=!1,this.state.paused=!1,this.emit("play"))}),i("pause",()=>{r.ended||(this.state.paused=!0,this.emit("pause"))}),i("ended",()=>{this.playRequested=!1,this.state.paused=!0,this.pendingStart=!0,this.emit("ended")}),["waiting","timeupdate","seeking","seeked"]))i(e,()=>this.emit(e));i("error",()=>{var e;this.playRequested=!1,this.state.paused=!0,this.playbackFailed((null==(e=r.error)?void 0:e.message)||"inner audio play failed")}),nq(this.state.src)&&(this.unsubscribeNetwork=n$(()=>{this.release(),this.state.paused=!0,this.playbackFailed(nO)})),r.preload="auto",r.src=t,r.load()}let t=this.audio;this.playRequested=!0,t.play().catch(r=>{this.audio!==t||this.destroyed||e!==this.playVersion||r instanceof DOMException&&"AbortError"===r.name||(this.state.paused=!0,this.playRequested=!1,this.playbackFailed(r instanceof Error?r.message:"inner audio play failed"))})}playbackFailed(e){this.errorReported||(this.errorReported=!0,this.emit("error",new sE(-2007,e)))}pause(){var e;this.interrupted=!1,this.playRequested=!1,++this.playVersion,this.state.paused=!0,null==(e=this.audio)||e.pause()}stop(){this.release(),this.state.currentTime=0,this.state.paused=!0,this.pendingStart=!0,this.emit("stop")}seek(e){if("number"!=typeof e||!Number.isFinite(e)||e<0)throw new sE(-2012,"invalid seek position");if(!this.audio)throw new sE(-2005,"inner audio player unavailable");try{this.pendingStart=!1,this.audio.currentTime=Math.min(e,Number.isFinite(this.audio.duration)?this.audio.duration:e)}catch{throw new sE(-2006,"inner audio seek failed")}}release(){var e;for(let t of(null==(e=this.unsubscribeNetwork)||e.call(this),this.unsubscribeNetwork=void 0,this.interrupted=!1,this.playRequested=!1,++this.playVersion,this.cleanup.splice(0)))t();let t=this.audio;this.audio=void 0,t&&(t.pause(),t.removeAttribute("src"),t.load())}destroy(){var e;this.destroyed||(this.release(),null==(e=this.unsubscribeFocus)||e.call(this),this.unsubscribeFocus=void 0,this.state.paused=!0,this.state.currentTime=0,this.emit("destroy"),this.destroyed=!0)}}let sT="doubao.onBackgroundAudioManagerStateChange",sA=()=>"function"==typeof Audio,sM=["title","epname","singer","coverImgUrl","webUrl"],sR=["play","pause","stop","seekto","previoustrack","nexttrack"];function sj(e){return e instanceof sE?{errCode:({[-2003]:-1001,[-2004]:-1002,[-2005]:-1004,[-2006]:-1003,[-2007]:-1002,[-2009]:-2001,[-2012]:-1007})[e.errCode]??e.errCode,errMsg:e.message.replaceAll("inner audio","background audio")}:{errCode:-1002,errMsg:e instanceof Error?e.message:"background audio play failed"}}let sP=new class{focus;player;appletId="";owner;unbind;metadata={};state=Object.freeze({paused:!0,playbackRate:1});listeners=new Set;callers=new Map;ownsMediaSession=!1;stopped=!0;mediaMetadataKey;constructor(e=sI){this.focus=e}getSnapshot=()=>this.state;subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));attach(e){var t,r,i,n;let a=(null==(t=e.navigation)?void 0:t.getPackageInfo().appId)??(null==(i=e.globalProps)||null==(r=i.packageInfo)?void 0:r.appId);if("string"!=typeof a||!a)throw new sE(-1008,"background audio appletId is empty");if(null==(n=e.applicationLifecycle)?void 0:n.signal.aborted)throw new sE(-1008,"background audio runtime is unavailable");let s=e.events;s&&!this.callers.has(s)&&(this.callers.set(s,a),s.onDestroy(()=>this.callers.delete(s)));let o=e.applicationLifecycle,l=(null==o?void 0:o.owner)??s;if(!l||!sA())throw new sE(-1004,"background audio player unavailable");if(!this.player||this.appletId!==a){this.reset(),this.appletId=a,this.owner=l,this.player=new sN("background",a,e,(e,t,r)=>{"destroy"!==e&&this.publish(e,t,r&&sj(r))},!1,this.focus);let t=()=>{this.owner===l&&this.reset()};o?(o.signal.addEventListener("abort",t,{once:!0}),this.unbind=()=>o.signal.removeEventListener("abort",t)):this.unbind=null==s?void 0:s.onDestroy(t),this.refresh()}}update(e){var t;for(let t of sM)if(void 0!==e[t]&&"string"!=typeof e[t])throw new sE(-1007,"background audio params are invalid");if(void 0!==e.playbackRate&&("number"!=typeof e.playbackRate||!Number.isFinite(e.playbackRate)||e.playbackRate<=0))throw new sE(-1007,"background audio params are invalid");for(let r of(null==(t=this.player)||t.update({src:e.src,startTime:e.startTime,playbackRate:e.playbackRate}),sM))"string"==typeof e[r]&&(this.metadata[r]=e[r]);this.refresh(),this.updateMediaSession()}async control(e,t){if(!this.player)throw new sE(-1004,"background audio player unavailable");switch(e){case"play":this.installMediaSession(),await this.player.play();break;case"pause":this.player.pause();break;case"stop":this.player.stop();break;case"seek":{if(!this.state.src)return;let e="number"==typeof t&&Number.isFinite(t)?Math.max(0,t):0;this.player.seek(e);break}case"prev":case"next":this.publish(e);break;default:throw new sE(-1006,"background audio action is invalid")}this.refresh(),this.updateMediaSession()}refresh(e){var t;let r=e??(null==(t=this.player)?void 0:t.snapshot());for(let e of(this.state=Object.freeze({...this.metadata,...r?{src:r.src,startTime:r.startTime,currentTime:r.currentTime,duration:r.duration,paused:r.paused,buffered:r.buffered,playbackRate:r.playbackRate}:{paused:!0,playbackRate:1}}),this.listeners))e()}publish(e,t,r){for(let[i,n]of("play"===e&&(this.stopped=!1),("stop"===e||"ended"===e)&&(this.stopped=!0),this.refresh(t),this.updateMediaSession(),this.callers))n===this.appletId&&i.emitPrivate(sT,{appletId:n,eventName:e,state:this.state,...r})}installMediaSession(){let e=navigator.mediaSession;if(e&&!this.ownsMediaSession)for(let t of(this.ownsMediaSession=!0,sR))try{e.setActionHandler(t,async e=>{try{await this.control("seekto"===t?"seek":"previoustrack"===t?"prev":"nexttrack"===t?"next":t,e.seekTime)}catch(e){this.publish("error",void 0,sj(e))}})}catch{}}updateMediaSession(){let e=navigator.mediaSession;if(e&&this.ownsMediaSession)try{let r=JSON.stringify([this.state.title,this.state.singer,this.state.epname,this.state.coverImgUrl]);if("function"==typeof MediaMetadata&&r!==this.mediaMetadataKey&&(e.metadata=new MediaMetadata({title:this.state.title,artist:this.state.singer,album:this.state.epname,artwork:this.state.coverImgUrl&&/^https?:\/\//i.test(this.state.coverImgUrl)?[{src:this.state.coverImgUrl}]:[]})),this.mediaMetadataKey=r,e.playbackState=this.stopped?"none":this.state.paused?"paused":"playing",this.state.duration&&this.state.duration>0){var t;null==(t=e.setPositionState)||t.call(e,{duration:this.state.duration,position:Math.min(this.state.duration,this.state.currentTime??0),playbackRate:this.state.playbackRate??1})}}catch{}}reset(){var e,t,r;null==(e=this.unbind)||e.call(this),this.unbind=void 0;let i=this.player;if(this.player=void 0,i&&(!this.stopped&&this.state.src&&this.publish("stop",{...i.snapshot(),currentTime:0,paused:!0}),i.destroy()),this.metadata={},this.owner=void 0,this.appletId="",this.ownsMediaSession&&navigator.mediaSession){for(let e of sR)try{navigator.mediaSession.setActionHandler(e,null)}catch{}navigator.mediaSession.metadata=null,navigator.mediaSession.playbackState="none";try{null==(t=(r=navigator.mediaSession).setPositionState)||t.call(r)}catch{}}this.ownsMediaSession=!1,this.stopped=!0,this.mediaMetadataKey=void 0,this.refresh()}},sL=new class{hardware;beacons=new Map;filters=[];unwatch;unregisterOwner;constructor(e=nL){this.hardware=e}start(e,t){if(!this.hardware.getBeacon().rangingAvailable)throw new w("beacon ranging is not available",116);if(!Array.isArray(e.uuids)||!e.uuids.length||e.uuids.some(e=>"string"!=typeof e||!iU(e))||void 0!==e.ignoreBluetoothAvailable&&"boolean"!=typeof e.ignoreBluetoothAvailable)throw new w("invalid or empty uuids",104);if(!this.hardware.getBeacon().locationAuthorized)throw new w("location permission denied",106);let r=this.hardware.getBluetooth();if(!r.authorized)throw new w("bluetooth permission denied",106);if(!r.available||!r.enabled)throw new w("bluetooth is unavailable or powered off",116);this.stop(),this.filters=e.uuids.map(e=>e.toLowerCase()),this.beacons.clear();let i=null==t?void 0:t.events;if(i){let e=!1;if(this.unregisterOwner=i.onDestroy(()=>{e=!0,this.stop()}),e)throw new w("beacon context is destroyed",102)}let n=()=>this.capture(),a=this.hardware.subscribe("beacon",n),s=this.hardware.subscribe("bluetooth",n);this.unwatch=()=>{a(),s()},this.capture()}capture(){let e=this.hardware.getBluetooth(),t=this.hardware.getBeacon();if(e.available&&e.enabled&&e.authorized&&t.locationAuthorized&&t.rangingAvailable)for(let e of t.beacons)this.filters.includes(e.uuid.toLowerCase())&&this.beacons.set(iq(e),{...e,uuid:e.uuid.toLowerCase()})}stop(){var e,t;null==(e=this.unwatch)||e.call(this),this.unwatch=void 0,null==(t=this.unregisterOwner)||t.call(this),this.unregisterOwner=void 0}get(){if(!this.hardware.getBluetooth().authorized||!this.hardware.getBeacon().locationAuthorized)throw new w("beacon permission denied",106);return{beacons:[...this.beacons.values()].sort((e,t)=>iq(e).localeCompare(iq(t)))}}},sO="doubao.onBLEConnectionStateChange";function sD(e,t){let r=e[t];if("string"!=typeof r||!r.trim())throw new w(`invalid ${t}`,104);return r}class sU{hardware;events;connections=new Map;pending=new Map;constructor(e,t){this.hardware=e,this.events=t}closeAll(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0];for(let e of[...this.pending.values()])e(new w("bluetooth connection closed",114));for(let t of[...this.connections.keys()])this.disconnect(t,e)}observe(e){if(!e.available||!e.enabled||!e.authorized)return void this.closeAll();for(let[t,r]of this.connections){let i=e.devices.find(e=>e.deviceId===t);if(!i){this.disconnect(t);continue}for(let e of i.services??[])for(let i of e.characteristics){let n=this.key(e.uuid,i.uuid),a=r.notifications.get(n);void 0!==a&&a!==i.value&&(r.notifications.set(n,i.value),this.publishValue(t,e.uuid,i.uuid,i.value))}}}device(e){let t=sD(e,"deviceId"),r=this.hardware.getBluetooth().devices.find(e=>e.deviceId.toLowerCase()===t.toLowerCase());if(!r)throw new w("bluetooth device not found",116);return r}connection(e){let t=this.connections.get(e.deviceId);if(!t)throw new w("ble connection not found",116);return t}uuid(e,t){let r=iz(sD(e,t));if(!r)throw new w(`invalid ${t} UUID`,104);return r}key(e,t){return`${iz(e)}|${iz(t)}`}target(e){var t;let r=this.device(e),i=this.connection(r),n=this.uuid(e,"serviceId"),a=this.uuid(e,"characteristicId"),s=null==(t=r.services)?void 0:t.find(e=>iz(e.uuid)===n);if(!s)throw new w("ble service not found",116);let o=s.characteristics.find(e=>iz(e.uuid)===a);if(!o)throw new w("ble characteristic not found",116);return{device:r,connection:i,service:s,characteristic:o}}publishValue(e,t,r,i){this.events.emit("doubao.onBLECharacteristicValueChange",{deviceId:e,serviceId:iz(t),characteristicId:iz(r),value:i})}disconnect(e){var t;let r=!(arguments.length>1)||void 0===arguments[1]||arguments[1];null==(t=this.pending.get(e))||t(new w("bluetooth connection closed",114)),this.connections.delete(e)&&r&&this.events.emit(sO,{deviceId:e,connected:!1})}connect(e){let t=this.device(e),r=this.hardware.getBluetooth();if(!r.available||!r.enabled)throw new w("bluetooth adapter is disabled",116);if(this.connections.has(t.deviceId)||this.pending.has(t.deviceId))throw new w("ble already connected or pending",118);if(void 0!==e.timeout&&("number"!=typeof e.timeout||!Number.isFinite(e.timeout)||e.timeout<=0))throw new w("invalid timeout",104);if(!t.connectable)throw new w("createBLEConnection failed",102);let i=t.connectionDelayMs??0,n=void 0===e.timeout?void 0:e.timeout;return new Promise((e,r)=>{let a=setTimeout(()=>{if(this.pending.delete(t.deviceId),void 0!==n&&n<i)return void r(new w("createBLEConnection timeout",115));let a=this.hardware.getBluetooth().devices.find(e=>e.deviceId===t.deviceId);(null==a?void 0:a.connectable)?(this.connections.set(t.deviceId,{mtu:23,notifications:new Map}),this.events.emit(sO,{deviceId:t.deviceId,connected:!0}),e()):r(new w("bluetooth device not found",116))},void 0===n?i:Math.min(i,n));this.pending.set(t.deviceId,e=>{clearTimeout(a),this.pending.delete(t.deviceId),r(e)})})}handle(e,t){switch(e){case"createBLEConnection":return this.connect(t);case"closeBLEConnection":{let e=this.device(t);if(!this.connections.has(e.deviceId)&&!this.pending.has(e.deviceId))throw new w("ble connection not found",116);this.disconnect(e.deviceId);return}case"getConnectedBluetoothDevices":{if(!Array.isArray(t.services)||t.services.some(e=>"string"!=typeof e||!iz(e)))throw new w("invalid services",104);let e=new Set(t.services.map(e=>iz(e)));return{devices:this.hardware.getBluetooth().devices.filter(t=>{var r;return this.connections.has(t.deviceId)&&(null==(r=t.services)?void 0:r.some(t=>e.has(iz(t.uuid))))}).map(e=>{let{deviceId:t,name:r}=e;return{deviceId:t,name:r}})}}case"makeBluetoothPair":{let e,r=this.device(t),i=sD(t,"pin");try{e=atob(i.replace(/\s/g,""))}catch{throw new w("invalid pin",104)}if(void 0!==t.timeout&&("number"!=typeof t.timeout||!Number.isFinite(t.timeout)||t.timeout<=0))throw new w("invalid timeout",104);if(r.paired)return;if(e!==atob(r.pin??"MDAwMDAw"))throw new w("bluetooth pair failed",102);let n=this.hardware.getBluetooth();this.hardware.setBluetooth({...n,devices:n.devices.map(e=>e===r?{...e,paired:!0}:e)});return}case"isBluetoothDevicePaired":if(!this.device(t).paired)throw new w("bluetooth device is not paired",116);return;case"getBLEDeviceServices":{let e=this.device(t);return this.connection(e),{services:(e.services??[]).map(e=>({uuid:iz(e.uuid),isPrimary:e.isPrimary}))}}case"getBLEDeviceCharacteristics":{var r;let e=this.device(t);this.connection(e);let i=this.uuid(t,"serviceId"),n=null==(r=e.services)?void 0:r.find(e=>iz(e.uuid)===i);if(!n)throw new w("ble service not found",116);return{characteristics:n.characteristics.map(e=>{let{uuid:t,properties:r}=e;return{uuid:iz(t),properties:{...r,writeDefault:r.write}}})}}case"getBLEDeviceRSSI":{let e=this.device(t);return this.connection(e),{RSSI:e.RSSI}}case"getBLEMTU":return{mtu:this.connection(this.device(t)).mtu};case"setBLEMTU":{let e=this.device(t),r=this.connection(e);if(!Number.isInteger(t.mtu)||t.mtu<23||t.mtu>517)throw new w("mtu must be an integer between 23 and 517",104);return r.mtu=Math.min(e.maxMTU??247,t.mtu),{mtu:r.mtu}}case"readBLECharacteristicValue":{let{device:e,service:r,characteristic:i}=this.target(t);if(!i.properties.read)throw new w("read characteristic failed",102);this.publishValue(e.deviceId,r.uuid,i.uuid,i.value);return}case"notifyBLECharacteristicValueChange":{if("boolean"!=typeof t.state||void 0!==t.type&&"string"!=typeof t.type)throw new w("invalid notification parameters",104);let{connection:e,service:r,characteristic:i}=this.target(t),n=(t.type||"indication").toLowerCase();if(t.state&&!("notification"===n?i.properties.notify:"indication"===n&&i.properties.indicate))throw new w("ble characteristic does not support notify type",103);let a=this.key(r.uuid,i.uuid);t.state?e.notifications.set(a,i.value):e.notifications.delete(a);return}case"writeBLECharacteristicValue":{if(!iW(t.value)||void 0!==t.writeType&&("string"!=typeof t.writeType||!["write","writeNoResponse"].includes(t.writeType)))throw new w("invalid characteristic value or writeType",104);let{device:e,service:r,characteristic:i}=this.target(t);if(!("string"==typeof t.writeType&&"writenoresponse"===t.writeType.toLowerCase()?i.properties.writeNoResponse:i.properties.write))throw new w("ble characteristic does not support write type",103);let n=this.hardware.getBluetooth(),a=t.value;this.hardware.setBluetooth({...n,devices:n.devices.map(t=>{var n;return t===e?{...t,services:null==(n=t.services)?void 0:n.map(e=>e===r?{...e,characteristics:e.characteristics.map(e=>e===i?{...e,value:a}:e)}:e)}:t})});return}}}}let sq="doubao.onBluetoothAdapterStateChange",s$="doubao.onBluetoothDeviceFound",sB=new class{hardware;clients=new WeakMap;released=new WeakSet;constructor(e=nL){this.hardware=e}client(e,t){var r;if(!e||this.released.has(e))throw new w("bluetooth context is unavailable",102);let i=this.clients.get(e);if(i)return(null==t?void 0:t.globalProps)&&(i.platform="Android"===t.globalProps.os?"Android":"iOS"),i;let n=i={events:e,platform:(null==t||null==(r=t.globalProps)?void 0:r.os)==="Android"?"Android":"iOS",opened:!1,discovering:!1,devices:new Map,unwatch:()=>{},gatt:new sU(this.hardware,e)};if(this.clients.set(e,n),e.onDestroy(()=>{this.released.add(e),this.stopTimer(n),n.unwatch(),n.devices.clear(),n.gatt.closeAll(!1),this.clients.delete(e)}),this.released.has(e))throw new w("bluetooth context is destroyed",102);let a=this.hardware.getBluetooth();return n.unwatch=this.hardware.subscribe("bluetooth",()=>{let e=this.hardware.getBluetooth();if(e===a)return;let t=e.available!==a.available||e.enabled!==a.enabled||e.authorized!==a.authorized;n.gatt.observe(e),a=e,t&&(this.available()||(this.stopTimer(n),n.discovering=!1),n.opened&&this.publishState(n,this.available()))}),n}available(){let e=this.hardware.getBluetooth();return e.available&&e.enabled&&e.authorized}requireOpened(e){if(this.requirePermission(),!e.opened)throw new w("bluetooth adapter is not initialized",116)}requirePermission(){if(!this.hardware.getBluetooth().authorized)throw new w("bluetooth permission denied",106)}requireAvailable(){if(this.requirePermission(),!this.hardware.getBluetooth().available)throw new w("bluetooth is unsupported",103);if(!this.available())throw new w("bluetooth adapter is unavailable or powered off",116)}publishState(e,t){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i={available:t,discovering:e.discovering},n=JSON.stringify(i);(r||n!==e.lastState)&&(e.lastState=n,e.events.emit(sq,i))}wake(e,t){let r=this.client(e,t);this.publishState(r,this.available(),!0)}open(e){this.requireAvailable(),e.opened=!0,this.publishState(e,!0)}close(e){this.requirePermission(),this.stopTimer(e),e.opened=!1,e.discovering=!1,e.gatt.closeAll(),e.devices.clear(),this.publishState(e,!1,!0)}state(e){this.requireOpened(e);let t=this.available();return{available:t,discovering:t&&e.discovering}}startDiscovery(e,t){if(this.requireOpened(e),e.discovering)throw new w("bluetooth discovery already started",118);this.requireAvailable();let{services:r,interval:i,allowDuplicatesKey:n}=t,a=t.powerLevel??"medium";if(void 0!==n&&"boolean"!=typeof n||void 0!==i&&!Number.isInteger(i)||"string"!=typeof a||!["low","medium","high"].includes(a.toLowerCase())||void 0!==r&&(!Array.isArray(r)||r.some(e=>"string"!=typeof e||!iz(e))))throw new w("invalid Bluetooth discovery parameters",104);let s=(null==r?void 0:r.map(iz))??[];this.stopTimer(e),e.devices.clear(),e.discovering=!0,e.timer=setInterval(()=>{if(this.available())for(let t of this.hardware.getBluetooth().devices){if(s.length&&!t.advertisServiceUUIDs.some(e=>s.includes(iz(e))))continue;let r=e.devices.get(t.deviceId);e.devices.set(t.deviceId,t),(n||JSON.stringify(r&&this.snapshot(r))!==JSON.stringify(this.snapshot(t)))&&e.events.emit(s$,{devices:[this.snapshot(t)]})}},Math.max(i??500,100)),this.publishState(e,!0)}stopDiscovery(e){this.requireOpened(e),e.discovering&&(this.stopTimer(e),e.discovering=!1,this.publishState(e,e.opened&&this.available()))}devices(e){return this.requireOpened(e),[...e.devices.values()].sort((e,t)=>e.deviceId.localeCompare(t.deviceId)).map(e=>this.snapshot(e))}snapshot(e){let{deviceId:t,name:r,localName:i,RSSI:n,connectable:a,advertisData:s,advertisServiceUUIDs:o,serviceData:l}=e;return{deviceId:t,name:r,localName:i,RSSI:n,connectable:a,advertisData:s,advertisServiceUUIDs:o,serviceData:l}}gatt(e,t,r){if("iOS"===e.platform&&["makeBluetoothPair","isBluetoothDevicePaired"].includes(t))throw new w(`${t} is not supported on iOS`,103);return this.requireOpened(e),e.gatt.handle(t,r)}stopTimer(e){void 0!==e.timer&&(clearInterval(e.timer),e.timer=void 0)}},sF=new Map,sz={"scope.userLocation":{description:"将使用你的位置信息,用于提供定位及位置相关服务。",title:"申请获取你的位置信息"},"scope.userFuzzyLocation":{description:"将使用你的大致位置信息,用于提供位置相关服务。",title:"申请获取你的模糊位置信息"},"scope.userLocationBackground":{description:"将在应用插件进入后台后继续使用你的位置信息。",title:"申请获取你的后台位置信息"},"scope.record":{description:"将使用你的麦克风,用于录制音频内容或进行语音输入。",title:"申请获取你的麦克风权限"},"scope.bluetooth":{description:"将使用你的蓝牙,用于发现和连接附近设备。",title:"申请获取你的蓝牙权限"},"scope.camera":{description:"将使用你的相机,用于拍摄照片或视频。",title:"申请获取你的相机权限"},"scope.addPhoneContact":{description:"将使用你的通讯录,用于添加或更新联系人。",title:"申请获取你的通讯录读写权限"},"scope.addPhoneCalendar":{description:"将使用你的日历,用于添加或更新日程。",title:"申请获取你的日历读写权限"}};function sW(e,t){return`${e||"unknown-app"}:${t}`}function sH(e){return sz[e]??{description:"需要获得你的授权后才能继续使用此功能。",title:`申请获取你的${e.replace(/^scope\./,"")||"相关"}权限`}}function sV(e){let t=sW(e,"");return Object.fromEntries([...sF].filter(e=>{let[r]=e;return r.startsWith(t)}).map(e=>{let[r,i]=e;return[r.slice(t.length),"granted"===i]}))}function sG(e,t,r){sF.set(sW(e,t),r)}async function sJ(e){let{appId:t,appIcon:r,appName:i,presenter:n,scope:a,signal:s,skipDialogIfDenied:o=!1}=e;if(null==s?void 0:s.aborted)return!1;let l=t||"unknown-app",d=sF.get(sW(l,a));if("granted"===d)return!0;if("denied"===d&&o)return!1;if(!n){let e="denied"!==d;return sG(l,a,e?"granted":"denied"),e}let u=await n({appId:l,appIcon:r,appName:i||"应用插件",scope:a,signal:s,...sH(a)});return(null==s||!s.aborted)&&(sG(l,a,u?"granted":"denied"),u)}let sK="doubao-debugger-virtual-calendar",sZ={accountAvailable:!0,writeSucceeds:!0,timeZone:"Asia/Shanghai"};function sX(e){if("boolean"!=typeof e.accountAvailable||"boolean"!=typeof e.writeSucceeds||"string"!=typeof e.timeZone)throw Error("日历账户和写入结果需为布尔值,时区需为 IANA 时区名称");new Intl.DateTimeFormat("en",{timeZone:e.timeZone}).format(0)}let sY=new class{settings=Object.freeze({...sZ});events=Object.freeze([]);listeners=new Set;constructor(){try{let e=JSON.parse(localStorage.getItem(sK)??"null");if(!e||(sX(e.settings),!Array.isArray(e.events)||e.events.some(e=>!e||"string"!=typeof e.id||"string"!=typeof e.appId||"string"!=typeof e.title||!Number.isFinite(e.startTime)||!Number.isFinite(e.endTime))))return;this.settings=Object.freeze({...e.settings}),this.events=Object.freeze(e.events.map(e=>Object.freeze({...e})))}catch{}}getSettings=()=>this.settings;getEvents=()=>this.events;subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));setSettings(e){sX(e),this.commit(Object.freeze({...e}),this.events)}clear(){this.commit(this.settings,Object.freeze([]))}write(e,t){if(!this.settings.accountAvailable)throw Error("no writable calendar account");if(!this.settings.writeSucceeds)throw Error("calendar store error");let r=Object.freeze({...e,id:`calendar-${Date.now()}-${this.events.length+1}`,appId:t,timeZone:this.settings.timeZone}),i=[...this.events,r];this.commit(this.settings,Object.freeze(i))}commit(e,t){for(let r of(localStorage.setItem(sK,JSON.stringify({settings:e,events:t})),this.settings=e,this.events=t,this.listeners))r()}};function sQ(e){return e??document.body}async function s0(e,t){var r;let i,n=sQ(t),a=new CustomEvent("doubao:multi-media-broadcast",{bubbles:!0,composed:!0,detail:e});n.dispatchEvent(a),window.dispatchEvent(new CustomEvent("doubao:multi-media-broadcast",{detail:e}));let s=(r=e.mediaId,i=Array.from(sQ(t).querySelectorAll("audio,video")),r?i.filter(e=>e.id===r||e.dataset.mediaId===r):i);return await Promise.all(s.map(t=>"play"===e.action?t.play():Promise.resolve(t.pause()))),{affected:s.length}}let s1=0,s2="x-web-sdk-file-transfer";function s3(e){return null==e?"":"object"==typeof e?JSON.stringify(e):String(e)}function s4(e,t){return new Promise((r,i)=>{let n=new Image;/^https?:/.test(e)&&(n.crossOrigin="anonymous");let a=()=>{null==t||t.removeEventListener("abort",s),n.onload=n.onerror=null},s=()=>{a(),n.removeAttribute("src"),i(null==t?void 0:t.reason)};(null==t?void 0:t.aborted)?s():(null==t||t.addEventListener("abort",s,{once:!0}),n.onload=()=>{a(),r(n)},n.onerror=()=>{a(),i(Error(`failed to load image: ${e}`))},n.src=e)})}async function s6(e,t){if("string"!=typeof e.src||!e.src)throw new w("src must be a non-empty string",104);let r=await rV(e.src,t),i=await (nq(r)?nB(e=>s4(r,e)):s4(r)),n=document.createElement("canvas"),a=(e.compressedWidth??0)>0&&(e.compressedHeight??0)>0,s=a?e.compressedWidth:i.naturalWidth||i.width,o=a?e.compressedHeight:i.naturalHeight||i.height;n.width=s,n.height=o;let l=n.getContext("2d");if(!l)throw Error("canvas 2d context is not available");return l.drawImage(i,0,0,s,o),{tempFilePath:n.toDataURL("image/jpeg",Math.min(100,Math.max(0,e.quality??80))/100)}}async function s5(e,t){var r;if("string"!=typeof e.filePath||!e.filePath)throw new w("filePath must be a non-empty string",104);let i=await rV(e.filePath,t);if(/^https?:/i.test(i))throw new w("filePath must refer to a local image",104);let n=nL.getSystem().album;if("denied"===n||"restricted"===n)throw new w("photo album write permission denied",106);let a=new AbortController,s=null==t||null==(r=t.events)?void 0:r.onDestroy(()=>a.abort(new w("image save view was destroyed",114)));try{try{await s4(i,a.signal)}catch(t){if(a.signal.aborted)throw t;let e=new w("cannot decode image",102);throw e.cause=t,e}if(a.signal.aborted)throw a.signal.reason}finally{null==s||s()}let o=document.createElement("a");o.href=i,o.download=e.filePath.split("/").pop()||"image",o.style.display="none",document.body.append(o);try{o.click()}finally{o.remove()}}function s8(){var e;let t=document.activeElement;for(;null==t||null==(e=t.shadowRoot)?void 0:e.activeElement;)t=t.shadowRoot.activeElement;return t}function s9(e,t){for(;e;){if(t.contains(e))return!0;let r=e.getRootNode();e=r instanceof ShadowRoot?r.host:null}return!1}let s7={enableHighAccuracy:!0,maximumAge:0,timeout:1e4};function oe(){return{browserAuthorization:"unknown",message:"未配置",tone:"muted",userAuthorization:"unknown"}}function ot(e){let{longitude:t,latitude:r}=e;if(!Number.isFinite(t)||!Number.isFinite(r)||t<-180||t>180||r<-90||r>90)throw Error("Invalid location coordinates")}function or(e,t){var r,i,n,a;if(ot({latitude:t,longitude:e}),e<72.004||e>137.8347||t<.8293||t>55.8271)return{latitude:t,longitude:e};let s=-100+2*(r=e-105)+3*(i=t-35)+.2*i*i+.1*r*i+.2*Math.sqrt(Math.abs(r))+(20*Math.sin(6*r*Math.PI)+20*Math.sin(2*r*Math.PI))*2/3+(20*Math.sin(i*Math.PI)+40*Math.sin(i/3*Math.PI))*2/3+(160*Math.sin(i/12*Math.PI)+320*Math.sin(i*Math.PI/30))*2/3,o=300+(n=e-105)+2*(a=t-35)+.1*n*n+.1*n*a+.1*Math.sqrt(Math.abs(n))+(20*Math.sin(6*n*Math.PI)+20*Math.sin(2*n*Math.PI))*2/3+(20*Math.sin(n*Math.PI)+40*Math.sin(n/3*Math.PI))*2/3+(150*Math.sin(n/12*Math.PI)+300*Math.sin(n/30*Math.PI))*2/3,l=t/180*Math.PI,d=Math.sin(l),u=Math.sqrt(d=1-.006693421622965943*d*d);return{latitude:t+(s=180*s/(6335552.717000426/(d*u)*Math.PI)),longitude:e+(o=180*o/(6378245/u*Math.cos(l)*Math.PI))}}let oi=new class{browserAuthorization="unknown";browserLocation;browserWatchId;locationListeners=new Set;locationUpdateRequests=new Map;manualLocation;pendingBrowserRequest;revision=0;snapshot=oe();snapshotListeners=new Set;updatesActive=!1;updateCoordinateType="gcj02";pendingBrowserOptions="";userAuthorization="unknown";watchRevision=0;getSnapshot=()=>this.snapshot;subscribe=e=>(this.snapshotListeners.add(e),()=>this.snapshotListeners.delete(e));subscribeLocation=e=>(this.locationListeners.add(e),()=>this.locationListeners.delete(e));isLocationScope(e){return"scope.userLocation"===e||"scope.userFuzzyLocation"===e||"scope.userLocationBackground"===e}updateUserAuthorization(e){this.userAuthorization=e?"granted":"denied",this.updateSnapshot({userAuthorization:this.userAuthorization}),!e&&this.locationUpdateRequests.size>0&&(this.stopLocationUpdates(),this.emitLocation({status:"user_unauthorized"}))}async requestLocation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:s7;return"granted"!==this.userAuthorization?{status:"user_unauthorized"}:this.requestLocationForHostDirective(e)}async requestLocationForHostDirective(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:s7,t=this.getConfiguredLocation();return t||("denied"===this.browserAuthorization?this.createBrowserUnauthorizedResult():this.locateWithBrowser(e))}async requestBrowserLocation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:s7;this.manualLocation=void 0,this.clearBrowserWatch();let t=await this.locateWithBrowser(e);return"success"===t.status&&!this.manualLocation&&this.updatesActive&&this.startBrowserWatch(e),t}setManualLocation(e){ot(e),this.revision+=1,this.pendingBrowserRequest=void 0,this.clearBrowserWatch(),this.manualLocation={...e,wgs84:function(e,t){let r={longitude:e,latitude:t};for(let i=0;i<8;i++){let i=or(r.longitude,r.latitude),n=i.longitude-e,a=i.latitude-t;if(r={longitude:r.longitude-n,latitude:r.latitude-a},1e-8>Math.max(Math.abs(n),Math.abs(a)))break}return r}(e.longitude,e.latitude),accuracy:0,source:"manual",speed:0,timestamp:Date.now()},this.browserAuthorization="granted",this.updateSnapshot({...e,browserAuthorization:"granted",errorMessage:void 0,message:"已配置(手动坐标)",source:"manual",tone:"success",updatedAtMs:Date.now()}),this.updatesActive&&this.emitLocation({location:this.manualLocation,status:"success"})}setConfigurationError(e){this.updateSnapshot({errorMessage:e,message:"定位失败",tone:"error",updatedAtMs:Date.now()})}get isUpdating(){return this.updatesActive}async startLocationUpdates(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:s7,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{type:r="gcj02",signal:i,authorize:n}=t;if(null==i?void 0:i.aborted)throw new DOMException("Location updates were stopped","AbortError");this.releaseLocationUpdate(i);let a={active:!1,stop:()=>this.releaseLocationUpdate(i)};this.locationUpdateRequests.set(i,a),null==i||i.addEventListener("abort",a.stop,{once:!0});let s=()=>{if(this.locationUpdateRequests.get(i)!==a)throw new DOMException("Location updates were stopped","AbortError")};try{if(n&&await n(),s(),"granted"!==this.userAuthorization){let e={status:"user_unauthorized"};return this.releaseLocationUpdate(i),this.emitLocation(e),e}if(this.updateCoordinateType=r,a.active=!0,this.updatesActive=!0,this.manualLocation)this.emitLocation({status:"success",location:{...this.manualLocation,timestamp:Date.now()}});else{var o;if("u"<typeof navigator||"function"!=typeof(null==(o=navigator.geolocation)?void 0:o.watchPosition))return this.releaseLocationUpdate(i),this.handleBrowserError(Error("Geolocation is not available in the current browser"));try{this.startBrowserWatch(e)}catch(e){return this.releaseLocationUpdate(i),this.handleBrowserError(e)}}return s(),{status:"success"}}catch(e){throw this.locationUpdateRequests.get(i)===a&&this.releaseLocationUpdate(i),e}}stopLocationUpdates(){for(let e of this.locationUpdateRequests.keys())this.releaseLocationUpdate(e);this.updatesActive=!1,this.clearBrowserWatch()}releaseLocationUpdate(e){let t=this.locationUpdateRequests.get(e);t&&(this.locationUpdateRequests.delete(e),null==e||e.removeEventListener("abort",t.stop),this.updatesActive=[...this.locationUpdateRequests.values()].some(e=>e.active),this.updatesActive||this.clearBrowserWatch())}createBusinessLocationInfo(e){let t=function(){try{return new Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{return""}}();return{latitude:e.latitude,longitude:e.longitude,city:"",city_code:"",client_time_zone:t,country:"",country_code:"",district:"",impr_time:String(Math.floor(Date.now()/1e3)),province:"",region:"",time_zone:t,town:""}}reset(){this.revision+=1,this.stopLocationUpdates(),this.browserAuthorization="unknown",this.browserLocation=void 0,this.manualLocation=void 0,this.pendingBrowserRequest=void 0,this.pendingBrowserOptions="",this.updateCoordinateType="gcj02",this.userAuthorization="unknown",this.snapshot=oe(),this.emitSnapshot()}getConfiguredLocation(){return this.manualLocation?{location:{...this.manualLocation,timestamp:Date.now()},status:"success"}:"granted"===this.browserAuthorization&&this.browserLocation&&Date.now()-this.browserLocation.timestamp<=6e4?{location:this.browserLocation,status:"success"}:void 0}locateWithBrowser(e){let t=JSON.stringify(e);if(this.pendingBrowserRequest&&this.pendingBrowserOptions===t)return this.pendingBrowserRequest;this.pendingBrowserOptions=t;let r=++this.revision;this.browserAuthorization="pending",this.updateSnapshot({browserAuthorization:"pending",errorMessage:void 0,latitude:void 0,longitude:void 0,message:"定位中...",source:"browser",tone:"pending",updatedAtMs:Date.now()});let i=this.getBrowserPosition(e).then(e=>{let t=this.toBrowserLocation(e);return r===this.revision&&(this.browserAuthorization="granted",this.browserLocation=t,this.updateSnapshot({browserAuthorization:"granted",errorMessage:void 0,latitude:t.latitude,longitude:t.longitude,message:"已配置(浏览器定位)",source:"browser",tone:"success",updatedAtMs:Date.now()})),{location:t,status:"success"}}).catch(e=>this.handleBrowserError(e,r)).finally(()=>{this.pendingBrowserRequest===i&&(this.pendingBrowserRequest=void 0)});return this.pendingBrowserRequest=i,i}getBrowserPosition(e){let t="u"<typeof navigator?void 0:navigator.geolocation;return t?new Promise((r,i)=>{t.getCurrentPosition(r,i,{...e,maximumAge:0})}):Promise.reject(Error("Geolocation is not available in the current browser"))}toBrowserLocation(e){return{...or(e.coords.longitude,e.coords.latitude),wgs84:{latitude:e.coords.latitude,longitude:e.coords.longitude},accuracy:e.coords.accuracy??0,altitude:e.coords.altitude??void 0,altitudeAccuracy:e.coords.altitudeAccuracy??void 0,heading:e.coords.heading??void 0,source:"browser",speed:e.coords.speed??0,timestamp:e.timestamp||Date.now()}}handleBrowserError(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.revision,r=e&&"object"==typeof e&&"code"in e&&"number"==typeof e.code?e.code:void 0,i=1===r?"denied":"unknown",n=function(e){switch(e&&"object"==typeof e&&"code"in e&&"number"==typeof e.code?e.code:void 0){case 1:return"浏览器或系统已拒绝定位权限,请允许位置访问后重试,或手动配置坐标";case 2:return"暂时无法获取浏览器位置,请检查设备定位服务后重试";case 3:return"获取浏览器位置超时,请重试";default:return e instanceof Error&&e.message.includes("not available")?"当前浏览器不支持定位,请手动配置坐标":"获取浏览器位置失败,请重试"}}(e),a={code:r,message:n,status:"browser_unauthorized"};return console.error("Browser geolocation failed",e),t===this.revision&&(this.browserAuthorization=i,this.browserLocation=void 0,this.updateSnapshot({browserAuthorization:i,errorMessage:n,latitude:void 0,longitude:void 0,message:1===r?"定位权限已拒绝(浏览器或系统)":"定位失败",source:"browser",tone:"error",updatedAtMs:Date.now()}),this.updatesActive&&(this.emitLocation(a),1===r&&this.stopLocationUpdates())),a}createBrowserUnauthorizedResult(){return{code:1,message:this.snapshot.errorMessage||"浏览器未授权定位,请在模拟器顶部“设置 → 定位”配置位置",status:"browser_unauthorized"}}startBrowserWatch(e){this.clearBrowserWatch();let t=++this.watchRevision,r="u"<typeof navigator?void 0:navigator.geolocation;r?this.browserWatchId=r.watchPosition(e=>{if(t!==this.watchRevision||!this.updatesActive)return;let r=this.toBrowserLocation(e);this.browserAuthorization="granted",this.browserLocation=r,this.updateSnapshot({browserAuthorization:"granted",errorMessage:void 0,latitude:r.latitude,longitude:r.longitude,message:"已配置(浏览器定位)",source:"browser",tone:"success",updatedAtMs:Date.now()}),this.emitLocation({location:r,status:"success"})},e=>{t===this.watchRevision&&this.updatesActive&&this.handleBrowserError(e)},e):this.handleBrowserError(Error("Geolocation is not available in the current browser"))}clearBrowserWatch(){if(this.watchRevision+=1,void 0===this.browserWatchId)return;let e="u"<typeof navigator?void 0:navigator.geolocation;null==e||e.clearWatch(this.browserWatchId),this.browserWatchId=void 0}updateSnapshot(e){this.snapshot={...this.snapshot,...e,browserAuthorization:this.browserAuthorization,userAuthorization:this.userAuthorization},this.emitSnapshot()}emitSnapshot(){for(let e of this.snapshotListeners)e()}emitLocation(e){for(let t of("success"===e.status&&"wgs84"===this.updateCoordinateType&&e.location.wgs84&&(e={status:"success",location:{...e.location,...e.location.wgs84}}),this.locationListeners))t(e)}},on="location_api_not_implemented";function oa(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{enableHighAccuracy:0!==e.mode,maximumAge:0,timeout:"number"==typeof e.timeoutMs&&Number.isFinite(e.timeoutMs)&&e.timeoutMs>0?e.timeoutMs:3e4}}function os(e,t,r,i){let n=S(e,r,t);return n.params.data={errMsg:r,...void 0===i?{}:{errCode:i}},n}function oo(e,t){let r="user_unauthorized"===t.status,i=!r&&1===t.code;if(r||i){let t=r?107:106;return os(e,t,r?"user permission denied":"system permission denied",t)}let n=3===t.code;return os(e,n?115:102,n?"location_timeout":"location_fail",n?115:102)}function ol(e){return e.getSystem().locationEnabled?e.getBeacon().locationAuthorized?void 0:"location_permission_denied":"location_service_disabled"}async function od(e,t,r,i){var n;let a=await sJ({appId:(null==r||null==(n=r.navigation)?void 0:n.getPackageInfo().appId)??e.appId,appIcon:e.appIcon,appName:e.appName,presenter:e.showSimulatorPermission,scope:"scope.userLocation",skipDialogIfDenied:!0,signal:i});return(null==i?void 0:i.aborted)||t.updateUserAuthorization(a),a}let ou=new Set,oc=new WeakSet,op=0;function oh(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL,t=e.getNetwork();return{isConnected:"none"!==t.networkType,networkType:t.networkType,signalStrength:"wifi"===t.networkType?t.signalStrength:void 0,hasSystemProxy:t.hasSystemProxy,weakNet:"wifi"===t.networkType?t.signalStrength<=-80:void 0}}function om(){return{timestamp:performance.now()/1e3,wallTime:Date.now()/1e3}}function og(e){for(let t of ou)try{t(e)}catch(e){console.error("Failed to record doubao.request in Chrome DevTools",e)}}function of(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nL,i=oh(r),n=(null==e||null==(t=e.globalProps)?void 0:t.os)==="iOS";return{networkType:i.networkType,networkAvailable:i.isConnected,...n?{}:{signalStrength:i.signalStrength,weakNet:i.weakNet},hasSystemProxy:i.hasSystemProxy??!1}}r(13546);let ov="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",oy=new Uint8Array(256);for(let e=0;e<ov.length;e++)oy[ov.charCodeAt(e)]=e;function ob(e){let t=new Uint8Array(e),r=t.length,i="";for(let e=0;e<r;e+=3)i+=ov[t[e]>>2],i+=ov[(3&t[e])<<4|t[e+1]>>4],i+=ov[(15&t[e+1])<<2|t[e+2]>>6],i+=ov[63&t[e+2]];return r%3==2?i=`${i.substring(0,i.length-1)}=`:r%3==1&&(i=`${i.substring(0,i.length-2)}==`),i}let ow="doubao.onRecorderStateChange",o_=0,oS=new Set([8e3,11025,12e3,16e3,22050,24e3,32e3,44100,48e3]),ox=`class CaptureProcessor extends AudioWorkletProcessor {
|
|
24
24
|
process(inputs) {
|
|
25
25
|
if (inputs[0]?.length) this.port.postMessage(inputs[0].map(channel => channel.slice()));
|
|
26
26
|
return true;
|
|
27
27
|
}
|
|
28
28
|
}
|
|
29
|
-
registerProcessor('doubao-recorder', CaptureProcessor);`;function oI(){var e;return"function"==typeof(null==(e=navigator.mediaDevices)?void 0:e.getUserMedia)&&("function"==typeof AudioContext&&"function"==typeof AudioWorkletNode||"function"==typeof MediaRecorder&&["audio/mp4;codecs=mp4a.40.2","audio/aac"].some(e=>MediaRecorder.isTypeSupported(e)))}class ok{context;stream;audio;processor;recorder;timer;unregister;destroyed=!1;state="starting";elapsed=0;startedAt=0;chunks=[];encodedChunks=[];frame=new Uint8Array;options;constructor(e,t){var r;this.context=t,this.options=function(e){let t={duration:6e4,format:"aac",sampleRate:44100,numberOfChannels:1,encodeBitRate:128e3,frameSize:0,...e};if(!Number.isInteger(t.duration)||t.duration<1||t.duration>6e5||!["aac","pcm","wav"].includes(t.format)||!oS.has(t.sampleRate)||![1,2].includes(t.numberOfChannels)||!Number.isInteger(t.encodeBitRate)||t.encodeBitRate<1||!Number.isInteger(t.frameSize)||t.frameSize<0||t.frameSize>4096)throw new w("invalid recorder options",104);return t}(e),this.unregister=null==t||null==(r=t.events)?void 0:r.onDestroy(()=>this.destroy())}emit(e){var t,r,i;this.destroyed||((null==(t=this.context)?void 0:t.events)?this.context.events.emitPrivate(ow,e):null==(i=this.context)||null==(r=i.emitEvent)||r.call(i,ow,e))}async start(){if(this.destroyed)throw new w("recording view was closed",114);try{let{sampleRate:e,numberOfChannels:t,encodeBitRate:r,frameSize:i,format:n}=this.options,a="aac"!==n||i>0,s=a||"function"!=typeof MediaRecorder?void 0:["audio/mp4;codecs=mp4a.40.2","audio/aac"].find(e=>MediaRecorder.isTypeSupported(e));if(!a&&!s)throw Error("AAC recording is unavailable in this browser; use format wav");if(a&&("function"!=typeof AudioContext||"function"!=typeof AudioWorkletNode))throw Error("PCM recording is unavailable in this browser");if(this.stream=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:e,channelCount:t}}),this.destroyed)throw this.release(),Error("Recording view was closed");if(a){this.audio=new AudioContext({sampleRate:e});let t=URL.createObjectURL(new Blob([ox],{type:"text/javascript"}));try{await this.audio.audioWorklet.addModule(t)}finally{URL.revokeObjectURL(t)}if(this.destroyed)throw Error("Recording view was closed");this.processor=new AudioWorkletNode(this.audio,"doubao-recorder"),this.processor.port.onmessage=e=>this.capture(e.data),this.audio.createMediaStreamSource(this.stream).connect(this.processor),this.processor.connect(this.audio.destination),await this.audio.resume()}else this.recorder=new MediaRecorder(this.stream,{mimeType:s,audioBitsPerSecond:r}),this.recorder.ondataavailable=e=>{e.data.size&&this.encodedChunks.push(e.data)},this.recorder.onerror=()=>{this.emit({state:"error",errMsg:"Audio recording failed"}),this.destroy()},this.recorder.start();if(this.destroyed)throw Error("Recording view was closed");this.state="recording",this.startedAt=Date.now(),this.scheduleStop(),this.emit({state:"start"})}catch(e){throw this.destroy(),e}}capture(e){var t;if("recording"!==this.state||!(null==(t=e[0])?void 0:t.length))return;let r=this.options.numberOfChannels,i=new Uint8Array(e[0].length*r*2),n=new DataView(i.buffer);for(let t=0;t<e[0].length;t++)for(let i=0;i<r;i++){let a=Math.max(-1,Math.min(1,(e[i]??e[0])[t]));n.setInt16((t*r+i)*2,a*(a<0?32768:32767),!0)}if(this.chunks.push(i),!this.options.frameSize)return;let a=new Uint8Array(this.frame.length+i.length);a.set(this.frame),a.set(i,this.frame.length);let s=1024*this.options.frameSize,o=0;for(;a.length-o>=s;)this.emit({state:"frameRecorded",frameBuffer:ob(a.slice(o,o+s).buffer),isLastFrame:!1}),o+=s;this.frame=a.slice(o)}scheduleStop(){this.timer=setTimeout(()=>{this.stop().catch(e=>{this.emit({state:"error",errMsg:String(e)}),this.destroy()})},Math.max(0,this.options.duration-this.elapsed))}pause(){var e;if("recording"!==this.state)throw new w("recorder is not recording",104);this.elapsed+=Date.now()-this.startedAt,void 0!==this.timer&&clearTimeout(this.timer),null==(e=this.recorder)||e.pause(),this.state="paused",this.emit({state:"pause"})}resume(){var e;if("paused"!==this.state)throw new w("recorder is not paused",104);null==(e=this.recorder)||e.resume(),this.state="recording",this.startedAt=Date.now(),this.scheduleStop(),this.emit({state:"resume"})}async stop(){if("recording"!==this.state&&"paused"!==this.state)throw new w("recorder is not started",104);"recording"===this.state&&(this.elapsed+=Date.now()-this.startedAt),this.state="stopped",void 0!==this.timer&&clearTimeout(this.timer);try{let e;this.recorder&&await new Promise(e=>{this.recorder.onstop=()=>e(),this.recorder.stop()});let t="wav";if(this.recorder){let r=new Blob(this.encodedChunks,{type:this.recorder.mimeType});e=new Uint8Array(await r.arrayBuffer()),t=this.recorder.mimeType.includes("audio/aac")?"aac":"m4a"}else e=function(e,t,r){let i=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(44+i),a=new DataView(n.buffer);for(let[e,t]of[[0,"RIFF"],[8,"WAVE"],[12,"fmt "],[36,"data"]])for(let r=0;r<t.length;r++)n[e+r]=t.charCodeAt(r);a.setUint32(4,i+36,!0),a.setUint32(16,16,!0),a.setUint16(20,1,!0),a.setUint16(22,r,!0),a.setUint32(24,t,!0),a.setUint32(28,t*r*2,!0),a.setUint16(32,2*r,!0),a.setUint16(34,16,!0),a.setUint32(40,i,!0);let s=44;for(let t of e)n.set(t,s),s+=t.length;return n}(this.chunks,this.audio.sampleRate,this.options.numberOfChannels);if(this.destroyed)return;let r=`appletfile://temp/recording-${Date.now()}-${++o_}.${t}`;await rH(r,e,this.context),this.options.frameSize&&this.emit({state:"frameRecorded",frameBuffer:ob(this.frame.slice().buffer),isLastFrame:!0}),this.emit({state:"stop",tempFilePath:r,duration:this.elapsed,fileSize:e.byteLength})}finally{this.destroy()}}release(){var e;void 0!==this.timer&&clearTimeout(this.timer),this.processor&&(this.processor.port.onmessage=null,this.processor.disconnect()),null==(e=this.stream)||e.getTracks().forEach(e=>e.stop()),this.audio&&"closed"!==this.audio.state&&this.audio.close().catch(()=>{})}destroy(){var e,t,r;this.destroyed||(this.destroyed=!0,null==(e=this.unregister)||e.call(this),(null==(t=this.recorder)?void 0:t.state)!=="inactive"&&(null==(r=this.recorder)||r.stop()),this.release())}}let oC=new Set,oE=new Set(["scope.userLocation","scope.userFuzzyLocation","scope.userLocationBackground","scope.record","scope.bluetooth","scope.camera","scope.addPhoneContact","scope.addPhoneCalendar"]);function oN(e){let t=nL.getSystem();if(oi.isLocationScope(e)){if("denied"===oi.getSnapshot().browserAuthorization)return!0;let r=t.locationAuthorization??(nL.getBeacon().locationAuthorized?"foreground precise":"denied");return!(r.startsWith("foreground ")||r.startsWith("background "))||"scope.userLocationBackground"===e&&!r.startsWith("background ")||"scope.userLocation"===e&&!r.endsWith("precise")}let r="scope.record"===e?t.microphone:"scope.camera"===e?t.camera:"scope.addPhoneCalendar"===e?t.phoneCalendar:"scope.addPhoneContact"===e?t.contacts:void 0;return"denied"===r||"restricted"===r||"read only"===r||"scope.bluetooth"===e&&!nL.getBluetooth().authorized}async function oT(e,t,r,i,n){var a;let s=await sJ({appId:(null==i||null==(a=i.navigation)?void 0:a.getPackageInfo().appId)??e.appId,appIcon:e.appIcon,appName:e.appName,presenter:e.showSimulatorPermission,scope:t,skipDialogIfDenied:r,signal:n});return!(null==n?void 0:n.aborted)&&oi.isLocationScope(t)&&oi.updateUserAuthorization(s),s}let oA="app_id_missing",oM="cashier_unavailable",oR="create_order_failed",oj="developer_order_exists",oP="login_credential_invalid",oL="login_credential_missing",oO="login_authorization_failed",oD="login_authorization_unsupported",oU="login_state_invalid",oq="login_session_unavailable",o$="payment_amount_invalid",oB="payment_authorization_invalid",oF="payment_cancelled",oz="payment_data_invalid",oW="payment_data_missing",oH="payment_data_unavailable",oV="payment_data_unavailable_with_sign",oG="payment_data_unsupported",oJ="payment_failed",oK="payment_method_unavailable",oZ="payment_order_invalid",oX="payment_parameter_missing",oY="payment_params_invalid",oQ="payment_params_unavailable",o0="payment_sign_params_invalid",o1="payment_sign_params_unavailable",o2="payment_incomplete",o3="privacy_state_unavailable",o4="privacy_authorization_failed",o5="pre_order_failed",o6="phone_authorization_failed",o8="request_format_invalid",o9="request_params_invalid",o7="sandbox_resource_not_found",le="sandbox_service_unavailable",lt="sandbox_session_expired",lr="sandbox_session_forbidden",li="sign_order_failed",ln="sign_order_already_exists",la="sign_order_not_found",ls="sign_order_params_invalid",lo="sign_order_status_invalid",ll="sign_order_create_failed",ld="sign_page_params_invalid",lu="sign_page_unavailable",lc="sign_page_data_unavailable",lp="请求暂时无法完成,请稍后重试;如持续失败,请提供 log_id";function lh(e,t){return!t||e.includes(t)?e:`${e}(log_id: ${t})`}class lm extends Error{code;details;logId;constructor(e,t={},r){super(lb(e,t,r)),this.code=e,this.details=t,this.logId=r,this.name="SandboxError"}}class lg extends Error{remoteCode;options;constructor(e,t,r={}){super(t),this.remoteCode=e,this.options=r,this.name="SandboxRemoteError"}}let lf={[oA]:"当前未配置应用 ID,请先完成应用配置。",[oM]:"无法打开模拟器收银台,请刷新模拟器后重试。",[oR]:"暂时无法创建订单,请检查签名参数后稍后重试;如持续失败,请提供 log_id",[oj]:"开发者订单号已存在,请查询原订单",[oP]:"登录失败:登录凭证已过期或已使用,请重新发起登录。",[oL]:"登录失败:成功登录回调未携带业务登录凭证,请检查登录实现。",[oO]:"暂时无法完成登录授权,请重新发起授权",[oD]:"当前 Sandbox 无法完成该授权请求,请检查授权方式和会话配置",[oU]:"用户登录状态已失效,请重新登录",[oq]:"登录失败:模拟器会话不可用,请登录开发者账号后重新打开模拟器。",[o$]:"支付金额无效,请使用最小货币单位的整数,并由业务服务端生成金额。",[oB]:"支付授权校验失败,请确认 data 和 dbAuthorization 使用同一个 dev.key 生成,并且模拟器配置了匹配的 dev.csr。",[oF]:"已取消支付。",[oz]:"支付数据格式无效,请检查业务服务端生成的 pay_data。",[oH]:"无法打开收银台:模拟器未返回支付数据,请检查订单状态和预下单响应。",[oV]:"无法打开支付签约收银台:模拟器未返回支付数据,请检查签约参数和订单状态。",[oG]:"当前支付数据不支持模拟器收银台,请检查模拟器支付配置。",[oJ]:lp,[oK]:"支付数据中没有可用的支付方式,请检查模拟器支付配置。",[oZ]:"订单不存在或不属于当前应用",[oY]:"请求参数不正确,请检查订单信息和金额",[oQ]:"暂时无法获取支付参数,请检查订单号后重试;如持续失败,请提供 log_id",[o0]:"请求参数不正确,请检查订单号和签约信息",[o1]:"暂时无法获取支付参数,请稍后重试;如持续失败,请提供 log_id",[o2]:"模拟支付未完成,请检查支付方式和订单状态后重试;如持续失败,请提供 log_id",[o3]:"暂时无法读取或保存授权状态,请稍后重试",[o4]:"隐私授权失败:请刷新模拟器后重试。",[o5]:"预下单失败:模拟器未返回订单 ID,请检查业务服务端预下单响应。",[o6]:"手机号授权失败:无法获取手机号授权凭证,请重试或使用其他登录方式。",[o8]:"请求格式不正确,请检查后重试",[o9]:"请求参数不正确,请检查必填字段和字段格式",[o7]:"未找到沙箱会话或相关资源,请重新创建后重试",[le]:"沙箱服务暂时不可用,请稍后重试;如持续失败,请提供 log_id",[lt]:"沙箱会话已过期,请重新启动调试会话",[lr]:"当前沙箱会话无权访问该应用,请检查应用和会话是否匹配",[li]:"创建签约订单失败:模拟器未返回签约订单 ID,请检查签约参数。",[ln]:"开发者签约单号已存在,请查询原签约单",[la]:"签约单不存在或不属于当前应用",[ls]:"签约单参数无效,请检查单号、应用和有效期",[lo]:"当前签约单状态不允许继续签约",[ll]:"暂时无法创建签约单,请检查签名参数后重试;如持续失败,请提供 log_id",[ld]:"签约单参数无效,请检查单号、应用和有效期",[lu]:"暂时无法获取签约页,请稍后重试;如持续失败,请提供 log_id",[lc]:"打开签约页面失败:模拟器未返回签约数据,请检查签约订单状态。"},lv={id:"支付方式 ID",name:"支付方式名称",pay_order_no:"支付订单号",pay_status:"支付状态",trade_no:"交易号"},ly={data:"业务服务端生成的 data",dbAuthorization:"业务服务端生成的 dbAuthorization",orderId:"requestOrder 返回的 orderId",signData:"业务服务端生成的 signData",signDbAuthorization:"业务服务端生成的 signDbAuthorization"};function lb(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;return lh(function(e,t){if(e===oW){let e=t.field?lv[t.field]:"必要字段";return`支付数据缺少${e},请检查业务服务端生成的 pay_data。`}if(e===oX){let e=t.key?ly[t.key]:"该参数";return`缺少支付参数,请提供${e}。`}return lf[e]}(e,t),r)}function lw(e){if("number"==typeof e&&Number.isInteger(e))return e;if("string"==typeof e&&e.trim()){let t=Number(e);return Number.isInteger(t)?t:void 0}}let l_={400:o9,401:lt,403:lr,404:o7,500:le};function lS(e,t){return 400===t?o8:void 0===e?void 0:l_[e]}let lx={[oV]:o0,[li]:ls,[lc]:ld},lI={[o5]:oR,[oV]:o1,[li]:ll,[lc]:lu};function lk(e,t,r){switch(e){case 500:return"payment"===r?o2:le;case 4201:return oB;case 0x1dcd6501:return lx[t]??oY;case 0x1dcdb322:return oj;case 5e8:return lI[t]??oQ;case 0x1dcdb325:return t===lc?la:oZ;case 0x1dcdb327:return ln;case 0x1dcdb328:return lo;default:return void 0===e||0===e?t:oJ}}let lC={[-1]:oq,4001:oP,2001:o4,502:oO,402:oU,501:o3,400:o9};function lE(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if("code"===r.errorField){let t=lS(e,r.httpStatus);if(t)return t}return"data.error_code"===r.errorField&&40001===e?oD:"err_code"===r.errorField&&401===e?o9:1001===e?"phone"===t?o6:oP:void 0===e?le:lC[e]??le}function lN(e,t){return e instanceof lm?e:e instanceof lg?new lm(lE(e.remoteCode,t,e.options),{},e.options.logId):new lm(le)}function lT(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:lp,r=arguments.length>2?arguments[2]:void 0;if(e instanceof lm)return lb(e.code,e.details,e.logId??r);if(e instanceof lg){let t="code"===e.options.errorField?lS(e.remoteCode,e.options.httpStatus):void 0,i=lk(e.remoteCode,oJ,e.options.operation);return lb(e.options.operation?i:t??i,{},e.options.logId??r)}return lh(t,r)}function lA(e,t){let r=e.err_code;if(r)throw new lm(lE(r,t,{errorField:"err_code"}),{},e.log_id)}function lM(e){return!e||"object"!=typeof e||Array.isArray(e)?{}:{code:lw(e.code),logId:"string"==typeof e.log_id?e.log_id:void 0}}function lR(e,t){let{code:r,logId:i}=lM(e);if(r)throw new lg(r,`Sandbox 请求失败,错误码为 ${String(r)}。`,{errorField:"code",httpStatus:t,logId:i})}let lj="web-sdk-debugger",lP=[{id:"douyin",name:"抖音支付"}];async function lL(e){let t=await fetch("/__web_sdk_sandbox_proxy__",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),r=await t.json().catch(()=>({})),{code:i,logId:n}=lM(r);if(!t.ok)throw new lg(i,`Sandbox 代理请求失败,HTTP 状态码为 ${t.status}。`,{errorField:"code",httpStatus:t.status,logId:n});return lR(r,t.status),r}let lO=new class{request=()=>{throw Error("FlowAppDeveloperOpenGatewayService.request is undefined")};baseURL="";constructor(e){this.request=(null==e?void 0:e.request)||this.request,this.baseURL=(null==e?void 0:e.baseURL)||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}FetchPackageDownLoadInfo(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.verson_tag}/packet`);return this.request({url:r,method:"POST"},t)}GetArtifactStatus(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.verson_tag}/artifact`);return this.request({url:r,method:"POST"},t)}GetUserBasicInfo(e,t){let r=e||{},i=this.genBaseURL("/app_developer/api/user/basic"),n={user_name:r.user_name,user_id:r.user_id};return this.request({url:i,method:"GET",params:n},t)}GetConfigRoleList(e,t){let r=this.genBaseURL("/app_developer/api/config/role/role_list");return this.request({url:r,method:"GET"},t)}RoleListByAppid(e,t){let r=this.genBaseURL("/app_developer/api/user/role/role_list");return this.request({url:r,method:"GET"},t)}UpdateUserName(e,t){let r=this.genBaseURL("/app_developer/api/user/basic/update_user_name"),i={user_name:e.user_name};return this.request({url:r,method:"PUT",data:i},t)}GetInviteMemberList(e,t){let r=e||{},i=this.genBaseURL("/app_developer/api/member/member_list"),n={app_key:r.app_key,user_name:r.user_name,page_size:r.page_size,page_num:r.page_num};return this.request({url:i,method:"GET",params:n},t)}SendInviteMember(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/member/invite/send_invite`),i={role_code:e.role_code,target_user_id:e.target_user_id};return this.request({url:r,method:"POST",data:i},t)}UpdateAppMeta(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/meta/update`),i={app_name:e.app_name,description:e.description,privacy_agreement:e.privacy_agreement,icon_url:e.icon_url,extra:e.extra,app_type:e.app_type,login_text:e.login_text};return this.request({url:r,method:"POST",data:i},t)}SubmitRelease(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/release`);return this.request({url:r,method:"POST"},t)}ActivateDeviceCode(e,t){let r=this.genBaseURL("/app_developer/oauth/device/activate"),i={user_code:e.user_code,client_name:e.client_name};return this.request({url:r,method:"POST",data:i},t)}GetPlatformCert(e,t){let r=this.genBaseURL("/app_developer/api/platform/cert");return this.request({url:r,method:"GET"},t)}UploadCsr(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/upload_csr`),i={csr_pem:e.csr_pem};return this.request({url:r,method:"POST",data:i},t)}GetAppCert(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/cert`);return this.request({url:r,method:"GET"},t)}CreateApp(e,t){let r=this.genBaseURL("/app_developer/api/apps"),i={app_name:e.app_name,description:e.description,privacy_agreement:e.privacy_agreement,icon_url:e.icon_url,extra:e.extra,app_type:e.app_type,login_text:e.login_text};return this.request({url:r,method:"POST",data:i},t)}UploadIcon(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/upload_icon`);return this.request({url:r,method:"POST"},t)}SubmitAudit(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/submit_audit`);return this.request({url:r,method:"POST"},t)}IssueDeviceCode(e,t){let r=this.genBaseURL("/app_developer/oauth/device/code"),i={client_name:e.client_name};return this.request({url:r,method:"POST",data:i},t)}GetAppWhitelist(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/whitelist`),i={offset:e.offset,limit:e.limit,keyword:e.keyword};return this.request({url:r,method:"GET",params:i},t)}UpdateAppWhitelist(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/whitelist`),i={action:e.action,subject:e.subject};return this.request({url:r,method:"POST",data:i},t)}ExchangeDeviceToken(e,t){let r=this.genBaseURL("/app_developer/oauth/token"),i={device_code:e.device_code};return this.request({url:r,method:"POST",data:i},t)}ListApps(e,t){let r=e||{},i=this.genBaseURL("/app_developer/api/apps"),n={app_limit:r.app_limit,app_offset:r.app_offset,key_word:r.key_word,app_key:r.app_key};return this.request({url:i,method:"GET",params:n},t)}GetAppMeta(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/meta`),i={limit:e.limit,offset:e.offset,status:e.status};return this.request({url:r,method:"GET",params:i},t)}ToolList(e,t){let r=this.genBaseURL("/developer/api/tools/list"),i={mcp_server_url:e.mcp_server_url,mcp_config:e.mcp_config};return this.request({url:r,method:"GET",params:i},t)}GetMiniAppVersionArtifact(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/artifact`);return this.request({url:r,method:"GET"},t)}UploadMiniAppVersionDraftPackage(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/draft/upload`),i={source_type:e.source_type};return this.request({url:r,method:"POST",params:i},t)}SubmitMiniAppVersionDraft(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/draft/submit`),i={project_config_version:e.project_config_version,app_version_tag:e.app_version_tag};return this.request({url:r,method:"POST",data:i},t)}ListMiniAppVersions(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions`),i={page:e.page,page_size:e.page_size,id:e.id};return this.request({url:r,method:"GET",params:i},t)}VerifyYAML(e,t){let r=this.genBaseURL("/app_developer/api/yaml/verify"),i={yaml:e.yaml,mode:e.mode,yaml_type:e.yaml_type};return this.request({url:r,method:"POST",data:i},t)}GetMiniAppVersionYAML(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/manifest`);return this.request({url:r,method:"GET"},t)}GetMiniAppVersionStructuredManifest(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/manifest_struct`);return this.request({url:r,method:"GET"},t)}QrcodeInfo(e,t){let r=this.genBaseURL("/app_developer/resource_api/package/qrcode_info"),i={app_key:e.app_key};return this.request({url:r,method:"POST",data:i},t)}GetMiniAppVersionDraftPackageDownloadURL(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/download_url`),i={source_type_list:e.source_type_list};return this.request({url:r,method:"GET",params:i},t)}GetSubMerchantList(e,t){let r=this.genBaseURL("/app_developer/api/trade/user/get_sub_merchant_list"),i={org_id:e.org_id};return this.request({url:r,method:"GET",params:i},t)}AppBindSubMerchant(e,t){let r=this.genBaseURL(`/app_developer/api/trade/apps/${e.app_key}/app_bind_sub_merchant`),i={sub_merchant_uid:e.sub_merchant_uid,org_id:e.org_id};return this.request({url:r,method:"PUT",data:i},t)}CreateSubMerchant(e,t){let r=this.genBaseURL("/app_developer/api/trade/user/create_sub_merchant"),i={org_id:e.org_id,sub_merchant_name:e.sub_merchant_name};return this.request({url:r,method:"POST",data:i},t)}UnBindSubMerchant(e,t){let r=this.genBaseURL(`/app_developer/api/trade/apps/${e.app_key}/unbind_sub_merchant`),i={sub_merchant_uid:e.sub_merchant_uid,org_id:e.org_id};return this.request({url:r,method:"POST",data:i},t)}GetSubMerchantCaijingUrl(e,t){let r=this.genBaseURL("/app_developer/api/trade/user/get_sub_merchant_url"),i={sub_merchant_uid:e.sub_merchant_uid};return this.request({url:r,method:"POST",data:i},t)}GetAppBindSubMerchants(e,t){let r=this.genBaseURL(`/app_developer/api/trade/apps/${e.app_key}/get_bind_sub_merchants`);return this.request({url:r,method:"GET"},t)}GetAppEventCallbackConf(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/events/get_callback_conf`),i={source:e.source};return this.request({url:r,method:"GET",params:i},t)}UpdateAppEventCallbackConf(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/events/update_callback_conf`),i={source:e.source,callback_address:e.callback_address};return this.request({url:r,method:"PUT",data:i},t)}CreateOrganization(e,t){let r=this.genBaseURL("/app_developer/api/organization"),i={name:e.name};return this.request({url:r,method:"POST",data:i},t)}UpdateOrganization(e,t){let r=this.genBaseURL(`/app_developer/api/organizations/${e.org_code}/update`),i={name:e.name};return this.request({url:r,method:"POST",data:i},t)}FinishMiniAppVersionDraftSourceCodeUploading(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/draft/source_code/upload/finish`),i={upload_token:e.upload_token,size:e.size,sha256:e.sha256};return this.request({url:r,method:"POST",data:i},t)}DeleteOrganization(e,t){let r=this.genBaseURL(`/app_developer/api/organizations/${e.org_code}/delete`);return this.request({url:r,method:"POST"},t)}GetOrganizationToken(e,t){let r=this.genBaseURL("/app_developer/api/organization/get_token"),i={org_code:e.org_code};return this.request({url:r,method:"POST",data:i},t)}StartMiniAppVersionDraftSourceCodeUploading(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/draft/source_code/upload/start`),i={sha256:e.sha256};return this.request({url:r,method:"POST",data:i},t)}ListOrganizations(e,t){let r=this.genBaseURL("/app_developer/api/organizations/list");return this.request({url:r,method:"GET"},t)}CreateAppDomainFile(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/file_create`),i={normalized_domain:e.normalized_domain,domain_category:e.domain_category};return this.request({url:r,method:"POST",data:i},t)}DeleteAppDomain(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/delete`),i={normalized_domain:e.normalized_domain,domain_category:e.domain_category};return this.request({url:r,method:"POST",data:i},t)}VerifyAppDomainFile(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/file_verify`),i={normalized_domain:e.normalized_domain,domain_category:e.domain_category};return this.request({url:r,method:"POST",data:i},t)}CreateAppDomain(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/create`),i={domain:e.domain,domain_category:e.domain_category};return this.request({url:r,method:"POST",data:i},t)}GetAppDomainList(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/list`);return this.request({url:r,method:"GET"},t)}SandboxGetAwemeCommonLoginInfo(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/auth/get_aweme_common_login_info"),i={app_key:e.app_key};return this.request({url:r,method:"POST",data:i},t)}SandboxUpdateMessageCardWidgetData(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/card/update_message_card_widget_data"),i={mixture_card_id:e.mixture_card_id,message_id:e.message_id,widget_id:e.widget_id,widget_data:e.widget_data};return this.request({url:r,method:"POST",data:i},t)}SandboxCreateSignOrder(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/create_sign_order"),i={data:e.data,db_authorization:e.db_authorization,app_key:e.app_key,message_id:e.message_id};return this.request({url:r,method:"POST",data:i},t)}SandboxGetOrderPaymentWithSign(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/get_order_payment_with_sign"),i={order_id:e.order_id,sign_data:e.sign_data,sign_db_authorization:e.sign_db_authorization,app_key:e.app_key,message_id:e.message_id,aweme_bind_status:e.aweme_bind_status};return this.request({url:r,method:"POST",data:i},t)}SandboxRequestOrder(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/request_order"),i={data:e.data,db_authorization:e.db_authorization,app_key:e.app_key,message_id:e.message_id};return this.request({url:r,method:"POST",data:i},t)}SandboxGetSignPageData(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/get_sign_page_data"),i={auth_order_id:e.auth_order_id,app_key:e.app_key,message_id:e.message_id,aweme_bind_status:e.aweme_bind_status};return this.request({url:r,method:"POST",data:i},t)}SandboxGetMessageInfoByMixtureCardID(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/card/get_message_info_by_mixture_card_id"),i={mixture_card_id:e.mixture_card_id};return this.request({url:r,method:"POST",data:i},t)}SandboxGetOrderPayment(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/get_order_payment"),i={order_id:e.order_id,app_key:e.app_key,platform_signed_pt_code:e.platform_signed_pt_code,message_id:e.message_id,aweme_bind_status:e.aweme_bind_status};return this.request({url:r,method:"POST",data:i},t)}SandboxApiGetUserAppsPermissionDetail(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/miniapp_permission/detail"),i={applets_list:e.applets_list};return this.request({url:r,method:"POST",data:i},t)}SandboxApiPostUserAppsPermission(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/miniapp_permission/post"),i={applet_id:e.applet_id,update_scope_info:e.update_scope_info,using_scope_infos:e.using_scope_infos};return this.request({url:r,method:"POST",data:i},t)}SandboxApiGetUserAppsPermissionRecord(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/miniapp_permission/record"),i={applet_id:e.applet_id};return this.request({url:r,method:"POST",data:i},t)}SandboxApiExchangeCode(e,t){let r=e||{},i=this.genBaseURL("/app_developer/api/sandbox/jsb/oauth/token"),n={app_key:r.app_key,code:r.code,device_id:r.device_id,version_tag:r.version_tag};return this.request({url:i,method:"POST",data:n},t)}SandboxApiGetPhoneMask(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/phone_mask");return this.request({url:r,method:"POST"},t)}SandboxApiCheckPrivacyOrLoginStatus(e,t){let r=e||{},i=this.genBaseURL("/app_developer/api/sandbox/jsb/user/privacy_login/check"),n={app_key:r.app_key,version_tag:r.version_tag,check_type:r.check_type};return this.request({url:i,method:"POST",data:n},t)}SandboxApiAcceptPrivacy(e,t){let r=e||{},i=this.genBaseURL("/app_developer/api/sandbox/jsb/user/privacy/accept"),n={app_key:r.app_key,request_id:r.request_id,device_id:r.device_id};return this.request({url:i,method:"POST",data:n},t)}SandboxApiDeleteDataObtainedByTicket(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/miniapp_permission/ticket_revoke"),i={applet_id:e.applet_id,scope_name:e.scope_name,permission_ticket_type:e.permission_ticket_type};return this.request({url:r,method:"POST",data:i},t)}ListPublicNoticeTemplates(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/public_notice_templates`),i={category:e.category,subscription_type:e.subscription_type,keyword:e.keyword,page_num:e.page_num,page_size:e.page_size};return this.request({url:r,method:"GET",params:i},t)}SandboxIssueLoginCode(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/passport/open/auth"),i={client_key:e.client_key,aid:e.aid,scope:e.scope,source:e.source,exchange_type:e.exchange_type};return this.request({url:r,method:"POST",data:i},t)}GetSandboxBusinessInfo(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/session/business_info/get"),i={sandbox_session_id:e.sandbox_session_id};return this.request({url:r,method:"POST",data:i},t)}UpdateSandboxBusinessInfo(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/session/business_info/update"),i={sandbox_session_id:e.sandbox_session_id,phone_num:e.phone_num,csr_pem:e.csr_pem,location_info:e.location_info};return this.request({url:r,method:"POST",data:i},t)}SandboxPay(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/payment/pay"),i={trade_no:e.trade_no,pay_type:e.pay_type};return this.request({url:r,method:"POST",data:i},t)}CheckDeveloperAccessWhitelist(e,t){let r=this.genBaseURL("/app_developer/api/user/whitelist/check"),i={invite_code:(e||{}).invite_code};return this.request({url:r,method:"POST",data:i},t)}OIDCGet(e,t){let r=this.genBaseURL("/app_developer/api/oidc_get");return this.request({url:r,method:"GET"},t)}OIDCCallback(e,t){let r=this.genBaseURL("/app_developer/api/oidc_callback"),i={code:e.code,nonce:e.nonce,state:e.state};return this.request({url:r,method:"GET",params:i},t)}AuditDetail(e,t){let r=this.genBaseURL("/app_developer/api/apps/audit/detail"),i={audit_id:e.audit_id,audit_type:e.audit_type};return this.request({url:r,method:"POST",data:i},t)}ListBusinessTemplates(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/business_templates`),i={biz_type:e.biz_type,status:e.status,sync_status:e.sync_status,page_num:e.page_num,page_size:e.page_size};return this.request({url:r,method:"GET",params:i},t)}GetBusinessTemplatesYaml(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/business_templates/yaml`),i={status:e.status};return this.request({url:r,method:"GET",params:i},t)}DeleteBusinessTemplate(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/business_templates/${e.biz_type}/${e.template_key}/delete`);return this.request({url:r,method:"POST"},t)}GetPublicNoticeTemplate(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/public_notice_templates/${e.public_template_key}`);return this.request({url:r,method:"GET"},t)}PullSandboxNotices(e,t){let r=e||{},i=this.genBaseURL("/app_developer/api/sandbox/resources/notices/pull"),n={notice_ids:r.notice_ids,cursor:r.cursor,limit:r.limit};return this.request({url:i,method:"POST",data:n},t)}RemoveSandboxTaskFromUser(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/resources/tasks/remove_from_user"),i={task_id:e.task_id};return this.request({url:r,method:"POST",data:i},t)}PullSandboxTasks(e,t){let r=e||{},i=this.genBaseURL("/app_developer/api/sandbox/resources/tasks/pull"),n={task_ids:r.task_ids,cursor:r.cursor,limit:r.limit};return this.request({url:i,method:"POST",data:n},t)}CreateSandboxSession(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/session/create"),i={sandbox_project_id:e.sandbox_project_id,app_id:e.app_id,bridge_origins:e.bridge_origins,manifest:e.manifest};return this.request({url:r,method:"POST",data:i},t)}PreviewTosFile(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/audit/tos/preview`),i={object_key:e.object_key};return this.request({url:r,method:"GET",params:i},t)}QrcodeShort(e,t){let r=this.genBaseURL("/app_developer/resource_api/package/qrcode_short"),i={url:e.url,ttl:e.ttl};return this.request({url:r,method:"POST",data:i},t)}GetQrcodeURL(e,t){let r=this.genBaseURL("/app_developer/resource_api/package/qrcode_url"),i={token:e.token};return this.request({url:r,method:"POST",data:i},t)}DownloadTosFile(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/audit/tos/download`),i={object_key:e.object_key};return this.request({url:r,method:"GET",params:i},t)}SandboxCallMcpTool(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/card/call_mcp_tool"),i={tool_name:e.tool_name,tool_args_json:e.tool_args_json,widget_instance_id:e.widget_instance_id,artifact_version_code:e.artifact_version_code,app_key:e.app_key,widget_id:e.widget_id,scene:e.scene,skip_widget_update:e.skip_widget_update};return this.request({url:r,method:"POST",data:i},t)}DeleteMember(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/member/delete`),i={user_id:e.user_id};return this.request({url:r,method:"POST",data:i},t)}SubmitSandboxEventReport(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/bridge/events/report"),i={event_id:e.event_id,data:e.data},n={"X-DBX-Sandbox-Session-ID":e["X-DBX-Sandbox-Session-ID"]};return this.request({url:r,method:"POST",data:i,headers:n},t)}UploadSimulatorImage(e,t){let r=this.genBaseURL("/app_developer/api/simulator/images/upload"),i={image:e.image};return this.request({url:r,method:"POST",data:i},t)}}({baseURL:"",request:lL});function lD(e,t){if(!e.data)throw Error(e.message||`${t} returned empty data`);return e.data}async function lU(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return lD(await lO.PullSandboxNotices(e),"PullSandboxNotices")}async function lq(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return lD(await lO.PullSandboxTasks(e),"PullSandboxTasks")}async function l$(e){return lD(await lO.RemoveSandboxTaskFromUser({task_id:e}),"RemoveSandboxTaskFromUser").removed_task}async function lB(e,t){return lL({data:{event_id:e,data:t},method:"POST",url:"/app_developer/api/sandbox/bridge/events/report"})}async function lF(e){let{appletId:t,granted:r,scopeName:i}=e;if(!t.trim())throw Error("appletId is required");if(!i.trim())throw Error("scopeName is required");let n=await lO.SandboxApiPostUserAppsPermission({applet_id:t,update_scope_info:{grant_status:r?1:2,scope_name:i}});if(0!==n.err_code)throw Error(n.err_msg||`Sandbox post Agentic Service permission failed with code ${String(n.err_code)}`)}async function lz(e){let{appKey:t,params:r,scene:i}=e;if(!t.trim())throw Error("callTool requires a simulator app context");if("widget"===i&&(!e.widgetId.trim()||!e.widgetInstanceId.trim()))throw Error("callTool requires a simulator conversation card context");let{skipWidgetUpdate:n,toolArgs:a,toolName:s}=function(e){if(!rP(e)||"string"!=typeof e.toolName||!e.toolName.trim()||!rP(e.toolArgs)||void 0!==e.skipWidgetUpdate&&"boolean"!=typeof e.skipWidgetUpdate)throw Error("callTool requires a non-empty toolName, an object toolArgs, and an optional boolean skipWidgetUpdate");return{skipWidgetUpdate:e.skipWidgetUpdate??!1,toolName:e.toolName.trim(),toolArgs:e.toolArgs}}(r),o=await lO.SandboxCallMcpTool({app_key:t,scene:"page"===i?2:1,skip_widget_update:n,tool_args_json:JSON.stringify(a),tool_name:s,..."widget"===i?{widget_id:e.widgetId,widget_instance_id:e.widgetInstanceId}:{}}),l=lw(o.err_code);if(void 0!==l&&0!==l)throw new lg(l,o.err_msg||`callTool failed with code ${l}`,{errorField:"err_code",logId:o.log_id});if(!o.result)throw Error(o.err_msg||"callTool returned an empty result");if(1!==o.result.output_kind&&2!==o.result.output_kind)throw Error("callTool returned an invalid output kind");let d=o.result.card_update_error,u=o.result.tool_error,c=o.result.tool_result_json,p=d?{cardUpdateError:{code:d.code,message:d.message,phase:"render"}}:{};if(u){let e=lw(u.code);if(void 0!==c||void 0===e||"string"!=typeof u.message||!u.message.trim())throw Error("callTool returned an invalid Tool error");return{toolError:{code:e,message:u.message},...p}}if(void 0===c)throw Error("callTool returned neither a Tool result nor a Tool error");return{toolResult:function(e){let t=JSON.parse(e);if(!rP(t))throw Error("callTool returned an invalid ToolResult");return t}(c),...p}}function lW(e){var t;let r=(null==(t=e.getAppId)?void 0:t.call(e))||e.appId;if(!r)throw new lm(oA);return r}function lH(e,t){var r;let i=null==e||null==(r=e[t])?void 0:r.trim();if(!i)throw new lm(oX,{key:t});return i}function lV(e,t,r){let i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=arguments.length>4?arguments[4]:void 0,a=lw(t.err_code),s=n?(n instanceof lg?n.remoteCode:void 0)??(void 0!==a&&0!==a?a:void 0)??-1:a??-1,o=(n instanceof lg?n.options.logId:void 0)??t.log_id,l=n?lT(n,lb(r),o):lb(lk(a,r),{},o),d={code:i?s:void 0,errNo:String(s),errMsg:l,errLogId:o};return{type:"callback",callbackId:e.callbackId,params:{code:0,data:d,errNo:s,errMsg:l,msg:l}}}async function lG(e,t){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];try{return await t()}catch(t){return lV(e,{},oJ,r,t)}}async function lJ(e,t){let r=function(e){let t;try{t=JSON.parse(e)}catch{throw new lm(oz)}if(!t||"object"!=typeof t||Array.isArray(t))throw new lm(oz);let r=t;if("sandbox_cashier"!==r.type)throw new lm(oG);let i="string"==typeof r.total_amount?r.total_amount.trim():"";if(!i||!/^\d+$/.test(i))throw new lm(o$);let n="string"==typeof r.pay_order_no?r.pay_order_no.trim():"",a="string"==typeof r.pay_status?r.pay_status.trim():"",s="string"==typeof r.trade_no?r.trade_no.trim():"";if(!n||!a||!s)throw new lm(oW,{field:n?a?"trade_no":"pay_status":"pay_order_no"});return{paymentTypes:function(e){if(!Array.isArray(e)||0===e.length)throw new lm(oK);let t=e.map(e=>{if(!rP(e))throw new lm(oz);let t="string"==typeof e.id?e.id.trim():"",r="string"==typeof e.name?e.name.trim():"";if(!t||!r)throw new lm(oW,{field:t?"name":"id"});return{id:t,name:r}});if(new Set(t.map(e=>{let{id:t}=e;return t})).size!==t.length)throw new lm(oz);return t}(r.pay_types??lP),payOrderNo:n,payStatus:a,totalAmount:i,tradeNo:s,type:"sandbox_cashier"}}(e);if(!t.showSandboxCashier)throw new lm(oM);if(!await t.showSandboxCashier(r,async e=>{if(!r.paymentTypes.some(t=>{let{id:r}=t;return r===e}))throw new lm(oK);try{await lO.SandboxPay({trade_no:r.tradeNo,pay_type:e})}catch(e){if(e instanceof lg&&"code"===e.options.errorField&&500===e.remoteCode)throw new lg(e.remoteCode,e.message,{...e.options,operation:"payment"});throw e}}))throw new lm(oF)}async function lK(e,t){let r,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"user_info",n=t?"phone":"login";try{r=await lO.SandboxIssueLoginCode({aid:"482431",client_key:lW(e),scope:i,source:"jsb",exchange_type:t})}catch(e){throw lN(e,n)}var a,s,o=lw(null==(a=r.data)?void 0:a.error_code),l=lM(r).logId;if(o)throw new lm(lE(o,n,{errorField:"data.error_code"}),{},l);let d=null==(s=r.data)?void 0:s.code;if(!d)throw new lm(le);return d}async function lZ(e){try{let t=void 0!==e.locationInfo,r=await lO.UpdateSandboxBusinessInfo({csr_pem:e.csrPem||(t?"":void 0),location_info:e.locationInfo,phone_num:e.phoneNum,sandbox_session_id:""});return lR(r),r}catch(r){let e=r instanceof lg?r.options.logId:r&&"object"==typeof r&&"logId"in r&&"string"==typeof r.logId?r.logId:void 0,t=Error(lh(r instanceof Error?r.message:String(r),e));throw t.logId=e,t}}async function lX(e){return lZ(e)}async function lY(e){return lZ({csrPem:"",locationInfo:e,phoneNum:""})}async function lQ(e){let t=await fetch("/__web_sdk_sandbox_session_recreate__",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),r=await t.json().catch(()=>({}));if(!t.ok)throw Error((null==r?void 0:r.message)||`Sandbox session recreate failed with status ${t.status}`);return r}let l0=["aztec","codabar","code_39","code_93","code_128","data_matrix","ean_8","ean_13","itf","pdf417","qr_code","upc_a","upc_e"],l1={barCode:["codabar","code_39","code_93","code_128","ean_8","ean_13","itf","upc_a","upc_e"],datamatrix:["data_matrix"],pdf417:["pdf417"],qrCode:["qr_code"]};async function l2(e){let t=e.getSupportedFormats;return"function"==typeof t?new Set(await t()):null}function l3(e){var t,r;return{characterSet:"UTF-8",path:"",rawData:(t=e.rawValue,"function"!=typeof btoa||"u"<typeof TextEncoder?t:btoa(String.fromCharCode(...new TextEncoder().encode(t)))),result:e.rawValue,scanType:(r=e.format,l0.includes(r)?"pdf417"===r?"PDF_417":r.toUpperCase():"QR_CODE")}}async function l4(e,t){if("function"==typeof createImageBitmap){let r=await createImageBitmap(t);try{return e.detect(r)}finally{r.close()}}let r=new Image,i=URL.createObjectURL(t);try{return await new Promise((e,t)=>{r.onload=()=>e(),r.onerror=()=>t(Error("Failed to load selected image")),r.src=i}),e.detect(r)}finally{URL.revokeObjectURL(i)}}function l5(e,t,r,i,n,a){return t()?Promise.resolve():new Promise((s,o)=>{let l=0,d=()=>{for(let t of(window.clearTimeout(l),r))e.removeEventListener(t,u);e.removeEventListener("error",c),null==a||a.removeEventListener("abort",c)},u=()=>{t()&&(d(),s())},c=()=>{d(),o(Error(n))};for(let t of(l=window.setTimeout(()=>{d(),o(Error(n))},i),r))e.addEventListener(t,u);e.addEventListener("error",c),null==a||a.addEventListener("abort",c,{once:!0}),(null==a?void 0:a.aborted)&&c()})}async function l6(e,t,r){e.srcObject=t,await l5(e,()=>e.readyState>=HTMLMediaElement.HAVE_METADATA,["loadedmetadata"],3e3,"Camera stream started, but video metadata was not loaded",r),await e.play(),await l5(e,()=>e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA,["loadeddata","canplay","playing"],3e3,"Camera stream started, but no video frame was rendered",r)}async function l8(e,t,r){var i;let n,a,s=globalThis.BarcodeDetector;if(!s)throw Error("BarcodeDetector is not supported in this browser");let o=await l2(s);if(null==r?void 0:r.aborted)throw Error("scanCode canceled");let l=[...new Set((null==(i=e.scanType)?void 0:i.length)?e.scanType.flatMap(e=>l1[e]):l0)].filter(e=>!o||o.has(e));if(0===l.length)throw Error("Requested scanType is not supported in this browser");let d=new s({formats:l}),u=!1,c=!1,p=0,h=null,m=null,g=()=>{null==h||h.getTracks().forEach(e=>e.stop()),h=null,m&&(m.srcObject=null)},f=()=>{u||(u=!0,a&&(null==r||r.removeEventListener("abort",a)),window.cancelAnimationFrame(p),g(),null==n||n.close())};try{return await new Promise((i,s)=>{let o=e=>{u||(f(),e())};a=()=>o(()=>s(Error("scanCode canceled"))),null==r||r.addEventListener("abort",a,{once:!0});let l=e=>{if(!u&&!c){if(!m||m.readyState<HTMLMediaElement.HAVE_CURRENT_DATA){e&&(null==n||n.setMessage("摄像头画面还未准备好"));return}c=!0,d.detect(m).then(t=>{let r=t[0];r?o(()=>i(l3(r))):e&&(null==n||n.setMessage("未识别到二维码或条形码"))}).catch(t=>{e&&(null==n||n.setMessage(t instanceof Error?t.message:String(t)))}).finally(()=>{c=!1})}};n=t({allowImageUpload:!e.onlyFromCamera,onCancel:()=>o(()=>s(Error("scanCode canceled"))),onCapture:()=>l(!0),onFile:e=>{u||(null==n||n.setMessage("正在识别图片..."),l4(d,e).then(e=>{let t=e[0];t?o(()=>i(l3(t))):null==n||n.setMessage("未识别到二维码或条形码,请换一张图片重试")}).catch(e=>{null==n||n.setMessage(e instanceof Error?e.message:String(e))}))},onVideoReady:t=>{var i;if(m||u)return;m=t;let a=nL.getSystem().camera;"denied"===a||"restricted"===a?e.onlyFromCamera?o(()=>s(Error("Camera permission denied by simulator settings"))):null==n||n.setMessage("模拟系统相机权限不可用,请从相册选择二维码或条形码图片"):(null==(i=navigator.mediaDevices)?void 0:i.getUserMedia)?navigator.mediaDevices.getUserMedia({audio:!1,video:{facingMode:{ideal:"environment"}}}).then(e=>u?void e.getTracks().forEach(e=>e.stop()):(h=e,l6(t,e,r))).then(()=>{if(u)return;let e=()=>{u||(l(!1),p=window.requestAnimationFrame(e))};e()}).catch(t=>{if(u)return;let r=t instanceof Error?t.message:String(t);if(g(),e.onlyFromCamera){null==n||n.setMessage(r),o(()=>s(t instanceof Error?t:Error(r)));return}null==n||n.setMessage(`无法使用摄像头,请从相册选择二维码或条形码图片:${r}`)}):e.onlyFromCamera?o(()=>s(Error("Camera is not available in this browser"))):null==n||n.setMessage("无法使用摄像头,请从相册选择二维码或条形码图片")}})})}catch(e){throw f(),e}}let l9=new class{hardware;overrides=new Map;listeners=new Set;captureListeners=new Set;snapshot={brightness:1,keepScreenOn:!1,screenRecordDisabled:!1};constructor(e=nL){this.hardware=e,this.updateSnapshot(),e.subscribe("screen",()=>this.updateSnapshot())}getSnapshot=()=>this.snapshot;subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));subscribeCapture=e=>(this.captureListeners.add(e),()=>this.captureListeners.delete(e));capture(){for(let e of this.captureListeners)e();return{protected:this.snapshot.screenRecordDisabled}}set(e,t){let r=this.overrides.get(e);this.overrides.delete(e),this.overrides.set(e,{...r,...t}),this.updateSnapshot()}release(e){this.overrides.delete(e),this.updateSnapshot()}updateSnapshot(){let e=this.hardware.getScreen().brightness,t=!1,r=!1;for(let i of this.overrides.values())i.background||(e=i.brightness??e),void 0!==i.keepScreenOn&&(t||=!i.background&&i.keepScreenOn),r=i.screenRecordDisabled??r;if(e!==this.snapshot.brightness||t!==this.snapshot.keepScreenOn||r!==this.snapshot.screenRecordDisabled)for(let i of(this.snapshot={brightness:e,keepScreenOn:t,screenRecordDisabled:r},this.listeners))i()}};function l7(e){var t,r;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nL,n={...e,packageInfo:(null==e?void 0:e.packageInfo)??(null==e||null==(r=e.navigation)||null==(t=r.getPackageInfo)?void 0:t.call(r)),globalProps:{...null==e?void 0:e.globalProps,appTheme:sn(i)}};return Object.fromEntries(["doubao.getSystemInfo","doubao.getAppBaseInfo"].map(e=>{let t=tg[e];return[e,"function"==typeof t.syncResult?t.syncResult(n):t.syncResult]}))}function de(e){return"not determined"===e?e:["denied","restricted","partial","read only"].includes(e)?"denied":"authorized"}function dt(e){var t,r;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nL,n=i.getBluetooth(),a=i.getWifi(),s=Number((null==e||null==(t=e.globalProps)?void 0:t.screenWidth)??window.innerWidth),o=Number((null==e||null==(r=e.globalProps)?void 0:r.screenHeight)??window.innerHeight);return{bluetoothEnabled:n.available&&n.enabled&&n.authorized,locationEnabled:i.getSystem().locationEnabled,wifiEnabled:a.available&&a.enabled,deviceOrientation:s>o?"landscape":"portrait"}}function dr(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nL,r=t.getSystem(),{camera:i,microphone:n,album:a,notification:s,phoneCalendar:o}=r,l=r.bluetoothAuthorization??(t.getBluetooth().authorized?"full":"denied"),d="denied"===oi.getSnapshot().browserAuthorization?"denied":r.locationAuthorization??(t.getBeacon().locationAuthorized?r.locationReducedAccuracy?"foreground approximate":"foreground precise":"denied"),u=d.startsWith("foreground ")||d.startsWith("background ");return{...r.healthData?{healthDataAuthorizationDetail:{readStatus:Object.entries(r.healthData.readStatus).map(e=>{let[t,r]=e;return{type:t,status:r}})}}:{},albumAuthorized:de(a),bluetoothAuthorized:de(l),cameraAuthorized:de(i),locationAuthorized:u?"authorized":de(d),locationReducedAccuracy:u&&d.endsWith("approximate"),microphoneAuthorized:de(n),notificationAuthorized:de(s),notificationAlertAuthorized:r.notificationAlert,notificationBadgeAuthorized:r.notificationBadge,notificationSoundAuthorized:r.notificationSound,phoneCalendarAuthorized:de(o),albumAuthorizationDetail:a,bluetoothAuthorizationDetail:l,cameraAuthorizationDetail:i,locationAuthorizationDetail:d,microphoneAuthorizationDetail:n,notificationAuthorizationDetail:s,phoneCalendarAuthorizationDetail:o}}function di(){throw Error("Simulator UI presenter is unavailable")}let dn="doubao-web-sdk-debugger-vibration-style",da="doubao-web-sdk-debugger-screen-vibrating",ds={heavy:4,light:1,medium:2},dl=0,dd=null;function du(e){e.classList.remove(da),e.style.removeProperty("--doubao-web-sdk-debugger-vibrate-distance"),e.style.removeProperty("--doubao-web-sdk-debugger-vibrate-duration")}function dc(e,t,r){if(!("function"==typeof navigator.vibrate&&navigator.vibrate(e)&&function(){let e=navigator.maxTouchPoints??0;if(e<=0)return!1;let t=navigator.platform??"",r=navigator.userAgent??"";return/android|iphone|ipad|ipod|mobile/i.test(`${t} ${r}`)||/mac/i.test(t)&&e>1}())){let i;(function(){if(document.getElementById(dn))return;let e=document.createElement("style");e.id=dn,e.textContent=`
|
|
29
|
+
registerProcessor('doubao-recorder', CaptureProcessor);`;function oI(){var e;return"function"==typeof(null==(e=navigator.mediaDevices)?void 0:e.getUserMedia)&&("function"==typeof AudioContext&&"function"==typeof AudioWorkletNode||"function"==typeof MediaRecorder&&["audio/mp4;codecs=mp4a.40.2","audio/aac"].some(e=>MediaRecorder.isTypeSupported(e)))}class ok{context;stream;audio;processor;recorder;timer;unregister;destroyed=!1;state="starting";elapsed=0;startedAt=0;chunks=[];encodedChunks=[];frame=new Uint8Array;options;constructor(e,t){var r;this.context=t,this.options=function(e){let t={duration:6e4,format:"aac",sampleRate:44100,numberOfChannels:1,encodeBitRate:128e3,frameSize:0,...e};if(!Number.isInteger(t.duration)||t.duration<1||t.duration>6e5||!["aac","pcm","wav"].includes(t.format)||!oS.has(t.sampleRate)||![1,2].includes(t.numberOfChannels)||!Number.isInteger(t.encodeBitRate)||t.encodeBitRate<1||!Number.isInteger(t.frameSize)||t.frameSize<0||t.frameSize>4096)throw new w("invalid recorder options",104);return t}(e),this.unregister=null==t||null==(r=t.events)?void 0:r.onDestroy(()=>this.destroy())}emit(e){var t,r,i;this.destroyed||((null==(t=this.context)?void 0:t.events)?this.context.events.emitPrivate(ow,e):null==(i=this.context)||null==(r=i.emitEvent)||r.call(i,ow,e))}async start(){if(this.destroyed)throw new w("recording view was closed",114);try{let{sampleRate:e,numberOfChannels:t,encodeBitRate:r,frameSize:i,format:n}=this.options,a="aac"!==n||i>0,s=a||"function"!=typeof MediaRecorder?void 0:["audio/mp4;codecs=mp4a.40.2","audio/aac"].find(e=>MediaRecorder.isTypeSupported(e));if(!a&&!s)throw Error("AAC recording is unavailable in this browser; use format wav");if(a&&("function"!=typeof AudioContext||"function"!=typeof AudioWorkletNode))throw Error("PCM recording is unavailable in this browser");if(this.stream=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:e,channelCount:t}}),this.destroyed)throw this.release(),Error("Recording view was closed");if(a){this.audio=new AudioContext({sampleRate:e});let t=URL.createObjectURL(new Blob([ox],{type:"text/javascript"}));try{await this.audio.audioWorklet.addModule(t)}finally{URL.revokeObjectURL(t)}if(this.destroyed)throw Error("Recording view was closed");this.processor=new AudioWorkletNode(this.audio,"doubao-recorder"),this.processor.port.onmessage=e=>this.capture(e.data),this.audio.createMediaStreamSource(this.stream).connect(this.processor),this.processor.connect(this.audio.destination),await this.audio.resume()}else this.recorder=new MediaRecorder(this.stream,{mimeType:s,audioBitsPerSecond:r}),this.recorder.ondataavailable=e=>{e.data.size&&this.encodedChunks.push(e.data)},this.recorder.onerror=()=>{this.emit({state:"error",errMsg:"Audio recording failed"}),this.destroy()},this.recorder.start();if(this.destroyed)throw Error("Recording view was closed");this.state="recording",this.startedAt=Date.now(),this.scheduleStop(),this.emit({state:"start"})}catch(e){throw this.destroy(),e}}capture(e){var t;if("recording"!==this.state||!(null==(t=e[0])?void 0:t.length))return;let r=this.options.numberOfChannels,i=new Uint8Array(e[0].length*r*2),n=new DataView(i.buffer);for(let t=0;t<e[0].length;t++)for(let i=0;i<r;i++){let a=Math.max(-1,Math.min(1,(e[i]??e[0])[t]));n.setInt16((t*r+i)*2,a*(a<0?32768:32767),!0)}if(this.chunks.push(i),!this.options.frameSize)return;let a=new Uint8Array(this.frame.length+i.length);a.set(this.frame),a.set(i,this.frame.length);let s=1024*this.options.frameSize,o=0;for(;a.length-o>=s;)this.emit({state:"frameRecorded",frameBuffer:ob(a.slice(o,o+s).buffer),isLastFrame:!1}),o+=s;this.frame=a.slice(o)}scheduleStop(){this.timer=setTimeout(()=>{this.stop().catch(e=>{this.emit({state:"error",errMsg:String(e)}),this.destroy()})},Math.max(0,this.options.duration-this.elapsed))}pause(){var e;if("recording"!==this.state)throw new w("recorder is not recording",104);this.elapsed+=Date.now()-this.startedAt,void 0!==this.timer&&clearTimeout(this.timer),null==(e=this.recorder)||e.pause(),this.state="paused",this.emit({state:"pause"})}resume(){var e;if("paused"!==this.state)throw new w("recorder is not paused",104);null==(e=this.recorder)||e.resume(),this.state="recording",this.startedAt=Date.now(),this.scheduleStop(),this.emit({state:"resume"})}async stop(){if("recording"!==this.state&&"paused"!==this.state)throw new w("recorder is not started",104);"recording"===this.state&&(this.elapsed+=Date.now()-this.startedAt),this.state="stopped",void 0!==this.timer&&clearTimeout(this.timer);try{let e;this.recorder&&await new Promise(e=>{this.recorder.onstop=()=>e(),this.recorder.stop()});let t="wav";if(this.recorder){let r=new Blob(this.encodedChunks,{type:this.recorder.mimeType});e=new Uint8Array(await r.arrayBuffer()),t=this.recorder.mimeType.includes("audio/aac")?"aac":"m4a"}else e=function(e,t,r){let i=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(44+i),a=new DataView(n.buffer);for(let[e,t]of[[0,"RIFF"],[8,"WAVE"],[12,"fmt "],[36,"data"]])for(let r=0;r<t.length;r++)n[e+r]=t.charCodeAt(r);a.setUint32(4,i+36,!0),a.setUint32(16,16,!0),a.setUint16(20,1,!0),a.setUint16(22,r,!0),a.setUint32(24,t,!0),a.setUint32(28,t*r*2,!0),a.setUint16(32,2*r,!0),a.setUint16(34,16,!0),a.setUint32(40,i,!0);let s=44;for(let t of e)n.set(t,s),s+=t.length;return n}(this.chunks,this.audio.sampleRate,this.options.numberOfChannels);if(this.destroyed)return;let r=`appletfile://temp/recording-${Date.now()}-${++o_}.${t}`;await rH(r,e,this.context),this.options.frameSize&&this.emit({state:"frameRecorded",frameBuffer:ob(this.frame.slice().buffer),isLastFrame:!0}),this.emit({state:"stop",tempFilePath:r,duration:this.elapsed,fileSize:e.byteLength})}finally{this.destroy()}}release(){var e;void 0!==this.timer&&clearTimeout(this.timer),this.processor&&(this.processor.port.onmessage=null,this.processor.disconnect()),null==(e=this.stream)||e.getTracks().forEach(e=>e.stop()),this.audio&&"closed"!==this.audio.state&&this.audio.close().catch(()=>{})}destroy(){var e,t,r;this.destroyed||(this.destroyed=!0,null==(e=this.unregister)||e.call(this),(null==(t=this.recorder)?void 0:t.state)!=="inactive"&&(null==(r=this.recorder)||r.stop()),this.release())}}let oC=new Set,oE=new Set(["scope.userLocation","scope.userFuzzyLocation","scope.userLocationBackground","scope.record","scope.bluetooth","scope.camera","scope.addPhoneContact","scope.addPhoneCalendar"]);function oN(e){let t=nL.getSystem();if(oi.isLocationScope(e)){if("denied"===oi.getSnapshot().browserAuthorization)return!0;let r=t.locationAuthorization??(nL.getBeacon().locationAuthorized?"foreground precise":"denied");return!(r.startsWith("foreground ")||r.startsWith("background "))||"scope.userLocationBackground"===e&&!r.startsWith("background ")||"scope.userLocation"===e&&!r.endsWith("precise")}let r="scope.record"===e?t.microphone:"scope.camera"===e?t.camera:"scope.addPhoneCalendar"===e?t.phoneCalendar:"scope.addPhoneContact"===e?t.contacts:void 0;return"denied"===r||"restricted"===r||"read only"===r||"scope.bluetooth"===e&&!nL.getBluetooth().authorized}async function oT(e,t,r,i,n){var a;let s=await sJ({appId:(null==i||null==(a=i.navigation)?void 0:a.getPackageInfo().appId)??e.appId,appIcon:e.appIcon,appName:e.appName,presenter:e.showSimulatorPermission,scope:t,skipDialogIfDenied:r,signal:n});return!(null==n?void 0:n.aborted)&&oi.isLocationScope(t)&&oi.updateUserAuthorization(s),s}let oA="app_id_missing",oM="cashier_unavailable",oR="create_order_failed",oj="developer_order_exists",oP="login_credential_invalid",oL="login_credential_missing",oO="login_authorization_failed",oD="login_authorization_unsupported",oU="login_state_invalid",oq="login_session_unavailable",o$="payment_amount_invalid",oB="payment_authorization_invalid",oF="payment_cancelled",oz="payment_data_invalid",oW="payment_data_missing",oH="payment_data_unavailable",oV="payment_data_unavailable_with_sign",oG="payment_data_unsupported",oJ="payment_failed",oK="payment_method_unavailable",oZ="payment_order_invalid",oX="payment_parameter_missing",oY="payment_params_invalid",oQ="payment_params_unavailable",o0="payment_sign_params_invalid",o1="payment_sign_params_unavailable",o2="payment_incomplete",o3="privacy_state_unavailable",o4="privacy_authorization_failed",o6="pre_order_failed",o5="phone_authorization_failed",o8="request_format_invalid",o9="request_params_invalid",o7="sandbox_resource_not_found",le="sandbox_service_unavailable",lt="sandbox_session_expired",lr="sandbox_session_forbidden",li="sign_order_failed",ln="sign_order_already_exists",la="sign_order_not_found",ls="sign_order_params_invalid",lo="sign_order_status_invalid",ll="sign_order_create_failed",ld="sign_page_params_invalid",lu="sign_page_unavailable",lc="sign_page_data_unavailable",lp="请求暂时无法完成,请稍后重试;如持续失败,请提供 log_id";function lh(e,t){return!t||e.includes(t)?e:`${e}(log_id: ${t})`}class lm extends Error{code;details;logId;constructor(e,t={},r){super(lb(e,t,r)),this.code=e,this.details=t,this.logId=r,this.name="SandboxError"}}class lg extends Error{remoteCode;options;constructor(e,t,r={}){super(t),this.remoteCode=e,this.options=r,this.name="SandboxRemoteError"}}let lf={[oA]:"当前未配置应用 ID,请先完成应用配置。",[oM]:"无法打开模拟器收银台,请刷新模拟器后重试。",[oR]:"暂时无法创建订单,请检查签名参数后稍后重试;如持续失败,请提供 log_id",[oj]:"开发者订单号已存在,请查询原订单",[oP]:"登录失败:登录凭证已过期或已使用,请重新发起登录。",[oL]:"登录失败:成功登录回调未携带业务登录凭证,请检查登录实现。",[oO]:"暂时无法完成登录授权,请重新发起授权",[oD]:"当前 Sandbox 无法完成该授权请求,请检查授权方式和会话配置",[oU]:"用户登录状态已失效,请重新登录",[oq]:"登录失败:模拟器会话不可用,请登录开发者账号后重新打开模拟器。",[o$]:"支付金额无效,请使用最小货币单位的整数,并由业务服务端生成金额。",[oB]:"支付授权校验失败,请确认 data 和 dbAuthorization 使用同一个 dev.key 生成,并且模拟器配置了匹配的 dev.csr。",[oF]:"已取消支付。",[oz]:"支付数据格式无效,请检查业务服务端生成的 pay_data。",[oH]:"无法打开收银台:模拟器未返回支付数据,请检查订单状态和预下单响应。",[oV]:"无法打开支付签约收银台:模拟器未返回支付数据,请检查签约参数和订单状态。",[oG]:"当前支付数据不支持模拟器收银台,请检查模拟器支付配置。",[oJ]:lp,[oK]:"支付数据中没有可用的支付方式,请检查模拟器支付配置。",[oZ]:"订单不存在或不属于当前应用",[oY]:"请求参数不正确,请检查订单信息和金额",[oQ]:"暂时无法获取支付参数,请检查订单号后重试;如持续失败,请提供 log_id",[o0]:"请求参数不正确,请检查订单号和签约信息",[o1]:"暂时无法获取支付参数,请稍后重试;如持续失败,请提供 log_id",[o2]:"模拟支付未完成,请检查支付方式和订单状态后重试;如持续失败,请提供 log_id",[o3]:"暂时无法读取或保存授权状态,请稍后重试",[o4]:"隐私授权失败:请刷新模拟器后重试。",[o6]:"预下单失败:模拟器未返回订单 ID,请检查业务服务端预下单响应。",[o5]:"手机号授权失败:无法获取手机号授权凭证,请重试或使用其他登录方式。",[o8]:"请求格式不正确,请检查后重试",[o9]:"请求参数不正确,请检查必填字段和字段格式",[o7]:"未找到沙箱会话或相关资源,请重新创建后重试",[le]:"沙箱服务暂时不可用,请稍后重试;如持续失败,请提供 log_id",[lt]:"沙箱会话已过期,请重新启动调试会话",[lr]:"当前沙箱会话无权访问该应用,请检查应用和会话是否匹配",[li]:"创建签约订单失败:模拟器未返回签约订单 ID,请检查签约参数。",[ln]:"开发者签约单号已存在,请查询原签约单",[la]:"签约单不存在或不属于当前应用",[ls]:"签约单参数无效,请检查单号、应用和有效期",[lo]:"当前签约单状态不允许继续签约",[ll]:"暂时无法创建签约单,请检查签名参数后重试;如持续失败,请提供 log_id",[ld]:"签约单参数无效,请检查单号、应用和有效期",[lu]:"暂时无法获取签约页,请稍后重试;如持续失败,请提供 log_id",[lc]:"打开签约页面失败:模拟器未返回签约数据,请检查签约订单状态。"},lv={id:"支付方式 ID",name:"支付方式名称",pay_order_no:"支付订单号",pay_status:"支付状态",trade_no:"交易号"},ly={data:"业务服务端生成的 data",dbAuthorization:"业务服务端生成的 dbAuthorization",orderId:"requestOrder 返回的 orderId",signData:"业务服务端生成的 signData",signDbAuthorization:"业务服务端生成的 signDbAuthorization"};function lb(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;return lh(function(e,t){if(e===oW){let e=t.field?lv[t.field]:"必要字段";return`支付数据缺少${e},请检查业务服务端生成的 pay_data。`}if(e===oX){let e=t.key?ly[t.key]:"该参数";return`缺少支付参数,请提供${e}。`}return lf[e]}(e,t),r)}function lw(e){if("number"==typeof e&&Number.isInteger(e))return e;if("string"==typeof e&&e.trim()){let t=Number(e);return Number.isInteger(t)?t:void 0}}let l_={400:o9,401:lt,403:lr,404:o7,500:le};function lS(e,t){return 400===t?o8:void 0===e?void 0:l_[e]}let lx={[oV]:o0,[li]:ls,[lc]:ld},lI={[o6]:oR,[oV]:o1,[li]:ll,[lc]:lu};function lk(e,t,r){switch(e){case 500:return"payment"===r?o2:le;case 4201:return oB;case 0x1dcd6501:return lx[t]??oY;case 0x1dcdb322:return oj;case 5e8:return lI[t]??oQ;case 0x1dcdb325:return t===lc?la:oZ;case 0x1dcdb327:return ln;case 0x1dcdb328:return lo;default:return void 0===e||0===e?t:oJ}}let lC={[-1]:oq,4001:oP,2001:o4,502:oO,402:oU,501:o3,400:o9};function lE(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if("code"===r.errorField){let t=lS(e,r.httpStatus);if(t)return t}return"data.error_code"===r.errorField&&40001===e?oD:"err_code"===r.errorField&&401===e?o9:1001===e?"phone"===t?o5:oP:void 0===e?le:lC[e]??le}function lN(e,t){return e instanceof lm?e:e instanceof lg?new lm(lE(e.remoteCode,t,e.options),{},e.options.logId):new lm(le)}function lT(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:lp,r=arguments.length>2?arguments[2]:void 0;if(e instanceof lm)return lb(e.code,e.details,e.logId??r);if(e instanceof lg){let t="code"===e.options.errorField?lS(e.remoteCode,e.options.httpStatus):void 0,i=lk(e.remoteCode,oJ,e.options.operation);return lb(e.options.operation?i:t??i,{},e.options.logId??r)}return lh(t,r)}function lA(e,t){let r=e.err_code;if(r)throw new lm(lE(r,t,{errorField:"err_code"}),{},e.log_id)}function lM(e){return!e||"object"!=typeof e||Array.isArray(e)?{}:{code:lw(e.code),logId:"string"==typeof e.log_id?e.log_id:void 0}}function lR(e,t){let{code:r,logId:i}=lM(e);if(r)throw new lg(r,`Sandbox 请求失败,错误码为 ${String(r)}。`,{errorField:"code",httpStatus:t,logId:i})}let lj="web-sdk-debugger",lP=[{id:"douyin",name:"抖音支付"}];async function lL(e){let t=await fetch("/__web_sdk_sandbox_proxy__",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),r=await t.json().catch(()=>({})),{code:i,logId:n}=lM(r);if(!t.ok)throw new lg(i,`Sandbox 代理请求失败,HTTP 状态码为 ${t.status}。`,{errorField:"code",httpStatus:t.status,logId:n});return lR(r,t.status),r}let lO=new class{request=()=>{throw Error("FlowAppDeveloperOpenGatewayService.request is undefined")};baseURL="";constructor(e){this.request=(null==e?void 0:e.request)||this.request,this.baseURL=(null==e?void 0:e.baseURL)||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}FetchPackageDownLoadInfo(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.verson_tag}/packet`);return this.request({url:r,method:"POST"},t)}GetArtifactStatus(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.verson_tag}/artifact`);return this.request({url:r,method:"POST"},t)}GetUserBasicInfo(e,t){let r=e||{},i=this.genBaseURL("/app_developer/api/user/basic"),n={user_name:r.user_name,user_id:r.user_id};return this.request({url:i,method:"GET",params:n},t)}GetConfigRoleList(e,t){let r=this.genBaseURL("/app_developer/api/config/role/role_list");return this.request({url:r,method:"GET"},t)}RoleListByAppid(e,t){let r=this.genBaseURL("/app_developer/api/user/role/role_list");return this.request({url:r,method:"GET"},t)}UpdateUserName(e,t){let r=this.genBaseURL("/app_developer/api/user/basic/update_user_name"),i={user_name:e.user_name};return this.request({url:r,method:"PUT",data:i},t)}GetInviteMemberList(e,t){let r=e||{},i=this.genBaseURL("/app_developer/api/member/member_list"),n={app_key:r.app_key,user_name:r.user_name,page_size:r.page_size,page_num:r.page_num};return this.request({url:i,method:"GET",params:n},t)}SendInviteMember(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/member/invite/send_invite`),i={role_code:e.role_code,target_user_id:e.target_user_id};return this.request({url:r,method:"POST",data:i},t)}UpdateAppMeta(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/meta/update`),i={app_name:e.app_name,description:e.description,privacy_agreement:e.privacy_agreement,icon_url:e.icon_url,extra:e.extra,app_type:e.app_type,login_text:e.login_text};return this.request({url:r,method:"POST",data:i},t)}SubmitRelease(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/release`);return this.request({url:r,method:"POST"},t)}ActivateDeviceCode(e,t){let r=this.genBaseURL("/app_developer/oauth/device/activate"),i={user_code:e.user_code,client_name:e.client_name};return this.request({url:r,method:"POST",data:i},t)}GetPlatformCert(e,t){let r=this.genBaseURL("/app_developer/api/platform/cert");return this.request({url:r,method:"GET"},t)}UploadCsr(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/upload_csr`),i={csr_pem:e.csr_pem};return this.request({url:r,method:"POST",data:i},t)}GetAppCert(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/cert`);return this.request({url:r,method:"GET"},t)}CreateApp(e,t){let r=this.genBaseURL("/app_developer/api/apps"),i={app_name:e.app_name,description:e.description,privacy_agreement:e.privacy_agreement,icon_url:e.icon_url,extra:e.extra,app_type:e.app_type,login_text:e.login_text};return this.request({url:r,method:"POST",data:i},t)}UploadIcon(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/upload_icon`);return this.request({url:r,method:"POST"},t)}SubmitAudit(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/submit_audit`);return this.request({url:r,method:"POST"},t)}IssueDeviceCode(e,t){let r=this.genBaseURL("/app_developer/oauth/device/code"),i={client_name:e.client_name};return this.request({url:r,method:"POST",data:i},t)}GetAppWhitelist(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/whitelist`),i={offset:e.offset,limit:e.limit,keyword:e.keyword};return this.request({url:r,method:"GET",params:i},t)}UpdateAppWhitelist(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/whitelist`),i={action:e.action,subject:e.subject};return this.request({url:r,method:"POST",data:i},t)}ExchangeDeviceToken(e,t){let r=this.genBaseURL("/app_developer/oauth/token"),i={device_code:e.device_code};return this.request({url:r,method:"POST",data:i},t)}ListApps(e,t){let r=e||{},i=this.genBaseURL("/app_developer/api/apps"),n={app_limit:r.app_limit,app_offset:r.app_offset,key_word:r.key_word,app_key:r.app_key};return this.request({url:i,method:"GET",params:n},t)}GetAppMeta(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/meta`),i={limit:e.limit,offset:e.offset,status:e.status};return this.request({url:r,method:"GET",params:i},t)}ToolList(e,t){let r=this.genBaseURL("/developer/api/tools/list"),i={mcp_server_url:e.mcp_server_url,mcp_config:e.mcp_config};return this.request({url:r,method:"GET",params:i},t)}GetMiniAppVersionArtifact(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/artifact`);return this.request({url:r,method:"GET"},t)}UploadMiniAppVersionDraftPackage(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/draft/upload`),i={source_type:e.source_type};return this.request({url:r,method:"POST",params:i},t)}SubmitMiniAppVersionDraft(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/draft/submit`),i={project_config_version:e.project_config_version,app_version_tag:e.app_version_tag};return this.request({url:r,method:"POST",data:i},t)}ListMiniAppVersions(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions`),i={page:e.page,page_size:e.page_size,id:e.id};return this.request({url:r,method:"GET",params:i},t)}VerifyYAML(e,t){let r=this.genBaseURL("/app_developer/api/yaml/verify"),i={yaml:e.yaml,mode:e.mode,yaml_type:e.yaml_type};return this.request({url:r,method:"POST",data:i},t)}GetMiniAppVersionYAML(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/manifest`);return this.request({url:r,method:"GET"},t)}GetMiniAppVersionStructuredManifest(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/manifest_struct`);return this.request({url:r,method:"GET"},t)}QrcodeInfo(e,t){let r=this.genBaseURL("/app_developer/resource_api/package/qrcode_info"),i={app_key:e.app_key};return this.request({url:r,method:"POST",data:i},t)}GetMiniAppVersionDraftPackageDownloadURL(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/download_url`),i={source_type_list:e.source_type_list};return this.request({url:r,method:"GET",params:i},t)}GetSubMerchantList(e,t){let r=this.genBaseURL("/app_developer/api/trade/user/get_sub_merchant_list"),i={org_id:e.org_id};return this.request({url:r,method:"GET",params:i},t)}AppBindSubMerchant(e,t){let r=this.genBaseURL(`/app_developer/api/trade/apps/${e.app_key}/app_bind_sub_merchant`),i={sub_merchant_uid:e.sub_merchant_uid,org_id:e.org_id};return this.request({url:r,method:"PUT",data:i},t)}CreateSubMerchant(e,t){let r=this.genBaseURL("/app_developer/api/trade/user/create_sub_merchant"),i={org_id:e.org_id,sub_merchant_name:e.sub_merchant_name};return this.request({url:r,method:"POST",data:i},t)}UnBindSubMerchant(e,t){let r=this.genBaseURL(`/app_developer/api/trade/apps/${e.app_key}/unbind_sub_merchant`),i={sub_merchant_uid:e.sub_merchant_uid,org_id:e.org_id};return this.request({url:r,method:"POST",data:i},t)}GetSubMerchantCaijingUrl(e,t){let r=this.genBaseURL("/app_developer/api/trade/user/get_sub_merchant_url"),i={sub_merchant_uid:e.sub_merchant_uid};return this.request({url:r,method:"POST",data:i},t)}GetAppBindSubMerchants(e,t){let r=this.genBaseURL(`/app_developer/api/trade/apps/${e.app_key}/get_bind_sub_merchants`);return this.request({url:r,method:"GET"},t)}GetAppEventCallbackConf(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/events/get_callback_conf`),i={source:e.source};return this.request({url:r,method:"GET",params:i},t)}UpdateAppEventCallbackConf(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/events/update_callback_conf`),i={source:e.source,callback_address:e.callback_address};return this.request({url:r,method:"PUT",data:i},t)}CreateOrganization(e,t){let r=this.genBaseURL("/app_developer/api/organization"),i={name:e.name};return this.request({url:r,method:"POST",data:i},t)}UpdateOrganization(e,t){let r=this.genBaseURL(`/app_developer/api/organizations/${e.org_code}/update`),i={name:e.name};return this.request({url:r,method:"POST",data:i},t)}FinishMiniAppVersionDraftSourceCodeUploading(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/draft/source_code/upload/finish`),i={upload_token:e.upload_token,size:e.size,sha256:e.sha256};return this.request({url:r,method:"POST",data:i},t)}DeleteOrganization(e,t){let r=this.genBaseURL(`/app_developer/api/organizations/${e.org_code}/delete`);return this.request({url:r,method:"POST"},t)}GetOrganizationToken(e,t){let r=this.genBaseURL("/app_developer/api/organization/get_token"),i={org_code:e.org_code};return this.request({url:r,method:"POST",data:i},t)}StartMiniAppVersionDraftSourceCodeUploading(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/draft/source_code/upload/start`),i={sha256:e.sha256};return this.request({url:r,method:"POST",data:i},t)}ListOrganizations(e,t){let r=this.genBaseURL("/app_developer/api/organizations/list");return this.request({url:r,method:"GET"},t)}CreateAppDomainFile(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/file_create`),i={normalized_domain:e.normalized_domain,domain_category:e.domain_category};return this.request({url:r,method:"POST",data:i},t)}DeleteAppDomain(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/delete`),i={normalized_domain:e.normalized_domain,domain_category:e.domain_category};return this.request({url:r,method:"POST",data:i},t)}VerifyAppDomainFile(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/file_verify`),i={normalized_domain:e.normalized_domain,domain_category:e.domain_category};return this.request({url:r,method:"POST",data:i},t)}CreateAppDomain(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/create`),i={domain:e.domain,domain_category:e.domain_category};return this.request({url:r,method:"POST",data:i},t)}GetAppDomainList(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/list`);return this.request({url:r,method:"GET"},t)}SandboxGetAwemeCommonLoginInfo(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/auth/get_aweme_common_login_info"),i={app_key:e.app_key};return this.request({url:r,method:"POST",data:i},t)}SandboxUpdateMessageCardWidgetData(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/card/update_message_card_widget_data"),i={mixture_card_id:e.mixture_card_id,message_id:e.message_id,widget_id:e.widget_id,widget_data:e.widget_data};return this.request({url:r,method:"POST",data:i},t)}SandboxCreateSignOrder(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/create_sign_order"),i={data:e.data,db_authorization:e.db_authorization,app_key:e.app_key,message_id:e.message_id};return this.request({url:r,method:"POST",data:i},t)}SandboxGetOrderPaymentWithSign(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/get_order_payment_with_sign"),i={order_id:e.order_id,sign_data:e.sign_data,sign_db_authorization:e.sign_db_authorization,app_key:e.app_key,message_id:e.message_id,aweme_bind_status:e.aweme_bind_status};return this.request({url:r,method:"POST",data:i},t)}SandboxRequestOrder(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/request_order"),i={data:e.data,db_authorization:e.db_authorization,app_key:e.app_key,message_id:e.message_id};return this.request({url:r,method:"POST",data:i},t)}SandboxGetSignPageData(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/get_sign_page_data"),i={auth_order_id:e.auth_order_id,app_key:e.app_key,message_id:e.message_id,aweme_bind_status:e.aweme_bind_status};return this.request({url:r,method:"POST",data:i},t)}SandboxGetMessageInfoByMixtureCardID(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/card/get_message_info_by_mixture_card_id"),i={mixture_card_id:e.mixture_card_id};return this.request({url:r,method:"POST",data:i},t)}SandboxGetOrderPayment(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/get_order_payment"),i={order_id:e.order_id,app_key:e.app_key,platform_signed_pt_code:e.platform_signed_pt_code,message_id:e.message_id,aweme_bind_status:e.aweme_bind_status};return this.request({url:r,method:"POST",data:i},t)}SandboxApiGetUserAppsPermissionDetail(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/miniapp_permission/detail"),i={applets_list:e.applets_list};return this.request({url:r,method:"POST",data:i},t)}SandboxApiPostUserAppsPermission(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/miniapp_permission/post"),i={applet_id:e.applet_id,update_scope_info:e.update_scope_info,using_scope_infos:e.using_scope_infos};return this.request({url:r,method:"POST",data:i},t)}SandboxApiGetUserAppsPermissionRecord(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/miniapp_permission/record"),i={applet_id:e.applet_id};return this.request({url:r,method:"POST",data:i},t)}SandboxApiExchangeCode(e,t){let r=e||{},i=this.genBaseURL("/app_developer/api/sandbox/jsb/oauth/token"),n={app_key:r.app_key,code:r.code,device_id:r.device_id,version_tag:r.version_tag};return this.request({url:i,method:"POST",data:n},t)}SandboxApiGetPhoneMask(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/phone_mask");return this.request({url:r,method:"POST"},t)}SandboxApiCheckPrivacyOrLoginStatus(e,t){let r=e||{},i=this.genBaseURL("/app_developer/api/sandbox/jsb/user/privacy_login/check"),n={app_key:r.app_key,version_tag:r.version_tag,check_type:r.check_type};return this.request({url:i,method:"POST",data:n},t)}SandboxApiAcceptPrivacy(e,t){let r=e||{},i=this.genBaseURL("/app_developer/api/sandbox/jsb/user/privacy/accept"),n={app_key:r.app_key,request_id:r.request_id,device_id:r.device_id};return this.request({url:i,method:"POST",data:n},t)}SandboxApiDeleteDataObtainedByTicket(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/miniapp_permission/ticket_revoke"),i={applet_id:e.applet_id,scope_name:e.scope_name,permission_ticket_type:e.permission_ticket_type};return this.request({url:r,method:"POST",data:i},t)}ListPublicNoticeTemplates(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/public_notice_templates`),i={category:e.category,subscription_type:e.subscription_type,keyword:e.keyword,page_num:e.page_num,page_size:e.page_size};return this.request({url:r,method:"GET",params:i},t)}SandboxIssueLoginCode(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/passport/open/auth"),i={client_key:e.client_key,aid:e.aid,scope:e.scope,source:e.source,exchange_type:e.exchange_type};return this.request({url:r,method:"POST",data:i},t)}GetSandboxBusinessInfo(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/session/business_info/get"),i={sandbox_session_id:e.sandbox_session_id};return this.request({url:r,method:"POST",data:i},t)}UpdateSandboxBusinessInfo(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/session/business_info/update"),i={sandbox_session_id:e.sandbox_session_id,phone_num:e.phone_num,csr_pem:e.csr_pem,location_info:e.location_info};return this.request({url:r,method:"POST",data:i},t)}SandboxPay(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/payment/pay"),i={trade_no:e.trade_no,pay_type:e.pay_type};return this.request({url:r,method:"POST",data:i},t)}CheckDeveloperAccessWhitelist(e,t){let r=this.genBaseURL("/app_developer/api/user/whitelist/check"),i={invite_code:(e||{}).invite_code};return this.request({url:r,method:"POST",data:i},t)}OIDCGet(e,t){let r=this.genBaseURL("/app_developer/api/oidc_get");return this.request({url:r,method:"GET"},t)}OIDCCallback(e,t){let r=this.genBaseURL("/app_developer/api/oidc_callback"),i={code:e.code,nonce:e.nonce,state:e.state};return this.request({url:r,method:"GET",params:i},t)}AuditDetail(e,t){let r=this.genBaseURL("/app_developer/api/apps/audit/detail"),i={audit_id:e.audit_id,audit_type:e.audit_type};return this.request({url:r,method:"POST",data:i},t)}ListBusinessTemplates(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/business_templates`),i={biz_type:e.biz_type,status:e.status,sync_status:e.sync_status,page_num:e.page_num,page_size:e.page_size};return this.request({url:r,method:"GET",params:i},t)}GetBusinessTemplatesYaml(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/business_templates/yaml`),i={status:e.status};return this.request({url:r,method:"GET",params:i},t)}DeleteBusinessTemplate(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/business_templates/${e.biz_type}/${e.template_key}/delete`);return this.request({url:r,method:"POST"},t)}GetPublicNoticeTemplate(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/public_notice_templates/${e.public_template_key}`);return this.request({url:r,method:"GET"},t)}PullSandboxNotices(e,t){let r=e||{},i=this.genBaseURL("/app_developer/api/sandbox/resources/notices/pull"),n={notice_ids:r.notice_ids,cursor:r.cursor,limit:r.limit};return this.request({url:i,method:"POST",data:n},t)}RemoveSandboxTaskFromUser(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/resources/tasks/remove_from_user"),i={task_id:e.task_id};return this.request({url:r,method:"POST",data:i},t)}PullSandboxTasks(e,t){let r=e||{},i=this.genBaseURL("/app_developer/api/sandbox/resources/tasks/pull"),n={task_ids:r.task_ids,cursor:r.cursor,limit:r.limit};return this.request({url:i,method:"POST",data:n},t)}CreateSandboxSession(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/session/create"),i={sandbox_project_id:e.sandbox_project_id,app_id:e.app_id,bridge_origins:e.bridge_origins,manifest:e.manifest};return this.request({url:r,method:"POST",data:i},t)}PreviewTosFile(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/audit/tos/preview`),i={object_key:e.object_key};return this.request({url:r,method:"GET",params:i},t)}QrcodeShort(e,t){let r=this.genBaseURL("/app_developer/resource_api/package/qrcode_short"),i={url:e.url,ttl:e.ttl};return this.request({url:r,method:"POST",data:i},t)}GetQrcodeURL(e,t){let r=this.genBaseURL("/app_developer/resource_api/package/qrcode_url"),i={token:e.token};return this.request({url:r,method:"POST",data:i},t)}DownloadTosFile(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/audit/tos/download`),i={object_key:e.object_key};return this.request({url:r,method:"GET",params:i},t)}SandboxCallMcpTool(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/card/call_mcp_tool"),i={tool_name:e.tool_name,tool_args_json:e.tool_args_json,widget_instance_id:e.widget_instance_id,artifact_version_code:e.artifact_version_code,app_key:e.app_key,widget_id:e.widget_id,scene:e.scene,skip_widget_update:e.skip_widget_update};return this.request({url:r,method:"POST",data:i},t)}DeleteMember(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/member/delete`),i={user_id:e.user_id};return this.request({url:r,method:"POST",data:i},t)}SubmitSandboxEventReport(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/bridge/events/report"),i={event_id:e.event_id,data:e.data},n={"X-DBX-Sandbox-Session-ID":e["X-DBX-Sandbox-Session-ID"]};return this.request({url:r,method:"POST",data:i,headers:n},t)}UploadSimulatorImage(e,t){let r=this.genBaseURL("/app_developer/api/simulator/images/upload"),i={image:e.image};return this.request({url:r,method:"POST",data:i},t)}}({baseURL:"",request:lL});function lD(e,t){if(!e.data)throw Error(e.message||`${t} returned empty data`);return e.data}async function lU(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return lD(await lO.PullSandboxNotices(e),"PullSandboxNotices")}async function lq(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return lD(await lO.PullSandboxTasks(e),"PullSandboxTasks")}async function l$(e){return lD(await lO.RemoveSandboxTaskFromUser({task_id:e}),"RemoveSandboxTaskFromUser").removed_task}async function lB(e,t){return lL({data:{event_id:e,data:t},method:"POST",url:"/app_developer/api/sandbox/bridge/events/report"})}async function lF(e){let{appletId:t,granted:r,scopeName:i}=e;if(!t.trim())throw Error("appletId is required");if(!i.trim())throw Error("scopeName is required");let n=await lO.SandboxApiPostUserAppsPermission({applet_id:t,update_scope_info:{grant_status:r?1:2,scope_name:i}});if(0!==n.err_code)throw Error(n.err_msg||`Sandbox post Agentic Service permission failed with code ${String(n.err_code)}`)}async function lz(e){let{appKey:t,params:r,scene:i}=e;if(!t.trim())throw Error("callTool requires a simulator app context");if("widget"===i&&(!e.widgetId.trim()||!e.widgetInstanceId.trim()))throw Error("callTool requires a simulator conversation card context");let{skipWidgetUpdate:n,toolArgs:a,toolName:s}=function(e){if(!rP(e)||"string"!=typeof e.toolName||!e.toolName.trim()||!rP(e.toolArgs)||void 0!==e.skipWidgetUpdate&&"boolean"!=typeof e.skipWidgetUpdate)throw Error("callTool requires a non-empty toolName, an object toolArgs, and an optional boolean skipWidgetUpdate");return{skipWidgetUpdate:e.skipWidgetUpdate??!1,toolName:e.toolName.trim(),toolArgs:e.toolArgs}}(r),o=await lO.SandboxCallMcpTool({app_key:t,scene:"page"===i?2:1,skip_widget_update:n,tool_args_json:JSON.stringify(a),tool_name:s,..."widget"===i?{widget_id:e.widgetId,widget_instance_id:e.widgetInstanceId}:{}}),l=lw(o.err_code);if(void 0!==l&&0!==l)throw new lg(l,o.err_msg||`callTool failed with code ${l}`,{errorField:"err_code",logId:o.log_id});if(!o.result)throw Error(o.err_msg||"callTool returned an empty result");if(1!==o.result.output_kind&&2!==o.result.output_kind)throw Error("callTool returned an invalid output kind");let d=o.result.card_update_error,u=o.result.tool_error,c=o.result.tool_result_json,p=d?{cardUpdateError:{code:d.code,message:d.message,phase:"render"}}:{};if(u){let e=lw(u.code);if(void 0!==c||void 0===e||"string"!=typeof u.message||!u.message.trim())throw Error("callTool returned an invalid Tool error");return{toolError:{code:e,message:u.message},...p}}if(void 0===c)throw Error("callTool returned neither a Tool result nor a Tool error");return{toolResult:function(e){let t=JSON.parse(e);if(!rP(t))throw Error("callTool returned an invalid ToolResult");return t}(c),...p}}function lW(e){var t;let r=(null==(t=e.getAppId)?void 0:t.call(e))||e.appId;if(!r)throw new lm(oA);return r}function lH(e,t){var r;let i=null==e||null==(r=e[t])?void 0:r.trim();if(!i)throw new lm(oX,{key:t});return i}function lV(e,t,r){let i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=arguments.length>4?arguments[4]:void 0,a=lw(t.err_code),s=n?(n instanceof lg?n.remoteCode:void 0)??(void 0!==a&&0!==a?a:void 0)??-1:a??-1,o=(n instanceof lg?n.options.logId:void 0)??t.log_id,l=n?lT(n,lb(r),o):lb(lk(a,r),{},o),d={code:i?s:void 0,errNo:String(s),errMsg:l,errLogId:o};return{type:"callback",callbackId:e.callbackId,params:{code:0,data:d,errNo:s,errMsg:l,msg:l}}}async function lG(e,t){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];try{return await t()}catch(t){return lV(e,{},oJ,r,t)}}async function lJ(e,t){let r=function(e){let t;try{t=JSON.parse(e)}catch{throw new lm(oz)}if(!t||"object"!=typeof t||Array.isArray(t))throw new lm(oz);let r=t;if("sandbox_cashier"!==r.type)throw new lm(oG);let i="string"==typeof r.total_amount?r.total_amount.trim():"";if(!i||!/^\d+$/.test(i))throw new lm(o$);let n="string"==typeof r.pay_order_no?r.pay_order_no.trim():"",a="string"==typeof r.pay_status?r.pay_status.trim():"",s="string"==typeof r.trade_no?r.trade_no.trim():"";if(!n||!a||!s)throw new lm(oW,{field:n?a?"trade_no":"pay_status":"pay_order_no"});return{paymentTypes:function(e){if(!Array.isArray(e)||0===e.length)throw new lm(oK);let t=e.map(e=>{if(!rP(e))throw new lm(oz);let t="string"==typeof e.id?e.id.trim():"",r="string"==typeof e.name?e.name.trim():"";if(!t||!r)throw new lm(oW,{field:t?"name":"id"});return{id:t,name:r}});if(new Set(t.map(e=>{let{id:t}=e;return t})).size!==t.length)throw new lm(oz);return t}(r.pay_types??lP),payOrderNo:n,payStatus:a,totalAmount:i,tradeNo:s,type:"sandbox_cashier"}}(e);if(!t.showSandboxCashier)throw new lm(oM);if(!await t.showSandboxCashier(r,async e=>{if(!r.paymentTypes.some(t=>{let{id:r}=t;return r===e}))throw new lm(oK);try{await lO.SandboxPay({trade_no:r.tradeNo,pay_type:e})}catch(e){if(e instanceof lg&&"code"===e.options.errorField&&500===e.remoteCode)throw new lg(e.remoteCode,e.message,{...e.options,operation:"payment"});throw e}}))throw new lm(oF)}async function lK(e,t){let r,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"user_info",n=t?"phone":"login";try{r=await lO.SandboxIssueLoginCode({aid:"482431",client_key:lW(e),scope:i,source:"jsb",exchange_type:t})}catch(e){throw lN(e,n)}var a,s,o=lw(null==(a=r.data)?void 0:a.error_code),l=lM(r).logId;if(o)throw new lm(lE(o,n,{errorField:"data.error_code"}),{},l);let d=null==(s=r.data)?void 0:s.code;if(!d)throw new lm(le);return d}async function lZ(e){try{let t=void 0!==e.locationInfo,r=await lO.UpdateSandboxBusinessInfo({csr_pem:e.csrPem||(t?"":void 0),location_info:e.locationInfo,phone_num:e.phoneNum,sandbox_session_id:""});return lR(r),r}catch(r){let e=r instanceof lg?r.options.logId:r&&"object"==typeof r&&"logId"in r&&"string"==typeof r.logId?r.logId:void 0,t=Error(lh(r instanceof Error?r.message:String(r),e));throw t.logId=e,t}}async function lX(e){return lZ(e)}async function lY(e){return lZ({csrPem:"",locationInfo:e,phoneNum:""})}async function lQ(e){let t=await fetch("/__web_sdk_sandbox_session_recreate__",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),r=await t.json().catch(()=>({}));if(!t.ok)throw Error((null==r?void 0:r.message)||`Sandbox session recreate failed with status ${t.status}`);return r}let l0=["aztec","codabar","code_39","code_93","code_128","data_matrix","ean_8","ean_13","itf","pdf417","qr_code","upc_a","upc_e"],l1={barCode:["codabar","code_39","code_93","code_128","ean_8","ean_13","itf","upc_a","upc_e"],datamatrix:["data_matrix"],pdf417:["pdf417"],qrCode:["qr_code"]};async function l2(e){let t=e.getSupportedFormats;return"function"==typeof t?new Set(await t()):null}function l3(e){var t,r;return{characterSet:"UTF-8",path:"",rawData:(t=e.rawValue,"function"!=typeof btoa||"u"<typeof TextEncoder?t:btoa(String.fromCharCode(...new TextEncoder().encode(t)))),result:e.rawValue,scanType:(r=e.format,l0.includes(r)?"pdf417"===r?"PDF_417":r.toUpperCase():"QR_CODE")}}async function l4(e,t){if("function"==typeof createImageBitmap){let r=await createImageBitmap(t);try{return e.detect(r)}finally{r.close()}}let r=new Image,i=URL.createObjectURL(t);try{return await new Promise((e,t)=>{r.onload=()=>e(),r.onerror=()=>t(Error("Failed to load selected image")),r.src=i}),e.detect(r)}finally{URL.revokeObjectURL(i)}}function l6(e,t,r,i,n,a){return t()?Promise.resolve():new Promise((s,o)=>{let l=0,d=()=>{for(let t of(window.clearTimeout(l),r))e.removeEventListener(t,u);e.removeEventListener("error",c),null==a||a.removeEventListener("abort",c)},u=()=>{t()&&(d(),s())},c=()=>{d(),o(Error(n))};for(let t of(l=window.setTimeout(()=>{d(),o(Error(n))},i),r))e.addEventListener(t,u);e.addEventListener("error",c),null==a||a.addEventListener("abort",c,{once:!0}),(null==a?void 0:a.aborted)&&c()})}async function l5(e,t,r){e.srcObject=t,await l6(e,()=>e.readyState>=HTMLMediaElement.HAVE_METADATA,["loadedmetadata"],3e3,"Camera stream started, but video metadata was not loaded",r),await e.play(),await l6(e,()=>e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA,["loadeddata","canplay","playing"],3e3,"Camera stream started, but no video frame was rendered",r)}async function l8(e,t,r){var i;let n,a,s=globalThis.BarcodeDetector;if(!s)throw Error("BarcodeDetector is not supported in this browser");let o=await l2(s);if(null==r?void 0:r.aborted)throw Error("scanCode canceled");let l=[...new Set((null==(i=e.scanType)?void 0:i.length)?e.scanType.flatMap(e=>l1[e]):l0)].filter(e=>!o||o.has(e));if(0===l.length)throw Error("Requested scanType is not supported in this browser");let d=new s({formats:l}),u=!1,c=!1,p=0,h=null,m=null,g=()=>{null==h||h.getTracks().forEach(e=>e.stop()),h=null,m&&(m.srcObject=null)},f=()=>{u||(u=!0,a&&(null==r||r.removeEventListener("abort",a)),window.cancelAnimationFrame(p),g(),null==n||n.close())};try{return await new Promise((i,s)=>{let o=e=>{u||(f(),e())};a=()=>o(()=>s(Error("scanCode canceled"))),null==r||r.addEventListener("abort",a,{once:!0});let l=e=>{if(!u&&!c){if(!m||m.readyState<HTMLMediaElement.HAVE_CURRENT_DATA){e&&(null==n||n.setMessage("摄像头画面还未准备好"));return}c=!0,d.detect(m).then(t=>{let r=t[0];r?o(()=>i(l3(r))):e&&(null==n||n.setMessage("未识别到二维码或条形码"))}).catch(t=>{e&&(null==n||n.setMessage(t instanceof Error?t.message:String(t)))}).finally(()=>{c=!1})}};n=t({allowImageUpload:!e.onlyFromCamera,onCancel:()=>o(()=>s(Error("scanCode canceled"))),onCapture:()=>l(!0),onFile:e=>{u||(null==n||n.setMessage("正在识别图片..."),l4(d,e).then(e=>{let t=e[0];t?o(()=>i(l3(t))):null==n||n.setMessage("未识别到二维码或条形码,请换一张图片重试")}).catch(e=>{null==n||n.setMessage(e instanceof Error?e.message:String(e))}))},onVideoReady:t=>{var i;if(m||u)return;m=t;let a=nL.getSystem().camera;"denied"===a||"restricted"===a?e.onlyFromCamera?o(()=>s(Error("Camera permission denied by simulator settings"))):null==n||n.setMessage("模拟系统相机权限不可用,请从相册选择二维码或条形码图片"):(null==(i=navigator.mediaDevices)?void 0:i.getUserMedia)?navigator.mediaDevices.getUserMedia({audio:!1,video:{facingMode:{ideal:"environment"}}}).then(e=>u?void e.getTracks().forEach(e=>e.stop()):(h=e,l5(t,e,r))).then(()=>{if(u)return;let e=()=>{u||(l(!1),p=window.requestAnimationFrame(e))};e()}).catch(t=>{if(u)return;let r=t instanceof Error?t.message:String(t);if(g(),e.onlyFromCamera){null==n||n.setMessage(r),o(()=>s(t instanceof Error?t:Error(r)));return}null==n||n.setMessage(`无法使用摄像头,请从相册选择二维码或条形码图片:${r}`)}):e.onlyFromCamera?o(()=>s(Error("Camera is not available in this browser"))):null==n||n.setMessage("无法使用摄像头,请从相册选择二维码或条形码图片")}})})}catch(e){throw f(),e}}let l9=new class{hardware;overrides=new Map;listeners=new Set;captureListeners=new Set;snapshot={brightness:1,keepScreenOn:!1,screenRecordDisabled:!1};constructor(e=nL){this.hardware=e,this.updateSnapshot(),e.subscribe("screen",()=>this.updateSnapshot())}getSnapshot=()=>this.snapshot;subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));subscribeCapture=e=>(this.captureListeners.add(e),()=>this.captureListeners.delete(e));capture(){for(let e of this.captureListeners)e();return{protected:this.snapshot.screenRecordDisabled}}set(e,t){let r=this.overrides.get(e);this.overrides.delete(e),this.overrides.set(e,{...r,...t}),this.updateSnapshot()}release(e){this.overrides.delete(e),this.updateSnapshot()}updateSnapshot(){let e=this.hardware.getScreen().brightness,t=!1,r=!1;for(let i of this.overrides.values())i.background||(e=i.brightness??e),void 0!==i.keepScreenOn&&(t||=!i.background&&i.keepScreenOn),r=i.screenRecordDisabled??r;if(e!==this.snapshot.brightness||t!==this.snapshot.keepScreenOn||r!==this.snapshot.screenRecordDisabled)for(let i of(this.snapshot={brightness:e,keepScreenOn:t,screenRecordDisabled:r},this.listeners))i()}};function l7(e){var t,r;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nL,n={...e,packageInfo:(null==e?void 0:e.packageInfo)??(null==e||null==(r=e.navigation)||null==(t=r.getPackageInfo)?void 0:t.call(r)),globalProps:{...null==e?void 0:e.globalProps,appTheme:sn(i)}};return Object.fromEntries(["doubao.getSystemInfo","doubao.getAppBaseInfo"].map(e=>{let t=tg[e];return[e,"function"==typeof t.syncResult?t.syncResult(n):t.syncResult]}))}function de(e){return"not determined"===e?e:["denied","restricted","partial","read only"].includes(e)?"denied":"authorized"}function dt(e){var t,r;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nL,n=i.getBluetooth(),a=i.getWifi(),s=Number((null==e||null==(t=e.globalProps)?void 0:t.screenWidth)??window.innerWidth),o=Number((null==e||null==(r=e.globalProps)?void 0:r.screenHeight)??window.innerHeight);return{bluetoothEnabled:n.available&&n.enabled&&n.authorized,locationEnabled:i.getSystem().locationEnabled,wifiEnabled:a.available&&a.enabled,deviceOrientation:s>o?"landscape":"portrait"}}function dr(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nL,r=t.getSystem(),{camera:i,microphone:n,album:a,notification:s,phoneCalendar:o}=r,l=r.bluetoothAuthorization??(t.getBluetooth().authorized?"full":"denied"),d="denied"===oi.getSnapshot().browserAuthorization?"denied":r.locationAuthorization??(t.getBeacon().locationAuthorized?r.locationReducedAccuracy?"foreground approximate":"foreground precise":"denied"),u=d.startsWith("foreground ")||d.startsWith("background ");return{...r.healthData?{healthDataAuthorizationDetail:{readStatus:Object.entries(r.healthData.readStatus).map(e=>{let[t,r]=e;return{type:t,status:r}})}}:{},albumAuthorized:de(a),bluetoothAuthorized:de(l),cameraAuthorized:de(i),locationAuthorized:u?"authorized":de(d),locationReducedAccuracy:u&&d.endsWith("approximate"),microphoneAuthorized:de(n),notificationAuthorized:de(s),notificationAlertAuthorized:r.notificationAlert,notificationBadgeAuthorized:r.notificationBadge,notificationSoundAuthorized:r.notificationSound,phoneCalendarAuthorized:de(o),albumAuthorizationDetail:a,bluetoothAuthorizationDetail:l,cameraAuthorizationDetail:i,locationAuthorizationDetail:d,microphoneAuthorizationDetail:n,notificationAuthorizationDetail:s,phoneCalendarAuthorizationDetail:o}}function di(){throw Error("Simulator UI presenter is unavailable")}let dn="doubao-web-sdk-debugger-vibration-style",da="doubao-web-sdk-debugger-screen-vibrating",ds={heavy:4,light:1,medium:2},dl=0,dd=null;function du(e){e.classList.remove(da),e.style.removeProperty("--doubao-web-sdk-debugger-vibrate-distance"),e.style.removeProperty("--doubao-web-sdk-debugger-vibrate-duration")}function dc(e,t,r){if(!("function"==typeof navigator.vibrate&&navigator.vibrate(e)&&function(){let e=navigator.maxTouchPoints??0;if(e<=0)return!1;let t=navigator.platform??"",r=navigator.userAgent??"";return/android|iphone|ipad|ipod|mobile/i.test(`${t} ${r}`)||/mac/i.test(t)&&e>1}())){let i;(function(){if(document.getElementById(dn))return;let e=document.createElement("style");e.id=dn,e.textContent=`
|
|
30
30
|
@keyframes doubao-web-sdk-debugger-screen-vibrate {
|
|
31
31
|
0%, 100% { transform: translate3d(0, 0, 0); }
|
|
32
32
|
12.5% { transform: translate3d(calc(var(--doubao-web-sdk-debugger-vibrate-distance) * -1), 0, 0); }
|
|
@@ -41,10 +41,11 @@ registerProcessor('doubao-recorder', CaptureProcessor);`;function oI(){var e;ret
|
|
|
41
41
|
.${da} {
|
|
42
42
|
animation: doubao-web-sdk-debugger-screen-vibrate var(--doubao-web-sdk-debugger-vibrate-duration) linear;
|
|
43
43
|
}
|
|
44
|
-
`,document.head.append(e)})(),window.clearTimeout(dl),i=r||(document.body??document.documentElement),dd&&dd!==i&&du(dd),dd=i,du(i),i.style.setProperty("--doubao-web-sdk-debugger-vibrate-distance",`${t}px`),i.style.setProperty("--doubao-web-sdk-debugger-vibrate-duration",`${e}ms`),i.offsetWidth,i.classList.add(da),dl=window.setTimeout(()=>{du(i),dd===i&&(dd=null)},e+50)}}let dp="socketStatusChanged",dh="socketDataReceived",dm=1,dg=new Map;function df(e,t){let r="number"==typeof e?dg.get(e):void 0;if(!r||r.owner!==(null==t?void 0:t.events))throw new w("The socketTaskId doesn't exist",116);return r}function dv(){if(!nD())throw new w(nO,305)}function dy(e,t,r){var i;(null==e?void 0:e.events)?e.events.emitPrivate(t,r):null==e||null==(i=e.emitEvent)||i.call(e,t,r)}function db(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return{ssid:e.ssid,...e.bssid?{bssid:e.bssid.toLowerCase()}:{},...!t&&void 0!==e.secure?{secure:e.secure}:{},...!t&&void 0!==e.signalStrength?{signalStrength:Math.round(e.signalStrength)}:{},...!t&&void 0!==e.frequency?{frequency:e.frequency}:{}}}let dw=new class{hardware;modules=new Map;released=new WeakSet;listeners=new Set;unwatch;lastWifiKey;constructor(e=nL){this.hardware=e}start(e){let t=null==e?void 0:e.events;if(!t||this.released.has(t))throw new w("context is null",102);if(!this.hardware.getWifi().available)throw new w("wifi is not available",103);if(this.modules.has(t))return;this.modules.set(t,()=>{});let r=t.onDestroy(()=>{this.released.add(t),this.stop(t)});if(this.released.has(t))throw new w("context is null",102);this.modules.set(t,r),this.unwatch??=this.hardware.subscribe("wifi",()=>this.publishCurrent())}stop(e){var t,r;e&&(null==(t=this.modules.get(e))||t(),this.modules.delete(e)),0===this.modules.size&&(null==(r=this.unwatch)||r.call(this),this.unwatch=void 0,this.lastWifiKey=void 0)}ensureStarted(e){if((null==e?void 0:e.events)&&this.released.has(e.events))throw new w("context is null",102);if(!(null==e?void 0:e.events)||!this.modules.has(e.events))throw new w("wifi module is not initialized",1401001)}currentNetwork(){let e=this.hardware.getWifi();return e.available&&e.enabled?e.networks.find(t=>ns(t)===e.connectedNetworkKey):void 0}subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));publishCurrent(){if(0===this.modules.size)return;let e=this.currentNetwork();if(!e){this.lastWifiKey=void 0;return}let t=ns(e);if(t!==this.lastWifiKey)for(let r of(this.lastWifiKey=t,this.listeners))r({wifi:db(e)})}};function d_(e,t){if(void 0!==e[t]&&"boolean"!=typeof e[t])throw new w(`${t} must be a boolean`,104)}function dS(e){return{...V(e),platform:sc}}function dx(){var e,t;let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=(null==(e=r.baseAPIRegistry)?void 0:e.fork())??new k(tg);return i.registerMany(function(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t.uiPresenter,i=t.scanCodePresenter;return{"doubao.request":function(e){if(oc.has(e))return e;let t=(t,r)=>{let i=`wsd-request-${++op}`,n=t.params??{},a=function(e){try{return nJ(e)}catch{return}}(n);og({phase:"request",request:a??{headers:{},method:"string"==typeof n.method?n.method.toUpperCase():"GET",url:"string"==typeof n.url?n.url:""},requestId:i,...om()});let s=e=>og({errorText:e,phase:"failure",requestId:i,...om()}),o=e=>((null==e?void 0:e.params.code)===1?og({phase:"response",requestId:i,response:e.params.data,...om()}):s((null==e?void 0:e.params.errMsg)??(null==e?void 0:e.params.msg)??"doubao.request failed"),e),l=e=>{throw s(e instanceof Error?e.message:String(e)),e};try{let i=e(t,r,a);return i instanceof Promise?i.then(e=>o(e),l):o(i)}catch(e){return l(e)}};return oc.add(t),t}(t.requestHandler??(async(e,t,r)=>_(e,await nK(e.params,r)))),...{"doubao.hideKeyboard":(e,t)=>{if((null==t?void 0:t.containerType)&&"PAGE"!==t.containerType)throw new w("hideKeyboard is only supported in page containers",103);let r=s8();return r instanceof HTMLElement&&(!(null==t?void 0:t.element)||s9(r,t.element))&&r.blur(),_(e,{})}},...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;return{"doubao.checkIsOpenAccessibility":(t,r)=>{var i;let n=e.getAccessibility(),a=(null==r||null==(i=r.globalProps)?void 0:i.os)==="iOS";if(!a&&!n.available)throw new w("accessibility service is unavailable",103);return _(t,{open:a?n.voiceOverRunning||n.switchControlRunning:n.androidEnabled&&n.touchExplorationEnabled})}}}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{"doubao.reportEvent":(t,r)=>{var i,n,a,s,o;let l=t.params;if(!rP(l)||"string"!=typeof l.eventName||!rP(l.data))throw new w("eventName must be a string and data must be an object",104);let d=null==r||null==(i=r.getAppletContext)?void 0:i.call(r).viewContext,u=(null==d?void 0:d.appId)??(null==r||null==(n=r.navigation)?void 0:n.getPackageInfo().appId)??(null==(a=e.getAppId)?void 0:a.call(e))??e.appId??(null==r||null==(o=r.globalProps)||null==(s=o.packageInfo)?void 0:s.appId);if("string"!=typeof u||!u||!(null==r?void 0:r.element))throw new w("An application and console target are required to report an event",102);let c={...l.data};"WIDGET"===r.containerType&&(Object.hasOwn(c,"widget_id")||(null==d?void 0:d.widgetId)===void 0||(c.widget_id=d.widgetId),Object.hasOwn(c,"message_id")||(null==d?void 0:d.messageId)===void 0||(c.message_id=d.messageId));let p={appId:u,eventName:l.eventName,data:c,containerType:r.containerType,timestamp:Date.now()};return s_(r.element,{level:"info",label:"analytics",message:`reportEvent ${l.eventName}`,args:[p]}),_(t,{})}}}(t),...function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nL,r=new WeakMap,i=new WeakSet,n={};return Object.fromEntries(["phone","sms"].map(a=>["phone"===a?"doubao.makePhoneCall":"doubao.sendSms",{canIUse:!!e,handler:async(s,o)=>{let l,d=s.params??{};if("object"!=typeof d||Array.isArray(d)||"phone"===a&&"string"!=typeof d.phoneNumber||void 0!==d.phoneNumber&&"string"!=typeof d.phoneNumber||"sms"===a&&void 0!==d.message&&"string"!=typeof d.message)throw new w("phoneNumber and message must be strings",104);let u=(d.phoneNumber??"").trim();if("phone"===a&&!u)throw new w("The phoneNumber parameter should not be empty.",104);let c=t.getCommunication();if(!("phone"===a?c.phoneAvailable:c.smsAvailable))throw new w(`${a} is not available`,103);if(!("phone"===a?c.phoneOpenSucceeds:c.smsOpenSucceeds)||!e)throw new w(`Opening the ${a} panel failed`,102);let p=function(e){let t=(null==e?void 0:e.events)??n,a=r.get(t)??new Set;if(!r.has(t)){var s;r.set(t,a),null==e||null==(s=e.events)||s.onDestroy(()=>{for(let e of(i.add(t),a))e.abort();a.clear()})}if(i.has(t))throw new w("communication view was destroyed",114);return a}(o),h=new AbortController;p.add(h);try{l=e({kind:a,phoneNumber:u,message:d.message??"",sendSucceeds:c.smsSendSucceeds},h.signal).closed}catch(e){throw p.delete(h),new w(e instanceof Error?e.message:String(e),102)}let m=l.finally(()=>p.delete(h));if(m.catch(()=>void 0),"sms"===a){let e;try{e=await m}catch(e){throw new w(e instanceof Error?e.message:String(e),102)}if(h.signal.aborted||"cancel"===e)throw new w("cancel",114);if("failed"===e)throw new w("sendSms failed",102)}return _(s,{})}}]))}(null==r?void 0:r.showCommunication),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sY,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:nL;return Object.fromEntries(["addPhoneCalendar","addPhoneRepeatCalendar"].map(i=>[`doubao.${i}`,{handler:async(n,a)=>{var s,o,l,d;let u=function(e,t){var r,i,n,a;if(!rP(e))throw Error("The calendar event parameter is invalid.");let s=t=>{let r=e[t];if(void 0!==r&&"string"!=typeof r)throw Error(`${t} must be a string`);return r},o=(t,r)=>{let i=e[t]??r;if("number"!=typeof i||!Number.isSafeInteger(i))throw Error(`${t} must be an integer number of seconds`);return i},l=(t,r)=>{let i=e[t]??r;if("boolean"!=typeof i)throw Error(`${t} must be a boolean`);return i},d=(null==(r=s("title"))?void 0:r.trim())??"";if(!d)throw Error("The title parameter should not be empty.");let u=o("startTime"),c=o("endTime",u),p=o("alarmOffset",0);if(u<=0||!Number.isFinite(new Date(1e3*u).getTime()))throw Error("The startTime parameter should be a valid Unix timestamp.");if(c<u||!Number.isFinite(new Date(1e3*c).getTime()))throw Error("The endTime parameter should not be earlier than startTime.");if(p<0)throw Error("The alarmOffset parameter should not be negative.");let h={title:d,startTime:u,endTime:c,allDay:l("allDay",!1),alarm:l("alarm",!0),alarmOffset:p,description:(null==(i=s("description"))?void 0:i.trim())||void 0,location:(null==(n=s("location"))?void 0:n.trim())||void 0,path:(null==(a=s("path"))?void 0:a.trim())||void 0};if(t){let t=(s("repeatInterval")??"month").trim().toLowerCase();if(!["day","week","month","year"].includes(t))throw Error("The repeatInterval parameter should be one of day, week, month, year.");if(h.repeatInterval=t,void 0!==e.repeatEndTime&&(h.repeatEndTime=o("repeatEndTime"),h.repeatEndTime<u||!Number.isFinite(new Date(1e3*h.repeatEndTime).getTime())))throw Error("The repeatEndTime parameter should not be earlier than startTime.")}return h}(n.params,"addPhoneRepeatCalendar"===i),c=(null==a||null==(o=a.getAppletContext)||null==(s=o.call(a).viewContext)?void 0:s.appId)??(null==a||null==(l=a.navigation)?void 0:l.getPackageInfo().appId)??e.appId;if(!c)throw Error("appletId is empty");let p=new AbortController,h=null==a||null==(d=a.events)?void 0:d.onDestroy(()=>p.abort());try{let i=await sJ({appId:c,appIcon:e.appIcon,appName:e.appName,presenter:e.showSimulatorPermission,scope:"scope.addPhoneCalendar",skipDialogIfDenied:!0,signal:p.signal});if(p.signal.aborted)throw Error("calendar view was destroyed");if(!i)throw Error("addPhoneCalendar authorization failed");if(!["full","write only"].includes(r.getSystem().phoneCalendar))throw Error("system calendar permission denied");return t.write(u,c),_(n,{})}finally{null==h||h(),p.abort()}}}]))}(t),...{...t.exitAppFromWidget?{"doubao.exitApp":{handler:async(e,r)=>{var i,n;if(!(null==r||null==(i=r.navigation)?void 0:i.exitApp))throw new w("No active Runtime to exit",102);return r.navigation.exitApp(),await (null==(n=t.exitAppFromWidget)?void 0:n.call(t)),_(e,{})}}}:{},"doubao.openPage":{canIUse:e=>(null==e?void 0:e.containerType)!=="WIDGET"||!!t.openPageFromWidget,handler:(e,r)=>{let i=tg["doubao.openPage"];return("function"==typeof i?i:i.handler)(e,(null==r?void 0:r.containerType)==="WIDGET"?{...r,navigation:{...r.navigation,openPage:t.openPageFromWidget}}:r)}}},"doubao.getDeviceInfo":{handler:(e,t)=>_(e,dS(null==t?void 0:t.globalProps)),syncResult:e=>dS(null==e?void 0:e.globalProps)},"doubao.getNetworkType":{handler:(e,t)=>_(e,of(t)),syncResult:of},"doubao.scanCode":{canIUse:()=>!!i&&"function"==typeof globalThis.BarcodeDetector,handler:async(e,t)=>{var r;if(!i)throw Error("Simulator scan-code presenter is unavailable");let n=new AbortController,a=null==t||null==(r=t.events)?void 0:r.onDestroy(()=>n.abort());try{return _(e,await l8(e.params,i,n.signal))}finally{null==a||a(),n.abort()}}},"doubao.vibrateLong":async e=>(await void dc(400,3,t.vibrationContainer),_(e,{})),"doubao.vibrateShort":async e=>(await function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0,{type:r="medium"}=e;dc(15,ds[r],t)}(e.params,t.vibrationContainer),_(e,{})),...{"doubao.chooseImage":async(e,t)=>_(e,await function(e,t){let r="string"==typeof e.imageId?document.getElementById(e.imageId):null,i=r instanceof HTMLInputElement?r:document.createElement("input"),n=i!==r,a=e.count??9;if(!Number.isInteger(a)||a<1)throw new w("count must be a positive integer",104);if(void 0!==e.sizeType&&(!Array.isArray(e.sizeType)||e.sizeType.some(e=>!["original","compressed"].includes(e))))throw new w("sizeType must contain original or compressed",104);i.type="file",i.accept="image/*",i.multiple=a>1;let s=Array.isArray(e.sourceType)?e.sourceType:[];return i.capture=s.includes("album")?"":s.includes("user")?"user":s.some(e=>"camera"===e||"environment"===e)?"environment":"",i.style.display="none",i.value="",n&&document.body.append(i),new Promise((r,s)=>{var o;let l=!1,d=()=>void 0,u=()=>{i.removeEventListener("change",p),i.removeEventListener("cancel",h),d(),n&&i.remove()},c=e=>{l||(l=!0,u(),s(e))},p=async()=>{let n,s=Array.from(i.files??[]).slice(0,a);if(0===s.length)return void h();try{n=await Promise.all(s.map(async r=>{var i;let n=await new Promise((e,t)=>{let i=new FileReader;i.onload=()=>e(String(i.result)),i.onerror=()=>t(i.error??Error("Failed to read media file")),i.readAsDataURL(r)}),a=(null==(i=e.sizeType)?void 0:i.length)===1&&"compressed"===e.sizeType[0],s=a?(await s5({src:n},t)).tempFilePath:n;return{path:s,size:a?atob(s.slice(s.indexOf(",")+1)).length:r.size,type:a?"image/jpeg":r.type,originalFileObj:r}}))}catch(e){c(e);return}l||(l=!0,u(),r({tempFilePaths:n.map(e=>e.path),tempFiles:n}))},h=()=>{c(new w("chooseImage was cancelled",114))};if(d=(null==t||null==(o=t.events)?void 0:o.onDestroy(h))??d,l)return void d();i.addEventListener("change",p,{once:!0}),i.addEventListener("cancel",h,{once:!0});try{i.click()}catch(e){c(e)}})}(e.params,t)),...(e=t.imagePreviewController)?{"doubao.previewImage":async(t,r)=>{var i;let n=t.params;return(null==(i=n.urls)?void 0:i.some(nq))&&nU(),e.previewImage({...n,urls:n.urls?await Promise.all(n.urls.map(e=>rV(e,r))):n.urls,current:"string"==typeof n.current?await rV(n.current,r):n.current}),_(t,{})}}:{},"doubao.getImageInfo":async(e,t)=>{let r=e.params;if("string"!=typeof r.src||!r.src)throw new w("src must be a non-empty string",104);let i=await rV(r.src,t),n=await (nq(i)?nB(e=>td({src:i},e)):td({src:i}));return n.path=r.src,_(e,n)},"doubao.compressImage":async(e,t)=>_(e,await s5(e.params,t)),"doubao.saveImageToPhotosAlbum":async(e,t)=>(await s6(e.params,t),_(e,{}))},...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:sx,t=new WeakMap;return{"doubao.createInnerAudioContext":{canIUse:sC,handler:async(r,i)=>{let n=rP(r.params)?r.params:{},a="string"==typeof n.audioId?n.audioId.trim():"";try{var s,o,l,d;if(!a)throw new sE(-2008,"inner audio audioId is empty");let u=(null==i||null==(s=i.navigation)?void 0:s.getPackageInfo().appId)??(null==i||null==(l=i.globalProps)||null==(o=l.packageInfo)?void 0:o.appId);if("string"!=typeof u||!u)throw new sE(-2001,"inner audio appletId is empty");let c=null==i?void 0:i.applicationLifecycle,p=(null==c?void 0:c.owner)??(null==i?void 0:i.events);if(!p||!i||!sC())throw new sE(-2010,"inner audio runtime is unavailable");let h=t.get(p);if(!h){h={instances:new Map,destroyed:!1},t.set(p,h);let e=()=>{for(let e of(h.destroyed=!0,h.instances.values()))e.destroy();h.instances.clear()};c?(c.signal.addEventListener("abort",e,{once:!0}),c.signal.aborted&&e()):null==(d=i.events)||d.onDestroy(e)}if(h.destroyed)throw new sE(-2010,"inner audio runtime is unavailable");let m=n.action??"create",g=h.instances.get(a);if("create"===m)return g??=new sN(a,u,i,void 0,!0,e),h.instances.set(a,g),_(r,g.snapshot());if("destroy"===m)return null==g||g.destroy(),h.instances.delete(a),_(r,{});if(!g)throw new sE(-2002,"inner audio instance not found");switch(m){case"get_state":return _(r,g.snapshot());case"set_state":await g.update(rP(n.state)?n.state:{});break;case"play":await g.play();break;case"pause":g.pause();break;case"stop":g.stop();break;case"seek":g.seek(n.position);break;default:throw new sE(-2011,"inner audio action is invalid")}return _(r,{})}catch(n){let e=n instanceof sE?n:new sE(-2007,"inner audio play failed"),t=[-2003,-2004,-2008,-2011,-2012].includes(e.errCode)?104:-2002===e.errCode?203:102,i=S(r,e.message,t);return i.params.data={audioId:a,errCode:e.errCode,errMsg:e.message},i}}}}}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:sP;return{"doubao.getBackgroundAudioManager":{canIUse:sA,handler:async(t,r)=>{try{if(!r)throw new sE(-1008,"background audio runtime is unavailable");e.attach(r);let s=rP(t.params)?t.params:{},o=s.action??"get_state";if("get_state"===o){var i,n,a;return _(t,{...e.getSnapshot(),appletId:(null==(i=r.navigation)?void 0:i.getPackageInfo().appId)??(null==(a=r.globalProps)||null==(n=a.packageInfo)?void 0:n.appId)})}return"set_state"===o?e.update(rP(s.state)?s.state:{}):await e.control(String(o),s.position),_(t,{})}catch(n){let e=sj(n),r=[-1001,-1006,-1007].includes(e.errCode)?104:102,i=S(t,e.errMsg,r);return i.params.data=e,i}}}}}(),...function(){let e=new WeakMap,t={tasks:new Map,destroyed:!1},r=new Set;function i(r){let i=null==r?void 0:r.events;if(!i)return t;let n=e.get(i);if(!n){n={tasks:new Map,destroyed:!1},e.set(i,n);let t=n;i.onDestroy(()=>{for(let e of(t.destroyed=!0,t.tasks.values()))e.cancel()})}return n}function n(e){return async(t,n)=>{let a,s=t.params??{},o=e?"uploadFile":"downloadFile",l=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;return new w(`${o}:fail ${e}`,t)},d=e?"uploadTaskId":"downloadTaskId",u=s[d];try{a=new URL("string"==typeof s.url?s.url.trim():"")}catch{throw l("url is invalid",e?121999:-1)}if(!["http:","https:"].includes(a.protocol))throw l("url is invalid",e?121999:-1);if("string"!=typeof u||!u.trim())throw l(`${d} is invalid`,e?121999:-1);if(e&&("string"!=typeof s.name||!s.name.trim()))throw l("name is required",121999);if(e&&!0===s.enableProfile)throw l("enableProfile is not supported",121992);if(nF(s.url,e?"upload":"download"),!e&&null!=s.filePath&&""!==s.filePath){if("string"!=typeof s.filePath)throw l("filePath must be appletfile://temp or appletfile://user");eD(s.filePath)}let c=i(n);if(c.destroyed)throw l("abort",e?121905:-1);let p=`${o}:${u}`;if(c.tasks.has(p))throw l(`${d} already exists`);if(!e&&r.size>=10)throw l("exceed max download connection count 10");if(!nD())throw l(nO,e?121985:-1);let h=new XMLHttpRequest;return _(t,await new Promise((t,i)=>{let o,m,g=!1,f=0,v=(e,t)=>{if(!g&&!c.destroyed){var r;null==n||null==(r=n.events)||r.emitPrivate(e,{[d]:u,...t})}},y=(e,n)=>{g||(g=!0,null==w||w(),c.tasks.delete(p),r.delete(b),h.onreadystatechange=null,h.onprogress=null,h.onload=h.onerror=h.ontimeout=h.onabort=null,e?i(e):t(n??{}))},b={cancel:()=>{y(l("abort",e?121905:-1)),h.abort()}},w=n$(()=>{y(l(nO,e?121985:-1)),h.abort()});c.tasks.set(p,b),e||r.add(b);let _=()=>{if(!o&&h.readyState>=2&&h.status>0)try{let t=h.getResponseHeader(s2);if(200!==h.status||!t)throw l("network error",e?121991:-1);o=JSON.parse(decodeURIComponent(t)),v(e?"uploadFileHeadersReceived":"downloadFileHeadersReceived",{header:o.header})}catch(e){y(e instanceof Error?e:l(String(e))),h.abort()}},S=()=>{if(!g&&!(h.readyState<2)&&0!==h.status)try{let e;if(200!==h.status||"application/x-ndjson"!==h.getResponseHeader("content-type"))throw l("network error",121991);let t=h.responseText;for(;!g&&-1!==(e=t.indexOf("\n",f));){let r=JSON.parse(t.slice(f,e));switch(f=e+1,r.type){case"progress":v("uploadFileProgressUpdate",{progress:Math.min(100,Math.floor(100*r.totalBytesSent/r.totalBytesExpectedToSend)),totalBytesSent:r.totalBytesSent,totalBytesExpectedToSend:r.totalBytesExpectedToSend});break;case"headers":o={statusCode:r.statusCode,header:r.header},v("uploadFileHeadersReceived",{header:r.header});break;case"result":m=r.data;break;case"error":throw l(r.message,121991);default:throw l("invalid upload response",121991)}}}catch(e){y(e instanceof Error?e:l(String(e),121991)),h.abort()}};h.onreadystatechange=e?S:_,h.onprogress=e?S:e=>{if(e.loaded>0xc800000||e.total>0xc800000){y(l("size exceeds 200MB")),h.abort();return}v("downloadProgressUpdate",{progress:e.lengthComputable&&e.total>0?Math.min(100,Math.floor(100*e.loaded/e.total)):0,totalBytesWritten:e.loaded,totalBytesExpectedToWrite:e.lengthComputable?e.total:-1})},h.onerror=()=>y(l(nD()?"network error":nO,e?nD()?121991:121985:-1)),h.ontimeout=()=>y(l("timeout",e?121920:-1)),h.onabort=()=>y(l("abort",e?121905:-1)),h.onload=async()=>{if(!g&&(e?S():_(),!g))try{if(!o)throw l("network error",e?121991:-1);let t=o;if(e){if(void 0===m||f!==h.responseText.length)throw l("incomplete upload response",121991);y(void 0,{...t,data:m});return}let r=new Uint8Array(h.response);if(r.length>0xc800000)throw l("size exceeds 200MB");let i="string"==typeof s.filePath&&s.filePath?s.filePath:`appletfile://temp/download_${Date.now()}_${++s1}`;await rH(i,r,n),y(void 0,{...t,[s.filePath?"filePath":"tempFilePath"]:i})}catch(e){y(e instanceof Error?e:l(String(e)))}},(async()=>{let t;if(e){let e,r=s.filePath;if("string"!=typeof r||!r)throw l("no file exist",121902);if(!r.startsWith("appletfile:")&&!r.startsWith("data:"))throw l("file path permission denied",121906);try{let t=await rV(r,n);e=await (await fetch(t)).blob()}catch{throw l("no file exist",121902)}if(g)return;for(let[e,r]of(t=new FormData,Object.entries(s.formData??{})))e.trim()&&t.append(e.trim(),s3(r));t.append(s.name,e,r.startsWith("data:")?"upload.bin":decodeURIComponent(r.split("/").pop()??"upload.bin"))}if(g)return;h.open(e?"POST":"GET","/__web_sdk_request_proxy__"),h.responseType=e?"text":"arraybuffer";let r=Number(s.timeout);h.timeout=r>0&&Number.isFinite(r)?Math.min(r,e?0x7fffffff:3e5):e?3e4:6e4;let i={};for(let[t,r]of Object.entries(s.header??{}))["referer","user-agent",...e?["content-type"]:[]].includes(t.trim().toLowerCase())||(i[t.trim()]=s3(r));h.setRequestHeader(s2,encodeURIComponent(JSON.stringify({url:a.href,header:i}))),h.send(t)})().catch(e=>y(e instanceof Error?e:l(String(e))))}))}}function a(e){return(t,r)=>{var n;let a=(t.params??{})[e?"uploadTaskId":"downloadTaskId"];return null==(n=i(r).tasks.get(`${e?"uploadFile":"downloadFile"}:${String(a)}`))||n.cancel(),_(t,{})}}return{"doubao.downloadFile":n(!1),"doubao.abortDownloadFile":a(!1),"doubao.uploadFile":n(!0),"doubao.abortUploadFile":a(!0)}}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL,t=()=>{let{isCharging:t,level:r}=e.getBattery();return{isCharging:t,level:r}};return{"doubao.getBatteryInfo":{handler:e=>_(e,t()),syncResult:t}}}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;return sy({name:"Accelerometer",getSample:e.getAccelerometer})}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;return sy({name:"Gyroscope",getSample:e.getGyroscope})}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;return sf({name:"Compass",readSample:()=>{let{available:t,direction:r,accuracy:i}=e.getCompass();return{available:t,params:{direction:r%360,accuracy:i}}}})}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;return sf({name:"DeviceMotion",readSample:()=>{let{available:t,alpha:r,beta:i,gamma:n}=e.getDeviceMotion(),a=2*Math.PI,s=r%a;return{available:t,params:{alpha:s<0?s+a:s,beta:i,gamma:n}}}})}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:dw;return{"doubao.startWifi":{handler:(t,r)=>(e.start(r),_(t,{}))},"doubao.stopWifi":{handler:(t,r)=>(e.stop(null==r?void 0:r.events),_(t,{}))},"doubao.getConnectedWifi":{handler:(t,r)=>{let i=t.params??{};d_(i,"partialInfo"),e.ensureStarted(r);let n=e.currentNetwork();if(!n)throw new w("wifi is not connected",1401002);return _(t,{wifi:db(n,!0===i.partialInfo)})}},"doubao.getWifiList":{handler:(t,r)=>{e.ensureStarted(r);let i=e.currentNetwork(),n=e.hardware.getWifi(),a=new Map;if(i&&a.set(ns(i),i),n.available&&n.enabled)for(let e of[...n.networks].sort((e,t)=>(t.signalStrength??-1)-(e.signalStrength??-1)))a.set(ns(e),e);return _(t,{wifiList:[...a.values()].map(e=>db(e))})}},"doubao.connectWifi":{handler:(t,r)=>{let i=t.params??{},n=i.bssid;if("string"!=typeof i.ssid||"string"!=typeof i.password||void 0!==n&&"string"!=typeof n)throw new w("ssid and password must be strings",104);if(d_(i,"manual"),d_(i,"partialInfo"),!0===i.manual)return na("network"),_(t,{});if(e.ensureStarted(r),!i.ssid.trim())throw new w("ssid is empty",104);let a=e.hardware.getWifi(),s=a.networks.find(e=>{var t;return e.ssid===i.ssid&&(!n||(null==(t=e.bssid)?void 0:t.toLowerCase())===n.toLowerCase())});if(!a.available||!a.enabled||!s||s.password!==i.password)throw new w("connect wifi failed",1401003);return e.hardware.setWifi({...a,connectedNetworkKey:ns(s)}),_(t,{})}},"doubao.setWifiList":{canIUse:!1,handler:()=>{throw new w("Wi-Fi presets are not supported; configure virtual networks in settings",103)}}}}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:sB,t={openBluetoothAdapter:t=>e.open(t),closeBluetoothAdapter:t=>e.close(t),getBluetoothAdapterState:t=>e.state(t),startBluetoothDevicesDiscovery:(t,r)=>e.startDiscovery(t,r),stopBluetoothDevicesDiscovery:t=>e.stopDiscovery(t),getBluetoothDevices:t=>({devices:e.devices(t)})};for(let r of["createBLEConnection","closeBLEConnection","getConnectedBluetoothDevices","makeBluetoothPair","isBluetoothDevicePaired","getBLEDeviceServices","getBLEDeviceCharacteristics","getBLEDeviceRSSI","getBLEMTU","setBLEMTU","readBLECharacteristicValue","writeBLECharacteristicValue","notifyBLECharacteristicValueChange"])t[r]=(t,i)=>e.gatt(t,r,i);return Object.fromEntries(Object.entries(t).map(t=>{let[r,i]=t;return[`doubao.${r}`,{handler:async(t,r)=>_(t,await i(e.client(null==r?void 0:r.events,r),t.params??{})??{})}]}))}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:sL;return{"doubao.startBeaconDiscovery":{handler:(t,r)=>(e.start(t.params??{},r),_(t,{}))},"doubao.stopBeaconDiscovery":{handler:t=>(e.stop(),_(t,{}))},"doubao.getBeacons":{handler:t=>_(t,e.get())}}}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;return Object.fromEntries(Object.entries({"doubao.getSystemSetting":t=>dt(t,e),"doubao.getAppAuthorizeSetting":t=>dr(t,e)}).map(e=>{let[t,r]=e;return[t,{handler:(e,t)=>_(e,r(t)),syncResult:r}]}))}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;return Object.fromEntries(["doubao.getSystemInfo","doubao.getAppBaseInfo"].map(t=>[t,{handler:(r,i)=>_(r,l7(i,e)[t]),syncResult:r=>l7(r,e)[t]}]))}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:l9,t={},r=new WeakSet,i=new WeakSet;function n(n){let a=(null==n?void 0:n.events)??t;if(!r.has(a)){var s,o;r.add(a);let t=!0,l=()=>e.set(a,{background:document.hidden||!t}),d=null==n||null==(s=n.events)?void 0:s.onVisibilityChange(e=>{t=e,l()});l(),document.addEventListener("visibilitychange",l),null==n||null==(o=n.events)||o.onDestroy(()=>{i.add(a),document.removeEventListener("visibilitychange",l),null==d||d(),e.release(a)})}if(i.has(a))throw new w("screen view was destroyed",114);return a}return{...Object.fromEntries(["disableUserScreenRecord","enableUserScreenRecord"].map(t=>[`doubao.${t}`,(r,i)=>(e.set(n(i),{screenRecordDisabled:"disableUserScreenRecord"===t}),_(r,{}))])),"doubao.getScreenBrightness":t=>_(t,{value:e.getSnapshot().brightness}),"doubao.setScreenBrightness":(t,r)=>{var i,a;let s=null==(i=t.params)?void 0:i.value;if("number"!=typeof s||!Number.isFinite(s)||s<0||s>1)throw new w("value must be a finite number between 0 and 1",104);if((null==r||null==(a=r.getAppletContext)?void 0:a.call(r).source)==="widget")throw new w("setScreenBrightness is only supported in page containers",103);return e.set(n(r),{brightness:s}),_(t,{})},"doubao.setKeepScreenOn":(t,r)=>{var i;let a=null==(i=t.params)?void 0:i.keepScreenOn;if("boolean"!=typeof a)throw new w("keepScreenOn must be a boolean",104);return e.set(n(r),{keepScreenOn:a}),_(t,{})}}}(),...function(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:oi,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:nL,n=()=>{let t=e;e=void 0,null==t||t.cleanup(),null==t||t.controller.abort(),r.stopLocationUpdates()};return{"doubao.getLocation":async(e,n)=>{var a,s;let o=new AbortController,l=null==n||null==(a=n.events)?void 0:a.onDestroy(()=>o.abort());try{let a=await od(t,r,n,o.signal);if(o.signal.aborted)return os(e,114,"operation cancelled");if(!a)return os(e,107,"user permission denied",107);let l=ol(i);if("location_permission_denied"===l)return os(e,106,"system permission denied",106);if(l)return os(e,102,l,102);let d=await r.requestLocation(oa(e.params));return"success"===d.status?_(e,{latitude:(s=d.location).latitude,longitude:s.longitude,timestamp:String(Math.trunc(s.timestamp)),speed:s.speed,accuracy:s.accuracy}):oo(e,d)}finally{null==l||l(),o.abort()}},"doubao.chooseLocation":{canIUse:!1,handler:async e=>await od(t,r)?S(e,on):S(e,"user permission denied")},"doubao.openLocation":{canIUse:!1,handler:async e=>await od(t,r)?S(e,on):S(e,"user permission denied")},"doubao.startLocationUpdate":async(a,s)=>{var o,l,d;let u=a.params,c=null==u?void 0:u.type;if(void 0!==c&&"gcj02"!==c&&"wgs84"!==c)return os(a,104,"type must be gcj02 or wgs84");if((null==e?void 0:e.pending)||r.isUpdating)return os(a,118,"already exists");n();let p=new AbortController,h={controller:p,pending:!0,cleanup:()=>{}};e=h;let m=()=>{e===h&&n()},g=(null==s||null==(o=s.applicationLifecycle)?void 0:o.signal)??(null==s?void 0:s.signal);g?(g.addEventListener("abort",m,{once:!0}),h.cleanup=()=>g.removeEventListener("abort",m),g.aborted&&m()):h.cleanup=(null==s||null==(l=s.events)?void 0:l.onDestroy(m))??(()=>{});let f=!1;try{let e=await od(t,r,s,p.signal);if(p.signal.aborted)return os(a,114,"operation cancelled");if(!e)return os(a,107,"user permission denied",107);if(ol(i)||"denied"===r.getSnapshot().browserAuthorization)return os(a,106,"system permission denied",106);if("manual"!==r.getSnapshot().source&&("u"<typeof navigator||"function"!=typeof(null==(d=navigator.geolocation)?void 0:d.watchPosition)))return os(a,103,"location updates not supported");let n=await r.startLocationUpdates(oa(),{type:c??"gcj02",signal:p.signal});if(p.signal.aborted)return os(a,114,"operation cancelled");if("success"!==n.status)return oo(a,n);return f=!0,_(a,{})}catch(e){if(p.signal.aborted)return os(a,114,"operation cancelled");throw e}finally{e===h&&(h.pending=!1,f||n())}},"doubao.stopLocationUpdate":e=>(n(),_(e,{}))}}(t),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.presenter??{hideLoading:di,hideToast:di,showActionSheet:async()=>di(),showBottomSheet:async()=>di(),showLoading:di,showModal:async()=>di(),showToast:di};return Object.fromEntries(Object.entries({"applet.showToast":e=>(t.showToast(e.params),_(e,{})),"doubao.hideToast":e=>(t.hideToast(),_(e,{})),"doubao.showLoading":e=>(t.showLoading(),_(e,{})),"doubao.hideLoading":e=>(t.hideLoading(),_(e,{})),"doubao.showModal":async e=>_(e,await t.showModal(e.params)),"doubao.showActionSheet":async e=>_(e,await t.showActionSheet(e.params)),"doubao.showBottomSheet":async e=>_(e,await t.showBottomSheet(e.params))}).map(t=>{let[r,i]=t;return[r,{handler:i,canIUse:!!e.presenter}]}))}({presenter:r}),...{"doubao.connectSocket":(e,t)=>_(e,function(e,t){var r;let i,n;if("string"!=typeof e.url||!e.url)throw new w("url must be a non-empty string",104);nF(e.url,"socket");try{i=new URL(e.url.trim())}catch{throw new w("invalid socket url",104)}if(!["ws:","wss:"].includes(i.protocol)||void 0!==e.protocols&&(!Array.isArray(e.protocols)||e.protocols.some(e=>"string"!=typeof e)))throw new w("invalid socket url or protocols",104);if(Array.from(dg.values()).filter(e=>e.owner===(null==t?void 0:t.events)).length>=5)throw new w("WebSocket connection count exceeds 5",1501001);dv();let a=dm++;try{let e=new URL("/__web_sdk_socket__",location.href);e.protocol="https:"===location.protocol?"wss:":"ws:",n=new WebSocket(e)}catch(t){let e=new w("invalid socket url or protocols",104);throw e.cause=t,e}let s={socket:n,owner:null==t?void 0:t.events,opened:!1,cancel:(e,r)=>{l(),n.close(),dy(t,dp,{socketTaskId:a,status:"closed",code:e,reason:r,protocolType:c})}};dg.set(a,s);let o=!1,l=()=>{o=!0,dg.delete(a),d(),null==u||u()},d=n$(()=>{o||(l(),n.close(),dy(t,dp,{socketTaskId:a,status:s.opened?"closed":"failed",code:1006,reason:nO,errMsg:nO,protocolType:n.protocol}))}),u=null==t||null==(r=t.events)?void 0:r.onDestroy(()=>{l(),n.close(1e3)}),c="";return n.addEventListener("open",()=>{if(!o){var t;n.send(JSON.stringify({url:i.href,header:e.header,protocols:null==(t=e.protocols)?void 0:t.map(e=>e.trim()).filter(Boolean)}))}}),n.addEventListener("message",e=>{if(!o)try{let r=JSON.parse(e.data);if("open"===r.type)s.opened=!0,c=r.protocol,dy(t,dp,{socketTaskId:a,status:"connected",header:{},protocolType:c});else if("message"===r.type){let e=r.binary?Uint8Array.from(atob(r.data),e=>e.charCodeAt(0)).buffer:r.data;"string"==typeof e?dy(t,dh,{socketTaskId:a,data:e,dataType:"string"}):e instanceof ArrayBuffer&&dy(t,dh,{socketTaskId:a,data:ob(e),dataType:"base64"})}else("close"===r.type||"error"===r.type)&&(l(),dy(t,dp,{socketTaskId:a,status:"close"===r.type?"closed":"failed",code:r.code,reason:r.reason,errMsg:r.message,protocolType:c}))}catch{n.close()}}),n.addEventListener("close",()=>{o||(l(),dy(t,dp,{socketTaskId:a,status:s.opened?"closed":"failed",code:1006,reason:"WebSocket bridge disconnected",protocolType:c}))}),n.addEventListener("error",()=>{o||(l(),n.close(),dy(t,dp,{socketTaskId:a,status:"failed",errMsg:"WebSocket error",protocolType:n.protocol}))}),{socketTaskId:a}}(e.params,t)),"doubao.sendSocketData":(e,t)=>(!function(e,t){let r;if(!["string","base64"].includes(e.dataType)||"string"!=typeof e.data)throw new w("unsupported dataType or data",104);let i=e.socketTaskId;try{r="base64"===e.dataType?Uint8Array.from(atob(e.data.replace(/[^A-Za-z0-9+/=]/g,"")),e=>e.charCodeAt(0)).buffer:e.data}catch(t){let e=new w("invalid base64 data",104);throw e.cause=t,e}!function(e,t){let{socket:r,opened:i}=df(e.socketTaskId,t),n=e.data;if("string"!=typeof n&&!(n instanceof ArrayBuffer))throw new w("data must be a string or ArrayBuffer",104);if(dv(),!i||1!==r.readyState)throw new w("WebSocket is not open",1501002);try{r.send(JSON.stringify({type:"send",binary:n instanceof ArrayBuffer,data:n instanceof ArrayBuffer?ob(n):n}))}catch(t){let e=new w("Failed to send WebSocket data",305);throw e.cause=t,e}}({socketTaskId:i,data:r},t)}(e.params,t),_(e,{})),"doubao.closeSocket":(e,t)=>(!function(e,t){let r=df(e.socketTaskId,t),{socket:i}=r,n=e.code??1e3;if(!Number.isInteger(n)||!(n>=1e3&&n<=1014&&![1004,1005,1006].includes(n)||n>=3e3&&n<=4999)||void 0!==e.reason&&("string"!=typeof e.reason||new TextEncoder().encode(e.reason).byteLength>123))throw new w("invalid close code or reason",104);if(!r.opened)return r.cancel(n,e.reason);try{i.send(JSON.stringify({type:"close",code:n,reason:e.reason}))}catch(t){let e=new w("Failed to close WebSocket",305);throw e.cause=t,e}}(e.params,t),_(e,{}))},...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{"doubao.requestOrder":t=>lG(t,async()=>{let r=await lO.SandboxRequestOrder({app_key:lW(e),data:lH(t.params,"data"),db_authorization:lH(t.params,"dbAuthorization")});return r.err_code||!r.order_id?lV(t,r,o5):_(t,{orderId:r.order_id,logId:r.log_id||""})}),"doubao.getOrderPayment":t=>lG(t,async()=>{var r,i;let n=lH(t.params,"orderId"),a=await lO.SandboxGetOrderPayment({app_key:lW(e),aweme_bind_status:!0,order_id:n,platform_signed_pt_code:null==(i=t.params)||null==(r=i.platformSignedPtCode)?void 0:r.trim()});if(a.err_code||!a.pay_data)return lV(t,a,oH);try{await lJ(a.pay_data,e)}catch(e){return lV(t,a,oH,!1,e)}return _(t,{orderId:n,logId:a.log_id||""})}),"doubao.getOrderPaymentWithSign":t=>lG(t,async()=>{let r=lH(t.params,"orderId"),i=await lO.SandboxGetOrderPaymentWithSign({app_key:lW(e),aweme_bind_status:!0,order_id:r,sign_data:lH(t.params,"signData"),sign_db_authorization:lH(t.params,"signDbAuthorization")});if(i.err_code||!i.pay_data)return lV(t,i,oV);try{await lJ(i.pay_data,e)}catch(e){return lV(t,i,oV,!1,e)}return _(t,{orderId:r,logId:i.log_id||""})}),"doubao.getPlatformSignInfo":e=>_(e,{signInfo:""}),"doubao.createSignOrder":t=>lG(t,async()=>{let r=await lO.SandboxCreateSignOrder({app_key:lW(e),data:lH(t.params,"data"),db_authorization:lH(t.params,"dbAuthorization")});return r.err_code||!r.auth_order_id?lV(t,r,li):_(t,{authOrderId:r.auth_order_id,logId:r.log_id||""})}),"doubao.sign":t=>lG(t,async()=>{let r=await lO.SandboxGetSignPageData({app_key:lW(e),auth_order_id:lH(t.params,"orderId"),aweme_bind_status:!0});return r.err_code||!r.data?lV(t,r,lc,!0):_(t,{})},!0),"doubao.login":async t=>_(t,{code:await lK(e)}),"doubao.loginWithDoubaoWidget":e=>_(e,{result:!0}),"doubao.postLoginResult":async t=>{var r,i,n,a;let s,o=t.params;if(!1===o.result)return null==(n=e.onPrivacyLoginCardClose)||n.call(e,"login"),await (null==(a=e.onGrantingCompleted)?void 0:a.call(e,"login",{noLogin:!0})),_(t,{});let l=o.code;if(!l)throw new lm(oL);try{s=await lO.SandboxApiExchangeCode({app_key:lW(e),code:l,version_tag:lj})}catch(e){throw lN(e,"login")}return lA(s,"login"),null==(r=e.onPrivacyLoginCardClose)||r.call(e,"login"),await (null==(i=e.onGrantingCompleted)?void 0:i.call(e,"login")),_(t,{})},"doubao.getPrivacySetting":async t=>{var r;let i;try{i=await lO.SandboxApiCheckPrivacyOrLoginStatus({app_key:lW(e),check_type:1,version_tag:lj})}catch(e){throw lN(e,"privacy")}return lA(i,"privacy"),_(t,{needAuthorization:(null==(r=i.data)?void 0:r.PrivacyAgreed)===!1})},"applet.agreePrivacyAuthorization":async t=>{var r,i;let n;try{n=await lO.SandboxApiAcceptPrivacy({app_key:lW(e)})}catch(e){throw lN(e,"privacy")}return lA(n,"privacy"),null==(r=e.onPrivacyLoginCardClose)||r.call(e,"privacy"),await (null==(i=e.onGrantingCompleted)?void 0:i.call(e,"privacy")),_(t,{result:!0})},"applet.getPhoneNumber":async t=>_(t,{code:await lK(e,"profile","user_info,mobile"),message:"success"}),"applet.openLoginPage":t=>{var r,i;let n=null==(r=t.params)?void 0:r.url;return n&&(null==(i=e.onCustomLoginNavigate)||i.call(e,n)),_(t,{})},"applet.closePrivacyLoginCard":t=>{var r,i;return null==(i=e.onPrivacyLoginCardClose)||i.call(e,(null==(r=t.params)?void 0:r.type)||""),_(t,{})},"applet.reportAppLog":e=>_(e,{}),"applet.open":e=>{var t;let r=null==(t=e.params)?void 0:t.schema;return r&&window.open(r,"_blank","noopener,noreferrer"),_(e,{})},"doubao.__debuggerUpdateSandboxBusinessInfo":async e=>{let t=e.params,r=t.csrPem,i=t.locationInfo;return _(e,await lZ({csrPem:r,locationInfo:i,phoneNum:t.phoneNum||""}))},...e.onCustomLoginNavigate?{"doubao.navigateTo":t=>{var r,i;let n=null==(r=t.params)?void 0:r.url;return n&&(null==(i=e.onCustomLoginNavigate)||i.call(e,n)),_(t,{})}}:{}}}(t),...function(){var e;let t,r,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{"doubao.openSetting":{canIUse:!!i.showSimulatorPermissionSettings,handler:async(e,t)=>{var r,n;let a=null==(r=e.params)?void 0:r.withSubscriptions;if(!0===a)return S(e,"subscription templates are not supported yet");if(void 0!==a&&!1!==a)return S(e,"withSubscriptions must be a boolean",104);let s=i.showSimulatorPermissionSettings;if(!s)return S(e,"settings presenter is unavailable");let o=i.appId||"unknown-app";if(oC.has(o))return S(e,"openSetting is already in progress");oC.add(o);let l=new AbortController,d=null==t||null==(n=t.events)?void 0:n.onDestroy(()=>l.abort()),u=sV(o);try{return await new Promise((e,t)=>{let r=()=>t(Error("settings view was destroyed"));(l.signal.addEventListener("abort",r,{once:!0}),l.signal.aborted)?r():s({appId:o,appIcon:i.appIcon,appName:i.appName||"应用插件",authSetting:u,signal:l.signal,onChange:(e,t)=>{!l.signal.aborted&&Object.hasOwn(u,e)&&(sG(o,e,t?"granted":"denied"),oi.isLocationScope(e)&&oi.updateUserAuthorization(t))}}).then(e,t)}),_(e,{authSetting:sV(o)})}finally{null==d||d(),l.abort(),oC.delete(o)}}},"doubao.getSetting":e=>{var t;let r=null==(t=e.params)?void 0:t.withSubscriptions;return!0===r?S(e,"subscription templates are not supported yet",103):void 0!==r&&!1!==r?S(e,"withSubscriptions must be a boolean",104):_(e,{authSetting:sV(i.appId||"unknown-app")})},"doubao.authorize":async(e,t)=>{var r,n,a;let s=null==(r=e.params)?void 0:r.scope;if("scope.healthData"===s){let t=nL.getSystem().healthData;if(!t)return S(e,"Health data simulation is not configured",103);let r=null==(a=e.params.options)?void 0:a.types;return!Array.isArray(r)||0===r.length||r.some(e=>"string"!=typeof e||!e.trim())?S(e,"options.types must be a non-empty supported health data type list",104):t.requestCompleted?_(e,{}):S(e,"Health data authorization failed",102)}if("string"!=typeof s||!oE.has(s)||void 0!==i.declaredScopes&&!i.declaredScopes.includes(s))return S(e,`invalid scope: ${String(s)}`,104);let o=new AbortController,l=null==t||null==(n=t.events)?void 0:n.onDestroy(()=>o.abort());try{let r=await oT(i,s,!1,t,o.signal);if(o.signal.aborted)return S(e,"operation cancelled",114);if(!r)return S(e,"user permission denied",107);return oN(s)?S(e,"system permission denied",106):_(e,{})}finally{null==l||l(),o.abort()}},...(e=async(e,t)=>{if(oN("scope.record"))throw new w("system permission denied",106);let r=await oT(i,"scope.record",!1,e,t);if(oN("scope.record"))throw new w("system permission denied",106);return r},r=!1,{"doubao.operateRecorder":{canIUse:oI,handler:async(i,n)=>{let a=i.params;switch(a.operationType){case"start":{var s;if(r)throw new w("recorder is starting",104);r=!0;let i=new AbortController,o=null==n||null==(s=n.events)?void 0:s.onDestroy(()=>i.abort());try{let r=await e(n,i.signal);if(i.signal.aborted)throw new w("operation cancelled",114);if(!r)throw new w("user permission denied",102);null==t||t.destroy(),t=new ok(a,n),await t.start()}finally{null==o||o(),i.abort(),r=!1}break}case"pause":case"resume":case"stop":if(!t)throw new w("recorder is not started",104);await t[a.operationType]();break;default:throw new w("invalid recorder operation",104)}return _(i,{})}}})}}(t),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{"doubao.sendFollowUpMessage":async t=>{if(!e.sendFollowUpMessage)throw Error("sendFollowUpMessage is not configured in web-sdk-debugger");return await e.sendFollowUpMessage(function(e){let t=e.content;if(!Array.isArray(t)||0===t.length)throw Error("content must be a non-empty array");let r=!1;for(let e of t){if(!rP(e))throw Error("content items must be objects");if("text"===e.type){if("string"!=typeof e.text)throw Error("text content must be a string");r||=!!e.text.trim();continue}if("api/call"===e.type){if(!rP(e.data)||"string"!=typeof e.data.name||!e.data.name.trim()||!rP(e.data.arguments))throw Error("api/call content must include a name and arguments object");continue}if("responseHint"===e.type){if(!rP(e.data)||void 0!==e.data.userAction&&"string"!=typeof e.data.userAction||void 0!==e.data.responseGuidance&&"string"!=typeof e.data.responseGuidance)throw Error("responseHint content must include valid string guidance fields");continue}throw Error('content type must be "text", "api/call", or "responseHint"')}if(!r)throw Error("content must include a non-empty text message");return{content:t}}(t.params)),_(t,{})},"doubao.multiMediaBroadcast":async t=>_(t,await s0(function(e){if("play"!==e.action&&"pause"!==e.action)throw Error('action must be "play" or "pause"');return{action:e.action,mediaId:"string"==typeof e.mediaId&&e.mediaId.trim()?e.mediaId.trim():void 0}}(t.params),e.multiMediaBroadcastContainer))}}(t)}}({...r,requestHandler:r.requestHandler??(null==(t=r.baseAPIRegistry)?void 0:t.get("doubao.request"))}),{override:!0}),i.registerEventSources({...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;return{"doubao.onBatteryInfoChange":t=>{let r=e.getBattery().isLowPowerModeEnabled;return e.subscribe("battery",()=>{let{isLowPowerModeEnabled:i}=e.getBattery();r!==i&&(r=i,t({isLowPowerModeEnabled:i}))})}}}(),...sv("Accelerometer"),...sv("Gyroscope"),...sv("Compass"),...sv("DeviceMotion"),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:dw;return{"doubao.onWifiConnected":e.subscribe}}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:sB;return Object.fromEntries([sq,s$,"doubao.onBLEConnectionStateChange","doubao.onBLECharacteristicValueChange"].map(t=>[t,{source:()=>void 0,onSubscribe:(t,r)=>e.wake(t,r)}]))}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL,t=new WeakMap;return{[e1]:{source:()=>void 0,onSubscribe:(r,i)=>{if(t.has(r))return;let n=()=>r.emit(e1,{globalProps:{appTheme:sn(e)},apiResults:{...l7(i,e),"doubao.getSystemSetting":dt(i,e),"doubao.getAppAuthorizeSetting":dr(i,e)}}),a=!1;if(r.onDestroy(()=>{var e;a=!0,null==(e=t.get(r))||e(),t.delete(r)}),a)return;let s=[sa(e,n),e.subscribe("location",n),e.subscribe("system",n),e.subscribe("bluetooth",n),e.subscribe("wifi",n),oi.subscribe(n)];t.set(r,()=>s.forEach(e=>e())),n()}}}}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;return{onThemeChange:t=>{let r=sn(e),i=!0,n=sa(e,()=>{let n=sn(e);n!==r&&(r=n,queueMicrotask(()=>{i&&t({appTheme:n})}))});return()=>{i=!1,n()}}}}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:l9,r=new WeakMap;return Object.fromEntries(["doubao.onUserCaptureScreen","doubao.onUserScreenRecord"].map(i=>[i,{source:()=>void 0,onSubscribe:n=>{let a;"doubao.onUserScreenRecord"===i&&!0===e.getScreen().recording&&n.emit(i,{state:"start"});let s=r.get(n)??new Set;if(s.has(i))return;s.add(i),r.set(n,s);let o="doubao.onUserCaptureScreen"===i?t.subscribeCapture(()=>{t.getSnapshot().screenRecordDisabled||n.emit(i,{})}):(a=e.getScreen().recording,e.subscribe("screen",()=>{let t=e.getScreen().recording;t!==a&&void 0!==t&&n.emit(i,{state:t?"start":"stop"}),a=t}));n.onDestroy(()=>{o(),s.delete(i)})}}]))}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL,t=new WeakSet,r="doubao.onKeyboardHeightChange";return{[r]:{source:()=>void 0,canIUse:e=>!(null==e?void 0:e.containerType)||"PAGE"===e.containerType,onSubscribe:(i,n)=>{let a=null==n?void 0:n.element;if(!a||t.has(i)||n.containerType&&"PAGE"!==n.containerType)return;t.add(i);let s=!1,o=0,l=()=>{if(s)return;let t=s8(),n=s9(t,a)&&t&&"none"!==t.getAttribute("inputmode")&&(t instanceof HTMLTextAreaElement?!t.disabled&&!t.readOnly:t instanceof HTMLInputElement?!t.disabled&&!t.readOnly&&!["button","submit","reset","checkbox","radio","range","color","file","hidden"].includes(t.type):t.matches('[contenteditable="true"], [contenteditable=""]'))?e.getKeyboard().height:0;o!==n&&(o=n,i.emit(r,{height:o}))},d=()=>queueMicrotask(l);a.addEventListener("focusin",l),a.addEventListener("focusout",d);let u=e.subscribe("keyboard",l);l(),i.onDestroy(()=>{s=!0,a.removeEventListener("focusin",l),a.removeEventListener("focusout",d),u(),t.delete(i)})}}}}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;return{"doubao.onNetworkStatusChange":t=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nL,r=oh(t);return t.subscribe("network",()=>{let i=oh(t);(i.isConnected!==r.isConnected||i.networkType!==r.networkType)&&(r=i,e(i))})})(e=>t({isConnected:e.isConnected,networkType:e.networkType}),e)}}(),...Object.fromEntries(["downloadProgressUpdate","downloadFileHeadersReceived","uploadFileProgressUpdate","uploadFileHeadersReceived"].map(e=>[e,()=>void 0])),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:oi,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nL;return Object.fromEntries(["doubao.onLocationChange","doubao.onLocationChangeError"].map(r=>{let i=new WeakMap;return[r,{source:()=>void 0,onSubscribe:n=>{if(i.has(n))return;let a=()=>{let i=ol(t);i&&e.isUpdating&&"doubao.onLocationChangeError"===r&&n.emit(r,{errMsg:i,errCode:"location_service_disabled"===i?102:106})},s=e.subscribeLocation(e=>{var i;let s,o;ol(t)?a():("doubao.onLocationChange"===r&&"success"===e.status&&n.emit(r,{latitude:(i=e.location).latitude,longitude:i.longitude,speed:i.speed,accuracy:i.accuracy,altitude:i.altitude,verticalAccuracy:i.altitudeAccuracy,horizontalAccuracy:i.accuracy}),"doubao.onLocationChangeError"===r&&"success"!==e.status&&n.emit(r,(s="user_unauthorized"===e.status||1===e.code,o="user_unauthorized"!==e.status&&3===e.code,{errMsg:s?"location_permission_denied":o?"location_timeout":"location_fail",errCode:s?"user_unauthorized"===e.status?107:106:o?115:102})))}),o=ol(t),l=t.subscribe("location",()=>{let e=ol(t);e!==o&&(o=e,a())}),d=()=>{s(),l(),i.delete(n)};i.set(n,d),n.onDestroy(d)}}]}))}(),...{[dp]:()=>void 0,[dh]:()=>void 0},...{[ow]:{canIUse:oI,source:()=>void 0}},...{[sk]:{source:()=>void 0,canIUse:sC}},...{[sT]:{source:()=>void 0,canIUse:sA}}},{override:!0}),i}function dI(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{apiRegistry:e.apiRegistry??dx(e),scanCodePresenter:e.scanCodePresenter,uiPresenter:e.uiPresenter}}var dk=r(17228);function dC(e,t,r){var i;null==e||e({category:"mcp",source:"local_mcp",trace_id:null==r||null==(i=r.trace)?void 0:i.trace_id,trace:null==r?void 0:r.trace,...t})}function dE(e){return{name:e.name,description:e.description||"",input_schema_json:r5(e.inputSchema??{type:"object",additionalProperties:!0})}}async function dN(e,t){var r,i,n;null==(r=t.signal)||r.throwIfAborted();let a=new dk.Kj({name:"web-sdk-debugger",version:"0.0.1"},{versionNegotiation:{mode:"auto"}}),s=new dk.jS(new URL(e),{fetch:t.fetcher,requestInit:t.headers?{headers:t.headers}:void 0}),o=()=>{dT(l)},l={client:a,transport:s,removeAbortListener:()=>{var e;return null==(e=t.signal)?void 0:e.removeEventListener("abort",o)}};null==(i=t.signal)||i.addEventListener("abort",o,{once:!0});try{await a.connect(s,{signal:t.signal}),null==(n=t.signal)||n.throwIfAborted()}catch(e){throw await dT(l),e}return l}async function dT(e){e.removeAbortListener(),await e.transport.close().catch(()=>void 0),await e.client.close().catch(()=>void 0)}let dA=new Set(["log","info","warn","error","debug"]);function dM(){return{entries:[],nextEntryId:0}}function dR(e){if(e instanceof Error)return e.stack||e.message;if("string"==typeof e)return e;if(void 0===e)return"undefined";if("function"==typeof e)return e.toString();try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}function dj(e){return"number"==typeof e&&Number.isFinite(e)?Math.max(e-1,0):0}function dP(e){let t=[e.url,e.src,e.getAttribute("url"),e.getAttribute("src")].find(e=>"string"==typeof e&&e.trim());return"string"==typeof t?t.trim():void 0}function dL(e,t){var r;let i=e.trim(),n=i.match(/^(.*):(\d+):(\d+)$/)??i.match(/^(.*):(\d+)$/);if(!n)return null;let[,a,s,o]=n;if(!a)return null;let l=t&&("<anonymous>"===a||a.endsWith(", <anonymous>")||/^eval at\b.*<anonymous>$/.test(a))?t:void 0,d=l&&/\.web\.bundle(?:[?#]|$)/.test(l)?2:0;return{url:l??a,lineNumber:Math.max(dj(Number(s))-d,0),columnNumber:void 0===o?0:"number"==typeof(r=Number(o))&&Number.isFinite(r)?Math.max(r-1,0):0}}function dO(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"!=typeof e)return;let r=e.split("\n").map(e=>(function(e,t){let r=e.trim(),i=r.startsWith("at ")?r.slice(3).trim():r,n=i.match(/^(.*?)\s+\((.*)\)$/);if(n){let[,e,r]=n,i=dL(r,t);return i?{functionName:e,scriptId:"",...i}:null}let a=dL(i,t);return a?{functionName:"",scriptId:"",...a}:null})(e,t.fallbackSourceUrl)).filter(e=>!!e),i=t.dropFirstFrame&&r.length>1?r.slice(1):r,n=i.filter(e=>!(e.url.includes("console-recorder")||e.url.includes("web-sdk-debugger")||/capture.*Stack|console\.(?:log|info|warn|error|debug)/.test(e.functionName))),a=n.length>0?n:i;return a.length>0?{callFrames:a}:void 0}function dD(e){let t=null==e?void 0:e.callFrames[0];return t?{url:t.url,lineNumber:t.lineNumber,columnNumber:t.columnNumber}:void 0}function dU(e){return e?{callFrames:[{functionName:"",scriptId:"",...e}]}:void 0}function dq(e){return e?`[${e}] `:""}class d${target;store;listeners=new Set;constructor(e,t=dM()){this.target=e,this.store=t,this.target.addEventListener("error",this.handleRuntimeError),this.target.addEventListener(sb,this.handleRuntimeConsole),this.drainPendingRuntimeConsoleEvents()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getEntries(){return this.store.entries}clear(){this.store.entries.length=0,this.notify()}evaluate(e){let t=this.getFirstIframeWindow()?"iframe":"host",r=this.getFirstIframeWindow()??window;this.addEntry("eval","eval",`> ${e}`);try{let i=r.eval(e),n=dR(i);return this.addEntry("eval","iframe"===t?"iframe":"eval",n),{ok:!0,value:n}}catch(t){let e=dR(t);return this.addEntry("error","eval",e),{ok:!1,value:e}}}destroy(){this.target.removeEventListener("error",this.handleRuntimeError),this.target.removeEventListener(sb,this.handleRuntimeConsole),this.listeners.clear()}addEntry(e,t,r){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};this.store.entries.push({id:`console-${++this.store.nextEntryId}`,level:e,source:t,timestamp:Date.now(),message:r,...i}),this.store.entries.length>1e3&&this.store.entries.splice(0,this.store.entries.length-1e3),this.notify()}getFirstIframeWindow(){let e=this.target.shadowRoot;if(!e)return null;for(let t of Array.from(e.querySelectorAll("iframe")))try{if(t.contentWindow)return t.contentWindow}catch{break}return null}handleRuntimeError=e=>{let t,r,i,n,a,s=(r=null==(t=e.detail)?void 0:t.error,i=e.currentTarget instanceof HTMLElement?dP(e.currentTarget):void 0,a=dD(n=dO(null==r?void 0:r.stack,{fallbackSourceUrl:i}))??function(e){var t,r,i,n,a,s;if((null==e?void 0:e.fileName)||(null==e?void 0:e.release)||(null==e||null==(t=e.sourceMap)?void 0:t.offset))return{url:e.fileName??e.release??"runtime",lineNumber:dj(null==(i=e.sourceMap)||null==(r=i.offset)?void 0:r.line),columnNumber:"number"==typeof(s=null==(a=e.sourceMap)||null==(n=a.offset)?void 0:n.col)&&Number.isFinite(s)?Math.max(s,0):0}}(t),"string"==typeof(null==r?void 0:r.message)&&r.message?{message:r.message,metadata:{location:a,stackTrace:n??dU(a)}}:{message:dR(r??t??e),metadata:{location:a,stackTrace:n??dU(a)}});this.addEntry("error","runtime",s.message,s.metadata)};handleRuntimeConsole=e=>{let t=e.detail;("string"==typeof(null==t?void 0:t.message)||Array.isArray(null==t?void 0:t.args))&&(e.preventDefault(),this.addRuntimeConsoleEntry(t))};drainPendingRuntimeConsoleEvents(){var e;let t;for(let r of(e=this.target,t=sw.get(e)??[],sw.delete(e),t))this.addRuntimeConsoleEntry(r)}addRuntimeConsoleEntry(e){var t;let r=e.stackTrace??dO(e.stack,{dropFirstFrame:!0,fallbackSourceUrl:dP(this.target)}),i=e.location??dD(r),n="string"==typeof e.message?e.message:(e.args??[]).map(dR).join(" "),a="string"==typeof e.pagePath&&e.pagePath?e.pagePath:void 0,s="string"==typeof e.label&&e.label?e.label:a;this.addEntry((t=e.level,dA.has(t)?t:"log"),"runtime",`${dq(s)}${n}`,{args:function(e,t){if(!e||!t)return e;let r=dq(t).trim(),i="app"===t?"color: #3b82f6":"color: #16a34a",[n,...a]=e;return"string"==typeof n?[`%c%s%c ${n}`,i,r,"",...a]:["%c%s%c",i,r,"",...e]}(e.args??[n],s),location:i,pagePath:a,stackTrace:r??dU(i)})}notify(){for(let e of this.listeners)e()}}let dB="doubao-component",dF="doubao-host-attrs",dz=new Map([["x-view","view"],["x-text","text"],["x-image","image"],["x-list","list"],["x-svg","svg"],["x-textarea","textarea"],["x-input","input"],["x-input-ng","input"],["x-canvas","canvas"],["x-markdown","markdown"]]);function dW(e){return e.getAttribute(dB)||null}function dH(e){let t=e.tagName.toLowerCase();return dW(e)??dz.get(t)??t}function dV(e){return Array.from(e).filter(e=>e&&!e.startsWith("doubao-"))}let dG=new Set(["IFRAME","LINK","SCRIPT","STYLE","TEMPLATE"]),dJ=new Set(["data-wsd-node-id"]),dK=new Set(["part","lynx-default-overflow-visible"]),dZ=new Set(["style","data-wsd-node-id"]);function dX(e){return e.nodeType===Node.ELEMENT_NODE&&!dG.has(e.tagName)}function dY(e){var t;return e.nodeType===Node.TEXT_NODE&&!!(null==(t=e.textContent)?void 0:t.trim())}function dQ(e){return e.nodeType===Node.DOCUMENT_FRAGMENT_NODE?"#shadow-root":e.nodeType===Node.TEXT_NODE?"#text":e.tagName.toLowerCase()}function d0(e){if(!Number.isFinite(e))return"0";let t=Math.round(100*e)/100;return Number.isInteger(t)?String(t):t.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function d1(e){return Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0")}function d2(e){let t=e.trim(),r=Number.parseFloat(t);return Number.isFinite(r)&&0===r?"0":t}function d3(e){let t=Number.parseFloat(e);return Number.isFinite(t)?t:0}function d4(e){var t,r,i;let n=null==(t=e.getAttribute("aria-label"))?void 0:t.trim();if(n)return n;let a=null==(r=e.getAttribute("title"))?void 0:r.trim();if(a)return a;if(e instanceof HTMLImageElement)return e.alt.trim();if(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement){let t=Array.from(e.labels??[]).map(e=>{var t;return null==(t=e.textContent)?void 0:t.replace(/\s+/g," ").trim()}).filter(Boolean).join(" ");if(t)return t}return e instanceof HTMLButtonElement||e instanceof HTMLAnchorElement?(null==(i=e.textContent)?void 0:i.replace(/\s+/g," ").trim())??"":""}function d5(e){var t;let r=null==(t=e.getAttribute("role"))?void 0:t.trim();if(r)return r;switch(e.tagName){case"A":return e.hasAttribute("href")?"link":"generic";case"BUTTON":return"button";case"IMG":return"img";case"INPUT":case"TEXTAREA":return"textbox";case"SELECT":return"combobox";default:return"generic"}}function d6(e){return!e.hasAttribute("disabled")&&"true"!==e.getAttribute("aria-disabled")&&(!!(e.isContentEditable||e instanceof HTMLAnchorElement&&e.hasAttribute("href"))||e.tabIndex>=0)}function d8(e){return Array.from(e.attributes).filter(e=>!dJ.has(e.name)).map(e=>({name:e.name,value:e.value}))}function d9(e){let t=document.createElement("template");return t.innerHTML=e,t.content}function d7(e){return dJ.has(e)||dK.has(e)}function ue(e){return"DIV"===e.tagName&&"page"===e.getAttribute("part")}function ut(e,t){return dJ.has(t)||ue(e)&&d7(t)}function ur(e,t){for(let r of t)ut(e,r.name)||e.setAttribute(r.name,r.value)}function ui(e){return d8(e).filter(t=>!ut(e,t.name))}function un(e,t,r){let i=new Map(t.map(e=>[e.name,e.value])),n=new Map(r.map(e=>[e.name,e.value])),a=r.filter(e=>i.get(e.name)!==e.value),s=t.filter(e=>!n.has(e.name)).map(e=>e.name);return a.length||s.length?[{type:"attributes",nodeId:e,before:t,modified:a,removed:s}]:[]}function ua(e){return Array.from(e.childNodes).filter(e=>dX(e)||dY(e))}function us(e,t,r){let i=("elementFromPoint"in e&&"function"==typeof e.elementFromPoint?e.elementFromPoint.bind(e):document.elementFromPoint.bind(document))(t,r);for(;(null==i?void 0:i.shadowRoot)&&"function"==typeof i.shadowRoot.elementFromPoint;){let e=i.shadowRoot.elementFromPoint(t,r);if(!e||e===i)break;i=e}return i}function uo(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(t>8)return null;let r=null;for(let i of Array.from(e.children)){let e=i.getBoundingClientRect(),n=e.width>0||e.height>0?{rect:e,styleSource:i}:i.shadowRoot&&uo(i.shadowRoot,t+1)||uo(i,t+1);n&&(r=r?{rect:function(e,t){let r=Math.min(e.left,t.left),i=Math.min(e.top,t.top);return new DOMRect(r,i,Math.max(e.right,t.right)-r,Math.max(e.bottom,t.bottom)-i)}(r.rect,n.rect),styleSource:r.styleSource}:n)}return r}function ul(e){let t=e.getBoundingClientRect();return t.width>0||t.height>0?{rect:t,styleSource:e}:e.shadowRoot&&uo(e.shadowRoot)||uo(e)||{rect:t,styleSource:e}}function ud(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement??null;for(;t;){if(dG.has(t.tagName))return!0;t=t.parentElement}return!1}class uu{target;nodeIds=new WeakMap;nodes=new Map;onChange;nextNodeId=0;mutationObserver=null;notifyTimer=null;constructor(e,t){this.target=e,this.onChange=t,this.observe()}getDocument(){let e=this.getRoot();return e?(this.nodes.clear(),this.serializeNode(e,!0)):null}getNode(e){return this.nodes.get(e)??null}getElement(e){let t=this.getNode(e);return t instanceof HTMLElement?t:null}setAttributesAsText(e,t,r){let i=function(e){let t=e.trim();if(!t)return[];let r=document.createElement("template");r.innerHTML=`<div ${t}></div>`;let i=r.content.firstElementChild;return i?d8(i):[]}(t),n=null==r?void 0:r.trim();return this.editElementAttributes(e,e=>{n&&!ut(e,n)&&e.removeAttribute(n),ur(e,i)})}setAttributeValue(e,t,r){let i=t.trim();return i?this.editElementAttributes(e,e=>{if(ut(e,i))return!1;e.setAttribute(i,r)}):[]}removeAttribute(e,t){let r=t.trim();return r?this.editElementAttributes(e,e=>{if(ut(e,r))return!1;e.removeAttribute(r)}):[]}setNodeValue(e,t){return this.runWithoutObservation(()=>{let r=this.getNode(e),i=(null==r?void 0:r.textContent)??"";return(null==r?void 0:r.nodeType)!==Node.TEXT_NODE||i===t?[]:(r.textContent=t,[{type:"characterData",nodeId:e,value:t,previousValue:i}])})}setNodeName(e,t){return this.runWithoutObservation(()=>{let r=this.getElement(e),i=t.trim();if(!r||!i)return{nodeId:null,mutations:[]};if(ue(r))return{nodeId:e,mutations:[]};let n=r.parentNode,a=this.getPreviousInspectableSiblingId(r),s=function(e,t){let r=document.createElement(t);for(let t of Array.from(e.attributes))r.setAttribute(t.name,t.value);for(;e.firstChild;)r.append(e.firstChild);return e.replaceWith(r),r}(r,i);return{nodeId:this.getNodeId(s),mutations:n?[this.getChildListMutation(n,[e],[{previousNodeId:a,node:this.serializeNode(s)}])]:[]}})}setOuterHTML(e,t){return this.runWithoutObservation(()=>{let r=this.getNode(e);if(!r)return[];if(r instanceof DocumentFragment){let e=ua(r).map(e=>this.getNodeId(e)),i=d9(t);return r.replaceChildren(...Array.from(i.childNodes)),[this.getChildListMutation(r,e,this.getInsertedNodeMutations(r,null,ua(r)))]}if(r instanceof Element&&ue(r)){let i=ui(r),n=ua(r).map(e=>this.getNodeId(e));!function(e,t){let r=d9(t),i=r.firstElementChild;if(!i)return e.replaceChildren(...Array.from(r.childNodes));for(let t of Array.from(e.attributes))d7(t.name)||e.removeAttribute(t.name);ur(e,d8(i)),e.replaceChildren(...Array.from(i.childNodes))}(r,t);let a=this.getInsertedNodeMutations(r,null,ua(r));return[...un(e,i,ui(r)),this.getChildListMutation(r,n,a)]}let i=r.parentNode;if(!i)return[];let n=this.getPreviousInspectableSiblingId(r),a=d9(t),s=ua(a);return i.replaceChild(a,r),[this.getChildListMutation(i,[e],this.getInsertedNodeMutations(i,n,s))]})}getNodeIdAtPoint(e,t){let r,i,n=this.getRoot(),a=this.target.shadowRoot,s=(r=null,(i=n=>{for(let a of(dX(n)&&function(e,t,r){let{rect:i}=ul(e);return i.width>0&&i.height>0&&t>=i.left&&t<=i.right&&r>=i.top&&r<=i.bottom}(n,e,t)&&(r=n),Array.from(n.childNodes)))dX(a)&&i(a)})(n),r),o=a?us(a,e,t):us(document,e,t),l=(s&&n.contains(s)?s:null)??(o&&n.contains(o)?o:null);if(!l)return null;let d=l;for(;d&&!dX(d);)d=d.parentNode??function(e){let t=e.getRootNode();return t instanceof ShadowRoot?t.host:null}(d);return d&&n.contains(d)?this.getNodeId(d):null}findLynxViews(){return function(e){let t=[],r=[e];for(;r.length;){let e=r.shift();for(let i of(e instanceof HTMLElement&&"LYNX-VIEW"===e.tagName&&t.push(e),e instanceof Element&&e.shadowRoot&&r.push(e.shadowRoot),e.children??[]))r.push(i)}return t}(this.target)}findNodeIdByLynxUniqueId(e){let t=function(e,t){let r=[e];for(;r.length;){let e=r.shift();if(e instanceof HTMLElement&&function(e){for(let t of Object.getOwnPropertySymbols(e))if("uniqueId"===t.description){let r=e[t];return"number"==typeof r?r:null}return null}(e)===t)return e;for(let t of(e instanceof Element&&e.shadowRoot&&r.push(e.shadowRoot),e.children??[]))r.push(t)}return null}(this.getRoot(),e);return t?this.getNodeId(t):null}getHighlight(e,t){var r,i;let n,a,s,o,l,d,u,c,p,h,m,g,f,v,y=this.getElement(e);if(!y||!y.isConnected)return null;let{rect:b,styleSource:w}=ul(y),_=t.getBoundingClientRect(),S=t.offsetWidth?_.width/t.offsetWidth:1,x=t.offsetHeight?_.height/t.offsetHeight:1,I=b.width/S,k=b.height/x,C=getComputedStyle(w),E=C.backgroundColor.trim(),N=(r=C.paddingTop,i=C.paddingRight,(n=[r,i,C.paddingBottom,C.paddingLeft].map(d2)).every(e=>"0"===e)?null:n.every(e=>e===n[0])?n[0]:n[0]===n[2]&&n[1]===n[3]?`${n[0]} ${n[1]}`:n[1]===n[3]?`${n[0]} ${n[1]} ${n[2]}`:n.join(" "));return{left:(b.left-_.left)/S,top:(b.top-_.top)/x,width:I,height:k,nodeName:dH(y),selector:function(e){let t=e.id.trim();if(dW(e)){let t=(e.getAttribute(dF)??"").split(/\s+/).filter(Boolean).includes("class")?e.firstElementChild:e;return{tagName:dH(e),classNames:dV((null==t?void 0:t.classList)??[])}}return{tagName:dH(e),id:t,classNames:Array.from(e.classList).filter(Boolean)}}(y),boxModel:(a=d3(C.borderTopWidth),s=d3(C.borderRightWidth),o=d3(C.borderBottomWidth),l=d3(C.borderLeftWidth),d=d3(C.paddingTop),u=d3(C.paddingRight),c=d3(C.paddingBottom),p=l+d3(C.paddingLeft),{content:{left:p,top:h=a+d,width:Math.max(0,I-p-s-u),height:Math.max(0,k-h-o-c)}}),dimensions:`${d0(I)} \xd7 ${d0(k)}`,styles:[...E?[{name:"Background",value:(g=(m=E.trim()).match(/^rgb\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*\)$/i),f=m.match(/^rgba\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d?(?:\.\d+)?)\s*\)$/i),(v=g??(f&&1===Number(f[4])?f:null))?`#${d1(Math.round(Number(v[1])))}${d1(Math.round(Number(v[2])))}${d1(Math.round(Number(v[3])))}`:m),swatch:E}]:[],...N?[{name:"Padding",value:N}]:[]],accessibility:{name:d4(y),role:d5(y),keyboardFocusable:d6(y)}}}destroy(){var e;null==(e=this.mutationObserver)||e.disconnect(),this.mutationObserver=null,null!==this.notifyTimer&&(window.clearTimeout(this.notifyTimer),this.notifyTimer=null),this.nodes.clear()}getRoot(){let e=this.target.shadowRoot;return e?e.querySelector('[part="page"]')??e:this.target}getNodeId(e){let t=this.nodeIds.get(e);if(t)return this.nodes.set(t,e),t;let r=`node-${++this.nextNodeId}`;return this.nodeIds.set(e,r),this.nodes.set(r,e),r}editElementAttributes(e,t){return this.runWithoutObservation(()=>{let r=this.getElement(e);if(!r)return[];let i=ui(r);return!1===t(r)?[]:un(e,i,ui(r))})}getPreviousInspectableSiblingId(e){let t=e.parentNode;if(!t)return null;let r=ua(t),i=r.findIndex(t=>t===e),n=i>0?r[i-1]:null;return n?this.getNodeId(n):null}getChildListMutation(e,t,r){return{type:"childList",parentNodeId:this.getNodeId(e),removedNodeIds:t,insertedNodes:r,childNodeCount:ua(e).length}}getInsertedNodeMutations(e,t,r){let i=[],n=t;for(let t of r){if((t.parentNode??(t instanceof ShadowRoot?t.host:null))!==e)continue;let r=this.serializeNode(t);i.push({previousNodeId:n,node:r}),n=r.id}return i}runWithoutObservation(e){var t,r;let i=null!==this.mutationObserver;i&&(null==(t=this.mutationObserver)||t.disconnect());try{return e()}finally{i&&(null==(r=this.mutationObserver)||r.takeRecords(),this.observe())}}serializeNode(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.getNodeId(e);if(e.nodeType===Node.TEXT_NODE){let t;return{id:r,type:"text",name:dQ(e),attributes:[],children:[],textContent:(t=(e.textContent??"").replace(/\s+/g," ").trim()).length>120?`${t.slice(0,120)}...`:t}}let i=e instanceof HTMLElement?e:null;return{id:r,type:t&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE?"document":"element",name:dQ(e),attributes:e instanceof Element?d8(e):[],children:ua(e).map(e=>this.serializeNode(e)),...i?{accessibility:{name:d4(i),role:d5(i),keyboardFocusable:d6(i)}}:{}}}observe(){let e=this.target.shadowRoot??this.target;this.mutationObserver=new MutationObserver(e=>{e.some(e=>(function(e){if(ud(e.target))return!1;if("attributes"===e.type)return e.target instanceof Element&&dX(e.target)&&!dZ.has(e.attributeName??"");if("characterData"===e.type){var t,r;return!!((null==(t=e.oldValue)?void 0:t.trim())||(null==(r=e.target.textContent)?void 0:r.trim()))}return"childList"!==e.type||[...Array.from(e.addedNodes),...Array.from(e.removedNodes)].some(e=>(function e(t){return!ud(t)&&(!!(dX(t)||dY(t))||Array.from(t.childNodes).some(t=>e(t)))})(e))})(e))&&this.scheduleNotify()}),this.mutationObserver.observe(e,{attributes:!0,childList:!0,characterData:!0,characterDataOldValue:!0,subtree:!0})}scheduleNotify(){null===this.notifyTimer&&(this.notifyTimer=window.setTimeout(()=>{this.notifyTimer=null,this.onChange()},0))}}let uc="data-wsd-node-id";function up(e){let t=[];for(let r=0;r<e.length;r++){let i="function"==typeof e.item?e.item(r):e[r];if(!i)continue;let n=e.getPropertyValue(i);t.push({name:i,value:n,priority:e.getPropertyPriority(i),active:!0})}return t}function uh(e){return"u">typeof CSSStyleRule&&e instanceof CSSStyleRule}function um(e,t,r){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",n=r.trim();n?e.setProperty(t,n,i):e.removeProperty(t)}function ug(e){return`${e.name}: ${e.value}${e.priority?` !${e.priority}`:""};`}function uf(e){return e.map(e=>({...e}))}function uv(e){return`inline:${e}`}function uy(e){return`rule:${e}`}class ub{target;elementInspector;ruleIds=new WeakMap;rules=new Map;overriddenElements=new Set;overrides=new Map;styleTextSnapshots=new Map;overrideStyleElement=null;inspectorRuleStyleElement=null;inspectorRuleStyleSheet=null;nextRuleId=0;constructor(e,t){this.target=e,this.elementInspector=t}getMatchedStyles(e){let t=this.elementInspector.getElement(e);if(!t)return null;let r=getComputedStyle(t);return{nodeId:e,inlineStyle:this.getInlineStyle(e,t,r),matchedRules:this.getMatchedRules(t,r),computedStyles:function(e){let t=[];for(let r=0;r<e.length;r++){let i=e.item(r);t.push({name:i,value:e.getPropertyValue(i)})}return t}(r)}}setInlineDeclaration(e,t,r){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",n=!(arguments.length>4)||void 0===arguments[4]||arguments[4],a=this.elementInspector.getElement(e);if(!a)return;let s=uv(e);this.rememberStyleTextDeclaration(s,up(a.style),t,r,i,n),um(a.style,t,n?r:"")}setInlineDeclarations(e,t){let r=this.elementInspector.getElement(e);if(r){for(let e of(r.style.cssText="",t))e.active&&um(r.style,e.name,e.value,e.priority);this.styleTextSnapshots.set(uv(e),uf(t))}}setRuleDeclaration(e,t,r,i){let n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"",a=!(arguments.length>5)||void 0===arguments[5]||arguments[5],s=this.rules.get(t),o=uy(t);if(this.rememberStyleTextDeclaration(o,s?up(s.style):[],r,i,n,a),!a){if(s)try{um(s.style,r,"")}catch{this.setOverrideDeclaration(e,r,"")}else this.setOverrideDeclaration(e,r,"");return}if(!s)return void this.setOverrideDeclaration(e,r,i,n);try{um(s.style,r,i,n)}catch{this.setOverrideDeclaration(e,r,i,n)}}setRuleDeclarations(e,t,r){let i=this.rules.get(t),n=r.filter(e=>e.active);if(this.styleTextSnapshots.set(uy(t),uf(r)),!i)return void this.setOverrideDeclarations(e,n);try{for(let e of(i.style.cssText="",n))um(i.style,e.name,e.value,e.priority)}catch{this.setOverrideDeclarations(e,n)}}addRule(e,t,r){let i=this.elementInspector.getElement(e),n=t.trim();if(!i||!n)return null;let a=this.getInspectorRuleStyleSheet();if(!a)return null;let s=`${n} { ${r.map(ug).join(" ")} }`;try{let e=a.cssRules.length;a.insertRule(s,e);let t=a.cssRules[e];if(t&&uh(t))return this.toMatchedStyleRule(t,getComputedStyle(i))}catch{}return null}setRuleSelector(e,t,r){let i=this.elementInspector.getElement(e),n=this.rules.get(t),a=r.trim();if(!i||!n||!a)return null;try{return n.selectorText=a,this.toMatchedStyleRule(n,getComputedStyle(i))}catch{return null}}setOverrideDeclaration(e,t,r){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",n=this.elementInspector.getElement(e);if(!n)return;n.setAttribute(uc,e),this.overriddenElements.add(n);let a=this.overrides.get(e)??new Map,s=r.trim();s?a.set(t,{value:s,priority:i}):a.delete(t),a.size>0?this.overrides.set(e,a):this.overrides.delete(e),this.renderOverrideStyleSheet()}setOverrideDeclarations(e,t){let r=this.elementInspector.getElement(e);if(!r)return;r.setAttribute(uc,e),this.overriddenElements.add(r);let i=new Map;for(let e of t)e.value.trim()&&i.set(e.name,{value:e.value.trim(),priority:e.priority});i.size>0?this.overrides.set(e,i):this.overrides.delete(e),this.renderOverrideStyleSheet()}destroy(){var e;for(let t of(null==(e=this.overrideStyleElement)||e.remove(),this.overrideStyleElement=null,this.removeInspectorRuleStyleSheet(),this.overrides.clear(),this.styleTextSnapshots.clear(),this.overriddenElements))t.removeAttribute(uc);this.overriddenElements.clear(),this.rules.clear()}getInlineStyle(e,t,r){return{id:"inline",selectorText:"element.style",editable:!0,declarations:this.getStyleTextSnapshot(uv(e))??up(t.style)}}getMatchedRules(e,t){let r,i=this.target.shadowRoot??this.target,n=[];for(let a of(this.rules.clear(),r=[],"styleSheets"in i&&r.push(...Array.from(i.styleSheets)),"adoptedStyleSheets"in i&&r.push(...i.adoptedStyleSheets),r))this.collectRulesFromList(a,e,t,n);return n}collectRulesFromList(e,t,r,i,n){let a;try{a=e.cssRules}catch{return}for(let e of Array.from(a)){if(uh(e)){if(!function(e,t){try{return e.matches(t)}catch{return!1}}(t,e.selectorText))continue;i.push(this.toMatchedStyleRule(e,r,n));continue}if("cssRules"in e){let a=function(e){if("conditionText"in e&&"string"==typeof e.conditionText)return e.conditionText}(e);this.collectRulesFromList(e,t,r,i,n&&a?`${n} and ${a}`:a??n)}}}getRuleId(e){let t=this.ruleIds.get(e);if(t)return t;let r=`rule-${++this.nextRuleId}`;return this.ruleIds.set(e,r),r}toMatchedStyleRule(e,t,r){let i=this.getRuleId(e);return this.rules.set(i,e),{id:i,selectorText:e.selectorText,conditionText:r,editable:!0,source:this.isOverrideRule(e)?"override":"rule",declarations:this.getStyleTextSnapshot(uy(i))??up(e.style)}}getStyleTextSnapshot(e){let t=this.styleTextSnapshots.get(e);return t?uf(t):void 0}rememberStyleTextDeclaration(e,t,r,i){let n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"",a=!(arguments.length>5)||void 0===arguments[5]||arguments[5],s=this.getStyleTextSnapshot(e)??uf(t),o=i.trim(),l=s.findIndex(e=>e.name===r);if(o||!a){let e={name:r,value:o||(l>=0?s[l].value:""),priority:n,active:a};l>=0?s[l]=e:s.push(e)}else l>=0&&s.splice(l,1);s.length>0?this.styleTextSnapshots.set(e,s):this.styleTextSnapshots.delete(e)}getOverrideStyleElement(){if(this.overrideStyleElement)return this.overrideStyleElement;let e=document.createElement("style");return e.dataset.wsdInspectorOverride="true",(this.target.shadowRoot??this.target).append(e),this.overrideStyleElement=e,e}getInspectorRuleStyleSheet(){if(this.inspectorRuleStyleSheet)return this.inspectorRuleStyleSheet;let e=this.target.shadowRoot??this.target;if("adoptedStyleSheets"in e&&"u">typeof CSSStyleSheet)try{let t=new CSSStyleSheet;return e.adoptedStyleSheets=[...e.adoptedStyleSheets,t],this.inspectorRuleStyleSheet=t,t}catch{}if(!this.inspectorRuleStyleElement){let t=document.createElement("style");t.dataset.wsdInspectorRules="true",e.append(t),this.inspectorRuleStyleElement=t}return this.inspectorRuleStyleSheet=this.inspectorRuleStyleElement.sheet,this.inspectorRuleStyleSheet}removeInspectorRuleStyleSheet(){var e;let t=this.target.shadowRoot??this.target;this.inspectorRuleStyleSheet&&"adoptedStyleSheets"in t&&(t.adoptedStyleSheets=t.adoptedStyleSheets.filter(e=>e!==this.inspectorRuleStyleSheet)),null==(e=this.inspectorRuleStyleElement)||e.remove(),this.inspectorRuleStyleElement=null,this.inspectorRuleStyleSheet=null}isOverrideRule(e){var t,r;return e.parentStyleSheet===(null==(t=this.overrideStyleElement)?void 0:t.sheet)||e.parentStyleSheet===(null==(r=this.inspectorRuleStyleElement)?void 0:r.sheet)||e.parentStyleSheet===this.inspectorRuleStyleSheet}renderOverrideStyleSheet(){if(0===this.overrides.size){var e;null==(e=this.overrideStyleElement)||e.remove(),this.overrideStyleElement=null;return}let t=Array.from(this.overrides.entries()).map(e=>{let[t,r]=e,i=Array.from(r.entries()).map(e=>{let[t,r]=e;return` ${t}: ${r.value}${r.priority?` !${r.priority}`:""};`}).join("\n");return`[${uc}="${t}"] {
|
|
44
|
+
`,document.head.append(e)})(),window.clearTimeout(dl),i=r||(document.body??document.documentElement),dd&&dd!==i&&du(dd),dd=i,du(i),i.style.setProperty("--doubao-web-sdk-debugger-vibrate-distance",`${t}px`),i.style.setProperty("--doubao-web-sdk-debugger-vibrate-duration",`${e}ms`),i.offsetWidth,i.classList.add(da),dl=window.setTimeout(()=>{du(i),dd===i&&(dd=null)},e+50)}}let dp="socketStatusChanged",dh="socketDataReceived",dm=1,dg=new Map;function df(e,t){let r="number"==typeof e?dg.get(e):void 0;if(!r||r.owner!==(null==t?void 0:t.events))throw new w("The socketTaskId doesn't exist",116);return r}function dv(){if(!nD())throw new w(nO,305)}function dy(e,t,r){var i;(null==e?void 0:e.events)?e.events.emitPrivate(t,r):null==e||null==(i=e.emitEvent)||i.call(e,t,r)}function db(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return{ssid:e.ssid,...e.bssid?{bssid:e.bssid.toLowerCase()}:{},...!t&&void 0!==e.secure?{secure:e.secure}:{},...!t&&void 0!==e.signalStrength?{signalStrength:Math.round(e.signalStrength)}:{},...!t&&void 0!==e.frequency?{frequency:e.frequency}:{}}}let dw=new class{hardware;modules=new Map;released=new WeakSet;listeners=new Set;unwatch;lastWifiKey;constructor(e=nL){this.hardware=e}start(e){let t=null==e?void 0:e.events;if(!t||this.released.has(t))throw new w("context is null",102);if(!this.hardware.getWifi().available)throw new w("wifi is not available",103);if(this.modules.has(t))return;this.modules.set(t,()=>{});let r=t.onDestroy(()=>{this.released.add(t),this.stop(t)});if(this.released.has(t))throw new w("context is null",102);this.modules.set(t,r),this.unwatch??=this.hardware.subscribe("wifi",()=>this.publishCurrent())}stop(e){var t,r;e&&(null==(t=this.modules.get(e))||t(),this.modules.delete(e)),0===this.modules.size&&(null==(r=this.unwatch)||r.call(this),this.unwatch=void 0,this.lastWifiKey=void 0)}ensureStarted(e){if((null==e?void 0:e.events)&&this.released.has(e.events))throw new w("context is null",102);if(!(null==e?void 0:e.events)||!this.modules.has(e.events))throw new w("wifi module is not initialized",1401001)}currentNetwork(){let e=this.hardware.getWifi();return e.available&&e.enabled?e.networks.find(t=>ns(t)===e.connectedNetworkKey):void 0}subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));publishCurrent(){if(0===this.modules.size)return;let e=this.currentNetwork();if(!e){this.lastWifiKey=void 0;return}let t=ns(e);if(t!==this.lastWifiKey)for(let r of(this.lastWifiKey=t,this.listeners))r({wifi:db(e)})}};function d_(e,t){if(void 0!==e[t]&&"boolean"!=typeof e[t])throw new w(`${t} must be a boolean`,104)}function dS(e){return{...V(e),platform:sc}}function dx(){var e,t;let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=(null==(e=r.baseAPIRegistry)?void 0:e.fork())??new k(tg);return i.registerMany(function(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t.uiPresenter,i=t.scanCodePresenter;return{"doubao.request":function(e){if(oc.has(e))return e;let t=(t,r)=>{let i=`wsd-request-${++op}`,n=t.params??{},a=function(e){try{return nJ(e)}catch{return}}(n);og({phase:"request",request:a??{headers:{},method:"string"==typeof n.method?n.method.toUpperCase():"GET",url:"string"==typeof n.url?n.url:""},requestId:i,...om()});let s=e=>og({errorText:e,phase:"failure",requestId:i,...om()}),o=e=>((null==e?void 0:e.params.code)===1?og({phase:"response",requestId:i,response:e.params.data,...om()}):s((null==e?void 0:e.params.errMsg)??(null==e?void 0:e.params.msg)??"doubao.request failed"),e),l=e=>{throw s(e instanceof Error?e.message:String(e)),e};try{let i=e(t,r,a);return i instanceof Promise?i.then(e=>o(e),l):o(i)}catch(e){return l(e)}};return oc.add(t),t}(t.requestHandler??(async(e,t,r)=>_(e,await nK(e.params,r)))),...{"doubao.hideKeyboard":(e,t)=>{if((null==t?void 0:t.containerType)&&"PAGE"!==t.containerType)throw new w("hideKeyboard is only supported in page containers",103);let r=s8();return r instanceof HTMLElement&&(!(null==t?void 0:t.element)||s9(r,t.element))&&r.blur(),_(e,{})}},...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;return{"doubao.checkIsOpenAccessibility":(t,r)=>{var i;let n=e.getAccessibility(),a=(null==r||null==(i=r.globalProps)?void 0:i.os)==="iOS";if(!a&&!n.available)throw new w("accessibility service is unavailable",103);return _(t,{open:a?n.voiceOverRunning||n.switchControlRunning:n.androidEnabled&&n.touchExplorationEnabled})}}}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{"doubao.reportEvent":(t,r)=>{var i,n,a,s,o;let l=t.params;if(!rP(l)||"string"!=typeof l.eventName||!rP(l.data))throw new w("eventName must be a string and data must be an object",104);let d=null==r||null==(i=r.getAppletContext)?void 0:i.call(r).viewContext,u=(null==d?void 0:d.appId)??(null==r||null==(n=r.navigation)?void 0:n.getPackageInfo().appId)??(null==(a=e.getAppId)?void 0:a.call(e))??e.appId??(null==r||null==(o=r.globalProps)||null==(s=o.packageInfo)?void 0:s.appId);if("string"!=typeof u||!u||!(null==r?void 0:r.element))throw new w("An application and console target are required to report an event",102);let c={...l.data};"WIDGET"===r.containerType&&(Object.hasOwn(c,"widget_id")||(null==d?void 0:d.widgetId)===void 0||(c.widget_id=d.widgetId),Object.hasOwn(c,"message_id")||(null==d?void 0:d.messageId)===void 0||(c.message_id=d.messageId));let p={appId:u,eventName:l.eventName,data:c,containerType:r.containerType,timestamp:Date.now()};return s_(r.element,{level:"info",label:"analytics",message:`reportEvent ${l.eventName}`,args:[p]}),_(t,{})}}}(t),...function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nL,r=new WeakMap,i=new WeakSet,n={};return Object.fromEntries(["phone","sms"].map(a=>["phone"===a?"doubao.makePhoneCall":"doubao.sendSms",{canIUse:!!e,handler:async(s,o)=>{let l,d=s.params??{};if("object"!=typeof d||Array.isArray(d)||"phone"===a&&"string"!=typeof d.phoneNumber||void 0!==d.phoneNumber&&"string"!=typeof d.phoneNumber||"sms"===a&&void 0!==d.message&&"string"!=typeof d.message)throw new w("phoneNumber and message must be strings",104);let u=(d.phoneNumber??"").trim();if("phone"===a&&!u)throw new w("The phoneNumber parameter should not be empty.",104);let c=t.getCommunication();if(!("phone"===a?c.phoneAvailable:c.smsAvailable))throw new w(`${a} is not available`,103);if(!("phone"===a?c.phoneOpenSucceeds:c.smsOpenSucceeds)||!e)throw new w(`Opening the ${a} panel failed`,102);let p=function(e){let t=(null==e?void 0:e.events)??n,a=r.get(t)??new Set;if(!r.has(t)){var s;r.set(t,a),null==e||null==(s=e.events)||s.onDestroy(()=>{for(let e of(i.add(t),a))e.abort();a.clear()})}if(i.has(t))throw new w("communication view was destroyed",114);return a}(o),h=new AbortController;p.add(h);try{l=e({kind:a,phoneNumber:u,message:d.message??"",sendSucceeds:c.smsSendSucceeds},h.signal).closed}catch(e){throw p.delete(h),new w(e instanceof Error?e.message:String(e),102)}let m=l.finally(()=>p.delete(h));if(m.catch(()=>void 0),"sms"===a){let e;try{e=await m}catch(e){throw new w(e instanceof Error?e.message:String(e),102)}if(h.signal.aborted||"cancel"===e)throw new w("cancel",114);if("failed"===e)throw new w("sendSms failed",102)}return _(s,{})}}]))}(null==r?void 0:r.showCommunication),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sY,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:nL;return Object.fromEntries(["addPhoneCalendar","addPhoneRepeatCalendar"].map(i=>[`doubao.${i}`,{handler:async(n,a)=>{var s,o,l,d;let u=function(e,t){var r,i,n,a;if(!rP(e))throw Error("The calendar event parameter is invalid.");let s=t=>{let r=e[t];if(void 0!==r&&"string"!=typeof r)throw Error(`${t} must be a string`);return r},o=(t,r)=>{let i=e[t]??r;if("number"!=typeof i||!Number.isSafeInteger(i))throw Error(`${t} must be an integer number of seconds`);return i},l=(t,r)=>{let i=e[t]??r;if("boolean"!=typeof i)throw Error(`${t} must be a boolean`);return i},d=(null==(r=s("title"))?void 0:r.trim())??"";if(!d)throw Error("The title parameter should not be empty.");let u=o("startTime"),c=o("endTime",u),p=o("alarmOffset",0);if(u<=0||!Number.isFinite(new Date(1e3*u).getTime()))throw Error("The startTime parameter should be a valid Unix timestamp.");if(c<u||!Number.isFinite(new Date(1e3*c).getTime()))throw Error("The endTime parameter should not be earlier than startTime.");if(p<0)throw Error("The alarmOffset parameter should not be negative.");let h={title:d,startTime:u,endTime:c,allDay:l("allDay",!1),alarm:l("alarm",!0),alarmOffset:p,description:(null==(i=s("description"))?void 0:i.trim())||void 0,location:(null==(n=s("location"))?void 0:n.trim())||void 0,path:(null==(a=s("path"))?void 0:a.trim())||void 0};if(t){let t=(s("repeatInterval")??"month").trim().toLowerCase();if(!["day","week","month","year"].includes(t))throw Error("The repeatInterval parameter should be one of day, week, month, year.");if(h.repeatInterval=t,void 0!==e.repeatEndTime&&(h.repeatEndTime=o("repeatEndTime"),h.repeatEndTime<u||!Number.isFinite(new Date(1e3*h.repeatEndTime).getTime())))throw Error("The repeatEndTime parameter should not be earlier than startTime.")}return h}(n.params,"addPhoneRepeatCalendar"===i),c=(null==a||null==(o=a.getAppletContext)||null==(s=o.call(a).viewContext)?void 0:s.appId)??(null==a||null==(l=a.navigation)?void 0:l.getPackageInfo().appId)??e.appId;if(!c)throw Error("appletId is empty");let p=new AbortController,h=null==a||null==(d=a.events)?void 0:d.onDestroy(()=>p.abort());try{let i=await sJ({appId:c,appIcon:e.appIcon,appName:e.appName,presenter:e.showSimulatorPermission,scope:"scope.addPhoneCalendar",skipDialogIfDenied:!0,signal:p.signal});if(p.signal.aborted)throw Error("calendar view was destroyed");if(!i)throw Error("addPhoneCalendar authorization failed");if(!["full","write only"].includes(r.getSystem().phoneCalendar))throw Error("system calendar permission denied");return t.write(u,c),_(n,{})}finally{null==h||h(),p.abort()}}}]))}(t),...{...t.exitAppFromWidget?{"doubao.exitApp":{handler:async(e,r)=>{var i,n;if(!(null==r||null==(i=r.navigation)?void 0:i.exitApp))throw new w("No active Runtime to exit",102);return r.navigation.exitApp(),await (null==(n=t.exitAppFromWidget)?void 0:n.call(t)),_(e,{})}}}:{},"doubao.openPage":{canIUse:e=>(null==e?void 0:e.containerType)!=="WIDGET"||!!t.openPageFromWidget,handler:(e,r)=>{let i=tg["doubao.openPage"];return("function"==typeof i?i:i.handler)(e,(null==r?void 0:r.containerType)==="WIDGET"?{...r,navigation:{...r.navigation,openPage:t.openPageFromWidget}}:r)}}},"doubao.getDeviceInfo":{handler:(e,t)=>_(e,dS(null==t?void 0:t.globalProps)),syncResult:e=>dS(null==e?void 0:e.globalProps)},"doubao.getNetworkType":{handler:(e,t)=>_(e,of(t)),syncResult:of},"doubao.scanCode":{canIUse:()=>!!i&&"function"==typeof globalThis.BarcodeDetector,handler:async(e,t)=>{var r;if(!i)throw Error("Simulator scan-code presenter is unavailable");let n=new AbortController,a=null==t||null==(r=t.events)?void 0:r.onDestroy(()=>n.abort());try{return _(e,await l8(e.params,i,n.signal))}finally{null==a||a(),n.abort()}}},"doubao.vibrateLong":async e=>(await void dc(400,3,t.vibrationContainer),_(e,{})),"doubao.vibrateShort":async e=>(await function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0,{type:r="medium"}=e;dc(15,ds[r],t)}(e.params,t.vibrationContainer),_(e,{})),...{"doubao.chooseImage":async(e,t)=>_(e,await function(e,t){let r="string"==typeof e.imageId?document.getElementById(e.imageId):null,i=r instanceof HTMLInputElement?r:document.createElement("input"),n=i!==r,a=e.count??9;if(!Number.isInteger(a)||a<1)throw new w("count must be a positive integer",104);if(void 0!==e.sizeType&&(!Array.isArray(e.sizeType)||e.sizeType.some(e=>!["original","compressed"].includes(e))))throw new w("sizeType must contain original or compressed",104);i.type="file",i.accept="image/*",i.multiple=a>1;let s=Array.isArray(e.sourceType)?e.sourceType:[];return i.capture=s.includes("album")?"":s.includes("user")?"user":s.some(e=>"camera"===e||"environment"===e)?"environment":"",i.style.display="none",i.value="",n&&document.body.append(i),new Promise((r,s)=>{var o;let l=!1,d=()=>void 0,u=()=>{i.removeEventListener("change",p),i.removeEventListener("cancel",h),d(),n&&i.remove()},c=e=>{l||(l=!0,u(),s(e))},p=async()=>{let n,s=Array.from(i.files??[]).slice(0,a);if(0===s.length)return void h();try{n=await Promise.all(s.map(async r=>{var i;let n=await new Promise((e,t)=>{let i=new FileReader;i.onload=()=>e(String(i.result)),i.onerror=()=>t(i.error??Error("Failed to read media file")),i.readAsDataURL(r)}),a=(null==(i=e.sizeType)?void 0:i.length)===1&&"compressed"===e.sizeType[0],s=a?(await s6({src:n},t)).tempFilePath:n;return{path:s,size:a?atob(s.slice(s.indexOf(",")+1)).length:r.size,type:a?"image/jpeg":r.type,originalFileObj:r}}))}catch(e){c(e);return}l||(l=!0,u(),r({tempFilePaths:n.map(e=>e.path),tempFiles:n}))},h=()=>{c(new w("chooseImage was cancelled",114))};if(d=(null==t||null==(o=t.events)?void 0:o.onDestroy(h))??d,l)return void d();i.addEventListener("change",p,{once:!0}),i.addEventListener("cancel",h,{once:!0});try{i.click()}catch(e){c(e)}})}(e.params,t)),...(e=t.imagePreviewController)?{"doubao.previewImage":async(t,r)=>{var i;let n=t.params;return(null==(i=n.urls)?void 0:i.some(nq))&&nU(),e.previewImage({...n,urls:n.urls?await Promise.all(n.urls.map(e=>rV(e,r))):n.urls,current:"string"==typeof n.current?await rV(n.current,r):n.current}),_(t,{})}}:{},"doubao.getImageInfo":async(e,t)=>{let r=e.params;if("string"!=typeof r.src||!r.src)throw new w("src must be a non-empty string",104);let i=await rV(r.src,t),n=await (nq(i)?nB(e=>td({src:i},e)):td({src:i}));return n.path=r.src,_(e,n)},"doubao.compressImage":async(e,t)=>_(e,await s6(e.params,t)),"doubao.saveImageToPhotosAlbum":async(e,t)=>(await s5(e.params,t),_(e,{}))},...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:sx,t=new WeakMap;return{"doubao.createInnerAudioContext":{canIUse:sC,handler:async(r,i)=>{let n=rP(r.params)?r.params:{},a="string"==typeof n.audioId?n.audioId.trim():"";try{var s,o,l,d;if(!a)throw new sE(-2008,"inner audio audioId is empty");let u=(null==i||null==(s=i.navigation)?void 0:s.getPackageInfo().appId)??(null==i||null==(l=i.globalProps)||null==(o=l.packageInfo)?void 0:o.appId);if("string"!=typeof u||!u)throw new sE(-2001,"inner audio appletId is empty");let c=null==i?void 0:i.applicationLifecycle,p=(null==c?void 0:c.owner)??(null==i?void 0:i.events);if(!p||!i||!sC())throw new sE(-2010,"inner audio runtime is unavailable");let h=t.get(p);if(!h){h={instances:new Map,destroyed:!1},t.set(p,h);let e=()=>{for(let e of(h.destroyed=!0,h.instances.values()))e.destroy();h.instances.clear()};c?(c.signal.addEventListener("abort",e,{once:!0}),c.signal.aborted&&e()):null==(d=i.events)||d.onDestroy(e)}if(h.destroyed)throw new sE(-2010,"inner audio runtime is unavailable");let m=n.action??"create",g=h.instances.get(a);if("create"===m)return g??=new sN(a,u,i,void 0,!0,e),h.instances.set(a,g),_(r,g.snapshot());if("destroy"===m)return null==g||g.destroy(),h.instances.delete(a),_(r,{});if(!g)throw new sE(-2002,"inner audio instance not found");switch(m){case"get_state":return _(r,g.snapshot());case"set_state":await g.update(rP(n.state)?n.state:{});break;case"play":await g.play();break;case"pause":g.pause();break;case"stop":g.stop();break;case"seek":g.seek(n.position);break;default:throw new sE(-2011,"inner audio action is invalid")}return _(r,{})}catch(n){let e=n instanceof sE?n:new sE(-2007,"inner audio play failed"),t=[-2003,-2004,-2008,-2011,-2012].includes(e.errCode)?104:-2002===e.errCode?203:102,i=S(r,e.message,t);return i.params.data={audioId:a,errCode:e.errCode,errMsg:e.message},i}}}}}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:sP;return{"doubao.getBackgroundAudioManager":{canIUse:sA,handler:async(t,r)=>{try{if(!r)throw new sE(-1008,"background audio runtime is unavailable");e.attach(r);let s=rP(t.params)?t.params:{},o=s.action??"get_state";if("get_state"===o){var i,n,a;return _(t,{...e.getSnapshot(),appletId:(null==(i=r.navigation)?void 0:i.getPackageInfo().appId)??(null==(a=r.globalProps)||null==(n=a.packageInfo)?void 0:n.appId)})}return"set_state"===o?e.update(rP(s.state)?s.state:{}):await e.control(String(o),s.position),_(t,{})}catch(n){let e=sj(n),r=[-1001,-1006,-1007].includes(e.errCode)?104:102,i=S(t,e.errMsg,r);return i.params.data=e,i}}}}}(),...function(){let e=new WeakMap,t={tasks:new Map,destroyed:!1},r=new Set;function i(r){let i=null==r?void 0:r.events;if(!i)return t;let n=e.get(i);if(!n){n={tasks:new Map,destroyed:!1},e.set(i,n);let t=n;i.onDestroy(()=>{for(let e of(t.destroyed=!0,t.tasks.values()))e.cancel()})}return n}function n(e){return async(t,n)=>{let a,s=t.params??{},o=e?"uploadFile":"downloadFile",l=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;return new w(`${o}:fail ${e}`,t)},d=e?"uploadTaskId":"downloadTaskId",u=s[d];try{a=new URL("string"==typeof s.url?s.url.trim():"")}catch{throw l("url is invalid",e?121999:-1)}if(!["http:","https:"].includes(a.protocol))throw l("url is invalid",e?121999:-1);if("string"!=typeof u||!u.trim())throw l(`${d} is invalid`,e?121999:-1);if(e&&("string"!=typeof s.name||!s.name.trim()))throw l("name is required",121999);if(e&&!0===s.enableProfile)throw l("enableProfile is not supported",121992);if(nF(s.url,e?"upload":"download"),!e&&null!=s.filePath&&""!==s.filePath){if("string"!=typeof s.filePath)throw l("filePath must be appletfile://temp or appletfile://user");eD(s.filePath)}let c=i(n);if(c.destroyed)throw l("abort",e?121905:-1);let p=`${o}:${u}`;if(c.tasks.has(p))throw l(`${d} already exists`);if(!e&&r.size>=10)throw l("exceed max download connection count 10");if(!nD())throw l(nO,e?121985:-1);let h=new XMLHttpRequest;return _(t,await new Promise((t,i)=>{let o,m,g=!1,f=0,v=(e,t)=>{if(!g&&!c.destroyed){var r;null==n||null==(r=n.events)||r.emitPrivate(e,{[d]:u,...t})}},y=(e,n)=>{g||(g=!0,null==w||w(),c.tasks.delete(p),r.delete(b),h.onreadystatechange=null,h.onprogress=null,h.onload=h.onerror=h.ontimeout=h.onabort=null,e?i(e):t(n??{}))},b={cancel:()=>{y(l("abort",e?121905:-1)),h.abort()}},w=n$(()=>{y(l(nO,e?121985:-1)),h.abort()});c.tasks.set(p,b),e||r.add(b);let _=()=>{if(!o&&h.readyState>=2&&h.status>0)try{let t=h.getResponseHeader(s2);if(200!==h.status||!t)throw l("network error",e?121991:-1);o=JSON.parse(decodeURIComponent(t)),v(e?"uploadFileHeadersReceived":"downloadFileHeadersReceived",{header:o.header})}catch(e){y(e instanceof Error?e:l(String(e))),h.abort()}},S=()=>{if(!g&&!(h.readyState<2)&&0!==h.status)try{let e;if(200!==h.status||"application/x-ndjson"!==h.getResponseHeader("content-type"))throw l("network error",121991);let t=h.responseText;for(;!g&&-1!==(e=t.indexOf("\n",f));){let r=JSON.parse(t.slice(f,e));switch(f=e+1,r.type){case"progress":v("uploadFileProgressUpdate",{progress:Math.min(100,Math.floor(100*r.totalBytesSent/r.totalBytesExpectedToSend)),totalBytesSent:r.totalBytesSent,totalBytesExpectedToSend:r.totalBytesExpectedToSend});break;case"headers":o={statusCode:r.statusCode,header:r.header},v("uploadFileHeadersReceived",{header:r.header});break;case"result":m=r.data;break;case"error":throw l(r.message,121991);default:throw l("invalid upload response",121991)}}}catch(e){y(e instanceof Error?e:l(String(e),121991)),h.abort()}};h.onreadystatechange=e?S:_,h.onprogress=e?S:e=>{if(e.loaded>0xc800000||e.total>0xc800000){y(l("size exceeds 200MB")),h.abort();return}v("downloadProgressUpdate",{progress:e.lengthComputable&&e.total>0?Math.min(100,Math.floor(100*e.loaded/e.total)):0,totalBytesWritten:e.loaded,totalBytesExpectedToWrite:e.lengthComputable?e.total:-1})},h.onerror=()=>y(l(nD()?"network error":nO,e?nD()?121991:121985:-1)),h.ontimeout=()=>y(l("timeout",e?121920:-1)),h.onabort=()=>y(l("abort",e?121905:-1)),h.onload=async()=>{if(!g&&(e?S():_(),!g))try{if(!o)throw l("network error",e?121991:-1);let t=o;if(e){if(void 0===m||f!==h.responseText.length)throw l("incomplete upload response",121991);y(void 0,{...t,data:m});return}let r=new Uint8Array(h.response);if(r.length>0xc800000)throw l("size exceeds 200MB");let i="string"==typeof s.filePath&&s.filePath?s.filePath:`appletfile://temp/download_${Date.now()}_${++s1}`;await rH(i,r,n),y(void 0,{...t,[s.filePath?"filePath":"tempFilePath"]:i})}catch(e){y(e instanceof Error?e:l(String(e)))}},(async()=>{let t;if(e){let e,r=s.filePath;if("string"!=typeof r||!r)throw l("no file exist",121902);if(!r.startsWith("appletfile:")&&!r.startsWith("data:"))throw l("file path permission denied",121906);try{let t=await rV(r,n);e=await (await fetch(t)).blob()}catch{throw l("no file exist",121902)}if(g)return;for(let[e,r]of(t=new FormData,Object.entries(s.formData??{})))e.trim()&&t.append(e.trim(),s3(r));t.append(s.name,e,r.startsWith("data:")?"upload.bin":decodeURIComponent(r.split("/").pop()??"upload.bin"))}if(g)return;h.open(e?"POST":"GET","/__web_sdk_request_proxy__"),h.responseType=e?"text":"arraybuffer";let r=Number(s.timeout);h.timeout=r>0&&Number.isFinite(r)?Math.min(r,e?0x7fffffff:3e5):e?3e4:6e4;let i={};for(let[t,r]of Object.entries(s.header??{}))["referer","user-agent",...e?["content-type"]:[]].includes(t.trim().toLowerCase())||(i[t.trim()]=s3(r));h.setRequestHeader(s2,encodeURIComponent(JSON.stringify({url:a.href,header:i}))),h.send(t)})().catch(e=>y(e instanceof Error?e:l(String(e))))}))}}function a(e){return(t,r)=>{var n;let a=(t.params??{})[e?"uploadTaskId":"downloadTaskId"];return null==(n=i(r).tasks.get(`${e?"uploadFile":"downloadFile"}:${String(a)}`))||n.cancel(),_(t,{})}}return{"doubao.downloadFile":n(!1),"doubao.abortDownloadFile":a(!1),"doubao.uploadFile":n(!0),"doubao.abortUploadFile":a(!0)}}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL,t=()=>{let{isCharging:t,level:r}=e.getBattery();return{isCharging:t,level:r}};return{"doubao.getBatteryInfo":{handler:e=>_(e,t()),syncResult:t}}}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;return sy({name:"Accelerometer",getSample:e.getAccelerometer})}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;return sy({name:"Gyroscope",getSample:e.getGyroscope})}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;return sf({name:"Compass",readSample:()=>{let{available:t,direction:r,accuracy:i}=e.getCompass();return{available:t,params:{direction:r%360,accuracy:i}}}})}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;return sf({name:"DeviceMotion",readSample:()=>{let{available:t,alpha:r,beta:i,gamma:n}=e.getDeviceMotion(),a=2*Math.PI,s=r%a;return{available:t,params:{alpha:s<0?s+a:s,beta:i,gamma:n}}}})}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:dw;return{"doubao.startWifi":{handler:(t,r)=>(e.start(r),_(t,{}))},"doubao.stopWifi":{handler:(t,r)=>(e.stop(null==r?void 0:r.events),_(t,{}))},"doubao.getConnectedWifi":{handler:(t,r)=>{let i=t.params??{};d_(i,"partialInfo"),e.ensureStarted(r);let n=e.currentNetwork();if(!n)throw new w("wifi is not connected",1401002);return _(t,{wifi:db(n,!0===i.partialInfo)})}},"doubao.getWifiList":{handler:(t,r)=>{e.ensureStarted(r);let i=e.currentNetwork(),n=e.hardware.getWifi(),a=new Map;if(i&&a.set(ns(i),i),n.available&&n.enabled)for(let e of[...n.networks].sort((e,t)=>(t.signalStrength??-1)-(e.signalStrength??-1)))a.set(ns(e),e);return _(t,{wifiList:[...a.values()].map(e=>db(e))})}},"doubao.connectWifi":{handler:(t,r)=>{let i=t.params??{},n=i.bssid;if("string"!=typeof i.ssid||"string"!=typeof i.password||void 0!==n&&"string"!=typeof n)throw new w("ssid and password must be strings",104);if(d_(i,"manual"),d_(i,"partialInfo"),!0===i.manual)return na("network"),_(t,{});if(e.ensureStarted(r),!i.ssid.trim())throw new w("ssid is empty",104);let a=e.hardware.getWifi(),s=a.networks.find(e=>{var t;return e.ssid===i.ssid&&(!n||(null==(t=e.bssid)?void 0:t.toLowerCase())===n.toLowerCase())});if(!a.available||!a.enabled||!s||s.password!==i.password)throw new w("connect wifi failed",1401003);return e.hardware.setWifi({...a,connectedNetworkKey:ns(s)}),_(t,{})}},"doubao.setWifiList":{canIUse:!1,handler:()=>{throw new w("Wi-Fi presets are not supported; configure virtual networks in settings",103)}}}}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:sB,t={openBluetoothAdapter:t=>e.open(t),closeBluetoothAdapter:t=>e.close(t),getBluetoothAdapterState:t=>e.state(t),startBluetoothDevicesDiscovery:(t,r)=>e.startDiscovery(t,r),stopBluetoothDevicesDiscovery:t=>e.stopDiscovery(t),getBluetoothDevices:t=>({devices:e.devices(t)})};for(let r of["createBLEConnection","closeBLEConnection","getConnectedBluetoothDevices","makeBluetoothPair","isBluetoothDevicePaired","getBLEDeviceServices","getBLEDeviceCharacteristics","getBLEDeviceRSSI","getBLEMTU","setBLEMTU","readBLECharacteristicValue","writeBLECharacteristicValue","notifyBLECharacteristicValueChange"])t[r]=(t,i)=>e.gatt(t,r,i);return Object.fromEntries(Object.entries(t).map(t=>{let[r,i]=t;return[`doubao.${r}`,{handler:async(t,r)=>_(t,await i(e.client(null==r?void 0:r.events,r),t.params??{})??{})}]}))}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:sL;return{"doubao.startBeaconDiscovery":{handler:(t,r)=>(e.start(t.params??{},r),_(t,{}))},"doubao.stopBeaconDiscovery":{handler:t=>(e.stop(),_(t,{}))},"doubao.getBeacons":{handler:t=>_(t,e.get())}}}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;return Object.fromEntries(Object.entries({"doubao.getSystemSetting":t=>dt(t,e),"doubao.getAppAuthorizeSetting":t=>dr(t,e)}).map(e=>{let[t,r]=e;return[t,{handler:(e,t)=>_(e,r(t)),syncResult:r}]}))}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;return Object.fromEntries(["doubao.getSystemInfo","doubao.getAppBaseInfo"].map(t=>[t,{handler:(r,i)=>_(r,l7(i,e)[t]),syncResult:r=>l7(r,e)[t]}]))}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:l9,t={},r=new WeakSet,i=new WeakSet;function n(n){let a=(null==n?void 0:n.events)??t;if(!r.has(a)){var s,o;r.add(a);let t=!0,l=()=>e.set(a,{background:document.hidden||!t}),d=null==n||null==(s=n.events)?void 0:s.onVisibilityChange(e=>{t=e,l()});l(),document.addEventListener("visibilitychange",l),null==n||null==(o=n.events)||o.onDestroy(()=>{i.add(a),document.removeEventListener("visibilitychange",l),null==d||d(),e.release(a)})}if(i.has(a))throw new w("screen view was destroyed",114);return a}return{...Object.fromEntries(["disableUserScreenRecord","enableUserScreenRecord"].map(t=>[`doubao.${t}`,(r,i)=>(e.set(n(i),{screenRecordDisabled:"disableUserScreenRecord"===t}),_(r,{}))])),"doubao.getScreenBrightness":t=>_(t,{value:e.getSnapshot().brightness}),"doubao.setScreenBrightness":(t,r)=>{var i,a;let s=null==(i=t.params)?void 0:i.value;if("number"!=typeof s||!Number.isFinite(s)||s<0||s>1)throw new w("value must be a finite number between 0 and 1",104);if((null==r||null==(a=r.getAppletContext)?void 0:a.call(r).source)==="widget")throw new w("setScreenBrightness is only supported in page containers",103);return e.set(n(r),{brightness:s}),_(t,{})},"doubao.setKeepScreenOn":(t,r)=>{var i;let a=null==(i=t.params)?void 0:i.keepScreenOn;if("boolean"!=typeof a)throw new w("keepScreenOn must be a boolean",104);return e.set(n(r),{keepScreenOn:a}),_(t,{})}}}(),...function(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:oi,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:nL,n=()=>{let t=e;e=void 0,null==t||t.cleanup(),null==t||t.controller.abort(),r.stopLocationUpdates()};return{"doubao.getLocation":async(e,n)=>{var a,s;let o=new AbortController,l=null==n||null==(a=n.events)?void 0:a.onDestroy(()=>o.abort());try{let a=await od(t,r,n,o.signal);if(o.signal.aborted)return os(e,114,"operation cancelled");if(!a)return os(e,107,"user permission denied",107);let l=ol(i);if("location_permission_denied"===l)return os(e,106,"system permission denied",106);if(l)return os(e,102,l,102);let d=await r.requestLocation(oa(e.params));return"success"===d.status?_(e,{latitude:(s=d.location).latitude,longitude:s.longitude,timestamp:String(Math.trunc(s.timestamp)),speed:s.speed,accuracy:s.accuracy}):oo(e,d)}finally{null==l||l(),o.abort()}},"doubao.chooseLocation":{canIUse:!1,handler:async e=>await od(t,r)?S(e,on):S(e,"user permission denied")},"doubao.openLocation":{canIUse:!1,handler:async e=>await od(t,r)?S(e,on):S(e,"user permission denied")},"doubao.startLocationUpdate":async(a,s)=>{var o,l,d;let u=a.params,c=null==u?void 0:u.type;if(void 0!==c&&"gcj02"!==c&&"wgs84"!==c)return os(a,104,"type must be gcj02 or wgs84");if((null==e?void 0:e.pending)||r.isUpdating)return os(a,118,"already exists");n();let p=new AbortController,h={controller:p,pending:!0,cleanup:()=>{}};e=h;let m=()=>{e===h&&n()},g=(null==s||null==(o=s.applicationLifecycle)?void 0:o.signal)??(null==s?void 0:s.signal);g?(g.addEventListener("abort",m,{once:!0}),h.cleanup=()=>g.removeEventListener("abort",m),g.aborted&&m()):h.cleanup=(null==s||null==(l=s.events)?void 0:l.onDestroy(m))??(()=>{});let f=!1;try{let e=await od(t,r,s,p.signal);if(p.signal.aborted)return os(a,114,"operation cancelled");if(!e)return os(a,107,"user permission denied",107);if(ol(i)||"denied"===r.getSnapshot().browserAuthorization)return os(a,106,"system permission denied",106);if("manual"!==r.getSnapshot().source&&("u"<typeof navigator||"function"!=typeof(null==(d=navigator.geolocation)?void 0:d.watchPosition)))return os(a,103,"location updates not supported");let n=await r.startLocationUpdates(oa(),{type:c??"gcj02",signal:p.signal});if(p.signal.aborted)return os(a,114,"operation cancelled");if("success"!==n.status)return oo(a,n);return f=!0,_(a,{})}catch(e){if(p.signal.aborted)return os(a,114,"operation cancelled");throw e}finally{e===h&&(h.pending=!1,f||n())}},"doubao.stopLocationUpdate":e=>(n(),_(e,{}))}}(t),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.presenter??{hideLoading:di,hideToast:di,showActionSheet:async()=>di(),showBottomSheet:async()=>di(),showLoading:di,showModal:async()=>di(),showToast:di};return Object.fromEntries(Object.entries({"applet.showToast":e=>(t.showToast(e.params),_(e,{})),"doubao.hideToast":e=>(t.hideToast(),_(e,{})),"doubao.showLoading":e=>(t.showLoading(),_(e,{})),"doubao.hideLoading":e=>(t.hideLoading(),_(e,{})),"doubao.showModal":async e=>_(e,await t.showModal(e.params)),"doubao.showActionSheet":async e=>_(e,await t.showActionSheet(e.params)),"doubao.showBottomSheet":async e=>_(e,await t.showBottomSheet(e.params))}).map(t=>{let[r,i]=t;return[r,{handler:i,canIUse:!!e.presenter}]}))}({presenter:r}),...{"doubao.connectSocket":(e,t)=>_(e,function(e,t){var r;let i,n;if("string"!=typeof e.url||!e.url)throw new w("url must be a non-empty string",104);nF(e.url,"socket");try{i=new URL(e.url.trim())}catch{throw new w("invalid socket url",104)}if(!["ws:","wss:"].includes(i.protocol)||void 0!==e.protocols&&(!Array.isArray(e.protocols)||e.protocols.some(e=>"string"!=typeof e)))throw new w("invalid socket url or protocols",104);if(Array.from(dg.values()).filter(e=>e.owner===(null==t?void 0:t.events)).length>=5)throw new w("WebSocket connection count exceeds 5",1501001);dv();let a=dm++;try{let e=new URL("/__web_sdk_socket__",location.href);e.protocol="https:"===location.protocol?"wss:":"ws:",n=new WebSocket(e)}catch(t){let e=new w("invalid socket url or protocols",104);throw e.cause=t,e}let s={socket:n,owner:null==t?void 0:t.events,opened:!1,cancel:(e,r)=>{l(),n.close(),dy(t,dp,{socketTaskId:a,status:"closed",code:e,reason:r,protocolType:c})}};dg.set(a,s);let o=!1,l=()=>{o=!0,dg.delete(a),d(),null==u||u()},d=n$(()=>{o||(l(),n.close(),dy(t,dp,{socketTaskId:a,status:s.opened?"closed":"failed",code:1006,reason:nO,errMsg:nO,protocolType:n.protocol}))}),u=null==t||null==(r=t.events)?void 0:r.onDestroy(()=>{l(),n.close(1e3)}),c="";return n.addEventListener("open",()=>{if(!o){var t;n.send(JSON.stringify({url:i.href,header:e.header,protocols:null==(t=e.protocols)?void 0:t.map(e=>e.trim()).filter(Boolean)}))}}),n.addEventListener("message",e=>{if(!o)try{let r=JSON.parse(e.data);if("open"===r.type)s.opened=!0,c=r.protocol,dy(t,dp,{socketTaskId:a,status:"connected",header:{},protocolType:c});else if("message"===r.type){let e=r.binary?Uint8Array.from(atob(r.data),e=>e.charCodeAt(0)).buffer:r.data;"string"==typeof e?dy(t,dh,{socketTaskId:a,data:e,dataType:"string"}):e instanceof ArrayBuffer&&dy(t,dh,{socketTaskId:a,data:ob(e),dataType:"base64"})}else("close"===r.type||"error"===r.type)&&(l(),dy(t,dp,{socketTaskId:a,status:"close"===r.type?"closed":"failed",code:r.code,reason:r.reason,errMsg:r.message,protocolType:c}))}catch{n.close()}}),n.addEventListener("close",()=>{o||(l(),dy(t,dp,{socketTaskId:a,status:s.opened?"closed":"failed",code:1006,reason:"WebSocket bridge disconnected",protocolType:c}))}),n.addEventListener("error",()=>{o||(l(),n.close(),dy(t,dp,{socketTaskId:a,status:"failed",errMsg:"WebSocket error",protocolType:n.protocol}))}),{socketTaskId:a}}(e.params,t)),"doubao.sendSocketData":(e,t)=>(!function(e,t){let r;if(!["string","base64"].includes(e.dataType)||"string"!=typeof e.data)throw new w("unsupported dataType or data",104);let i=e.socketTaskId;try{r="base64"===e.dataType?Uint8Array.from(atob(e.data.replace(/[^A-Za-z0-9+/=]/g,"")),e=>e.charCodeAt(0)).buffer:e.data}catch(t){let e=new w("invalid base64 data",104);throw e.cause=t,e}!function(e,t){let{socket:r,opened:i}=df(e.socketTaskId,t),n=e.data;if("string"!=typeof n&&!(n instanceof ArrayBuffer))throw new w("data must be a string or ArrayBuffer",104);if(dv(),!i||1!==r.readyState)throw new w("WebSocket is not open",1501002);try{r.send(JSON.stringify({type:"send",binary:n instanceof ArrayBuffer,data:n instanceof ArrayBuffer?ob(n):n}))}catch(t){let e=new w("Failed to send WebSocket data",305);throw e.cause=t,e}}({socketTaskId:i,data:r},t)}(e.params,t),_(e,{})),"doubao.closeSocket":(e,t)=>(!function(e,t){let r=df(e.socketTaskId,t),{socket:i}=r,n=e.code??1e3;if(!Number.isInteger(n)||!(n>=1e3&&n<=1014&&![1004,1005,1006].includes(n)||n>=3e3&&n<=4999)||void 0!==e.reason&&("string"!=typeof e.reason||new TextEncoder().encode(e.reason).byteLength>123))throw new w("invalid close code or reason",104);if(!r.opened)return r.cancel(n,e.reason);try{i.send(JSON.stringify({type:"close",code:n,reason:e.reason}))}catch(t){let e=new w("Failed to close WebSocket",305);throw e.cause=t,e}}(e.params,t),_(e,{}))},...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{"doubao.requestOrder":t=>lG(t,async()=>{let r=await lO.SandboxRequestOrder({app_key:lW(e),data:lH(t.params,"data"),db_authorization:lH(t.params,"dbAuthorization")});return r.err_code||!r.order_id?lV(t,r,o6):_(t,{orderId:r.order_id,logId:r.log_id||""})}),"doubao.getOrderPayment":t=>lG(t,async()=>{var r,i;let n=lH(t.params,"orderId"),a=await lO.SandboxGetOrderPayment({app_key:lW(e),aweme_bind_status:!0,order_id:n,platform_signed_pt_code:null==(i=t.params)||null==(r=i.platformSignedPtCode)?void 0:r.trim()});if(a.err_code||!a.pay_data)return lV(t,a,oH);try{await lJ(a.pay_data,e)}catch(e){return lV(t,a,oH,!1,e)}return _(t,{orderId:n,logId:a.log_id||""})}),"doubao.getOrderPaymentWithSign":t=>lG(t,async()=>{let r=lH(t.params,"orderId"),i=await lO.SandboxGetOrderPaymentWithSign({app_key:lW(e),aweme_bind_status:!0,order_id:r,sign_data:lH(t.params,"signData"),sign_db_authorization:lH(t.params,"signDbAuthorization")});if(i.err_code||!i.pay_data)return lV(t,i,oV);try{await lJ(i.pay_data,e)}catch(e){return lV(t,i,oV,!1,e)}return _(t,{orderId:r,logId:i.log_id||""})}),"doubao.getPlatformSignInfo":e=>_(e,{signInfo:""}),"doubao.createSignOrder":t=>lG(t,async()=>{let r=await lO.SandboxCreateSignOrder({app_key:lW(e),data:lH(t.params,"data"),db_authorization:lH(t.params,"dbAuthorization")});return r.err_code||!r.auth_order_id?lV(t,r,li):_(t,{authOrderId:r.auth_order_id,logId:r.log_id||""})}),"doubao.sign":t=>lG(t,async()=>{let r=await lO.SandboxGetSignPageData({app_key:lW(e),auth_order_id:lH(t.params,"orderId"),aweme_bind_status:!0});return r.err_code||!r.data?lV(t,r,lc,!0):_(t,{})},!0),"doubao.login":async t=>_(t,{code:await lK(e)}),"doubao.loginWithDoubaoWidget":e=>_(e,{result:!0}),"doubao.postLoginResult":async t=>{var r,i,n,a;let s,o=t.params;if(!1===o.result)return null==(n=e.onPrivacyLoginCardClose)||n.call(e,"login"),await (null==(a=e.onGrantingCompleted)?void 0:a.call(e,"login",{noLogin:!0})),_(t,{});let l=o.code;if(!l)throw new lm(oL);try{s=await lO.SandboxApiExchangeCode({app_key:lW(e),code:l,version_tag:lj})}catch(e){throw lN(e,"login")}return lA(s,"login"),null==(r=e.onPrivacyLoginCardClose)||r.call(e,"login"),await (null==(i=e.onGrantingCompleted)?void 0:i.call(e,"login")),_(t,{})},"doubao.getPrivacySetting":async t=>{var r;let i;try{i=await lO.SandboxApiCheckPrivacyOrLoginStatus({app_key:lW(e),check_type:1,version_tag:lj})}catch(e){throw lN(e,"privacy")}return lA(i,"privacy"),_(t,{needAuthorization:(null==(r=i.data)?void 0:r.PrivacyAgreed)===!1})},"applet.agreePrivacyAuthorization":async t=>{var r,i;let n;try{n=await lO.SandboxApiAcceptPrivacy({app_key:lW(e)})}catch(e){throw lN(e,"privacy")}return lA(n,"privacy"),null==(r=e.onPrivacyLoginCardClose)||r.call(e,"privacy"),await (null==(i=e.onGrantingCompleted)?void 0:i.call(e,"privacy")),_(t,{result:!0})},"applet.getPhoneNumber":async t=>_(t,{code:await lK(e,"profile","user_info,mobile"),message:"success"}),"applet.openLoginPage":t=>{var r,i;let n=null==(r=t.params)?void 0:r.url;return n&&(null==(i=e.onCustomLoginNavigate)||i.call(e,n)),_(t,{})},"applet.closePrivacyLoginCard":t=>{var r,i;return null==(i=e.onPrivacyLoginCardClose)||i.call(e,(null==(r=t.params)?void 0:r.type)||""),_(t,{})},"applet.reportAppLog":e=>_(e,{}),"applet.open":e=>{var t;let r=null==(t=e.params)?void 0:t.schema;return r&&window.open(r,"_blank","noopener,noreferrer"),_(e,{})},"doubao.__debuggerUpdateSandboxBusinessInfo":async e=>{let t=e.params,r=t.csrPem,i=t.locationInfo;return _(e,await lZ({csrPem:r,locationInfo:i,phoneNum:t.phoneNum||""}))},...e.onCustomLoginNavigate?{"doubao.navigateTo":t=>{var r,i;let n=null==(r=t.params)?void 0:r.url;return n&&(null==(i=e.onCustomLoginNavigate)||i.call(e,n)),_(t,{})}}:{}}}(t),...function(){var e;let t,r,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{"doubao.openSetting":{canIUse:!!i.showSimulatorPermissionSettings,handler:async(e,t)=>{var r,n;let a=null==(r=e.params)?void 0:r.withSubscriptions;if(!0===a)return S(e,"subscription templates are not supported yet");if(void 0!==a&&!1!==a)return S(e,"withSubscriptions must be a boolean",104);let s=i.showSimulatorPermissionSettings;if(!s)return S(e,"settings presenter is unavailable");let o=i.appId||"unknown-app";if(oC.has(o))return S(e,"openSetting is already in progress");oC.add(o);let l=new AbortController,d=null==t||null==(n=t.events)?void 0:n.onDestroy(()=>l.abort()),u=sV(o);try{return await new Promise((e,t)=>{let r=()=>t(Error("settings view was destroyed"));(l.signal.addEventListener("abort",r,{once:!0}),l.signal.aborted)?r():s({appId:o,appIcon:i.appIcon,appName:i.appName||"应用插件",authSetting:u,signal:l.signal,onChange:(e,t)=>{!l.signal.aborted&&Object.hasOwn(u,e)&&(sG(o,e,t?"granted":"denied"),oi.isLocationScope(e)&&oi.updateUserAuthorization(t))}}).then(e,t)}),_(e,{authSetting:sV(o)})}finally{null==d||d(),l.abort(),oC.delete(o)}}},"doubao.getSetting":e=>{var t;let r=null==(t=e.params)?void 0:t.withSubscriptions;return!0===r?S(e,"subscription templates are not supported yet",103):void 0!==r&&!1!==r?S(e,"withSubscriptions must be a boolean",104):_(e,{authSetting:sV(i.appId||"unknown-app")})},"doubao.authorize":async(e,t)=>{var r,n,a;let s=null==(r=e.params)?void 0:r.scope;if("scope.healthData"===s){let t=nL.getSystem().healthData;if(!t)return S(e,"Health data simulation is not configured",103);let r=null==(a=e.params.options)?void 0:a.types;return!Array.isArray(r)||0===r.length||r.some(e=>"string"!=typeof e||!e.trim())?S(e,"options.types must be a non-empty supported health data type list",104):t.requestCompleted?_(e,{}):S(e,"Health data authorization failed",102)}if("string"!=typeof s||!oE.has(s)||void 0!==i.declaredScopes&&!i.declaredScopes.includes(s))return S(e,`invalid scope: ${String(s)}`,104);let o=new AbortController,l=null==t||null==(n=t.events)?void 0:n.onDestroy(()=>o.abort());try{let r=await oT(i,s,!1,t,o.signal);if(o.signal.aborted)return S(e,"operation cancelled",114);if(!r)return S(e,"user permission denied",107);return oN(s)?S(e,"system permission denied",106):_(e,{})}finally{null==l||l(),o.abort()}},...(e=async(e,t)=>{if(oN("scope.record"))throw new w("system permission denied",106);let r=await oT(i,"scope.record",!1,e,t);if(oN("scope.record"))throw new w("system permission denied",106);return r},r=!1,{"doubao.operateRecorder":{canIUse:oI,handler:async(i,n)=>{let a=i.params;switch(a.operationType){case"start":{var s;if(r)throw new w("recorder is starting",104);r=!0;let i=new AbortController,o=null==n||null==(s=n.events)?void 0:s.onDestroy(()=>i.abort());try{let r=await e(n,i.signal);if(i.signal.aborted)throw new w("operation cancelled",114);if(!r)throw new w("user permission denied",102);null==t||t.destroy(),t=new ok(a,n),await t.start()}finally{null==o||o(),i.abort(),r=!1}break}case"pause":case"resume":case"stop":if(!t)throw new w("recorder is not started",104);await t[a.operationType]();break;default:throw new w("invalid recorder operation",104)}return _(i,{})}}})}}(t),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{"doubao.sendFollowUpMessage":async t=>{if(!e.sendFollowUpMessage)throw Error("sendFollowUpMessage is not configured in web-sdk-debugger");return await e.sendFollowUpMessage(function(e){let t=e.content;if(!Array.isArray(t)||0===t.length)throw Error("content must be a non-empty array");let r=!1;for(let e of t){if(!rP(e))throw Error("content items must be objects");if("text"===e.type){if("string"!=typeof e.text)throw Error("text content must be a string");r||=!!e.text.trim();continue}if("api/call"===e.type){if(!rP(e.data)||"string"!=typeof e.data.name||!e.data.name.trim()||!rP(e.data.arguments))throw Error("api/call content must include a name and arguments object");continue}if("responseHint"===e.type){if(!rP(e.data)||void 0!==e.data.userAction&&"string"!=typeof e.data.userAction||void 0!==e.data.responseGuidance&&"string"!=typeof e.data.responseGuidance)throw Error("responseHint content must include valid string guidance fields");continue}throw Error('content type must be "text", "api/call", or "responseHint"')}if(!r)throw Error("content must include a non-empty text message");return{content:t}}(t.params)),_(t,{})},"doubao.multiMediaBroadcast":async t=>_(t,await s0(function(e){if("play"!==e.action&&"pause"!==e.action)throw Error('action must be "play" or "pause"');return{action:e.action,mediaId:"string"==typeof e.mediaId&&e.mediaId.trim()?e.mediaId.trim():void 0}}(t.params),e.multiMediaBroadcastContainer))}}(t)}}({...r,requestHandler:r.requestHandler??(null==(t=r.baseAPIRegistry)?void 0:t.get("doubao.request"))}),{override:!0}),i.registerEventSources({...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;return{"doubao.onBatteryInfoChange":t=>{let r=e.getBattery().isLowPowerModeEnabled;return e.subscribe("battery",()=>{let{isLowPowerModeEnabled:i}=e.getBattery();r!==i&&(r=i,t({isLowPowerModeEnabled:i}))})}}}(),...sv("Accelerometer"),...sv("Gyroscope"),...sv("Compass"),...sv("DeviceMotion"),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:dw;return{"doubao.onWifiConnected":e.subscribe}}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:sB;return Object.fromEntries([sq,s$,"doubao.onBLEConnectionStateChange","doubao.onBLECharacteristicValueChange"].map(t=>[t,{source:()=>void 0,onSubscribe:(t,r)=>e.wake(t,r)}]))}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL,t=new WeakMap;return{[e1]:{source:()=>void 0,onSubscribe:(r,i)=>{if(t.has(r))return;let n=()=>r.emit(e1,{globalProps:{appTheme:sn(e)},apiResults:{...l7(i,e),"doubao.getSystemSetting":dt(i,e),"doubao.getAppAuthorizeSetting":dr(i,e)}}),a=!1;if(r.onDestroy(()=>{var e;a=!0,null==(e=t.get(r))||e(),t.delete(r)}),a)return;let s=[sa(e,n),e.subscribe("location",n),e.subscribe("system",n),e.subscribe("bluetooth",n),e.subscribe("wifi",n),oi.subscribe(n)];t.set(r,()=>s.forEach(e=>e())),n()}}}}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;return{onThemeChange:t=>{let r=sn(e),i=!0,n=sa(e,()=>{let n=sn(e);n!==r&&(r=n,queueMicrotask(()=>{i&&t({appTheme:n})}))});return()=>{i=!1,n()}}}}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:l9,r=new WeakMap;return Object.fromEntries(["doubao.onUserCaptureScreen","doubao.onUserScreenRecord"].map(i=>[i,{source:()=>void 0,onSubscribe:n=>{let a;"doubao.onUserScreenRecord"===i&&!0===e.getScreen().recording&&n.emit(i,{state:"start"});let s=r.get(n)??new Set;if(s.has(i))return;s.add(i),r.set(n,s);let o="doubao.onUserCaptureScreen"===i?t.subscribeCapture(()=>{t.getSnapshot().screenRecordDisabled||n.emit(i,{})}):(a=e.getScreen().recording,e.subscribe("screen",()=>{let t=e.getScreen().recording;t!==a&&void 0!==t&&n.emit(i,{state:t?"start":"stop"}),a=t}));n.onDestroy(()=>{o(),s.delete(i)})}}]))}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL,t=new WeakSet,r="doubao.onKeyboardHeightChange";return{[r]:{source:()=>void 0,canIUse:e=>!(null==e?void 0:e.containerType)||"PAGE"===e.containerType,onSubscribe:(i,n)=>{let a=null==n?void 0:n.element;if(!a||t.has(i)||n.containerType&&"PAGE"!==n.containerType)return;t.add(i);let s=!1,o=0,l=()=>{if(s)return;let t=s8(),n=s9(t,a)&&t&&"none"!==t.getAttribute("inputmode")&&(t instanceof HTMLTextAreaElement?!t.disabled&&!t.readOnly:t instanceof HTMLInputElement?!t.disabled&&!t.readOnly&&!["button","submit","reset","checkbox","radio","range","color","file","hidden"].includes(t.type):t.matches('[contenteditable="true"], [contenteditable=""]'))?e.getKeyboard().height:0;o!==n&&(o=n,i.emit(r,{height:o}))},d=()=>queueMicrotask(l);a.addEventListener("focusin",l),a.addEventListener("focusout",d);let u=e.subscribe("keyboard",l);l(),i.onDestroy(()=>{s=!0,a.removeEventListener("focusin",l),a.removeEventListener("focusout",d),u(),t.delete(i)})}}}}(),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL;return{"doubao.onNetworkStatusChange":t=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nL,r=oh(t);return t.subscribe("network",()=>{let i=oh(t);(i.isConnected!==r.isConnected||i.networkType!==r.networkType)&&(r=i,e(i))})})(e=>t({isConnected:e.isConnected,networkType:e.networkType}),e)}}(),...Object.fromEntries(["downloadProgressUpdate","downloadFileHeadersReceived","uploadFileProgressUpdate","uploadFileHeadersReceived"].map(e=>[e,()=>void 0])),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:oi,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nL;return Object.fromEntries(["doubao.onLocationChange","doubao.onLocationChangeError"].map(r=>{let i=new WeakMap;return[r,{source:()=>void 0,onSubscribe:n=>{if(i.has(n))return;let a=()=>{let i=ol(t);i&&e.isUpdating&&"doubao.onLocationChangeError"===r&&n.emit(r,{errMsg:i,errCode:"location_service_disabled"===i?102:106})},s=e.subscribeLocation(e=>{var i;let s,o;ol(t)?a():("doubao.onLocationChange"===r&&"success"===e.status&&n.emit(r,{latitude:(i=e.location).latitude,longitude:i.longitude,speed:i.speed,accuracy:i.accuracy,altitude:i.altitude,verticalAccuracy:i.altitudeAccuracy,horizontalAccuracy:i.accuracy}),"doubao.onLocationChangeError"===r&&"success"!==e.status&&n.emit(r,(s="user_unauthorized"===e.status||1===e.code,o="user_unauthorized"!==e.status&&3===e.code,{errMsg:s?"location_permission_denied":o?"location_timeout":"location_fail",errCode:s?"user_unauthorized"===e.status?107:106:o?115:102})))}),o=ol(t),l=t.subscribe("location",()=>{let e=ol(t);e!==o&&(o=e,a())}),d=()=>{s(),l(),i.delete(n)};i.set(n,d),n.onDestroy(d)}}]}))}(),...{[dp]:()=>void 0,[dh]:()=>void 0},...{[ow]:{canIUse:oI,source:()=>void 0}},...{[sk]:{source:()=>void 0,canIUse:sC}},...{[sT]:{source:()=>void 0,canIUse:sA}}},{override:!0}),i}function dI(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{apiRegistry:e.apiRegistry??dx(e),scanCodePresenter:e.scanCodePresenter,uiPresenter:e.uiPresenter}}var dk=r(17228);function dC(e,t,r){var i;null==e||e({category:"mcp",source:"local_mcp",trace_id:null==r||null==(i=r.trace)?void 0:i.trace_id,trace:null==r?void 0:r.trace,...t})}function dE(e){return{name:e.name,description:e.description||"",input_schema_json:r6(e.inputSchema??{type:"object",additionalProperties:!0})}}async function dN(e,t){var r,i,n;null==(r=t.signal)||r.throwIfAborted();let a=new dk.Kj({name:"web-sdk-debugger",version:"0.0.1"},{versionNegotiation:{mode:"auto"}}),s=new dk.jS(new URL(e),{fetch:t.fetcher,requestInit:t.headers?{headers:t.headers}:void 0}),o=()=>{dT(l)},l={client:a,transport:s,removeAbortListener:()=>{var e;return null==(e=t.signal)?void 0:e.removeEventListener("abort",o)}};null==(i=t.signal)||i.addEventListener("abort",o,{once:!0});try{await a.connect(s,{signal:t.signal}),null==(n=t.signal)||n.throwIfAborted()}catch(e){throw await dT(l),e}return l}async function dT(e){e.removeAbortListener(),await e.transport.close().catch(()=>void 0),await e.client.close().catch(()=>void 0)}let dA=new Set(["log","info","warn","error","debug"]);function dM(){return{entries:[],nextEntryId:0}}function dR(e){if(e instanceof Error)return e.stack||e.message;if("string"==typeof e)return e;if(void 0===e)return"undefined";if("function"==typeof e)return e.toString();try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}function dj(e){return"number"==typeof e&&Number.isFinite(e)?Math.max(e-1,0):0}function dP(e){let t=[e.url,e.src,e.getAttribute("url"),e.getAttribute("src")].find(e=>"string"==typeof e&&e.trim());return"string"==typeof t?t.trim():void 0}function dL(e,t){var r;let i=e.trim(),n=i.match(/^(.*):(\d+):(\d+)$/)??i.match(/^(.*):(\d+)$/);if(!n)return null;let[,a,s,o]=n;if(!a)return null;let l=t&&("<anonymous>"===a||a.endsWith(", <anonymous>")||/^eval at\b.*<anonymous>$/.test(a))?t:void 0,d=l&&/\.web\.bundle(?:[?#]|$)/.test(l)?2:0;return{url:l??a,lineNumber:Math.max(dj(Number(s))-d,0),columnNumber:void 0===o?0:"number"==typeof(r=Number(o))&&Number.isFinite(r)?Math.max(r-1,0):0}}function dO(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"!=typeof e)return;let r=e.split("\n").map(e=>(function(e,t){let r=e.trim(),i=r.startsWith("at ")?r.slice(3).trim():r,n=i.match(/^(.*?)\s+\((.*)\)$/);if(n){let[,e,r]=n,i=dL(r,t);return i?{functionName:e,scriptId:"",...i}:null}let a=dL(i,t);return a?{functionName:"",scriptId:"",...a}:null})(e,t.fallbackSourceUrl)).filter(e=>!!e),i=t.dropFirstFrame&&r.length>1?r.slice(1):r,n=i.filter(e=>!(e.url.includes("console-recorder")||e.url.includes("web-sdk-debugger")||/capture.*Stack|console\.(?:log|info|warn|error|debug)/.test(e.functionName))),a=n.length>0?n:i;return a.length>0?{callFrames:a}:void 0}function dD(e){let t=null==e?void 0:e.callFrames[0];return t?{url:t.url,lineNumber:t.lineNumber,columnNumber:t.columnNumber}:void 0}function dU(e){return e?{callFrames:[{functionName:"",scriptId:"",...e}]}:void 0}function dq(e){return e?`[${e}] `:""}class d${target;store;listeners=new Set;constructor(e,t=dM()){this.target=e,this.store=t,this.target.addEventListener("error",this.handleRuntimeError),this.target.addEventListener(sb,this.handleRuntimeConsole),this.drainPendingRuntimeConsoleEvents()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getEntries(){return this.store.entries}clear(){this.store.entries.length=0,this.notify()}evaluate(e){let t=this.getFirstIframeWindow()?"iframe":"host",r=this.getFirstIframeWindow()??window;this.addEntry("eval","eval",`> ${e}`);try{let i=r.eval(e),n=dR(i);return this.addEntry("eval","iframe"===t?"iframe":"eval",n),{ok:!0,value:n}}catch(t){let e=dR(t);return this.addEntry("error","eval",e),{ok:!1,value:e}}}destroy(){this.target.removeEventListener("error",this.handleRuntimeError),this.target.removeEventListener(sb,this.handleRuntimeConsole),this.listeners.clear()}addEntry(e,t,r){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};this.store.entries.push({id:`console-${++this.store.nextEntryId}`,level:e,source:t,timestamp:Date.now(),message:r,...i}),this.store.entries.length>1e3&&this.store.entries.splice(0,this.store.entries.length-1e3),this.notify()}getFirstIframeWindow(){let e=this.target.shadowRoot;if(!e)return null;for(let t of Array.from(e.querySelectorAll("iframe")))try{if(t.contentWindow)return t.contentWindow}catch{break}return null}handleRuntimeError=e=>{let t,r,i,n,a,s=(r=null==(t=e.detail)?void 0:t.error,i=e.currentTarget instanceof HTMLElement?dP(e.currentTarget):void 0,a=dD(n=dO(null==r?void 0:r.stack,{fallbackSourceUrl:i}))??function(e){var t,r,i,n,a,s;if((null==e?void 0:e.fileName)||(null==e?void 0:e.release)||(null==e||null==(t=e.sourceMap)?void 0:t.offset))return{url:e.fileName??e.release??"runtime",lineNumber:dj(null==(i=e.sourceMap)||null==(r=i.offset)?void 0:r.line),columnNumber:"number"==typeof(s=null==(a=e.sourceMap)||null==(n=a.offset)?void 0:n.col)&&Number.isFinite(s)?Math.max(s,0):0}}(t),"string"==typeof(null==r?void 0:r.message)&&r.message?{message:r.message,metadata:{location:a,stackTrace:n??dU(a)}}:{message:dR(r??t??e),metadata:{location:a,stackTrace:n??dU(a)}});this.addEntry("error","runtime",s.message,s.metadata)};handleRuntimeConsole=e=>{let t=e.detail;("string"==typeof(null==t?void 0:t.message)||Array.isArray(null==t?void 0:t.args))&&(e.preventDefault(),this.addRuntimeConsoleEntry(t))};drainPendingRuntimeConsoleEvents(){var e;let t;for(let r of(e=this.target,t=sw.get(e)??[],sw.delete(e),t))this.addRuntimeConsoleEntry(r)}addRuntimeConsoleEntry(e){var t;let r=e.stackTrace??dO(e.stack,{dropFirstFrame:!0,fallbackSourceUrl:dP(this.target)}),i=e.location??dD(r),n="string"==typeof e.message?e.message:(e.args??[]).map(dR).join(" "),a="string"==typeof e.pagePath&&e.pagePath?e.pagePath:void 0,s="string"==typeof e.label&&e.label?e.label:a;this.addEntry((t=e.level,dA.has(t)?t:"log"),"runtime",`${dq(s)}${n}`,{args:function(e,t){if(!e||!t)return e;let r=dq(t).trim(),i="app"===t?"color: #3b82f6":"color: #16a34a",[n,...a]=e;return"string"==typeof n?[`%c%s%c ${n}`,i,r,"",...a]:["%c%s%c",i,r,"",...e]}(e.args??[n],s),location:i,pagePath:a,stackTrace:r??dU(i)})}notify(){for(let e of this.listeners)e()}}let dB="doubao-component",dF="doubao-host-attrs",dz=new Map([["x-view","view"],["x-text","text"],["x-image","image"],["x-list","list"],["x-svg","svg"],["x-textarea","textarea"],["x-input","input"],["x-input-ng","input"],["x-canvas","canvas"],["x-markdown","markdown"]]);function dW(e){return e.getAttribute(dB)||null}function dH(e){let t=e.tagName.toLowerCase();return dW(e)??dz.get(t)??t}function dV(e){return Array.from(e).filter(e=>e&&!e.startsWith("doubao-"))}let dG=new Set(["IFRAME","LINK","SCRIPT","STYLE","TEMPLATE"]),dJ=new Set(["data-wsd-node-id"]),dK=new Set(["part","lynx-default-overflow-visible"]),dZ=new Set(["style","data-wsd-node-id"]);function dX(e){return e.nodeType===Node.ELEMENT_NODE&&!dG.has(e.tagName)}function dY(e){var t;return e.nodeType===Node.TEXT_NODE&&!!(null==(t=e.textContent)?void 0:t.trim())}function dQ(e){return e.nodeType===Node.DOCUMENT_FRAGMENT_NODE?"#shadow-root":e.nodeType===Node.TEXT_NODE?"#text":e.tagName.toLowerCase()}function d0(e){if(!Number.isFinite(e))return"0";let t=Math.round(100*e)/100;return Number.isInteger(t)?String(t):t.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function d1(e){return Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0")}function d2(e){let t=e.trim(),r=Number.parseFloat(t);return Number.isFinite(r)&&0===r?"0":t}function d3(e){let t=Number.parseFloat(e);return Number.isFinite(t)?t:0}function d4(e){var t,r,i;let n=null==(t=e.getAttribute("aria-label"))?void 0:t.trim();if(n)return n;let a=null==(r=e.getAttribute("title"))?void 0:r.trim();if(a)return a;if(e instanceof HTMLImageElement)return e.alt.trim();if(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement){let t=Array.from(e.labels??[]).map(e=>{var t;return null==(t=e.textContent)?void 0:t.replace(/\s+/g," ").trim()}).filter(Boolean).join(" ");if(t)return t}return e instanceof HTMLButtonElement||e instanceof HTMLAnchorElement?(null==(i=e.textContent)?void 0:i.replace(/\s+/g," ").trim())??"":""}function d6(e){var t;let r=null==(t=e.getAttribute("role"))?void 0:t.trim();if(r)return r;switch(e.tagName){case"A":return e.hasAttribute("href")?"link":"generic";case"BUTTON":return"button";case"IMG":return"img";case"INPUT":case"TEXTAREA":return"textbox";case"SELECT":return"combobox";default:return"generic"}}function d5(e){return!e.hasAttribute("disabled")&&"true"!==e.getAttribute("aria-disabled")&&(!!(e.isContentEditable||e instanceof HTMLAnchorElement&&e.hasAttribute("href"))||e.tabIndex>=0)}function d8(e){return Array.from(e.attributes).filter(e=>!dJ.has(e.name)).map(e=>({name:e.name,value:e.value}))}function d9(e){let t=document.createElement("template");return t.innerHTML=e,t.content}function d7(e){return dJ.has(e)||dK.has(e)}function ue(e){return"DIV"===e.tagName&&"page"===e.getAttribute("part")}function ut(e,t){return dJ.has(t)||ue(e)&&d7(t)}function ur(e,t){for(let r of t)ut(e,r.name)||e.setAttribute(r.name,r.value)}function ui(e){return d8(e).filter(t=>!ut(e,t.name))}function un(e,t,r){let i=new Map(t.map(e=>[e.name,e.value])),n=new Map(r.map(e=>[e.name,e.value])),a=r.filter(e=>i.get(e.name)!==e.value),s=t.filter(e=>!n.has(e.name)).map(e=>e.name);return a.length||s.length?[{type:"attributes",nodeId:e,before:t,modified:a,removed:s}]:[]}function ua(e){return Array.from(e.childNodes).filter(e=>dX(e)||dY(e))}function us(e,t,r){let i=("elementFromPoint"in e&&"function"==typeof e.elementFromPoint?e.elementFromPoint.bind(e):document.elementFromPoint.bind(document))(t,r);for(;(null==i?void 0:i.shadowRoot)&&"function"==typeof i.shadowRoot.elementFromPoint;){let e=i.shadowRoot.elementFromPoint(t,r);if(!e||e===i)break;i=e}return i}function uo(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(t>8)return null;let r=null;for(let i of Array.from(e.children)){let e=i.getBoundingClientRect(),n=e.width>0||e.height>0?{rect:e,styleSource:i}:i.shadowRoot&&uo(i.shadowRoot,t+1)||uo(i,t+1);n&&(r=r?{rect:function(e,t){let r=Math.min(e.left,t.left),i=Math.min(e.top,t.top);return new DOMRect(r,i,Math.max(e.right,t.right)-r,Math.max(e.bottom,t.bottom)-i)}(r.rect,n.rect),styleSource:r.styleSource}:n)}return r}function ul(e){let t=e.getBoundingClientRect();return t.width>0||t.height>0?{rect:t,styleSource:e}:e.shadowRoot&&uo(e.shadowRoot)||uo(e)||{rect:t,styleSource:e}}function ud(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement??null;for(;t;){if(dG.has(t.tagName))return!0;t=t.parentElement}return!1}class uu{target;nodeIds=new WeakMap;nodes=new Map;onChange;nextNodeId=0;mutationObserver=null;notifyTimer=null;constructor(e,t){this.target=e,this.onChange=t,this.observe()}getDocument(){let e=this.getRoot();return e?(this.nodes.clear(),this.serializeNode(e,!0)):null}getNode(e){return this.nodes.get(e)??null}getElement(e){let t=this.getNode(e);return t instanceof HTMLElement?t:null}setAttributesAsText(e,t,r){let i=function(e){let t=e.trim();if(!t)return[];let r=document.createElement("template");r.innerHTML=`<div ${t}></div>`;let i=r.content.firstElementChild;return i?d8(i):[]}(t),n=null==r?void 0:r.trim();return this.editElementAttributes(e,e=>{n&&!ut(e,n)&&e.removeAttribute(n),ur(e,i)})}setAttributeValue(e,t,r){let i=t.trim();return i?this.editElementAttributes(e,e=>{if(ut(e,i))return!1;e.setAttribute(i,r)}):[]}removeAttribute(e,t){let r=t.trim();return r?this.editElementAttributes(e,e=>{if(ut(e,r))return!1;e.removeAttribute(r)}):[]}setNodeValue(e,t){return this.runWithoutObservation(()=>{let r=this.getNode(e),i=(null==r?void 0:r.textContent)??"";return(null==r?void 0:r.nodeType)!==Node.TEXT_NODE||i===t?[]:(r.textContent=t,[{type:"characterData",nodeId:e,value:t,previousValue:i}])})}setNodeName(e,t){return this.runWithoutObservation(()=>{let r=this.getElement(e),i=t.trim();if(!r||!i)return{nodeId:null,mutations:[]};if(ue(r))return{nodeId:e,mutations:[]};let n=r.parentNode,a=this.getPreviousInspectableSiblingId(r),s=function(e,t){let r=document.createElement(t);for(let t of Array.from(e.attributes))r.setAttribute(t.name,t.value);for(;e.firstChild;)r.append(e.firstChild);return e.replaceWith(r),r}(r,i);return{nodeId:this.getNodeId(s),mutations:n?[this.getChildListMutation(n,[e],[{previousNodeId:a,node:this.serializeNode(s)}])]:[]}})}setOuterHTML(e,t){return this.runWithoutObservation(()=>{let r=this.getNode(e);if(!r)return[];if(r instanceof DocumentFragment){let e=ua(r).map(e=>this.getNodeId(e)),i=d9(t);return r.replaceChildren(...Array.from(i.childNodes)),[this.getChildListMutation(r,e,this.getInsertedNodeMutations(r,null,ua(r)))]}if(r instanceof Element&&ue(r)){let i=ui(r),n=ua(r).map(e=>this.getNodeId(e));!function(e,t){let r=d9(t),i=r.firstElementChild;if(!i)return e.replaceChildren(...Array.from(r.childNodes));for(let t of Array.from(e.attributes))d7(t.name)||e.removeAttribute(t.name);ur(e,d8(i)),e.replaceChildren(...Array.from(i.childNodes))}(r,t);let a=this.getInsertedNodeMutations(r,null,ua(r));return[...un(e,i,ui(r)),this.getChildListMutation(r,n,a)]}let i=r.parentNode;if(!i)return[];let n=this.getPreviousInspectableSiblingId(r),a=d9(t),s=ua(a);return i.replaceChild(a,r),[this.getChildListMutation(i,[e],this.getInsertedNodeMutations(i,n,s))]})}getNodeIdAtPoint(e,t){let r,i,n=this.getRoot(),a=this.target.shadowRoot,s=(r=null,(i=n=>{for(let a of(dX(n)&&function(e,t,r){let{rect:i}=ul(e);return i.width>0&&i.height>0&&t>=i.left&&t<=i.right&&r>=i.top&&r<=i.bottom}(n,e,t)&&(r=n),Array.from(n.childNodes)))dX(a)&&i(a)})(n),r),o=a?us(a,e,t):us(document,e,t),l=(s&&n.contains(s)?s:null)??(o&&n.contains(o)?o:null);if(!l)return null;let d=l;for(;d&&!dX(d);)d=d.parentNode??function(e){let t=e.getRootNode();return t instanceof ShadowRoot?t.host:null}(d);return d&&n.contains(d)?this.getNodeId(d):null}findLynxViews(){return function(e){let t=[],r=[e];for(;r.length;){let e=r.shift();for(let i of(e instanceof HTMLElement&&"LYNX-VIEW"===e.tagName&&t.push(e),e instanceof Element&&e.shadowRoot&&r.push(e.shadowRoot),e.children??[]))r.push(i)}return t}(this.target)}findNodeIdByLynxUniqueId(e){let t=function(e,t){let r=[e];for(;r.length;){let e=r.shift();if(e instanceof HTMLElement&&function(e){for(let t of Object.getOwnPropertySymbols(e))if("uniqueId"===t.description){let r=e[t];return"number"==typeof r?r:null}return null}(e)===t)return e;for(let t of(e instanceof Element&&e.shadowRoot&&r.push(e.shadowRoot),e.children??[]))r.push(t)}return null}(this.getRoot(),e);return t?this.getNodeId(t):null}getHighlight(e,t){var r,i;let n,a,s,o,l,d,u,c,p,h,m,g,f,v,y=this.getElement(e);if(!y||!y.isConnected)return null;let{rect:b,styleSource:w}=ul(y),_=t.getBoundingClientRect(),S=t.offsetWidth?_.width/t.offsetWidth:1,x=t.offsetHeight?_.height/t.offsetHeight:1,I=b.width/S,k=b.height/x,C=getComputedStyle(w),E=C.backgroundColor.trim(),N=(r=C.paddingTop,i=C.paddingRight,(n=[r,i,C.paddingBottom,C.paddingLeft].map(d2)).every(e=>"0"===e)?null:n.every(e=>e===n[0])?n[0]:n[0]===n[2]&&n[1]===n[3]?`${n[0]} ${n[1]}`:n[1]===n[3]?`${n[0]} ${n[1]} ${n[2]}`:n.join(" "));return{left:(b.left-_.left)/S,top:(b.top-_.top)/x,width:I,height:k,nodeName:dH(y),selector:function(e){let t=e.id.trim();if(dW(e)){let t=(e.getAttribute(dF)??"").split(/\s+/).filter(Boolean).includes("class")?e.firstElementChild:e;return{tagName:dH(e),classNames:dV((null==t?void 0:t.classList)??[])}}return{tagName:dH(e),id:t,classNames:Array.from(e.classList).filter(Boolean)}}(y),boxModel:(a=d3(C.borderTopWidth),s=d3(C.borderRightWidth),o=d3(C.borderBottomWidth),l=d3(C.borderLeftWidth),d=d3(C.paddingTop),u=d3(C.paddingRight),c=d3(C.paddingBottom),p=l+d3(C.paddingLeft),{content:{left:p,top:h=a+d,width:Math.max(0,I-p-s-u),height:Math.max(0,k-h-o-c)}}),dimensions:`${d0(I)} \xd7 ${d0(k)}`,styles:[...E?[{name:"Background",value:(g=(m=E.trim()).match(/^rgb\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*\)$/i),f=m.match(/^rgba\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d?(?:\.\d+)?)\s*\)$/i),(v=g??(f&&1===Number(f[4])?f:null))?`#${d1(Math.round(Number(v[1])))}${d1(Math.round(Number(v[2])))}${d1(Math.round(Number(v[3])))}`:m),swatch:E}]:[],...N?[{name:"Padding",value:N}]:[]],accessibility:{name:d4(y),role:d6(y),keyboardFocusable:d5(y)}}}destroy(){var e;null==(e=this.mutationObserver)||e.disconnect(),this.mutationObserver=null,null!==this.notifyTimer&&(window.clearTimeout(this.notifyTimer),this.notifyTimer=null),this.nodes.clear()}getRoot(){let e=this.target.shadowRoot;return e?e.querySelector('[part="page"]')??e:this.target}getNodeId(e){let t=this.nodeIds.get(e);if(t)return this.nodes.set(t,e),t;let r=`node-${++this.nextNodeId}`;return this.nodeIds.set(e,r),this.nodes.set(r,e),r}editElementAttributes(e,t){return this.runWithoutObservation(()=>{let r=this.getElement(e);if(!r)return[];let i=ui(r);return!1===t(r)?[]:un(e,i,ui(r))})}getPreviousInspectableSiblingId(e){let t=e.parentNode;if(!t)return null;let r=ua(t),i=r.findIndex(t=>t===e),n=i>0?r[i-1]:null;return n?this.getNodeId(n):null}getChildListMutation(e,t,r){return{type:"childList",parentNodeId:this.getNodeId(e),removedNodeIds:t,insertedNodes:r,childNodeCount:ua(e).length}}getInsertedNodeMutations(e,t,r){let i=[],n=t;for(let t of r){if((t.parentNode??(t instanceof ShadowRoot?t.host:null))!==e)continue;let r=this.serializeNode(t);i.push({previousNodeId:n,node:r}),n=r.id}return i}runWithoutObservation(e){var t,r;let i=null!==this.mutationObserver;i&&(null==(t=this.mutationObserver)||t.disconnect());try{return e()}finally{i&&(null==(r=this.mutationObserver)||r.takeRecords(),this.observe())}}serializeNode(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.getNodeId(e);if(e.nodeType===Node.TEXT_NODE){let t;return{id:r,type:"text",name:dQ(e),attributes:[],children:[],textContent:(t=(e.textContent??"").replace(/\s+/g," ").trim()).length>120?`${t.slice(0,120)}...`:t}}let i=e instanceof HTMLElement?e:null;return{id:r,type:t&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE?"document":"element",name:dQ(e),attributes:e instanceof Element?d8(e):[],children:ua(e).map(e=>this.serializeNode(e)),...i?{accessibility:{name:d4(i),role:d6(i),keyboardFocusable:d5(i)}}:{}}}observe(){let e=this.target.shadowRoot??this.target;this.mutationObserver=new MutationObserver(e=>{e.some(e=>(function(e){if(ud(e.target))return!1;if("attributes"===e.type)return e.target instanceof Element&&dX(e.target)&&!dZ.has(e.attributeName??"");if("characterData"===e.type){var t,r;return!!((null==(t=e.oldValue)?void 0:t.trim())||(null==(r=e.target.textContent)?void 0:r.trim()))}return"childList"!==e.type||[...Array.from(e.addedNodes),...Array.from(e.removedNodes)].some(e=>(function e(t){return!ud(t)&&(!!(dX(t)||dY(t))||Array.from(t.childNodes).some(t=>e(t)))})(e))})(e))&&this.scheduleNotify()}),this.mutationObserver.observe(e,{attributes:!0,childList:!0,characterData:!0,characterDataOldValue:!0,subtree:!0})}scheduleNotify(){null===this.notifyTimer&&(this.notifyTimer=window.setTimeout(()=>{this.notifyTimer=null,this.onChange()},0))}}let uc="data-wsd-node-id";function up(e){let t=[];for(let r=0;r<e.length;r++){let i="function"==typeof e.item?e.item(r):e[r];if(!i)continue;let n=e.getPropertyValue(i);t.push({name:i,value:n,priority:e.getPropertyPriority(i),active:!0})}return t}function uh(e){return"u">typeof CSSStyleRule&&e instanceof CSSStyleRule}function um(e,t,r){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",n=r.trim();n?e.setProperty(t,n,i):e.removeProperty(t)}function ug(e){return`${e.name}: ${e.value}${e.priority?` !${e.priority}`:""};`}function uf(e){return e.map(e=>({...e}))}function uv(e){return`inline:${e}`}function uy(e){return`rule:${e}`}class ub{target;elementInspector;ruleIds=new WeakMap;rules=new Map;overriddenElements=new Set;overrides=new Map;styleTextSnapshots=new Map;overrideStyleElement=null;inspectorRuleStyleElement=null;inspectorRuleStyleSheet=null;nextRuleId=0;constructor(e,t){this.target=e,this.elementInspector=t}getMatchedStyles(e){let t=this.elementInspector.getElement(e);if(!t)return null;let r=getComputedStyle(t);return{nodeId:e,inlineStyle:this.getInlineStyle(e,t,r),matchedRules:this.getMatchedRules(t,r),computedStyles:function(e){let t=[];for(let r=0;r<e.length;r++){let i=e.item(r);t.push({name:i,value:e.getPropertyValue(i)})}return t}(r)}}setInlineDeclaration(e,t,r){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",n=!(arguments.length>4)||void 0===arguments[4]||arguments[4],a=this.elementInspector.getElement(e);if(!a)return;let s=uv(e);this.rememberStyleTextDeclaration(s,up(a.style),t,r,i,n),um(a.style,t,n?r:"")}setInlineDeclarations(e,t){let r=this.elementInspector.getElement(e);if(r){for(let e of(r.style.cssText="",t))e.active&&um(r.style,e.name,e.value,e.priority);this.styleTextSnapshots.set(uv(e),uf(t))}}setRuleDeclaration(e,t,r,i){let n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"",a=!(arguments.length>5)||void 0===arguments[5]||arguments[5],s=this.rules.get(t),o=uy(t);if(this.rememberStyleTextDeclaration(o,s?up(s.style):[],r,i,n,a),!a){if(s)try{um(s.style,r,"")}catch{this.setOverrideDeclaration(e,r,"")}else this.setOverrideDeclaration(e,r,"");return}if(!s)return void this.setOverrideDeclaration(e,r,i,n);try{um(s.style,r,i,n)}catch{this.setOverrideDeclaration(e,r,i,n)}}setRuleDeclarations(e,t,r){let i=this.rules.get(t),n=r.filter(e=>e.active);if(this.styleTextSnapshots.set(uy(t),uf(r)),!i)return void this.setOverrideDeclarations(e,n);try{for(let e of(i.style.cssText="",n))um(i.style,e.name,e.value,e.priority)}catch{this.setOverrideDeclarations(e,n)}}addRule(e,t,r){let i=this.elementInspector.getElement(e),n=t.trim();if(!i||!n)return null;let a=this.getInspectorRuleStyleSheet();if(!a)return null;let s=`${n} { ${r.map(ug).join(" ")} }`;try{let e=a.cssRules.length;a.insertRule(s,e);let t=a.cssRules[e];if(t&&uh(t))return this.toMatchedStyleRule(t,getComputedStyle(i))}catch{}return null}setRuleSelector(e,t,r){let i=this.elementInspector.getElement(e),n=this.rules.get(t),a=r.trim();if(!i||!n||!a)return null;try{return n.selectorText=a,this.toMatchedStyleRule(n,getComputedStyle(i))}catch{return null}}setOverrideDeclaration(e,t,r){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",n=this.elementInspector.getElement(e);if(!n)return;n.setAttribute(uc,e),this.overriddenElements.add(n);let a=this.overrides.get(e)??new Map,s=r.trim();s?a.set(t,{value:s,priority:i}):a.delete(t),a.size>0?this.overrides.set(e,a):this.overrides.delete(e),this.renderOverrideStyleSheet()}setOverrideDeclarations(e,t){let r=this.elementInspector.getElement(e);if(!r)return;r.setAttribute(uc,e),this.overriddenElements.add(r);let i=new Map;for(let e of t)e.value.trim()&&i.set(e.name,{value:e.value.trim(),priority:e.priority});i.size>0?this.overrides.set(e,i):this.overrides.delete(e),this.renderOverrideStyleSheet()}destroy(){var e;for(let t of(null==(e=this.overrideStyleElement)||e.remove(),this.overrideStyleElement=null,this.removeInspectorRuleStyleSheet(),this.overrides.clear(),this.styleTextSnapshots.clear(),this.overriddenElements))t.removeAttribute(uc);this.overriddenElements.clear(),this.rules.clear()}getInlineStyle(e,t,r){return{id:"inline",selectorText:"element.style",editable:!0,declarations:this.getStyleTextSnapshot(uv(e))??up(t.style)}}getMatchedRules(e,t){let r,i=this.target.shadowRoot??this.target,n=[];for(let a of(this.rules.clear(),r=[],"styleSheets"in i&&r.push(...Array.from(i.styleSheets)),"adoptedStyleSheets"in i&&r.push(...i.adoptedStyleSheets),r))this.collectRulesFromList(a,e,t,n);return n}collectRulesFromList(e,t,r,i,n){let a;try{a=e.cssRules}catch{return}for(let e of Array.from(a)){if(uh(e)){if(!function(e,t){try{return e.matches(t)}catch{return!1}}(t,e.selectorText))continue;i.push(this.toMatchedStyleRule(e,r,n));continue}if("cssRules"in e){let a=function(e){if("conditionText"in e&&"string"==typeof e.conditionText)return e.conditionText}(e);this.collectRulesFromList(e,t,r,i,n&&a?`${n} and ${a}`:a??n)}}}getRuleId(e){let t=this.ruleIds.get(e);if(t)return t;let r=`rule-${++this.nextRuleId}`;return this.ruleIds.set(e,r),r}toMatchedStyleRule(e,t,r){let i=this.getRuleId(e);return this.rules.set(i,e),{id:i,selectorText:e.selectorText,conditionText:r,editable:!0,source:this.isOverrideRule(e)?"override":"rule",declarations:this.getStyleTextSnapshot(uy(i))??up(e.style)}}getStyleTextSnapshot(e){let t=this.styleTextSnapshots.get(e);return t?uf(t):void 0}rememberStyleTextDeclaration(e,t,r,i){let n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"",a=!(arguments.length>5)||void 0===arguments[5]||arguments[5],s=this.getStyleTextSnapshot(e)??uf(t),o=i.trim(),l=s.findIndex(e=>e.name===r);if(o||!a){let e={name:r,value:o||(l>=0?s[l].value:""),priority:n,active:a};l>=0?s[l]=e:s.push(e)}else l>=0&&s.splice(l,1);s.length>0?this.styleTextSnapshots.set(e,s):this.styleTextSnapshots.delete(e)}getOverrideStyleElement(){if(this.overrideStyleElement)return this.overrideStyleElement;let e=document.createElement("style");return e.dataset.wsdInspectorOverride="true",(this.target.shadowRoot??this.target).append(e),this.overrideStyleElement=e,e}getInspectorRuleStyleSheet(){if(this.inspectorRuleStyleSheet)return this.inspectorRuleStyleSheet;let e=this.target.shadowRoot??this.target;if("adoptedStyleSheets"in e&&"u">typeof CSSStyleSheet)try{let t=new CSSStyleSheet;return e.adoptedStyleSheets=[...e.adoptedStyleSheets,t],this.inspectorRuleStyleSheet=t,t}catch{}if(!this.inspectorRuleStyleElement){let t=document.createElement("style");t.dataset.wsdInspectorRules="true",e.append(t),this.inspectorRuleStyleElement=t}return this.inspectorRuleStyleSheet=this.inspectorRuleStyleElement.sheet,this.inspectorRuleStyleSheet}removeInspectorRuleStyleSheet(){var e;let t=this.target.shadowRoot??this.target;this.inspectorRuleStyleSheet&&"adoptedStyleSheets"in t&&(t.adoptedStyleSheets=t.adoptedStyleSheets.filter(e=>e!==this.inspectorRuleStyleSheet)),null==(e=this.inspectorRuleStyleElement)||e.remove(),this.inspectorRuleStyleElement=null,this.inspectorRuleStyleSheet=null}isOverrideRule(e){var t,r;return e.parentStyleSheet===(null==(t=this.overrideStyleElement)?void 0:t.sheet)||e.parentStyleSheet===(null==(r=this.inspectorRuleStyleElement)?void 0:r.sheet)||e.parentStyleSheet===this.inspectorRuleStyleSheet}renderOverrideStyleSheet(){if(0===this.overrides.size){var e;null==(e=this.overrideStyleElement)||e.remove(),this.overrideStyleElement=null;return}let t=Array.from(this.overrides.entries()).map(e=>{let[t,r]=e,i=Array.from(r.entries()).map(e=>{let[t,r]=e;return` ${t}: ${r.value}${r.priority?` !${r.priority}`:""};`}).join("\n");return`[${uc}="${t}"] {
|
|
45
45
|
${i}
|
|
46
|
-
}`});this.getOverrideStyleElement().textContent=t.join("\n\n")}}class uw{listeners=new Set;elementInspector;styleInspector;consoleRecorder;selectedNodeId=null;consoleUnsubscribe=null;constructor(e,t={}){this.elementInspector=new uu(e,()=>this.notify({type:"document"})),this.styleInspector=new ub(e,this.elementInspector),this.consoleRecorder=new d$(e,t.consoleStore),this.consoleUnsubscribe=this.consoleRecorder.subscribe(()=>this.notify({type:"console"}))}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getDocument(){return this.elementInspector.getDocument()}getElement(e){return this.elementInspector.getElement(e)}getSelectedNodeId(){return this.selectedNodeId}selectNode(e){this.selectedNodeId!==e&&(this.selectedNodeId=e,this.notify({type:"selection"}))}getNodeIdAtPoint(e,t){return this.elementInspector.getNodeIdAtPoint(e,t)}findLynxViews(){return this.elementInspector.findLynxViews()}findNodeIdByLynxUniqueId(e){return this.elementInspector.findNodeIdByLynxUniqueId(e)}getNodeHighlight(e,t){return this.elementInspector.getHighlight(e,t)}getMatchedStyles(e){return this.styleInspector.getMatchedStyles(e)}setAttributesAsText(e,t,r){return this.elementInspector.setAttributesAsText(e,t,r)}setAttributeValue(e,t,r){return this.elementInspector.setAttributeValue(e,t,r)}removeAttribute(e,t){return this.elementInspector.removeAttribute(e,t)}setNodeValue(e,t){return this.elementInspector.setNodeValue(e,t)}setNodeName(e,t){let r=this.elementInspector.setNodeName(e,t);return this.selectedNodeId===e&&(this.selectedNodeId=r.nodeId),r}setOuterHTML(e,t){return this.elementInspector.setOuterHTML(e,t)}setInlineDeclaration(e,t,r,i,n){this.styleInspector.setInlineDeclaration(e,t,r,i,n),this.notify({type:"style",styleSheetId:`inline:${e}`})}setInlineDeclarations(e,t){this.styleInspector.setInlineDeclarations(e,t),this.notify({type:"style",styleSheetId:`inline:${e}`})}setRuleDeclaration(e,t,r,i,n,a){this.styleInspector.setRuleDeclaration(e,t,r,i,n,a),this.notify({type:"style",styleSheetId:`rule:${t}`})}setRuleDeclarations(e,t,r){this.styleInspector.setRuleDeclarations(e,t,r),this.notify({type:"style",styleSheetId:`rule:${t}`})}addRule(e,t,r){let i=this.styleInspector.addRule(e,t,r);return this.notify({type:"style",styleSheetId:i?`rule:${i.id}`:"inspector:main"}),i}setRuleSelector(e,t,r){let i=this.styleInspector.setRuleSelector(e,t,r);return this.notify({type:"style",styleSheetId:i?`rule:${i.id}`:`rule:${t}`}),i}getConsoleEntries(){return this.consoleRecorder.getEntries()}clearConsole(){this.consoleRecorder.clear()}evaluate(e){return this.consoleRecorder.evaluate(e)}destroy(){var e;null==(e=this.consoleUnsubscribe)||e.call(this),this.consoleUnsubscribe=null,this.elementInspector.destroy(),this.styleInspector.destroy(),this.consoleRecorder.destroy(),this.listeners.clear()}notify(e){for(let t of this.listeners)t(e)}}async function u_(e){let t,r="string"==typeof(t=[e.url,e.src,e.getAttribute("url"),e.getAttribute("src")].find(e=>"string"==typeof e&&e.trim()))?t.trim():void 0;if(!r||!/\.web\.bundle(?:[?#]|$)/.test(r))return;let i=new URL(r,window.location.href);i.pathname+=".map";let n=await fetch(i.href).catch(()=>void 0);if(!(null==n?void 0:n.ok))return;let a=await n.text();return{content:"",sourceMapURL:`data:application/json;charset=utf-8,${encodeURIComponent(a)}`,url:r}}let uS=new Set(["class","style"]);function ux(e){var t;return"element"!==e.type?null:(null==(t=e.attributes.find(e=>e.name===dB))?void 0:t.value)??null}function uI(e){var t;return(null==(t=e.attributes.find(e=>"doubao-children"===e.name))?void 0:t.value)==="all"}function uk(e){return e.attributes.some(e=>"doubao-slot"===e.name)}function uC(e){return e.attributes.filter(e=>uS.has(e.name)).map(e=>"class"===e.name?{name:e.name,value:dV(e.value.split(/\s+/)).join(" ")}:e).filter(e=>e.value)}function uE(e){return Array.isArray(e)?"array":void 0}function uN(e){return Array.isArray(e)?`Array(${e.length})`:uT(e)}function uT(e){if(Array.isArray(e))return"Array";try{var t,r;return(null==(r=Object.getPrototypeOf(e))||null==(t=r.constructor)?void 0:t.name)||"Object"}catch{return"Object"}}function uA(e,t){let r=uM(t),i="object"==typeof t&&null!==t||"function"==typeof t;return{name:e,type:r,subtype:i?uE(t):void 0,value:i?uN(t):String(t)}}function uM(e){return null===e?"object":typeof e}function uR(e,t){if(void 0===e)return{type:"undefined",description:"undefined"};if(null===e)return{type:"object",subtype:"null",value:null,description:"null"};let r=function(e){if("number"==typeof e){if(Object.is(e,-0))return"-0";let t=String(e);return"NaN"===t||"Infinity"===t||"-Infinity"===t?t:void 0}return"bigint"==typeof e?`${e}n`:void 0}(e);if(r)return{type:uM(e),unserializableValue:r,description:r};if("symbol"==typeof e)return{type:"symbol",description:String(e)};if("object"==typeof e&&null!==e||"function"==typeof e){let r;return{type:"function"==typeof e?"function":"object",subtype:"function"==typeof e?void 0:uE(e),className:"function"==typeof e?"Function":uT(e),description:"function"==typeof e?e.toString():uN(e),objectId:null==t?void 0:t.register(e),preview:"function"==typeof e||Array.isArray(e)?void 0:(r=function(e){try{return Object.keys(e)}catch{return[]}}(e),{type:"object",subtype:uE(e),description:uN(e),overflow:r.length>5,properties:r.slice(0,5).map(t=>{try{let r=Object.getOwnPropertyDescriptor(e,t);return uA(t,r&&"value"in r?r.value:void 0)}catch{return uA(t,void 0)}})})}}return{type:uM(e),value:e,description:String(e)}}function uj(e,t){return(e.args??[e.message]).map(e=>uR(e,t))}function uP(e,t){return{startLine:0,startColumn:e,endLine:0,endColumn:t}}function uL(e,t){let r=0,i="",n=t.map(e=>{let t=`${e.name}: ${e.value}${e.priority?` !${e.priority}`:""};`,n=e.active?t:`/* ${t} */`,a=uP(r,r+n.length);return i+=`${n} `,r=i.length,{name:e.name,value:e.value,important:"important"===e.priority,disabled:!e.active,parsedOk:!0,implicit:!1,text:n,range:a}});return{styleSheetId:e,cssText:i.trim(),range:uP(0,Math.max(0,i.trim().length)),shorthandEntries:[],cssProperties:n}}function uO(e){let t=e.indexOf(":");return t<0?{kind:e,id:""}:{kind:e.slice(0,t),id:e.slice(t+1)}}function uD(e){let t,r=e.includes("{")?e.slice(e.indexOf("{")+1,e.lastIndexOf("}")):e,i=[],n=/\/\*([\s\S]*?)\*\//g,a=0;for(;t=n.exec(r);)i.push(...uU(r.slice(a,t.index),!0)),i.push(...uU(t[1],!1)),a=t.index+t[0].length;return i.push(...uU(r.slice(a),!0)),i}function uU(e,t){let r=[];for(let i of e.split(";")){let e=i.indexOf(":");if(e<=0)continue;let n=i.slice(0,e).trim(),a=i.slice(e+1).trim(),s="";/!\s*important$/i.test(a)&&(a=a.replace(/!\s*important$/i,"").trim(),s="important"),n&&r.push({name:n,value:a,priority:s,active:t})}return r}function uq(e){if("element"!==e.type||"div"!==e.name)return!1;let t=e.attributes.find(e=>"part"===e.name);return(null==t?void 0:t.value)==="page"}function u$(e){return uq(e)?e.attributes.filter(e=>"part"!==e.name&&"lynx-default-overflow-visible"!==e.name):e.attributes}function uB(e){return u$(e).flatMap(e=>[e.name,e.value])}function uF(e){return uq(e)?"page":dz.get(e.name)??e.name}function uz(e,t){var r;return null==(r=e.attributes.find(e=>e.name===t))?void 0:r.value}function uW(e,t){return e.type===t.type&&e.name===t.name&&(t.id?uz(e,"id")===t.id:!t.className||uz(e,"class")===t.className)}function uH(e,t){let r=Number(e);return Number.isFinite(r)?r<0?1/0:r:t}function uV(e){return 1/0===e?e:Math.max(0,e-1)}function uG(e){if("text"===e.type)return e.textContent??"";if("document"===e.type)return uJ(e);let t=u$(e).map(e=>` ${e.name}="${e.value}"`).join(""),r=e.children.map(e=>uG(e)).join(""),i=uF(e);return`<${i}${t}>${r}</${i}>`}function uJ(e){return e.children.map(e=>uG(e)).join("")}function uK(e,t){let r=(e,i)=>{let n=[...i,e];if(e.id===t)return n;for(let t of e.children){let e=r(t,n);if(e)return e}return null};return r(e,[])}let uZ="__wsd_document__";function uX(e){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation()}let uY="wsd-main-frame";function uQ(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function u0(e){var t;let r;if(e instanceof ArrayBuffer)return{base64Encoded:!0,body:ob(e),byteLength:e.byteLength};if("string"==typeof e)r=e;else if(void 0===e)r="";else try{r=JSON.stringify(e)??String(e)}catch{r=String(e)}return{base64Encoded:!1,body:r,byteLength:(t=r,new TextEncoder().encode(t).byteLength)}}function u1(e){throw Object.assign(Error(e),{code:-32602})}function u2(e,t,r){return e??u1(null===e?r:t)}class u3{emit;enabledSessions=new Map;payloads=new Map;requests=new Map;unsubscribe;maxTotalBufferSize=262144e3;storedPayloadSize=0;constructor(e){this.emit=e}enable(e,t){var r;return this.unsubscribe??=(r=this.handleRequestLifecycle,ou.add(r),()=>ou.delete(r)),this.enabledSessions.set(t,{maxPostDataSize:uQ(null==e?void 0:e.maxPostDataSize,65536),maxTotalBufferSize:uQ(null==e?void 0:e.maxTotalBufferSize,262144e3)}),this.refreshBufferLimit(),{}}disable(e){for(let[t,r]of(this.enabledSessions.delete(e),this.requests))r.sessions.delete(e),0===r.sessions.size&&this.deleteRequest(t,r);if(0===this.enabledSessions.size){var t;null==(t=this.unsubscribe)||t.call(this),this.unsubscribe=void 0,this.clearRequests()}else this.refreshBufferLimit();return{}}getRequestPostData(e,t){let r=u2(this.getRequest(e,t).requestBody,"No post data was sent with this request","Request post data is no longer available");return{postData:r.body,base64Encoded:r.base64Encoded}}getResponseBody(e,t){let r=u2(this.getRequest(e,t).responseBody,"No response body is available for this request","Response body is no longer available");return{body:r.body,base64Encoded:r.base64Encoded}}destroy(){var e;null==(e=this.unsubscribe)||e.call(this),this.unsubscribe=void 0,this.enabledSessions.clear(),this.clearRequests()}handleRequestLifecycle=e=>{if("request"===e.phase)return void this.handleRequestStarted(e);let t=this.requests.get(e.requestId);if(t){if("response"===e.phase)return void this.handleResponseReceived(e,t);this.emitForRequest(t,{method:"Network.loadingFailed",params:{canceled:!1,errorText:e.errorText,requestId:e.requestId,timestamp:e.timestamp,type:"XHR"}})}};handleRequestStarted(e){var t;let r;if(0===this.enabledSessions.size)return;let i=void 0===e.request.body?void 0:u0(e.request.body),n={request:e.request,sessions:new Set(this.enabledSessions.keys())};this.requests.set(e.requestId,n),i&&this.storePayload(n,"requestBody",i);let a=(r=(t=e.request.url).indexOf("#"))<0?{url:t}:{url:t.slice(0,r),urlFragment:t.slice(r)};for(let t of n.sessions){let r=this.enabledSessions.get(t);if(!r)continue;let n=i&&!i.base64Encoded&&i.byteLength<=r.maxPostDataSize;this.emit({method:"Network.requestWillBeSent",params:{documentURL:a.url,frameId:uY,initiator:{type:"script"},loaderId:uY,redirectHasExtraInfo:!1,request:{...a,hasPostData:!!i,headers:e.request.headers,initialPriority:"High",isSameSite:!0,method:e.request.method,mixedContentType:"none",postData:n?i.body:void 0,referrerPolicy:"no-referrer"},requestId:e.requestId,timestamp:e.timestamp,type:"XHR",wallTime:e.wallTime}},t)}}handleResponseReceived(e,t){var r;let i=e.response??{},n=!(r=i.header)||"object"!=typeof r||Array.isArray(r)?{}:Object.fromEntries(Object.entries(r).map(e=>{let[t,r]=e;return[t,String(r)]})),a=u0(i.data),{charset:s,mimeType:o}=function(e){var t,r;let i,n=(null==(i=Object.entries(e).find(e=>{let[t]=e;return"content-type"===t.toLowerCase()}))?void 0:i[1])??"",[a=""]=n.split(";");return{charset:(null==(r=/(?:^|;)\s*charset\s*=\s*["']?([^;"']+)/i.exec(n))||null==(t=r[1])?void 0:t.trim())??"",mimeType:a.trim()}}(n),l="number"==typeof i.statusCode&&Number.isFinite(i.statusCode)?i.statusCode:0;this.storePayload(t,"responseBody",a),this.emitForRequest(t,{method:"Network.responseReceived",params:{frameId:uY,hasExtraInfo:!1,loaderId:uY,requestId:e.requestId,response:{charset:s,connectionId:0,connectionReused:!1,encodedDataLength:a.byteLength,fromDiskCache:!1,fromPrefetchCache:!1,fromServiceWorker:!1,headers:n,mimeType:o,protocol:"",requestHeaders:t.request.headers,responseTime:1e3*e.wallTime,securityState:"unknown",status:l,statusText:"",url:t.request.url},timestamp:e.timestamp,type:"XHR"}}),this.emitForRequest(t,{method:"Network.loadingFinished",params:{encodedDataLength:a.byteLength,requestId:e.requestId,timestamp:e.timestamp}})}emitForRequest(e,t){for(let r of e.sessions)this.enabledSessions.has(r)&&this.emit(t,r)}getRequest(e,t){let r="string"!=typeof(null==e?void 0:e.requestId)||0===e.requestId.length?u1("requestId must be a non-empty string"):e.requestId,i=this.requests.get(r);return(null==i?void 0:i.sessions.has(t))?i:u1(`Unknown requestId: ${r}`)}storePayload(e,t,r){let i=e[t];i&&(this.payloads.delete(i),this.storedPayloadSize-=i.byteLength),e[t]=r,this.payloads.set(r,[e,t]),this.storedPayloadSize+=r.byteLength,this.evictPayloads()}evictPayloads(){for(;this.storedPayloadSize>this.maxTotalBufferSize;){let e=this.payloads.entries().next().value;if(!e)return;let[t,[r,i]]=e;this.payloads.delete(t),this.storedPayloadSize-=t.byteLength,r[i]=null}}refreshBufferLimit(){this.maxTotalBufferSize=Math.min(...[...this.enabledSessions.values()].map(e=>e.maxTotalBufferSize)),this.evictPayloads()}deleteRequest(e,t){for(let e of[t.requestBody,t.responseBody])e&&(this.payloads.delete(e),this.storedPayloadSize-=e.byteLength);this.requests.delete(e)}clearRequests(){this.requests.clear(),this.payloads.clear(),this.storedPayloadSize=0}}class u4{cdpNodes=new Map;nodeIds=new Map;inspectorNodeIds=new Map;nextNodeId=0;get size(){return this.nodeIds.size}reset(){this.cdpNodes.clear(),this.nodeIds.clear(),this.inspectorNodeIds.clear(),this.nextNodeId=0}getCdpNodeId(e){let t=this.nodeIds.get(e);if(t)return t;let r=++this.nextNodeId;return this.nodeIds.set(e,r),this.inspectorNodeIds.set(r,e),r}getExistingCdpNodeId(e){return this.nodeIds.get(e)}getInspectorNodeId(e){return this.inspectorNodeIds.get(e)}resolveInspectorNodeId(e){let t=this.inspectorNodeIds.get(Number(e));if(!t)throw Object.assign(Error(`Unknown nodeId: ${String(e)}`),{code:-32602});return t}toDocumentCdpNode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1/0,r=this.getCdpNodeId(uZ),i=uV(t),n=t>0?[this.toCdpNode(e,i,r)]:void 0,a={nodeId:r,backendNodeId:r,nodeType:9,nodeName:"#document",localName:"",nodeValue:"",childNodeCount:1,frameId:"wsd-main-frame",documentURL:"wsd://runtime",baseURL:"wsd://runtime",publicId:"",systemId:"",xmlVersion:"",children:n};return this.cdpNodes.set(r,a),a}toCdpNode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1/0,r=arguments.length>2?arguments[2]:void 0,i=this.getCdpNodeId(e.id),n=uV(t),a=t>0?e.children.map(e=>this.toCdpNode(e,n,i)):void 0,s="text"===e.type,o="document"===e.type,l=uF(e),d={nodeId:i,backendNodeId:i,parentId:r,nodeType:"text"===e.type?3:"document"===e.type?11:1,nodeName:s||o?e.name:l.toUpperCase(),localName:s||o?"":l,nodeValue:e.textContent??"",childNodeCount:e.children.length,frameId:o?"wsd-main-frame":void 0,documentURL:o?"wsd://runtime":void 0,baseURL:o?"wsd://runtime":void 0,publicId:o?"":void 0,systemId:o?"":void 0,xmlVersion:o?"":void 0,name:s?e.name:void 0,value:s?e.textContent??"":void 0,attributes:"element"===e.type?uB(e):void 0,children:a};return this.cdpNodes.set(i,d),d}}function u5(e){return e.map(e=>({...e}))}function u6(e){return"attributes"===e.type||"characterData"===e.type}class u8{adapter;consoleAdapter=null;appAdapter=null;appTarget=null;target;listeners=new Set;options;nodeStore=new u4;network;consoleStore=dM();appConsoleStore=dM();knownConsoleEntryIdsBySession=new Map;preservingConsoleOnTargetChange;knownStyleSheetIds=new Set;unsubscribeAdapter=null;unsubscribeConsoleAdapter=null;unsubscribeAppAdapter=null;stopInspectModeListener=null;selectedNodeSignaturePath=null;preferredNodeSignaturePath=null;pendingDocumentRevealSignaturePath=null;shouldRevealDocumentAfterUpdate=!1;activeSessionId;isApplyingStyleEdit=!1;runtimeEnabledSessions=new Set;debuggerEnabledSessions=new Set;nextScriptId=0;scriptIdsByUrl=new Map;sourceScriptsById=new Map;parsedScriptIdsBySession=new Map;sourceLoadId=0;undoEntries=[];pendingUndoEntry=null;nextRemoteObjectId=0;remoteObjects=new Map;remoteObjectStore={get:e=>this.remoteObjects.get(e),register:e=>this.registerRemoteObject(e)};constructor(e,t){this.target=e,this.options=t,this.preservingConsoleOnTargetChange=!!t.preserveConsoleOnTargetChange,this.adapter=this.createTargetAdapter(e),this.network=new u3((e,t)=>this.emit(e,t)),this.subscribeAdapter(),this.createConsoleAdapter(),this.loadSources(e)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getInspectorSnapshot(){return{root:this.adapter.getDocument(),selectedUid:this.adapter.getSelectedNodeId()}}getComputedStyles(e,t){var r;let i=null==(r=this.adapter.getMatchedStyles(e))?void 0:r.computedStyles;if(!i)return null;if(!(null==t?void 0:t.length))return i;let n=new Set(t);return i.filter(e=>n.has(e.name))}getElementRect(e){let t=this.options.getRuntimeFrame(),r=t?this.adapter.getNodeHighlight(e,t):null;return r?{x:r.left,y:r.top,width:r.width,height:r.height}:null}getElement(e){return this.adapter.getElement(e)}dispatch(e){e.sessionId&&(this.activeSessionId=e.sessionId);try{let t={id:e.id,result:this.handleRequest(e)};return e.sessionId&&(t.sessionId=e.sessionId),t}catch(i){let t,r={id:e.id,error:{code:"number"==typeof(t=null==i?void 0:i.code)?t:-32603,message:i instanceof Error?i.message:String(i)}};return e.sessionId&&(r.sessionId=e.sessionId),r}}destroy(){var e,t,r,i,n;this.sourceLoadId++,this.stopInspectMode(),null==(e=this.unsubscribeAdapter)||e.call(this),this.unsubscribeAdapter=null,null==(t=this.unsubscribeConsoleAdapter)||t.call(this),this.unsubscribeConsoleAdapter=null,null==(r=this.consoleAdapter)||r.destroy(),this.consoleAdapter=null,null==(i=this.unsubscribeAppAdapter)||i.call(this),this.unsubscribeAppAdapter=null,null==(n=this.appAdapter)||n.destroy(),this.appAdapter=null,this.appTarget=null,this.adapter.destroy(),this.network.destroy(),this.sourceScriptsById.clear(),this.remoteObjects.clear(),this.listeners.clear(),this.options.onHighlightChange(null)}subscribeAdapter(){this.unsubscribeAdapter=this.adapter.subscribe(this.handleAdapterChange)}createConsoleAdapter(){let e=this.options.consoleTarget;e&&e!==this.target&&(this.consoleAdapter=new uw(e,{consoleStore:this.consoleStore}),this.unsubscribeConsoleAdapter=this.consoleAdapter.subscribe(e=>{"console"===e.type&&this.handleConsoleChange()}))}getConsoleAdapter(){return this.consoleAdapter??this.adapter}createTargetAdapter(e){return new uw(e,{consoleStore:this.options.preserveConsoleOnTargetChange?this.consoleStore:void 0})}createAppTargetAdapter(e){return new uw(e,{consoleStore:this.appConsoleStore})}subscribeAppAdapter(){var e;this.unsubscribeAppAdapter=(null==(e=this.appAdapter)?void 0:e.subscribe(e=>{"console"===e.type&&(this.emitUnseenConsoleEntries("app"),this.emit({method:"WSD.appConsoleUpdated"}))}))??null}handleAdapterChange=e=>{if("document"===e.type){if(!this.pendingDocumentRevealSignaturePath){let e=this.preferredNodeSignaturePath??this.selectedNodeSignaturePath;this.pendingDocumentRevealSignaturePath=e?[...e]:null}this.nodeStore.reset(),this.shouldRevealDocumentAfterUpdate=!0,this.emit({method:"DOM.documentUpdated"});return}if("console"===e.type){this.consoleAdapter||this.handleConsoleChange();return}"selection"===e.type?this.emitSelectedStyleInvalidated():this.isApplyingStyleEdit||(this.emitSelectedStyleInvalidated(),this.emit({method:"CSS.styleSheetChanged",params:{styleSheetId:e.styleSheetId??"inspector:main"}}))};setConsoleTarget(e){var t,r;this.options.consoleTarget!==e&&(null==(t=this.unsubscribeConsoleAdapter)||t.call(this),this.unsubscribeConsoleAdapter=null,null==(r=this.consoleAdapter)||r.destroy(),this.consoleAdapter=null,this.options.consoleTarget=e,this.createConsoleAdapter(),this.emitUnseenConsoleEntries(),this.emit({method:"WSD.consoleUpdated"}))}setTarget(e){var t;if(this.target===e)return;let r=!!this.options.preserveConsoleOnTargetChange,i=r!==this.preservingConsoleOnTargetChange;if(this.preservingConsoleOnTargetChange=r,null==(t=this.unsubscribeAdapter)||t.call(this),this.unsubscribeAdapter=null,this.adapter.destroy(),this.target=e,this.adapter=this.createTargetAdapter(e),this.nodeStore.reset(),this.knownStyleSheetIds.clear(),this.sourceScriptsById.clear(),this.parsedScriptIdsBySession.clear(),!this.consoleAdapter&&!this.options.preserveConsoleOnTargetChange){for(let e of this.knownConsoleEntryIdsBySession.values())e.delete("current");0===this.appConsoleStore.entries.length&&this.remoteObjects.clear()}this.selectedNodeSignaturePath=null,this.preferredNodeSignaturePath=null,this.pendingDocumentRevealSignaturePath=null,this.shouldRevealDocumentAfterUpdate=!1,this.undoEntries.length=0,this.pendingUndoEntry=null,this.subscribeAdapter(),this.loadSources(e),this.appTarget&&this.loadAppSource(this.appTarget),i&&this.clearConsoleForTargetScopeChange(),this.emit({method:"DOM.documentUpdated"}),this.emitUnseenConsoleEntries(),this.emit({method:"WSD.consoleUpdated"})}handleConsoleChange(){this.emitUnseenConsoleEntries(),this.emit({method:"WSD.consoleUpdated"})}getAppAdapter(){var e,t,r,i,n,a;let s=(null==(e=(t=this.options).getAppTarget)?void 0:e.call(t))??null;return s?(this.appAdapter&&this.appTarget===s||(null==(r=this.unsubscribeAppAdapter)||r.call(this),this.unsubscribeAppAdapter=null,null==(i=this.appAdapter)||i.destroy(),this.appTarget=s,this.appAdapter=this.createAppTargetAdapter(s),this.subscribeAppAdapter(),this.loadAppSource(s),this.emit({method:"WSD.appConsoleUpdated"})),this.appAdapter):(null==(n=this.unsubscribeAppAdapter)||n.call(this),this.unsubscribeAppAdapter=null,null==(a=this.appAdapter)||a.destroy(),this.appAdapter=null,this.appTarget=null,null)}handleRequest(e){switch(e.method){case"DOM.enable":case"CSS.enable":case"Overlay.enable":case"Page.enable":case"Log.enable":case"CSS.trackComputedStyleUpdatesForNode":case"Page.removeScriptToEvaluateOnNewDocument":case"Log.startViolationsReport":case"Runtime.addBinding":case"Runtime.removeBinding":case"Runtime.runIfWaitingForDebugger":case"Runtime.setCustomObjectFormatterEnabled":return{};case"Runtime.enable":return this.runtimeEnabledSessions.add(e.sessionId),this.emitRuntimeExecutionContext(e.sessionId),this.emitUnseenConsoleEntriesForSession(e.sessionId),this.getAppAdapter(),this.emitUnseenConsoleEntriesForSession(e.sessionId,"app"),{};case"Runtime.disable":return this.runtimeEnabledSessions.delete(e.sessionId),this.knownConsoleEntryIdsBySession.delete(e.sessionId),{};case"Debugger.enable":return this.debuggerEnabledSessions.add(e.sessionId),this.getAppAdapter(),this.emitUnseenConsoleEntries("app"),this.emitSourceScripts(e.sessionId),{debuggerId:"wsd-debugger"};case"Debugger.disable":return this.debuggerEnabledSessions.delete(e.sessionId),this.parsedScriptIdsBySession.delete(e.sessionId),{};case"Debugger.getScriptSource":return this.getScriptSource(e.params);case"DOM.getFlattenedDocument":return this.getFlattenedDocument();case"DOM.getDocument":return this.getDocument(e.params,e.sessionId);case"DOM.requestChildNodes":return this.requestChildNodes(e.params,e.sessionId);case"DOM.describeNode":return this.describeNode(e.params);case"DOM.getAttributes":return this.getAttributes(e.params);case"DOM.getOuterHTML":return this.getOuterHTML(e.params);case"DOM.setAttributesAsText":return this.setAttributesAsText(e.params,e.sessionId);case"DOM.setAttributeValue":return this.setAttributeValue(e.params,e.sessionId);case"DOM.removeAttribute":return this.removeAttribute(e.params,e.sessionId);case"DOM.setNodeValue":return this.setNodeValue(e.params,e.sessionId);case"DOM.setNodeName":return this.setNodeName(e.params,e.sessionId);case"DOM.setOuterHTML":return this.setOuterHTML(e.params,e.sessionId);case"DOM.getBoxModel":return this.getBoxModel(e.params);case"DOM.pushNodesByBackendIdsToFrontend":return this.pushNodesByBackendIdsToFrontend(e.params,e.sessionId);case"DOM.markUndoableState":return this.markUndoableState();case"DOM.undo":return this.undo(e.sessionId);case"DOM.querySelector":return{nodeId:0};case"DOM.querySelectorAll":case"DOM.getSearchResults":return{nodeIds:[]};case"DOM.performSearch":return{searchId:"wsd-empty-search",resultCount:0};case"DOM.resolveNode":return this.resolveNode(e.params);case"CSS.getMatchedStylesForNode":return this.getMatchedStylesForNode(e.params);case"CSS.getInlineStylesForNode":return this.getInlineStylesForNode(e.params);case"CSS.getComputedStyleForNode":return this.getComputedStyleForNode(e.params);case"CSS.getPlatformFontsForNode":return{fonts:[]};case"CSS.getMediaQueries":return{medias:[]};case"CSS.getEnvironmentVariables":return{environmentVariables:{}};case"CSS.getBackgroundColors":return{backgroundColors:[],computedFontSize:"",computedFontWeight:"",computedBodyFontSize:""};case"CSS.getStyleSheetText":return this.getStyleSheetText(e.params);case"CSS.resolveValues":return this.resolveCssValues(e.params);case"CSS.setStyleTexts":return this.setStyleTexts(e.params);case"CSS.setEffectivePropertyValueForNode":return this.setEffectivePropertyValueForNode(e.params);case"CSS.createStyleSheet":return{styleSheetId:"inspector:main"};case"CSS.addRule":return this.addRule(e.params);case"CSS.setRuleSelector":return this.setRuleSelector(e.params);case"Page.getResourceTree":case"Page.getFrameTree":return this.getFrameTree();case"Page.getNavigationHistory":return{currentIndex:0,entries:[{id:1,url:"wsd://runtime",title:"Web SDK Runtime",transitionType:"typed"}]};case"Page.getLayoutMetrics":return this.getLayoutMetrics();case"Page.createIsolatedWorld":return{executionContextId:1};case"Page.addScriptToEvaluateOnNewDocument":return{identifier:"wsd-script"};case"Page.getCookies":return{cookies:[]};case"Page.getAppManifest":return{url:"",errors:[],data:""};case"Network.enable":return this.network.enable(e.params,e.sessionId);case"Network.disable":return this.network.disable(e.sessionId);case"Network.getRequestPostData":return this.network.getRequestPostData(e.params,e.sessionId);case"Network.getResponseBody":return this.network.getResponseBody(e.params,e.sessionId);case"Network.emulateNetworkConditionsByRule":return{ruleIds:[]};case"Performance.getMetrics":return{metrics:[]};case"Memory.getDOMCounters":return{documents:1,nodes:this.nodeStore.size,jsEventListeners:0};case"SystemInfo.getInfo":return{gpu:{devices:[],auxAttributes:{},featureStatus:{},driverBugWorkarounds:[]},modelName:"Web SDK Debugger",modelVersion:"",commandLine:""};case"Browser.getVersion":return{protocolVersion:"1.3",product:"Web SDK Debugger",revision:"",userAgent:"u"<typeof navigator?"":navigator.userAgent,jsVersion:""};case"Schema.getDomains":return{domains:[]};case"Runtime.evaluate":return this.evaluate(e.params);case"Runtime.getProperties":return this.getRuntimeProperties(e.params);case"Runtime.callFunctionOn":case"Runtime.awaitPromise":return{result:{type:"undefined",description:"undefined"}};case"Runtime.releaseObject":var t;return"string"==typeof(null==(t=e.params)?void 0:t.objectId)&&this.remoteObjects.delete(e.params.objectId),{};case"Runtime.releaseObjectGroup":return this.remoteObjects.clear(),{};case"Runtime.discardConsoleEntries":case"Console.clearMessages":case"Log.clear":return this.clearConsole(),{};case"Overlay.highlightNode":return this.highlightNode(e.params);case"Overlay.hideHighlight":return this.options.onHighlightChange(null),{};case"Overlay.setInspectMode":return this.setInspectMode(e.params,e.sessionId);case"WSD.getConsoleEntries":return{entries:this.getConsoleAdapter().getConsoleEntries().map(e=>this.toConsoleEntry(e))};case"WSD.getAppConsoleEntries":return this.getAppAdapter(),this.emitUnseenConsoleEntries("app"),{entries:this.appConsoleStore.entries.map(e=>this.toConsoleEntry(e))};case"WSD.clearAppConsole":return this.clearAppConsole(),{};case"WSD.setStyleDeclaration":return this.setStyleDeclaration(e.params);default:if(function(e){let[t,r]=e.split(".");return new Set(["Audits","Browser","DOMDebugger","Debugger","Emulation","HeapProfiler","IndexedDB","Inspector","LayerTree","Memory","Network","Performance","Profiler","Security","ServiceWorker","Storage","Target"]).has(t)||"enable"===r||"disable"===r||(null==r?void 0:r.startsWith("set"))||(null==r?void 0:r.startsWith("clear"))||(null==r?void 0:r.startsWith("stop"))}(e.method))return{};throw Object.assign(Error(`Unsupported CDP method: ${e.method}`),{code:-32601})}}getDocument(e,t){let r=this.getInspectorDocument(),i=uH(null==e?void 0:e.depth,1);if(r&&this.shouldRevealDocumentAfterUpdate){let e=this.pendingDocumentRevealSignaturePath?[...this.pendingDocumentRevealSignaturePath]:null;this.shouldRevealDocumentAfterUpdate=!1,window.setTimeout(()=>this.revealDocumentAfterUpdate(r,t,e),0)}return{root:r?this.nodeStore.toDocumentCdpNode(r,i):null}}getFlattenedDocument(){let e=this.getDocument({depth:-1}).root;return{nodes:e?function e(t){return[t,...(t.children??[]).flatMap(t=>e(t))]}(e):[]}}requestChildNodes(e,t){let r=Number(null==e?void 0:e.nodeId),i=this.nodeStore.resolveInspectorNodeId(r),n=uH(null==e?void 0:e.depth,1),a=this.getInspectorDocument(),s=i===uZ?null:this.findInspectorNode(i),o=i===uZ?a?[this.nodeStore.toCdpNode(a,uV(n),r)]:[]:(null==s?void 0:s.children.map(e=>this.nodeStore.toCdpNode(e,uV(n),r)))??[];return this.emit({method:"DOM.setChildNodes",params:{parentId:r,nodes:o}},t),{}}pushNodesByBackendIdsToFrontend(e,t){let r=this.getInspectorDocument();return{nodeIds:(Array.isArray(null==e?void 0:e.backendNodeIds)?e.backendNodeIds:[]).map(e=>{let i=Number(e),n=this.nodeStore.getInspectorNodeId(i);return r&&n&&this.materializeInspectorNodePath(r,n,t)?i:0})}}materializeInspectorNodePath(e,t,r){let i=uK(e,t);if(!i)return!1;let n=this.nodeStore.getCdpNodeId(uZ);for(let t of(this.emit({method:"DOM.setChildNodes",params:{parentId:n,nodes:[this.nodeStore.toCdpNode(e,0,n)]}},r),this.emit({method:"DOM.childNodeCountUpdated",params:{nodeId:n,childNodeCount:1}},r),i.slice(0,-1))){let e=this.nodeStore.getCdpNodeId(t.id),i=t.children.map(t=>this.nodeStore.toCdpNode(t,0,e));this.emit({method:"DOM.setChildNodes",params:{parentId:e,nodes:i}},r),this.emit({method:"DOM.childNodeCountUpdated",params:{nodeId:e,childNodeCount:i.length}},r)}return!0}revealDocumentAfterUpdate(e,t,r){if(!(null==r?void 0:r.length))return;let i=this.findInspectorNodeBySignaturePath(e,r??null),n=i??this.findDocumentRevealNode(e);if(!n||!this.materializeInspectorNodePath(e,n.id,t))return;let a=this.nodeStore.getCdpNodeId(n.id),s=!!i||!(null==r?void 0:r.length);this.selectInspectorNode(n.id,{rememberPreferred:s}),s&&(this.pendingDocumentRevealSignaturePath=null),this.emit({method:"Overlay.nodeHighlightRequested",params:{nodeId:a}},t),this.emit({method:"Overlay.inspectNodeRequested",params:{backendNodeId:a}},t)}findDocumentRevealNode(e){let t=this.adapter.getSelectedNodeId();if(t){let r=uK(e,t);if(r)return r[r.length-1]}let r=this.findInspectorNodeBySignaturePath(e,this.selectedNodeSignaturePath);if(r)return r;let i=e;for(let e=0;e<3;e+=1){let e=i.children.find(e=>"element"===e.type);if(!e)break;i=e}return i}selectInspectorNode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{rememberPreferred:!0};this.adapter.selectNode(e);let r=this.rememberSelectedNodePath(e);t.rememberPreferred&&r&&(this.preferredNodeSignaturePath=[...r])}rememberSelectedNodePath(e){let t=this.getInspectorDocument(),r=t?uK(t,e):null;if(r){let e=r.map(e=>({type:e.type,name:e.name,className:uz(e,"class"),id:uz(e,"id")}));return this.selectedNodeSignaturePath=e,e}return null}findInspectorNodeBySignaturePath(e,t){if(!(null==t?void 0:t.length)||!uW(e,t[0]))return null;let r=e;for(let e of t.slice(1)){let t=r.children.find(t=>uW(t,e));if(!t)return null;r=t}return r}resolveNode(e){let t=this.nodeStore.resolveInspectorNodeId((null==e?void 0:e.nodeId)??(null==e?void 0:e.backendNodeId));return{object:{objectId:`node:${t}`,type:"object",subtype:"node",className:"HTMLElement",description:t}}}describeNode(e){let t=Number((null==e?void 0:e.nodeId)??(null==e?void 0:e.backendNodeId)),r=this.nodeStore.resolveInspectorNodeId(t),i=this.findInspectorNode(r),n=this.getInspectorDocument();return{node:r===uZ&&n?this.nodeStore.toDocumentCdpNode(n):i?this.nodeStore.toCdpNode(i):null}}getAttributes(e){let t=this.findInspectorNode(this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId));return{attributes:t?uB(t):[]}}getOuterHTML(e){let t=this.nodeStore.resolveInspectorNodeId((null==e?void 0:e.nodeId)??(null==e?void 0:e.backendNodeId)),r=this.findInspectorNode(t),i=this.getInspectorDocument();return{outerHTML:t===uZ&&i?uG(i):r?uG(r):""}}setAttributesAsText(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),i=String((null==e?void 0:e.text)??""),n="string"==typeof(null==e?void 0:e.name)?e.name:void 0,a=this.applyDomEdit(()=>this.adapter.setAttributesAsText(r,i,n));return this.emitDomMutations(a,t),{}}setAttributeValue(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),i=String((null==e?void 0:e.name)??""),n=String((null==e?void 0:e.value)??""),a=this.applyDomEdit(()=>this.adapter.setAttributeValue(r,i,n));return this.emitDomMutations(a,t),{}}removeAttribute(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),i=String((null==e?void 0:e.name)??""),n=this.applyDomEdit(()=>this.adapter.removeAttribute(r,i));return this.emitDomMutations(n,t),{}}setNodeValue(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),i=String((null==e?void 0:e.value)??""),n=this.applyDomEdit(()=>this.adapter.setNodeValue(r,i));return this.emitDomMutations(n,t),{}}setNodeName(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),i=String((null==e?void 0:e.name)??""),n=this.applyDomEdit(()=>this.adapter.setNodeName(r,i),!0);return this.emitDomMutations(n.mutations,t),{nodeId:n.nodeId?this.nodeStore.getCdpNodeId(n.nodeId):0}}setOuterHTML(e,t){let r=this.nodeStore.resolveInspectorNodeId((null==e?void 0:e.nodeId)??(null==e?void 0:e.backendNodeId)),i=String((null==e?void 0:e.outerHTML)??""),n=this.applyDomEdit(()=>this.adapter.setOuterHTML(r,i),!0);return this.emitDomMutations(n,t),{}}applyDomEdit(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=t?this.adapter.getDocument():null,i=r?this.createDomRootSnapshot(r):null,n=e(),a=Array.isArray(n)?n:n.mutations,s=a.filter(u6),o=null;return a.length>0&&s.length===a.length?o={type:"mutations",mutations:s}:a.length>0&&i&&(o=i),o&&this.rememberDomUndoEntry(o),n}createDomRootSnapshot(e){return{type:"rootSnapshot",rootHtml:"document"===e.type?uJ(e):uG(e)}}emitDomMutations(e,t){for(let r of e){if("attributes"===r.type){for(let e of r.removed)this.emit({method:"DOM.attributeRemoved",params:{nodeId:this.nodeStore.getCdpNodeId(r.nodeId),name:e}},t);for(let e of r.modified)this.emit({method:"DOM.attributeModified",params:{nodeId:this.nodeStore.getCdpNodeId(r.nodeId),name:e.name,value:e.value}},t);continue}if("characterData"===r.type){this.emit({method:"DOM.characterDataModified",params:{nodeId:this.nodeStore.getCdpNodeId(r.nodeId),characterData:r.value}},t);continue}let e=this.nodeStore.getCdpNodeId(r.parentNodeId);for(let i of r.removedNodeIds)this.emit({method:"DOM.childNodeRemoved",params:{parentNodeId:e,nodeId:this.nodeStore.getCdpNodeId(i)}},t);for(let i of r.insertedNodes)this.emit({method:"DOM.childNodeInserted",params:{parentNodeId:e,previousNodeId:i.previousNodeId?this.nodeStore.getCdpNodeId(i.previousNodeId):0,node:this.nodeStore.toCdpNode(i.node,1/0,e)}},t);this.emit({method:"DOM.childNodeCountUpdated",params:{nodeId:e,childNodeCount:r.childNodeCount}},t)}}getMatchedStylesForNode(e){let t=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId);this.selectInspectorNode(t,{rememberPreferred:!this.pendingDocumentRevealSignaturePath&&!this.preferredNodeSignaturePath});let r=this.adapter.getMatchedStyles(t);return r?{inlineStyle:uL(`inline:${t}`,r.inlineStyle.declarations),attributesStyle:null,matchedCSSRules:r.matchedRules.map(e=>({matchingSelectors:[0],rule:this.toCdpRulePayload(e)})),pseudoElements:[],inherited:[],cssKeyframesRules:[]}:{inlineStyle:null,attributesStyle:null,matchedCSSRules:[],pseudoElements:[],inherited:[],cssKeyframesRules:[]}}getInlineStylesForNode(e){let t=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),r=this.adapter.getMatchedStyles(t);return{inlineStyle:r?uL(`inline:${t}`,r.inlineStyle.declarations):null,attributesStyle:null}}getComputedStyleForNode(e){let t=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),r=this.adapter.getMatchedStyles(t);return{computedStyle:((null==r?void 0:r.computedStyles)??[]).map(e=>({name:e.name,value:e.value}))}}resolveCssValues(e){return{results:Array.isArray(null==e?void 0:e.values)?e.values.map(String):[]}}setStyleTexts(e){let t=Array.isArray(null==e?void 0:e.edits)?e.edits:[],r=[];this.isApplyingStyleEdit=!0;try{for(let e of t){let t=String(e.styleSheetId??""),i=uD(String(e.text??"")),{id:n,kind:a}=uO(t),s=this.adapter.getSelectedNodeId(),o="inline"===a?n:s,l=this.getDeclarationsForStyleSheet(t);"inline"===a?this.adapter.setInlineDeclarations(n,i):"rule"===a&&s&&this.adapter.setRuleDeclarations(s,n,i),r.push(this.getStylePayloadForStyleSheet(t,i)),this.rememberStyleUndoEntry(t,o,l,this.getDeclarationsForStyleSheet(t))}}finally{this.isApplyingStyleEdit=!1}return{styles:r}}getStyleSheetText(e){let t=String((null==e?void 0:e.styleSheetId)??"");return{text:this.getStylePayloadForStyleSheet(t,[]).cssText}}setEffectivePropertyValueForNode(e){let t=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),r=String((null==e?void 0:e.propertyName)??(null==e?void 0:e.name)??""),i=String((null==e?void 0:e.value)??"");return r&&this.adapter.setInlineDeclaration(t,r,i),{}}addRule(e){let t=String((null==e?void 0:e.ruleText)??""),r=this.getRuleSelectorText(t),i=uD(t).map(e=>({...e,active:!0})),n=this.adapter.getSelectedNodeId(),a=n?this.adapter.addRule(n,r,i):null;return{rule:a?this.toCdpRulePayload(a):{origin:"inspector",selectorList:this.toSelectorList(r),style:uL("inspector:main",i)}}}setRuleSelector(e){let t=String((null==e?void 0:e.selector)??(null==e?void 0:e.text)??"").trim(),{id:r,kind:i}=uO(String((null==e?void 0:e.styleSheetId)??"")),n=this.adapter.getSelectedNodeId(),a="rule"===i&&n?this.adapter.setRuleSelector(n,r,t):null;return{selectorList:this.toSelectorList((null==a?void 0:a.selectorText)??t)}}evaluate(e){let t=String((null==e?void 0:e.expression)??""),r=this.adapter.evaluate(t);return{result:function(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return{type:t?"string":"object",subtype:t?void 0:"error",value:e,description:e}}(r.value,r.ok),exceptionDetails:r.ok?void 0:{text:r.value}}}getRuntimeProperties(e){let t="string"==typeof(null==e?void 0:e.objectId)?this.remoteObjectStore.get(e.objectId):void 0;return{result:function(e,t){if(("object"!=typeof e||null===e)&&"function"!=typeof e)return[];try{return Object.getOwnPropertyNames(e).map(r=>{let i=Object.getOwnPropertyDescriptor(e,r),n={name:r,configurable:(null==i?void 0:i.configurable)??!0,enumerable:(null==i?void 0:i.enumerable)??!0,isOwn:!0};return i&&"value"in i&&(n.value=uR(i.value,t),n.writable=i.writable),n})}catch{return[]}}(t,this.remoteObjectStore),internalProperties:function(e,t){if(("object"!=typeof e||null===e)&&"function"!=typeof e)return[];let r=Object.getPrototypeOf(e);return r?[{name:"[[Prototype]]",value:uR(r,t)}]:[]}(t,this.remoteObjectStore)}}clearConsole(){this.getConsoleAdapter().clearConsole(),this.clearAppConsole(),this.remoteObjects.clear()}clearConsoleForTargetScopeChange(){for(let e of(this.consoleStore.entries.length=0,this.knownConsoleEntryIdsBySession.clear(),this.parsedScriptIdsBySession.clear(),this.remoteObjects.clear(),this.runtimeEnabledSessions))this.emit({method:"Runtime.executionContextsCleared"},e),this.emitRuntimeExecutionContext(e),this.emitUnseenConsoleEntriesForSession(e,"app")}clearAppConsole(){this.getAppAdapter(),0!==this.appConsoleStore.entries.length&&(this.appConsoleStore.entries.length=0,this.emit({method:"WSD.appConsoleUpdated"}))}highlightNode(e){let t=this.nodeStore.resolveInspectorNodeId((null==e?void 0:e.nodeId)??(null==e?void 0:e.backendNodeId)),r=this.options.getRuntimeFrame();return r?this.options.onHighlightChange(this.adapter.getNodeHighlight(t,r)):this.options.onHighlightChange(null),{}}sendPreactDevtoolsMessage(e){let t=JSON.stringify(e);for(let e of this.adapter.findLynxViews()){var r;null==(r=e.sendDevtoolEvent)||r.call(e,"PreactDevtools",t)}}highlightLynxNode(e){if(null==e)return void this.options.onHighlightChange(null);let t=this.options.getRuntimeFrame(),r=t?this.adapter.findNodeIdByLynxUniqueId(e):null;this.options.onHighlightChange(r&&t?this.adapter.getNodeHighlight(r,t):null)}setInspectMode(e,t){return"none"===String((null==e?void 0:e.mode)??"none")?this.stopInspectMode():this.startInspectMode(t),{}}startInspectMode(e){this.stopInspectMode();let t=this.options.getRuntimeFrame();t&&(this.stopInspectModeListener=function(e){let{frame:t,highlightNodeAtPoint:r,onHighlightChange:i,onNodeHighlightRequested:n,onNodeInspected:a}=e;t.classList.add("is-inspecting");let s=e=>{let t=r(e.clientX,e.clientY);t&&n(t)},o=()=>{i(null)},l=e=>{if(0!==e.button)return;let i=r(e.clientX,e.clientY);i&&(uX(e),function(e){let t=["mousedown","mouseup","pointerup","pointercancel","click","dblclick","auxclick","contextmenu"],r=[e,e.ownerDocument],i=e.ownerDocument.defaultView;i&&r.push(i);let n=null,a=()=>{for(let e of(null!==n&&(window.clearTimeout(n),n=null),r))for(let r of t)e.removeEventListener(r,s,!0)},s=e=>{uX(e),("click"===e.type||"dblclick"===e.type||"auxclick"===e.type)&&a()};for(let e of r)for(let r of t)e.addEventListener(r,s,!0);n=window.setTimeout(a,800)}(t),a(i))};return t.addEventListener("pointermove",s,!0),t.addEventListener("pointerleave",o,!0),t.addEventListener("pointerdown",l,!0),t.addEventListener("mousemove",s,!0),t.addEventListener("mouseleave",o,!0),t.addEventListener("mousedown",l,!0),()=>{t.classList.remove("is-inspecting"),t.removeEventListener("pointermove",s,!0),t.removeEventListener("pointerleave",o,!0),t.removeEventListener("pointerdown",l,!0),t.removeEventListener("mousemove",s,!0),t.removeEventListener("mouseleave",o,!0),t.removeEventListener("mousedown",l,!0),i(null)}}({frame:t,highlightNodeAtPoint:(e,t)=>this.highlightNodeAtPoint(e,t),onHighlightChange:this.options.onHighlightChange,onNodeHighlightRequested:t=>{this.emit({method:"Overlay.nodeHighlightRequested",params:{nodeId:t.cdpNodeId}},e)},onNodeInspected:t=>{let r=this.getInspectorDocument();r&&this.materializeInspectorNodePath(r,t.inspectorNodeId,e),this.selectInspectorNode(t.inspectorNodeId,{rememberPreferred:!0}),this.emit({method:"Overlay.nodeHighlightRequested",params:{nodeId:t.cdpNodeId}},e),this.emit({method:"Overlay.inspectNodeRequested",params:{backendNodeId:t.cdpNodeId}},e),this.stopInspectMode()}}))}stopInspectMode(){var e;null==(e=this.stopInspectModeListener)||e.call(this),this.stopInspectModeListener=null}highlightNodeAtPoint(e,t){var r,i;let n=null==(r=(i=this.options).resolveTargetAtPoint)?void 0:r.call(i,e,t);n&&this.setTarget(n);let a=this.adapter.getNodeIdAtPoint(e,t),s=this.options.getRuntimeFrame();if(!a||!s)return this.options.onHighlightChange(null),null;let o=function(e,t){if(!e)return t;let r=(e,i)=>{let n=i??(ux(e)?e.id:null);if(e.id===t)return n??e.id;let a=uk(e)||uI(e)?null:n;for(let t of e.children){let e=r(t,a);if(e)return e}return null};return r(e,null)??t}(this.adapter.getDocument(),a);return this.options.onHighlightChange(this.adapter.getNodeHighlight(o,s)),{cdpNodeId:this.nodeStore.getCdpNodeId(o),inspectorNodeId:o}}setStyleDeclaration(e){let t=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),r=String((null==e?void 0:e.name)??"").trim(),i=String((null==e?void 0:e.value)??""),n="string"==typeof(null==e?void 0:e.ruleId)?e.ruleId:null;if(!r)throw Error("CSS property name is required");return n?this.adapter.setRuleDeclaration(t,n,r,i):this.adapter.setInlineDeclaration(t,r,i),{}}undo(e){let t=this.pendingUndoEntry??this.undoEntries.pop()??null;return(this.pendingUndoEntry=null,t)?"dom"===t.type?(this.undoDomEdit(t.entry,e)||(this.pendingUndoEntry=t),{}):this.undoStyleEdit(t.entry):{}}undoDomEdit(e,t){if("mutations"===e.type)return this.undoIncrementalDomMutations(e.mutations,t),!0;let r=this.adapter.getDocument();if(!r)return!1;let i=this.adapter.setOuterHTML(r.id,e.rootHtml);return 0!==i.length&&(this.emitDomMutations(i,t),!0)}undoIncrementalDomMutations(e,t){let r=[];for(let t of[...e].reverse())"attributes"===t.type?r.push(...this.restoreAttributeMutation(t)):r.push(...this.adapter.setNodeValue(t.nodeId,t.previousValue));this.emitDomMutations(r,t)}restoreAttributeMutation(e){let t=new Set(e.before.map(e=>e.name)),r=new Set(e.modified.map(e=>e.name)),i=new Set(e.removed),n=[];for(let r of e.modified)t.has(r.name)||n.push(...this.adapter.removeAttribute(e.nodeId,r.name));for(let t of e.before)(r.has(t.name)||i.has(t.name))&&n.push(...this.adapter.setAttributeValue(e.nodeId,t.name,t.value));return n}undoStyleEdit(e){return this.applyStyleDeclarations(e),{styleSheetId:e.styleSheetId}}markUndoableState(){return this.commitPendingUndoEntry(),{}}rememberDomUndoEntry(e){this.setPendingUndoEntry({type:"dom",entry:e})}rememberStyleUndoEntry(e,t,r,i){var n;t&&JSON.stringify(r)!==JSON.stringify(i)&&((null==(n=this.pendingUndoEntry)?void 0:n.type)!=="style"||this.pendingUndoEntry.entry.styleSheetId!==e||this.pendingUndoEntry.entry.nodeId!==t)&&this.setPendingUndoEntry({type:"style",entry:{styleSheetId:e,nodeId:t,previousDeclarations:u5(r)}})}setPendingUndoEntry(e){var t;((null==(t=this.pendingUndoEntry)?void 0:t.type)!=="style"||"style"!==e.type||this.pendingUndoEntry.entry.styleSheetId!==e.entry.styleSheetId||this.pendingUndoEntry.entry.nodeId!==e.entry.nodeId)&&(this.commitPendingUndoEntry(),this.pendingUndoEntry=e)}commitPendingUndoEntry(){this.pendingUndoEntry&&(this.pushUndoEntry(this.pendingUndoEntry),this.pendingUndoEntry=null)}pushUndoEntry(e){this.undoEntries.push(e),this.undoEntries.length>50&&this.undoEntries.shift()}applyStyleDeclarations(e){let{id:t,kind:r}=uO(e.styleSheetId);this.isApplyingStyleEdit=!0;try{"inline"===r?this.adapter.setInlineDeclarations(t,u5(e.previousDeclarations)):"rule"===r&&this.adapter.setRuleDeclarations(e.nodeId,t,u5(e.previousDeclarations))}finally{this.isApplyingStyleEdit=!1}this.emitSelectedStyleInvalidated(),this.emit({method:"CSS.styleSheetChanged",params:{styleSheetId:e.styleSheetId}})}getBoxModel(e){let t=this.nodeStore.resolveInspectorNodeId((null==e?void 0:e.nodeId)??(null==e?void 0:e.backendNodeId)),r=this.options.getRuntimeFrame(),i=r?this.adapter.getNodeHighlight(t,r):null,n=(null==i?void 0:i.left)??0,a=(null==i?void 0:i.top)??0,s=(null==i?void 0:i.width)??0,o=(null==i?void 0:i.height)??0,l=[n,a,n+s,a,n+s,a+o,n,a+o];return{model:{content:l,padding:l,border:l,margin:l,width:s,height:o}}}getFrameTree(){return{frameTree:{frame:{id:"wsd-main-frame",loaderId:"wsd-loader",url:"wsd://runtime",securityOrigin:"wsd://runtime",mimeType:"text/html"},resources:[{url:"wsd://runtime",type:"Other",mimeType:"text/html"}]}}}getLayoutMetrics(){let e=this.options.getRuntimeFrame(),t=(null==e?void 0:e.offsetWidth)??0,r=(null==e?void 0:e.offsetHeight)??0;return{layoutViewport:{pageX:0,pageY:0,clientWidth:t,clientHeight:r},visualViewport:{offsetX:0,offsetY:0,pageX:0,pageY:0,clientWidth:t,clientHeight:r,scale:1,zoom:1},contentSize:{x:0,y:0,width:t,height:r}}}getInspectorDocument(){let e=this.adapter.getDocument();return e?function e(t){let r=ux(t);if(r){let i,n,a=uI(t)?t:function e(t){let r=!(arguments.length>1)||void 0===arguments[1]||arguments[1];if(!r&&ux(t))return null;if(uk(t))return t;for(let r of t.children){let t=e(r,!1);if(t)return t}return null}(t);return{...t,name:r,attributes:(i=uC(t),n=(function(e){var t;let r=null==(t=e.attributes.find(e=>e.name===dF))?void 0:t.value.split(/\s+/).filter(Boolean);if(!(null==r?void 0:r.length))return[];let i=e.children.find(e=>"element"===e.type);return i?uC(i).filter(e=>r.includes(e.name)):[]})(t).filter(e=>!i.some(t=>t.name===e.name)),[...i,...n]),children:a?a.children.map(t=>e(t)):[]}}let i=t.children.map(t=>e(t));return i.some((e,r)=>e!==t.children[r])?{...t,children:i}:t}(e):null}findInspectorNode(e){let t=this.getInspectorDocument();if(!t)return null;let r=[t];for(;r.length;){let t=r.shift();if(t){if(t.id===e)return t;r.push(...t.children)}}return null}getStylePayloadForStyleSheet(e,t){var r,i;let{id:n,kind:a}=uO(e),s=t.map(e=>({name:e.name,value:e.value,priority:e.priority,active:e.active}));if("inline"===a)return uL(e,(null==(r=this.adapter.getMatchedStyles(n))?void 0:r.inlineStyle.declarations)??s);if("rule"===a){let t=this.adapter.getSelectedNodeId(),r=t?null==(i=this.adapter.getMatchedStyles(t))?void 0:i.matchedRules.find(e=>e.id===n):null;return uL(e,(null==r?void 0:r.declarations)??s)}return uL(e,s)}getDeclarationsForStyleSheet(e){var t,r;let{id:i,kind:n}=uO(e);if("inline"===n)return u5((null==(t=this.adapter.getMatchedStyles(i))?void 0:t.inlineStyle.declarations)??[]);if("rule"===n){let e=this.adapter.getSelectedNodeId(),t=e?null==(r=this.adapter.getMatchedStyles(e))?void 0:r.matchedRules.find(e=>e.id===i):null;return u5((null==t?void 0:t.declarations)??[])}return[]}getRuleSelectorText(e){let t=e.indexOf("{");return t<0?e.trim():e.slice(0,t).trim()}toSelectorList(e){return{selectors:[{text:e,range:uP(0,e.length)}],text:e}}toCdpRulePayload(e){let t=`rule:${e.id}`,r=uL(t,e.declarations);return this.ensureStyleSheetAdded(t,r.cssText,"override"===e.source?"inspector":"regular"),{styleSheetId:t,origin:"override"===e.source?"inspector":"regular",selectorList:this.toSelectorList(e.selectorText),style:r}}ensureStyleSheetAdded(e,t,r){this.knownStyleSheetIds.has(e)||(this.knownStyleSheetIds.add(e),this.emit({method:"CSS.styleSheetAdded",params:{header:{styleSheetId:e,frameId:"wsd-main-frame",sourceURL:`wsd://styles/${e}`,origin:r,title:e,disabled:!1,isInline:!1,isMutable:!0,isConstructed:!0,startLine:0,startColumn:0,length:t.length,endLine:0,endColumn:t.length}}}))}toConsoleEntry(e){let t=this.toCdpStackTrace(e.stackTrace),r={...e,stackTrace:t,args:uj(e,this.remoteObjectStore)};return e.location&&(r.url=e.location.url,r.lineNumber=e.location.lineNumber,r.columnNumber=e.location.columnNumber),r}getKnownConsoleEntryIds(e,t){let r=this.knownConsoleEntryIdsBySession.get(e)??new Map;this.knownConsoleEntryIdsBySession.set(e,r);let i=r.get(t)??new Set;return r.set(t,i),i}getParsedScriptIds(e){let t=this.parsedScriptIdsBySession.get(e)??new Set;return this.parsedScriptIdsBySession.set(e,t),t}getScriptId(e){let t=this.scriptIdsByUrl.get(e)??`wsd-script-${++this.nextScriptId}`;return this.scriptIdsByUrl.set(e,t),t}getScriptSource(e){let t=String((null==e?void 0:e.scriptId)??""),r=this.sourceScriptsById.get(t);return{scriptSource:(null==r?void 0:r.content)??""}}async loadSources(e){let t=++this.sourceLoadId,r=await u_(e);t===this.sourceLoadId&&(r&&this.sourceScriptsById.set(this.getScriptId(r.url),r),this.emitSourceScriptsForEnabledSessions())}async loadAppSource(e){let t=await u_(e);e===this.appTarget&&(t&&this.sourceScriptsById.set(this.getScriptId(t.url),t),this.emitSourceScriptsForEnabledSessions())}emitSourceScriptsForEnabledSessions(){for(let e of this.debuggerEnabledSessions)this.emitSourceScripts(e)}emitSourceScripts(e){for(let t of this.sourceScriptsById.values())this.emitScriptParsed(t.url,e,t)}toCdpStackTrace(e){return e?{callFrames:e.callFrames.map(e=>({...e,scriptId:e.scriptId||(e.url?this.getScriptId(e.url):e.scriptId)}))}:void 0}registerRemoteObject(e){let t=`runtime:${++this.nextRemoteObjectId}`;return this.remoteObjects.set(t,e),t}emitScriptParsed(e,t,r){var i;let n=this.getScriptId(e),a=this.getParsedScriptIds(t);if(!this.debuggerEnabledSessions.has(t)||a.has(n))return;a.add(n);let s=(null==r?void 0:r.content.split("\n"))??[""];this.emit({method:"Debugger.scriptParsed",params:{scriptId:n,url:r?"":e,startLine:0,startColumn:0,endLine:r?s.length-1:1,endColumn:r?(null==(i=s.at(-1))?void 0:i.length)??0:0,executionContextId:1,hash:"",executionContextAuxData:{isDefault:!0,frameId:"wsd-main-frame"},isLiveEdit:!1,hasSourceURL:!1,isModule:!1,length:(null==r?void 0:r.content.length)??0,sourceMapURL:null==r?void 0:r.sourceMapURL,scriptLanguage:"JavaScript"}},t)}emit(e){for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];let n=r.length>0?r[0]:this.activeSessionId,a=n?{...e,sessionId:n}:e;for(let e of this.listeners)e(a)}emitRuntimeExecutionContext(e){this.emit({method:"Runtime.executionContextCreated",params:{context:{id:1,origin:"wsd://runtime",name:"Doubao",auxData:{isDefault:!0,frameId:"wsd-main-frame"}}}},e)}emitUnseenConsoleEntries(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"current";for(let t of this.runtimeEnabledSessions)this.emitUnseenConsoleEntriesForSession(t,e)}emitUnseenConsoleEntriesForSession(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"current";if(!this.runtimeEnabledSessions.has(e))return;let r="app"===t?this.appConsoleStore.entries:this.getConsoleAdapter().getConsoleEntries(),i=this.getKnownConsoleEntryIds(e,t);for(let t of r){var n;if(i.has(t.id)||(i.add(t.id),"host"===t.source))continue;let r=this.toCdpStackTrace(t.stackTrace),a={type:"warn"===(n=t.level)?"warning":"eval"===n?"log":n,args:uj(t,this.remoteObjectStore),executionContextId:1,timestamp:t.timestamp};r&&(a.stackTrace=r),this.emit({method:"Runtime.consoleAPICalled",params:a},e)}}emitSelectedStyleInvalidated(){let e=this.adapter.getSelectedNodeId(),t=e?this.nodeStore.getExistingCdpNodeId(e):void 0;t&&this.emit({method:"DOM.inlineStyleInvalidated",params:{nodeIds:[t]}})}}function u9(e){let{onReopen:t}=e;return(0,s.jsxs)("div",{className:"wsd-runtime-empty",children:[(0,s.jsx)("div",{"aria-hidden":"true",className:"wsd-runtime-empty-icon"}),(0,s.jsx)("div",{className:"wsd-runtime-empty-title",children:"页面已关闭"}),(0,s.jsx)("div",{className:"wsd-runtime-empty-description",children:"当前页面栈为空,可从调试面板重新选择页面渲染。"}),(0,s.jsx)("button",{className:"wsd-runtime-empty-action",onClick:t,type:"button",children:"重新打开当前页面"})]})}let u7=new Set(["log","info","warn","error","debug"]);function ce(e){return"AppletJSModule"===e||"LynxConsoleModule"===e}function ct(e,t,r){if("log"!==e)return null;let i="object"!=typeof t||null===t?null:"string"==typeof t.message||Array.isArray(t.args)?{level:u7.has(t.level)?t.level:void 0,message:"string"==typeof t.message?t.message:void 0,args:Array.isArray(t.args)?t.args:void 0,stack:"string"==typeof t.stack?t.stack:void 0}:null;return i?ce(r)?i:null:ce(r)?{level:"log",message:function(e){if("string"==typeof e)return e;if(void 0===e)return"undefined";try{return JSON.stringify(e)??String(e)}catch{return String(e)}}(t)}:null}class cr{listeners=new Set;runtimeConsoleEvents=[];current=null;subscribe(e){return this.listeners.add(e),()=>void this.listeners.delete(e)}reset(){this.runtimeConsoleEvents.length=0,this.set(null)}destroy(){this.reset(),this.listeners.clear()}set(e){this.current=e,this.flush(),this.notify()}notify(){for(let e of this.listeners)e(this.current)}dispatch(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];!this.current||t?this.runtimeConsoleEvents.push(e):s_(this.current,e)}flush(){if(this.current)for(let e of this.runtimeConsoleEvents.splice(0))s_(this.current,e)}}let ci=new Set(["doubao.openPage","doubao.navigateTo","doubao.redirectTo","doubao.reLaunch","doubao.navigateBack","doubao.exitApp"]);function cn(e){"function"==typeof queueMicrotask?queueMicrotask(e):Promise.resolve().then(e)}class ca{container;fileSystemNamespace;nativeModulesCallHandler;webSdkDebugger;onExitApp;onHideApp;visible=!0;onError;confirmBeforeUnload;apiEnvironment;previewTarget=new cr;appPreviewTarget=new cr;pageRoutesByTarget=new WeakMap;targetObserver=null;runtime=null;runtimeManifestUrl=null;lastRenderOptions=null;pageDevice=so["0"];isRuntimeTargetChanging=!1;navigationSourceTarget=null;deferredPageRoute;constructor(e){if(!e.container)throw Error("Page preview controller requires a container element");this.container=e.container,this.fileSystemNamespace=e.fileSystemNamespace,this.nativeModulesCallHandler=e.nativeModulesCallHandler,this.webSdkDebugger=e.webSdkDebugger,this.onExitApp=e.onExitApp,this.onHideApp=e.onHideApp,this.onError=e.onError,this.confirmBeforeUnload=e.confirmBeforeUnload,this.apiEnvironment=e.apiEnvironment??dI(),"u">typeof MutationObserver&&(this.targetObserver=new MutationObserver(this.handleRuntimeContainerMutation),this.targetObserver.observe(this.container,{childList:!0}))}async render(){var e,t,r;let i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=this.webSdkDebugger.getState(),a=!i.entry&&(null==(e=n.pageSelection)?void 0:e.routeUrl)?tO({url:n.pageSelection.routeUrl},n.manifest):void 0,s=(null==a?void 0:a.entry)??function(e,t){if(t.entry)return t.entry;if(!e.pageSelection)throw Error("No page selected");return e.pageSelection.item}(n,i),o=i.device??so["0"];this.pageDevice=o;let l=(null==a?void 0:a.initData)??i.initData??{},d=a?{...i.globalProps,...a.globalProps}:i.globalProps,u=this.getRuntime(n),c=a?null==(t=n.pageSelection)?void 0:t.routeUrl:void 0,p=s.path;if(c){let e=c.indexOf("?");p+=e<0?"":c.slice(e)}this.lastRenderOptions=i,this.isRuntimeTargetChanging=!0,this.deferredPageRoute={path:s.path,url:p};try{let e=await u[({navigate:"pushPage",redirect:"replacePage",relaunch:"reLaunchPage"})[i.routeMode??"redirect"]]({entry:s,initData:l,globalProps:d,pageCapsule:i.pageCapsule??{statusBarHeight:o.statusBarHeight}});if((null==(r=u.currentPage)?void 0:r.element)!==e.element)throw new DOMException("Page rendering was cancelled","AbortError");return this.bindPageTarget(e.element,{path:s.path,url:p}),this.previewTarget.set(e.element),e.element}catch(e){throw this.syncCurrentRuntimeTarget(),e}finally{this.isRuntimeTargetChanging=!1,this.navigationSourceTarget=null,this.deferredPageRoute=void 0,this.previewTarget.flush()}}getCurrentTarget(){return this.previewTarget.current}getCurrentAppTarget(){return this.appPreviewTarget.current}getCurrentPageUrl(){var e,t;let r=null==(e=this.runtime)?void 0:e.currentPage;return r?r.url??(null==(t=this.pageRoutesByTarget.get(r.element))?void 0:t.url)??r.route:null}async openPage(e){var t,r;if(!(null==(r=this.runtime)||null==(t=r.bridge.navigation)?void 0:t.openPage))throw Error("No Page runtime is active");await this.runtime.bridge.navigation.openPage(e),this.syncCurrentRuntimeTarget()}getPageStackSize(){var e;return(null==(e=this.runtime)?void 0:e.pages.length)??0}subscribeTarget(e){return this.previewTarget.subscribe(e)}subscribeAppTarget(e){return this.appPreviewTarget.subscribe(e)}sendAgentEvent(e,t){if(!this.runtime)throw Error("No Page runtime is active");this.runtime.sendAppEvent("onAgentEvent",{name:e,payload:t})}closeCurrentPage(){this.navigateBack()}navigateBack(e){var t;let r=(null==(t=this.runtime)?void 0:t.requestBack(e))??!1;return this.syncCurrentRuntimeTarget(),r}exitApp(){var e,t,r;null==(r=this.runtime)||null==(t=r.bridge.navigation)||null==(e=t.exitApp)||e.call(t),this.syncCurrentRuntimeTarget(),this.syncAppRuntimeTarget()}setVisible(e){var t;this.visible=e,null==(t=this.runtime)||t.setVisible(e)}async reopenCurrentPage(){try{await this.render(this.lastRenderOptions??{})}catch(t){var e;if(rP(t)&&"AbortError"===t.name)return;null==(e=this.onError)||e.call(this,t,new Event("error"))}}async restartRuntime(){var e,t;this.previewTarget.reset(),this.appPreviewTarget.reset();try{await (null==(e=this.runtime)?void 0:e.restart())}catch(e){if(rP(e)&&"AbortError"===e.name)return;null==(t=this.onError)||t.call(this,e,new Event("error"))}this.syncCurrentRuntimeTarget(),this.syncAppRuntimeTarget()}reload(){var e;null==(e=this.runtime)||e.reload(),this.previewTarget.notify()}clear(){var e;null==(e=this.runtime)||e.clear(),this.navigationSourceTarget=null,this.deferredPageRoute=void 0,this.previewTarget.reset(),this.appPreviewTarget.reset()}destroy(){var e,t;null==(e=this.targetObserver)||e.disconnect(),null==(t=this.runtime)||t.destroy(),this.runtime=null,this.runtimeManifestUrl=null,this.previewTarget.destroy(),this.appPreviewTarget.destroy()}packageManager=new tT;getRuntime(e){this.packageManager.configure({resolveManifestUrl:()=>e.manifestUrl,resourceUrlVersion:e.resourceUrlVersion}),this.packageManager.setPackage({manifest:e.manifest,manifestUrl:String(e.manifestUrl)});let t=e.manifestUrl;if(!this.runtime){let r={pageHost:new rW({container:this.container,confirmBeforeUnload:this.confirmBeforeUnload,onHide:this.onHideApp,mountEmptyState:e=>{var t;let r;return t=()=>this.reopenCurrentPage(),(r=(0,rZ.H)(e)).render((0,s.jsx)(u9,{onReopen:t})),()=>r.unmount()}}),packageManager:this.packageManager,sandboxUrl:void 0,manifest:e.manifest,manifestUrl:t,apiRegistry:this.apiEnvironment.apiRegistry,fileSystemNamespace:this.fileSystemNamespace,nativeModulesCallHandler:this.handleNativeModulesCall,onError:this.onError,getRuntimeGlobalProps:()=>sh(this.pageDevice)};return this.runtime=new rK(r),this.runtime.setVisible(this.visible),this.runtimeManifestUrl=t,this.runtime}return this.runtimeManifestUrl!==t&&(this.previewTarget.set(null),this.appPreviewTarget.set(null),this.runtime.setManifest(e.manifest,t),this.runtimeManifestUrl=t),this.runtime}handleNativeModulesCall=(e,t,r,i)=>{var n;if((null==i?void 0:i.containerType)==="APP"&&function(e,t,r){if("invokeCdp"!==e||"LynxDevToolSetModule"!==r||"string"!=typeof t)return!1;try{var i;return(null==(i=JSON.parse(t))?void 0:i.method)==="Page.reload"}catch{return!1}}(e,t,r))return cn(()=>this.restartRuntime()),JSON.stringify({result:{}});let a=function(e,t,r){if("AppletBridgeModule"===r&&"postMessage"===e&&"object"==typeof t&&null!==t&&"call"===t.type&&"string"==typeof t.name&&ci.has(t.name))return t.name}(e,t,r);a&&(this.navigationSourceTarget=this.previewTarget.current,this.deferredPageRoute=this.resolveNavigationPageRoute(t),this.scheduleRuntimeTargetSync("doubao.exitApp"===a?this.onExitApp:void 0));let s=ct(e,t,r);if(s){if((null==i?void 0:i.containerType)==="APP")this.syncAppRuntimeTarget(i.element),this.appPreviewTarget.dispatch({...s,label:"app"});else{let e=this.getRuntimeConsolePagePath(i);this.previewTarget.dispatch(e?{...s,pagePath:e}:s,this.isRuntimeTargetChanging)}return}return null==(n=this.nativeModulesCallHandler)?void 0:n.call(this,e,t,r,i)};handleRuntimeContainerMutation=()=>{this.syncCurrentRuntimeTarget(),this.syncAppRuntimeTarget()};scheduleRuntimeTargetSync(e){this.isRuntimeTargetChanging=!0;let t=this.navigationSourceTarget,r=()=>{this.isRuntimeTargetChanging=!1,this.navigationSourceTarget=null,this.deferredPageRoute=void 0,this.previewTarget.flush(),null==e||e()};cn(()=>{(this.syncCurrentRuntimeTarget(),this.previewTarget.current!==t)?r():cn(()=>{this.syncCurrentRuntimeTarget(),r()})})}syncCurrentRuntimeTarget(){var e;let t=(null==(e=this.runtime)?void 0:e.currentPage)??null,r=(null==t?void 0:t.element)??null,i=r!==this.navigationSourceTarget?this.deferredPageRoute:void 0;(r&&this.bindPageTarget(r,{path:(null==i?void 0:i.path)??this.getCurrentPagePath(),url:(null==t?void 0:t.url)??(null==i?void 0:i.url)}),this.previewTarget.current===r)?this.previewTarget.flush():this.previewTarget.set(r)}syncAppRuntimeTarget(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.getAppRuntimeElement();this.appPreviewTarget.current===e?this.appPreviewTarget.flush():this.appPreviewTarget.set(e)}getAppRuntimeElement(){return this.container.querySelector('lynx-view[data-container-type="APP"]')}bindPageTarget(e,t){if(!e)return;let r=this.pageRoutesByTarget.get(e),i=t.path??(null==r?void 0:r.path),n=t.url??(null==r?void 0:r.url)??i;(i||n)&&this.pageRoutesByTarget.set(e,{path:i,url:n})}resolveNavigationPageRoute(e){var t;if("object"!=typeof e||null===e)return;let r=null==(t=e.params)?void 0:t.url;if("string"!=typeof r||!r)return;let i=r.indexOf("?"),n=i<0?"":r.slice(i);try{let e=tO({url:r},this.webSdkDebugger.getState().manifest).entry;return{path:e.path,url:`${e.path}${n}`}}catch{return}}getCurrentPagePath(){var e;let t=null==(e=this.runtime)?void 0:e.currentPage;return null==t?void 0:t.entry.path}getRuntimeConsolePagePath(e){var t,r,i,n;if((null==e?void 0:e.containerType)!=="PAGE")return;let a=(null==(t=this.pageRoutesByTarget.get(e.element))?void 0:t.path)??(null==(r=this.deferredPageRoute)?void 0:r.path)??this.getCurrentPagePath();return this.bindPageTarget(null==(n=this.runtime)||null==(i=n.currentPage)?void 0:i.element,{path:a}),a}}class cs{container;fileSystemNamespace;nativeModulesCallHandler;webSdkDebugger;onError;apiEnvironment;previewTarget=new cr;widget=null;runtime=null;constructor(e){if(!e.container)throw Error("Widget preview controller requires a container element");this.container=e.container,this.fileSystemNamespace=e.fileSystemNamespace,this.nativeModulesCallHandler=e.nativeModulesCallHandler,this.webSdkDebugger=e.webSdkDebugger,this.onError=e.onError,this.apiEnvironment=e.apiEnvironment??dI()}async render(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.webSdkDebugger.getState(),r=function(e,t){if(t.widgetId)return t.widgetId;if(!e.widgetSelection)throw Error("No widget selected");return e.widgetSelection.item.widgetId}(t,e),i=e.viewport??sd,n=r2(e.initData??{}),a=e.globalProps??sm(i);this.clear();let s=new tT({resolveManifestUrl:()=>t.manifestUrl,resourceUrlVersion:t.resourceUrlVersion});s.setPackage({manifest:t.manifest,manifestUrl:String(t.manifestUrl)}),this.runtime=new rK({manifest:t.manifest,manifestUrl:t.manifestUrl,packageManager:s,sandboxUrl:void 0,apiRegistry:this.apiEnvironment.apiRegistry,fileSystemNamespace:this.fileSystemNamespace,nativeModulesCallHandler:this.handleNativeModulesCall,onError:this.onError}),this.widget=new rJ({runtime:this.runtime,appId:t.manifest.appId,container:this.container,globalProps:a,initData:n,onError:this.onError,widgetId:r});let o=await this.widget.render();return this.previewTarget.set(o),o}getCurrentTarget(){return this.previewTarget.current}subscribeTarget(e){return this.previewTarget.subscribe(e)}reload(){var e,t;null==(e=this.widget)||e.reload(),this.previewTarget.set((null==(t=this.widget)?void 0:t.element)??null)}clear(){this.disposeWidget(),this.previewTarget.reset()}destroy(){this.disposeWidget(),this.previewTarget.destroy()}disposeWidget(){var e,t;null==(e=this.widget)||e.destroy(),this.widget=null,null==(t=this.runtime)||t.destroy(),this.runtime=null,this.container.replaceChildren()}handleNativeModulesCall=(e,t,r,i)=>{var n;let a=ct(e,t,r);return a?void this.previewTarget.dispatch(a):null==(n=this.nativeModulesCallHandler)?void 0:n.call(this,e,t,r,i)}}var co=e=>(0,s.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",width:13.6,height:13.6,fill:"none",overflow:"visible",preserveAspectRatio:"none",style:{display:"block"},viewBox:"0 0 13.6 13.6",...e,children:(0,s.jsx)("path",{fill:"#999",d:"M.8 8.667a.8.8 0 0 1 .8.8V9.6c0 .573.001.955.025 1.248.023.284.064.415.106.497a1.2 1.2 0 0 0 .524.524c.083.042.213.083.497.106C3.045 12 3.427 12 4 12h.133a.8.8 0 0 1 0 1.6H4c-.547 0-1.005 0-1.379-.03-.383-.031-.747-.1-1.092-.275a2.8 2.8 0 0 1-1.224-1.223c-.176-.346-.244-.71-.275-1.093C0 10.606 0 10.147 0 9.6v-.133a.8.8 0 0 1 .8-.8m12 0a.8.8 0 0 1 .8.8V9.6c0 .547 0 1.006-.03 1.38-.031.382-.1.746-.275 1.092a2.8 2.8 0 0 1-1.223 1.223c-.346.176-.71.244-1.093.275-.373.03-.832.03-1.379.03h-.133a.8.8 0 0 1 0-1.6H9.6c.573 0 .955 0 1.248-.025.284-.023.415-.064.497-.106a1.2 1.2 0 0 0 .524-.524c.042-.082.083-.213.106-.497C12 10.555 12 10.173 12 9.6v-.133a.8.8 0 0 1 .8-.8M10.8 6a.8.8 0 0 1 0 1.6h-8a.8.8 0 0 1 0-1.6zM4.133 0a.8.8 0 0 1 0 1.6H4c-.573 0-.955.001-1.248.025-.284.023-.414.064-.497.106a1.2 1.2 0 0 0-.524.524c-.042.083-.083.213-.106.497C1.601 3.045 1.6 3.427 1.6 4v.133a.8.8 0 0 1-1.6 0V4c0-.547 0-1.005.03-1.379.031-.383.1-.747.275-1.092A2.8 2.8 0 0 1 1.53.305C1.874.13 2.239.061 2.62.03 2.995 0 3.453 0 4 0zM9.6 0c.547 0 1.006 0 1.38.03.382.031.746.1 1.092.275a2.8 2.8 0 0 1 1.223 1.224c.176.345.244.71.275 1.092.03.374.03.832.03 1.379v.133a.8.8 0 0 1-1.6 0V4c0-.573 0-.955-.025-1.248-.023-.284-.064-.414-.106-.497a1.2 1.2 0 0 0-.524-.524c-.082-.042-.213-.083-.497-.106-.293-.024-.675-.025-1.248-.025h-.133a.8.8 0 0 1 0-1.6z"})});function cl(e){let t=(0,iD.useRef)(e);t.current=e;let r=(0,iD.useRef)();return r.current??=function(){for(var e=arguments.length,r=Array(e),i=0;i<e;i++)r[i]=arguments[i];return t.current(...r)},r.current}let cd={revision:0,phase:"idle",canCancel:!1,canRetry:!1},cu=(0,iD.createContext)({});function cc(e){let{capability:t,children:r,getAppIdentity:i}=e;return(0,s.jsx)(cu.Provider,{value:{capability:t,getAppIdentity:i},children:r})}async function cp(e){let t=await e.json();if(!e.ok){var r;throw Error("error"in t&&(null==(r=t.error)?void 0:r.message)||"真机调试请求失败")}return t}function ch(){var e,t,r,i,n,a,o,l;let{capability:d,getAppIdentity:u}=(0,iD.useContext)(cu),[c,p]=(0,iD.useState)(!1),[h,m]=(0,iD.useState)(cd),[g,f]=(0,iD.useState)(),[v,y]=(0,iD.useState)("modern"),[b,w]=(0,iD.useState)(),_=(0,iD.useId)(),S=(0,iD.useRef)(!1),x=(0,iD.useRef)(cd),I=(0,iD.useRef)(null),k=cl(e=>{e.revision<x.current.revision||(x.current=e,m(e))}),C=cl(async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!d)throw Error("真机调试能力不可用");return cp(await fetch(e,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","X-DBX-Real-Device-Token":d.accessToken},body:JSON.stringify(t)}))}),E=cl(async()=>{if(d)try{let e=await C(d.stateEndpoint);k(e),f(void 0)}catch(e){f(e instanceof Error?e.message:String(e))}}),N=cl(async()=>{if(d){f(void 0);try{let e=await C(d.startEndpoint);if(!S.current&&e.operationId&&e.canCancel&&"web"===e.owner)return void await C(d.cancelEndpoint,{operationId:e.operationId}).catch(()=>void 0);k(e)}catch(e){f(e instanceof Error?e.message:String(e))}}}),T=cl(async()=>{let e=x.current;if(d&&e.operationId&&e.canCancel&&"web"===e.owner)try{let t=await C(d.cancelEndpoint,{operationId:e.operationId});k(t)}catch{}}),A=cl(()=>{S.current=!1,p(!1),T()});if((0,iD.useEffect)(()=>{if(!c||!d)return;E();let e=window.setInterval(()=>void E(),d.pollIntervalMs);return()=>window.clearInterval(e)},[d,c,E]),(0,iD.useEffect)(()=>{if(!c)return;let e=e=>{var t;(null==(t=I.current)?void 0:t.contains(e.target))||A()},t=e=>{"Escape"===e.key&&A()};return window.addEventListener("pointerdown",e),window.addEventListener("keydown",t),()=>{window.removeEventListener("pointerdown",e),window.removeEventListener("keydown",t)}},[A,c]),(0,iD.useEffect)(()=>{h.qr&&"modern"===v&&!h.qr.modernAvailable&&h.qr.legacyAvailable&&y("legacy")},[v,h.qr]),(0,iD.useEffect)(()=>{let e=!1;return c&&d&&h.operationId&&"waiting_for_scan"===h.phase&&h.qr&&("modern"===v?h.qr.modernAvailable:h.qr.legacyAvailable)?(w(void 0),f(void 0),fetch(d.qrEndpoint,{method:"POST",headers:{"Content-Type":"application/json","X-DBX-Real-Device-Token":d.accessToken},body:JSON.stringify({operationId:h.operationId,kind:v})}).then(e=>{if(!e.ok)throw Error("二维码暂不可用");return e.blob()}).then(t=>{e||w(URL.createObjectURL(t))}).catch(t=>{e||f(t instanceof Error?t.message:String(t))}),()=>{e=!0}):void w(void 0)},[d,c,v,h.connectionMode,h.operationId,h.phase,null==(e=h.qr)?void 0:e.legacyAvailable,null==(t=h.qr)?void 0:t.modernAvailable,null==(r=h.qr)?void 0:r.revision]),(0,iD.useEffect)(()=>{if(b)return()=>URL.revokeObjectURL(b)},[b]),!d)return null;let M=function(e){switch(e.phase){case"preparing":return"正在准备真机调试环境";case"downloading":return"正在下载 Desktop 工具";case"installing_tool":return"正在安装 Desktop 工具";case"reusing_client":return"检测到已连接客户端,正在继续真机调试";case"waiting_for_scan":return"使用已登录的豆包客户端扫码";case"waiting_for_install":return"设备已连接,正在安装调试包";case"launching_tool":return"正在启动 Desktop 工具";case"connected":return"环境已就绪";case"timed_out":return"等待设备连接超时";case"cancelled":return"已取消真机调试";case"failed":var t;return(null==(t=e.error)?void 0:t.message)||"真机调试启动失败";default:return"准备开始真机调试"}}(h),R=null==(i=h.progress)?void 0:i.percentage,j="number"==typeof R&&"downloading"===h.phase,P="waiting_for_scan"===h.phase&&!!h.qr,L=!!b&&P,O="waiting_for_scan"!==h.phase&&"connected"!==h.phase,D="failed"===h.phase||"timed_out"===h.phase||!!g,U=D?"二维码暂不可用":"connected"===h.phase?"连接成功,请勿重复扫码":"准备完成后可扫码",q="existing_client"===h.connectionMode?"已复用当前连接,无需扫码":"扫码成功",$=null==u?void 0:u(),B=[null==$||null==(n=$.appName)?void 0:n.trim(),null==$||null==(a=$.appKey)?void 0:a.trim()].filter(Boolean).join(" · ");return(0,s.jsxs)("div",{className:"wsd-physical-device-wrapper",ref:I,children:[(0,s.jsx)("button",{"aria-expanded":c,"aria-haspopup":"dialog","aria-label":"真机调试","aria-pressed":c,"aria-describedby":_,className:(0,rL.$)("wsd-device-toolbar-icon",c&&"is-active"),onClick:()=>{c?A():(y("modern"),S.current=!0,p(!0),N())},type:"button",children:(0,s.jsx)(co,{"aria-hidden":"true"})}),(0,s.jsx)("span",{className:"wsd-physical-device-tooltip",id:_,role:"tooltip",children:"真机调试"}),c?(0,s.jsxs)("dialog",{"aria-label":"真机调试",className:"wsd-physical-device-popover",open:!0,children:[(0,s.jsxs)("header",{className:"wsd-physical-device-header",children:[(0,s.jsx)("h2",{children:"真机调试"}),(0,s.jsx)("p",{children:"使用已登录的客户端扫码,创建新的真机调试对话"})]}),(0,s.jsxs)("div",{className:"wsd-physical-device-content",children:[(0,s.jsxs)("div",{"aria-label":"客户端版本",className:"wsd-physical-device-client-tabs",role:"tablist",children:[(0,s.jsx)("button",{"aria-selected":"modern"===v,className:(0,rL.$)("modern"===v&&"is-active"),disabled:!P||!(null==(o=h.qr)?void 0:o.modernAvailable),onClick:()=>y("modern"),role:"tab",type:"button",children:"新版客户端"}),(0,s.jsx)("button",{"aria-selected":"legacy"===v,className:(0,rL.$)("legacy"===v&&"is-active"),disabled:!P||!(null==(l=h.qr)?void 0:l.legacyAvailable),onClick:()=>y("legacy"),role:"tab",type:"button",children:"旧版客户端"})]}),(0,s.jsx)("div",{className:(0,rL.$)("wsd-physical-device-qr",!L&&"is-locked"),children:L&&b?(0,s.jsx)("img",{alt:"modern"===v?"新版客户端真机调试二维码":"旧版客户端真机调试二维码",src:b}):(0,s.jsx)("div",{className:"wsd-physical-device-placeholder",children:(0,s.jsx)("strong",{children:U})})})]}),"waiting_for_scan"===h.phase?(0,s.jsx)("div",{className:"wsd-physical-device-notice",children:"使用豆包 14.70 以上版本扫码"}):"connected"===h.phase?(0,s.jsx)("div",{className:"wsd-physical-device-notice is-success",children:q}):null,j?(0,s.jsx)("div",{className:"wsd-physical-device-progress","aria-label":`下载进度 ${Math.round(R)}%`,children:(0,s.jsx)("span",{style:{width:`${Math.max(0,Math.min(100,R))}%`}})}):null,O?(0,s.jsxs)("div",{className:"wsd-physical-device-details",children:[B?(0,s.jsx)("div",{"aria-label":"小程序信息",className:"wsd-physical-device-app-identity",title:B,children:B}):null,(0,s.jsxs)("div",{className:(0,rL.$)("wsd-physical-device-status",D&&"is-error"),children:[["preparing","downloading","installing_tool","reusing_client","waiting_for_scan","waiting_for_install","launching_tool"].includes(h.phase)&&!j?(0,s.jsx)("span",{className:"wsd-physical-device-spinner","aria-hidden":"true"}):null,(0,s.jsx)("div",{children:(0,s.jsx)("strong",{children:g||M})})]})]}):null,(h.canRetry||g)&&D?(0,s.jsx)("button",{className:"wsd-physical-device-retry",onClick:()=>void N(),type:"button",children:"重新尝试"}):null]}):null]})}let cm=(0,iD.createContext)(null);function cg(e){let t=function(e){let t=(0,iD.useContext)(cm),r=e??t;if(!r)throw Error("WebSdkDebuggerProvider is missing");return r}(e),r=(0,iD.useCallback)(e=>t.subscribe(e),[t]),i=(0,iD.useCallback)(()=>t.getState(),[t]);return(0,iD.useSyncExternalStore)(r,i,i)}function cf(e){let{fallbackName:t,selector:r}=e;return r?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("span",{className:"wsd-runtime-highlight-selector-tag",children:r.tagName}),r.id?(0,s.jsxs)("span",{className:"wsd-runtime-highlight-selector-id",children:["#",r.id]}):null,r.classNames.map(e=>(0,s.jsxs)("span",{className:"wsd-runtime-highlight-selector-class",children:[".",e]},e))]}):(0,s.jsx)("span",{className:"wsd-runtime-highlight-selector-tag",children:t??"element"})}function cv(e){let{focusable:t}=e;return t?(0,s.jsx)("span",{children:"true"}):(0,s.jsx)("span",{"aria-label":"not focusable",className:"wsd-runtime-highlight-not-focusable"})}function cy(e){var t,r,i,n,a;let{highlightRect:o,overlay:l,runtimeFrameRef:d,runtimeFrameScaleBoxRef:u,runtimeScaleMode:c,runtimeShellRef:p,runtimeStyle:h,runtimeTargetRef:m}=e,g=(0,iD.useSyncExternalStore)(l9.subscribe,l9.getSnapshot),f=(0,iD.useRef)(null),[v,y]=(0,iD.useState)(null),b=function(e,t){let r=e[t];if("number"==typeof r)return r;if("string"!=typeof r)return null;let i=Number.parseFloat(r);return Number.isFinite(i)?i:null}(h,"--wsd-runtime-height"),w=o&&v&&null!==b&&o.top+o.height+v.gap+v.height>b&&o.top>v.gap+v.height,_=o?{"--wsd-highlight-content-height":`${(null==(t=o.boxModel)?void 0:t.content.height)??o.height}px`,"--wsd-highlight-content-left":`${(null==(r=o.boxModel)?void 0:r.content.left)??0}px`,"--wsd-highlight-content-top":`${(null==(i=o.boxModel)?void 0:i.content.top)??0}px`,"--wsd-highlight-content-width":`${(null==(n=o.boxModel)?void 0:n.content.width)??o.width}px`,"--wsd-highlight-height":`${o.height}px`,"--wsd-highlight-left":`${o.left}px`,"--wsd-highlight-top":`${o.top}px`,"--wsd-highlight-width":`${o.width}px`}:void 0,S=cl(e=>{let t=Number.parseFloat(getComputedStyle(e).getPropertyValue("--wsd-highlight-popover-gap")),r={gap:Number.isFinite(t)?t:0,height:e.offsetHeight};y(e=>(null==e?void 0:e.gap)===r.gap&&e.height===r.height?e:r)}),x=cl(e=>{var t;if(null==(t=f.current)||t.disconnect(),f.current=null,!e||(S(e),"u"<typeof ResizeObserver))return;let r=new ResizeObserver(()=>S(e));r.observe(e),f.current=r});return(0,s.jsx)("section",{className:"wsd-device-preview","data-scale-mode":c,ref:p,children:(0,s.jsx)("div",{className:"wsd-device-preview-scale-box",ref:u,style:h,children:(0,s.jsxs)("div",{className:"wsd-device-preview-frame",ref:d,style:{filter:`brightness(${g.brightness})`},children:[m?(0,s.jsx)("div",{className:"wsd-runtime-target",ref:m}):null,o?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("div",{"aria-hidden":"true",className:"wsd-runtime-highlight",style:_,children:(0,s.jsx)("div",{className:"wsd-runtime-highlight-content-frame"})}),(0,s.jsxs)("div",{"aria-hidden":"true",className:(0,rL.$)("wsd-runtime-highlight-popover",w&&"is-above"),ref:x,style:_,children:[(0,s.jsxs)("div",{className:"wsd-runtime-highlight-header",children:[(0,s.jsx)("span",{"aria-hidden":"true",className:"wsd-runtime-highlight-node-icon"}),(0,s.jsx)("strong",{className:"wsd-runtime-highlight-selector",children:(0,s.jsx)(cf,{fallbackName:o.nodeName,selector:o.selector})}),(0,s.jsx)("span",{className:"wsd-runtime-highlight-dimensions",children:o.dimensions??`${o.width} \xd7 ${o.height}`})]}),(null==(a=o.styles)?void 0:a.length)?(0,s.jsx)("dl",{className:"wsd-runtime-highlight-details",children:o.styles.map(e=>(0,s.jsxs)("div",{className:"wsd-runtime-highlight-detail",children:[(0,s.jsx)("dt",{children:e.name}),(0,s.jsxs)("dd",{children:[e.swatch?(0,s.jsx)("span",{className:"wsd-runtime-highlight-swatch",style:{backgroundColor:e.swatch}}):null,(0,s.jsx)("span",{children:e.value})]})]},e.name))}):null,o.accessibility?(0,s.jsxs)("section",{className:"wsd-runtime-highlight-accessibility",children:[(0,s.jsx)("div",{className:"wsd-runtime-highlight-section-title",children:(0,s.jsx)("span",{children:"ACCESSIBILITY"})}),(0,s.jsxs)("dl",{className:"wsd-runtime-highlight-details",children:[(0,s.jsxs)("div",{className:"wsd-runtime-highlight-detail",children:[(0,s.jsx)("dt",{children:"Name"}),(0,s.jsx)("dd",{children:o.accessibility.name})]}),(0,s.jsxs)("div",{className:"wsd-runtime-highlight-detail",children:[(0,s.jsx)("dt",{children:"Role"}),(0,s.jsx)("dd",{children:o.accessibility.role})]}),(0,s.jsxs)("div",{className:"wsd-runtime-highlight-detail",children:[(0,s.jsx)("dt",{children:"Keyboard-focusable"}),(0,s.jsx)("dd",{children:(0,s.jsx)(cv,{focusable:o.accessibility.keyboardFocusable})})]})]})]}):null]})]}):null,l]})})})}function cb(e){let t,r,i,{cashier:n,onCancel:a,onConfirm:o}=e,[l,d]=(0,iD.useState)(!1),[u,c]=(0,iD.useState)(""),[p,h]=(0,iD.useState)(n.paymentTypes[0].id),m=n.paymentTypes.find(e=>{let{id:t}=e;return t===p})||n.paymentTypes[0],g=n.paymentTypes.length>1,f=async()=>{if(!l){d(!0),c("");try{await o(p)}catch(e){d(!1),c(lT(e))}}};return(0,s.jsxs)("div",{className:"wsd-simulator-overlay-layer wsd-sandbox-cashier-layer",children:[(0,s.jsx)("div",{"aria-hidden":"true",className:"wsd-simulator-overlay-backdrop wsd-sandbox-cashier-backdrop"}),(0,s.jsxs)("dialog",{"aria-label":"支付收银台","aria-modal":"true",className:"wsd-sandbox-cashier",open:!0,children:[(0,s.jsx)("button",{"aria-label":"关闭收银台",className:"wsd-sandbox-cashier-close",disabled:l,onClick:a,type:"button",children:"×"}),(0,s.jsx)("section",{className:"wsd-sandbox-cashier-amount",children:(0,s.jsx)("strong",{children:(r=(t=n.totalAmount.replace(/^0+(?=\d)/,"").padStart(3,"0")).slice(0,-2)||"0",i=t.slice(-2),`\xa5${r.replace(/\B(?=(\d{3})+(?!\d))/g,",")}.${i}`)})}),(0,s.jsxs)("section",{className:"wsd-sandbox-cashier-payment",children:[(0,s.jsx)("h2",{children:"支付方式"}),g?(0,s.jsx)("div",{className:"wsd-sandbox-cashier-payment-options",children:n.paymentTypes.map(e=>{let t=e.id===p;return(0,s.jsxs)("button",{"aria-pressed":t,className:"wsd-sandbox-cashier-payment-option",disabled:l,onClick:()=>{h(e.id)},type:"button",children:[(0,s.jsx)("span",{children:e.name}),t?(0,s.jsx)("span",{"aria-hidden":"true",children:"✓"}):null]},e.id)})}):(0,s.jsx)("div",{className:"wsd-sandbox-cashier-payment-trigger is-static",children:m.name}),u?(0,s.jsxs)("p",{className:"wsd-sandbox-cashier-error",role:"alert",children:["支付失败,请重试:",u]}):null]}),(0,s.jsx)("footer",{className:"wsd-sandbox-cashier-actions",children:(0,s.jsx)("button",{"aria-busy":l,className:"wsd-sandbox-cashier-button",disabled:l,onClick:()=>void f(),type:"button",children:l?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("svg",{"aria-hidden":"true",className:"wsd-sandbox-cashier-spinner",viewBox:"0 0 16 16",children:[(0,s.jsx)("circle",{className:"wsd-sandbox-cashier-spinner-track",cx:"8",cy:"8",fill:"none",r:"6",strokeWidth:"2"}),(0,s.jsx)("path",{className:"wsd-sandbox-cashier-spinner-indicator",d:"M 8 2 A 6 6 0 0 1 14 8",fill:"none",strokeLinecap:"round",strokeWidth:"2"})]}),"支付中"]}):"模拟支付"})})]})]})}function cw(){let[e,t]=(0,iD.useState)(),r=(0,iD.useRef)(null),i=(0,iD.useRef)(null),n=(0,iD.useRef)(!1),a=cl((e,n)=>r.current?Promise.reject(Error("Sandbox cashier is already open")):new Promise(a=>{r.current=a,i.current=n,t(e)})),s=cl(e=>{let n=r.current;n&&(r.current=null,i.current=null,t(void 0),n(e))}),o=cl(()=>{n.current||s(!1)}),l=cl(async e=>{let t=i.current;if(!t)throw Error("Sandbox cashier is unavailable");if(!n.current){n.current=!0;try{await t(e),s(!0)}finally{n.current=!1}}});return(0,iD.useEffect)(()=>()=>{let e=r.current;r.current=null,i.current=null,n.current=!1,null==e||e(!1)},[]),{cashier:e,cancelCashier:o,confirmCashier:l,showCashier:a}}let c_=new WeakMap;async function cS(e,t,r){c_.set(e,t);try{await e.sendSimulatorQuery(r)}finally{c_.get(e)===t&&c_.delete(e)}}function cx(e,t){let r=c_.get(e);if(r&&(!t||r===t))return c_.delete(e),e.cancelSimulatorQuery(),r}var cI=e=>(0,s.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:15,height:15,fill:"none",viewBox:"0 0 15 15",...e,children:[(0,s.jsx)("path",{fill:"#999",fillRule:"evenodd",d:"M7.333 4.545a2.788 2.788 0 1 0 0 5.576 2.788 2.788 0 0 0 0-5.576m0 1.334a1.455 1.455 0 1 0 0 2.909 1.455 1.455 0 0 0 0-2.91",clipRule:"evenodd"}),(0,s.jsx)("path",{fill:"#999",fillRule:"evenodd",d:"M5.067 1.862c.489-2.483 4.045-2.483 4.533 0 2.1-1.41 4.615 1.104 3.205 3.205 2.482.489 2.482 4.044 0 4.533 1.41 2.1-1.104 4.615-3.205 3.205-.488 2.483-4.044 2.482-4.533 0-2.1 1.41-4.615-1.104-3.205-3.205-2.483-.488-2.483-4.045 0-4.533-1.41-2.1 1.105-4.615 3.205-3.205m1.307.266c.202-1.06 1.718-1.06 1.92 0a1.322 1.322 0 0 0 2.042.846c.891-.607 1.964.466 1.357 1.357a1.322 1.322 0 0 0 .846 2.043c1.06.201 1.06 1.718 0 1.92a1.322 1.322 0 0 0-.846 2.042c.607.891-.466 1.963-1.357 1.357a1.322 1.322 0 0 0-2.042.846c-.202 1.06-1.719 1.06-1.92 0a1.322 1.322 0 0 0-2.043-.846c-.891.607-1.963-.466-1.357-1.357a1.322 1.322 0 0 0-.846-2.043c-1.06-.201-1.06-1.718 0-1.92l.44-.083A1.028 1.028 0 0 0 3.225 4.7l-.251-.37c-.607-.891.466-1.964 1.357-1.357a1.322 1.322 0 0 0 2.043-.846",clipRule:"evenodd"})]});function ck(){return(0,s.jsxs)("div",{className:"wsd-doubao-status-bar","aria-hidden":"true",children:[(0,s.jsx)("span",{className:"wsd-doubao-status-time",children:"9:41"}),(0,s.jsx)("span",{className:"wsd-doubao-status-indicators"})]})}function cC(e){let{className:t,fallback:r,src:i}=e,[n,a]=(0,iD.useState)(!1);return(0,iD.useEffect)(()=>{a(!1)},[i]),(0,s.jsx)("span",{className:`${t}-box`,"aria-hidden":"true",children:i&&!n?(0,s.jsx)("img",{alt:"",className:t,onError:()=>a(!0),src:i}):(0,s.jsx)("span",{className:`${t}-fallback`,children:(null==r?void 0:r.trim().slice(0,1))||"服"})})}function cE(e){let t=Number(e);if(!Number.isFinite(t))return;let r=new Date(t);return Number.isFinite(r.getTime())?r:void 0}function cN(e){let{notices:t,onAction:r,onBack:i,status:n}=e;return(0,s.jsxs)("section",{"aria-label":"服务通知",className:"wsd-service-notice-panel",children:[(0,s.jsxs)("header",{className:"wsd-service-notice-chrome",children:[(0,s.jsx)(ck,{}),(0,s.jsxs)("div",{className:"wsd-service-notice-title-bar",children:[(0,s.jsx)("button",{"aria-label":"返回对话",className:"wsd-service-notice-nav-button is-back",onClick:i,type:"button",children:(0,s.jsx)("span",{"aria-hidden":"true"})}),(0,s.jsx)("h1",{children:"服务通知"}),(0,s.jsx)("button",{"aria-label":"服务通知设置",className:"wsd-service-notice-nav-button is-settings",type:"button",children:(0,s.jsx)(cI,{"aria-hidden":"true"})})]})]}),(0,s.jsx)("div",{className:"wsd-service-notice-list",children:"loading"===n&&0===t.length?(0,s.jsx)("p",{className:"wsd-service-notice-empty",children:"正在加载服务通知..."}):t.length>0?t.map(e=>{let t=e.title||"服务通知",i=cE(e.created_at_ms),n=e.redirect_url;return(0,s.jsxs)("div",{className:"wsd-service-notice-item",children:[(0,s.jsx)("time",{dateTime:null==i?void 0:i.toISOString(),children:function(e){let t=cE(e);if(!t)return"";let r=new Date,i=new Date(r.getFullYear(),r.getMonth(),r.getDate()).getTime(),n=new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime(),a=new Intl.DateTimeFormat("zh-CN",{hour:"2-digit",hour12:!1,minute:"2-digit"}).format(t);return n===i?a:n===i-864e5?`昨天 ${a}`:`${t.getMonth()+1}月${t.getDate()}日 ${a}`}(e.created_at_ms)}),(0,s.jsxs)("article",{"aria-label":n?`${t},查看详情`:void 0,className:`wsd-service-notice-card${n?" is-clickable":""}`,onClick:()=>{n&&(null==r||r(n))},onKeyDown:e=>{n&&("Enter"===e.key||" "===e.key)&&(e.preventDefault(),null==r||r(n))},role:n?"link":void 0,tabIndex:n?0:void 0,children:[(0,s.jsxs)("div",{className:"wsd-service-notice-app",children:[(0,s.jsx)(cC,{className:"wsd-service-notice-icon",fallback:e.app_name,src:e.app_icon_url}),(0,s.jsx)("span",{children:e.app_name||"应用插件"})]}),(0,s.jsxs)("div",{className:"wsd-service-notice-body",children:[(0,s.jsx)("h2",{children:t}),e.fields.length>0?(0,s.jsx)("dl",{children:e.fields.map((e,t)=>(0,s.jsxs)("div",{children:[(0,s.jsx)("dt",{children:e.name}),(0,s.jsx)("dd",{children:e.value})]},`${e.name}-${t}`))}):e.brief?(0,s.jsx)("p",{children:e.brief}):null]})]})]},e.notice_id)}):(0,s.jsx)("p",{className:"wsd-service-notice-empty",children:"暂无服务通知"})})]})}let cT=new Set([1,2,3]);function cA(e){return e.filter(e=>1!==e.display_status&&cT.has(e.status))}function cM(e){let{onAction:t,onClose:r,onRemove:i,onRemoveAction:n,removingTaskIds:a,tasks:o}=e,l=cA(o);async function d(e){var t,r;let a=null==(t=e.remove_action)?void 0:t.confirm;(null==a||!a.need_confirm||window.confirm([a.title||"移除任务",a.content||"确定要移除这个任务吗?"].join("\n")))&&((null==(r=e.remove_action)?void 0:r.target)&&await (null==n?void 0:n(e.remove_action.target)),await i(e.task_id))}async function u(e,i){await (null==t?void 0:t(e,i))&&r()}return((0,iD.useEffect)(()=>{let e=e=>{"Escape"===e.key&&r()};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[r]),(0,iD.useEffect)(()=>{0===l.length&&r()},[l.length,r]),0===l.length)?null:(0,s.jsxs)("div",{className:"wsd-sandbox-task-overlay-layer",children:[(0,s.jsx)("button",{"aria-label":"关闭进行中的任务",className:"wsd-sandbox-task-overlay-backdrop",onClick:r,type:"button"}),(0,s.jsx)("dialog",{"aria-label":"进行中的任务","aria-modal":"true",className:"wsd-sandbox-task-overlay",open:!0,children:(0,s.jsx)("div",{className:"wsd-sandbox-task-list",children:l.map(e=>{var t,r,i,n,o,l;let c=(null==(t=e.display_data)?void 0:t.title)||"未命名任务",p=(null==(r=e.display_data)?void 0:r.sub_title)||(null==(i=e.progress)?void 0:i.text),h=null==(n=e.primary_action)?void 0:n.target,m=a.has(e.task_id);return(0,s.jsxs)("article",{"aria-label":h?`${c},${(null==(o=e.primary_action)?void 0:o.text)||"查看详情"}`:void 0,className:(0,rL.A)("wsd-sandbox-task-card",h&&"is-clickable"),onClick:()=>{h&&u(h,e)},onKeyDown:t=>{h&&("Enter"===t.key||" "===t.key)&&(t.preventDefault(),u(h,e))},role:h?"button":void 0,tabIndex:h?0:void 0,children:[(0,s.jsx)(cC,{className:"wsd-sandbox-task-icon",fallback:c,src:null==(l=e.display_data)?void 0:l.icon_url}),(0,s.jsxs)("span",{className:"wsd-sandbox-task-copy",children:[(0,s.jsx)("strong",{children:c}),p?(0,s.jsx)("span",{children:p}):null]}),(0,s.jsx)("button",{"aria-label":`移除任务:${c}`,className:"wsd-sandbox-task-remove",disabled:m,onClick:t=>{t.stopPropagation(),d(e)},type:"button",children:(0,s.jsx)("span",{"aria-hidden":"true"})})]},e.task_id)})})})]})}let cR={bridgeLogs:[],clearBridgeLogs:()=>Promise.reject(Error("服务端日志接口不可用")),hasUnreadNotices:!1,hasUnreadTasks:!1,markServiceNoticesRead:()=>void 0,markTasksRead:()=>void 0,localConnectionStatus:"unavailable",notices:[],reconnect:()=>void 0,removeTask:async()=>void 0,removingTaskIds:new Set,status:"unavailable",tasks:[]},cj=(0,iD.createContext)(cR),cP={logs:[],updatedAtMs:0};function cL(){return{eventSequence:0,generation:0,instanceId:"",simulatorEventSequence:0}}function cO(e,t){try{let r=BigInt(e),i=BigInt(t);return r===i?0:r>i?1:-1}catch{return String(e).localeCompare(String(t),void 0,{numeric:!0})}}function cD(e){if(rP(e)&&"string"==typeof e.id&&rP(e.request)&&"string"==typeof e.status&&["error","pending","success"].includes(e.status)&&"number"==typeof e.timestamp&&"number"==typeof e.updatedAtMs)return{errorMessage:"string"==typeof e.errorMessage?e.errorMessage:void 0,id:e.id,logIds:Array.isArray(e.logIds)?e.logIds.filter(e=>"string"==typeof e):[],request:e.request,requestId:"string"==typeof e.requestId?e.requestId:"",response:rP(e.response)?e.response:void 0,sandboxSessionId:"string"==typeof e.sandboxSessionId?e.sandboxSessionId:"",status:e.status,timestamp:e.timestamp,updatedAtMs:e.updatedAtMs}}function cU(e){if(rP(e)&&("remove"===e.action||"upsert"===e.action)&&("notice"===e.resource||"task"===e.resource)&&"string"==typeof e.resourceId&&("number"==typeof e.revision||"string"==typeof e.revision)&&"number"==typeof e.sequence)return{action:e.action,eventId:"string"==typeof e.eventId?e.eventId:"",occurredAtMs:"number"==typeof e.occurredAtMs?e.occurredAtMs:void 0,resource:e.resource,resourceId:e.resourceId,revision:e.revision,sequence:e.sequence}}function cq(e){if(rP(e)&&("card_delta"===e.type||"get_simulator_card_snapshots"===e.type)&&rP(e.payload)&&("get_simulator_card_snapshots"!==e.type||"string"==typeof e.payload.event_id)&&"number"==typeof e.sequence)return{payload:e.payload,sequence:e.sequence,type:e.type}}function c$(e){let{children:t,enabled:r,connection:i,onMessage:n,webSdkDebugger:a}=e,[o,l]=(0,iD.useState)([]),[d,u]=(0,iD.useState)([]),[c,p]=(0,iD.useState)(!1),[h,m]=(0,iD.useState)(!1),[g,f]=(0,iD.useState)(r&&i?"loading":"unavailable"),[v,y]=(0,iD.useState)(cP),[b,w]=(0,iD.useState)(r&&i?"connecting":"unavailable"),[_,S]=(0,iD.useState)(new Set),x=(0,iD.useRef)(new Map),I=(0,iD.useRef)(new Map),k=(0,iD.useRef)(new Map),C=(0,iD.useRef)(new Map),E=(0,iD.useRef)({notice:void 0,task:void 0}),N=(0,iD.useRef)({}),T=(0,iD.useRef)(new Set),A=(0,iD.useRef)(!1),M=(0,iD.useRef)(),R=(0,iD.useRef)(cL()),j=(0,iD.useRef)(0),P=(0,iD.useRef)(n);P.current=n;let L=cl(async e=>{let t="string"==typeof e.payload.event_id?e.payload.event_id:"";if("card_delta"===e.type){null==a||a.applySimulatorCardDelta(e.payload);return}if(T.current.has(t))return;T.current.add(t);let r=(()=>{try{if(!a)throw Error("Web SDK debugger is unavailable");return{card_snapshots:aQ(a.getState().simulator.messages)}}catch{return{error:{code:"SNAPSHOT_COLLECTION_FAILED",message:"failed to collect simulator state"}}}})();await lB(t,r)}),O=cl(()=>{l([...x.current.values()].sort((e,t)=>Number(e.created_at_ms)-Number(t.created_at_ms)))}),D=cl(()=>{u([...I.current.values()].sort((e,t)=>Number(t.updated_at_ms)-Number(e.updated_at_ms)))}),U=cl(function(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1],r=!1;for(let t of e.notices??[]){let e=k.current.get(t.notice_id);(void 0===e||cO(t.revision,e)>0)&&(k.current.set(t.notice_id,t.revision),x.current.set(t.notice_id,t),r=!0)}for(let t of e.removed_notices??[]){let e=k.current.get(t.resource_id);(void 0===e||cO(t.revision,e)>=0)&&(k.current.set(t.resource_id,t.revision),x.current.delete(t.resource_id))}r&&t&&p(!0),O()}),q=cl(e=>{let t=C.current.get(e.resource_id);(void 0===t||cO(e.revision,t)>=0)&&(C.current.set(e.resource_id,e.revision),I.current.delete(e.resource_id),D())}),$=cl(e=>{let t=!1;for(let r of e.tasks??[]){let e=C.current.get(r.task_id);void 0!==e&&0>=cO(r.revision,e)||(C.current.set(r.task_id,r.revision),t=!0,1===r.display_status?I.current.delete(r.task_id):I.current.set(r.task_id,r))}for(let r of e.removed_tasks??[]){let e=C.current.get(r.resource_id);(void 0===e||cO(r.revision,e)>=0)&&(C.current.set(r.resource_id,r.revision),I.current.delete(r.resource_id),t=!0)}t&&m(!0),D()}),B=cl(async function(e,t){let r,i=!(arguments.length>2)||void 0===arguments[2]||arguments[2];do{let n=E.current[e],a="notice"===e?await lU({cursor:n,limit:100}):await lq({cursor:n,limit:100});if(j.current!==t)return;if("notice"===e?U(a,i):$(a),a.has_more&&!a.next_cursor)throw Error(`Sandbox ${e} pull returned has_more without next_cursor`);a.next_cursor&&(E.current[e]=a.next_cursor),r=a.has_more}while(r)}),F=cl(function(e,t){let r=!(arguments.length>2)||void 0===arguments[2]||arguments[2],i=N.current[e];if(i)return i;let n=B(e,t,r).finally(()=>{N.current[e]===n&&delete N.current[e]});return N.current[e]=n,n}),z=cl(async(e,t)=>{if(j.current===t){if("remove"===e.action){let t={resource_id:e.resourceId,revision:e.revision,updated_at_ms:e.occurredAtMs??Date.now()};if("notice"===e.resource){let t=k.current.get(e.resourceId);(void 0===t||cO(e.revision,t)>=0)&&(k.current.set(e.resourceId,e.revision),x.current.delete(e.resourceId),O())}else q(t);return}if("notice"===e.resource){let r=await lU({notice_ids:[e.resourceId]});j.current===t&&U(r)}else{let r=await lq({task_ids:[e.resourceId]});j.current===t&&$(r)}}}),W=cl(function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];e||(x.current.clear(),k.current.clear(),p(!1),l([])),I.current.clear(),C.current.clear(),E.current={notice:void 0,task:void 0},N.current={},m(!1),u([])}),H=cl(async()=>{if(!i)throw Error("服务端日志接口不可用");await i.clearSandboxLogs()}),V=cl(()=>null==i?void 0:i.start());(0,iD.useEffect)(()=>{let e;if(!i){W(),A.current=!1,M.current=void 0,R.current=cL(),y(cP),w("unavailable"),f("unavailable");return}let t=!1,n=++j.current,a=!1,s=-1,o=!1,l=M.current!==i;l||!A.current?(W(),A.current=!1,l&&(R.current=cL())):N.current={},M.current=i,f(r?"loading":"unavailable");let d=e=>{var r;if(t)return;let i=e instanceof Error?e.message:String(e);f("error"),null==(r=P.current)||r.call(P,`Sandbox 资源同步失败:${i}`,!0)},u=function(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return o?Promise.resolve():Promise.all([F("notice",n,e),F("task",n)])},c=async(i,l)=>{var d;if(t)return;if(i.bridgeLogs){let e={logs:(i.bridgeLogs??[]).map(cD).filter(e=>!!e),updatedAtMs:i.bridgeLogsUpdatedAtMs??0};y(t=>t.updatedAtMs===e.updatedAtMs?t:e)}if(!r)return;let c=i.connectionStatus!==e;e=i.connectionStatus;let p=R.current,h=!!p.instanceId&&i.instanceId!==p.instanceId||0!==p.generation&&i.generation!==p.generation;if(p.instanceId||(p.instanceId=i.instanceId),0===p.generation&&(p.generation=i.generation),h&&(p.instanceId=i.instanceId,p.generation=i.generation,p.eventSequence=0,p.simulatorEventSequence=0,T.current.clear(),o=!1,n=++j.current,a=!1,W(A.current),f("loading")),l&&(await u(A.current),A.current=!0,a=!0),i.updatedAtMs!==s){for(let e of(s=i.updatedAtMs,i.simulatorEvents.filter(e=>e.sequence>p.simulatorEventSequence).sort((e,t)=>e.sequence-t.sequence)))try{await L(e)}catch(t){let e=t instanceof Error?t.message:String(t);null==(d=P.current)||d.call(P,`Sandbox 模拟器事件处理失败:${e}`,!0)}finally{p.simulatorEventSequence=Math.max(p.simulatorEventSequence,e.sequence)}if(h&&!l&&(await u(),a=!0),o)return;let e=i.events.filter(e=>e.sequence>p.eventSequence).sort((e,t)=>e.sequence-t.sequence);for(let t of(p.eventSequence>0&&e[0]&&e[0].sequence>p.eventSequence+1&&await u(),e))await z(t,n),p.eventSequence=Math.max(p.eventSequence,t.sequence)}!o&&("reconnecting"===i.connectionStatus&&c?(f("reconnecting"),await u()):a&&"connected"===i.connectionStatus&&f("connected"))},p=async(e,t)=>{try{await c(e,t)}catch(e){(function(e){if(!(e instanceof lg))return!1;let t=e.remoteCode??e.options.httpStatus;return -1===t||401===t||403===t||404===t})(e)&&(o||(o=!0,d(e)),1)||d(e)}},h=!0,m=Promise.resolve(),g=i.subscribe(e=>{if("status"===e.type)w(e.status),"connected"!==e.status&&(h=!0);else if("sandbox"===e.type){let t=function(e){if(rP(e)&&["connected","connecting","reconnecting"].includes(String(e.connectionStatus))&&"number"==typeof e.generation&&"number"==typeof e.updatedAtMs)return{bridgeLogs:Array.isArray(e.bridgeLogs)?e.bridgeLogs:void 0,bridgeLogsUpdatedAtMs:"number"==typeof e.bridgeLogsUpdatedAtMs?e.bridgeLogsUpdatedAtMs:void 0,connectionStatus:e.connectionStatus,events:Array.isArray(e.events)?e.events.map(cU).filter(e=>!!e):[],generation:e.generation,instanceId:"string"==typeof e.instanceId?e.instanceId:"",simulatorEvents:Array.isArray(e.simulatorEvents)?e.simulatorEvents.map(cq).filter(e=>!!e):[],updatedAtMs:e.updatedAtMs}}(e.data);if(!t)return void d(Error("本地调试服务事件格式错误"));let r=h;h=!1,m=m.then(()=>p(t,r))}});return()=>{t=!0,j.current+=1,g()}},[r,i,L,F,z,W]);let G=cl(async e=>{S(t=>new Set(t).add(e));try{let t=await l$(e);q(t)}finally{S(t=>{let r=new Set(t);return r.delete(e),r})}}),J=cl(()=>{p(!1)}),K=cl(()=>{m(!1)}),Z=(0,iD.useMemo)(()=>({bridgeLogs:v.logs,clearBridgeLogs:H,hasUnreadNotices:c,hasUnreadTasks:h,localConnectionStatus:b,markServiceNoticesRead:J,markTasksRead:K,notices:o,reconnect:V,removeTask:G,removingTaskIds:_,status:g,tasks:d}),[v.logs,H,c,h,b,J,K,o,V,G,_,g,d]);return(0,s.jsx)(cj.Provider,{value:Z,children:t})}function cB(){return(0,iD.useContext)(cj)}var cF=r(64031),cz=r(88460);let cW={a(e){let{children:t,href:r}=e;return r&&function(e){if(!e)return!1;if(e.startsWith("#"))return!0;try{let t=new URL(e,"http://localhost");return["http:","https:","mailto:"].includes(t.protocol)}catch{return!1}}(r)?(0,s.jsx)("a",{href:r,rel:"noreferrer",target:"_blank",children:t}):(0,s.jsx)(s.Fragment,{children:t})}};function cH(e){let{text:t}=e;return(0,s.jsx)("div",{className:"wsd-widget-chat-text markdown-body wsd-widget-chat-markdown",children:(0,s.jsx)(cF.oz,{components:cW,remarkPlugins:[cz.A],children:t})})}async function cV(e,t){var r,i;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:globalThis.fetch,a=new URL(e,null==(r=globalThis.location)?void 0:r.href);t&&a.searchParams.set("version_tag",t);let s=await n(a.toString());if(!s.ok)throw Error(`Get Web CDN URL failed with HTTP ${s.status}`);let o=await s.json();if(0!==o.code){let e=o.message??o.msg??o.log_id??"";throw Error(`Get Web CDN URL failed: ${o.code} ${e}`.trim())}let l=null==(i=o.data)?void 0:i.web_cdn_url;if(!l)throw Error("Web CDN URL response did not include data.web_cdn_url");return l}let cG=new class extends tT{options;constructor(e={}){super(e),this.options=e}async getPackageSource(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e)throw Error("OnlinePackageManager requires appId");let r=await this.cached(`cdn:${e}\0${t.versionTag??""}`,()=>cV(this.options.requestUrl??`https://developer.doubao.com/app_developer/resource_api/apps/${encodeURIComponent(e)}/web_cdn_url`,t.versionTag,this.options.fetcher),t);return{manifestUrl:new URL("base/manifest.json",r).href,resourceRoot:r}}async fetchPackage(e,t){let r=this.options.fetcher??globalThis.fetch,i=await r(e);if(!i.ok)throw Error(`Failed to load Web manifest: ${i.status}`);let n=await i.json();if(!(null==n?void 0:n.appId)||!n.applet)throw Error("Invalid online Web manifest");return{manifestUrl:e,resourceRoot:t,manifest:new c({...n,applet:{...n.applet,pages:n.applet.pages??[]},widgets:n.widgets??[]})}}};function cJ(e){return{"doubao.callMcpTool":async t=>_(t,await lz({...e,params:t.params}))}}function cK(e){return{"doubao.updateWidget":t=>{if(!rP(t.params))return S(t,"Invalid updateWidget parameters",104);let r=e(t.params);return"updated"===r.status?_(t,{}):S(t,r.message,"not_found"===r.status?116:104)}}}function cZ(e,t,r){var i;return{request_id:t,trace_id:r,card_id:e.card_id,widget_id:e.widget_id,card_type:e.card_type,entity_id:e.entity_id,source_tool_call_id:null==(i=e.source)?void 0:i.tool_call_id,render_data:e.render_data}}function cX(e){let{packageManager:t=cG,apiEnvironment:r,appId:i,fileSystemNamespace:n,card:a,inspectableTargetKey:o,reloadKey:l,nativeModulesCallHandler:d,onInspectableTargetChange:u,onTraceEvent:c,onUpdateWidget:p,requestId:h,runtimeConsoleTarget:m,traceId:g,viewport:f,widgets:v}=e,y=(0,iD.useRef)(null),b=(0,iD.useRef)(null),w=(0,iD.useRef)(a);w.current=a;let _=a.widget_id,S=f??sd,x=!!_&&((null==v?void 0:v.some(e=>e.widgetId===_))??!1),[I,k]=(0,iD.useState)(),[C,E]=(0,iD.useState)(0),[N,T]=(0,iD.useState)({status:"idle"}),A=I??S.width,M={height:`${C||Math.round(1.35*A)}px`},R=(0,iD.useMemo)(()=>{let e=(null==r?void 0:r.apiRegistry.fork())??dx();return e.registerMany(cJ({appKey:a.app_id||i||"",scene:"widget",widgetId:_||"",widgetInstanceId:a.card_id||""}),{override:!0}),p&&e.registerMany(cK(p),{override:!0}),e},[null==r?void 0:r.apiRegistry,i,a.app_id,a.card_id,p,_]),j=(0,iD.useMemo)(()=>(e,t,r,i)=>{let n=ct(e,t,r);return n?void s_(m??i.element,n):null==d?void 0:d(e,t,r,i)},[d,m]);return(0,iD.useEffect)(()=>{let e=y.current;if(!e)return;let t=()=>{let t=e.clientWidth;(t>0||"u"<typeof ResizeObserver)&&k(t||S.width)};if(t(),"u"<typeof ResizeObserver)return window.addEventListener("resize",t),()=>{window.removeEventListener("resize",t)};let r=new ResizeObserver(t);return r.observe(e),()=>{r.disconnect()}},[S.width]),(0,iD.useEffect)(()=>{let e,r,a=y.current;if(!a||void 0===I)return;let s=w.current;if(a.replaceChildren(),E(0),o&&(null==u||u(o,null)),!_){let e="缺少 widget_id,已展示 fallback";T({status:"skipped",message:e}),null==c||c({category:"card",event:"simulator_card_render_skipped",reason:"missing_widget_id",summary:e,...cZ(s,h,g)});return}if(!i){let e="缺少 appId,已展示 fallback";T({status:"skipped",message:e}),null==c||c({category:"card",event:"simulator_card_render_skipped",reason:"missing_app_id",summary:e,...cZ(s,h,g)});return}if(!x){let e=`Manifest 中找不到 widget_id: ${_}`;T({status:"skipped",message:e}),null==c||c({category:"card",event:"simulator_card_render_skipped",reason:"widget_not_found",summary:e,...cZ(s,h,g)});return}let l=!1,d=null,p=null,m=new AbortController,f=sm({...S,width:I}),v=()=>{l||E(Math.ceil(a.scrollHeight||a.getBoundingClientRect().height))},k=()=>{"u"<typeof window?v():(void 0!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(v))},C=Date.now();return T({status:"rendering"}),(async()=>(p=new rK({appId:i,signal:m.signal,packageManager:t,apiRegistry:R,fileSystemNamespace:n,sandboxUrl:void 0,nativeModulesCallHandler:j}),l)?void p.destroy():(b.current=d=new rJ({runtime:p,appId:i,viewContext:{appId:i,widgetId:_,widgetInstanceId:s.card_id},container:a,globalProps:f,initData:r2(s.render_data),onError:e=>{null==c||c({category:"card",event:"simulator_card_runtime_error",elapsed_ms:Date.now()-C,summary:e.message,...cZ(s,h,g)})},widgetId:_}),d.render()))().then(e=>{!l&&e&&(null==d||d.updateData(r2(w.current.render_data)),T({status:"rendered"}),o&&(null==u||u(o,e,I)),k(),"u">typeof ResizeObserver&&(r=new ResizeObserver(k)).observe(a),null==c||c({category:"card",event:"simulator_card_rendered",elapsed_ms:Date.now()-C,...cZ(s,h,g)}))}).catch(e=>{if(l)return;let t=r6(e);T({status:"error",message:t}),o&&(null==u||u(o,null)),null==c||c({category:"card",event:"simulator_card_render_failed",elapsed_ms:Date.now()-C,summary:t,...cZ(s,h,g)})}),()=>{l=!0,m.abort(),void 0!==e&&window.cancelAnimationFrame(e),null==r||r.disconnect(),b.current=null,null==d||d.destroy(),null==p||p.destroy(),a.replaceChildren(),o&&(null==u||u(o,null))}},[t,r,R,i,n,a.card_id,a.refresh_key,j,o,u,c,l,S,I,x,_]),(0,iD.useEffect)(()=>{var e;null==(e=b.current)||e.updateData(r2(a.render_data))},[a.render_data]),(0,s.jsxs)("div",{className:"wsd-widget-chat-card-runtime",children:[(0,s.jsx)("div",{className:"wsd-widget-chat-card-runtime-viewport",style:M,children:(0,s.jsx)("div",{className:"wsd-widget-chat-card-runtime-target",ref:y})}),"rendering"===N.status?(0,s.jsx)("span",{className:"wsd-widget-chat-card-runtime-status",children:"卡片渲染中..."}):null,"skipped"===N.status||"error"===N.status?(0,s.jsx)("span",{className:"wsd-widget-chat-card-runtime-status",children:N.message}):null]})}let cY="mcp-privacy-login-card",cQ="__doubao_apps__expired-widget";function c0(e){return e.title||e.fallback_text||e.card_type||e.card_id||"卡片"}function c1(e,t){return(null==e?void 0:e.some(e=>e.widgetId===t))?e:[...e??[],{widgetId:t}]}function c2(e,t){return`${e.messageId}:${t.blockId}:${t.card.card_id||t.blockId}`}function c3(e){let{packageManager:t,apiEnvironment:r,appId:i,fileSystemNamespace:n,block:a,cardReloadKey:o,message:l,nativeModulesCallHandler:d,onInspectableCardTargetChange:u,grantingItemIndex:c,onGrantingCardOpen:p,onGrantingPermissionDecision:h,onGrantingCardSkip:m,onTraceEvent:g,onUpdateWidget:f,runtimeConsoleTarget:v,widgetViewport:y,widgets:b}=e,w=(0,iD.useMemo)(()=>"card"===a.type&&a.card.widget_id===cQ?c1(b,cQ):b,[a,b]);if((0,iD.useEffect)(()=>{var e;"card"!==a.type||"permission_apply"===a.card.card_type||a.card.widget_id||null==g||g({category:"card",event:"simulator_card_render_skipped",reason:"missing_widget_id",summary:"缺少 widget_id,已展示 fallback",...(e=a.card,{request_id:l.requestId,trace_id:l.traceId,card_id:e.card_id,widget_id:e.widget_id,card_type:e.card_type})})},[a,l.requestId,l.traceId,g]),"text"===a.type)return(0,s.jsx)(cH,{text:a.text});if("image"===a.type)return(0,s.jsx)("img",{alt:a.image.name||"对话图片",className:"wsd-widget-chat-image",src:a.image.previewUrl});if("permission_apply"===a.card.card_type){var _;let e=c2(l,a),t=(null==(_=c6(a.card,c))?void 0:_.itemIndex)??0;return(0,s.jsx)(c9,{card:a.card,grantingItemIndex:t,onLogin:()=>null==p?void 0:p(a.card,e,t),onPermissionDecision:r=>null==h?void 0:h(a.card,e,t,r),onSkip:r=>null==m?void 0:m(r,a.card,e,t),onTraceEvent:g})}return a.card.widget_id?(0,s.jsx)("article",{className:"wsd-widget-chat-card has-runtime",children:(0,s.jsx)(cX,{packageManager:t,apiEnvironment:r,appId:i,fileSystemNamespace:n,card:a.card,inspectableTargetKey:c2(l,a),reloadKey:o,nativeModulesCallHandler:d,onInspectableTargetChange:u,onTraceEvent:g,onUpdateWidget:f,requestId:l.requestId,runtimeConsoleTarget:v,traceId:l.traceId,viewport:y,widgets:w})}):(0,s.jsxs)("article",{className:"wsd-widget-chat-card",children:[(0,s.jsx)("span",{className:"wsd-widget-chat-card-kicker",children:a.card.card_type||"卡片"}),(0,s.jsx)("strong",{children:c0(a.card)}),a.card.fallback_text&&a.card.fallback_text!==c0(a.card)?(0,s.jsx)("span",{className:"wsd-widget-chat-card-summary",children:a.card.fallback_text}):null]})}function c4(e){var t;return null==(t=e.render_data)?void 0:t.grantingData}function c5(e){return"pending"===e.permissionStatus||"revoked"===e.permissionStatus}function c6(e,t){let r=c4(e),i=(null==r?void 0:r.grantingList.findIndex(c5))??-1,n="number"==typeof t&&(null==r?void 0:r.grantingList[t])?t:-1===i?0:i;if(n<0)return;let a=null==r?void 0:r.grantingList[n];return a&&r?{grantingData:r,item:a,itemIndex:n}:void 0}function c8(e){let{appIcon:t}=e,[r,i]=(0,iD.useState)(!1);return((0,iD.useEffect)(()=>{i(!1)},[t]),!t||r)?null:(0,s.jsx)("img",{alt:"",className:"wsd-widget-granting-prompt-logo",onError:()=>i(!0),src:t})}function c9(e){let{card:t,grantingItemIndex:r,onLogin:i,onPermissionDecision:n,onSkip:a,onTraceEvent:o}=e,l=(0,iD.useMemo)(()=>c6(t,r),[t,r]),d=null==l?void 0:l.grantingData,u=null==l?void 0:l.item,c=(null==d?void 0:d.doubaoAppletName)||"应用插件",p=(null==u?void 0:u.grantingName)==="permission",h=(null==u?void 0:u.relatedData.scopeName)??"",m=(0,iD.useMemo)(()=>sH(h),[h]),[g,f]=(0,iD.useState)(),[v,y]=(0,iD.useState)(),b=oi.isLocationScope(h),w=void 0!==v,_=b&&"granted"===v,S=p&&(null==d?void 0:d.cardStatus)==="expired",x=p&&!g&&(!w||b)&&!S&&((null==u?void 0:u.permissionStatus)==="pending"||(null==u?void 0:u.permissionStatus)==="revoked"),I=p?m.title:`在豆包内使用 ${c}`,k=p?"granted"===g?`已允许${c}获取`:"refused"===g?`已拒绝${c}获取`:S?"已过期,暂无法操作":(null==u?void 0:u.relatedData.scopeDescription)||m.description:(null==u?void 0:u.relatedData.bizLoginDescription)||((null==u?void 0:u.grantingName)==="privacy"?"需同意后才可以继续使用":"需登录后才可以继续使用");async function C(e){if(!w){y(e?"granted":"refused"),null==o||o({category:"card",event:"simulator_granting_prompt_permission_click",granted:e,scope:h});try{let t=await (null==n?void 0:n(e));!1!==t&&f(e?"granted":"refused")}finally{y(void 0)}}}return(0,iD.useEffect)(()=>{f(void 0),y(void 0)},[t.card_id,null==d?void 0:d.cardStatus,r,null==u?void 0:u.permissionStatus,h]),(0,s.jsxs)("article",{className:(0,rL.$)("wsd-widget-granting-prompt-card",p&&"is-permission"),children:[(0,s.jsxs)("header",{className:"wsd-widget-granting-prompt-brand",children:[(0,s.jsx)(c8,{appIcon:null==d?void 0:d.doubaoAppletIcon}),(0,s.jsx)("span",{children:c})]}),(0,s.jsx)("strong",{className:"wsd-widget-granting-prompt-title",children:I}),(0,s.jsx)("p",{className:"wsd-widget-granting-prompt-description",children:k}),p?x?(0,s.jsxs)("footer",{className:"wsd-widget-granting-prompt-actions",children:[(0,s.jsx)("button",{className:"wsd-widget-granting-prompt-secondary",disabled:w,onClick:()=>void C(!1),type:"button",children:"拒绝"}),(0,s.jsxs)("button",{"aria-busy":_,className:"wsd-widget-granting-prompt-primary",disabled:w,onClick:()=>void C(!0),type:"button",children:[_?(0,s.jsxs)("svg",{"aria-hidden":"true",className:"wsd-widget-granting-prompt-spinner",viewBox:"0 0 16 16",children:[(0,s.jsx)("circle",{className:"wsd-widget-granting-prompt-spinner-track",cx:"8",cy:"8",fill:"none",r:"6",strokeWidth:"2"}),(0,s.jsx)("path",{className:"wsd-widget-granting-prompt-spinner-indicator",d:"M 8 2 A 6 6 0 0 1 14 8",fill:"none",strokeLinecap:"round",strokeWidth:"2"})]}):null,"允许"]})]}):null:(0,s.jsxs)("footer",{className:"wsd-widget-granting-prompt-actions",children:[(0,s.jsx)("button",{className:"wsd-widget-granting-prompt-secondary",onClick:function(){null==o||o({category:"card",event:"simulator_granting_prompt_skip_click",granting_name:null==u?void 0:u.grantingName}),null==a||a((null==u?void 0:u.grantingName)==="privacy"?"privacy":"login")},type:"button",children:"暂不登录"}),(0,s.jsx)("button",{className:"wsd-widget-granting-prompt-primary",onClick:function(){null==o||o({category:"card",event:"simulator_granting_prompt_login_click",granting_name:null==u?void 0:u.grantingName}),null==i||i()},type:"button",children:"登录"})]})]})}function c7(e){let{packageManager:t,apiEnvironment:r,appId:i,fileSystemNamespace:n,card:a,grantingItemIndex:o,inspectableTargetKey:l,nativeModulesCallHandler:d,onInspectableTargetChange:u,onTraceEvent:c,runtimeConsoleTarget:p,widgets:h}=e,m=(0,iD.useMemo)(()=>c1(h,cY),[h]),g=(0,iD.useMemo)(()=>(function(e,t){let r,i,n,a,s,o,l,d;return{...e,card_id:`${e.card_id||"permission_apply"}:${cY}`,card_type:"permission_apply",render_data:{...e.render_data,viewData:(i=null==(r=c6(e,t))?void 0:r.grantingData,a=(null==(n=null==r?void 0:r.item)?void 0:n.relatedData)??{},s=(null==i?void 0:i.doubaoAppletName)||"应用插件",o=(null==n?void 0:n.grantingName)==="privacy",l=a.mobileMask??"",d=o?a.bizPrivacyContent||`${s} 需要你同意隐私政策后继续。`:a.bizLoginDescription||"登录后继续使用相关服务",{type:(null==n?void 0:n.grantingName)==="privacy"?"agreePrivacyAuthorization":"getPhoneNumber",currentPage:"chat",brand:{name:s,logo:(null==i?void 0:i.doubaoAppletIcon)||""},content:{title:o?"隐私协议提示":"申请获取并验证你的手机号",description:d},buttons:o?{primary:{text:"同意并继续",loadingText:"处理中..."},secondary:{text:"暂不同意"}}:{primary:{text:l,loadingText:"登录中...",subtext:"豆包绑定号码"},secondary:{text:"暂不登录"},other:{text:"其他登录方式"}},agreement:{text:[{text:`已阅读并同意${s}的`},{text:"服务协议",url:a.termsOfServiceURL},{text:"和"},{text:"隐私政策",url:a.privacyURL}]},warningToast:"请先阅读并同意协议"})},widget_id:cY}})(a,o),[a,o]),f=(0,iD.useMemo)(()=>({key:"simulator-login-sheet",label:"登录半屏",width:393,density:3}),[]);return(0,s.jsx)("dialog",{className:"wsd-widget-granting-card has-runtime",open:!0,children:(0,s.jsx)(cX,{packageManager:t,apiEnvironment:r,appId:i,fileSystemNamespace:n,card:g,inspectableTargetKey:l,nativeModulesCallHandler:d,onInspectableTargetChange:u,onTraceEvent:c,runtimeConsoleTarget:p,viewport:f,widgets:m})})}function pe(e){let{packageManager:t,apiEnvironment:r,appId:i,fileSystemNamespace:n,cardReloadKey:a,grantingItemIndexes:o,message:l,nativeModulesCallHandler:d,onInspectableCardTargetChange:u,onGrantingCardOpen:c,onGrantingPermissionDecision:p,onGrantingCardSkip:h,onTraceEvent:m,onTraceSelect:g,onUpdateWidget:f,runtimeConsoleTarget:v,selectedTraceId:y,widgetViewport:b,widgets:w}=e,_="assistant"===l.role,S=(l.blocks.length>0?l.blocks:l.text.trim()?[{blockId:`${l.messageId}-text`,type:"text",text:l.text}]:[]).reduce((e,t)=>{let r=e[e.length-1];return"text"===t.type&&(null==r?void 0:r.type)==="text"?e[e.length-1]={...r,text:`${r.text}${t.text}`}:e.push(t),e},[]),x=S.some(e=>"card"===e.type),I=S.some(e=>"image"===e.type),k=S.some(e=>"text"===e.type&&e.text.trim()),C=l.traceId,E=!!(C&&g),N=!!(C&&C===y);return(0,s.jsxs)("article",{"aria-pressed":E?N:void 0,className:(0,rL.$)("wsd-widget-chat-message",_?"is-assistant":"is-user",k&&"has-text",x&&"has-card",I&&"has-image",E&&"is-trace-selectable",N&&"is-trace-selected"),onClick:e=>{!C||!g||pt(e.target)||g(C)},onKeyDown:e=>{!C||!g||pt(e.target)||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),g(C))},role:E?"button":void 0,tabIndex:E?0:void 0,children:[_?(0,s.jsx)("span",{className:"wsd-widget-chat-avatar",children:"AI"}):null,(0,s.jsxs)("div",{className:"wsd-widget-chat-bubble",children:[S.map(e=>(0,s.jsx)(c3,{packageManager:t,apiEnvironment:r,appId:i,fileSystemNamespace:n,block:e,cardReloadKey:a,grantingItemIndex:"card"===e.type?null==o?void 0:o[c2(l,e)]:void 0,message:l,nativeModulesCallHandler:d,onGrantingCardOpen:c,onGrantingPermissionDecision:p,onGrantingCardSkip:h,onInspectableCardTargetChange:u,onTraceEvent:m,onUpdateWidget:f,runtimeConsoleTarget:v,widgetViewport:b,widgets:w},e.blockId)),"streaming"===l.status&&S.every(e=>"text"!==e.type||!e.text)?(0,s.jsx)("span",{className:"wsd-widget-chat-placeholder",children:"正在思考..."}):null]})]})}function pt(e){return e instanceof Element&&!!e.closest("button,a,input,textarea,select,.wsd-widget-chat-card")}let pr="mcp-login-page";function pi(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return JSON.stringify([e,...t.map(e=>e.resource_uri)])}function pn(e){return e.split(":")[0]||""}function pa(e){var t,r,i;let{messageInputDisabled:n=!1,packageManager:a,apiEnvironment:o,appId:l,fileSystemNamespace:d,cardReloadKey:u,controlCommand:c,nativeModulesCallHandler:p,onGrantingSheetTargetChange:h,onControlResult:m,onInspectableCardTargetChange:g,onNavigateToPage:f,onQuerySubmit:v,onSandboxLocationConfigOpen:y,onTraceEvent:b,onTraceMessageSelect:w,runtimeConsoleTarget:_,sandboxLoginHint:S,simulator:x,selectedTraceId:I,widgetViewport:k,widgets:C,webSdkDebugger:E,onMessage:N}=e,[T,A]=(0,iD.useState)(""),[M,R]=(0,iD.useState)(),[j,P]=(0,iD.useState)(!1),[L,O]=(0,iD.useState)(!1),[D,U]=(0,iD.useState)(!1),q=cB(),$=(0,iD.useMemo)(()=>cA(q.tasks).length>0,[q.tasks]),B=(0,iD.useRef)(null),F=(0,iD.useRef)(x.messages.length),z=(0,iD.useRef)(0),W=(0,iD.useRef)(),H=(0,iD.useRef)(),V=(0,iD.useRef)(0),G=(0,iD.useRef)(!0),[J,K]=(0,iD.useState)(),[Z,X]=(0,iD.useState)({}),Y=(0,iD.useRef)(new Set),Q=(0,iD.useRef)(),ee=(0,iD.useRef)(new Set),et=(0,iD.useRef)(new Set),er=(0,iD.useRef)(new Set),ei="streaming"===x.streamStatus,en=(null==M?void 0:M.uploadStatus)==="uploading",ea=!!(T.trim()||(null==M?void 0:M.uploadedImage))&&!en&&!ei,es=(r=null==J?void 0:J.card)?null==(i=c4(r))?void 0:i.doubaoAppletKey:void 0,eo=l||es,el=cl(e=>{(K(void 0),f)?f({url:e}):E.navigateToPage(e)}),ed=cl(()=>{var e;null==o||null==(e=o.uiPresenter)||e.showToast({duration:3e3,icon:"warn",message:"请先在模拟器顶部“设置 → 定位”配置位置",type:"warning"}),null==y||y()}),eu=cl(e=>E.updateSimulatorWidget(e)),ec=cl((e,t)=>{let r=af(E,{grantingMessageId:(null==t?void 0:t.grantingMessageId)??(J?pn(J.key):void 0),noLogin:null==t?void 0:t.noLogin});if("not_found"===r.status){null==N||N("未找到需要重发的原始消息",!0);return}if("streaming"===r.status){null==N||N("当前仍在生成中,暂不重发授权后的消息",!0);return}K(void 0),null==b||b({category:"card",event:"simulator_granting_resend_query",granting_type:e,no_login:(null==t?void 0:t.noLogin)===!0,removed_message_ids:r.target.messageIds,query_preview:r.target.query.slice(0,80)}),null==v||v(),r.completion.catch(e=>{null==N||N(e.message,!0)})}),ep=cl(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};null==b||b({category:"card",event:e,card_id:t.cardId,request_id:t.requestId,source_tool_call_id:t.sourceToolCallId,tool_name:t.toolName,...r})}),eh=cl(async(e,t)=>{ep("simulator_location_directive_started",e);try{let r=await oi.requestLocationForHostDirective();if("success"!==r.status){ed(),ep("simulator_location_directive_unavailable",e,{failure_type:r.code?`browser_geolocation_${r.code}`:"browser_geolocation_unavailable",location_status:r.status});return}try{let e=oi.createBusinessLocationInfo(r.location);await lY(JSON.stringify(e))}catch(t){ep("simulator_location_directive_report_failed",e,{failure_type:t instanceof Error?t.name:typeof t}),null==N||N(`位置信息上报失败:${t instanceof Error?t.message:String(t)}`,!0);return}if(ep("simulator_location_directive_reported",e),"completed"!==E.getState().simulator.streamStatus){ep("simulator_location_directive_unavailable",e,{failure_type:"simulator_stream_not_completed"}),null==N||N("当前仍在生成中,暂不重发定位后的消息",!0);return}er.current.add(t.key),E.removeSimulatorMessages(t.messageIds),ep("simulator_location_directive_resend_started",e),null==v||v();try{await (t.images?E.sendSimulatorQuery(t.query,{images:t.images}):E.sendSimulatorQuery(t.query))}catch(e){null==N||N(e.message,!0)}}finally{et.current.delete(t.key)}});(0,iD.useEffect)(()=>{let e=x.locationDirective;if(!e||"completed"!==x.streamStatus||ee.current.has(e.cardId))return;ee.current.add(e.cardId),E.consumeSimulatorLocationDirective(e.cardId);let t=function(e,t){let r=t.replyMessageId?e.findIndex(e=>e.messageId===t.replyMessageId):e.findIndex(e=>"assistant"===e.role&&e.requestId===t.requestId),i=e.find(e=>"user"===e.role&&e.messageId===t.queryMessageId)??e.findLast((e,t)=>(-1===r||t<r)&&"user"===e.role&&(!!e.text.trim()||e.blocks.some(e=>"image"===e.type)));if(!i)return;let n=i.text.trim(),a=i.blocks.filter(e=>"image"===e.type).map(e=>e.image);if(n||0!==a.length)return{images:a.length>0?a:void 0,key:pi(n,a),messageIds:[i.messageId,...-1===r?[]:[e[r].messageId]],query:n}}(x.messages,e);if(!t)return void ep("simulator_location_directive_unavailable",e,{failure_type:"original_query_not_found"});if(et.current.has(t.key)||er.current.has(t.key)){ep("simulator_location_directive_loop_prevented",e),null==N||N("位置已上报但平台仍要求定位,请检查“设置 → 定位”中的位置状态",!0);return}et.current.add(t.key),eh(e,t)},[eh,N,x.locationDirective,x.messages,x.streamStatus,ep]);let em=cl((e,t,r,i)=>{var n;let a=c6(e,r);if(!a){null==N||N("索权卡缺少有效的授权项",!0);return}let s=`${t}:${r}`;if(Y.current.has(s))return;Y.current.add(s);let o=function(e,t){let r=c4(e);if(!r)return;let i=r.grantingList.findIndex((e,r)=>r>t&&c5(e));return -1===i?void 0:i}(e,r),l=function(e){switch(e){case"permission":case"privacy":return e;default:return"login"}}(a.item.grantingName);if(!i&&!1!==a.item.required)return void ec(l,{grantingMessageId:pn(t),noLogin:!0});if(void 0!==o){X(e=>({...e,[t]:o})),K(e=>(null==e?void 0:e.key)===t?void 0:e),null==b||b({category:"card",event:"simulator_granting_item_advanced",granted:i,granting_name:a.item.grantingName,next_granting_name:null==(n=c6(e,o))?void 0:n.item.grantingName});return}ec(l,{grantingMessageId:pn(t)})}),eg=cl((e,t,r)=>{var i,n;let a;(null==(a=null==(i=c6(e,r))?void 0:i.item)?void 0:a.grantingName)==="privacy"||(null==a||null==(n=a.relatedData.mobileMask)?void 0:n.trim())?K({card:e,itemIndex:r,key:t}):(null==b||b({category:"card",event:"simulator_granting_custom_login_navigate",reason:"missing_mobile_mask",url:pr}),el(pr))}),ef=cl(async(e,t,r,i)=>{let n,a=function(e,t){var r;let i=c6(e,t),n=null==i?void 0:i.grantingData,a=null==i?void 0:i.item,s=(null==n?void 0:n.doubaoAppletKey.trim())??"",o=(null==a||null==(r=a.relatedData.scopeName)?void 0:r.trim())??"";if((null==a?void 0:a.grantingName)==="permission"&&s&&o)return{appId:s,appName:(null==n?void 0:n.doubaoAppletName)||"应用插件",required:!1!==a.required,scope:o}}(e,r);if(!a)return null==N||N("索权卡缺少有效的应用插件 appId 或 scopeName",!0),!1;if(oi.isLocationScope(a.scope)&&(oi.updateUserAuthorization(i),i)){let e=await oi.requestLocation();if("success"!==e.status)return"browser_unauthorized"===e.status&&ed(),null==b||b({category:"card",event:"simulator_granting_location_unavailable",location_status:e.status,scope:a.scope}),!1;n=oi.createBusinessLocationInfo(e.location)}try{await lF({appletId:a.appId,granted:i,scopeName:a.scope})}catch(t){let e=t instanceof Error?t.message:String(t);return null==b||b({category:"card",event:"simulator_granting_permission_report_failed",applet_id:a.appId,granted:i,scope:a.scope}),null==N||N(`权限授权状态上报失败:${e}`,!0),!1}if(n){try{await lY(JSON.stringify(n))}catch(t){let e=t instanceof Error?t.message:String(t);return null==b||b({category:"card",event:"simulator_granting_location_report_failed",scope:a.scope}),null==N||N(`位置信息上报失败:${e}`,!0),!1}null==b||b({category:"card",event:"simulator_granting_location_reported",scope:a.scope})}return sG(a.appId,a.scope,i?"granted":"denied"),null==b||b({category:"card",event:"simulator_granting_permission_reported",applet_id:a.appId,granted:i,scope:a.scope}),em(e,t,r,i),!0}),ev=cl((e,t,r,i)=>{em(t,r,i,!1)}),ey=(0,iD.useMemo)(()=>{var e,t;if(!J)return;let r=(e=J.key,t=J.itemIndex,`${e}:${t}`);return dI({appId:eo,baseAPIRegistry:null==o?void 0:o.apiRegistry,onGrantingCompleted:(e,t)=>em(J.card,J.key,J.itemIndex,!(null==t?void 0:t.noLogin)),onCustomLoginNavigate:el,onPrivacyLoginCardClose:()=>{Promise.resolve().then(()=>{Y.current.has(r)||em(J.card,J.key,J.itemIndex,!1)})},scanCodePresenter:null==o?void 0:o.scanCodePresenter,uiPresenter:null==o?void 0:o.uiPresenter})},[J,o,eo,em,el]),eb=cl((e,t,r)=>{null==g||g(e,t,r),null==h||h(t)}),ew=cl(async e=>!1!==(f?await f(e):E.navigateToPage(e.url,{routeMode:e.routeMode}))),e_=cl(async e=>{try{let t=r1(e,E.getState().manifest.appId);if(await ew(t))return}catch{}let t=function(e,t){try{let r=new URL(e,t);return"http:"===r.protocol||"https:"===r.protocol?r.toString():void 0}catch{return}}(e,window.location.href);t&&window.open(t,"_blank","noopener,noreferrer")}),eS=cl(async(e,t)=>{try{if(!q.tasks.includes(t))throw Error("任务资源已失效,请刷新后重试");let r=r1(e,E.getState().manifest.appId);if(!await ew(r)){let e=E.getState().status;throw e.error??Error(e.message||"页面导航失败")}return!0}catch(t){var r;console.error("[web-sdk-debugger] Task navigation failed",t);let e="任务跳转失败,请检查任务配置后重试";return null==o||null==(r=o.uiPresenter)||r.showToast({duration:3e3,icon:"warn",message:e,type:"warning"}),null==N||N(e,!0),!1}}),ex=cl(()=>{U(!1)}),eI=cl(async e=>{try{await q.removeTask(e)}catch(e){null==N||N(e.message,!0)}});function ek(e){let t=W.current;t&&t.previewUrl!==(null==e?void 0:e.previewUrl)&&URL.revokeObjectURL(t.previewUrl),W.current=e,R(e)}async function eC(e){var t,r;if(ei)return;try{n4(e)}catch(t){let e=t instanceof Error?t.message:String(t);null==o||null==(r=o.uiPresenter)||r.showToast({duration:3e3,message:e,type:"error"}),null==N||N(e,!0);return}let i={name:e.name,previewUrl:URL.createObjectURL(e),uploadStatus:"uploading"},n=++V.current,a=new AbortController;null==(t=H.current)||t.abort(),H.current=a,ek(i);try{let t=await E.uploadSimulatorImage(e,a.signal);if(n!==V.current)return;ek({...i,uploadStatus:"uploaded",uploadedImage:{...t,name:e.name,previewUrl:i.previewUrl}})}catch(e){n===V.current&&"AbortError"!==e.name&&(ek({...i,uploadStatus:"failed"}),null==N||N(e.message,!0))}finally{n===V.current&&(H.current=void 0)}}(0,iD.useEffect)(()=>{let e=B.current,t=F.current,r=x.messages.at(-1),i=x.messages.length>t&&(null==r?void 0:r.role)==="user";F.current=x.messages.length,e&&(G.current||i)&&(e.scrollTop=e.scrollHeight,G.current=!0)},[null==(t=x.error)?void 0:t.message,x.messages,x.streamStatus]);let eE=cl(async(e,t)=>{er.current.delete(pi(e)),null==v||v(),await (t?cS(E,t,e):E.sendSimulatorQuery(e))});return((0,iD.useEffect)(()=>()=>{var e;V.current+=1,null==(e=H.current)||e.abort(),W.current&&URL.revokeObjectURL(W.current.previewUrl)},[]),(0,iD.useEffect)(()=>{if((null==c?void 0:c.type)!=="submit_chat_query"||Q.current===c.commandId)return;Q.current=c.commandId;let e=E.getState();if("ready"!==e.status.type){null==m||m(c.commandId,{ok:!1,error:{code:"CHAT_NOT_READY",message:"Web SDK debugger is not ready to submit a chat query"}});return}if("streaming"===e.simulator.streamStatus){null==m||m(c.commandId,{ok:!1,error:{code:"CHAT_BUSY",message:"A chat query is already streaming"}});return}let t=e.simulator.messages.length;eE(c.query,c.commandId).then(()=>{var e,r;let i=E.getState().simulator,n=null==(e=i.messages.slice(t).reverse().find(e=>"assistant"===e.role&&!!e.requestId))?void 0:e.requestId;if("completed"!==i.streamStatus||!n)throw Error((null==(r=i.error)?void 0:r.message)??"Chat query did not complete with a request ID");null==m||m(c.commandId,{ok:!0,result:{completed:!0,query:c.query,requestId:n}})}).catch(e=>{null==m||m(c.commandId,{ok:!1,error:{code:"CHAT_SUBMIT_FAILED",message:e.message}})})},[c,m,eE,E]),(0,iD.useEffect)(()=>{L&&q.hasUnreadNotices&&q.markServiceNoticesRead()},[q.hasUnreadNotices,q.markServiceNoticesRead,L]),L)?(0,s.jsx)(cN,{notices:q.notices,onAction:e_,onBack:()=>O(!1),status:q.status}):(0,s.jsxs)("div",{className:"wsd-widget-chat-panel",children:[(0,s.jsxs)("header",{className:"wsd-doubao-simulator-chrome","aria-label":"豆包模拟器标题栏",children:[(0,s.jsx)(ck,{}),(0,s.jsxs)("div",{className:"wsd-doubao-title-bar",children:[(0,s.jsxs)("div",{className:"wsd-doubao-title-actions is-left",children:[(0,s.jsx)("button",{"aria-label":q.hasUnreadNotices?"打开菜单,有更新":"打开菜单",className:(0,rL.$)("wsd-doubao-icon-button",q.hasUnreadNotices&&"has-badge"),onClick:()=>O(!0),type:"button",children:(0,s.jsx)("span",{className:"wsd-doubao-menu-icon","aria-hidden":"true"})}),(0,s.jsx)("button",{"aria-label":"打开应用入口",className:"wsd-doubao-icon-button",type:"button",children:(0,s.jsx)("span",{className:"wsd-doubao-mask-icon is-circle4","aria-hidden":"true"})})]}),(0,s.jsxs)("div",{className:"wsd-doubao-title-stack",children:[(0,s.jsxs)("span",{className:"wsd-doubao-title",children:["豆包",(0,s.jsx)("span",{"aria-hidden":"true",children:"›"})]}),(0,s.jsx)("span",{className:"wsd-doubao-subtitle",children:"doubao.com"})]}),(0,s.jsxs)("div",{className:"wsd-doubao-title-actions",children:[(0,s.jsx)("button",{"aria-label":"语音通话",className:"wsd-doubao-icon-button",type:"button",children:(0,s.jsx)("span",{className:"wsd-doubao-mask-icon is-phone","aria-hidden":"true"})}),(0,s.jsx)("button",{"aria-label":"静音",className:"wsd-doubao-icon-button",type:"button",children:(0,s.jsx)("span",{className:"wsd-doubao-mask-icon is-mute","aria-hidden":"true"})})]})]})]}),S?(0,s.jsxs)("div",{className:(0,rL.$)("wsd-doubao-login-banner",!S.available&&"is-unavailable"),children:[(0,s.jsxs)("button",{className:"wsd-doubao-login-banner-open",onClick:S.onOpen,type:"button",children:[(0,s.jsx)("span",{children:S.available?"配置登录信息,模拟登录后场景":"无法模拟平台服务"}),S.available?(0,s.jsx)("span",{"aria-hidden":"true",className:"wsd-doubao-login-banner-arrow",children:"→"}):null]}),(0,s.jsx)("button",{"aria-label":"关闭登录信息配置提示",className:"wsd-doubao-login-banner-close",onClick:S.onClose,type:"button",children:"×"})]}):null,(0,s.jsxs)("div",{"aria-label":"对话预览",className:"wsd-widget-chat-messages",onScroll:function(e){let t=e.currentTarget;G.current=t.scrollHeight-t.scrollTop-t.clientHeight<=24},ref:B,children:[x.messages.length>0?x.messages.map(e=>(0,s.jsx)(pe,{packageManager:a,apiEnvironment:o,appId:l,fileSystemNamespace:d,cardReloadKey:u,grantingItemIndexes:Z,message:e,nativeModulesCallHandler:p,onGrantingCardOpen:eg,onGrantingPermissionDecision:ef,onGrantingCardSkip:ev,onInspectableCardTargetChange:g,onTraceEvent:b,onTraceSelect:w,onUpdateWidget:eu,runtimeConsoleTarget:_,selectedTraceId:I,widgetViewport:k,widgets:C},e.messageId)):null,x.error?(0,s.jsx)("div",{className:"wsd-widget-chat-error",children:x.error.message}):null]}),!n&&(0,s.jsx)("div",{className:"wsd-widget-chat-input-dock",children:(0,s.jsxs)("form",{className:(0,rL.$)("wsd-widget-chat-composer",M&&"has-image",j&&"is-dragging-image"),onDragEnter:function(e){!ei&&Array.from(e.dataTransfer.types).includes("Files")&&(e.preventDefault(),z.current+=1,P(!0))},onDragLeave:function(e){e.preventDefault(),z.current=Math.max(0,z.current-1),0===z.current&&P(!1)},onDragOver:function(e){!ei&&Array.from(e.dataTransfer.types).includes("Files")&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},onDrop:function(e){if(e.preventDefault(),z.current=0,P(!1),ei)return;let t=Array.from(e.dataTransfer.files),r=t.find(e=>e.type.startsWith("image/"))??t[0];r&&eC(r)},onSubmit:function(e){e.preventDefault();let t=T.trim(),r=null==M?void 0:M.uploadedImage;if((t||r)&&!en&&!ei){if(A(""),r){er.current.delete(pi(t,[r])),W.current=void 0,R(void 0),null==v||v(),E.sendSimulatorQuery(t,{images:[r]}).catch(e=>{null==N||N(e.message,!0)});return}M&&ek(),eE(t).catch(e=>{null==N||N(e.message,!0)})}},children:[M?(0,s.jsxs)("div",{className:(0,rL.$)("wsd-widget-chat-image-preview",`is-${M.uploadStatus}`),children:[(0,s.jsx)("img",{alt:M.name||"待发送图片",src:M.previewUrl}),"uploading"===M.uploadStatus?(0,s.jsx)("output",{"aria-label":"图片上传中",className:"wsd-widget-chat-image-status is-uploading",children:(0,s.jsx)("span",{"aria-hidden":"true",className:"wsd-widget-chat-image-spinner"})}):null,"failed"===M.uploadStatus?(0,s.jsxs)("span",{className:"wsd-widget-chat-image-status is-failed",role:"alert",children:[(0,s.jsx)("strong",{children:"!"}),(0,s.jsx)("span",{children:"上传失败"})]}):null,(0,s.jsx)("button",{"aria-label":"移除图片",className:"wsd-widget-chat-image-remove",onClick:function(){var e;V.current+=1,null==(e=H.current)||e.abort(),H.current=void 0,ek()},type:"button",children:"×"})]}):null,(0,s.jsx)("input",{"aria-label":"输入消息",className:"wsd-widget-chat-input",disabled:ei,onChange:e=>A(e.currentTarget.value),onPaste:function(e){let t=Array.from(e.clipboardData.files).find(e=>e.type.startsWith("image/"));t&&eC(t)},placeholder:"发消息或粘贴图片...",type:"text",value:T}),(0,s.jsx)("button",{"aria-label":ei?"取消生成":"发送消息",className:"wsd-widget-chat-send",disabled:!ei&&!ea,onClick:function(){ei&&E.cancelSimulatorQuery()},type:ei?"button":"submit",children:ei?(0,s.jsx)("span",{"aria-hidden":"true",className:"wsd-doubao-cancel-icon"}):(0,s.jsx)("span",{"aria-hidden":"true",className:"wsd-doubao-send-icon"})})]})}),$&&!D?(0,s.jsx)("button",{"aria-label":"展开进行中的任务",className:"wsd-sandbox-task-collapsed-entry",onClick:()=>{q.markTasksRead(),U(!0)},type:"button",children:(0,s.jsx)("span",{"aria-hidden":"true"})}):null,J?(0,s.jsxs)("div",{className:"wsd-simulator-overlay-layer wsd-widget-granting-sheet-layer",children:[(0,s.jsx)("div",{className:"wsd-simulator-overlay-backdrop wsd-widget-granting-sheet-backdrop"}),(0,s.jsx)("div",{className:"wsd-widget-granting-sheet",children:(0,s.jsx)(c7,{packageManager:a,apiEnvironment:ey,appId:eo,fileSystemNamespace:d,card:J.card,grantingItemIndex:J.itemIndex,inspectableTargetKey:J.key,nativeModulesCallHandler:p,onInspectableTargetChange:eb,onTraceEvent:b,runtimeConsoleTarget:_,widgets:C})})]}):null,D?(0,s.jsx)(cM,{onAction:eS,onClose:ex,onRemove:eI,onRemoveAction:e_,removingTaskIds:q.removingTaskIds,tasks:q.tasks}):null]})}var ps=e=>(0,s.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",width:13,height:13,fill:"none",viewBox:"0 0 13 13",...e,children:(0,s.jsx)("path",{fill:"#999",d:"M6.346 0a6.33 6.33 0 0 1 4.763 2.153V.75a.667.667 0 0 1 1.334 0v2.813a1 1 0 0 1-1 1H8.63a.667.667 0 0 1 0-1.334h1.639a4.997 4.997 0 0 0-3.923-1.896 5.012 5.012 0 1 0 4.517 7.188.667.667 0 0 1 1.2.58A6.346 6.346 0 1 1 6.347 0"})}),po=r(35668),pl=r(27860),pd=r(26661),pu=e=>(0,s.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",width:12,height:15,fill:"none",viewBox:"0 0 12 15",...e,children:(0,s.jsx)("path",{fill:"#999",d:"M6.667 0c1.866 0 2.8 0 3.513.363l.116.062c.574.322 1.041.807 1.34 1.395l.065.136C12 2.653 12 3.583 12 5.333v4l-.006 1.237c-.017 1.083-.085 1.742-.357 2.276a3.34 3.34 0 0 1-1.457 1.457l-.136.064c-.511.22-1.148.278-2.141.294l-1.236.006H5.333l-1.236-.006c-.993-.016-1.63-.074-2.14-.294l-.137-.064a3.34 3.34 0 0 1-1.395-1.34l-.062-.117c-.272-.534-.34-1.193-.357-2.276L0 9.333v-4c0-1.866 0-2.8.363-3.513.32-.627.83-1.137 1.457-1.457C2.533 0 3.467 0 5.333 0zM5.333 1.333c-.955 0-1.591.001-2.08.041-.474.039-.69.108-.828.177a2 2 0 0 0-.874.874c-.07.137-.138.354-.177.828-.04.489-.04 1.125-.04 2.08v4c0 .956 0 1.592.04 2.081.039.473.108.69.177.828a2 2 0 0 0 .874.873c.137.07.354.139.828.177.489.04 1.125.041 2.08.041h1.334c.955 0 1.591 0 2.08-.04.474-.04.69-.108.828-.178a2 2 0 0 0 .874-.873c.07-.138.138-.355.177-.828.04-.489.04-1.125.04-2.08v-4c0-.956 0-1.592-.04-2.081-.039-.474-.107-.69-.177-.828a2 2 0 0 0-.874-.874c-.137-.07-.354-.138-.828-.177-.489-.04-1.125-.04-2.08-.04zM8 2.667A.667.667 0 1 1 8 4H4a.667.667 0 0 1 0-1.333z"})});let pc={"not determined":"尚未决定",full:"已授权",authorized:"已授权",denied:"已拒绝",restricted:"受系统限制",limited:"有限授权","add only":"仅允许添加","read only":"仅允许读取","write only":"仅允许写入",provisional:"临时授权",partial:"部分授权","foreground precise":"前台精确定位","foreground approximate":"前台模糊定位","background precise":"后台精确定位","background approximate":"后台模糊定位"},pp={none:"未中断",temporary:"临时中断",forced:"强制中断"},ph={high:"高精度",medium:"中精度",low:"低精度",unreliable:"读数不可靠","no-contact":"无法测量(无接触)"},pm={wifi:"Wi-Fi","2g":"2G","3g":"3G","4g":"4G","5g":"5G",unknown:"已连接(类型未知)",none:"断网"},pg={request:"网络请求",upload:"文件上传",download:"文件下载",socket:"WebSocket"};function pf(){let e=(0,iD.useSyncExternalStore)(sI.subscribe,sI.getSnapshot),t=(0,iD.useSyncExternalStore)(sP.subscribe,sP.getSnapshot),[r,i]=(0,iD.useState)(""),n=cl(async e=>{try{await sP.control(e),i("")}catch(e){i(e instanceof Error?e.message:String(e))}});return(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"背景音频播控"}),(0,s.jsx)("p",{children:"应用插件设置资源后,可模拟系统播控。上一首和下一首只触发事件,由应用插件切换资源。"}),(0,s.jsx)("p",{children:"播放控制即时生效,状态只保留在当前调试会话中。关闭浏览器或结束应用调试时停止播放。"}),(0,s.jsx)("div",{className:"wsd-virtual-hardware-actions",children:[["play","播放"],["pause","暂停"],["stop","停止"],["prev","上一首"],["next","下一首"]].map(e=>{let[r,i]=e;return(0,s.jsx)("button",{type:"button",disabled:!t.src,onClick:()=>n(r),children:i},r)})}),(0,s.jsxs)("label",{className:"wsd-virtual-hardware-range",children:[(0,s.jsxs)("span",{children:["场景音量 ",(0,s.jsxs)("output",{children:[Math.round(100*e.volumeFactor),"%"]})]}),(0,s.jsx)("input",{type:"range","aria-label":"背景音频场景音量",min:0,max:1,step:.01,value:e.volumeFactor,onChange:e=>sI.setVolumeFactor(e.currentTarget.valueAsNumber)})]}),(0,s.jsx)("div",{className:"wsd-virtual-hardware-actions",children:[["temporary","背景音频临时中断"],["forced","背景音频强制中断"],["none","结束背景音频中断"]].map(e=>{let[t,r]=e;return(0,s.jsx)("button",{type:"button",onClick:()=>sI.setInterruption(t),children:r},t)})}),(0,s.jsxs)("p",{role:"status",children:["背景音频中断状态:",pp[e.interruption]]}),(0,s.jsx)("p",{children:"临时中断结束后恢复播放,强制中断保持暂停;主动暂停、停止、切换音频资源或退出应用后,不再自动恢复播放。"}),r?(0,s.jsx)("p",{role:"alert",children:r}):null,(0,s.jsx)("pre",{"aria-label":"背景音频状态",children:JSON.stringify(t,null,2)})]})}function pv(){let{interruption:e,volumeFactor:t}=(0,iD.useSyncExternalStore)(sx.subscribe,sx.getSnapshot);return(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"应用内音频中断"}),(0,s.jsxs)("label",{className:"wsd-virtual-hardware-range",children:[(0,s.jsxs)("span",{children:["场景音量 ",(0,s.jsxs)("output",{children:[Math.round(100*t),"%"]})]}),(0,s.jsx)("input",{type:"range","aria-label":"应用内音频场景音量",min:0,max:1,step:.01,value:t,onChange:e=>sx.setVolumeFactor(e.currentTarget.valueAsNumber)})]}),(0,s.jsx)("p",{children:"实际播放音量为应用设置的音量乘以此处的百分比,不改变播放状态。"}),(0,s.jsxs)("div",{className:"wsd-virtual-hardware-actions",children:[(0,s.jsx)("button",{type:"button",onClick:()=>sx.setInterruption("temporary"),children:"临时中断"}),(0,s.jsx)("button",{type:"button",onClick:()=>sx.setInterruption("forced"),children:"强制中断"}),(0,s.jsx)("button",{type:"button",onClick:()=>sx.setInterruption("none"),children:"结束中断"})]}),(0,s.jsxs)("p",{role:"status",children:["应用内音频中断状态:",pp[e]]}),(0,s.jsx)("p",{children:"临时中断结束后恢复播放;强制中断保持暂停。应用插件主动暂停、停止或销毁的实例不自动恢复。"}),(0,s.jsx)("p",{children:"只影响模拟器中的应用音频,不改变电脑的音频播放。中断期间调用 play 返回 -2009。"})]})}function py(e){let{namespace:t}=e,[r,i]=(0,iD.useState)(),[n,a]=(0,iD.useState)(""),[o,l]=(0,iD.useState)(""),[d,u]=(0,iD.useState)(!1),[c,p]=(0,iD.useState)(),[h,m]=(0,iD.useState)(""),g=(0,iD.useRef)(null),[f,v]=(0,iD.useState)("temp");(0,iD.useEffect)(()=>{if(!t)return;let e=!0,r=ef(t),n=ew(r=>{e&&r.fileSystemNamespace===t&&i(ey(t))});return r.ready.then(()=>{e&&i(ey(t))}).catch(t=>{e&&a(String(t))}),()=>{e=!1,n(),r.release()}},[t]);let y=cl(async(e,t)=>{u(!0),a(""),l("");try{await e(),l(t)}catch(e){a(e instanceof Error?e.message:String(e))}finally{u(!1)}}),b=Object.values((null==r?void 0:r.storageSnapshot)??{}),w=Object.entries((null==r?void 0:r.fileSystemSnapshot.entries)??{}).filter(e=>{let[,t]=e;return"file"===t.type}),_=e=>{let t=w.filter(t=>{let[r]=t;return r.startsWith(e)}),r=t.reduce((e,t)=>{let[,r]=t;return e+("file"===r.type?3*r.data.length/4-(r.data.endsWith("==")?2:+!!r.data.endsWith("=")):0)},0);return`${t.length} 个文件 \xb7 ${(r/1024).toFixed(1)} KiB`};return(0,s.jsxs)("fieldset",{"aria-label":"存储与文件",disabled:d||!r,children:[(0,s.jsx)("p",{children:"管理当前应用插件的数据。Storage、持久文件和临时文件按应用隔离,切换应用后仍会保留。"}),(0,s.jsxs)("dl",{className:"wsd-storage-summary",children:[(0,s.jsx)("dt",{children:"Storage"}),(0,s.jsxs)("dd",{children:[b.length," 个键 ·"," ",(b.reduce((e,t)=>e+new TextEncoder().encode(t).byteLength,0)/1024).toFixed(1)," ","KiB"]}),(0,s.jsx)("dt",{children:"持久文件"}),(0,s.jsx)("dd",{children:_("/user/")}),(0,s.jsx)("dt",{children:"临时文件"}),(0,s.jsx)("dd",{children:_("/temp/")})]}),(0,s.jsx)("button",{type:"button",onClick:()=>void y(async()=>{var e;let r,i;e=await ev(t,()=>({format:"doubao-web-storage",version:1,...ey(t)})),r=URL.createObjectURL(new Blob([JSON.stringify(e,null,2)],{type:"application/json"})),(i=document.createElement("a")).href=r,i.download="app-storage-and-files.json",i.click(),setTimeout(()=>URL.revokeObjectURL(r),1e3)},"已导出当前应用的存储与文件"),children:"导出存储与文件"}),(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"导入备份"}),(0,s.jsx)("input",{ref:g,hidden:!0,"aria-label":"导入存储与文件",type:"file",accept:".json,application/json",onChange:e=>{var t;let r=null==(t=e.currentTarget.files)?void 0:t[0];e.currentTarget.value="",r&&(m(r.name),p(void 0),y(async()=>{let e;try{e=JSON.parse(await r.text())}catch(e){throw Error("无法读取备份,请选择模拟器导出的存储与文件备份",{cause:e})}eC(e),p(e)},"备份格式校验通过,确认后导入"))}}),(0,s.jsxs)("div",{className:"wsd-storage-import-actions",children:[(0,s.jsx)("button",{type:"button",onClick:()=>{var e;return null==(e=g.current)?void 0:e.click()},children:"选择文件"}),(0,s.jsx)("button",{type:"button",disabled:!c,onClick:()=>void y(async()=>{await (eC(c),ev(t,()=>ex(t,{clearStorage:!0,storageChanges:c.storageSnapshot,fileSystemChanges:eS(eb(t).entries,c.fileSystemSnapshot.entries)}))),p(void 0),m("")},"已导入存储与文件"),children:"确认导入并覆盖"})]}),(0,s.jsx)("p",{className:"wsd-storage-import-filename",children:h||"未选择文件"}),(0,s.jsx)("p",{children:"备份包含 Storage、持久文件和临时文件。导入会覆盖当前应用的数据;其他应用不受影响。"})]}),(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"清理数据"}),(0,s.jsxs)("label",{className:"wsd-virtual-hardware-row",children:["数据范围",(0,s.jsxs)("select",{value:f,onChange:e=>v(e.currentTarget.value),children:[(0,s.jsx)("option",{value:"temp",children:"临时文件"}),(0,s.jsx)("option",{value:"storage",children:"Storage"}),(0,s.jsx)("option",{value:"all",children:"全部存储与文件"})]})]}),(0,s.jsx)("button",{type:"button",onClick:()=>{window.confirm("确认清理当前应用所选的数据?此操作无法撤销。")&&y(()=>ev(t,()=>{let e=eb(t).entries,r="all"===f?ec().entries:Object.fromEntries(Object.entries(e).filter(e=>{let[t]=e;return!t.startsWith("/temp/")}));return ex(t,{clearStorage:"temp"!==f,fileSystemChanges:"storage"===f?void 0:eS(e,r)})}),"已清理所选数据")},children:"清理所选数据"})]}),n?(0,s.jsx)("p",{role:"alert",children:n}):null,o?(0,s.jsx)("p",{role:"status",children:o}):null,t?null:(0,s.jsx)("p",{role:"alert",children:"当前应用未提供存储作用域"})]})}function pb(e){let{label:t,value:r,example:i,description:n,exampleActionLabel:a="填入示例",onChange:o}=e,l=(0,iD.useId)(),d=(0,iD.useRef)(null),[u,c]=(0,iD.useState)(()=>JSON.stringify(r,null,2)),[p,h]=(0,iD.useState)(""),m=JSON.stringify(i,null,2),g=cl(e=>{var t;c(e);let r="";try{o(JSON.parse(e))}catch(e){r=e instanceof SyntaxError?"JSON 格式错误,请检查双引号、逗号和括号":e instanceof Error?e.message:String(e)}null==(t=d.current)||t.setCustomValidity(r),h(r)});return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("label",{className:"wsd-virtual-hardware-json",children:[t,(0,s.jsx)("textarea",{ref:d,"aria-label":t,"aria-invalid":!!p,"aria-describedby":p?`${l}-format ${l}-error`:`${l}-format`,required:!0,spellCheck:!1,placeholder:m,value:u,onChange:e=>g(e.currentTarget.value)})]}),p?(0,s.jsx)("p",{id:`${l}-error`,role:"alert",children:p}):null,(0,s.jsx)("p",{id:`${l}-format`,children:n}),(0,s.jsxs)("details",{className:"wsd-virtual-json-example",children:[(0,s.jsx)("summary",{children:"查看示例"}),(0,s.jsx)("pre",{"aria-label":`${t}示例`,children:m})]}),(0,s.jsx)("button",{type:"button",onClick:()=>g(m),children:a})]})}function pw(e){let{label:t,onClick:r}=e;return(0,s.jsx)("button",{"aria-label":t,className:"wsd-virtual-hardware-link",onClick:r,title:t,type:"button",children:(0,s.jsx)("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round",children:(0,s.jsx)("path",{d:"m5.5 3 5 5-5 5"})})})}function p_(e){let{beacon:t,onChange:r,locationAuthorization:i,onOpenAuthorization:n}=e;return(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"iBeacon 广播"}),(0,s.jsxs)("div",{className:"wsd-virtual-permission-row",children:[(0,s.jsx)("span",{children:"定位授权"}),(0,s.jsx)("span",{children:pc[i]}),(0,s.jsx)(pw,{label:"前往定位授权设置",onClick:n})]}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:t.rangingAvailable,onChange:e=>r({...t,rangingAvailable:e.currentTarget.checked})}),"Beacon 测距可用"]}),(0,s.jsx)(pb,{label:"虚拟 Beacon 广播(JSON)",value:t.beacons,example:iF.beacons,description:"输入广播数组,必填 uuid(完整 UUID)、major/minor(0–65535 的整数)、proximity(0–3 的整数)、accuracy(不小于 -1 的米数)、rssi(-127–20 的整数 dBm)。UUID/major/minor 组合不可重复。",onChange:e=>{let i={...t,beacons:e};i$(i),r(i)}}),(0,s.jsx)("p",{children:"与上方设备共用蓝牙开关。停止搜索保留已发现缓存,重新开始清空缓存。"})]})}function pS(e){let{bluetooth:t,onChange:r,authorization:i,onOpenAuthorization:n}=e;return(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"蓝牙设备"}),[["available","蓝牙硬件可用"],["enabled","蓝牙开关"]].map(e=>{let[i,n]=e;return(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:t[i],onChange:e=>r({...t,[i]:e.currentTarget.checked})}),n]},i)}),(0,s.jsxs)("div",{className:"wsd-virtual-permission-row",children:[(0,s.jsx)("span",{children:"蓝牙授权"}),(0,s.jsx)("span",{children:pc[i]}),(0,s.jsx)(pw,{label:"前往蓝牙授权设置",onClick:n})]}),(0,s.jsx)(pb,{label:"虚拟蓝牙设备(JSON)",value:t.devices,example:iG.devices,exampleActionLabel:"恢复默认设备",description:"输入设备数组,必填 deviceId(非空字符串)、name(字符串)、RSSI(-127–20 的整数 dBm)、connectable(布尔值)、advertisServiceUUIDs(UUID 数组)。deviceId 不可重复;广播、特征值和 PIN 使用 Base64。",onChange:e=>{let i={...t,devices:e};iH(i),r(i)}}),(0,s.jsx)("p",{children:"默认 GATT 服务 FFF0 / 特征 FFF1 支持读写与通知;PIN 为 MDAwMDAw(000000),最大 MTU 247。 connectionDelayMs 为 0–60000 的整数毫秒,可模拟连接延迟与超时;maxMTU 为 23–517 的整数。"})]})}async function px(e,t,r){try{if(!navigator.clipboard)throw Error("Clipboard API is unavailable");return await navigator.clipboard.writeText(t),null==r||r(`${e} copied`),!0}catch(t){return null==r||r(`${e}: ${t.message}`,!0),!1}}function pI(e){let{settings:t,onChange:r,authorization:i,onOpenAuthorization:n}=e,[a,o]=(0,iD.useState)(t.timeZone),[l,d]=(0,iD.useState)(""),u=(0,iD.useSyncExternalStore)(sY.subscribe,sY.getEvents),[c,p]=(0,iD.useState)("structured"),[h,m]=(0,iD.useState)(""),[g,f]=(0,iD.useState)(!1),v=JSON.stringify(u,null,2),y=cl(async()=>{let e=await px("虚拟日历事件 JSON",v);m(e?v:""),f(!e)});return(0,s.jsxs)("fieldset",{"aria-label":"日历",children:[(0,s.jsxs)("div",{className:"wsd-virtual-permission-row",children:[(0,s.jsx)("span",{children:"日历授权"}),(0,s.jsx)("span",{children:pc[i]}),(0,s.jsx)(pw,{label:"前往日历授权设置",onClick:n})]}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:t.accountAvailable,onChange:e=>r({...t,accountAvailable:e.currentTarget.checked})}),"有可写日历账户"]}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:t.writeSucceeds,onChange:e=>r({...t,writeSucceeds:e.currentTarget.checked})}),"日历写入成功"]}),(0,s.jsx)("p",{children:"系统日历写入授权在“系统设置与授权”中配置,应用权限使用本地授权弹层。"}),(0,s.jsxs)("label",{className:"wsd-virtual-hardware-row",children:["日历时区",(0,s.jsx)("input",{type:"text",required:!0,value:a,onChange:e=>{let i=e.currentTarget.value;o(i);try{sX({...t,timeZone:i}),e.currentTarget.setCustomValidity(""),d(""),r({...t,timeZone:i})}catch{let t="请输入有效的 IANA 时区,例如 Asia/Shanghai";e.currentTarget.setCustomValidity(t),d(t)}}})]}),l?(0,s.jsx)("p",{role:"alert",children:l}):null,(0,s.jsx)("p",{children:"事件保存在当前浏览器,不写入电脑日历。时间、重复周期、结束时间和提醒参数可在下方查看。"}),(0,s.jsxs)("p",{role:"status",children:["虚拟日历事件:",u.length," 条"]}),(0,s.jsxs)("div",{className:"wsd-calendar-events-toolbar",children:[(0,s.jsxs)("div",{role:"group","aria-label":"日历事件显示方式",children:[(0,s.jsx)("button",{type:"button","aria-pressed":"structured"===c,onClick:()=>p("structured"),children:"结构化"}),(0,s.jsx)("button",{type:"button","aria-pressed":"json"===c,onClick:()=>p("json"),children:"JSON"})]}),(0,s.jsx)("button",{type:"button",className:"wsd-calendar-events-copy","aria-label":"复制日历事件 JSON",onClick:()=>void y(),children:h===v?"已复制":"复制 JSON"})]}),g?(0,s.jsx)("p",{role:"alert",children:"复制失败,请切换到 JSON 视图后手动复制。"}):null,"json"===c?(0,s.jsx)("textarea",{className:"wsd-calendar-events-json","aria-label":"虚拟日历事件 JSON",readOnly:!0,value:v}):u.length>0?(0,s.jsx)("ul",{className:"wsd-calendar-events-list","aria-label":"虚拟日历事件",children:u.map(e=>(0,s.jsx)(pC,{event:e},e.id))}):(0,s.jsx)("p",{children:"暂无日历事件"}),(0,s.jsx)("div",{className:"wsd-virtual-hardware-actions",children:(0,s.jsx)("button",{type:"button",disabled:0===u.length,onClick:()=>sY.clear(),children:"清空虚拟日历"})})]})}let pk={day:"每天",week:"每周",month:"每月",year:"每年"};function pC(e){let{event:t}=e,r=new Intl.DateTimeFormat("zh-CN",{timeZone:t.timeZone,dateStyle:"medium",timeStyle:t.allDay?void 0:"short",hour12:!1}).format,i=t.alarmOffset%60==0?`${t.alarmOffset/60} 分钟`:`${t.alarmOffset} 秒`,n=[["开始时间",r(1e3*t.startTime)],["结束时间",r(1e3*t.endTime)],["时区",`${t.allDay?"全天 · ":""}${t.timeZone}`],["地点",t.location],["重复",t.repeatInterval?`${pk[t.repeatInterval]},${void 0===t.repeatEndTime?"无截止日期":`截至 ${r(1e3*t.repeatEndTime)}`}`:"不重复"],["提醒",t.alarm?0===t.alarmOffset?"开始时提醒":`提前 ${i}`:"不提醒"],["备注",t.description]];return(0,s.jsxs)("li",{children:[(0,s.jsx)("strong",{children:t.title}),(0,s.jsx)("dl",{children:n.map(e=>{let[t,r]=e;return r?(0,s.jsxs)(iD.Fragment,{children:[(0,s.jsx)("dt",{children:t}),(0,s.jsx)("dd",{children:r})]},t):null})})]})}let pE=[["accelerometer","加速度计","m/s²"],["gyroscope","陀螺仪","rad/s"]],pN={ArrowLeft:[-20,0],ArrowRight:[20,0],ArrowUp:[0,-20],ArrowDown:[0,20]},pT={x:0,y:0,z:0,rx:0,ry:0,rz:0,sample:nr},pA=(e,t)=>Math.max(-t,Math.min(t,e)),pM=Math.PI/4;function pR(e){let{availability:t,onAvailabilityChange:r}=e,i=(0,iD.useRef)(null),n=(0,iD.useRef)(),a=(0,iD.useRef)(),o=(0,iD.useRef)({x:0,y:0,z:0,vx:0,vy:0,vz:0,ax:0,ay:0,az:0,rx:0,ry:0,rz:0,targetX:0,targetY:0,targetZ:0,targetRz:0,maxX:140,maxY:36,time:0}),[l,d]=(0,iD.useState)(pT),[u,c]=(0,iD.useState)(!1),p=cl(e=>{let t=o.current,r=Math.max(1/240,Math.min((e-t.time)/1e3,.05)),i=1-Math.exp(-18*r),a=t.x+(t.targetX-t.x)*i,s=t.y+(t.targetY-t.y)*i,l=t.z+(t.targetZ-t.z)*i,u=t.rz+(t.targetRz-t.rz)*i,c=(a-t.x)/r*.002,h=-(.002*((s-t.y)/r)),m=(l-t.z)/r*.002,g=t.ax+(pA((c-t.vx)/r,40)-t.ax)*i,f=t.ay+(pA((h-t.vy)/r,40)-t.ay)*i,v=t.az+(pA((m-t.vz)/r,40)-t.az)*i,y=.05>Math.abs(a-t.targetX)&&.05>Math.abs(s-t.targetY)&&.05>Math.abs(l-t.targetZ)&&5e-4>Math.abs(u-t.targetRz)&&.005>Math.hypot(c,h,m)&&.05>Math.hypot(g,f,v);y&&(a=t.targetX,s=t.targetY,l=t.targetZ,u=t.targetRz,c=h=m=g=f=v=0);let b=pA(-(.5*h),.65),w=pA(.5*c,.65),_=nr.accelerometer.z,S={accelerometer:{x:g-_*Math.sin(w),y:f+_*Math.sin(b)*Math.cos(w),z:v+_*Math.cos(b)*Math.cos(w)},gyroscope:y?nr.gyroscope:{x:pA((b-t.rx)/r,12),y:pA((w-t.ry)/r,12),z:pA((u-t.rz)/r,12)}};Object.assign(t,{x:a,y:s,z:l,vx:c,vy:h,vz:m,ax:g,ay:f,az:v,rx:b,ry:w,rz:u,time:e}),nL.setMotionSample(S),d({x:a,y:s,z:l,rx:b,ry:w,rz:u,sample:S}),n.current=y?void 0:window.requestAnimationFrame(p)}),h=()=>{void 0===n.current&&(o.current.time=performance.now(),n.current=window.requestAnimationFrame(p))},m=()=>{let e=i.current;e&&(o.current.maxX=Math.max(1,e.clientWidth/2-38),o.current.maxY=Math.max(1,e.clientHeight/2-54))},g=cl(()=>{window.cancelAnimationFrame(n.current??0),n.current=void 0,a.current=void 0,Object.assign(o.current,{x:0,y:0,z:0,vx:0,vy:0,vz:0,ax:0,ay:0,az:0,rx:0,ry:0,rz:0,targetX:0,targetY:0,targetZ:0,targetRz:0}),nL.setMotionSample(nr),d(pT),c(!1)});(0,iD.useEffect)(()=>{let e=()=>{document.hidden&&g()};return window.addEventListener("blur",g),document.addEventListener("visibilitychange",e),()=>{window.removeEventListener("blur",g),document.removeEventListener("visibilitychange",e),window.cancelAnimationFrame(n.current??0),nL.setMotionSample(nr)}},[g]);let f=cl(e=>{0!==e.button||a.current||(e.preventDefault(),e.currentTarget.focus({preventScroll:!0}),e.currentTarget.setPointerCapture(e.pointerId),m(),a.current={id:e.pointerId,originX:e.clientX+(e.shiftKey?o.current.rz/.005:-o.current.x),originY:e.clientY+(e.shiftKey?o.current.z:-o.current.y),depth:e.shiftKey},o.current.targetX=o.current.x,o.current.targetY=o.current.y,o.current.targetZ=o.current.z,o.current.targetRz=o.current.rz,c(!0),h())}),v=cl(e=>{let t=a.current;(null==t?void 0:t.id)===e.pointerId&&(t.depth?(o.current.targetZ=pA(t.originY-e.clientY,60),o.current.targetRz=pA((t.originX-e.clientX)*.005,pM)):(o.current.targetX=pA(e.clientX-t.originX,o.current.maxX),o.current.targetY=pA(e.clientY-t.originY,o.current.maxY)),h())}),y=()=>{o.current.targetX=o.current.targetY=o.current.targetZ=o.current.targetRz=0,c(!1),h()},b=cl(e=>{var t;(null==(t=a.current)?void 0:t.id)===e.pointerId&&(a.current=void 0,y())}),w=cl(e=>{let t=pN[e.key];t&&!a.current&&(e.preventDefault(),m(),e.shiftKey?(o.current.targetZ=pA(o.current.targetZ-t[1],60),o.current.targetRz=pA(o.current.targetRz-.005*t[0],pM)):(o.current.targetX=pA(o.current.targetX+t[0],o.current.maxX),o.current.targetY=pA(o.current.targetY+t[1],o.current.maxY)),c(!0),h())}),_=cl(e=>{e.key in pN&&!a.current&&y()});return(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"运动模拟"}),(0,s.jsx)("div",{className:"wsd-motion-stage",ref:i,children:(0,s.jsx)("button",{type:"button","aria-label":"拖动手机模拟运动","aria-describedby":"wsd-motion-help",className:(0,rL.$)("wsd-motion-phone",u&&"is-dragging"),style:{transform:`translate3d(${l.x}px, ${l.y}px, ${l.z}px) rotateZ(${-l.rz}rad) rotateY(${l.ry}rad) rotateX(${-l.rx}rad)`},onPointerDown:f,onPointerMove:v,onPointerUp:b,onPointerCancel:b,onLostPointerCapture:b,onKeyDown:w,onKeyUp:_,onBlur:g,children:"拖动"})}),(0,s.jsx)("p",{id:"wsd-motion-help",children:"按住手机拖动,快速往返可模拟摇动。按住 Shift 时,上下拖动模拟前后移动,左右拖动模拟绕 Z 轴旋转;方向键支持相同操作。停住后运动加速度和角速度归零,Z 轴保留重力,松开后自动复位。"}),pE.map(e=>{let[i,n,a]=e;return(0,s.jsxs)("fieldset",{children:[(0,s.jsxs)("legend",{children:[n,"(",a,")"]}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:t[i],onChange:e=>r({...t,[i]:e.currentTarget.checked})}),n,"可用"]}),(0,s.jsx)("dl",{className:"wsd-motion-readings",children:["x","y","z"].map(e=>(0,s.jsxs)("div",{children:[(0,s.jsx)("dt",{children:e.toUpperCase()}),(0,s.jsx)("dd",{children:(0,s.jsx)("output",{"aria-live":"off","aria-label":`${n} ${e.toUpperCase()}(${a})`,children:.005>Math.abs(l.sample[i][e])?"0.00":l.sample[i][e].toFixed(2)})})]},e))})]},i)})]})}function pj(e){let{network:t,onChange:r}=e,i=t.domainPolicy??iZ;return(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"网络状态"}),(0,s.jsxs)("label",{className:"wsd-virtual-hardware-row",children:["网络制式",(0,s.jsx)("select",{value:t.networkType,onChange:e=>r({...t,networkType:e.currentTarget.value}),children:iJ.map(e=>(0,s.jsx)("option",{value:e,children:pm[e]},e))})]}),(0,s.jsx)("p",{children:"在“网络制式”中选择“断网”后,会阻止联网 API 调用,并中断网络请求、文件上传下载、WebSocket 连接和网络媒体的加载或播放;恢复联网后需重新发起相关操作。联网时仍通过本机网络访问服务,所选制式与信号强度不会限制实际带宽。"}),(0,s.jsxs)("label",{className:"wsd-virtual-hardware-row",children:["Wi-Fi 信号(dBm)",(0,s.jsx)("input",{type:"number",min:-126,max:-1,step:1,required:!0,disabled:"wifi"!==t.networkType,value:Number.isFinite(t.signalStrength)?t.signalStrength:"",onChange:e=>r({...t,signalStrength:e.currentTarget.valueAsNumber})})]}),(0,s.jsx)("p",{children:"Wi-Fi 信号强度仅在模拟 Android 设备时返回,≤ -80 dBm 时标记为弱网;模拟 iOS 设备时不返回信号强度和弱网标记。下方可配置 Wi-Fi 列表与连接。"}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:t.hasSystemProxy,onChange:e=>r({...t,hasSystemProxy:e.currentTarget.checked})}),"模拟检测到系统代理"]}),(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"网络白名单"}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:!i.enabled,onChange:e=>r({...t,domainPolicy:{...i,enabled:!e.currentTarget.checked}})}),"绕过网络白名单校验"]}),i.enabled?(0,s.jsxs)(s.Fragment,{children:[iK.map(e=>(0,s.jsxs)("label",{className:"wsd-virtual-domain-list",children:[pg[e],"域名白名单",(0,s.jsx)("textarea",{value:i[e],placeholder:"socket"===e?"wss://example.com":"https://example.com",onChange:n=>r({...t,domainPolicy:{...i,[e]:n.currentTarget.value}})})]},e)),(0,s.jsx)("p",{children:"每行或逗号分隔一个地址,留空则拒绝该类联网调用;网络请求和文件上传下载使用 HTTPS,WebSocket 使用 WSS。域名和显式端口精确匹配, 不匹配子域名或通配符,路径不参与匹配。修改只影响新调用。"})]}):(0,s.jsx)("p",{children:"完全绕过网络请求、文件上传下载和 WebSocket 的域名白名单校验;取消勾选后可分别配置。"})]})]})}let pP=[["camera","摄像头授权",i2],["contacts","联系人授权",i2],["microphone","麦克风授权",i2],["album","相册授权",i3],["locationAuthorization","定位授权",i9],["bluetoothAuthorization","蓝牙授权",i8],["phoneCalendar","日历授权",i4],["notification","通知授权",i5],["notificationAlert","通知提醒",i6],["notificationBadge","通知角标",i6],["notificationSound","通知声音",i6]],pL={locationAuthorization:"location",bluetoothAuthorization:"bluetooth",phoneCalendar:"calendar"};function pO(e){let{system:t,onChange:r,authorizationFallbacks:i,onHardwareChange:n}=e,a=t.healthData,o={...t,...i};return(0,s.jsxs)("fieldset",{"aria-label":"系统设置与授权",children:[(0,s.jsxs)("label",{className:"wsd-virtual-hardware-row",children:[(0,s.jsx)("span",{children:"系统主题"}),(0,s.jsxs)("select",{value:t.theme??"",onChange:e=>r({...t,theme:e.currentTarget.value||void 0}),children:[(0,s.jsx)("option",{value:"",children:"跟随浏览器"}),(0,s.jsx)("option",{value:"light",children:"浅色"}),(0,s.jsx)("option",{value:"dark",children:"深色"})]})]}),pP.map(e=>{let[i,a,l]=e,d=pL[i];return(0,s.jsxs)("div",{className:"wsd-virtual-permission-row",children:[(0,s.jsx)("label",{htmlFor:`wsd-system-permission-${i}`,children:a}),(0,s.jsx)("select",{id:`wsd-system-permission-${i}`,value:o[i]??"not determined",onChange:e=>r({...t,[i]:e.currentTarget.value}),children:l.map(e=>(0,s.jsx)("option",{value:e,children:pc[e]},e))}),d?(0,s.jsx)(pw,{label:`前往${a.replace("授权","")}设置`,onClick:()=>n(d)}):null]},i)}),(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"健康授权模拟"}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:!!a,onChange:e=>{r({...t,healthData:e.currentTarget.checked?{requestCompleted:!0,readStatus:{}}:void 0})}}),"启用健康授权模拟"]}),(0,s.jsx)("p",{children:"直接返回配置的状态,不读取真实健康数据;适用于所有模拟设备。"}),a&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:a.requestCompleted,onChange:e=>r({...t,healthData:{...a,requestCompleted:e.currentTarget.checked}})}),"健康授权流程成功"]}),(0,s.jsx)(pb,{label:"健康读取状态 JSON",value:a.readStatus,example:{heart_rate:2},description:"输入 JSON 对象,键为非空的健康数据类型,值为数字状态:-1 未知或不支持、0 需要授权、1 推断已拒绝、2 未发现授权错误。允许使用空对象 {}。",onChange:e=>{let i={...t,healthData:{...a,readStatus:e}};i7(i),r(i)}})]})]})]})}let pD=[{ssid:"Example Wi-Fi",bssid:"10:20:30:40:50:60",password:"wifi-password",secure:!0,signalStrength:88,frequency:2462}];function pU(e){let{wifi:t,onChange:r}=e;return(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"Wi-Fi 连接与设备"}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{checked:t.available,type:"checkbox",onChange:e=>r({...t,available:e.currentTarget.checked})}),"Wi-Fi 硬件可用"]}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{checked:t.enabled,type:"checkbox",onChange:e=>r({...t,enabled:e.currentTarget.checked})}),"Wi-Fi 开关"]}),(0,s.jsxs)("label",{className:"wsd-virtual-hardware-row",children:["当前连接",(0,s.jsxs)("select",{value:t.connectedNetworkKey,onChange:e=>r({...t,connectedNetworkKey:e.currentTarget.value}),children:[(0,s.jsx)("option",{value:"",children:"未连接"}),t.networks.map(e=>(0,s.jsxs)("option",{value:ns(e),children:[e.ssid,e.bssid?` (${e.bssid})`:""]},ns(e)))]})]}),(0,s.jsx)(pb,{label:"虚拟 Wi-Fi 网络(JSON)",value:t.networks,example:pD,description:"输入网络数组,必填 ssid(非空字符串)、password(字符串,开放网络使用空字符串)。可选 bssid 为 MAC 地址,secure 为布尔值,signalStrength 为 0–100 的数值,frequency 为正整数 MHz。SSID/BSSID 组合不可重复。",onChange:e=>{let i={...t,networks:e,connectedNetworkKey:""};no(i),e.some(e=>ns(e)===t.connectedNetworkKey)&&(i.connectedNetworkKey=t.connectedNetworkKey),r(i)}})]})}let pq=[["北",80,12],["东",148,80],["南",80,148],["西",12,80]];function p$(e){let{direction:t,onChange:r}=e,i=(0,iD.useRef)(),n=t%360,a=e=>{let t=e.currentTarget.getBoundingClientRect(),r=e.clientX-t.left-t.width/2,i=e.clientY-t.top-t.height/2;if(!(8>Math.hypot(r,i)))return 180*Math.atan2(r,-i)/Math.PI},o=cl(e=>{0!==e.button||i.current||(e.preventDefault(),e.currentTarget.focus({preventScroll:!0}),e.currentTarget.setPointerCapture(e.pointerId),i.current={id:e.pointerId,angle:a(e),heading:n})}),l=cl(e=>{let t=i.current;if((null==t?void 0:t.id)!==e.pointerId)return;let s=a(e);if(void 0===s||void 0===t.angle){t.angle=s,t.heading=n;return}r((Math.round(t.heading+t.angle-s)+360)%360)}),d=e=>{var t;(null==(t=i.current)?void 0:t.id)===e.pointerId&&(i.current=void 0)},u=cl(e=>{if(i.current)return;let t=e.shiftKey?10:1,a=n;switch(e.key){case"ArrowUp":case"ArrowRight":a+=t;break;case"ArrowDown":case"ArrowLeft":a-=t;break;case"Home":a=0;break;case"End":a=359;break;default:return}e.preventDefault(),r((a+360)%360)});return(0,s.jsxs)("div",{className:"wsd-compass-control",children:[(0,s.jsx)("span",{className:"wsd-compass-heading",children:"设备朝向"}),(0,s.jsxs)("button",{type:"button",role:"slider","aria-label":"设备朝向","aria-valuemin":0,"aria-valuemax":360,"aria-valuenow":n,"aria-valuetext":`${n}\xb0`,"aria-describedby":"wsd-compass-help",className:"wsd-compass-dial",onPointerDown:o,onPointerMove:l,onPointerUp:d,onPointerCancel:d,onLostPointerCapture:d,onBlur:()=>{i.current=void 0},onKeyDown:u,children:[(0,s.jsx)("svg",{viewBox:"0 0 160 160","aria-hidden":"true",children:(0,s.jsxs)("g",{transform:`rotate(${-n} 80 80)`,children:[Array.from({length:24},(e,t)=>(0,s.jsx)("line",{x1:"80",y1:"23",x2:"80",y2:t%6==0?"31":"27",transform:`rotate(${15*t} 80 80)`},t)),pq.map(e=>{let[t,r,i]=e;return(0,s.jsx)("text",{x:r,y:i,transform:`rotate(${n} ${r} ${i})`,children:t},t)})]})}),(0,s.jsxs)("output",{"aria-hidden":"true",children:[n,"°"]})]}),(0,s.jsx)("p",{id:"wsd-compass-help",children:"拖动方位盘模拟转向,方向键微调,Shift + 方向键每次调整 10°。"})]})}function pB(e){let{onClose:t,storageNamespace:r,selectedHardware:i,onHardwareChange:n}=e,a=(0,iD.useRef)(null),o=(0,iD.useRef)(null),l=cl(e=>{let t=e.currentTarget===a.current?o.current:a.current;t&&(t.scrollTop=e.currentTarget.scrollTop)});(0,iD.useEffect)(()=>{let e=a.current,t=o.current,r=null==t?void 0:t.firstElementChild;if(!e||!t||!r)return;let i=()=>{r.style.height=e.scrollHeight>e.clientHeight?`${e.scrollHeight}px`:"0px",t.scrollTop=e.scrollTop},n=new ResizeObserver(i);for(let t of(n.observe(e),e.children))n.observe(t);return i(),()=>n.disconnect()},[i]);let[d,u,c]=pF(nL.getBattery,e=>nL.setBattery(e)),[p,h,m]=pF(()=>({accelerometer:nL.getAccelerometer().available,gyroscope:nL.getGyroscope().available}),e=>{e.accelerometer!==nL.getAccelerometer().available&&nL.setAccelerometer({available:e.accelerometer}),e.gyroscope!==nL.getGyroscope().available&&nL.setGyroscope({available:e.gyroscope})}),[g,f,v]=pF(nL.getCompass,e=>nL.setCompass(e)),[y,b,w]=pF(nL.getWifi,e=>nL.setWifi(e)),[_,S,x]=pF(nL.getNetwork,e=>nL.setNetwork(e)),[I,k,C]=pF(nL.getBluetooth,e=>nL.setBluetooth(e)),[E,N,T]=pF(nL.getBeacon,e=>nL.setBeacon(e)),[A,M,R]=pF(nL.getSystem,e=>nL.setSystem(e)),j=A.bluetoothAuthorization??(I.authorized?"full":"denied"),P=A.locationAuthorization??(E.locationAuthorized?A.locationReducedAccuracy?"foreground approximate":"foreground precise":"denied"),[L,O,D]=pF(nL.getScreen,e=>nL.setScreen(e)),[U,q,$]=pF(nL.getKeyboard,e=>nL.setKeyboard(e)),[B,F,z]=pF(nL.getAccessibility,e=>nL.setAccessibility(e)),[W,H,V]=pF(nL.getCommunication,e=>nL.setCommunication(e)),[G,J,K]=pF(sY.getSettings,e=>sY.setSettings(e)),Z=(0,iD.useSyncExternalStore)(oi.subscribe,oi.getSnapshot,oi.getSnapshot),[X,Y]=(0,iD.useState)(()=>{var e,t;return{longitude:(null==(e=Z.longitude)?void 0:e.toString())??"",latitude:(null==(t=Z.latitude)?void 0:t.toString())??""}});(0,iD.useEffect)(()=>{if("browser"===Z.source){var e,t;Y({longitude:(null==(e=Z.longitude)?void 0:e.toString())??"",latitude:(null==(t=Z.latitude)?void 0:t.toString())??""})}},[Z.source,Z.longitude,Z.latitude]);let Q=(0,iD.useSyncExternalStore)(l9.subscribe,l9.getSnapshot),[ee,et,er]=pF(nL.getDeviceMotion,e=>nL.setDeviceMotion(e)),[ei,en]=(0,iD.useState)(""),[ea,es]=(0,iD.useState)(""),eo=cl(e=>{Y(e);try{if(e.longitude||e.latitude){if(!e.longitude||!e.latitude)throw Error("请填写完整的经纬度");oi.setManualLocation({longitude:Number(e.longitude),latitude:Number(e.latitude)})}es("")}catch(e){es(e instanceof Error?e.message:String(e))}}),el={battery:c,sensors:m||v||er,network:x||w,bluetooth:C||T||R,system:R,screen:D||$,accessibility:z,communication:V,calendar:K,location:ea||R,audio:"",storage:""},ed=cl(async()=>{es(""),await oi.requestBrowserLocation()});return(0,s.jsx)("dialog",{"aria-label":"模拟器设置",className:"wsd-preview-toolbar-menu wsd-virtual-hardware-settings",open:!0,children:(0,s.jsxs)("div",{className:"wsd-virtual-hardware-layout",children:[(0,s.jsxs)("div",{className:"wsd-virtual-hardware-header",children:[(0,s.jsx)("strong",{children:"模拟器设置"}),el[i]?(0,s.jsx)("p",{role:"alert",children:el[i]}):null,(0,s.jsxs)("label",{className:"wsd-virtual-hardware-category",children:["设置类别",(0,s.jsxs)("select",{value:i,onChange:e=>{n(e.currentTarget.value)},children:[(0,s.jsx)("option",{value:"system",children:"系统设置与授权"}),(0,s.jsx)("option",{value:"storage",children:"存储与文件"}),(0,s.jsx)("option",{value:"battery",children:"电池"}),(0,s.jsx)("option",{value:"network",children:"网络与 Wi-Fi"}),(0,s.jsx)("option",{value:"location",children:"定位"}),(0,s.jsx)("option",{value:"bluetooth",children:"蓝牙与 iBeacon"}),(0,s.jsx)("option",{value:"sensors",children:"传感器"}),(0,s.jsx)("option",{value:"screen",children:"屏幕与键盘"}),(0,s.jsx)("option",{value:"audio",children:"音频与中断"}),(0,s.jsx)("option",{value:"accessibility",children:"无障碍"}),(0,s.jsx)("option",{value:"calendar",children:"日历"}),(0,s.jsx)("option",{value:"communication",children:"电话与短信"})]})]})]}),(0,s.jsxs)("div",{className:"wsd-virtual-hardware-content",ref:a,onScroll:l,children:["storage"===i?(0,s.jsx)(py,{namespace:r},r):null,"battery"===i?(0,s.jsxs)("fieldset",{"aria-label":"电池",children:[(0,s.jsxs)("label",{className:"wsd-virtual-hardware-range",children:[(0,s.jsxs)("span",{children:["电量 ",(0,s.jsxs)("output",{children:[d.level,"%"]})]}),(0,s.jsx)("input",{max:100,min:0,step:1,type:"range","aria-label":"电量",value:d.level,onChange:e=>{u({...d,level:Number(e.currentTarget.value)})}})]}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{checked:d.isCharging,type:"checkbox",onChange:e=>{u({...d,isCharging:e.currentTarget.checked})}}),"充电中"]}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{checked:d.isLowPowerModeEnabled,type:"checkbox",onChange:e=>{u({...d,isLowPowerModeEnabled:e.currentTarget.checked})}}),"省电模式"]})]}):null,"location"===i?(0,s.jsxs)("fieldset",{"aria-label":"定位",children:[(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:A.locationEnabled,onChange:e=>{M({...A,locationEnabled:e.currentTarget.checked})}}),"系统定位开关"]}),(0,s.jsxs)("div",{className:"wsd-virtual-permission-row",children:[(0,s.jsx)("span",{children:"定位授权"}),(0,s.jsx)("span",{children:pc["denied"===Z.browserAuthorization?"denied":P]}),(0,s.jsx)(pw,{label:"前往定位授权设置",onClick:()=>n("system")})]}),(0,s.jsx)("p",{children:"此授权也用于 iBeacon。"}),["longitude","latitude"].map(e=>(0,s.jsxs)("label",{className:"wsd-virtual-hardware-row",children:["longitude"===e?"经度":"纬度",(0,s.jsx)("input",{type:"number",min:"longitude"===e?-180:-90,max:"longitude"===e?180:90,step:"any",required:!!X["longitude"===e?"latitude":"longitude"],value:X[e],onChange:t=>{eo({...X,[e]:t.currentTarget.value})}})]},e)),(0,s.jsx)("p",{children:"坐标用于应用插件定位和对话中的位置权限请求。经纬度均留空时,沿用已有定位配置;尚未配置时,在应用请求位置时使用浏览器定位。手动输入使用 GCJ-02 坐标系,浏览器位置会自动转换。"}),(0,s.jsx)("p",{role:"error"===Z.tone?"alert":"status",children:Z.message}),Z.errorMessage?(0,s.jsx)("p",{role:"alert",children:Z.errorMessage}):null,(0,s.jsx)("button",{type:"button",disabled:"pending"===Z.tone,onClick:ed,children:"使用浏览器定位"})]}):null,"sensors"===i?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(pR,{availability:p,onAvailabilityChange:h}),(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"罗盘"}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{checked:g.available,type:"checkbox",onChange:e=>{f({...g,available:e.currentTarget.checked})}}),"罗盘可用"]}),(0,s.jsx)(p$,{direction:g.direction,onChange:e=>f({...g,direction:e})}),(0,s.jsxs)("label",{className:"wsd-virtual-hardware-row",children:["罗盘精度",(0,s.jsx)("select",{value:g.accuracy,onChange:e=>{f({...g,accuracy:e.currentTarget.value})},children:nu.map(e=>(0,s.jsx)("option",{value:e,children:ph[e]},e))})]})]}),(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"设备方向(rad)"}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{checked:ee.available,type:"checkbox",onChange:e=>{et({...ee,available:e.currentTarget.checked})}}),"设备方向可用"]}),(0,s.jsx)("div",{className:"wsd-virtual-sensor-axes",children:["alpha","beta","gamma"].map(e=>(0,s.jsxs)("label",{children:[e,(0,s.jsx)("input",{"aria-label":`设备方向 ${e}(rad)`,required:!0,step:"any",type:"number",value:Number.isFinite(ee[e])?ee[e]:"",onChange:t=>{et({...ee,[e]:t.currentTarget.valueAsNumber})}})]},e))})]})]}):null,"network"===i?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(pj,{network:_,onChange:S}),(0,s.jsx)(pU,{wifi:y,onChange:b})]}):null,"bluetooth"===i?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(pS,{bluetooth:I,authorization:j,onOpenAuthorization:()=>n("system"),onChange:e=>{k(e)}}),(0,s.jsx)(p_,{beacon:E,onChange:N,locationAuthorization:P,onOpenAuthorization:()=>n("system")})]}):null,"system"===i?(0,s.jsx)(pO,{system:A,onChange:M,authorizationFallbacks:{bluetoothAuthorization:j,locationAuthorization:P},onHardwareChange:n}):null,"screen"===i?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"屏幕"}),(0,s.jsxs)("label",{className:"wsd-virtual-hardware-range",children:[(0,s.jsxs)("span",{children:["基准亮度 ",(0,s.jsxs)("output",{children:[Math.round(100*L.brightness),"%"]})]}),(0,s.jsx)("input",{min:0,max:1,step:.01,type:"range","aria-label":"基准亮度",value:L.brightness,onChange:e=>{O({...L,brightness:Number(e.currentTarget.value)})}})]}),(0,s.jsx)("p",{children:"亮度作用于手机预览。应用通过 API 设置的亮度仅在页面显示时生效,页面关闭后恢复基准亮度。"}),(0,s.jsxs)("p",{children:["当前模拟亮度:",Q.brightness,";常亮状态:",Q.keepScreenOn?"开启":"关闭","。常亮开关只记录模拟状态。"]}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:L.recording,onChange:e=>{O({...L,recording:e.currentTarget.checked})}}),"正在录屏"]}),(0,s.jsxs)("p",{children:["录屏保护:",Q.screenRecordDisabled?"开启":"关闭"]}),(0,s.jsx)("p",{children:"截屏和录屏使用模拟输入,浏览器或系统截图不受此处保护开关限制。"}),(0,s.jsx)("button",{type:"button",onClick:()=>{en(l9.capture().protected?"模拟捕获结果:应用内容受保护":"模拟捕获结果:应用内容可见")},children:"模拟截屏"}),(0,s.jsx)("p",{role:"status",children:ei})]}),(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"键盘"}),(0,s.jsxs)("label",{className:"wsd-virtual-hardware-row",children:["键盘高度",(0,s.jsx)("input",{"aria-label":"键盘高度(Android dp / iOS pt)",type:"number",min:0,max:1e3,step:"any",required:!0,value:Number.isFinite(U.height)?U.height:"",onChange:e=>{q({height:e.currentTarget.valueAsNumber})}})]}),(0,s.jsx)("p",{children:"高度单位为 Android dp / iOS pt。页面内文本输入获得焦点时报告此高度,失去焦点或调用 hideKeyboard 时报告 0。"}),(0,s.jsx)("p",{children:"使用电脑键盘输入,不绘制手机软键盘,也不改变浏览器窗口尺寸。"})]})]}):null,"accessibility"===i?(0,s.jsxs)("fieldset",{"aria-label":"无障碍状态",children:[[["available","Android 无障碍服务可用"],["androidEnabled","Android 无障碍服务已开启"],["touchExplorationEnabled","Android 触摸探索已开启"],["voiceOverRunning","iOS VoiceOver 已开启"],["switchControlRunning","iOS 开关控制已开启"]].map(e=>{let[t,r]=e;return(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:B[t],onChange:e=>{F({...B,[t]:e.currentTarget.checked})}}),r]},t)}),(0,s.jsx)("p",{children:"Android 同时开启服务与触摸探索时返回 true;iOS 开启 VoiceOver 或开关控制时返回 true。"}),(0,s.jsx)("p",{children:"只模拟查询结果,不改变电脑的辅助功能。"})]}):null,"communication"===i?(0,s.jsxs)("fieldset",{"aria-label":"电话与短信",children:[[["phoneAvailable","设备支持电话"],["phoneOpenSucceeds","拨号面板打开成功"],["smsAvailable","设备支持短信"],["smsOpenSucceeds","短信面板打开成功"],["smsSendSucceeds","模拟发送短信成功"]].map(e=>{let[t,r]=e;return(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:W[t],onChange:e=>{H({...W,[t]:e.currentTarget.checked})}}),r]},t)}),(0,s.jsx)("p",{children:"短信等待模拟发送或取消后返回结果。所有交互均在模拟器内完成。"})]}):null,"calendar"===i?(0,s.jsx)(pI,{settings:G,onChange:J,authorization:A.phoneCalendar,onOpenAuthorization:()=>n("system")}):null,"audio"===i?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(pv,{}),(0,s.jsx)(pf,{})]}):null]},i),(0,s.jsx)("div",{"aria-hidden":"true",className:"wsd-virtual-hardware-scrollbar",ref:o,tabIndex:-1,onScroll:l,children:(0,s.jsx)("div",{})}),(0,s.jsx)("div",{className:"wsd-virtual-hardware-actions",children:(0,s.jsx)("button",{onClick:t,type:"button",children:"关闭"})})]})})}function pF(e,t){let[r,i]=(0,iD.useState)(e),[n,a]=(0,iD.useState)(""),s=cl(n=>{let s=Object.fromEntries(Object.entries(n).filter(e=>{let[t,i]=e;return!Object.is(i,r[t])}));try{t({...e(),...s}),i(e()),a("")}catch(e){i(n),a(e instanceof Error?e.message:String(e))}});return[r,s,n]}let pz=[{key:"conversation",label:"对话"},{key:"tool",label:"工具"},{key:"card",label:"卡片"},{key:"page",label:"全页"}],pW=[{label:"iOS",devices:so.filter(e=>e.key.startsWith("iphone"))},{label:"Android",devices:so.filter(e=>e.key.startsWith("pixel")||e.key.startsWith("galaxy"))},{label:"平板",devices:so.filter(e=>e.key.startsWith("ipad"))}];function pH(e){let{activeView:t,children:r,hasTools:i=!1,onActiveViewChange:n,onDeviceChange:a,selectedDeviceKey:o,storageNamespace:l}=e,d=pz.filter(e=>"tool"!==e.key||i),[u,c]=(0,iD.useState)(!1),[p,h]=(0,iD.useState)(!1),[m,g]=(0,iD.useState)(ni["0"]),[f,v]=(0,iD.useState)(),y=su(o??ss),[b,w]=(0,iD.useState)(()=>String(y.width)),[_,S]=(0,iD.useState)(()=>String(y.height)),x=(0,iD.useRef)(null),I=(null==o?void 0:o.startsWith("custom-"))===!0&&y.key===o,k=(e,t)=>{let r=`custom-${e}x${t}`;su(r).key===r&&(null==a||a(r))};return(0,iD.useEffect)(()=>{let e=e=>{let t=e.detail;"string"==typeof t&&ni.includes(t)&&(g(t),v("settings"),c(!1),h(!0))},t=e=>{var t;(null==(t=x.current)?void 0:t.contains(e.target))||(c(!1),h(!1))},r=e=>{"Escape"===e.key&&(c(!1),h(!1))};return window.addEventListener("pointerdown",t),window.addEventListener("keydown",r),window.addEventListener(nn,e),()=>{window.removeEventListener("pointerdown",t),window.removeEventListener("keydown",r),window.removeEventListener(nn,e)}},[]),(0,s.jsxs)("header",{className:"wsd-preview-device-toolbar",ref:x,children:[(0,s.jsxs)("div",{className:"wsd-device-toolbar-leading",children:[(0,s.jsx)("button",{"aria-label":"手机预览","aria-expanded":u,"aria-haspopup":"dialog","aria-pressed":"phone"===f,className:(0,rL.$)("wsd-device-toolbar-icon","phone"===f&&"is-active"),onClick:()=>{v("phone"),h(!1),u||(w(String(y.width)),S(String(y.height))),c(e=>!e)},type:"button",children:(0,s.jsx)(pu,{"aria-hidden":"true"})}),u?(0,s.jsxs)("dialog",{"aria-label":"选择模拟器类型",className:"wsd-preview-toolbar-menu",open:!0,children:[(0,s.jsx)("div",{className:"wsd-custom-device-size-label",children:"自定义"}),(0,s.jsxs)("div",{className:(0,rL.$)("wsd-custom-device-size",I&&"is-selected"),children:[(0,s.jsx)("input",{"aria-label":"自定义宽度",className:"wsd-custom-device-size-input",max:9999,min:1,onChange:e=>{let t=e.currentTarget.value;w(t),k(t,_)},step:1,type:"number",value:b}),(0,s.jsx)("span",{"aria-hidden":"true",className:"wsd-custom-device-size-separator",children:"×"}),(0,s.jsx)("input",{"aria-label":"自定义高度",className:"wsd-custom-device-size-input",max:9999,min:1,onChange:e=>{let t=e.currentTarget.value;S(t),k(b,t)},step:1,type:"number",value:_}),(0,s.jsx)("span",{"aria-hidden":"true",className:"wsd-custom-device-size-check",children:"✓"})]}),(0,s.jsx)(po.o,{"aria-label":"选择预设机型",className:"wsd-preview-toolbar-device-menu",selectedKeys:!I&&o?[o]:[],selectionMode:"single",onAction:e=>{null==a||a(String(e)),c(!1)},children:pW.map(e=>(0,s.jsx)(pl.g,{showDivider:e!==pW.at(-1),title:e.label,children:e.devices.map(e=>(0,s.jsx)(pd.Y,{title:e.label,children:e.label},e.key))},e.label))})]}):null,(0,s.jsx)("button",{"aria-label":"设置","aria-expanded":p,"aria-haspopup":"dialog","aria-pressed":"settings"===f,className:(0,rL.$)("wsd-device-toolbar-icon","settings"===f&&"is-active"),onClick:()=>{v("settings"),c(!1),h(e=>!e)},type:"button",children:(0,s.jsx)(cI,{"aria-hidden":"true"})}),p?(0,s.jsx)(pB,{selectedHardware:m,storageNamespace:l,onHardwareChange:g,onClose:()=>h(!1)}):null]}),(0,s.jsx)("div",{className:"wsd-debug-mode-slot",children:(0,s.jsx)("nav",{"aria-label":"调试视图",className:"wsd-debug-mode-tabs",role:"tablist",children:d.map(e=>(0,s.jsx)("span",{"aria-selected":t===e.key,className:(0,rL.$)("wsd-debug-mode-tab",t===e.key&&"is-active"),onClick:()=>null==n?void 0:n(e.key),onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),null==n||n(e.key))},role:"tab",tabIndex:0,children:e.label},e.key))})}),(0,s.jsxs)("div",{className:"wsd-page-toolbar-actions",children:[(0,s.jsx)(ch,{}),r]})]})}function pV(e){var t;let{children:r,runtime:i,showReloadButton:n=!0,toolbarView:a=i.activeView}=e,o="card"===i.activeView?i.devtoolsTarget:i.devtoolsTarget??(null==(t=i.conversationControlTarget)?void 0:t.target)??null,l=(0,iD.useMemo)(()=>({consoleTarget:"conversation"===i.activeView?i.conversationConsoleTarget:void 0,controlCommand:i.controlCommand,controlTarget:o,debugState:i.debugState,frontendUrl:i.chromeDevToolsFrontendUrl,getRuntimeFrame:i.getRuntimeFrame,onConsoleSnapshotChange:i.setRuntimeConsoleSnapshot,onControlResult:i.onControlResult,onDebugAction:i.handleDebugAction,onHighlightChange:i.setHighlightRect,onRuntimeSnapshotChange:i.setRuntimeDomSnapshot,runtimeSnapshotTarget:i.runtimeSnapshotTarget,resolveTargetAtPoint:"conversation"===i.activeView?i.resolveConversationInspectTarget:void 0,showPanelId:i.devToolsPanelId,showPanelRequestId:i.latestDevToolsPanelRequestId,target:o}),[i.activeView,o,i.chromeDevToolsFrontendUrl,i.controlCommand,i.conversationConsoleTarget,i.debugState,i.devToolsPanelId,i.devtoolsTarget,i.getRuntimeFrame,i.handleDebugAction,i.latestDevToolsPanelRequestId,i.onControlResult,i.resolveConversationInspectTarget,i.runtimeSnapshotTarget,i.setHighlightRect,i.setRuntimeConsoleSnapshot,i.setRuntimeDomSnapshot]);return(0,iD.useEffect)(()=>{var e;null==(e=i.onChromeDevToolsPanelChange)||e.call(i,l)},[l,i.onChromeDevToolsPanelChange]),(0,s.jsxs)("div",{className:(0,rL.$)("wsd-widget-preview-column","card"===i.activeView&&"is-card-debug"),children:[(0,s.jsx)(pH,{activeView:a,storageNamespace:i.fileSystemNamespace,hasTools:Object.keys(i.state.manifest.raw.tools??{}).length>0,onActiveViewChange:i.onActiveViewChange,onDeviceChange:i.setSelectedDeviceKey,selectedDeviceKey:i.selectedDeviceKey,children:n?(0,s.jsx)("button",{"aria-label":"刷新资源并重载卡片",className:"wsd-icon-button",disabled:!i.canReloadResources,onClick:i.reloadResources,title:"streaming"===i.simulatorState.streamStatus?"对话生成中暂不能刷新资源":"刷新资源并重载卡片",type:"button",children:(0,s.jsx)(ps,{"aria-hidden":"true"})}):null}),r]})}function pG(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return{type:"callback",callbackId:e.callbackId,params:{code:1,data:t}}}function pJ(e){let{appIcon:t}=e,[r,i]=(0,iD.useState)(!1);return((0,iD.useEffect)(()=>{i(!1)},[t]),!t||r)?null:(0,s.jsx)("img",{alt:"",className:"wsd-simulator-permission-app-icon",onError:()=>i(!0),src:t})}function pK(e){let{onAllow:t,onReject:r,permission:i}=e;return(0,s.jsxs)("div",{className:"wsd-simulator-permission-layer",children:[(0,s.jsx)("div",{"aria-hidden":"true",className:"wsd-simulator-permission-backdrop"}),(0,s.jsxs)("dialog",{"aria-label":`${i.appName}权限申请`,"aria-modal":"true",className:"wsd-simulator-permission-dialog",open:!0,children:[(0,s.jsxs)("header",{className:"wsd-simulator-permission-brand",children:[(0,s.jsx)(pJ,{appIcon:i.appIcon}),(0,s.jsx)("strong",{children:i.appName})]}),(0,s.jsxs)("section",{className:"wsd-simulator-permission-content",children:[(0,s.jsx)("h2",{children:i.title}),(0,s.jsx)("p",{children:i.description})]}),(0,s.jsxs)("footer",{className:"wsd-simulator-permission-actions",children:[(0,s.jsx)("button",{className:"is-primary",onClick:t,type:"button",children:"允许"}),(0,s.jsx)("button",{className:"is-secondary",onClick:r,type:"button",children:"拒绝"})]})]})]})}function pZ(){let[e,t]=(0,iD.useState)(),[r,i]=(0,iD.useState)(),n=(0,iD.useRef)(null),a=(0,iD.useRef)(null),o=cl(e=>{var t;null==(t=a.current)||t.call(a,e)}),l=cl(e=>n.current||a.current?Promise.reject(Error("openSetting is already in progress")):e.signal.aborted?Promise.reject(Error("settings view was destroyed")):new Promise((t,r)=>{let n=()=>o(Error("settings view was destroyed"));a.current=s=>{e.signal.removeEventListener("abort",n),a.current=null,i(void 0),s?r(s):t()},e.signal.addEventListener("abort",n,{once:!0}),i(e)})),d=cl(e=>{var r;return(null==(r=e.signal)?void 0:r.aborted)?Promise.resolve(!1):n.current||a.current?Promise.reject(Error("Simulator permission prompt is already open")):new Promise(r=>{var i;let a=()=>s(!1),s=i=>{var o;n.current===s&&(n.current=null,null==(o=e.signal)||o.removeEventListener("abort",a),t(void 0),r(i))};n.current=s,null==(i=e.signal)||i.addEventListener("abort",a,{once:!0}),t(e)})}),u=cl(e=>{let t=n.current;t&&t(e)}),c=cl(()=>u(!0)),p=cl(()=>u(!1));return(0,iD.useEffect)(()=>()=>{var e;let t=n.current;null==t||t(!1),null==(e=a.current)||e.call(a,Error("settings presenter was destroyed"))},[]),{allowPermission:c,permission:e,rejectPermission:p,showPermission:d,showSettings:l,overlay:r?(0,s.jsx)(pX,{settings:r,onClose:()=>o()}):e?(0,s.jsx)(pK,{permission:e,onAllow:c,onReject:p}):null}}function pX(e){let{settings:t,onClose:r}=e,[i,n]=(0,iD.useState)(t.authSetting);return(0,s.jsxs)("div",{className:"wsd-simulator-permission-layer",children:[(0,s.jsx)("div",{"aria-hidden":"true",className:"wsd-simulator-permission-backdrop"}),(0,s.jsxs)("dialog",{"aria-label":`${t.appName}授权设置`,"aria-modal":"true",className:"wsd-simulator-permission-dialog wsd-simulator-permission-settings",open:!0,children:[(0,s.jsxs)("header",{className:"wsd-simulator-permission-brand",children:[(0,s.jsx)(pJ,{appIcon:t.appIcon}),(0,s.jsx)("strong",{children:t.appName})]}),(0,s.jsxs)("section",{className:"wsd-simulator-permission-content",children:[(0,s.jsx)("h2",{children:"应用权限设置"}),(0,s.jsx)("p",{children:"仅显示已请求过的权限,修改立即生效。"})]}),(0,s.jsxs)("div",{className:"wsd-simulator-permission-scopes",children:[Object.entries(i).map(e=>{let[r,i]=e;return(0,s.jsxs)("label",{children:[(0,s.jsx)("span",{children:sH(r).title}),(0,s.jsx)("input",{"aria-label":r,checked:i,onChange:e=>{let i=e.currentTarget.checked;t.onChange(r,i),n(e=>({...e,[r]:i}))},type:"checkbox"})]},r)}),0===Object.keys(i).length?(0,s.jsx)("p",{children:"尚未请求任何应用权限"}):null]}),(0,s.jsx)("footer",{className:"wsd-simulator-permission-actions",children:(0,s.jsx)("button",{className:"is-primary",onClick:r,type:"button",children:"完成"})})]})]})}let pY=["agreeMain","agreeSub","reject"],pQ=e=>nL.subscribe("network",e),p0={success:"M12 21.91a9.95 9.95 0 1 0 0-19.92 9.95 9.95 0 0 0 0 19.92Zm-1.09-5.2a.88.88 0 0 1-.86-.46L7.6 13.24a1.05 1.05 0 0 1-.24-.64c0-.22.08-.41.23-.56a.75.75 0 0 1 .55-.25c.14 0 .27.03.38.09.12.06.24.17.36.33l1.98 2.56 4.17-6.7c.18-.3.42-.45.7-.45.21 0 .4.07.57.2.17.14.25.32.25.55 0 .11-.02.22-.08.33-.05.11-.1.21-.16.31l-4.59 7.24a1.1 1.1 0 0 1-.82.46Z",error:"M4.43 21.18c-.55 0-1.03-.12-1.42-.35a2.4 2.4 0 0 1-.92-.96 2.75 2.75 0 0 1-.32-1.34c0-.47.12-.93.38-1.37L9.72 3.96c.25-.44.58-.77.99-1 .41-.22.84-.34 1.29-.34s.88.12 1.28.34c.41.23.74.56 1 1l7.57 13.2c.12.22.22.44.28.68.07.23.1.46.1.69 0 .5-.1.94-.32 1.34-.21.4-.52.72-.92.96-.4.23-.87.35-1.42.35H4.43Zm7.58-6.54c.5 0 .77-.26.77-.8l.15-5.31a.81.81 0 0 0-.27-.63.9.9 0 0 0-.66-.27c-.27 0-.5.09-.67.26a.8.8 0 0 0-.25.63l.13 5.32c.01.54.28.8.8.8Zm0 3.28c.29 0 .55-.1.76-.3.22-.21.33-.45.33-.75 0-.29-.11-.54-.33-.74a1.08 1.08 0 0 0-.76-.31c-.3 0-.56.1-.77.31-.22.2-.32.45-.32.74 0 .3.1.54.32.75.22.2.47.3.77.3Z",warn:"M12 21.91a9.95 9.95 0 1 0 0-19.92 9.95 9.95 0 0 0 0 19.92Zm0-8.14c-.52 0-.79-.27-.8-.8l-.13-5.33a.8.8 0 0 1 .25-.63c.18-.17.4-.26.67-.26.27 0 .49.09.67.27.18.17.27.38.26.63l-.15 5.32c0 .53-.26.8-.77.8Zm0 3.27c-.3 0-.56-.1-.77-.3a1 1 0 0 1-.32-.75c0-.29.1-.54.32-.74.21-.21.47-.31.77-.31.29 0 .55.1.76.31.22.2.33.45.33.74 0 .3-.11.54-.33.75-.21.2-.47.3-.76.3Z"},p1={error:"error",success:"success",warning:"warn"};function p2(e){return Array.isArray(e.itemList)?e.itemList:[]}function p3(e){let t=new DOMParser().parseFromString(e,"text/html");return t.doctype||0!==t.documentElement.attributes.length||0!==t.head.attributes.length||0!==t.head.childNodes.length||0!==t.body.attributes.length?null:function e(t){let r=[];for(let i of Array.from(t)){let t=function(t){if(t.nodeType===Node.TEXT_NODE)return{type:"text",value:t.textContent??""};if(t.nodeType!==Node.ELEMENT_NODE)return null;let r=e(t.childNodes);if(!r)return null;if("a"===t.localName){if(1!==t.attributes.length||!t.hasAttribute("href"))return null;try{let e=new URL(t.getAttribute("href")??"");if("http:"!==e.protocol&&"https:"!==e.protocol)return null;return{children:r,href:e.href,type:"link"}}catch{return null}}return 0!==t.attributes.length||"p"!==t.localName&&"b"!==t.localName?null:{children:r,type:"p"===t.localName?"paragraph":"bold"}}(i);if(!t)return null;r.push(t)}return r}(t.body.childNodes)}function p4(e){let{content:t}=e,r=(0,iD.useMemo)(()=>p3(t)??[],[t]);return(0,s.jsx)("div",{className:"wsd-simulator-bottom-sheet-content",children:function e(t){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"content";return t.map((t,i)=>{if("text"===t.type)return t.value;let n=`${r}-${i}`,a=e(t.children,n);return"paragraph"===t.type?(0,s.jsx)("p",{children:a},n):"bold"===t.type?(0,s.jsx)("b",{children:a},n):"link"===t.type?(0,s.jsx)("a",{href:t.href,rel:"noreferrer",target:"_blank",children:a},n):null})}(r)})}function p5(e){let{scanner:t}=e,r=(0,iD.useRef)(null),i=(0,iD.useRef)(null);return(0,iD.useEffect)(()=>{let e=i.current;e&&t.options.onVideoReady(e)},[t.options]),(0,s.jsxs)("div",{"aria-label":"扫码",className:"wsd-simulator-scan-code",children:[(0,s.jsx)("video",{autoPlay:!0,muted:!0,playsInline:!0,ref:i}),(0,s.jsx)("div",{className:"wsd-simulator-scan-code-message",children:t.message}),(0,s.jsxs)("div",{className:"wsd-simulator-scan-code-actions",children:[(0,s.jsx)("button",{onClick:t.options.onCancel,type:"button",children:"关闭"}),(0,s.jsx)("button",{onClick:t.options.onCapture,type:"button",children:"识别"}),t.options.allowImageUpload?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("button",{onClick:()=>{var e;return null==(e=r.current)?void 0:e.click()},type:"button",children:"相册"}),(0,s.jsx)("input",{accept:"image/*",hidden:!0,onChange:e=>{var r;let i=null==(r=e.currentTarget.files)?void 0:r[0];e.currentTarget.value="",i&&t.options.onFile(i)},ref:r,type:"file"})]}):null]})]})}function p6(e){let{children:t,className:r,exiting:i=!1,onDismiss:n}=e;return(0,s.jsxs)("div",{className:`wsd-simulator-overlay-interaction${r?` ${r}`:""}${i?" is-exiting":""}`,children:[(0,s.jsx)("div",{"aria-hidden":"true",className:"wsd-simulator-overlay-backdrop",onClick:n}),t]})}function p8(e){var t;let{interaction:r,onActionSheetSelect:i,onBottomSheetSelect:n,onDismiss:a,onModalResult:o}=e,[l,d]=(0,iD.useState)(""),u=cl(e=>d(e.currentTarget.value)),c=()=>a(r);if("modal"===r.kind){let{params:e}=r,t=!1!==e.showCancel;return(0,s.jsx)(p6,{className:"is-modal",exiting:r.exiting,onDismiss:c,children:(0,s.jsxs)("dialog",{"aria-label":e.title||"提示","aria-modal":"true",className:`wsd-simulator-modal${e.title?" has-title":""}`,onClick:e=>e.stopPropagation(),open:!0,children:[e.title?(0,s.jsx)("h2",{className:"wsd-simulator-modal-title",children:e.title}):null,(0,s.jsx)("p",{className:"wsd-simulator-modal-message",children:e.content||""}),e.editable?(0,s.jsx)("input",{"aria-label":e.placeholderText||"输入内容",className:"wsd-simulator-modal-input",onChange:u,placeholder:e.placeholderText,value:l}):null,(0,s.jsxs)("footer",{className:`wsd-simulator-modal-actions${t?"":" is-single"}`,children:[t?(0,s.jsx)("button",{className:"wsd-simulator-modal-button is-cancel",onClick:()=>o(r.id,"cancel"),style:e.cancelColor?{color:e.cancelColor}:void 0,type:"button",children:e.cancelText||"cancel"}):null,(0,s.jsx)("button",{className:"wsd-simulator-modal-button is-confirm",onClick:()=>o(r.id,"confirm",e.editable?l:void 0),style:e.confirmColor?{color:e.confirmColor}:void 0,type:"button",children:e.confirmText||"confirm"})]})]})})}if("actionSheet"===r.kind){let e=p2(r.params);return(0,s.jsx)(p6,{onDismiss:c,children:(0,s.jsxs)("dialog",{"aria-label":r.params.title||"操作菜单","aria-modal":"true",className:"wsd-simulator-overlay-sheet wsd-simulator-action-sheet",onClick:e=>e.stopPropagation(),open:!0,children:[r.params.title?(0,s.jsx)("h2",{children:r.params.title}):null,(0,s.jsx)("div",{className:"wsd-simulator-overlay-list",children:e.map((e,t)=>(0,s.jsx)("button",{className:"wsd-simulator-overlay-list-item",onClick:()=>i(r.id,t),style:r.params.itemColor?{color:r.params.itemColor}:void 0,type:"button",children:e},`${e}-${t}`))})]})})}let p=Array.isArray((t=r.params).buttons)?t.buttons:[];return(0,s.jsx)(p6,{onDismiss:c,children:(0,s.jsxs)("dialog",{"aria-label":r.params.title||"底部弹窗","aria-modal":"true",className:"wsd-simulator-overlay-sheet wsd-simulator-bottom-sheet",onClick:e=>e.stopPropagation(),open:!0,children:[r.params.title?(0,s.jsx)("h2",{children:r.params.title}):null,r.params.content?(0,s.jsx)(p4,{content:r.params.content}):null,(0,s.jsx)("div",{className:"wsd-simulator-overlay-actions",children:p.map(e=>(0,s.jsx)("button",{className:`wsd-simulator-overlay-button ${"reject"===e.role?"is-secondary":"is-primary"}`,onClick:()=>n(r.id,e.role),type:"button",children:e.text},e.role))})]})})}function p9(e){let{imagePreview:t,interaction:r,loading:i,onActionSheetSelect:n,onBottomSheetSelect:a,onDismiss:o,onImagePreviewClose:l,onImagePreviewNavigate:d,onModalResult:u,scanner:c,toast:p}=e,h=(0,iD.useSyncExternalStore)(pQ,nL.getNetwork),m=null==t?void 0:t.urls[t.currentIndex],g=m&&nq(m)&&"none"===h.networkType;return(0,s.jsxs)("div",{className:"wsd-simulator-overlay-layer wsd-simulator-overlay-host",children:[i?(0,s.jsxs)("div",{"aria-live":"polite",className:"wsd-simulator-loading",children:[(0,s.jsx)("span",{className:"wsd-simulator-loading-spinner"}),(0,s.jsx)("span",{children:"Loading..."})]}):null,p?(0,s.jsxs)("output",{"aria-live":"polite",className:`wsd-simulator-toast is-${p.type}${p.exiting?" is-exiting":""}`,children:[function(e){if(e.customIcon)return(0,s.jsx)("img",{alt:"",className:"wsd-simulator-toast-icon",src:e.customIcon});let t=e.icon||p1[e.type];return t?(0,s.jsx)("svg",{"aria-hidden":"true",className:`wsd-simulator-toast-icon is-${t}`,focusable:"false",viewBox:"0 0 24 24",children:(0,s.jsx)("path",{d:p0[t]})}):null}(p),(0,s.jsx)("span",{className:"wsd-simulator-toast-message",children:p.message})]},p.id):null,c?(0,s.jsx)(p5,{scanner:c}):null,t?(0,s.jsxs)("div",{className:"wsd-simulator-image-preview",children:[g?(0,s.jsx)("p",{role:"status",children:"模拟网络已断开"}):(0,s.jsx)("img",{alt:`图片 ${t.currentIndex+1}`,onContextMenu:t.showmenu?void 0:e=>e.preventDefault(),referrerPolicy:t.referrerPolicy,src:m}),(0,s.jsx)("button",{"aria-label":"关闭图片预览",className:"wsd-simulator-image-preview-close",onClick:l,type:"button",children:"×"}),t.urls.length>1?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("button",{"aria-label":"上一张图片",className:"wsd-simulator-image-preview-navigation is-previous",onClick:()=>d(-1),type:"button",children:"‹"}),(0,s.jsx)("button",{"aria-label":"下一张图片",className:"wsd-simulator-image-preview-navigation is-next",onClick:()=>d(1),type:"button",children:"›"}),(0,s.jsxs)("span",{className:"wsd-simulator-image-preview-counter",children:[t.currentIndex+1," / ",t.urls.length]})]}):null]}):null,r?(0,s.jsx)(p8,{interaction:r,onActionSheetSelect:n,onBottomSheetSelect:a,onDismiss:o,onModalResult:u},r.id):null]})}function p7(){let e=function(){let[e,t]=(0,iD.useState)(null),r=(0,iD.useRef)(null),i=(0,iD.useRef)(0),n=cl((e,i)=>{let n=r.current;(null==n?void 0:n.id)===e&&(r.current=null,n.cleanup(),n.resolve(i),t(null))}),a=cl((e,a)=>{if(a.aborted||r.current)throw Error("The communication panel is unavailable");let s=++i.current,o=()=>n(s,"cancel");return{closed:new Promise(i=>{let n={id:s,params:e,resolve:i,cleanup:()=>a.removeEventListener("abort",o)};r.current=n,t(n),a.addEventListener("abort",o,{once:!0})})}});(0,iD.useEffect)(()=>()=>{var e,t;null==(e=r.current)||e.cleanup(),null==(t=r.current)||t.resolve("cancel"),r.current=null},[]);let o=(null==e?void 0:e.params.kind)==="sms";return{show:a,overlay:e?(0,s.jsx)("div",{className:"wsd-simulator-overlay-layer wsd-simulator-overlay-host",children:(0,s.jsxs)("div",{className:"wsd-simulator-overlay-interaction is-modal",children:[(0,s.jsx)("div",{"aria-hidden":"true",className:"wsd-simulator-overlay-backdrop",onClick:()=>n(e.id,"cancel")}),(0,s.jsxs)("dialog",{open:!0,"aria-modal":"true","aria-label":o?"模拟短信":"模拟拨号盘",className:"wsd-simulator-modal has-title",children:[(0,s.jsx)("h2",{className:"wsd-simulator-modal-title",children:o?"模拟短信":"模拟拨号盘"}),(0,s.jsx)("p",{className:"wsd-simulator-modal-message",children:o?"此面板只模拟短信编辑与结果,不会发送真实短信。":"此面板只模拟拨号界面,不会发起真实呼叫。"}),(0,s.jsxs)("div",{className:"wsd-simulator-communication-fields",children:[(0,s.jsxs)("label",{children:[o?"收件号码":"电话号码",(0,s.jsx)("input",{className:"wsd-simulator-modal-input",defaultValue:e.params.phoneNumber,type:"tel"})]}),o?(0,s.jsxs)("label",{children:["短信内容",(0,s.jsx)("textarea",{className:"wsd-simulator-modal-input",defaultValue:e.params.message,rows:4})]}):null,o?(0,s.jsxs)("p",{children:["本次模拟发送结果:",e.params.sendSucceeds?"成功":"失败"]}):null]},e.id),(0,s.jsxs)("footer",{className:`wsd-simulator-modal-actions${o?"":" is-single"}`,children:[(0,s.jsx)("button",{className:"wsd-simulator-modal-button is-cancel",type:"button",onClick:()=>n(e.id,"cancel"),children:o?"取消":"关闭"}),o?(0,s.jsx)("button",{className:"wsd-simulator-modal-button is-confirm",type:"button",onClick:()=>n(e.id,e.params.sendSucceeds?"sent":"failed"),children:"模拟发送"}):null]})]})]})}):null}}(),[t,r]=(0,iD.useState)(null),[i,n]=(0,iD.useState)(null),[a,o]=(0,iD.useState)(!1),[l,d]=(0,iD.useState)(null),u=(0,iD.useRef)(null),c=(0,iD.useRef)(),p=(0,iD.useRef)(0),h=(0,iD.useRef)(0),m=(0,iD.useRef)(0),g=(0,iD.useRef)(null),[f,v]=(0,iD.useState)(null),y=(0,iD.useRef)(null),b=(0,iD.useRef)(),w=(0,iD.useRef)(),_=cl((e,t,r)=>{let i=u.current;i&&i.id===e&&(c.current&&(clearTimeout(c.current),c.current=void 0),r?i.reject(r):i.resolve(t),u.current=null,n(null))}),S=cl(()=>{let e=u.current;e&&("modal"===e.kind?_(e.id,{action:"cancel"}):"bottomSheet"===e.kind?_(e.id,{action:"cancel",source:"unknown"}):_(e.id,void 0,Error("action sheet selection was cancelled")))}),x=cl((e,t,r,i)=>{c.current&&(clearTimeout(c.current),c.current=void 0),S();let a={exiting:!1,id:++p.current,kind:e,params:t,reject:i,resolve:r};u.current=a,n({exiting:a.exiting,id:a.id,kind:a.kind,params:a.params})}),I=cl(()=>{w.current&&(clearTimeout(w.current),w.current=void 0),b.current&&(clearTimeout(b.current),b.current=void 0)}),k=cl(e=>{var t;(null==(t=y.current)?void 0:t.id)===e&&(y.current=null,b.current=void 0,d(null))}),C=cl(()=>{let e=y.current;if(!e||e.exiting)return;w.current&&(clearTimeout(w.current),w.current=void 0);let t={...e,exiting:!0};y.current=t,d(t),b.current=setTimeout(()=>k(e.id),180)}),E=cl(e=>{I();let t="number"==typeof e.duration&&e.duration>=0?e.duration:2e3,r={customIcon:e.customIcon,exiting:!1,id:++m.current,icon:e.icon,message:"string"==typeof e.message?e.message:"",type:e.type||"default"};y.current=r,d(r),t>0&&(w.current=setTimeout(C,Math.max(0,t-180)))}),N=cl(e=>{var t;(null==(t=g.current)?void 0:t.id)===e&&(g.current=null,v(null))}),T=cl((e,t)=>{let r=g.current;if((null==r?void 0:r.id)!==e)return;let i={...r,message:t};g.current=i,v(i)}),A=cl(e=>{var t;null==(t=g.current)||t.options.onCancel();let r=++h.current,i={id:r,message:"正在打开摄像头...",options:e};return g.current=i,v(i),{close:()=>N(r),setMessage:e=>T(r,e)}}),M=(0,iD.useMemo)(()=>({previewImage:e=>{let t=Array.isArray(e.urls)?e.urls.filter(e=>"string"==typeof e):[];if(0===t.length)throw Error("urls must contain at least one image");r({currentIndex:function(e,t){if("number"==typeof e.current&&Number.isInteger(e.current))return Math.min(Math.max(e.current,0),t.length-1);if("string"==typeof e.current){let r=t.indexOf(e.current);return r<0?0:r}return 0}(e,t),referrerPolicy:["","no-referrer","no-referrer-when-downgrade","origin","origin-when-cross-origin","same-origin","strict-origin","strict-origin-when-cross-origin","unsafe-url"].find(t=>t===e.referrerPolicy),showmenu:!1!==e.showmenu,urls:t})}}),[]),R=cl(()=>r(null)),j=cl(e=>{r(t=>t?{...t,currentIndex:(t.currentIndex+e+t.urls.length)%t.urls.length}:null)}),P=cl((e,t)=>{let r;return(null==t?void 0:t.aborted)?Promise.resolve({action:"cancel"}):new Promise((i,n)=>{x("modal",e,i,n);let a=u.current.id;r=()=>_(a,{action:"cancel"}),null==t||t.addEventListener("abort",r,{once:!0})}).finally(()=>{r&&(null==t||t.removeEventListener("abort",r))})}),L=cl(e=>new Promise((t,r)=>{0===p2(e).length?r(Error("itemList must contain at least one item")):x("actionSheet",e,t,r)})),O=cl(e=>new Promise((t,r)=>{let i=function(e){if("string"!=typeof e.title||""===e.title.trim())return"title must not be empty";if("string"!=typeof e.content||""===e.content.trim())return"content must not be empty";if(!p3(e.content))return"content contains unsupported HTML";let t=e.buttons;if(!Array.isArray(t)||t.length<1||t.length>3)return"buttons must contain between one and three buttons";let r=new Set;for(let e of t){if("object"!=typeof e||null===e)return"button must be an object";let t="role"in e?e.role:void 0,i=pY.find(e=>e===t);if(!i)return"button role is invalid";if(r.has(i))return"button roles must be unique";r.add(i);let n="text"in e?e.text:void 0;if("string"!=typeof n||""===n.trim())return"button text must not be empty"}return null}(e);i?r(Error(i)):x("bottomSheet",e,t,r)})),D=cl((e,t)=>{let r=u.current;r&&r.id===e&&"modal"===r.kind&&(r.resolve(t),u.current=null,n(t=>(null==t?void 0:t.id)===e?{...t,exiting:!0}:t),c.current=setTimeout(()=>{c.current=void 0,n(t=>(null==t?void 0:t.id)===e?null:t)},200))}),U=cl((e,t,r)=>{let i=u.current;i&&i.id===e&&D(e,{action:t,...void 0!==r?{content:r}:{}})}),q=cl((e,t)=>{let r=u.current;r&&r.id===e&&"actionSheet"===r.kind&&_(e,{tapIndex:t})}),$=cl((e,t)=>{let r=u.current;r&&r.id===e&&"bottomSheet"===r.kind&&_(e,{action:"buttonClick",role:t})}),B=cl(e=>{let t=u.current;if(t&&t.id===e.id)if("modal"===e.kind){if(!1===e.params.tapMaskToDismiss)return;D(e.id,{action:"mask"})}else if("bottomSheet"===e.kind){var r;if((null==(r=e.params.behavior)?void 0:r.dismissOnMaskTap)===!1)return;_(e.id,{action:"cancel",source:"mask"})}else _(e.id,void 0,Error("action sheet selection was cancelled"))});(0,iD.useEffect)(()=>()=>{var e;I(),y.current=null,c.current&&(clearTimeout(c.current),c.current=void 0);let t=u.current;t&&(t.reject(Error("simulator overlay was unmounted")),u.current=null),null==(e=g.current)||e.options.onCancel(),g.current=null},[]);let F=(0,iD.useMemo)(()=>({hideLoading:()=>o(!1),hideToast:C,showActionSheet:L,showBottomSheet:O,showLoading:()=>o(!0),showModal:P,showCommunication:e.show,showToast:E}),[C,L,O,P,E,e.show]);return{overlay:(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(p9,{imagePreview:t,interaction:i,loading:a,onActionSheetSelect:q,onBottomSheetSelect:$,onDismiss:B,onImagePreviewClose:R,onImagePreviewNavigate:j,onModalResult:U,scanner:f,toast:l}),e.overlay]}),imagePreviewController:M,presenter:F,scanCodePresenter:A}}function he(e){let{debugContext:t,sources:r}=e;return{launch_dir:t.launchDir,manifest_url:e.manifestUrl,app_id:e.appId,app_name:e.appName,mcp_endpoint:t.mcpEndpoint,mcp_original_endpoint:r.mcp.original,mcp_proxy_endpoint:r.mcp.proxy,simulator_endpoint:e.simulatorEndpoint,simulator_manifest_original_url:r.manifest.original,simulator_manifest_proxy_url:r.manifest.proxy,simulator_manifest_url:t.simulatorManifestUrl,simulator_skills_directory_original_url:r.skill.original,simulator_skills_index_proxy_url:r.skill.proxy,simulator_skills_index_url:t.simulatorSkillsIndexUrl,web_url:t.webUrl}}function ht(e){return(null==e?void 0:e.sandboxPhoneNumberUploaded)===void 0?void 0:!1===e.sandboxCsrRequired?e.sandboxPhoneNumberUploaded:void 0!==e.sandboxCsrUploaded?e.sandboxCsrUploaded&&e.sandboxPhoneNumberUploaded:void 0}function hr(e){return(null==e?void 0:e.raw)??{}}function hi(e,t){for(let r=e.length-1;r>=0;r-=1){let i=e[r].payload;if((null==i?void 0:i.event)===t)return i}}function hn(e,t,r){return!e||function(e,t){if(!e)return!1;try{return new URL(e,"http://localhost").pathname===t}catch{return!1}}(e,r)&&!t?"":e}function ha(e,t,r){let i=new Set(["missing","fetch_started","load_started","fetch_failed","load_failed","fetch_succeeded","loaded","empty"].map(e=>`simulator_${t}_${e}`)),n=e.map(e=>e.payload).findLast(e=>i.has(e.event)),a=(null==n?void 0:n.event)||"",s=function(){for(var e=arguments.length,r=Array(e),i=0;i<e;i++)r[i]=arguments[i];return r.some(e=>a===`simulator_${t}_${e}`)};if(n&&s("fetch_succeeded","loaded")){let e="skill"===t&&Array.isArray(n.skill_paths)?n.skill_paths.filter(Boolean).map(e=>e.startsWith("./")?e:`./${e}`):[];return{bytes:n.bytes??n.skill_length??n.skills_length,detail:n.url||r,details:e.length>0?e:void 0,label:"已加载",tone:"success"}}return s("empty")?{detail:r||"未配置",label:"空内容",tone:"muted"}:s("missing")||!r?{detail:r,label:"未配置",tone:"muted"}:n&&s("fetch_failed","load_failed")?{detail:n.error||n.url||r,label:"加载失败",tone:"error"}:n&&s("fetch_started","load_started")?{detail:n.url||r,label:"加载中",tone:"pending"}:{detail:r,label:"检查中",tone:"pending"}}function hs(e){return"string"==typeof e?e.trim():e.name||e.id||""}function ho(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return t.map((e,t)=>0===t?e.replace(/\/+$/g,""):e.replace(/^\/+|\/+$/g,"")).filter(Boolean).join("/")}function hl(e,t,r,i){if(!e)return"";if(i.startsWith(`${t}/`)){let e=i.replace(/\.web\.bundle$/g,"").replace(/\.bundle$/g,"").replace(/\.template\.js$/g,"").replace(/\.js$/g,"");return ho("src",/\.(tsx|ts|jsx|js)$/.test(e)?e:`${e}.tsx`)}return!r||r.startsWith("__")?"":ho("src",t,r,"index.tsx")}function hd(e){var t,r,i,n,a;let s,o,l,d,u,c,p,h,m,g,f,{context:v,events:y,manifest:b,pages:w=[],widgets:_}=e,S=(null==v?void 0:v.launchDir)||"",x=(null==v?void 0:v.mcpEndpoint)||(null==v?void 0:v.mcpProxyEndpoint)||"",I=(null==v?void 0:v.mcpOriginalEndpoint)||(null==(o=hr(b).mcp_server)?void 0:o.end_point)||(null==o?void 0:o.endpoint)||(null==o?void 0:o.url)||(null==o?void 0:o.mcp_endpoint)||"",k=(null==v?void 0:v.mcpProxyEndpoint)||(null==v?void 0:v.mcpEndpoint)||"",C=(null==v?void 0:v.simulatorManifestOriginalUrl)||"",E=(null==v?void 0:v.simulatorManifestProxyUrl)||(null==v?void 0:v.simulatorManifestUrl)||"",N=(null==v?void 0:v.simulatorManifestRelativePath)||"",T=(null==v?void 0:v.simulatorBusinessTemplatesOriginalUrl)||"",A=(null==v?void 0:v.simulatorBusinessTemplatesRelativePath)||"",M=(null==v?void 0:v.simulatorManifestUrl)||(null==v?void 0:v.simulatorManifestProxyUrl)||"",R=(null==v?void 0:v.simulatorSkillsDirectoryOriginalUrl)||(null==v?void 0:v.simulatorSkillsIndexOriginalUrl)||"",j=(null==v?void 0:v.simulatorSkillsIndexProxyUrl)||(null==v?void 0:v.simulatorSkillsIndexUrl)||"",P=(null==v?void 0:v.simulatorSkillsDirectoryRelativePath)||"",L=(null==v?void 0:v.simulatorSkillsIndexUrl)||(null==v?void 0:v.simulatorSkillsIndexProxyUrl)||"",O=hn(M,C,"/__simulator_manifest/manifest.yaml"),D=hn(L,R,"/__simulator_skills/index.json"),U=hn(x,(null==v?void 0:v.mcpOriginalEndpoint)||"","/__mcp_proxy"),q=function(e){let t=new Set;for(let r of e){let e=r.payload;for(let r of e.tools??[]){let e=hs(r);e&&t.add(e)}for(let r of e.mcp_servers??[])for(let e of r.tools??[]){let r=hs(e);r&&t.add(r)}}return[...t]}(y),$=function(e){let t=new Map,r=function(e,r){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",n="string"==typeof r?r:r.widget_id||r.widgetId||r.widget,a="string"==typeof r?i:r.entity_type||r.entityType||r.entity||i;e&&n&&t.set(`${e}:${n}:${a}`,{entityType:a,toolName:e,widgetId:n})},i=hr(e);for(let[e,t]of Object.entries(i.tool_card_binding??{}))r(e,t);for(let[e,t]of Object.entries(i.entities??{})){let i=t.entity_type||t.entityType||e;for(let[e,n]of Object.entries(t.tool_card_binding??{}))r(e,n,i)}return[...t.values()]}(b),B={manifest:ha(y,"manifest",O),mcp:(l=hi(y,"local_mcp_missing"),d=hi(y,"local_mcp_tools_load_started"),u=hi(y,"local_mcp_tools_load_failed"),c=hi(y,"local_mcp_tools_loaded"),p=hi(y,"client_tools_resolved"),h=hi(y,"client_tools_empty"),c?{detail:c.mcp_endpoint||U,label:"已连接",tone:"success"}:u?{detail:u.error||u.mcp_endpoint||U,label:"连接失败",tone:"error"}:p?{detail:`${p.tool_count??0} tools`,label:"客户端工具",tone:"success"}:h?{detail:"manifest.yaml 未声明 tools",label:"无客户端工具",tone:"muted"}:l||!U?{detail:U,label:"未配置",tone:"muted"}:d?{detail:d.mcp_endpoint||U,label:"连接中",tone:"pending"}:{detail:U,label:"检查中",tone:"pending"}),skill:ha(y,"skill",D)},F=!!O||"success"===B.manifest.tone,z=!!D||"success"===B.skill.tone,W=!!U||"success"===B.mcp.tone,H={businessTemplates:T?{detail:A||T,label:"已加载",tone:"success"}:{detail:"",label:"未配置",tone:"muted"},manifest:{...B.manifest,detail:N||B.manifest.detail},mcp:B.mcp,skill:{...B.skill,detail:P||B.skill.detail}};return{appId:(m=hr(b),(null==b?void 0:b.appId)||m.appId||m.app_key||(null==(t=m.applet)?void 0:t.appletId)||""),appName:(g=hr(b),(null==b?void 0:b.name)||g.name||g.app_name||(null==(r=g.applet)?void 0:r.name)||""),context:{launchDir:function(e,t){if(!t||!e.startsWith(t))return e;let r=e.slice(t.length);return""===r||/^[\\/]/.test(r)?`~${r.replaceAll("\\","/")}`:e}(S,(null==v?void 0:v.homeDir)||"")},mcpTools:q,pages:(i=b,f=(null==(s=function(e,t){if(t)return e.find(e=>t.startsWith("/")?e.path===t:e.id===t)}(n=w,null==(a=hr(i).applet)?void 0:a.appletEntry)??n.find(e=>"index"===e.id||"/pages/index"===e.path||"/pages/index/index"===e.path)??n[0])?void 0:s.path)||"",w.map(e=>({entry:hl(S,"pages",e.path.slice(1).replace(/^pages\//,"").replace(/\/index$/,""),e.entry||""),isHome:!!f&&e.path===f,name:e.name||e.title||"",pageId:e.id,path:e.path}))),resources:H,sources:{manifest:{original:F?C:"",proxy:F?E||M:""},mcp:{original:W?I:"",proxy:W?k:""},skill:{original:z?R:"",proxy:z?j||L:""}},widgets:function(e,t,r){let i=new Map;for(let e of t){let t=i.get(e.widgetId)??[];t.push(e.toolName),i.set(e.widgetId,t)}return e.filter(nY).map(e=>({boundTools:i.get(e.widgetId)??[],entry:hl(r,"widgets",e.widgetId,e.entry||""),name:e.name||"",widgetId:e.widgetId}))}(_,$,S)}}function hu(e,t,r){return!!(e&&t&&t!==r&&e.sourceTarget===t)}function hc(e,t){return{pages:e.pages.map(e=>{let{isHome:t,name:r,pageId:i,path:n}=e;return{isHome:t,name:r,pageId:i,path:n}}),widgets:e.widgets.map(e=>{let{name:t,widgetId:r}=e;return{name:t,widgetId:r}}),currentTarget:t}}function hp(e,t,r){let i=0,n=!1,a=()=>{n=!0},s=e=>{if(i>=5e3)return n=!0,null;i+=1;let t=e.children.map(s).filter(e=>null!==e);return{uid:e.id,type:e.type,name:"text"===e.type?"#text":uF(e),attributes:"element"===e.type?u$(e).map(e=>{var t;return{name:e.name,value:(t=e.value,t.length<=500?t:(a(),`${t.slice(0,499)}…`))}}):[],children:t,accessibility:e.accessibility,text:e.textContent}};return{root:e?s(e):null,selectedUid:t,nodeCount:i,truncated:n,sourceTarget:r,updatedAtMs:Date.now()}}let hh={message:"未上传",tone:"muted"},hm={message:"已上传",tone:"success"},hg=hh,hf=new Set;function hv(e){return hf.add(e),()=>hf.delete(e)}function hy(){return hg}function hb(e){for(let t of(hg=e,hf))t()}function hw(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:hh.message;hb({message:e,tone:"muted",updatedAtMs:Date.now()})}function h_(e){let t=(0,iD.useSyncExternalStore)(hv,hy,hy);return(0,iD.useEffect)(()=>{void 0!==e&&hb(e?hm:hh)},[e]),t}let hS={message:"可用",tone:"success"},hx={message:"不可用",tone:"error"},hI=hS,hk=new Set;function hC(e){return hk.add(e),()=>hk.delete(e)}function hE(){return hI}function hN(e){for(let t of(hI=e,hk))t()}function hT(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0],t=(0,iD.useSyncExternalStore)(hC,hE,hE);return(0,iD.useEffect)(()=>{hN(e?hS:hx)},[e]),t}function hA(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("open-location-settings"===e.kind)return na("location"),!0;if("clear-sandbox-bridge-logs"===e.kind){if(!t.onClearLogs){var r;return null==(r=t.onMessage)||r.call(t,"服务端日志接口不可用",!0),!0}return t.onClearLogs().then(()=>{var e;return null==(e=t.onMessage)?void 0:e.call(t,"服务端交互日志已清空")}).catch(e=>{var r;return null==(r=t.onMessage)?void 0:r.call(t,e.message,!0)}),!0}return"recreate-sandbox-session"===e.kind?(hN({message:"正在重建",tone:"pending",updatedAtMs:Date.now()}),lQ({csrPem:e.csrPem,phoneNum:e.phoneNum}).then(r=>{var i,n,a,s,o;let l=(null==(i=r.data)?void 0:i.business_info_uploaded)===!0;l?hb({message:"已上传",tone:"success",updatedAtMs:Date.now()}):hw(),hN({message:"已重建",tone:"success",updatedAtMs:Date.now()}),l?null==(s=t.onUpdated)||s.call(t):null==(o=t.onRecreated)||o.call(t),null==(a=t.onMessage)||a.call(t,`调试会话已重建${l?`,${e.csrPem.trim()?"手机号和证书":"手机号"}已自动上传`:""}:${(null==(n=r.data)?void 0:n.sandbox_session_id)??""}`)}).catch(e=>{var r,i;let n=`重建调试会话失败:${e.message}`;hw(),hN({errorMessage:n,message:"重建失败",tone:"error",updatedAtMs:Date.now()}),null==(r=t.onRecreated)||r.call(t),null==(i=t.onMessage)||i.call(t,n,!0)}),!0):"update-sandbox-business-info"===e.kind&&(hb({message:"正在上传...",tone:"pending",updatedAtMs:Date.now()}),lX({csrPem:e.csrPem,phoneNum:e.phoneNum}).then(()=>{var e,r;hb({message:"上传成功",tone:"success",updatedAtMs:Date.now()}),null==(e=t.onUpdated)||e.call(t),null==(r=t.onMessage)||r.call(t,"上传成功")}).catch(e=>{var r;let i=e&&"object"==typeof e&&"logId"in e&&"string"==typeof e.logId?e.logId:"";hb({errorMessage:e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message?e.message:"",message:"上传失败",tone:"error",updatedAtMs:Date.now()}),console.error("Sandbox business info upload failed",e,{logId:i}),null==(r=t.onMessage)||r.call(t,"上传失败",!0)}),!0)}function hM(e){let[t,r]=(0,iD.useState)(),i=(0,iD.useRef)(),n=(0,iD.useRef)(),a=cl((e,t)=>{if(n.current===e.commandId)return!1;n.current=e.commandId;let a={previousTarget:t,command:e};return i.current=a,r(a),!0}),s=cl((t,n)=>{var a;(null==(a=i.current)?void 0:a.command.commandId)===t&&(i.current=void 0,r(void 0),null==e||e(t,n))});return{accept:a,pending:t,pendingRef:i,report:s}}let hR="u"<typeof window?iD.useEffect:iD.useLayoutEffect;function hj(e,t){let[r,i]=(0,iD.useState)(ss),[n,a]=(0,iD.useState)("fit"),s=(0,iD.useRef)(),o=(0,iD.useMemo)(()=>su(r),[r]),l=sl.find(e=>e.key===n)??sl.find(e=>"fit"===e.key)??sl[0],d="fit"===l.key,{fitScale:u,setRuntimeShellRef:c}=function(e){let{deviceHeight:t,deviceWidth:r,enabled:i}=e,[n,a]=(0,iD.useState)(.88),s=(0,iD.useRef)(null),o=(0,iD.useRef)(null),l=(0,iD.useCallback)(()=>{let e=s.current;if(!e)return;let i=getComputedStyle(e),n=Number.parseFloat(i.paddingLeft)+Number.parseFloat(i.paddingRight),o=Number.parseFloat(i.paddingTop)+Number.parseFloat(i.paddingBottom),l=Math.floor(1e3*Math.max(.1,Math.min(1,(e.clientWidth-n-12)/r,(e.clientHeight-o-12)/t)))/1e3;a(e=>Math.abs(e-l)>.001?l:e)},[t,r]),d=(0,iD.useCallback)(e=>{var t;if(null==(t=o.current)||t.disconnect(),o.current=null,s.current=e,!e||!i)return;let r=new ResizeObserver(l);r.observe(e),o.current=r,l()},[i,l]);return hR(()=>{i&&l()},[i,l]),hR(()=>()=>{var e;null==(e=o.current)||e.disconnect()},[]),{fitScale:n,setRuntimeShellRef:d}}({deviceHeight:o.height,deviceWidth:o.width,enabled:d}),p=d?u:l.scale,h=d?"fit":"fixed",m={"--wsd-runtime-width":`${o.width}px`,"--wsd-runtime-height":`${o.height}px`,"--wsd-runtime-layout-width":`${o.width*p}px`,"--wsd-runtime-layout-height":`${o.height*p}px`,"--wsd-runtime-radius":`${o.radius}px`,"--wsd-runtime-home-indicator-display":o.homeIndicator?"block":"none","--wsd-runtime-safe-area-bottom":`${o.safeArea.bottom}px`,"--wsd-runtime-scale":p};return(0,iD.useEffect)(()=>{if((null==e?void 0:e.type)!=="set_viewport"||s.current===e.commandId)return;let n=`custom-${e.width}x${e.height}`;r!==n?i(n):(s.current=e.commandId,null==t||t(e.commandId,{ok:!0,result:{width:e.width,height:e.height}}))},[e,t,r]),{runtimeScaleMode:h,runtimeStyle:m,selectedDevice:o,selectedDeviceKey:r,selectedScaleKey:n,setRuntimeShellRef:c,setSelectedDeviceKey:i,setSelectedScaleKey:a}}function hP(e,t,r){let i=!(arguments.length>3)||void 0===arguments[3]||arguments[3];(0,iD.useEffect)(()=>{if(!e||!i)return;let n=setTimeout(()=>e.publishSnapshot(t,r),500);return()=>clearTimeout(n)},[e,i,t,r])}let hL={appEntries:[],entries:[],updatedAtMs:0};function hO(e,t){var r;return!t||e.traceId===t||(null==(r=e.trace)?void 0:r.trace_id)===t}function hD(e,t){var r;let{activeView:i,chromeDevToolsFrontendUrl:n,controlCommand:a,controlClientId:s,debugContext:o,onChromeDevToolsPanelChange:l,onActiveViewChange:d,onControlResult:u,onMessage:c,onNavigateToPage:p,onWidgetNavigateBack:h,onWidgetExitApp:m,apiEnvironment:g,showDebugTrace:f,connection:y,webSdkDebugger:b}=e,w=cg(b),x=(0,iD.useMemo)(()=>w.widgets.filter(nY),[w.widgets]),I=(0,iD.useRef)(null),k=(0,iD.useRef)(null),C=(0,iD.useRef)(null),E=(0,iD.useRef)(null),N=(0,iD.useRef)(null);!N.current&&"u">typeof document&&(N.current=document.createElement("div"));let[T,A]=(0,iD.useState)(0),M=cl(()=>k.current),[R,j]=(0,iD.useState)(null),[P,L]=(0,iD.useState)(!1),[O,D]=(0,iD.useState)(0),[U,q]=(0,iD.useState)(!1),[$,B]=(0,iD.useState)([]),[F,z]=(0,iD.useState)(hL),[W,H]=(0,iD.useState)(null),[V,G]=(0,iD.useState)(null),[J,K]=(0,iD.useState)(null),[Z,X]=(0,iD.useState)(),[Y,Q]=(0,iD.useState)(0),[ee,et]=(0,iD.useState)(0),er=cw(),ei=p7(),en=pZ(),ea=(null==o?void 0:o.sandboxSessionAvailable)!==!1,es=ht(o),[eo,el]=(0,iD.useState)(!0!==es),ed=h_(es),eu=hT(ea),{bridgeLogs:ec,clearBridgeLogs:ep}=cB(),eh=(0,iD.useRef)(null),em=(0,iD.useMemo)(()=>E.current,[T]),{accept:eg,pending:ef,pendingRef:ev,report:ey}=hM(u),eb=(0,iD.useRef)(),ew=(0,iD.useRef)(new Map),e_=(0,iD.useRef)(new Map),eS=(0,iD.useRef)(0),{runtimeScaleMode:ex,runtimeStyle:eI,selectedDevice:ek,selectedDeviceKey:eC,setRuntimeShellRef:eE,setSelectedDeviceKey:eN}=hj(a,u),eT=(0,iD.useRef)(eC),eA=(null==(r=w.widgetSelection)?void 0:r.item.widgetId)??"",eM=(0,iD.useRef)(eA),eR=w.simulator,ej=(0,iD.useRef)(eR.toolCalls),eP=!!w.widgetSelection&&"streaming"!==eR.streamStatus&&!U,eL=(0,iD.useMemo)(()=>({...sd,device:ek,density:ek.density,label:ek.label,width:Math.max(1,ek.width-38)}),[ek]);(0,iD.useEffect)(()=>{ej.current=eR.toolCalls},[eR.toolCalls]);let eO=cl(e=>{let t=function(e,t){var r;if(!rP(e))return{};let i=e.source_tool_call_id,n=i?t.find(e=>e.toolCallId===i):void 0;if(!n)return e;let a=e.trace??{};return{...e,request_id:e.request_id||n.requestId,trace_id:e.trace_id||a.trace_id||(null==(r=n.trace)?void 0:r.trace_id)}}(e,ej.current),r=++eS.current,i={display:ah(t),id:`trace-${r}`,order:r,payload:t,timestamp:Date.now()};B(e=>[...e,i].slice(-200))}),eD=cl(()=>{B([])}),eU=(0,iD.useMemo)(()=>[...eR.traceEvents.map((e,t)=>({event:e,sortOrder:e.order??t})),...$.map((e,t)=>({event:e,sortOrder:e.order??eR.traceEvents.length+t}))].sort((e,t)=>e.event.timestamp-t.event.timestamp||e.sortOrder-t.sortOrder||e.event.id.localeCompare(t.event.id)).map(e=>{let{event:t}=e;return t}),[$,eR.traceEvents]),eq=(0,iD.useMemo)(()=>({...o,manifestUrl:w.manifestUrl,simulatorEndpoint:eR.endpoint}),[o,eR.endpoint,w.manifestUrl]),e$=(0,iD.useMemo)(()=>hd({context:eq,events:eU,manifest:w.manifest,pages:w.pages,widgets:w.widgets}),[eU,eq,w.manifest,w.pages,w.widgets]),eB=e$.appId,eF=e$.appName,ez=(0,iD.useMemo)(()=>({type:"widget",appId:eB,appName:eF,widgetId:eA,viewport:{key:ek.key,label:ek.label,width:Math.max(1,ek.width-38),height:ek.height,density:ek.density}}),[eB,eF,ek,eA]),eW=(0,iD.useMemo)(()=>hc(e$,"card"===t&&w.widgetSelection?ez:null==J?void 0:J.targetInfo),[t,J,ez,e$.pages,e$.widgets,w.widgetSelection]),eH=!!(ef&&hu(W,em,ef.previousTarget)&&"card"===t&&eA===ef.command.widgetId),eV=(0,iD.useMemo)(()=>{let e="card"===t?em:null==J?void 0:J.target,r="card"===t?ez:null==J?void 0:J.targetInfo;return e&&r&&(null==W?void 0:W.sourceTarget)===e?{target:r,root:W.root,nodeCount:W.nodeCount,selectedUid:W.selectedUid,truncated:W.truncated,updatedAtMs:W.updatedAtMs}:void 0},[t,J,ez,W,em]),eG=(0,iD.useMemo)(()=>({exported_at:new Date().toISOString(),client_id:s,command_id:eH?null==ef?void 0:ef.command.commandId:void 0,context:{...he({appId:eB,appName:e$.appName,debugContext:eq,manifestUrl:w.manifestUrl,simulatorEndpoint:eR.endpoint,sources:e$.sources}),widget_id:eA},render_targets:eW,runtime_snapshot:eV,simulator:{stream_status:eR.streamStatus,active_request_id:eR.activeRequestId,active_reply_message_id:eR.activeReplyMessageId,error:eR.error,answer_finish:eR.answerFinish,messages:eR.messages,tool_calls:eR.toolCalls,trace_events:eR.traceEvents},runtime_console:{app:{entries:F.appEntries,updated_at_ms:F.updatedAtMs},widget:{entries:F.entries,updated_at_ms:F.updatedAtMs}},widget_runtime_trace_events:$}),[$,e$.sources.manifest.original,e$.sources.manifest.proxy,e$.sources.mcp.original,e$.sources.mcp.proxy,e$.sources.skill.original,e$.sources.skill.proxy,eq.launchDir,eq.mcpEndpoint,eq.simulatorManifestUrl,eq.simulatorSkillsIndexUrl,eq.webUrl,F,eA,eR,eB,s,eH,null==ef?void 0:ef.command.commandId,eW,w.manifest.name,w.manifestUrl,eV]),eJ=cl(e=>{b.approveSimulatorToolCall(e).catch(e=>{null==c||c(e.message,!0)})}),eK=cl(e=>{b.rejectSimulatorToolCall(e).catch(e=>{null==c||c(e.message,!0)})}),eZ=cl(e=>{"clear-trace-filter"===e.kind?X(void 0):hA(e,{onClearLogs:ep,onMessage:c,onRecreated:()=>el(!0),onUpdated:()=>el(!1)})||("approve-tool-call"===e.kind||"reject-tool-call"===e.kind)&&("approve-tool-call"===e.kind?eJ:eK)(e.toolCallId)}),eX=cl(e=>{X(t=>t===e?void 0:e)}),eY=cl(()=>{Q(e=>Math.max(e,ee)+1)});(0,iD.useEffect)(()=>{"success"===ed.tone&&el(!1)},[ed.tone]),(0,iD.useEffect)(()=>{void 0!==es&&el(!es)},[es]);let eQ=cl(()=>{et(e=>Math.max(e,Y)+1)}),e0=cl(()=>{na("location")}),e1=cl(e=>{e.stopPropagation(),el(!1)}),e2=Math.max(Y,ee);(0,iD.useEffect)(()=>{Z&&!eR.messages.some(e=>hO(e,Z))&&X(void 0)},[Z,eR.messages]);let e3=(0,iD.useMemo)(()=>f?eU:eU.filter(e=>{var t;return!(null==(t=e.display)?void 0:t.debugOnly)}),[eU,f]),e4="conversation"===t?V:em,e5=cl(e=>{G(e)}),e6=()=>{for(let e of eR.messages.slice().reverse())for(let t of e.blocks.slice().reverse()){if("card"!==t.type)continue;let r=e_.current.get(c2(e,t));if(null==r?void 0:r.target.isConnected)return r}let e=Array.from(e_.current.values()).reverse();return e.find(e=>e.target.isConnected)??e[0]??null},e8=cl((e,t,r)=>{if(t){let i=eR.messages.slice().reverse().flatMap(t=>{let r=t.blocks.find(r=>"card"===r.type&&c2(t,r)===e);return(null==r?void 0:r.type)==="card"?[{card:r.card,message:t}]:[]})[0],n={target:t,targetInfo:{...ez,viewport:{...ez.viewport,width:r??ez.viewport.width},appId:null==i?void 0:i.card.app_id,widgetId:null==i?void 0:i.card.widget_id,cardId:null==i?void 0:i.card.card_id,requestId:null==i?void 0:i.message.requestId}};e_.current.set(e,n),K(e6());return}let i=e_.current.get(e);e_.current.delete(e),K(e=>i&&(null==e?void 0:e.target)===i.target?e6():e)}),e9=cl((e,t)=>{var r;return(null==(r=Array.from(e_.current.values()).reverse().find(r=>{let i,{target:n}=r;return n.isConnected&&(i=n.getBoundingClientRect()).width>0&&i.height>0&&e>=i.left&&e<=i.right&&t>=i.top&&t<=i.bottom}))?void 0:r.target)??null}),e7=(0,iD.useMemo)(()=>iI(e3,{debug:f,messages:eR.messages,traceId:Z}),[Z,f,eR.messages,e3]),te=(0,iD.useMemo)(()=>Z?eR.toolCalls.filter(e=>hO(e,Z)):eR.toolCalls,[Z,eR.toolCalls]),tt=(0,iD.useMemo)(()=>ix(eG,{debug:f,traceId:Z}),[Z,f,eG]),tr=(0,iD.useMemo)(()=>iw(tt),[tt]),ti=(0,iD.useMemo)(()=>({debugData:e$,events:e7,logSnapshot:tt,logSnapshotText:tr,sandbox:{available:ea,csrRequired:(null==o?void 0:o.sandboxCsrRequired)!==!1,input:{csrPem:(null==o?void 0:o.sandboxCsrPem)??"",phoneNum:(null==o?void 0:o.sandboxPhoneNum)??""},logs:ec,businessInfoStatus:ed,sessionStatus:eu},showDebugTrace:f,traceFilterId:Z??"",traceSurface:"conversation",toolCalls:te,updatedAtMs:Date.now()}),[e$,te,e7,tt,tr,ec,ea,ed,eu,null==o?void 0:o.sandboxCsrRequired,Z,f]);hP(y,eG,W,!i||i===t),(0,iD.useEffect)(()=>{if((null==a?void 0:a.type)==="render_widget"&&eg(a,em))try{b.selectWidget(a.widgetId)}catch(e){ey(a.commandId,{ok:!1,error:{code:"TARGET_NOT_FOUND",message:e.message}})}},[eg,a,ey,b,em]),(0,iD.useEffect)(()=>{ef&&eH&&ey(ef.command.commandId,{ok:!0,target:ez,snapshot:iS(eG)})},[ez,eH,ef,ey,eG]);let tn=(0,iD.useMemo)(()=>{let e=(e,t,r)=>{var i;if("AppletBridgeModule"===r&&("postMessage"===e||"postMessageSync"===e)&&rP(i=t)&&"call"===i.type&&"string"==typeof i.name&&"number"==typeof i.callbackId){if("mind.getAgentTraceSwitch"===t.name)return pG(t,{value:!0});if("mind.reportAgentTraceEvent"===t.name)return eO(t.params??{}),pG(t)}};return(t,r,i,n)=>{if("AppletBridgeModule"===i&&"postMessage"===t&&v(r)&&"doubao.navigateBack"===r.name)return Promise.resolve().then(async()=>await (null==h?void 0:h(r.params??{}))?_(r,{}):S(r,"No host Page is available to navigate back",102)).catch(e=>S(r,e instanceof Error?e.message:String(e),102));if("AppletBridgeModule"===i&&"postMessage"===t&&v(r)&&["doubao.navigateTo","doubao.redirectTo","doubao.reLaunch"].includes(r.name)){let e=r.params;if(!rP(e)||"string"!=typeof e.url||!e.url.trim())return S(r,"invalid url",104);let t=e.url;try{tO({url:t},w.manifest)}catch(e){return S(r,e instanceof Error?e.message:String(e),104)}if(!p)return S(r,"No host page presenter is available",102);let i="doubao.navigateTo"===r.name?"navigate":"doubao.redirectTo"===r.name?"redirect":"relaunch";return Promise.resolve().then(()=>p({url:t,routeMode:i})).then(e=>!1===e?S(r,"Opening a Page from the chat card failed",102):(null==c||c(`卡片 ${r.name.slice(7)}: ${t}`),_(r,{})),e=>S(r,e instanceof Error?e.message:String(e),102))}return e(t,r,i,n)}},[eO,c,p,h,w.manifest]),ta=(0,iD.useCallback)(e=>dI({appId:eB,appIcon:w.manifest.iconSrc,appName:eF,exitAppFromWidget:m,declaredScopes:Object.keys(w.manifest.raw.permissions??{}),baseAPIRegistry:null==g?void 0:g.apiRegistry,imagePreviewController:ei.imagePreviewController,onCustomLoginNavigate:e=>null==p?void 0:p({url:e}),openPageFromWidget:async e=>{let{url:t}=e;if(!1===(!!p&&await p({url:t,routeMode:"relaunch"})))throw Error("Opening a Page from the chat card failed")},sendFollowUpMessage:e=>{let{content:t}=e;return b.sendSimulatorFollowUpMessage(t)},multiMediaBroadcastContainer:e,scanCodePresenter:ei.scanCodePresenter,showSandboxCashier:er.showCashier,uiPresenter:ei.presenter,showSimulatorPermission:en.showPermission,showSimulatorPermissionSettings:en.showSettings,vibrationContainer:C.current}),[g,eB,eF,p,m,er.showCashier,ei.imagePreviewController,ei.scanCodePresenter,ei.presenter,en.showPermission,en.showSettings,w.manifest.iconSrc,w.manifest.raw.permissions,b]),ts=(0,iD.useMemo)(()=>ta(),[ta]),to=cl(e=>{E.current!==e&&(E.current=e,A(e=>e+1)),j(null)});(0,iD.useEffect)(()=>{let e=I.current;if(!e)return;let t=ta(e),r=new cs({container:e,fileSystemNamespace:null==o?void 0:o.fileSystemNamespace,nativeModulesCallHandler:tn,webSdkDebugger:b,onError:e=>{null==c||c(`Widget runtime error ${eA}: ${e.message}`,!0)},apiEnvironment:t});eh.current=r;let i=r.subscribeTarget(to);return to(r.getCurrentTarget()),()=>{i(),r.destroy(),eh.current=null,to(null)}},[t,ta,null==o?void 0:o.fileSystemNamespace,tn,c,eA,to,b]);let tl=cl(async function(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=eh.current,i=t.widgetId??(null==(e=w.widgetSelection)?void 0:e.item.widgetId);if(!r||!i)return!1;let n=t.initData??ew.current.get(i);void 0!==t.initData&&ew.current.set(i,t.initData),eD();try{return await r.render({widgetId:i,initData:n,viewport:{...sd,device:ek,density:ek.density,label:ek.label,width:Math.max(1,ek.width-38)}}),eT.current=eC,L(!0),null==c||c(`Rendered widget ${i}`),!0}catch(t){L(!1),null==c||c(t.message,!0);let e=ev.current;return(null==e?void 0:e.command.widgetId)===i&&ey(e.command.commandId,{ok:!1,error:{code:"RENDER_FAILED",message:t.message}}),!1}});(0,iD.useEffect)(()=>{let e=ev.current;e&&"card"===t&&eh.current&&eb.current!==e.command.commandId&&(eb.current=e.command.commandId,tl({widgetId:e.command.widgetId,initData:e.command.structuredContent}))},[t,ef,tl]),(0,iD.useEffect)(()=>{var e,t;let r=eM.current;if((eM.current=eA,r!==eA)&&(null==(e=ev.current)?void 0:e.command.widgetId)!==eA){if(w.widgetSelection)return void tl();eD(),L(!1),null==(t=eh.current)||t.clear()}},[eD,tl,eA,w.widgetSelection]),(0,iD.useEffect)(()=>{!ev.current&&P&&eT.current!==eC&&tl()},[P,tl,eC]);let td=cl(async()=>{if(!eP)return!1;q(!0);try{if(await b.reloadResources(),D(e=>e+1),P&&!await tl())return!1;return null==c||c("已刷新卡片资源"),!0}catch(e){return null==c||c(e.message,!0),!1}finally{q(!1)}});return{activeView:t,fileSystemNamespace:null==o?void 0:o.fileSystemNamespace,appendAgentTraceEvent:eO,canReloadResources:eP,cardReloadKey:O,chromeDevToolsFrontendUrl:n,controlCommand:a,conversationAPIEnvironment:ts,conversationConsoleTarget:N.current,conversationControlTarget:J,conversationWidgetViewport:eL,currentDebugAppId:eB,currentDebugAppName:eF,debugState:ti,devtoolsTarget:e4,devToolsPanelId:ee===e2&&e2>0?"wsd-sandbox":Y>0?"wsd-trace":void 0,getRuntimeFrame:M,handleDebugAction:eZ,handleGrantingSheetTargetChange:e5,handleInspectableCardTargetChange:e8,handleQuerySubmit:eY,handleSandboxLoginHintClick:eQ,handleSandboxLoginHintClose:e1,handleSandboxLocationConfigOpen:e0,handleTraceMessageSelect:eX,hasRenderedPreview:P,highlightRect:R,latestDevToolsPanelRequestId:e2,nativeModulesCallHandler:tn,onActiveViewChange:d,onChromeDevToolsPanelChange:l,onControlResult:u,onMessage:c,onNavigateToPage:p,reloadResources:td,renderSelectedWidget:tl,resolveConversationInspectTarget:e9,runtimeFrameRef:k,runtimeFrameScaleBoxRef:C,runtimeScaleMode:ex,runtimeStyle:eI,runtimeSnapshotTarget:"conversation"===t?(null==J?void 0:J.targetInfo)??ez:ez,runtimeTargetRef:I,sandboxCashier:er,simulatorUI:ei,simulatorPermissionPrompt:en,simulatorSkillsIndexUrl:null==o?void 0:o.simulatorSkillsIndexUrl,selectedDeviceKey:eC,selectedTraceId:Z,selectedWidgetId:eA,setHighlightRect:j,setRuntimeConsoleSnapshot:z,setRuntimeDomSnapshot:H,setSelectedDeviceKey:eN,setRuntimeShellRef:eE,sandboxLoginAvailable:ea,showSandboxLoginHint:eo,simulatorState:eR,state:w,visibleWidgets:x,webSdkDebugger:b}}function hU(e){let t=hD(e,"conversation"),{manifest:r,manifestUrl:i,resourceUrlVersion:n}=t.state,a=(0,iD.useMemo)(()=>{let e=new tT({resolveManifestUrl:()=>i,resourceUrlVersion:n});return e.setPackage({manifest:r,manifestUrl:String(i)}),e},[r,i,n]);return(0,s.jsx)(pV,{runtime:t,children:(0,s.jsx)(cy,{highlightRect:t.highlightRect,overlay:(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("section",{"aria-label":"对话",className:"wsd-widget-phone-scroll is-conversation",children:(0,s.jsx)(pa,{messageInputDisabled:e.messageInputDisabled,packageManager:a,apiEnvironment:t.conversationAPIEnvironment,appId:t.currentDebugAppId,fileSystemNamespace:t.fileSystemNamespace,cardReloadKey:t.cardReloadKey,controlCommand:t.controlCommand,nativeModulesCallHandler:t.nativeModulesCallHandler,onControlResult:t.onControlResult,onMessage:t.onMessage,onGrantingSheetTargetChange:t.handleGrantingSheetTargetChange,onInspectableCardTargetChange:t.handleInspectableCardTargetChange,onNavigateToPage:t.onNavigateToPage,onQuerySubmit:t.handleQuerySubmit,onSandboxLocationConfigOpen:t.handleSandboxLocationConfigOpen,onTraceEvent:t.appendAgentTraceEvent,onTraceMessageSelect:t.handleTraceMessageSelect,runtimeConsoleTarget:t.conversationConsoleTarget,sandboxLoginHint:t.showSandboxLoginHint?{available:t.sandboxLoginAvailable,onClose:t.handleSandboxLoginHintClose,onOpen:t.handleSandboxLoginHintClick}:void 0,selectedTraceId:t.selectedTraceId,simulator:t.simulatorState,webSdkDebugger:t.webSdkDebugger,widgetViewport:t.conversationWidgetViewport,widgets:t.state.widgets})}),t.simulatorUI.overlay,t.sandboxCashier.cashier?(0,s.jsx)(cb,{cashier:t.sandboxCashier.cashier,onCancel:t.sandboxCashier.cancelCashier,onConfirm:t.sandboxCashier.confirmCashier}):null,t.simulatorPermissionPrompt.overlay]}),runtimeFrameRef:t.runtimeFrameRef,runtimeFrameScaleBoxRef:t.runtimeFrameScaleBoxRef,runtimeScaleMode:t.runtimeScaleMode,runtimeShellRef:t.setRuntimeShellRef,runtimeStyle:t.runtimeStyle})})}var hq=r(18017),h$=r(29912),hB=r(80405);function hF(e){let{actionDisabled:t,actionLabel:r,JsonEditorComponent:i,label:n,minHeight:a=96,onAction:o,onChange:l,onMessage:d,value:u}=e;return(0,s.jsxs)("form",{className:"wsd-debug-inputs",onSubmit:function(e){e.preventDefault(),null==o||o()},children:[(0,s.jsxs)("div",{className:"wsd-debug-editor-block",children:[(0,s.jsxs)("div",{className:"wsd-editor-toolbar",children:[(0,s.jsx)("span",{className:"wsd-section-label",children:n}),(0,s.jsxs)("div",{className:"wsd-editor-actions",children:[(0,s.jsx)("button",{className:"wsd-button wsd-button-ghost",onClick:function(){try{l(JSON.stringify(sg("JSON",u),null,2)),null==d||d(`${n} formatted`)}catch(e){null==d||d(e.message,!0)}},type:"button",children:"格式化"}),(0,s.jsx)("button",{className:"wsd-button wsd-button-ghost",onClick:()=>{px(n,u,d)},type:"button",children:"复制"})]})]}),i?(0,s.jsx)(i,{ariaLabel:n,minHeight:a,onChange:l,value:u}):(0,s.jsx)("textarea",{"aria-label":n,className:"wsd-json-textarea",onChange:e=>l(e.currentTarget.value),spellCheck:!1,style:{minHeight:a},value:u})]}),r?(0,s.jsx)("div",{className:"wsd-debug-action-bar",children:(0,s.jsx)("button",{className:"wsd-button wsd-button-primary",disabled:t,type:"submit",children:r})}):null]})}function hz(){return{inputError:"",inputMode:"form",inputParams:{},inputText:"{}"}}function hW(e){return Array.isArray(e)?e.map(hW):rP(e)?Object.fromEntries(Object.entries(e).map(e=>{let[t,r]=e;return"type"===t&&"int"===r?[t,"integer"]:"type"===t&&"float"===r?[t,"number"]:[t,hW(r)]})):e}function hH(e){let{id:t,name:r,onChange:i,onError:n,type:a,value:o}=e,[l,d]=(0,iD.useState)(JSON.stringify(o??("array"===a?[]:{}),null,2));function u(e){try{let t=JSON.parse(e);if(!("array"===a?Array.isArray(t):rP(t)))throw Error(`expected a JSON ${a}`);i(t)}catch(e){n(`${r}: ${e.message}`)}}return(0,s.jsx)("textarea",{"aria-label":`参数 ${r}`,className:"wsd-schema-complex-input",id:t,onBlur:()=>u(l),onChange:e=>{let t=e.currentTarget.value;d(t),u(t)},spellCheck:!1,value:l})}function hV(e){let{onChange:t,schema:r,value:i}=e,n=(0,iD.useId)(),a=(0,iD.useRef)(new Map),o=rP(r.properties)?r.properties:{},l=new Set(Array.isArray(r.required)?r.required.filter(e=>"string"==typeof e):[]);function d(){return a.current.values().next().value??""}function u(e,r){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];n&&a.current.delete(e);let s={...i};void 0===r?delete s[e]:s[e]=r,t(s,d())}return 0===Object.keys(o).length?(0,s.jsx)("div",{className:"wsd-schema-empty-input",children:"无需输入参数"}):(0,s.jsx)("div",{className:"wsd-schema-input-form",children:Object.entries(o).map(e=>{let[r,o]=e,c=rP(o)?o:{},p=c.type||"string",h="string"==typeof c.description?c.description:"",m=Array.isArray(c.enum)?c.enum:void 0,g=i[r],f=`${n}-${r}`;return(0,s.jsxs)("label",{className:"wsd-schema-form-field",htmlFor:f,children:[(0,s.jsxs)("span",{className:"wsd-schema-form-field-title",children:[(0,s.jsx)("strong",{children:r}),l.has(r)?(0,s.jsx)("em",{children:"必填"}):null,(0,s.jsx)("small",{children:`${p}${m?" · enum":""}`})]}),h?(0,s.jsx)("span",{className:"wsd-schema-form-field-description",children:h}):null,m?(0,s.jsxs)("select",{"aria-label":`参数 ${r}`,id:f,onChange:e=>u(r,e.currentTarget.value?JSON.parse(e.currentTarget.value):void 0),value:void 0===g?"":JSON.stringify(g),children:[(0,s.jsx)("option",{value:"",children:"请选择"}),m.map(e=>(0,s.jsx)("option",{value:JSON.stringify(e),children:String(e)},JSON.stringify(e)))]}):"boolean"===p?(0,s.jsxs)("select",{"aria-label":`参数 ${r}`,id:f,onChange:e=>u(r,""===e.currentTarget.value?void 0:"true"===e.currentTarget.value),value:"boolean"==typeof g?String(g):"",children:[(0,s.jsx)("option",{value:"",children:"请选择"}),(0,s.jsx)("option",{value:"true",children:"true"}),(0,s.jsx)("option",{value:"false",children:"false"})]}):"null"===p?(0,s.jsxs)("select",{"aria-label":`参数 ${r}`,id:f,onChange:e=>u(r,"null"===e.currentTarget.value?null:void 0),value:null===g?"null":"",children:[(0,s.jsx)("option",{value:"",children:"请选择"}),(0,s.jsx)("option",{value:"null",children:"null"})]}):"array"===p||"object"===p?(0,s.jsx)(hH,{id:f,name:r,onChange:e=>u(r,e,!0),onError:e=>{a.current.set(r,e),t(i,d())},type:p,value:g}):(0,s.jsx)("input",{"aria-label":`参数 ${r}`,id:f,onChange:e=>{u(r,function(e,t){if(e)return"number"===t||"integer"===t?Number(e):e}(e.currentTarget.value,p))},step:"integer"===p?1:"any",type:"number"===p||"integer"===p?"number":"text",value:"string"==typeof g||"number"==typeof g?g:""})]},r)})})}function hG(e){let{heading:t,jsonLabel:r,minHeight:i=160,onChange:n,onMessage:a,schema:o,value:l}=e;return(0,s.jsxs)("div",{className:"wsd-schema-input-editor",children:[(0,s.jsxs)("div",{className:"wsd-schema-input-heading",children:[(0,s.jsx)("span",{children:t}),(0,s.jsx)("button",{className:"wsd-button wsd-button-ghost",onClick:function(){if("form"===l.inputMode)return void n({inputMode:"text"});try{let e=sg(r,l.inputText);n({inputError:"",inputMode:"form",inputParams:e,inputText:JSON.stringify(e,null,2)})}catch(e){n({inputError:e.message})}},type:"button",children:"form"===l.inputMode?"文本模式":"表单模式"})]}),"form"===l.inputMode?(0,s.jsx)(hV,{onChange:function(e,t){n({inputError:t,inputParams:e,inputText:JSON.stringify(e,null,2)})},schema:o,value:l.inputParams}):(0,s.jsx)(hF,{label:r,minHeight:i,onChange:e=>n({inputError:"",inputText:e}),onMessage:a,value:l.inputText}),l.inputError?(0,s.jsx)("span",{className:"wsd-schema-input-error",children:l.inputError}):null]})}function hJ(e){var t;let{events:r,onMessage:i,onTrigger:n}=e,a=(0,iD.useRef)(null),[o,l]=(0,iD.useState)(!1),[d,u]=(0,iD.useState)((null==(t=r[0])?void 0:t.name)??""),[c,p]=(0,iD.useState)(hz),[h,m]=(0,iD.useState)(""),g=r.find(e=>e.name===d)??r[0],f=cl(()=>l(!1));(0,iD.useEffect)(()=>{if(!g){u(""),p(hz()),l(!1);return}g.name!==d&&(u(g.name),p(hz()))},[g,d]),(0,iD.useEffect)(()=>{if(o)return document.addEventListener("mousedown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",t)};function e(e){var t;(null==(t=a.current)?void 0:t.contains(e.target))||f()}function t(e){"Escape"===e.key&&f()}},[f,o]);let v=cl(()=>{let e;if(g&&!c.inputError){try{e=sg("事件参数",c.inputText)}catch(e){p(t=>({...t,inputError:e.message}));return}try{n(g.name,e),p(t=>({...t,inputError:"",inputParams:e})),m(`已触发 ${g.name}`),null==i||i(`Agent event ${g.name} triggered`),f()}catch(t){let e=t.message;m(e),null==i||i(e,!0)}}});return(0,s.jsxs)("div",{className:"wsd-agent-event-debug",ref:a,children:[(0,s.jsxs)("button",{"aria-expanded":o,"aria-haspopup":"dialog","aria-label":"调试 Agent 事件",className:"wsd-agent-event-button",onClick:()=>l(e=>!e),title:"触发 Agent 事件",type:"button",children:[(0,s.jsx)("span",{"aria-hidden":"true",children:"+"}),"事件"]}),o&&g?(0,s.jsxs)("dialog",{"aria-label":"Agent 事件调试",className:"wsd-agent-event-popup",open:!0,children:[(0,s.jsxs)("header",{className:"wsd-agent-event-header",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)("strong",{children:"触发事件"}),(0,s.jsx)("span",{children:"发送到当前小程序的 App runtime"})]}),(0,s.jsx)("button",{"aria-label":"关闭事件调试",onClick:f,type:"button",children:"×"})]}),(0,s.jsxs)("label",{className:"wsd-agent-event-select-control",children:[(0,s.jsx)("span",{children:"事件"}),(0,s.jsx)("select",{"aria-label":"调试事件",onChange:e=>{u(e.currentTarget.value),p(hz()),m("")},value:g.name,children:r.map(e=>(0,s.jsx)("option",{value:e.name,children:e.name},e.name))})]}),g.description?(0,s.jsx)("p",{className:"wsd-agent-event-description",children:g.description}):null,(0,s.jsx)(hG,{heading:"事件参数 · PAYLOADSCHEMA",jsonLabel:"事件参数",minHeight:132,onChange:e=>p(t=>({...t,...e})),onMessage:i,schema:g.payloadSchema,value:c},g.name),(0,s.jsxs)("footer",{className:"wsd-agent-event-footer",children:[h?(0,s.jsx)("span",{"aria-live":"polite",children:h}):(0,s.jsx)("span",{}),(0,s.jsx)("button",{className:"wsd-button wsd-button-primary wsd-agent-event-trigger",onClick:v,type:"button",children:"触发"})]})]}):null]})}async function hK(e,t,r){let i=await r(e,{cache:"no-store",headers:{Accept:"application/json"}});if(!i.ok)throw Error(`加载 ${t}失败:HTTP ${i.status} ${i.statusText}`);return i.json()}async function hZ(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/__web_sdk_debug_scenes",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:fetch;var r=await hK(e,"Scene ",t);if(!rP(r)||!Array.isArray(r.scenes)||!Array.isArray(r.errors))throw Error("Scene 发现接口返回了无效数据");let i=r.scenes.flatMap(e=>rP(e)&&"string"==typeof e.name&&rP(e.content)?[{content:e.content,name:e.name}]:[]);return{errors:r.errors.flatMap(e=>rP(e)&&"string"==typeof e.name&&"string"==typeof e.message?[{name:e.name,message:e.message}]:[]),scenes:i}}let hX={appEntries:[],entries:[],updatedAtMs:0},hY="scene:";function hQ(e){let{showTooltip:t=!1,value:r}=e,i=r.indexOf("?"),n=i<0?r:r.slice(0,i),a=i<0?"":r.slice(i),o=(0,s.jsxs)("span",{className:"wsd-page-route-label",children:[(0,s.jsx)("span",{className:"wsd-page-route-path",children:n}),a?(0,s.jsx)("span",{className:"wsd-page-route-query",children:a}):null]});return t?(0,s.jsx)(hq.I,{closeDelay:0,content:r,delay:300,placement:"right",children:o}):o}function h0(){return(0,s.jsx)("svg",{"aria-hidden":"true",className:"wsd-page-route-arrow is-back",viewBox:"0 0 16 16",children:(0,s.jsx)("path",{d:"M3 8h10M9 4l4 4-4 4",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5"})})}function h1(e){var t,r,i,n,a,o;let{activeView:l,chromeDevToolsFrontendUrl:d,controlCommand:u,controlClientId:c,debugContext:p,onChromeDevToolsPanelChange:h,onActiveViewChange:m,onControllerChange:g,onControlResult:f,onMessage:v,apiEnvironment:y,showDebugTrace:b,connection:w,webSdkDebugger:_}=e,S=cg(_),x=(0,iD.useMemo)(()=>S.pages.filter(nY),[S.pages]),[I,k]=(0,iD.useState)({errors:[],scenes:[]}),[C,E]=(0,iD.useState)([]),[N,T]=(0,iD.useState)(""),[A,M]=(0,iD.useState)(null),[R,j]=(0,iD.useState)(null),[P,L]=(0,iD.useState)(null),[O,D]=(0,iD.useState)(null),[U,q]=(0,iD.useState)(null),[$,B]=(0,iD.useState)(0),[F,z]=(0,iD.useState)(""),[W,H]=(0,iD.useState)(null),[V,G]=(0,iD.useState)(hX),J=cw(),K=p7(),Z=(null==p?void 0:p.sandboxSessionAvailable)!==!1,X=h_(ht(p)),Y=hT(Z),{bridgeLogs:Q,clearBridgeLogs:ee}=cB(),[et,er]=(0,iD.useState)(null),ei=pZ(),en=(0,iD.useRef)(null),ea=(0,iD.useRef)(null),{accept:es,pending:eo,pendingRef:el,report:ed}=hM(f),{runtimeScaleMode:eu,runtimeStyle:ec,selectedDevice:ep,selectedDeviceKey:eh,setRuntimeShellRef:em,setSelectedDeviceKey:eg}=hj(u,f),ef=(null==(t=S.pageSelection)?void 0:t.item.id)??"",ev=(null==(r=S.pageSelection)?void 0:r.item.path)??"",ey=cl(e=>{null==v||v(e,!0)});(0,iD.useEffect)(()=>{let e=null==p?void 0:p.eventsConfigUrl;if(!e)return void E([]);let t=new AbortController;return fetch(e,{cache:"no-store",headers:{Accept:"application/json"},signal:t.signal}).then(async e=>{if(!e.ok)throw Error(`Failed to load events.json: HTTP ${e.status}`);return e.json()}).then(e=>E(rP(e)&&Array.isArray(e.events)?e.events.flatMap(e=>{if(!rP(e))return[];let t="string"==typeof e.name?e.name.trim():"",r=hW(e.payloadSchema);return t&&rP(r)?[{description:"string"==typeof e.description?e.description:"",name:t,payloadSchema:r}]:[]}):[])).catch(e=>{t.signal.aborted||(E([]),ey(e.message))}),()=>t.abort()},[null==p?void 0:p.eventsConfigUrl,ey]);let eb=(0,iD.useMemo)(()=>I.scenes.flatMap(e=>{let t=rA(e.content);if("page"!==t.type||t.unresolvedVariables.length>0)return[];try{return tO({url:t.url},S.manifest),[{key:`${hY}${e.name}`,label:t.url,type:"scene",url:t.url}]}catch{return[]}}),[I.scenes,S.manifest]),ew=(0,iD.useMemo)(()=>[...x.map(e=>({key:e.path,url:e.path})),...eb],[eb,x]),e_=F||(null==(i=S.pageSelection)?void 0:i.routeUrl)||ev,eS=e_.split("?")[0],ex=(null==(n=eb.find(e=>e.key===N&&e.url===e_))?void 0:n.key)??"",eI=(null==(a=ew.find(e=>!e.key.startsWith(hY)&&e.url===eS))?void 0:a.key)??"",ek=(0,iD.useMemo)(()=>({...p,manifestUrl:S.manifestUrl,simulatorEndpoint:S.simulator.endpoint}),[p,S.manifestUrl,S.simulator.endpoint]),eC=(0,iD.useMemo)(()=>hd({context:ek,events:S.simulator.traceEvents,manifest:S.manifest,pages:S.pages,widgets:S.widgets}),[ek,S.manifest,S.pages,S.simulator.traceEvents,S.widgets]),eE=eC.appId,eN=eC.appName,eT=(0,iD.useMemo)(()=>({type:"page",appId:eE,appName:eN,pageId:ef,pagePath:ev,url:e_,viewport:{key:ep.key,label:ep.label,width:ep.width,height:ep.height,density:ep.density}}),[eE,eN,ep,ef,ev,e_]),eA=(0,iD.useMemo)(()=>hc(eC,S.pageSelection?eT:void 0),[eT,eC.pages,eC.widgets,S.pageSelection]),eM=!!(eo&&hu(et,O,eo.previousTarget)&&(null==(o=S.pageSelection)?void 0:o.routeUrl)===eo.command.url),eR=(0,iD.useMemo)(()=>(null==et?void 0:et.sourceTarget)===O?{target:eT,root:et.root,nodeCount:et.nodeCount,selectedUid:et.selectedUid,truncated:et.truncated,updatedAtMs:et.updatedAtMs}:void 0,[eT,O,et]),ej=(0,iD.useMemo)(()=>({exported_at:new Date().toISOString(),client_id:c,command_id:eM?null==eo?void 0:eo.command.commandId:void 0,context:{...he({appId:eE,appName:eC.appName,debugContext:ek,manifestUrl:S.manifestUrl,simulatorEndpoint:S.simulator.endpoint,sources:eC.sources}),page_id:ef,page_path:ev},render_targets:eA,runtime_snapshot:eR,page_runtime_trace_events:[],runtime_console:{app:{entries:V.appEntries,updated_at_ms:V.updatedAtMs},page:{entries:V.entries,updated_at_ms:V.updatedAtMs}},simulator:{stream_status:S.simulator.streamStatus,messages:S.simulator.messages,trace_events:S.simulator.traceEvents,tool_calls:S.simulator.toolCalls}}),[eC.appId,eC.appName,eC.sources.manifest.original,eC.sources.manifest.proxy,eC.sources.mcp.original,eC.sources.mcp.proxy,eC.sources.skill.original,eC.sources.skill.proxy,ek.launchDir,ek.mcpEndpoint,ek.simulatorManifestUrl,ek.simulatorSkillsIndexUrl,ek.webUrl,V,ef,ev,eE,c,eM,null==eo?void 0:eo.command.commandId,eA,S.manifest.name,S.manifestUrl,S.simulator.endpoint,S.simulator.messages,S.simulator.streamStatus,S.simulator.toolCalls,S.simulator.traceEvents,eR]),eP=(0,iD.useMemo)(()=>b?S.simulator.traceEvents:S.simulator.traceEvents.filter(e=>{var t;return!(null==(t=e.display)?void 0:t.debugOnly)}),[b,S.simulator.traceEvents]),eL=(0,iD.useMemo)(()=>iI(eP,{debug:b,messages:S.simulator.messages}),[b,S.simulator.messages,eP]),eO=(0,iD.useMemo)(()=>ix(ej,{debug:b}),[b,ej]),eD=(0,iD.useMemo)(()=>iw(eO),[eO]);(0,iD.useEffect)(()=>{let e=!0;return hZ(null==p?void 0:p.debugScenesEndpoint).then(t=>{if(e)for(let e of(k(t),t.errors))null==v||v(`${e.name}: ${e.message}`,!0)}).catch(t=>{e&&(k({errors:[],scenes:[]}),null==v||v(t.message,!0))}),()=>{e=!1}},[null==p?void 0:p.debugScenesEndpoint,v]);let eU=cl(e=>{var t,r;let i=(null==(t=en.current)?void 0:t.getCurrentTarget())??(null==(r=en.current)?void 0:r.getCurrentAppTarget()),n=`[Debug Scene] ${e}`;i?s_(i,{level:"error",message:n,pagePath:ev}):console.error(n)}),eq=cl(e=>{eb.some(e=>{var t;return e.key===N&&e.url===(null==(t=S.pageSelection)?void 0:t.routeUrl)})?eU(e):null==v||v(e,!0)}),e$=async()=>{var e;await _.reloadResources(),null==(e=en.current)||e.reload()},eB=cl(e=>{let t=ew.find(t=>t.key===e);t&&(t.key.startsWith(hY)?T(t.key):T(""),_.navigateToPage(t.url))}),eF=cl(e=>{hA(e,{onClearLogs:ee,onMessage:v})}),ez=(0,iD.useMemo)(()=>({debugData:{...eC,appId:(null==p?void 0:p.sandboxCsrRequired)?p.sandboxAppId||"":eC.appId},events:eL,logSnapshot:eO,logSnapshotText:eD,sandbox:{available:Z,csrRequired:(null==p?void 0:p.sandboxCsrRequired)!==!1,input:{csrPem:(null==p?void 0:p.sandboxCsrPem)??"",phoneNum:(null==p?void 0:p.sandboxPhoneNum)??""},logs:Q,businessInfoStatus:X,sessionStatus:Y},showDebugTrace:b,traceSurface:"page",toolCalls:S.simulator.toolCalls,updatedAtMs:Date.now()}),[eC,eL,eO,eD,Q,X,Z,Y,null==p?void 0:p.sandboxCsrRequired,null==p?void 0:p.sandboxAppId,b,S.simulator.toolCalls]);hP(w,ej,et,"page"===l),(0,iD.useEffect)(()=>{if((null==u?void 0:u.type)==="render_page"&&es(u,O))try{T(""),_.navigateToPage(u.url)}catch(e){ed(u.commandId,{ok:!1,error:{code:"TARGET_NOT_FOUND",message:e.message}})}},[es,u,O,ed,_]),(0,iD.useEffect)(()=>{eo&&eM&&ed(eo.command.commandId,{ok:!0,target:eT,snapshot:iS(ej)})},[eT,eM,eo,ed,ej]);let eW=cl((e,t)=>{let r=af(_,{noLogin:null==t?void 0:t.noLogin});if("not_found"===r.status){null==v||v("未找到需要重发的原始消息",!0);return}if("streaming"===r.status){null==v||v("当前仍在生成中,暂不重发授权后的消息",!0);return}_.appendSimulatorTraceEvent({category:"card",event:"simulator_granting_resend_query",granting_type:e,no_login:(null==t?void 0:t.noLogin)===!0,removed_message_ids:r.target.messageIds,query_preview:r.target.query.slice(0,80),source:"custom_login_page"}),r.completion.catch(e=>{null==v||v(e.message,!0)})}),eH=cl((e,t)=>{eW(e,t),"login"===e&&(null==m||m("conversation"))}),eV=cl(async e=>{let t=en.current;if(!t)throw Error("No Page runtime is active");await t.openPage(e)}),eG=(0,iD.useMemo)(()=>{let e=dI({appId:eE,appIcon:S.manifest.iconSrc,appName:eN,declaredScopes:Object.keys(S.manifest.raw.permissions??{}),baseAPIRegistry:null==y?void 0:y.apiRegistry,imagePreviewController:K.imagePreviewController,onGrantingCompleted:eH,openPageFromWidget:eV,sendFollowUpMessage:e=>{let{content:t}=e;return _.sendSimulatorFollowUpMessage(t)},multiMediaBroadcastContainer:A,scanCodePresenter:K.scanCodePresenter,showSandboxCashier:J.showCashier,uiPresenter:K.presenter,showSimulatorPermission:ei.showPermission,showSimulatorPermissionSettings:ei.showSettings,vibrationContainer:P});return e.apiRegistry.registerMany(cJ({appKey:eE,scene:"page"}),{override:!0}),e.apiRegistry.registerMany(cK(e=>_.updateSimulatorWidget(e)),{override:!0}),e},[y,eH,eV,eE,eN,K.imagePreviewController,P,A,J.showCashier,K.scanCodePresenter,K.presenter,ei.showPermission,ei.showSettings,S.manifest.iconSrc,S.manifest.raw.permissions,_]),eJ=cl(async(e,t)=>"confirm"===(await K.presenter.showModal({content:e,showCancel:!0,confirmText:"确认",cancelText:"取消"},t)).action);(0,iD.useEffect)(()=>{if(!A)return;let e=new ca({container:A,fileSystemNamespace:null==p?void 0:p.fileSystemNamespace,webSdkDebugger:_,onExitApp:()=>null==m?void 0:m("conversation"),onHideApp:()=>null==m?void 0:m("conversation"),confirmBeforeUnload:eJ,onError:e=>{null==v||v(`Page runtime error: ${e.message}`,!0)},apiEnvironment:eG});en.current=e,null==g||g(e);let t=e.subscribeTarget(t=>{D(t),B(e.getPageStackSize()),z(e.getCurrentPageUrl()??""),H(null)}),r=e.subscribeAppTarget(e=>{q(e)});return D(e.getCurrentTarget()),q(e.getCurrentAppTarget()),B(e.getPageStackSize()),z(e.getCurrentPageUrl()??""),()=>{t(),r(),e.destroy(),en.current=null,null==g||g(null),D(null),q(null),B(0),z(""),H(null)}},[eJ,null==p?void 0:p.fileSystemNamespace,m,g,v,eG,A,_]);let eK=cl((e,t)=>{let r=en.current;if(!r)throw Error("Page runtime is not ready");r.sendAgentEvent(e,t)});(0,iD.useEffect)(()=>{let e=en.current;if(!e||!S.pageSelection){null==e||e.clear();return}let t=ea.current===S.pageSelection?void 0:S.pageSelection.routeMode;ea.current=S.pageSelection;let r=!1;return e.render({device:ep,routeMode:t}).catch(e=>{if(r||rP(e)&&"AbortError"===e.name)return;eq(e.message);let t=el.current;t&&ed(t.command.commandId,{ok:!1,error:{code:"RENDER_FAILED",message:e.message}})}),()=>{r=!0}},[eq,ed,A,ep,ef,S.pageSelection]);let eZ=(0,iD.useMemo)(()=>({appTarget:U,controlCommand:u,controlTarget:S.pageSelection?O:null,debugState:ez,frontendUrl:d,onConsoleSnapshotChange:G,onControlResult:f,onDebugAction:eF,onHighlightChange:H,onRuntimeSnapshotChange:er,preserveConsoleOnTargetChange:!0,runtimeSnapshotTarget:eT,runtimeFrame:R,target:S.pageSelection?O:null}),[U,d,u,eT,ez,eF,f,O,R,S.pageSelection]);return(0,iD.useEffect)(()=>{"page"===l&&(null==h||h(eZ))},[l,eZ,h]),(0,iD.useEffect)(()=>{var e;null==(e=en.current)||e.setVisible("page"===l)},[l,A]),(0,s.jsxs)("div",{className:"wsd-page-preview-column",hidden:"page"!==l,children:[(0,s.jsx)(pH,{activeView:l??"page",storageNamespace:null==p?void 0:p.fileSystemNamespace,hasTools:Object.keys(S.manifest.raw.tools??{}).length>0,onActiveViewChange:m,onDeviceChange:eg,selectedDeviceKey:eh,children:(0,s.jsx)("button",{"aria-label":"Reload",className:"wsd-icon-button",disabled:!S.pageSelection,onClick:()=>void e$(),title:"Reload",type:"button",children:(0,s.jsx)(ps,{"aria-hidden":"true"})})}),(0,s.jsxs)("div",{className:"wsd-page-route-control",children:[(0,s.jsx)("div",{className:"wsd-page-route-navigation",children:(0,s.jsx)("button",{"aria-label":"返回",className:"wsd-page-route-button",disabled:0===$,onClick:()=>{var e;return null==(e=en.current)?void 0:e.closeCurrentPage()},title:"返回",type:"button",children:(0,s.jsx)(h0,{})})}),(0,s.jsx)("div",{className:"wsd-page-route-select-wrapper",children:(0,s.jsx)(h$.d,{"aria-label":"页面路径",className:"wsd-page-route-select",classNames:{listbox:"wsd-page-path-listbox",popoverContent:"wsd-page-path-popover",selectorIcon:"wsd-page-path-icon",trigger:"wsd-page-path-select",value:"wsd-page-path-value"},isDisabled:0===x.length&&0===eb.length,listboxProps:{itemClasses:{base:"wsd-page-path-option",selectedIcon:"wsd-page-path-selected-icon"}},onChange:e=>eB(e.target.value),placeholder:e_||"No page",popoverProps:{offset:0},renderValue:()=>(0,s.jsx)(hQ,{value:e_||ev}),selectedKeys:ex?[ex]:eI?[eI]:[],size:"sm",children:ew.map(e=>(0,s.jsx)(hB.y,{textValue:e.url,children:(0,s.jsx)(hQ,{showTooltip:!0,value:e.url})},e.key))})}),S.pageSelection&&C.length>0?(0,s.jsx)(hJ,{events:C,onMessage:v,onTrigger:eK}):null]}),S.pageSelection?(0,s.jsx)(cy,{highlightRect:W,overlay:(0,s.jsxs)(s.Fragment,{children:[K.overlay,J.cashier?(0,s.jsx)(cb,{cashier:J.cashier,onCancel:J.cancelCashier,onConfirm:J.confirmCashier}):null,ei.overlay]}),runtimeFrameRef:j,runtimeFrameScaleBoxRef:L,runtimeScaleMode:eu,runtimeShellRef:em,runtimeStyle:ec,runtimeTargetRef:M}):(0,s.jsx)("div",{className:"wsd-page-empty",children:"No page"})]})}let h2=0;function h3(){return{...hz(),callError:"",isRunning:!1,selectedOutputIndex:0,selectedToolName:""}}function h4(e){var t;let r=null==e||null==(t=e.debug)?void 0:t.mcp_output,i=!1,n=(r?[r]:[]).flatMap(e=>{var t;if(Array.isArray(e.structuredContent)){i=!0;let t=e.structuredContent;return t.length>0?t.map(t=>({...e,structuredContent:t})):[e]}if(!Array.isArray(null==(t=e.structuredContent)?void 0:t.entities))return[e];i=!0;let r=e.structuredContent.entities;return r.length>0?r.map(t=>({...e,structuredContent:t})):[e]});return{collectionType:i?"entity":void 0,outputs:n}}function h5(e){return((null==e?void 0:e.content)??[]).map(e=>"text"===e.type&&e.text||"").filter(Boolean).join("\n")}function h6(e){var t;let{onSessionChange:r,onUseWidgetOutput:i,session:n,...a}=e,o=hD(a,"card"),l=null==(t=a.debugContext)?void 0:t.toolsConfigUrl,d=cl(e=>{var t;null==(t=a.onMessage)||t.call(a,e,!0)}),[u,c]=(0,iD.useState)({}),p=(0,iD.useMemo)(()=>{var e;return e=o.state.manifest.raw,Object.entries(e.tools??{}).map(t=>{let[r,i]=t;return{description:i.description||"",inputSchema:u[r]??hW(i.input_schema??{}),name:r,widgetId:function(e,t){for(let i of Object.values(e.entities??{})){var r;let e=null==(r=i.tool_card_binding)?void 0:r[t];if(e)return e}}(e,r)}})},[o.state.manifest,u]),{callError:h,copiedResultSection:m,inputError:g,inputText:f,isRunning:v,result:y,selectedOutputIndex:b,selectedToolName:w}=n,_=p.find(e=>e.name===w)??p[0],S=null==_?void 0:_.widgetId,x=h4(y),I=x.outputs,k=I[b]??I[0],C=Array.isArray(null==k?void 0:k.structuredContent)||null==k?void 0:k.structuredContent,E=null==k?void 0:k._meta,N=h5(k);async function T(){let e;if(!_||g)return;try{e=sg("调用参数",f)}catch(e){r(t=>({...t,inputError:e.message}));return}let t=h2+=1;r(r=>({...r,activeInvocationId:t,callError:"",copiedResultSection:void 0,inputError:"",inputParams:e,isRunning:!0,result:void 0,selectedOutputIndex:0}));try{let i=await o.webSdkDebugger.callSimulatorTool({params:e,toolName:_.name});r(e=>{let r;return e.activeInvocationId===t?{...e,result:i,selectedOutputIndex:(r=h4(i).outputs.findIndex(e=>e.structuredContent))<0?0:r}:e})}catch(e){r(r=>r.activeInvocationId===t?{...r,callError:e.message}:r)}finally{r(e=>e.activeInvocationId===t?{...e,activeInvocationId:void 0,isRunning:!1}:e)}}async function A(e,t){await px("meta"===e?"META JSON":"STRUCTUREDCONTENT JSON",JSON.stringify(t,null,2),o.onMessage)&&r(t=>({...t,copiedResultSection:e}))}return(0,iD.useEffect)(()=>{if(!l)return void c({});let e=new AbortController;return fetch(l,{cache:"no-store",headers:{Accept:"application/json"},signal:e.signal}).then(async e=>{if(!e.ok)throw Error(`Failed to load tools.json: HTTP ${e.status}`);return e.json()}).then(e=>{c(rP(e)&&Array.isArray(e.tools)?Object.fromEntries(e.tools.flatMap(e=>rP(e)&&"string"==typeof e.name&&rP(e.inputSchema)?[[e.name,e.inputSchema]]:[])):{})}).catch(t=>{e.signal.aborted||d(t.message)}),()=>e.abort()},[d,l]),(0,iD.useEffect)(()=>{_&&_.name!==w&&r(e=>({...e,selectedToolName:_.name}))},[r,_,w]),(0,s.jsx)(pV,{runtime:o,showReloadButton:!1,toolbarView:"tool",children:(0,s.jsx)("div",{className:"wsd-tool-debug",children:_?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("section",{className:"wsd-tool-debug-card",children:[(0,s.jsxs)("label",{className:"wsd-tool-select-control",children:[(0,s.jsx)("span",{children:"工具"}),(0,s.jsx)("select",{"aria-label":"调试工具",onChange:e=>{var t;return t=e.currentTarget.value,void r({...h3(),selectedToolName:t})},value:_.name,children:p.map(e=>(0,s.jsx)("option",{value:e.name,children:e.name},e.name))})]}),(0,s.jsx)("h2",{children:_.name}),_.description?(0,s.jsx)("p",{children:_.description}):null,(0,s.jsx)(hG,{heading:"输入参数 · INPUTSCHEMA",jsonLabel:"调用参数",onChange:e=>r(t=>({...t,...e})),onMessage:o.onMessage,schema:_.inputSchema,value:n},_.name),(0,s.jsx)("button",{className:"wsd-button wsd-button-primary wsd-tool-run-button",disabled:v,onClick:()=>void T(),type:"button",children:v?"运行中…":"▶ 运行"})]}),y||h?(0,s.jsxs)("section",{className:"wsd-tool-debug-result","aria-live":"polite",children:[(0,s.jsxs)("div",{className:"wsd-tool-result-title",children:[(0,s.jsx)("span",{children:"输出结果"}),(0,s.jsx)("strong",{className:(null==y?void 0:y.status)==="succeeded"?"is-success":"is-error",children:(null==y?void 0:y.status)==="succeeded"?"运行成功":"运行失败"})]}),x.collectionType&&I.length>0?(0,s.jsxs)("label",{className:"wsd-tool-select-control wsd-tool-output-select-control",children:[(0,s.jsx)("span",{children:"entity"===x.collectionType?"Entity 元素":"数组元素"}),(0,s.jsx)("select",{"aria-label":"entity"===x.collectionType?"Entity 元素":"数组元素",onChange:e=>{let t=Number(e.currentTarget.value);r(e=>({...e,copiedResultSection:void 0,selectedOutputIndex:t}))},value:b,children:I.map((e,t)=>{let r,i,n;return(0,s.jsx)("option",{value:t,children:(i=[null==(r=Array.isArray(e.structuredContent)?void 0:e.structuredContent)?void 0:r.name,null==r?void 0:r.title].find(e=>"string"==typeof e&&e.trim()),n=h5(e).split("\n")[0],`${t+1}. ${i||n||"空结果"}`)},t)})})]}):null,h||(null==y?void 0:y.error)?(0,s.jsxs)("div",{className:"wsd-tool-result-block",children:[(0,s.jsx)("span",{children:"ERROR"}),(0,s.jsx)("pre",{children:h||JSON.stringify(null==y?void 0:y.error,null,2)})]}):null,N?(0,s.jsxs)("div",{className:"wsd-tool-result-block",children:[(0,s.jsx)("span",{children:"CONTENT"}),(0,s.jsx)("p",{children:N})]}):null,C?(0,s.jsxs)("div",{className:"wsd-tool-result-block",children:[(0,s.jsxs)("div",{className:"wsd-tool-result-block-heading",children:[(0,s.jsx)("span",{children:"STRUCTUREDCONTENT"}),(0,s.jsx)("button",{"aria-label":"复制 STRUCTUREDCONTENT JSON",className:"wsd-button wsd-button-ghost",onClick:()=>void A("structuredContent",C),type:"button",children:"structuredContent"===m?"已复制":"复制 JSON"})]}),(0,s.jsx)("pre",{children:JSON.stringify(C,null,2)})]}):null,E?(0,s.jsxs)("div",{className:"wsd-tool-result-block",children:[(0,s.jsxs)("div",{className:"wsd-tool-result-block-heading",children:[(0,s.jsx)("span",{children:"META"}),(0,s.jsx)("button",{"aria-label":"复制 META JSON",className:"wsd-button wsd-button-ghost",onClick:()=>void A("meta",E),type:"button",children:"meta"===m?"已复制":"复制 JSON"})]}),(0,s.jsx)("pre",{children:JSON.stringify(E,null,2)})]}):null,(null==y?void 0:y.status)==="succeeded"&&S&&C?(0,s.jsxs)("button",{className:"wsd-button wsd-button-primary wsd-tool-use-widget-output",onClick:()=>i({viewData:C,widgetId:S}),type:"button",children:["填入 ",S," 卡片预览"]}):null]}):null]}):null})})}var h8=e=>(0,s.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",width:12,height:12,fill:"none",viewBox:"0 0 12 12",...e,children:(0,s.jsx)("path",{fill:"#BABABA",d:"M1.162 4.61a.5.5 0 1 1 .707-.706l4.06 4.06a.1.1 0 0 0 .142 0l4.06-4.06a.5.5 0 0 1 .707.707l-4.06 4.06a1.1 1.1 0 0 1-1.556 0z"})}),h9=r(48986),h7=r(80704),me=r(51290),mt=r(36091);let mr=me.Lz.theme({"&":{height:"100%",backgroundColor:"#fbfcff",color:"#172033",fontSize:"12px"},"&.cm-focused":{outline:"none"},".cm-scroller":{fontFamily:"'SFMono-Regular', Consolas, monospace",lineHeight:"1.55"},".cm-content":{padding:"8px 0"},".cm-line":{padding:"0 10px 0 8px"},".cm-gutters":{borderRight:"1px solid #dfe5ee",backgroundColor:"#f4f7fb",color:"#8a98ab"},".cm-activeLine":{backgroundColor:"rgba(36, 84, 198, 0.05)"},".cm-activeLineGutter":{backgroundColor:"rgba(36, 84, 198, 0.08)"},".cm-tooltip":{border:"1px solid #c7d0dd",borderRadius:"7px",boxShadow:"0 12px 28px rgba(28, 39, 56, 0.16)"}}),mi=[(0,h9.Pq)(),(0,h7.pJ)(),(0,h7.bu)((0,h9.cp)()),me.Lz.lineWrapping,mr];function mn(e){let{ariaLabel:t,minHeight:r=96,onChange:i,value:n}=e,a={"--json-editor-min-height":`${r}px`};return(0,s.jsx)("div",{"aria-label":t,className:"json-editor-shell",style:a,children:(0,s.jsx)(mt.Ay,{basicSetup:{autocompletion:!0,bracketMatching:!0,closeBrackets:!0,foldGutter:!0,highlightActiveLine:!0,highlightActiveLineGutter:!0,lineNumbers:!0,searchKeymap:!0},extensions:mi,minHeight:`${r}px`,onChange:i,value:n})})}function ma(e){return rP(e)?Object.fromEntries(Object.entries(e).flatMap(e=>{let[t,r]=e;return rP(r)?[[t,r]]:[]})):{}}async function ms(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/__web_sdk_widget_view_data_templates",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:fetch,r=await t(e,{cache:"no-store",headers:{Accept:"application/json"}});if(!r.ok)throw Error(`加载 Widget viewData 模板失败:HTTP ${r.status} ${r.statusText}`);let i=await r.json();if(!rP(i)||!rP(i.templatesByEntry)&&!rP(i.templatesByWidget))throw Error("Widget viewData 模板接口返回了无效数据");return{templatesByEntry:ma(i.templatesByEntry),templatesByWidget:ma(i.templatesByWidget)}}let mo="输入数据(structuredContent)",ml={};function md(e){var t,r,i;let{initDataDraft:n,...a}=e,o=hD(a,"card"),[l,d]=(0,iD.useState)("{}"),[u,c]=(0,iD.useState)([]),[p,h]=(0,iD.useState)({templatesByEntry:{},templatesByWidget:{}}),m=(0,iD.useRef)(!1),g=(0,iD.useRef)(o.selectedWidgetId),f=((null==(t=o.state.widgetSelection)?void 0:t.item.entry)??"").replaceAll("\\","/").replace(/^src\//,"").replace(/\.(?:bundle|tsx?|jsx?)$/,""),v=p.templatesByWidget[o.selectedWidgetId]??p.templatesByEntry[f]??ml,y=(0,iD.useMemo)(()=>u.flatMap(e=>{let t=rA(e.content);return"widget"===t.type&&t.id===o.selectedWidgetId?[{...t,sceneName:e.name}]:[]}),[u,o.selectedWidgetId]);(0,iD.useEffect)(()=>{var e;(null==(e=a.controlCommand)?void 0:e.type)==="render_widget"&&a.controlCommand.widgetId===o.selectedWidgetId&&(m.current=!0,d(JSON.stringify(a.controlCommand.structuredContent,null,2)))},[a.controlCommand,o.selectedWidgetId]),(0,iD.useEffect)(()=>{var e;let t=g.current!==o.selectedWidgetId;g.current=o.selectedWidgetId,((null==(e=a.controlCommand)?void 0:e.type)!=="render_widget"||a.controlCommand.widgetId!==o.selectedWidgetId)&&(t&&(m.current=!1),m.current||d(JSON.stringify(v,null,2)))},[v,a.controlCommand,o.selectedWidgetId]),(0,iD.useEffect)(()=>{var e;let t=!0;return hZ(null==(e=a.debugContext)?void 0:e.debugScenesEndpoint).then(e=>{t&&c(e.scenes)}).catch(e=>{if(t){var r;c([]),null==(r=o.onMessage)||r.call(o,e.message,!0)}}),()=>{t=!1}},[null==(r=a.debugContext)?void 0:r.debugScenesEndpoint,o.onMessage]);let b=cl(async function(){var e,t;let r=arguments.length>0&&void 0!==arguments[0]&&arguments[0];try{let t=await ms(null==(e=a.debugContext)?void 0:e.widgetViewDataTemplatesEndpoint);r&&(m.current=!1),h(t)}catch(e){h({templatesByEntry:{},templatesByWidget:{}}),null==(t=o.onMessage)||t.call(o,e.message,!0)}});(0,iD.useEffect)(()=>{b()},[null==(i=a.debugContext)?void 0:i.widgetViewDataTemplatesEndpoint,b]);let w=cl(e=>{m.current=!0,d(e)}),_=cl(async()=>{let e=await o.reloadResources();return e&&await b(!0),e});function S(){try{let e=sg(mo,l);o.renderSelectedWidget({initData:{viewData:e}})}catch(t){var e;null==(e=o.onMessage)||e.call(o,t.message,!0)}}return(0,iD.useEffect)(()=>{n&&(m.current=!0,d(JSON.stringify(n,null,2)))},[n]),(0,s.jsx)(pV,{runtime:{...o,reloadResources:_},children:o.state.widgetSelection?(0,s.jsx)(cy,{highlightRect:o.highlightRect,overlay:(0,s.jsxs)("section",{"aria-label":"卡片调试",className:(0,rL.$)("wsd-widget-card-debug",{"has-rendered-preview":o.hasRenderedPreview}),children:[(0,s.jsx)(ck,{}),(0,s.jsxs)("section",{className:"wsd-widget-card-form",children:[(0,s.jsxs)("label",{className:"wsd-widget-card-template-control",children:[(0,s.jsx)("span",{children:"卡片模板:"}),(0,s.jsx)("span",{className:"wsd-widget-card-template-value",children:o.selectedWidgetId}),(0,s.jsx)(h8,{"aria-hidden":"true"}),(0,s.jsx)("select",{"aria-label":"卡片模板",disabled:0===o.visibleWidgets.length,onChange:e=>o.webSdkDebugger.selectWidget(e.currentTarget.value),value:o.selectedWidgetId,children:o.visibleWidgets.map(e=>(0,s.jsx)("option",{value:e.widgetId,children:e.widgetId},e.widgetId))})]}),y.length>0?(0,s.jsx)("div",{"aria-label":"Debug Scene 预设",className:"wsd-widget-scene-presets",children:y.map(e=>(0,s.jsx)("button",{className:"wsd-widget-scene-preset",onClick:()=>{m.current=!0,d(JSON.stringify(e.resolvedInput,null,2))},type:"button",children:e.sceneName},e.sceneName))}):null,(0,s.jsx)(hF,{JsonEditorComponent:mn,label:mo,minHeight:200,onAction:S,onChange:w,onMessage:o.onMessage,value:l}),(0,s.jsx)("button",{className:"wsd-button wsd-button-primary wsd-widget-card-render-button",onClick:S,type:"button",children:"渲染卡片"})]}),(0,s.jsxs)("section",{className:"wsd-widget-card-preview-section",children:[(0,s.jsx)("span",{children:"以下是卡片渲染预览"}),(0,s.jsxs)("div",{className:"wsd-widget-card-preview-canvas",children:[(0,s.jsx)("div",{className:(0,rL.$)({"wsd-widget-card-preview-target":o.hasRenderedPreview}),ref:o.runtimeTargetRef}),o.hasRenderedPreview?null:(0,s.jsx)("span",{className:"wsd-widget-card-preview-empty",children:"未传入内容"}),o.simulatorUI.overlay,o.sandboxCashier.cashier?(0,s.jsx)(cb,{cashier:o.sandboxCashier.cashier,onCancel:o.sandboxCashier.cancelCashier,onConfirm:o.sandboxCashier.confirmCashier}):null,o.simulatorPermissionPrompt.overlay]})]})]}),runtimeFrameRef:o.runtimeFrameRef,runtimeFrameScaleBoxRef:o.runtimeFrameScaleBoxRef,runtimeScaleMode:o.runtimeScaleMode,runtimeShellRef:o.setRuntimeShellRef,runtimeStyle:o.runtimeStyle}):(0,s.jsx)("div",{className:"wsd-page-empty",children:"No widget"})})}var mu=r(85624);function mc(e,t){let r=Math.max(0,e.scrollWidth-e.clientWidth),i=Math.max(0,e.scrollHeight-e.clientHeight);return(r>0||i>0)&&(void 0===t.x||0===t.x||r>0)&&(void 0===t.y||0===t.y||i>0)}async function mp(e,t,r){let i=e.uid?t.getElement(e.uid):null,n=e.uid?i?{element:i,uid:e.uid}:null:function(e,t,r){let i=t.getInspectorSnapshot().root,n=i?[i]:[],a=null;for(let i=0;i<n.length;i+=1){let s=n[i];n.push(...s.children);let o=t.getElement(s.id);if(!o||!mc(o,e))continue;let l=function(e,t){if(!e.isConnected)return 0;let r=getComputedStyle(e);if("none"===r.display||"hidden"===r.visibility||"collapse"===r.visibility)return 0;let i=e.getBoundingClientRect(),n=t.getBoundingClientRect();return Math.max(0,Math.min(i.right,n.right)-Math.max(i.left,n.left))*Math.max(0,Math.min(i.bottom,n.bottom)-Math.max(i.top,n.top))}(o,r);l>0&&(!a||l>a.area)&&(a={area:l,element:o,uid:s.id})}return a}(e,t,r);if(!n||!mc(n.element,e))return null;let a=Math.max(0,n.element.scrollWidth-n.element.clientWidth),s=Math.max(0,n.element.scrollHeight-n.element.clientHeight);void 0!==e.x&&(n.element.scrollLeft=Math.min(e.x,a)),void 0!==e.y&&(n.element.scrollTop=Math.min(e.y,s)),await new Promise(e=>{requestAnimationFrame(()=>requestAnimationFrame(()=>e()))});let o=Math.max(0,n.element.scrollWidth-n.element.clientWidth),l=Math.max(0,n.element.scrollHeight-n.element.clientHeight);return{uid:n.uid,x:Math.max(0,Math.min(n.element.scrollLeft,o)),y:Math.max(0,Math.min(n.element.scrollTop,l)),maxX:o,maxY:l,viewportWidth:n.element.clientWidth,viewportHeight:n.element.clientHeight}}let mh="wsd-cdp-adapter",mm={jpeg:"image/jpeg",png:"image/png",webp:"image/webp"};function mg(e,t){return{ok:!1,error:{code:e,message:t}}}async function mf(e,t,r,i){if("take_snapshot"===e.type){if(!t||!r||!i)return mg("TARGET_NOT_FOUND","No Page or Widget target is currently rendered");let e=t.getInspectorSnapshot(),n=hp(e.root,e.selectedUid,r);return{ok:!0,result:{runtimeSnapshot:{target:i,root:n.root,nodeCount:n.nodeCount,selectedUid:n.selectedUid,truncated:n.truncated,updatedAtMs:n.updatedAtMs}}}}if(!t||!r)return mg("TARGET_NOT_FOUND","No Page or Widget target is currently rendered");if("scroll_to"===e.type){if(e.uid&&!t.getElement(e.uid))return mg("ELEMENT_NOT_FOUND",`Element uid ${e.uid} was not found`);let i=await mp(e,t,r);return i?{ok:!0,result:i}:mg("SCROLL_FAILED",e.uid?`Element uid ${e.uid} is not scrollable`:"No visible scrollable container was found")}if("get_computed_style"===e.type){let r=t.getComputedStyles(e.uid,e.properties);return r?{ok:!0,result:{uid:e.uid,computedStyle:r}}:mg("ELEMENT_NOT_FOUND",`Element uid ${e.uid} was not found`)}if("get_element_rect"===e.type){let r=t.getElementRect(e.uid);return r?{ok:!0,result:{uid:e.uid,...r}}:mg("ELEMENT_NOT_FOUND",`Element uid ${e.uid} was not found`)}let n=e.uid?t.getElement(e.uid):r;if(!n)return mg("ELEMENT_NOT_FOUND",`Element uid ${e.uid} was not found`);let a=mm[e.format],s=n.getBoundingClientRect(),o=n.offsetWidth||s.width,l=n.offsetHeight||s.height;try{let t=await (0,mu.TC)(n,{height:l,scale:3,type:a,width:o,quality:void 0!==e.quality&&"png"!==e.format?e.quality/100:void 0,onCloneEachNode:e=>{if(!(e instanceof HTMLElement)||"raw-text"!==e.localName)return;let t=e.getAttribute("text");null!==t&&(e.textContent=t)}}),r=`data:${a};base64,`,i=t.startsWith(r)?t.slice(r.length):"";if(!i||i.length>8388608)return mg("SCREENSHOT_FAILED",i?"Screenshot exceeds the 8 MiB debugger limit":"Screenshot returned invalid image data");return{ok:!0,result:{data:i,format:e.format,mimeType:a,width:Math.floor(3*o),height:Math.floor(3*l),uid:e.uid}}}catch(e){return mg("SCREENSHOT_FAILED",e instanceof Error?e.message:String(e))}}function mv(e){let{controlCommand:t,controlTarget:r,debugState:i,frontendUrl:n,onDebugAction:a,onConsoleSnapshotChange:o,onControlResult:l,onHighlightChange:d,onRuntimeSnapshotChange:u,preserveConsoleOnTargetChange:c,resolveTargetAtPoint:p,getRuntimeFrame:h,runtimeFrame:m,runtimeSnapshotTarget:g,showPanelId:f,showPanelRequestId:v,appTarget:y,consoleTarget:b,target:w}=e,_=(0,iD.useRef)(null),S=(0,iD.useRef)(i),x=(0,iD.useRef)(m??null),I=(0,iD.useRef)(y??null),k=(0,iD.useRef)(w),C=(0,iD.useRef)({consoleTarget:b,getRuntimeFrame:h,onConsoleSnapshotChange:o,onDebugAction:a,onHighlightChange:d,onRuntimeSnapshotChange:u,preserveConsoleOnTargetChange:c,resolveTargetAtPoint:p}),E=(0,iD.useRef)(),N=(0,iD.useRef)(null),T=(0,iD.useRef)(null),A=(0,iD.useRef)(null),M=(0,iD.useRef)(null),R=(0,iD.useMemo)(()=>(function(e){let t,r=null==e?void 0:e.trim();if(!r||"u"<typeof window)return null;try{t=new URL(r,window.location.href)}catch{return null}if("http:"!==t.protocol&&"https:"!==t.protocol)return null;t.origin===window.location.origin&&window.localStorage.setItem("navigator-just-my-code","true"),t.searchParams.set("wsdCdpTransport","postmessage");let i=t.searchParams.get("panel");return i&&"wsd-mcp"!==i&&"wsd-view"!==i||t.searchParams.set("panel","wsd-overview"),{origin:t.origin,url:t.toString()}})(n),[n]),j=(null==R?void 0:R.url)??null;C.current={consoleTarget:b,getRuntimeFrame:h,onConsoleSnapshotChange:o,onDebugAction:a,onHighlightChange:d,onRuntimeSnapshotChange:u,preserveConsoleOnTargetChange:c,resolveTargetAtPoint:p};let P=(0,iD.useCallback)(e=>{var t,r;R&&(null==(r=_.current)||null==(t=r.contentWindow)||t.postMessage({source:mh,type:"wsd-show-panel",panelId:e},R.origin))},[R]),L=cl(()=>{var e,t;let r=S.current;r&&R&&(null==(t=_.current)||null==(e=t.contentWindow)||e.postMessage({source:mh,type:"wsd-debug-state",state:r},R.origin))});(0,iD.useEffect)(()=>{x.current=m??null},[m]),(0,iD.useEffect)(()=>{var e;I.current=y??null,null==(e=T.current)||e.call(T)},[y]),(0,iD.useEffect)(()=>{S.current=i,L()},[i,L,j]);let O=cl(()=>{L(),f&&P(f)});return((0,iD.useEffect)(()=>{f&&v&&P(f)},[P,f,v]),(0,iD.useEffect)(()=>{C.current.onHighlightChange(null);let e=null==R?void 0:R.origin;M.current??=document.createElement("div");let t=new u8(k.current??M.current,{consoleTarget:C.current.consoleTarget,getAppTarget:()=>I.current,getRuntimeFrame:()=>C.current.getRuntimeFrame?C.current.getRuntimeFrame():x.current,onHighlightChange:e=>C.current.onHighlightChange(e),get preserveConsoleOnTargetChange(){return C.current.preserveConsoleOnTargetChange},resolveTargetAtPoint:(e,t)=>{var r,i;return(null==(r=(i=C.current).resolveTargetAtPoint)?void 0:r.call(i,e,t))??null}});N.current=t;let r=0,i=e=>{var i;let n=null==(i=t.dispatch({id:--r,method:e}).result)?void 0:i.entries;return Array.isArray(n)?n:[]},n=()=>{var e,t;null==(e=(t=C.current).onConsoleSnapshotChange)||e.call(t,{appEntries:i("WSD.getAppConsoleEntries"),entries:i("WSD.getConsoleEntries"),updatedAtMs:Date.now()})},a=()=>{var e,r,i,n;let a=k.current;if(!a){null==(i=(n=C.current).onRuntimeSnapshotChange)||i.call(n,null);return}let s=t.getInspectorSnapshot();null==(e=(r=C.current).onRuntimeSnapshotChange)||e.call(r,hp(s.root,s.selectedUid,a))},s=t=>{var r,i;e&&(null==(i=_.current)||null==(r=i.contentWindow)||r.postMessage({source:mh,type:"cdp-raw-message",message:JSON.stringify(t)},e))};T.current=n,A.current=a;let o=t.subscribe(e=>{"WSD.consoleUpdated"===e.method||"WSD.appConsoleUpdated"===e.method?n():(s(e),("DOM.documentUpdated"===e.method||"DOM.inlineStyleInvalidated"===e.method||"Overlay.inspectNodeRequested"===e.method)&&a())});s({method:"DOM.documentUpdated"}),n(),a();let l=r=>{var i,n,a,o,l,d,u,c,p;if(!e||r.source!==(null==(i=_.current)?void 0:i.contentWindow)||r.origin!==e)return;let h=r.data;if((null==h?void 0:h.source)==="wsd-chrome-devtools-frontend"){if("ready"===h.type)return void O();if("wsd-debug-ready"===h.type)return void L();if("wsd-debug-action"===h.type){let e=h.action;if((null==e?void 0:e.kind)==="clear-sandbox-bridge-logs"||(null==e?void 0:e.kind)==="clear-trace-filter"||(null==e?void 0:e.kind)==="open-location-settings"){null==(n=(a=C.current).onDebugAction)||n.call(a,e);return}if((null==e?void 0:e.kind)==="update-sandbox-business-info"&&"string"==typeof e.phoneNum&&"string"==typeof e.csrPem){null==(o=(l=C.current).onDebugAction)||o.call(l,e);return}if((null==e?void 0:e.kind)==="recreate-sandbox-session"&&"string"==typeof e.phoneNum&&"string"==typeof e.csrPem){null==(d=(u=C.current).onDebugAction)||d.call(u,e);return}e&&("approve-tool-call"===e.kind||"reject-tool-call"===e.kind)&&"string"==typeof e.toolCallId&&(null==(c=(p=C.current).onDebugAction)||c.call(p,e));return}if("wsd-preact-devtools-message"===h.type)return void t.sendPreactDevtoolsMessage(h.payload);if("wsd-preact-highlight"===h.type){let e=h.uniqueId;t.highlightLynxNode("number"==typeof e?e:null);return}if("cdp-raw-message"===h.type&&"string"==typeof h.message){let e;try{e=JSON.parse(h.message)}catch{return}s(t.dispatch(e));return}}},d=t=>{let r=t.detail;if((null==r?void 0:r.type)==="PreactDevtools"&&"string"==typeof r.data)try{var i,n,a;i={type:"wsd-preact-devtools-message",payload:JSON.parse(r.data)},e&&(null==(a=_.current)||null==(n=a.contentWindow)||n.postMessage({source:mh,...i},e))}catch{}};return e&&(window.addEventListener("message",l),document.addEventListener("devtoolMessage",d)),()=>{window.removeEventListener("message",l),document.removeEventListener("devtoolMessage",d),o(),T.current===n&&(T.current=null),A.current===a&&(A.current=null),N.current===t&&(N.current=null),t.destroy(),C.current.onHighlightChange(null)}},[O,L,R]),(0,iD.useEffect)(()=>{var e,t,r,i;k.current=w,M.current??=document.createElement("div"),null==(e=N.current)||e.setConsoleTarget(b),null==(t=N.current)||t.setTarget(w??M.current),null==(r=T.current)||r.call(T),null==(i=A.current)||i.call(A)},[b,w]),(0,iD.useEffect)(()=>{if(!t||"render_page"===t.type||"render_widget"===t.type||"set_viewport"===t.type||"submit_chat_query"===t.type||"execute_sandbox_tool_call"===t.type||E.current===t.commandId)return;let e=void 0===r?k.current:r;if(("take_snapshot"===t.type||"take_screenshot"===t.type&&!t.uid)&&(!e||"take_snapshot"===t.type&&!g)){let e=window.setTimeout(()=>{E.current!==t.commandId&&(E.current=t.commandId,null==l||l(t.commandId,mg("TARGET_NOT_FOUND","No Page or Widget target is currently rendered")))},2e3);return()=>window.clearTimeout(e)}E.current=t.commandId,(async()=>{let r;try{r=await mf(t,N.current,e,g)}catch(e){r=mg("take_screenshot"===t.type?"SCREENSHOT_FAILED":"take_snapshot"===t.type?"SNAPSHOT_FAILED":"scroll_to"===t.type?"SCROLL_FAILED":"INSPECTION_FAILED",e instanceof Error?e.message:String(e))}null==l||l(t.commandId,r)})()},[t,r,l,g,w]),j)?(0,s.jsx)("aside",{className:"wsd-chrome-devtools",children:(0,s.jsx)("iframe",{allow:"clipboard-write",className:"wsd-chrome-devtools-frame",onLoad:O,ref:_,sandbox:"allow-scripts allow-same-origin allow-forms",src:j,title:"Chrome DevTools"})}):(0,s.jsx)("aside",{className:"wsd-chrome-devtools",children:(0,s.jsx)("div",{className:"wsd-chrome-devtools-empty",children:"Chrome DevTools frontend is not configured"})})}function my(e,t,r){return Math.min(Math.max(e,t),r)}function mb(e,t,r,i){if(!t)return my(e,r,i);let n=t.getBoundingClientRect().width;if(!n)return my(e,r,i);let a=Math.min(i,Math.max(r,n-8-340));return my(e,r,a)}function mw(){let{localConnectionStatus:e,reconnect:t}=cB();return"disconnected"!==e?null:(0,s.jsxs)("div",{className:"wsd-local-debug-connection-warning",role:"alert",children:[(0,s.jsx)("span",{children:"与本地调试服务的链接已断开"}),(0,s.jsx)("button",{onClick:t,type:"button",children:"重新连接"})]})}function m_(e){var t;let{activeView:r="conversation",className:i,onActiveViewChange:n,...a}=e,o=cg(a.webSdkDebugger),l="tool"===r&&0===Object.keys(o.manifest.raw.tools??{}).length?"conversation":r,[d,u]=(0,iD.useState)(h3),[c,p]=(0,iD.useState)(),[h,m]=(0,iD.useState)("page"===l),[g,f]=(0,iD.useState)("conversation"===l),v=(0,iD.useRef)(null),y=cl(e=>{v.current=e}),b=cl(e=>{var t;return(null==(t=v.current)?void 0:t.navigateBack(e))??!1}),w=cl(()=>{var e;null==(e=v.current)||e.exitApp(),null==n||n("conversation")}),[_,S]=(0,iD.useState)({onHighlightChange:()=>void 0,target:null}),x=cl(e=>{S(e)}),{isResizing:I,panelStyle:k,separatorProps:C}=function(){let{defaultWidth:e=520,minWidth:t=420,maxWidth:r=640}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},[i,n]=(0,iD.useState)(e),[a,s]=(0,iD.useState)(!1),o=(0,iD.useRef)(null),l=(0,iD.useMemo)(()=>({"--wsd-preview-column-width":`${i}px`}),[i]),d=cl((e,i)=>{if(!i)return;let a=i.getBoundingClientRect();a.width&&n(mb(e-a.left,i,t,r))});(0,iD.useEffect)(()=>()=>{var e;null==(e=o.current)||e.call(o)},[]);let u=cl(e=>{var t,r;if(0!==e.button)return;let i=e.currentTarget,n=i.parentElement;if(!n)return;e.preventDefault(),null==(t=o.current)||t.call(o),null==(r=i.setPointerCapture)||r.call(i,e.pointerId),d(e.clientX,n),s(!0);let a=document.body.style.cursor,l=document.body.style.userSelect;document.body.style.cursor="col-resize",document.body.style.userSelect="none";let u=e=>{d(e.clientX,n)},c=()=>{o.current===c&&(o.current=null,window.removeEventListener("pointermove",u),window.removeEventListener("pointerup",c),window.removeEventListener("pointercancel",c),document.body.style.cursor=a,document.body.style.userSelect=l,s(!1))};o.current=c,window.addEventListener("pointermove",u),window.addEventListener("pointerup",c),window.addEventListener("pointercancel",c)}),c=cl(e=>{let i=e.currentTarget.parentElement;if("ArrowLeft"===e.key){e.preventDefault(),n(e=>mb(e-24,i,t,r));return}if("ArrowRight"===e.key){e.preventDefault(),n(e=>mb(e+24,i,t,r));return}if("Home"===e.key){e.preventDefault(),n(mb(t,i,t,r));return}"End"===e.key&&(e.preventDefault(),n(mb(r,i,t,r)))});return{isResizing:a,panelStyle:l,separatorProps:{"aria-label":"Resize preview and DevTools","aria-orientation":"vertical","aria-valuemax":r,"aria-valuemin":t,"aria-valuenow":Math.round(i),onKeyDown:c,onPointerDown:u,role:"separator",tabIndex:0}}}({defaultWidth:340,maxWidth:560,minWidth:300}),E={...a,onWidgetNavigateBack:b,onWidgetExitApp:w,onChromeDevToolsPanelChange:x};(0,iD.useEffect)(()=>{"ready"===o.status.type&&r!==l&&(null==n||n(l))},[l,n,r,o.status.type]),(0,iD.useEffect)(()=>{"page"===l&&m(!0),"conversation"===l&&f(!0)},[l]);let N="tool"===l?(0,s.jsx)(h6,{...E,onActiveViewChange:n,onSessionChange:u,onUseWidgetOutput:e=>{let{viewData:t,widgetId:r}=e;a.webSdkDebugger.selectWidget(r),p(t),null==n||n("card")},session:d}):"card"===l?(0,s.jsx)(md,{...E,initDataDraft:c,onActiveViewChange:n}):null;return(0,s.jsxs)("section",{className:(0,rL.$)("page"===l?"wsd-page-panel":"wsd-widget-panel",I&&"is-resizing",i),style:k,children:[(0,s.jsxs)(c$,{enabled:!!((null==(t=a.debugContext)?void 0:t.sandboxEventsAvailable)&&!1!==a.debugContext.sandboxSessionAvailable),connection:a.connection,onMessage:a.onMessage,webSdkDebugger:a.webSdkDebugger,children:[(0,s.jsx)(mw,{}),"page"===l||h?(0,s.jsx)(h1,{...E,activeView:l,onActiveViewChange:n,onControllerChange:y}):null,"conversation"===l||g?(0,s.jsx)("div",{hidden:"conversation"!==l,style:{display:"conversation"===l?"contents":"none"},children:(0,s.jsx)(hU,{...E,activeView:l,controlCommand:"conversation"===l?a.controlCommand:void 0,onActiveViewChange:n,onChromeDevToolsPanelChange:"conversation"===l?x:void 0})}):null,N]}),(0,s.jsx)("div",{className:"wsd-runtime-splitter",...C}),(0,s.jsx)(mv,{..._})]})}function mS(e,t){var r,i,n;null==e||e({category:(null==(r=t.event)?void 0:r.startsWith("simulator_manifest_"))||(null==(i=t.event)?void 0:i.startsWith("simulator_skill_"))||(null==(n=t.event)?void 0:n.startsWith("simulator_resources_"))?"resource":"mcp",source:"local_mcp",...t})}function mx(e){return rR(e,{allowRootRelative:!0,baseUrl:window.location.href})}function mI(e){let t=function(e){let t={};for(let r of["content-type","content-length","x-tt-logid"]){let i=e.headers.get(r);i&&(t[r]=i)}return t}(e);return{status:e.status,status_text:e.statusText,response_headers:Object.keys(t).length>0?t:void 0}}function mk(e,t,r){mS(e,{event:`simulator_${t}_fetch_started`,phase:"request",url:r})}function mC(e,t,r,i){let n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};mS(e,{event:`simulator_${t}_fetch_succeeded`,phase:"response",url:r,...mI(i),...n})}function mE(e,t,r,i,n){mS(e,{event:`simulator_${t}_fetch_failed`,phase:"error",url:r,...n?mI(n):{},error:i instanceof Error?i.message:String(i)})}function mN(e,t,r){return Error(`Simulator ${e} failed: ${r.status} ${r.statusText} (${t})`)}let mT="web-sdk-debugger-demo",mA="mock_local_mcp",mM="mock_lookup",mR=["template-transport-card","template-price-action-card","weather-card","flight-card","api-demo-card","summary-card","configured-widget-id"],mj=[{server_id:mA,name:"Mock Local MCP",description:"Web SDK Debugger 本地模拟 MCP server",tools:[{name:mM,description:"返回用于本地调试的应用插件结构化结果",input_schema_json:JSON.stringify({type:"object",properties:{keyword:{type:"string"}},required:["keyword"]})}]}];function mP(e,t){return`id: evt_mock_${t.toString().padStart(4,"0")}
|
|
46
|
+
}`});this.getOverrideStyleElement().textContent=t.join("\n\n")}}class uw{listeners=new Set;elementInspector;styleInspector;consoleRecorder;selectedNodeId=null;consoleUnsubscribe=null;constructor(e,t={}){this.elementInspector=new uu(e,()=>this.notify({type:"document"})),this.styleInspector=new ub(e,this.elementInspector),this.consoleRecorder=new d$(e,t.consoleStore),this.consoleUnsubscribe=this.consoleRecorder.subscribe(()=>this.notify({type:"console"}))}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getDocument(){return this.elementInspector.getDocument()}getElement(e){return this.elementInspector.getElement(e)}getSelectedNodeId(){return this.selectedNodeId}selectNode(e){this.selectedNodeId!==e&&(this.selectedNodeId=e,this.notify({type:"selection"}))}getNodeIdAtPoint(e,t){return this.elementInspector.getNodeIdAtPoint(e,t)}findLynxViews(){return this.elementInspector.findLynxViews()}findNodeIdByLynxUniqueId(e){return this.elementInspector.findNodeIdByLynxUniqueId(e)}getNodeHighlight(e,t){return this.elementInspector.getHighlight(e,t)}getMatchedStyles(e){return this.styleInspector.getMatchedStyles(e)}setAttributesAsText(e,t,r){return this.elementInspector.setAttributesAsText(e,t,r)}setAttributeValue(e,t,r){return this.elementInspector.setAttributeValue(e,t,r)}removeAttribute(e,t){return this.elementInspector.removeAttribute(e,t)}setNodeValue(e,t){return this.elementInspector.setNodeValue(e,t)}setNodeName(e,t){let r=this.elementInspector.setNodeName(e,t);return this.selectedNodeId===e&&(this.selectedNodeId=r.nodeId),r}setOuterHTML(e,t){return this.elementInspector.setOuterHTML(e,t)}setInlineDeclaration(e,t,r,i,n){this.styleInspector.setInlineDeclaration(e,t,r,i,n),this.notify({type:"style",styleSheetId:`inline:${e}`})}setInlineDeclarations(e,t){this.styleInspector.setInlineDeclarations(e,t),this.notify({type:"style",styleSheetId:`inline:${e}`})}setRuleDeclaration(e,t,r,i,n,a){this.styleInspector.setRuleDeclaration(e,t,r,i,n,a),this.notify({type:"style",styleSheetId:`rule:${t}`})}setRuleDeclarations(e,t,r){this.styleInspector.setRuleDeclarations(e,t,r),this.notify({type:"style",styleSheetId:`rule:${t}`})}addRule(e,t,r){let i=this.styleInspector.addRule(e,t,r);return this.notify({type:"style",styleSheetId:i?`rule:${i.id}`:"inspector:main"}),i}setRuleSelector(e,t,r){let i=this.styleInspector.setRuleSelector(e,t,r);return this.notify({type:"style",styleSheetId:i?`rule:${i.id}`:`rule:${t}`}),i}getConsoleEntries(){return this.consoleRecorder.getEntries()}clearConsole(){this.consoleRecorder.clear()}evaluate(e){return this.consoleRecorder.evaluate(e)}destroy(){var e;null==(e=this.consoleUnsubscribe)||e.call(this),this.consoleUnsubscribe=null,this.elementInspector.destroy(),this.styleInspector.destroy(),this.consoleRecorder.destroy(),this.listeners.clear()}notify(e){for(let t of this.listeners)t(e)}}async function u_(e){let t,r="string"==typeof(t=[e.url,e.src,e.getAttribute("url"),e.getAttribute("src")].find(e=>"string"==typeof e&&e.trim()))?t.trim():void 0;if(!r||!/\.web\.bundle(?:[?#]|$)/.test(r))return;let i=new URL(r,window.location.href);i.pathname+=".map";let n=await fetch(i.href).catch(()=>void 0);if(!(null==n?void 0:n.ok))return;let a=await n.text();return{content:"",sourceMapURL:`data:application/json;charset=utf-8,${encodeURIComponent(a)}`,url:r}}let uS=new Set(["class","style"]);function ux(e){var t;return"element"!==e.type?null:(null==(t=e.attributes.find(e=>e.name===dB))?void 0:t.value)??null}function uI(e){var t;return(null==(t=e.attributes.find(e=>"doubao-children"===e.name))?void 0:t.value)==="all"}function uk(e){return e.attributes.some(e=>"doubao-slot"===e.name)}function uC(e){return e.attributes.filter(e=>uS.has(e.name)).map(e=>"class"===e.name?{name:e.name,value:dV(e.value.split(/\s+/)).join(" ")}:e).filter(e=>e.value)}function uE(e){return Array.isArray(e)?"array":void 0}function uN(e){return Array.isArray(e)?`Array(${e.length})`:uT(e)}function uT(e){if(Array.isArray(e))return"Array";try{var t,r;return(null==(r=Object.getPrototypeOf(e))||null==(t=r.constructor)?void 0:t.name)||"Object"}catch{return"Object"}}function uA(e,t){let r=uM(t),i="object"==typeof t&&null!==t||"function"==typeof t;return{name:e,type:r,subtype:i?uE(t):void 0,value:i?uN(t):String(t)}}function uM(e){return null===e?"object":typeof e}function uR(e,t){if(void 0===e)return{type:"undefined",description:"undefined"};if(null===e)return{type:"object",subtype:"null",value:null,description:"null"};let r=function(e){if("number"==typeof e){if(Object.is(e,-0))return"-0";let t=String(e);return"NaN"===t||"Infinity"===t||"-Infinity"===t?t:void 0}return"bigint"==typeof e?`${e}n`:void 0}(e);if(r)return{type:uM(e),unserializableValue:r,description:r};if("symbol"==typeof e)return{type:"symbol",description:String(e)};if("object"==typeof e&&null!==e||"function"==typeof e){let r;return{type:"function"==typeof e?"function":"object",subtype:"function"==typeof e?void 0:uE(e),className:"function"==typeof e?"Function":uT(e),description:"function"==typeof e?e.toString():uN(e),objectId:null==t?void 0:t.register(e),preview:"function"==typeof e||Array.isArray(e)?void 0:(r=function(e){try{return Object.keys(e)}catch{return[]}}(e),{type:"object",subtype:uE(e),description:uN(e),overflow:r.length>5,properties:r.slice(0,5).map(t=>{try{let r=Object.getOwnPropertyDescriptor(e,t);return uA(t,r&&"value"in r?r.value:void 0)}catch{return uA(t,void 0)}})})}}return{type:uM(e),value:e,description:String(e)}}function uj(e,t){return(e.args??[e.message]).map(e=>uR(e,t))}function uP(e,t){return{startLine:0,startColumn:e,endLine:0,endColumn:t}}function uL(e,t){let r=0,i="",n=t.map(e=>{let t=`${e.name}: ${e.value}${e.priority?` !${e.priority}`:""};`,n=e.active?t:`/* ${t} */`,a=uP(r,r+n.length);return i+=`${n} `,r=i.length,{name:e.name,value:e.value,important:"important"===e.priority,disabled:!e.active,parsedOk:!0,implicit:!1,text:n,range:a}});return{styleSheetId:e,cssText:i.trim(),range:uP(0,Math.max(0,i.trim().length)),shorthandEntries:[],cssProperties:n}}function uO(e){let t=e.indexOf(":");return t<0?{kind:e,id:""}:{kind:e.slice(0,t),id:e.slice(t+1)}}function uD(e){let t,r=e.includes("{")?e.slice(e.indexOf("{")+1,e.lastIndexOf("}")):e,i=[],n=/\/\*([\s\S]*?)\*\//g,a=0;for(;t=n.exec(r);)i.push(...uU(r.slice(a,t.index),!0)),i.push(...uU(t[1],!1)),a=t.index+t[0].length;return i.push(...uU(r.slice(a),!0)),i}function uU(e,t){let r=[];for(let i of e.split(";")){let e=i.indexOf(":");if(e<=0)continue;let n=i.slice(0,e).trim(),a=i.slice(e+1).trim(),s="";/!\s*important$/i.test(a)&&(a=a.replace(/!\s*important$/i,"").trim(),s="important"),n&&r.push({name:n,value:a,priority:s,active:t})}return r}function uq(e){if("element"!==e.type||"div"!==e.name)return!1;let t=e.attributes.find(e=>"part"===e.name);return(null==t?void 0:t.value)==="page"}function u$(e){return uq(e)?e.attributes.filter(e=>"part"!==e.name&&"lynx-default-overflow-visible"!==e.name):e.attributes}function uB(e){return u$(e).flatMap(e=>[e.name,e.value])}function uF(e){return uq(e)?"page":dz.get(e.name)??e.name}function uz(e,t){var r;return null==(r=e.attributes.find(e=>e.name===t))?void 0:r.value}function uW(e,t){return e.type===t.type&&e.name===t.name&&(t.id?uz(e,"id")===t.id:!t.className||uz(e,"class")===t.className)}function uH(e,t){let r=Number(e);return Number.isFinite(r)?r<0?1/0:r:t}function uV(e){return 1/0===e?e:Math.max(0,e-1)}function uG(e){if("text"===e.type)return e.textContent??"";if("document"===e.type)return uJ(e);let t=u$(e).map(e=>` ${e.name}="${e.value}"`).join(""),r=e.children.map(e=>uG(e)).join(""),i=uF(e);return`<${i}${t}>${r}</${i}>`}function uJ(e){return e.children.map(e=>uG(e)).join("")}function uK(e,t){let r=(e,i)=>{let n=[...i,e];if(e.id===t)return n;for(let t of e.children){let e=r(t,n);if(e)return e}return null};return r(e,[])}let uZ="__wsd_document__";function uX(e){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation()}let uY="wsd-main-frame";function uQ(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function u0(e){var t;let r;if(e instanceof ArrayBuffer)return{base64Encoded:!0,body:ob(e),byteLength:e.byteLength};if("string"==typeof e)r=e;else if(void 0===e)r="";else try{r=JSON.stringify(e)??String(e)}catch{r=String(e)}return{base64Encoded:!1,body:r,byteLength:(t=r,new TextEncoder().encode(t).byteLength)}}function u1(e){throw Object.assign(Error(e),{code:-32602})}function u2(e,t,r){return e??u1(null===e?r:t)}class u3{emit;enabledSessions=new Map;payloads=new Map;requests=new Map;unsubscribe;maxTotalBufferSize=262144e3;storedPayloadSize=0;constructor(e){this.emit=e}enable(e,t){var r;return this.unsubscribe??=(r=this.handleRequestLifecycle,ou.add(r),()=>ou.delete(r)),this.enabledSessions.set(t,{maxPostDataSize:uQ(null==e?void 0:e.maxPostDataSize,65536),maxTotalBufferSize:uQ(null==e?void 0:e.maxTotalBufferSize,262144e3)}),this.refreshBufferLimit(),{}}disable(e){for(let[t,r]of(this.enabledSessions.delete(e),this.requests))r.sessions.delete(e),0===r.sessions.size&&this.deleteRequest(t,r);if(0===this.enabledSessions.size){var t;null==(t=this.unsubscribe)||t.call(this),this.unsubscribe=void 0,this.clearRequests()}else this.refreshBufferLimit();return{}}getRequestPostData(e,t){let r=u2(this.getRequest(e,t).requestBody,"No post data was sent with this request","Request post data is no longer available");return{postData:r.body,base64Encoded:r.base64Encoded}}getResponseBody(e,t){let r=u2(this.getRequest(e,t).responseBody,"No response body is available for this request","Response body is no longer available");return{body:r.body,base64Encoded:r.base64Encoded}}destroy(){var e;null==(e=this.unsubscribe)||e.call(this),this.unsubscribe=void 0,this.enabledSessions.clear(),this.clearRequests()}handleRequestLifecycle=e=>{if("request"===e.phase)return void this.handleRequestStarted(e);let t=this.requests.get(e.requestId);if(t){if("response"===e.phase)return void this.handleResponseReceived(e,t);this.emitForRequest(t,{method:"Network.loadingFailed",params:{canceled:!1,errorText:e.errorText,requestId:e.requestId,timestamp:e.timestamp,type:"XHR"}})}};handleRequestStarted(e){var t;let r;if(0===this.enabledSessions.size)return;let i=void 0===e.request.body?void 0:u0(e.request.body),n={request:e.request,sessions:new Set(this.enabledSessions.keys())};this.requests.set(e.requestId,n),i&&this.storePayload(n,"requestBody",i);let a=(r=(t=e.request.url).indexOf("#"))<0?{url:t}:{url:t.slice(0,r),urlFragment:t.slice(r)};for(let t of n.sessions){let r=this.enabledSessions.get(t);if(!r)continue;let n=i&&!i.base64Encoded&&i.byteLength<=r.maxPostDataSize;this.emit({method:"Network.requestWillBeSent",params:{documentURL:a.url,frameId:uY,initiator:{type:"script"},loaderId:uY,redirectHasExtraInfo:!1,request:{...a,hasPostData:!!i,headers:e.request.headers,initialPriority:"High",isSameSite:!0,method:e.request.method,mixedContentType:"none",postData:n?i.body:void 0,referrerPolicy:"no-referrer"},requestId:e.requestId,timestamp:e.timestamp,type:"XHR",wallTime:e.wallTime}},t)}}handleResponseReceived(e,t){var r;let i=e.response??{},n=!(r=i.header)||"object"!=typeof r||Array.isArray(r)?{}:Object.fromEntries(Object.entries(r).map(e=>{let[t,r]=e;return[t,String(r)]})),a=u0(i.data),{charset:s,mimeType:o}=function(e){var t,r;let i,n=(null==(i=Object.entries(e).find(e=>{let[t]=e;return"content-type"===t.toLowerCase()}))?void 0:i[1])??"",[a=""]=n.split(";");return{charset:(null==(r=/(?:^|;)\s*charset\s*=\s*["']?([^;"']+)/i.exec(n))||null==(t=r[1])?void 0:t.trim())??"",mimeType:a.trim()}}(n),l="number"==typeof i.statusCode&&Number.isFinite(i.statusCode)?i.statusCode:0;this.storePayload(t,"responseBody",a),this.emitForRequest(t,{method:"Network.responseReceived",params:{frameId:uY,hasExtraInfo:!1,loaderId:uY,requestId:e.requestId,response:{charset:s,connectionId:0,connectionReused:!1,encodedDataLength:a.byteLength,fromDiskCache:!1,fromPrefetchCache:!1,fromServiceWorker:!1,headers:n,mimeType:o,protocol:"",requestHeaders:t.request.headers,responseTime:1e3*e.wallTime,securityState:"unknown",status:l,statusText:"",url:t.request.url},timestamp:e.timestamp,type:"XHR"}}),this.emitForRequest(t,{method:"Network.loadingFinished",params:{encodedDataLength:a.byteLength,requestId:e.requestId,timestamp:e.timestamp}})}emitForRequest(e,t){for(let r of e.sessions)this.enabledSessions.has(r)&&this.emit(t,r)}getRequest(e,t){let r="string"!=typeof(null==e?void 0:e.requestId)||0===e.requestId.length?u1("requestId must be a non-empty string"):e.requestId,i=this.requests.get(r);return(null==i?void 0:i.sessions.has(t))?i:u1(`Unknown requestId: ${r}`)}storePayload(e,t,r){let i=e[t];i&&(this.payloads.delete(i),this.storedPayloadSize-=i.byteLength),e[t]=r,this.payloads.set(r,[e,t]),this.storedPayloadSize+=r.byteLength,this.evictPayloads()}evictPayloads(){for(;this.storedPayloadSize>this.maxTotalBufferSize;){let e=this.payloads.entries().next().value;if(!e)return;let[t,[r,i]]=e;this.payloads.delete(t),this.storedPayloadSize-=t.byteLength,r[i]=null}}refreshBufferLimit(){this.maxTotalBufferSize=Math.min(...[...this.enabledSessions.values()].map(e=>e.maxTotalBufferSize)),this.evictPayloads()}deleteRequest(e,t){for(let e of[t.requestBody,t.responseBody])e&&(this.payloads.delete(e),this.storedPayloadSize-=e.byteLength);this.requests.delete(e)}clearRequests(){this.requests.clear(),this.payloads.clear(),this.storedPayloadSize=0}}class u4{cdpNodes=new Map;nodeIds=new Map;inspectorNodeIds=new Map;nextNodeId=0;get size(){return this.nodeIds.size}reset(){this.cdpNodes.clear(),this.nodeIds.clear(),this.inspectorNodeIds.clear(),this.nextNodeId=0}getCdpNodeId(e){let t=this.nodeIds.get(e);if(t)return t;let r=++this.nextNodeId;return this.nodeIds.set(e,r),this.inspectorNodeIds.set(r,e),r}getExistingCdpNodeId(e){return this.nodeIds.get(e)}getInspectorNodeId(e){return this.inspectorNodeIds.get(e)}resolveInspectorNodeId(e){let t=this.inspectorNodeIds.get(Number(e));if(!t)throw Object.assign(Error(`Unknown nodeId: ${String(e)}`),{code:-32602});return t}toDocumentCdpNode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1/0,r=this.getCdpNodeId(uZ),i=uV(t),n=t>0?[this.toCdpNode(e,i,r)]:void 0,a={nodeId:r,backendNodeId:r,nodeType:9,nodeName:"#document",localName:"",nodeValue:"",childNodeCount:1,frameId:"wsd-main-frame",documentURL:"wsd://runtime",baseURL:"wsd://runtime",publicId:"",systemId:"",xmlVersion:"",children:n};return this.cdpNodes.set(r,a),a}toCdpNode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1/0,r=arguments.length>2?arguments[2]:void 0,i=this.getCdpNodeId(e.id),n=uV(t),a=t>0?e.children.map(e=>this.toCdpNode(e,n,i)):void 0,s="text"===e.type,o="document"===e.type,l=uF(e),d={nodeId:i,backendNodeId:i,parentId:r,nodeType:"text"===e.type?3:"document"===e.type?11:1,nodeName:s||o?e.name:l.toUpperCase(),localName:s||o?"":l,nodeValue:e.textContent??"",childNodeCount:e.children.length,frameId:o?"wsd-main-frame":void 0,documentURL:o?"wsd://runtime":void 0,baseURL:o?"wsd://runtime":void 0,publicId:o?"":void 0,systemId:o?"":void 0,xmlVersion:o?"":void 0,name:s?e.name:void 0,value:s?e.textContent??"":void 0,attributes:"element"===e.type?uB(e):void 0,children:a};return this.cdpNodes.set(i,d),d}}function u6(e){return e.map(e=>({...e}))}function u5(e){return"attributes"===e.type||"characterData"===e.type}class u8{adapter;consoleAdapter=null;appAdapter=null;appTarget=null;target;listeners=new Set;options;nodeStore=new u4;network;consoleStore=dM();appConsoleStore=dM();knownConsoleEntryIdsBySession=new Map;preservingConsoleOnTargetChange;knownStyleSheetIds=new Set;unsubscribeAdapter=null;unsubscribeConsoleAdapter=null;unsubscribeAppAdapter=null;stopInspectModeListener=null;selectedNodeSignaturePath=null;preferredNodeSignaturePath=null;pendingDocumentRevealSignaturePath=null;shouldRevealDocumentAfterUpdate=!1;activeSessionId;isApplyingStyleEdit=!1;runtimeEnabledSessions=new Set;debuggerEnabledSessions=new Set;nextScriptId=0;scriptIdsByUrl=new Map;sourceScriptsById=new Map;parsedScriptIdsBySession=new Map;sourceLoadId=0;undoEntries=[];pendingUndoEntry=null;nextRemoteObjectId=0;remoteObjects=new Map;remoteObjectStore={get:e=>this.remoteObjects.get(e),register:e=>this.registerRemoteObject(e)};constructor(e,t){this.target=e,this.options=t,this.preservingConsoleOnTargetChange=!!t.preserveConsoleOnTargetChange,this.adapter=this.createTargetAdapter(e),this.network=new u3((e,t)=>this.emit(e,t)),this.subscribeAdapter(),this.createConsoleAdapter(),this.loadSources(e)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getInspectorSnapshot(){return{root:this.adapter.getDocument(),selectedUid:this.adapter.getSelectedNodeId()}}getComputedStyles(e,t){var r;let i=null==(r=this.adapter.getMatchedStyles(e))?void 0:r.computedStyles;if(!i)return null;if(!(null==t?void 0:t.length))return i;let n=new Set(t);return i.filter(e=>n.has(e.name))}getElementRect(e){let t=this.options.getRuntimeFrame(),r=t?this.adapter.getNodeHighlight(e,t):null;return r?{x:r.left,y:r.top,width:r.width,height:r.height}:null}getElement(e){return this.adapter.getElement(e)}dispatch(e){e.sessionId&&(this.activeSessionId=e.sessionId);try{let t={id:e.id,result:this.handleRequest(e)};return e.sessionId&&(t.sessionId=e.sessionId),t}catch(i){let t,r={id:e.id,error:{code:"number"==typeof(t=null==i?void 0:i.code)?t:-32603,message:i instanceof Error?i.message:String(i)}};return e.sessionId&&(r.sessionId=e.sessionId),r}}destroy(){var e,t,r,i,n;this.sourceLoadId++,this.stopInspectMode(),null==(e=this.unsubscribeAdapter)||e.call(this),this.unsubscribeAdapter=null,null==(t=this.unsubscribeConsoleAdapter)||t.call(this),this.unsubscribeConsoleAdapter=null,null==(r=this.consoleAdapter)||r.destroy(),this.consoleAdapter=null,null==(i=this.unsubscribeAppAdapter)||i.call(this),this.unsubscribeAppAdapter=null,null==(n=this.appAdapter)||n.destroy(),this.appAdapter=null,this.appTarget=null,this.adapter.destroy(),this.network.destroy(),this.sourceScriptsById.clear(),this.remoteObjects.clear(),this.listeners.clear(),this.options.onHighlightChange(null)}subscribeAdapter(){this.unsubscribeAdapter=this.adapter.subscribe(this.handleAdapterChange)}createConsoleAdapter(){let e=this.options.consoleTarget;e&&e!==this.target&&(this.consoleAdapter=new uw(e,{consoleStore:this.consoleStore}),this.unsubscribeConsoleAdapter=this.consoleAdapter.subscribe(e=>{"console"===e.type&&this.handleConsoleChange()}))}getConsoleAdapter(){return this.consoleAdapter??this.adapter}createTargetAdapter(e){return new uw(e,{consoleStore:this.options.preserveConsoleOnTargetChange?this.consoleStore:void 0})}createAppTargetAdapter(e){return new uw(e,{consoleStore:this.appConsoleStore})}subscribeAppAdapter(){var e;this.unsubscribeAppAdapter=(null==(e=this.appAdapter)?void 0:e.subscribe(e=>{"console"===e.type&&(this.emitUnseenConsoleEntries("app"),this.emit({method:"WSD.appConsoleUpdated"}))}))??null}handleAdapterChange=e=>{if("document"===e.type){if(!this.pendingDocumentRevealSignaturePath){let e=this.preferredNodeSignaturePath??this.selectedNodeSignaturePath;this.pendingDocumentRevealSignaturePath=e?[...e]:null}this.nodeStore.reset(),this.shouldRevealDocumentAfterUpdate=!0,this.emit({method:"DOM.documentUpdated"});return}if("console"===e.type){this.consoleAdapter||this.handleConsoleChange();return}"selection"===e.type?this.emitSelectedStyleInvalidated():this.isApplyingStyleEdit||(this.emitSelectedStyleInvalidated(),this.emit({method:"CSS.styleSheetChanged",params:{styleSheetId:e.styleSheetId??"inspector:main"}}))};setConsoleTarget(e){var t,r;this.options.consoleTarget!==e&&(null==(t=this.unsubscribeConsoleAdapter)||t.call(this),this.unsubscribeConsoleAdapter=null,null==(r=this.consoleAdapter)||r.destroy(),this.consoleAdapter=null,this.options.consoleTarget=e,this.createConsoleAdapter(),this.emitUnseenConsoleEntries(),this.emit({method:"WSD.consoleUpdated"}))}setTarget(e){var t;if(this.target===e)return;let r=!!this.options.preserveConsoleOnTargetChange,i=r!==this.preservingConsoleOnTargetChange;if(this.preservingConsoleOnTargetChange=r,null==(t=this.unsubscribeAdapter)||t.call(this),this.unsubscribeAdapter=null,this.adapter.destroy(),this.target=e,this.adapter=this.createTargetAdapter(e),this.nodeStore.reset(),this.knownStyleSheetIds.clear(),this.sourceScriptsById.clear(),this.parsedScriptIdsBySession.clear(),!this.consoleAdapter&&!this.options.preserveConsoleOnTargetChange){for(let e of this.knownConsoleEntryIdsBySession.values())e.delete("current");0===this.appConsoleStore.entries.length&&this.remoteObjects.clear()}this.selectedNodeSignaturePath=null,this.preferredNodeSignaturePath=null,this.pendingDocumentRevealSignaturePath=null,this.shouldRevealDocumentAfterUpdate=!1,this.undoEntries.length=0,this.pendingUndoEntry=null,this.subscribeAdapter(),this.loadSources(e),this.appTarget&&this.loadAppSource(this.appTarget),i&&this.clearConsoleForTargetScopeChange(),this.emit({method:"DOM.documentUpdated"}),this.emitUnseenConsoleEntries(),this.emit({method:"WSD.consoleUpdated"})}handleConsoleChange(){this.emitUnseenConsoleEntries(),this.emit({method:"WSD.consoleUpdated"})}getAppAdapter(){var e,t,r,i,n,a;let s=(null==(e=(t=this.options).getAppTarget)?void 0:e.call(t))??null;return s?(this.appAdapter&&this.appTarget===s||(null==(r=this.unsubscribeAppAdapter)||r.call(this),this.unsubscribeAppAdapter=null,null==(i=this.appAdapter)||i.destroy(),this.appTarget=s,this.appAdapter=this.createAppTargetAdapter(s),this.subscribeAppAdapter(),this.loadAppSource(s),this.emit({method:"WSD.appConsoleUpdated"})),this.appAdapter):(null==(n=this.unsubscribeAppAdapter)||n.call(this),this.unsubscribeAppAdapter=null,null==(a=this.appAdapter)||a.destroy(),this.appAdapter=null,this.appTarget=null,null)}handleRequest(e){switch(e.method){case"DOM.enable":case"CSS.enable":case"Overlay.enable":case"Page.enable":case"Log.enable":case"CSS.trackComputedStyleUpdatesForNode":case"Page.removeScriptToEvaluateOnNewDocument":case"Log.startViolationsReport":case"Runtime.addBinding":case"Runtime.removeBinding":case"Runtime.runIfWaitingForDebugger":case"Runtime.setCustomObjectFormatterEnabled":return{};case"Runtime.enable":return this.runtimeEnabledSessions.add(e.sessionId),this.emitRuntimeExecutionContext(e.sessionId),this.emitUnseenConsoleEntriesForSession(e.sessionId),this.getAppAdapter(),this.emitUnseenConsoleEntriesForSession(e.sessionId,"app"),{};case"Runtime.disable":return this.runtimeEnabledSessions.delete(e.sessionId),this.knownConsoleEntryIdsBySession.delete(e.sessionId),{};case"Debugger.enable":return this.debuggerEnabledSessions.add(e.sessionId),this.getAppAdapter(),this.emitUnseenConsoleEntries("app"),this.emitSourceScripts(e.sessionId),{debuggerId:"wsd-debugger"};case"Debugger.disable":return this.debuggerEnabledSessions.delete(e.sessionId),this.parsedScriptIdsBySession.delete(e.sessionId),{};case"Debugger.getScriptSource":return this.getScriptSource(e.params);case"DOM.getFlattenedDocument":return this.getFlattenedDocument();case"DOM.getDocument":return this.getDocument(e.params,e.sessionId);case"DOM.requestChildNodes":return this.requestChildNodes(e.params,e.sessionId);case"DOM.describeNode":return this.describeNode(e.params);case"DOM.getAttributes":return this.getAttributes(e.params);case"DOM.getOuterHTML":return this.getOuterHTML(e.params);case"DOM.setAttributesAsText":return this.setAttributesAsText(e.params,e.sessionId);case"DOM.setAttributeValue":return this.setAttributeValue(e.params,e.sessionId);case"DOM.removeAttribute":return this.removeAttribute(e.params,e.sessionId);case"DOM.setNodeValue":return this.setNodeValue(e.params,e.sessionId);case"DOM.setNodeName":return this.setNodeName(e.params,e.sessionId);case"DOM.setOuterHTML":return this.setOuterHTML(e.params,e.sessionId);case"DOM.getBoxModel":return this.getBoxModel(e.params);case"DOM.pushNodesByBackendIdsToFrontend":return this.pushNodesByBackendIdsToFrontend(e.params,e.sessionId);case"DOM.markUndoableState":return this.markUndoableState();case"DOM.undo":return this.undo(e.sessionId);case"DOM.querySelector":return{nodeId:0};case"DOM.querySelectorAll":case"DOM.getSearchResults":return{nodeIds:[]};case"DOM.performSearch":return{searchId:"wsd-empty-search",resultCount:0};case"DOM.resolveNode":return this.resolveNode(e.params);case"CSS.getMatchedStylesForNode":return this.getMatchedStylesForNode(e.params);case"CSS.getInlineStylesForNode":return this.getInlineStylesForNode(e.params);case"CSS.getComputedStyleForNode":return this.getComputedStyleForNode(e.params);case"CSS.getPlatformFontsForNode":return{fonts:[]};case"CSS.getMediaQueries":return{medias:[]};case"CSS.getEnvironmentVariables":return{environmentVariables:{}};case"CSS.getBackgroundColors":return{backgroundColors:[],computedFontSize:"",computedFontWeight:"",computedBodyFontSize:""};case"CSS.getStyleSheetText":return this.getStyleSheetText(e.params);case"CSS.resolveValues":return this.resolveCssValues(e.params);case"CSS.setStyleTexts":return this.setStyleTexts(e.params);case"CSS.setEffectivePropertyValueForNode":return this.setEffectivePropertyValueForNode(e.params);case"CSS.createStyleSheet":return{styleSheetId:"inspector:main"};case"CSS.addRule":return this.addRule(e.params);case"CSS.setRuleSelector":return this.setRuleSelector(e.params);case"Page.getResourceTree":case"Page.getFrameTree":return this.getFrameTree();case"Page.getNavigationHistory":return{currentIndex:0,entries:[{id:1,url:"wsd://runtime",title:"Web SDK Runtime",transitionType:"typed"}]};case"Page.getLayoutMetrics":return this.getLayoutMetrics();case"Page.createIsolatedWorld":return{executionContextId:1};case"Page.addScriptToEvaluateOnNewDocument":return{identifier:"wsd-script"};case"Page.getCookies":return{cookies:[]};case"Page.getAppManifest":return{url:"",errors:[],data:""};case"Network.enable":return this.network.enable(e.params,e.sessionId);case"Network.disable":return this.network.disable(e.sessionId);case"Network.getRequestPostData":return this.network.getRequestPostData(e.params,e.sessionId);case"Network.getResponseBody":return this.network.getResponseBody(e.params,e.sessionId);case"Network.emulateNetworkConditionsByRule":return{ruleIds:[]};case"Performance.getMetrics":return{metrics:[]};case"Memory.getDOMCounters":return{documents:1,nodes:this.nodeStore.size,jsEventListeners:0};case"SystemInfo.getInfo":return{gpu:{devices:[],auxAttributes:{},featureStatus:{},driverBugWorkarounds:[]},modelName:"Web SDK Debugger",modelVersion:"",commandLine:""};case"Browser.getVersion":return{protocolVersion:"1.3",product:"Web SDK Debugger",revision:"",userAgent:"u"<typeof navigator?"":navigator.userAgent,jsVersion:""};case"Schema.getDomains":return{domains:[]};case"Runtime.evaluate":return this.evaluate(e.params);case"Runtime.getProperties":return this.getRuntimeProperties(e.params);case"Runtime.callFunctionOn":case"Runtime.awaitPromise":return{result:{type:"undefined",description:"undefined"}};case"Runtime.releaseObject":var t;return"string"==typeof(null==(t=e.params)?void 0:t.objectId)&&this.remoteObjects.delete(e.params.objectId),{};case"Runtime.releaseObjectGroup":return this.remoteObjects.clear(),{};case"Runtime.discardConsoleEntries":case"Console.clearMessages":case"Log.clear":return this.clearConsole(),{};case"Overlay.highlightNode":return this.highlightNode(e.params);case"Overlay.hideHighlight":return this.options.onHighlightChange(null),{};case"Overlay.setInspectMode":return this.setInspectMode(e.params,e.sessionId);case"WSD.getConsoleEntries":return{entries:this.getConsoleAdapter().getConsoleEntries().map(e=>this.toConsoleEntry(e))};case"WSD.getAppConsoleEntries":return this.getAppAdapter(),this.emitUnseenConsoleEntries("app"),{entries:this.appConsoleStore.entries.map(e=>this.toConsoleEntry(e))};case"WSD.clearAppConsole":return this.clearAppConsole(),{};case"WSD.setStyleDeclaration":return this.setStyleDeclaration(e.params);default:if(function(e){let[t,r]=e.split(".");return new Set(["Audits","Browser","DOMDebugger","Debugger","Emulation","HeapProfiler","IndexedDB","Inspector","LayerTree","Memory","Network","Performance","Profiler","Security","ServiceWorker","Storage","Target"]).has(t)||"enable"===r||"disable"===r||(null==r?void 0:r.startsWith("set"))||(null==r?void 0:r.startsWith("clear"))||(null==r?void 0:r.startsWith("stop"))}(e.method))return{};throw Object.assign(Error(`Unsupported CDP method: ${e.method}`),{code:-32601})}}getDocument(e,t){let r=this.getInspectorDocument(),i=uH(null==e?void 0:e.depth,1);if(r&&this.shouldRevealDocumentAfterUpdate){let e=this.pendingDocumentRevealSignaturePath?[...this.pendingDocumentRevealSignaturePath]:null;this.shouldRevealDocumentAfterUpdate=!1,window.setTimeout(()=>this.revealDocumentAfterUpdate(r,t,e),0)}return{root:r?this.nodeStore.toDocumentCdpNode(r,i):null}}getFlattenedDocument(){let e=this.getDocument({depth:-1}).root;return{nodes:e?function e(t){return[t,...(t.children??[]).flatMap(t=>e(t))]}(e):[]}}requestChildNodes(e,t){let r=Number(null==e?void 0:e.nodeId),i=this.nodeStore.resolveInspectorNodeId(r),n=uH(null==e?void 0:e.depth,1),a=this.getInspectorDocument(),s=i===uZ?null:this.findInspectorNode(i),o=i===uZ?a?[this.nodeStore.toCdpNode(a,uV(n),r)]:[]:(null==s?void 0:s.children.map(e=>this.nodeStore.toCdpNode(e,uV(n),r)))??[];return this.emit({method:"DOM.setChildNodes",params:{parentId:r,nodes:o}},t),{}}pushNodesByBackendIdsToFrontend(e,t){let r=this.getInspectorDocument();return{nodeIds:(Array.isArray(null==e?void 0:e.backendNodeIds)?e.backendNodeIds:[]).map(e=>{let i=Number(e),n=this.nodeStore.getInspectorNodeId(i);return r&&n&&this.materializeInspectorNodePath(r,n,t)?i:0})}}materializeInspectorNodePath(e,t,r){let i=uK(e,t);if(!i)return!1;let n=this.nodeStore.getCdpNodeId(uZ);for(let t of(this.emit({method:"DOM.setChildNodes",params:{parentId:n,nodes:[this.nodeStore.toCdpNode(e,0,n)]}},r),this.emit({method:"DOM.childNodeCountUpdated",params:{nodeId:n,childNodeCount:1}},r),i.slice(0,-1))){let e=this.nodeStore.getCdpNodeId(t.id),i=t.children.map(t=>this.nodeStore.toCdpNode(t,0,e));this.emit({method:"DOM.setChildNodes",params:{parentId:e,nodes:i}},r),this.emit({method:"DOM.childNodeCountUpdated",params:{nodeId:e,childNodeCount:i.length}},r)}return!0}revealDocumentAfterUpdate(e,t,r){if(!(null==r?void 0:r.length))return;let i=this.findInspectorNodeBySignaturePath(e,r??null),n=i??this.findDocumentRevealNode(e);if(!n||!this.materializeInspectorNodePath(e,n.id,t))return;let a=this.nodeStore.getCdpNodeId(n.id),s=!!i||!(null==r?void 0:r.length);this.selectInspectorNode(n.id,{rememberPreferred:s}),s&&(this.pendingDocumentRevealSignaturePath=null),this.emit({method:"Overlay.nodeHighlightRequested",params:{nodeId:a}},t),this.emit({method:"Overlay.inspectNodeRequested",params:{backendNodeId:a}},t)}findDocumentRevealNode(e){let t=this.adapter.getSelectedNodeId();if(t){let r=uK(e,t);if(r)return r[r.length-1]}let r=this.findInspectorNodeBySignaturePath(e,this.selectedNodeSignaturePath);if(r)return r;let i=e;for(let e=0;e<3;e+=1){let e=i.children.find(e=>"element"===e.type);if(!e)break;i=e}return i}selectInspectorNode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{rememberPreferred:!0};this.adapter.selectNode(e);let r=this.rememberSelectedNodePath(e);t.rememberPreferred&&r&&(this.preferredNodeSignaturePath=[...r])}rememberSelectedNodePath(e){let t=this.getInspectorDocument(),r=t?uK(t,e):null;if(r){let e=r.map(e=>({type:e.type,name:e.name,className:uz(e,"class"),id:uz(e,"id")}));return this.selectedNodeSignaturePath=e,e}return null}findInspectorNodeBySignaturePath(e,t){if(!(null==t?void 0:t.length)||!uW(e,t[0]))return null;let r=e;for(let e of t.slice(1)){let t=r.children.find(t=>uW(t,e));if(!t)return null;r=t}return r}resolveNode(e){let t=this.nodeStore.resolveInspectorNodeId((null==e?void 0:e.nodeId)??(null==e?void 0:e.backendNodeId));return{object:{objectId:`node:${t}`,type:"object",subtype:"node",className:"HTMLElement",description:t}}}describeNode(e){let t=Number((null==e?void 0:e.nodeId)??(null==e?void 0:e.backendNodeId)),r=this.nodeStore.resolveInspectorNodeId(t),i=this.findInspectorNode(r),n=this.getInspectorDocument();return{node:r===uZ&&n?this.nodeStore.toDocumentCdpNode(n):i?this.nodeStore.toCdpNode(i):null}}getAttributes(e){let t=this.findInspectorNode(this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId));return{attributes:t?uB(t):[]}}getOuterHTML(e){let t=this.nodeStore.resolveInspectorNodeId((null==e?void 0:e.nodeId)??(null==e?void 0:e.backendNodeId)),r=this.findInspectorNode(t),i=this.getInspectorDocument();return{outerHTML:t===uZ&&i?uG(i):r?uG(r):""}}setAttributesAsText(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),i=String((null==e?void 0:e.text)??""),n="string"==typeof(null==e?void 0:e.name)?e.name:void 0,a=this.applyDomEdit(()=>this.adapter.setAttributesAsText(r,i,n));return this.emitDomMutations(a,t),{}}setAttributeValue(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),i=String((null==e?void 0:e.name)??""),n=String((null==e?void 0:e.value)??""),a=this.applyDomEdit(()=>this.adapter.setAttributeValue(r,i,n));return this.emitDomMutations(a,t),{}}removeAttribute(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),i=String((null==e?void 0:e.name)??""),n=this.applyDomEdit(()=>this.adapter.removeAttribute(r,i));return this.emitDomMutations(n,t),{}}setNodeValue(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),i=String((null==e?void 0:e.value)??""),n=this.applyDomEdit(()=>this.adapter.setNodeValue(r,i));return this.emitDomMutations(n,t),{}}setNodeName(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),i=String((null==e?void 0:e.name)??""),n=this.applyDomEdit(()=>this.adapter.setNodeName(r,i),!0);return this.emitDomMutations(n.mutations,t),{nodeId:n.nodeId?this.nodeStore.getCdpNodeId(n.nodeId):0}}setOuterHTML(e,t){let r=this.nodeStore.resolveInspectorNodeId((null==e?void 0:e.nodeId)??(null==e?void 0:e.backendNodeId)),i=String((null==e?void 0:e.outerHTML)??""),n=this.applyDomEdit(()=>this.adapter.setOuterHTML(r,i),!0);return this.emitDomMutations(n,t),{}}applyDomEdit(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=t?this.adapter.getDocument():null,i=r?this.createDomRootSnapshot(r):null,n=e(),a=Array.isArray(n)?n:n.mutations,s=a.filter(u5),o=null;return a.length>0&&s.length===a.length?o={type:"mutations",mutations:s}:a.length>0&&i&&(o=i),o&&this.rememberDomUndoEntry(o),n}createDomRootSnapshot(e){return{type:"rootSnapshot",rootHtml:"document"===e.type?uJ(e):uG(e)}}emitDomMutations(e,t){for(let r of e){if("attributes"===r.type){for(let e of r.removed)this.emit({method:"DOM.attributeRemoved",params:{nodeId:this.nodeStore.getCdpNodeId(r.nodeId),name:e}},t);for(let e of r.modified)this.emit({method:"DOM.attributeModified",params:{nodeId:this.nodeStore.getCdpNodeId(r.nodeId),name:e.name,value:e.value}},t);continue}if("characterData"===r.type){this.emit({method:"DOM.characterDataModified",params:{nodeId:this.nodeStore.getCdpNodeId(r.nodeId),characterData:r.value}},t);continue}let e=this.nodeStore.getCdpNodeId(r.parentNodeId);for(let i of r.removedNodeIds)this.emit({method:"DOM.childNodeRemoved",params:{parentNodeId:e,nodeId:this.nodeStore.getCdpNodeId(i)}},t);for(let i of r.insertedNodes)this.emit({method:"DOM.childNodeInserted",params:{parentNodeId:e,previousNodeId:i.previousNodeId?this.nodeStore.getCdpNodeId(i.previousNodeId):0,node:this.nodeStore.toCdpNode(i.node,1/0,e)}},t);this.emit({method:"DOM.childNodeCountUpdated",params:{nodeId:e,childNodeCount:r.childNodeCount}},t)}}getMatchedStylesForNode(e){let t=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId);this.selectInspectorNode(t,{rememberPreferred:!this.pendingDocumentRevealSignaturePath&&!this.preferredNodeSignaturePath});let r=this.adapter.getMatchedStyles(t);return r?{inlineStyle:uL(`inline:${t}`,r.inlineStyle.declarations),attributesStyle:null,matchedCSSRules:r.matchedRules.map(e=>({matchingSelectors:[0],rule:this.toCdpRulePayload(e)})),pseudoElements:[],inherited:[],cssKeyframesRules:[]}:{inlineStyle:null,attributesStyle:null,matchedCSSRules:[],pseudoElements:[],inherited:[],cssKeyframesRules:[]}}getInlineStylesForNode(e){let t=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),r=this.adapter.getMatchedStyles(t);return{inlineStyle:r?uL(`inline:${t}`,r.inlineStyle.declarations):null,attributesStyle:null}}getComputedStyleForNode(e){let t=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),r=this.adapter.getMatchedStyles(t);return{computedStyle:((null==r?void 0:r.computedStyles)??[]).map(e=>({name:e.name,value:e.value}))}}resolveCssValues(e){return{results:Array.isArray(null==e?void 0:e.values)?e.values.map(String):[]}}setStyleTexts(e){let t=Array.isArray(null==e?void 0:e.edits)?e.edits:[],r=[];this.isApplyingStyleEdit=!0;try{for(let e of t){let t=String(e.styleSheetId??""),i=uD(String(e.text??"")),{id:n,kind:a}=uO(t),s=this.adapter.getSelectedNodeId(),o="inline"===a?n:s,l=this.getDeclarationsForStyleSheet(t);"inline"===a?this.adapter.setInlineDeclarations(n,i):"rule"===a&&s&&this.adapter.setRuleDeclarations(s,n,i),r.push(this.getStylePayloadForStyleSheet(t,i)),this.rememberStyleUndoEntry(t,o,l,this.getDeclarationsForStyleSheet(t))}}finally{this.isApplyingStyleEdit=!1}return{styles:r}}getStyleSheetText(e){let t=String((null==e?void 0:e.styleSheetId)??"");return{text:this.getStylePayloadForStyleSheet(t,[]).cssText}}setEffectivePropertyValueForNode(e){let t=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),r=String((null==e?void 0:e.propertyName)??(null==e?void 0:e.name)??""),i=String((null==e?void 0:e.value)??"");return r&&this.adapter.setInlineDeclaration(t,r,i),{}}addRule(e){let t=String((null==e?void 0:e.ruleText)??""),r=this.getRuleSelectorText(t),i=uD(t).map(e=>({...e,active:!0})),n=this.adapter.getSelectedNodeId(),a=n?this.adapter.addRule(n,r,i):null;return{rule:a?this.toCdpRulePayload(a):{origin:"inspector",selectorList:this.toSelectorList(r),style:uL("inspector:main",i)}}}setRuleSelector(e){let t=String((null==e?void 0:e.selector)??(null==e?void 0:e.text)??"").trim(),{id:r,kind:i}=uO(String((null==e?void 0:e.styleSheetId)??"")),n=this.adapter.getSelectedNodeId(),a="rule"===i&&n?this.adapter.setRuleSelector(n,r,t):null;return{selectorList:this.toSelectorList((null==a?void 0:a.selectorText)??t)}}evaluate(e){let t=String((null==e?void 0:e.expression)??""),r=this.adapter.evaluate(t);return{result:function(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return{type:t?"string":"object",subtype:t?void 0:"error",value:e,description:e}}(r.value,r.ok),exceptionDetails:r.ok?void 0:{text:r.value}}}getRuntimeProperties(e){let t="string"==typeof(null==e?void 0:e.objectId)?this.remoteObjectStore.get(e.objectId):void 0;return{result:function(e,t){if(("object"!=typeof e||null===e)&&"function"!=typeof e)return[];try{return Object.getOwnPropertyNames(e).map(r=>{let i=Object.getOwnPropertyDescriptor(e,r),n={name:r,configurable:(null==i?void 0:i.configurable)??!0,enumerable:(null==i?void 0:i.enumerable)??!0,isOwn:!0};return i&&"value"in i&&(n.value=uR(i.value,t),n.writable=i.writable),n})}catch{return[]}}(t,this.remoteObjectStore),internalProperties:function(e,t){if(("object"!=typeof e||null===e)&&"function"!=typeof e)return[];let r=Object.getPrototypeOf(e);return r?[{name:"[[Prototype]]",value:uR(r,t)}]:[]}(t,this.remoteObjectStore)}}clearConsole(){this.getConsoleAdapter().clearConsole(),this.clearAppConsole(),this.remoteObjects.clear()}clearConsoleForTargetScopeChange(){for(let e of(this.consoleStore.entries.length=0,this.knownConsoleEntryIdsBySession.clear(),this.parsedScriptIdsBySession.clear(),this.remoteObjects.clear(),this.runtimeEnabledSessions))this.emit({method:"Runtime.executionContextsCleared"},e),this.emitRuntimeExecutionContext(e),this.emitUnseenConsoleEntriesForSession(e,"app")}clearAppConsole(){this.getAppAdapter(),0!==this.appConsoleStore.entries.length&&(this.appConsoleStore.entries.length=0,this.emit({method:"WSD.appConsoleUpdated"}))}highlightNode(e){let t=this.nodeStore.resolveInspectorNodeId((null==e?void 0:e.nodeId)??(null==e?void 0:e.backendNodeId)),r=this.options.getRuntimeFrame();return r?this.options.onHighlightChange(this.adapter.getNodeHighlight(t,r)):this.options.onHighlightChange(null),{}}sendPreactDevtoolsMessage(e){let t=JSON.stringify(e);for(let e of this.adapter.findLynxViews()){var r;null==(r=e.sendDevtoolEvent)||r.call(e,"PreactDevtools",t)}}highlightLynxNode(e){if(null==e)return void this.options.onHighlightChange(null);let t=this.options.getRuntimeFrame(),r=t?this.adapter.findNodeIdByLynxUniqueId(e):null;this.options.onHighlightChange(r&&t?this.adapter.getNodeHighlight(r,t):null)}setInspectMode(e,t){return"none"===String((null==e?void 0:e.mode)??"none")?this.stopInspectMode():this.startInspectMode(t),{}}startInspectMode(e){this.stopInspectMode();let t=this.options.getRuntimeFrame();t&&(this.stopInspectModeListener=function(e){let{frame:t,highlightNodeAtPoint:r,onHighlightChange:i,onNodeHighlightRequested:n,onNodeInspected:a}=e;t.classList.add("is-inspecting");let s=e=>{let t=r(e.clientX,e.clientY);t&&n(t)},o=()=>{i(null)},l=e=>{if(0!==e.button)return;let i=r(e.clientX,e.clientY);i&&(uX(e),function(e){let t=["mousedown","mouseup","pointerup","pointercancel","click","dblclick","auxclick","contextmenu"],r=[e,e.ownerDocument],i=e.ownerDocument.defaultView;i&&r.push(i);let n=null,a=()=>{for(let e of(null!==n&&(window.clearTimeout(n),n=null),r))for(let r of t)e.removeEventListener(r,s,!0)},s=e=>{uX(e),("click"===e.type||"dblclick"===e.type||"auxclick"===e.type)&&a()};for(let e of r)for(let r of t)e.addEventListener(r,s,!0);n=window.setTimeout(a,800)}(t),a(i))};return t.addEventListener("pointermove",s,!0),t.addEventListener("pointerleave",o,!0),t.addEventListener("pointerdown",l,!0),t.addEventListener("mousemove",s,!0),t.addEventListener("mouseleave",o,!0),t.addEventListener("mousedown",l,!0),()=>{t.classList.remove("is-inspecting"),t.removeEventListener("pointermove",s,!0),t.removeEventListener("pointerleave",o,!0),t.removeEventListener("pointerdown",l,!0),t.removeEventListener("mousemove",s,!0),t.removeEventListener("mouseleave",o,!0),t.removeEventListener("mousedown",l,!0),i(null)}}({frame:t,highlightNodeAtPoint:(e,t)=>this.highlightNodeAtPoint(e,t),onHighlightChange:this.options.onHighlightChange,onNodeHighlightRequested:t=>{this.emit({method:"Overlay.nodeHighlightRequested",params:{nodeId:t.cdpNodeId}},e)},onNodeInspected:t=>{let r=this.getInspectorDocument();r&&this.materializeInspectorNodePath(r,t.inspectorNodeId,e),this.selectInspectorNode(t.inspectorNodeId,{rememberPreferred:!0}),this.emit({method:"Overlay.nodeHighlightRequested",params:{nodeId:t.cdpNodeId}},e),this.emit({method:"Overlay.inspectNodeRequested",params:{backendNodeId:t.cdpNodeId}},e),this.stopInspectMode()}}))}stopInspectMode(){var e;null==(e=this.stopInspectModeListener)||e.call(this),this.stopInspectModeListener=null}highlightNodeAtPoint(e,t){var r,i;let n=null==(r=(i=this.options).resolveTargetAtPoint)?void 0:r.call(i,e,t);n&&this.setTarget(n);let a=this.adapter.getNodeIdAtPoint(e,t),s=this.options.getRuntimeFrame();if(!a||!s)return this.options.onHighlightChange(null),null;let o=function(e,t){if(!e)return t;let r=(e,i)=>{let n=i??(ux(e)?e.id:null);if(e.id===t)return n??e.id;let a=uk(e)||uI(e)?null:n;for(let t of e.children){let e=r(t,a);if(e)return e}return null};return r(e,null)??t}(this.adapter.getDocument(),a);return this.options.onHighlightChange(this.adapter.getNodeHighlight(o,s)),{cdpNodeId:this.nodeStore.getCdpNodeId(o),inspectorNodeId:o}}setStyleDeclaration(e){let t=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),r=String((null==e?void 0:e.name)??"").trim(),i=String((null==e?void 0:e.value)??""),n="string"==typeof(null==e?void 0:e.ruleId)?e.ruleId:null;if(!r)throw Error("CSS property name is required");return n?this.adapter.setRuleDeclaration(t,n,r,i):this.adapter.setInlineDeclaration(t,r,i),{}}undo(e){let t=this.pendingUndoEntry??this.undoEntries.pop()??null;return(this.pendingUndoEntry=null,t)?"dom"===t.type?(this.undoDomEdit(t.entry,e)||(this.pendingUndoEntry=t),{}):this.undoStyleEdit(t.entry):{}}undoDomEdit(e,t){if("mutations"===e.type)return this.undoIncrementalDomMutations(e.mutations,t),!0;let r=this.adapter.getDocument();if(!r)return!1;let i=this.adapter.setOuterHTML(r.id,e.rootHtml);return 0!==i.length&&(this.emitDomMutations(i,t),!0)}undoIncrementalDomMutations(e,t){let r=[];for(let t of[...e].reverse())"attributes"===t.type?r.push(...this.restoreAttributeMutation(t)):r.push(...this.adapter.setNodeValue(t.nodeId,t.previousValue));this.emitDomMutations(r,t)}restoreAttributeMutation(e){let t=new Set(e.before.map(e=>e.name)),r=new Set(e.modified.map(e=>e.name)),i=new Set(e.removed),n=[];for(let r of e.modified)t.has(r.name)||n.push(...this.adapter.removeAttribute(e.nodeId,r.name));for(let t of e.before)(r.has(t.name)||i.has(t.name))&&n.push(...this.adapter.setAttributeValue(e.nodeId,t.name,t.value));return n}undoStyleEdit(e){return this.applyStyleDeclarations(e),{styleSheetId:e.styleSheetId}}markUndoableState(){return this.commitPendingUndoEntry(),{}}rememberDomUndoEntry(e){this.setPendingUndoEntry({type:"dom",entry:e})}rememberStyleUndoEntry(e,t,r,i){var n;t&&JSON.stringify(r)!==JSON.stringify(i)&&((null==(n=this.pendingUndoEntry)?void 0:n.type)!=="style"||this.pendingUndoEntry.entry.styleSheetId!==e||this.pendingUndoEntry.entry.nodeId!==t)&&this.setPendingUndoEntry({type:"style",entry:{styleSheetId:e,nodeId:t,previousDeclarations:u6(r)}})}setPendingUndoEntry(e){var t;((null==(t=this.pendingUndoEntry)?void 0:t.type)!=="style"||"style"!==e.type||this.pendingUndoEntry.entry.styleSheetId!==e.entry.styleSheetId||this.pendingUndoEntry.entry.nodeId!==e.entry.nodeId)&&(this.commitPendingUndoEntry(),this.pendingUndoEntry=e)}commitPendingUndoEntry(){this.pendingUndoEntry&&(this.pushUndoEntry(this.pendingUndoEntry),this.pendingUndoEntry=null)}pushUndoEntry(e){this.undoEntries.push(e),this.undoEntries.length>50&&this.undoEntries.shift()}applyStyleDeclarations(e){let{id:t,kind:r}=uO(e.styleSheetId);this.isApplyingStyleEdit=!0;try{"inline"===r?this.adapter.setInlineDeclarations(t,u6(e.previousDeclarations)):"rule"===r&&this.adapter.setRuleDeclarations(e.nodeId,t,u6(e.previousDeclarations))}finally{this.isApplyingStyleEdit=!1}this.emitSelectedStyleInvalidated(),this.emit({method:"CSS.styleSheetChanged",params:{styleSheetId:e.styleSheetId}})}getBoxModel(e){let t=this.nodeStore.resolveInspectorNodeId((null==e?void 0:e.nodeId)??(null==e?void 0:e.backendNodeId)),r=this.options.getRuntimeFrame(),i=r?this.adapter.getNodeHighlight(t,r):null,n=(null==i?void 0:i.left)??0,a=(null==i?void 0:i.top)??0,s=(null==i?void 0:i.width)??0,o=(null==i?void 0:i.height)??0,l=[n,a,n+s,a,n+s,a+o,n,a+o];return{model:{content:l,padding:l,border:l,margin:l,width:s,height:o}}}getFrameTree(){return{frameTree:{frame:{id:"wsd-main-frame",loaderId:"wsd-loader",url:"wsd://runtime",securityOrigin:"wsd://runtime",mimeType:"text/html"},resources:[{url:"wsd://runtime",type:"Other",mimeType:"text/html"}]}}}getLayoutMetrics(){let e=this.options.getRuntimeFrame(),t=(null==e?void 0:e.offsetWidth)??0,r=(null==e?void 0:e.offsetHeight)??0;return{layoutViewport:{pageX:0,pageY:0,clientWidth:t,clientHeight:r},visualViewport:{offsetX:0,offsetY:0,pageX:0,pageY:0,clientWidth:t,clientHeight:r,scale:1,zoom:1},contentSize:{x:0,y:0,width:t,height:r}}}getInspectorDocument(){let e=this.adapter.getDocument();return e?function e(t){let r=ux(t);if(r){let i,n,a=uI(t)?t:function e(t){let r=!(arguments.length>1)||void 0===arguments[1]||arguments[1];if(!r&&ux(t))return null;if(uk(t))return t;for(let r of t.children){let t=e(r,!1);if(t)return t}return null}(t);return{...t,name:r,attributes:(i=uC(t),n=(function(e){var t;let r=null==(t=e.attributes.find(e=>e.name===dF))?void 0:t.value.split(/\s+/).filter(Boolean);if(!(null==r?void 0:r.length))return[];let i=e.children.find(e=>"element"===e.type);return i?uC(i).filter(e=>r.includes(e.name)):[]})(t).filter(e=>!i.some(t=>t.name===e.name)),[...i,...n]),children:a?a.children.map(t=>e(t)):[]}}let i=t.children.map(t=>e(t));return i.some((e,r)=>e!==t.children[r])?{...t,children:i}:t}(e):null}findInspectorNode(e){let t=this.getInspectorDocument();if(!t)return null;let r=[t];for(;r.length;){let t=r.shift();if(t){if(t.id===e)return t;r.push(...t.children)}}return null}getStylePayloadForStyleSheet(e,t){var r,i;let{id:n,kind:a}=uO(e),s=t.map(e=>({name:e.name,value:e.value,priority:e.priority,active:e.active}));if("inline"===a)return uL(e,(null==(r=this.adapter.getMatchedStyles(n))?void 0:r.inlineStyle.declarations)??s);if("rule"===a){let t=this.adapter.getSelectedNodeId(),r=t?null==(i=this.adapter.getMatchedStyles(t))?void 0:i.matchedRules.find(e=>e.id===n):null;return uL(e,(null==r?void 0:r.declarations)??s)}return uL(e,s)}getDeclarationsForStyleSheet(e){var t,r;let{id:i,kind:n}=uO(e);if("inline"===n)return u6((null==(t=this.adapter.getMatchedStyles(i))?void 0:t.inlineStyle.declarations)??[]);if("rule"===n){let e=this.adapter.getSelectedNodeId(),t=e?null==(r=this.adapter.getMatchedStyles(e))?void 0:r.matchedRules.find(e=>e.id===i):null;return u6((null==t?void 0:t.declarations)??[])}return[]}getRuleSelectorText(e){let t=e.indexOf("{");return t<0?e.trim():e.slice(0,t).trim()}toSelectorList(e){return{selectors:[{text:e,range:uP(0,e.length)}],text:e}}toCdpRulePayload(e){let t=`rule:${e.id}`,r=uL(t,e.declarations);return this.ensureStyleSheetAdded(t,r.cssText,"override"===e.source?"inspector":"regular"),{styleSheetId:t,origin:"override"===e.source?"inspector":"regular",selectorList:this.toSelectorList(e.selectorText),style:r}}ensureStyleSheetAdded(e,t,r){this.knownStyleSheetIds.has(e)||(this.knownStyleSheetIds.add(e),this.emit({method:"CSS.styleSheetAdded",params:{header:{styleSheetId:e,frameId:"wsd-main-frame",sourceURL:`wsd://styles/${e}`,origin:r,title:e,disabled:!1,isInline:!1,isMutable:!0,isConstructed:!0,startLine:0,startColumn:0,length:t.length,endLine:0,endColumn:t.length}}}))}toConsoleEntry(e){let t=this.toCdpStackTrace(e.stackTrace),r={...e,stackTrace:t,args:uj(e,this.remoteObjectStore)};return e.location&&(r.url=e.location.url,r.lineNumber=e.location.lineNumber,r.columnNumber=e.location.columnNumber),r}getKnownConsoleEntryIds(e,t){let r=this.knownConsoleEntryIdsBySession.get(e)??new Map;this.knownConsoleEntryIdsBySession.set(e,r);let i=r.get(t)??new Set;return r.set(t,i),i}getParsedScriptIds(e){let t=this.parsedScriptIdsBySession.get(e)??new Set;return this.parsedScriptIdsBySession.set(e,t),t}getScriptId(e){let t=this.scriptIdsByUrl.get(e)??`wsd-script-${++this.nextScriptId}`;return this.scriptIdsByUrl.set(e,t),t}getScriptSource(e){let t=String((null==e?void 0:e.scriptId)??""),r=this.sourceScriptsById.get(t);return{scriptSource:(null==r?void 0:r.content)??""}}async loadSources(e){let t=++this.sourceLoadId,r=await u_(e);t===this.sourceLoadId&&(r&&this.sourceScriptsById.set(this.getScriptId(r.url),r),this.emitSourceScriptsForEnabledSessions())}async loadAppSource(e){let t=await u_(e);e===this.appTarget&&(t&&this.sourceScriptsById.set(this.getScriptId(t.url),t),this.emitSourceScriptsForEnabledSessions())}emitSourceScriptsForEnabledSessions(){for(let e of this.debuggerEnabledSessions)this.emitSourceScripts(e)}emitSourceScripts(e){for(let t of this.sourceScriptsById.values())this.emitScriptParsed(t.url,e,t)}toCdpStackTrace(e){return e?{callFrames:e.callFrames.map(e=>({...e,scriptId:e.scriptId||(e.url?this.getScriptId(e.url):e.scriptId)}))}:void 0}registerRemoteObject(e){let t=`runtime:${++this.nextRemoteObjectId}`;return this.remoteObjects.set(t,e),t}emitScriptParsed(e,t,r){var i;let n=this.getScriptId(e),a=this.getParsedScriptIds(t);if(!this.debuggerEnabledSessions.has(t)||a.has(n))return;a.add(n);let s=(null==r?void 0:r.content.split("\n"))??[""];this.emit({method:"Debugger.scriptParsed",params:{scriptId:n,url:r?"":e,startLine:0,startColumn:0,endLine:r?s.length-1:1,endColumn:r?(null==(i=s.at(-1))?void 0:i.length)??0:0,executionContextId:1,hash:"",executionContextAuxData:{isDefault:!0,frameId:"wsd-main-frame"},isLiveEdit:!1,hasSourceURL:!1,isModule:!1,length:(null==r?void 0:r.content.length)??0,sourceMapURL:null==r?void 0:r.sourceMapURL,scriptLanguage:"JavaScript"}},t)}emit(e){for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];let n=r.length>0?r[0]:this.activeSessionId,a=n?{...e,sessionId:n}:e;for(let e of this.listeners)e(a)}emitRuntimeExecutionContext(e){this.emit({method:"Runtime.executionContextCreated",params:{context:{id:1,origin:"wsd://runtime",name:"Doubao",auxData:{isDefault:!0,frameId:"wsd-main-frame"}}}},e)}emitUnseenConsoleEntries(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"current";for(let t of this.runtimeEnabledSessions)this.emitUnseenConsoleEntriesForSession(t,e)}emitUnseenConsoleEntriesForSession(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"current";if(!this.runtimeEnabledSessions.has(e))return;let r="app"===t?this.appConsoleStore.entries:this.getConsoleAdapter().getConsoleEntries(),i=this.getKnownConsoleEntryIds(e,t);for(let t of r){var n;if(i.has(t.id)||(i.add(t.id),"host"===t.source))continue;let r=this.toCdpStackTrace(t.stackTrace),a={type:"warn"===(n=t.level)?"warning":"eval"===n?"log":n,args:uj(t,this.remoteObjectStore),executionContextId:1,timestamp:t.timestamp};r&&(a.stackTrace=r),this.emit({method:"Runtime.consoleAPICalled",params:a},e)}}emitSelectedStyleInvalidated(){let e=this.adapter.getSelectedNodeId(),t=e?this.nodeStore.getExistingCdpNodeId(e):void 0;t&&this.emit({method:"DOM.inlineStyleInvalidated",params:{nodeIds:[t]}})}}function u9(e){let{onReopen:t}=e;return(0,s.jsxs)("div",{className:"wsd-runtime-empty",children:[(0,s.jsx)("div",{"aria-hidden":"true",className:"wsd-runtime-empty-icon"}),(0,s.jsx)("div",{className:"wsd-runtime-empty-title",children:"页面已关闭"}),(0,s.jsx)("div",{className:"wsd-runtime-empty-description",children:"当前页面栈为空,可从调试面板重新选择页面渲染。"}),(0,s.jsx)("button",{className:"wsd-runtime-empty-action",onClick:t,type:"button",children:"重新打开当前页面"})]})}let u7=new Set(["log","info","warn","error","debug"]);function ce(e){return"AppletJSModule"===e||"LynxConsoleModule"===e}function ct(e,t,r){if("log"!==e)return null;let i="object"!=typeof t||null===t?null:"string"==typeof t.message||Array.isArray(t.args)?{level:u7.has(t.level)?t.level:void 0,message:"string"==typeof t.message?t.message:void 0,args:Array.isArray(t.args)?t.args:void 0,stack:"string"==typeof t.stack?t.stack:void 0}:null;return i?ce(r)?i:null:ce(r)?{level:"log",message:function(e){if("string"==typeof e)return e;if(void 0===e)return"undefined";try{return JSON.stringify(e)??String(e)}catch{return String(e)}}(t)}:null}class cr{listeners=new Set;runtimeConsoleEvents=[];current=null;subscribe(e){return this.listeners.add(e),()=>void this.listeners.delete(e)}reset(){this.runtimeConsoleEvents.length=0,this.set(null)}destroy(){this.reset(),this.listeners.clear()}set(e){this.current=e,this.flush(),this.notify()}notify(){for(let e of this.listeners)e(this.current)}dispatch(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];!this.current||t?this.runtimeConsoleEvents.push(e):s_(this.current,e)}flush(){if(this.current)for(let e of this.runtimeConsoleEvents.splice(0))s_(this.current,e)}}let ci=new Set(["doubao.openPage","doubao.navigateTo","doubao.redirectTo","doubao.reLaunch","doubao.navigateBack","doubao.exitApp"]);function cn(e){"function"==typeof queueMicrotask?queueMicrotask(e):Promise.resolve().then(e)}class ca{container;fileSystemNamespace;nativeModulesCallHandler;webSdkDebugger;onExitApp;onHideApp;visible=!0;onError;confirmBeforeUnload;apiEnvironment;previewTarget=new cr;appPreviewTarget=new cr;pageRoutesByTarget=new WeakMap;targetObserver=null;runtime=null;runtimeManifestUrl=null;lastRenderOptions=null;pageDevice=so["0"];isRuntimeTargetChanging=!1;navigationSourceTarget=null;deferredPageRoute;constructor(e){if(!e.container)throw Error("Page preview controller requires a container element");this.container=e.container,this.fileSystemNamespace=e.fileSystemNamespace,this.nativeModulesCallHandler=e.nativeModulesCallHandler,this.webSdkDebugger=e.webSdkDebugger,this.onExitApp=e.onExitApp,this.onHideApp=e.onHideApp,this.onError=e.onError,this.confirmBeforeUnload=e.confirmBeforeUnload,this.apiEnvironment=e.apiEnvironment??dI(),"u">typeof MutationObserver&&(this.targetObserver=new MutationObserver(this.handleRuntimeContainerMutation),this.targetObserver.observe(this.container,{childList:!0}))}async render(){var e,t,r;let i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=this.webSdkDebugger.getState(),a=!i.entry&&(null==(e=n.pageSelection)?void 0:e.routeUrl)?tO({url:n.pageSelection.routeUrl},n.manifest):void 0,s=(null==a?void 0:a.entry)??function(e,t){if(t.entry)return t.entry;if(!e.pageSelection)throw Error("No page selected");return e.pageSelection.item}(n,i),o=i.device??so["0"];this.pageDevice=o;let l=(null==a?void 0:a.initData)??i.initData??{},d=a?{...i.globalProps,...a.globalProps}:i.globalProps,u=this.getRuntime(n),c=a?null==(t=n.pageSelection)?void 0:t.routeUrl:void 0,p=s.path;if(c){let e=c.indexOf("?");p+=e<0?"":c.slice(e)}this.lastRenderOptions=i,this.isRuntimeTargetChanging=!0,this.deferredPageRoute={path:s.path,url:p};try{let e=await u[({navigate:"pushPage",redirect:"replacePage",relaunch:"reLaunchPage"})[i.routeMode??"redirect"]]({entry:s,initData:l,globalProps:d,pageCapsule:i.pageCapsule??{statusBarHeight:o.statusBarHeight}});if((null==(r=u.currentPage)?void 0:r.element)!==e.element)throw new DOMException("Page rendering was cancelled","AbortError");return this.bindPageTarget(e.element,{path:s.path,url:p}),this.previewTarget.set(e.element),e.element}catch(e){throw this.syncCurrentRuntimeTarget(),e}finally{this.isRuntimeTargetChanging=!1,this.navigationSourceTarget=null,this.deferredPageRoute=void 0,this.previewTarget.flush()}}getCurrentTarget(){return this.previewTarget.current}getCurrentAppTarget(){return this.appPreviewTarget.current}getCurrentPageUrl(){var e,t;let r=null==(e=this.runtime)?void 0:e.currentPage;return r?r.url??(null==(t=this.pageRoutesByTarget.get(r.element))?void 0:t.url)??r.route:null}async openPage(e){var t,r;if(!(null==(r=this.runtime)||null==(t=r.bridge.navigation)?void 0:t.openPage))throw Error("No Page runtime is active");await this.runtime.bridge.navigation.openPage(e),this.syncCurrentRuntimeTarget()}getPageStackSize(){var e;return(null==(e=this.runtime)?void 0:e.pages.length)??0}subscribeTarget(e){return this.previewTarget.subscribe(e)}subscribeAppTarget(e){return this.appPreviewTarget.subscribe(e)}sendAgentEvent(e,t){if(!this.runtime)throw Error("No Page runtime is active");this.runtime.sendAppEvent("onAgentEvent",{name:e,payload:t})}closeCurrentPage(){this.navigateBack()}navigateBack(e){var t;let r=(null==(t=this.runtime)?void 0:t.requestBack(e))??!1;return this.syncCurrentRuntimeTarget(),r}exitApp(){var e,t,r;null==(r=this.runtime)||null==(t=r.bridge.navigation)||null==(e=t.exitApp)||e.call(t),this.syncCurrentRuntimeTarget(),this.syncAppRuntimeTarget()}setVisible(e){var t;this.visible=e,null==(t=this.runtime)||t.setVisible(e)}async reopenCurrentPage(){try{await this.render(this.lastRenderOptions??{})}catch(t){var e;if(rP(t)&&"AbortError"===t.name)return;null==(e=this.onError)||e.call(this,t,new Event("error"))}}async restartRuntime(){var e,t;this.previewTarget.reset(),this.appPreviewTarget.reset();try{await (null==(e=this.runtime)?void 0:e.restart())}catch(e){if(rP(e)&&"AbortError"===e.name)return;null==(t=this.onError)||t.call(this,e,new Event("error"))}this.syncCurrentRuntimeTarget(),this.syncAppRuntimeTarget()}reload(){var e;null==(e=this.runtime)||e.reload(),this.previewTarget.notify()}clear(){var e;null==(e=this.runtime)||e.clear(),this.navigationSourceTarget=null,this.deferredPageRoute=void 0,this.previewTarget.reset(),this.appPreviewTarget.reset()}destroy(){var e,t;null==(e=this.targetObserver)||e.disconnect(),null==(t=this.runtime)||t.destroy(),this.runtime=null,this.runtimeManifestUrl=null,this.previewTarget.destroy(),this.appPreviewTarget.destroy()}packageManager=new tT;getRuntime(e){this.packageManager.configure({resolveManifestUrl:()=>e.manifestUrl,resourceUrlVersion:e.resourceUrlVersion}),this.packageManager.setPackage({manifest:e.manifest,manifestUrl:String(e.manifestUrl)});let t=e.manifestUrl;if(!this.runtime){let r={pageHost:new rW({container:this.container,confirmBeforeUnload:this.confirmBeforeUnload,onHide:this.onHideApp,mountEmptyState:e=>{var t;let r;return t=()=>this.reopenCurrentPage(),(r=(0,rZ.H)(e)).render((0,s.jsx)(u9,{onReopen:t})),()=>r.unmount()}}),packageManager:this.packageManager,sandboxUrl:void 0,manifest:e.manifest,manifestUrl:t,apiRegistry:this.apiEnvironment.apiRegistry,fileSystemNamespace:this.fileSystemNamespace,nativeModulesCallHandler:this.handleNativeModulesCall,onError:this.onError,getRuntimeGlobalProps:()=>sh(this.pageDevice)};return this.runtime=new rK(r),this.runtime.setVisible(this.visible),this.runtimeManifestUrl=t,this.runtime}return this.runtimeManifestUrl!==t&&(this.previewTarget.set(null),this.appPreviewTarget.set(null),this.runtime.setManifest(e.manifest,t),this.runtimeManifestUrl=t),this.runtime}handleNativeModulesCall=(e,t,r,i)=>{var n;if((null==i?void 0:i.containerType)==="APP"&&function(e,t,r){if("invokeCdp"!==e||"LynxDevToolSetModule"!==r||"string"!=typeof t)return!1;try{var i;return(null==(i=JSON.parse(t))?void 0:i.method)==="Page.reload"}catch{return!1}}(e,t,r))return cn(()=>this.restartRuntime()),JSON.stringify({result:{}});let a=function(e,t,r){if("AppletBridgeModule"===r&&"postMessage"===e&&"object"==typeof t&&null!==t&&"call"===t.type&&"string"==typeof t.name&&ci.has(t.name))return t.name}(e,t,r);a&&(this.navigationSourceTarget=this.previewTarget.current,this.deferredPageRoute=this.resolveNavigationPageRoute(t),this.scheduleRuntimeTargetSync("doubao.exitApp"===a?this.onExitApp:void 0));let s=ct(e,t,r);if(s){if((null==i?void 0:i.containerType)==="APP")this.syncAppRuntimeTarget(i.element),this.appPreviewTarget.dispatch({...s,label:"app"});else{let e=this.getRuntimeConsolePagePath(i);this.previewTarget.dispatch(e?{...s,pagePath:e}:s,this.isRuntimeTargetChanging)}return}return null==(n=this.nativeModulesCallHandler)?void 0:n.call(this,e,t,r,i)};handleRuntimeContainerMutation=()=>{this.syncCurrentRuntimeTarget(),this.syncAppRuntimeTarget()};scheduleRuntimeTargetSync(e){this.isRuntimeTargetChanging=!0;let t=this.navigationSourceTarget,r=()=>{this.isRuntimeTargetChanging=!1,this.navigationSourceTarget=null,this.deferredPageRoute=void 0,this.previewTarget.flush(),null==e||e()};cn(()=>{(this.syncCurrentRuntimeTarget(),this.previewTarget.current!==t)?r():cn(()=>{this.syncCurrentRuntimeTarget(),r()})})}syncCurrentRuntimeTarget(){var e;let t=(null==(e=this.runtime)?void 0:e.currentPage)??null,r=(null==t?void 0:t.element)??null,i=r!==this.navigationSourceTarget?this.deferredPageRoute:void 0;(r&&this.bindPageTarget(r,{path:(null==i?void 0:i.path)??this.getCurrentPagePath(),url:(null==t?void 0:t.url)??(null==i?void 0:i.url)}),this.previewTarget.current===r)?this.previewTarget.flush():this.previewTarget.set(r)}syncAppRuntimeTarget(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.getAppRuntimeElement();this.appPreviewTarget.current===e?this.appPreviewTarget.flush():this.appPreviewTarget.set(e)}getAppRuntimeElement(){return this.container.querySelector('lynx-view[data-container-type="APP"]')}bindPageTarget(e,t){if(!e)return;let r=this.pageRoutesByTarget.get(e),i=t.path??(null==r?void 0:r.path),n=t.url??(null==r?void 0:r.url)??i;(i||n)&&this.pageRoutesByTarget.set(e,{path:i,url:n})}resolveNavigationPageRoute(e){var t;if("object"!=typeof e||null===e)return;let r=null==(t=e.params)?void 0:t.url;if("string"!=typeof r||!r)return;let i=r.indexOf("?"),n=i<0?"":r.slice(i);try{let e=tO({url:r},this.webSdkDebugger.getState().manifest).entry;return{path:e.path,url:`${e.path}${n}`}}catch{return}}getCurrentPagePath(){var e;let t=null==(e=this.runtime)?void 0:e.currentPage;return null==t?void 0:t.entry.path}getRuntimeConsolePagePath(e){var t,r,i,n;if((null==e?void 0:e.containerType)!=="PAGE")return;let a=(null==(t=this.pageRoutesByTarget.get(e.element))?void 0:t.path)??(null==(r=this.deferredPageRoute)?void 0:r.path)??this.getCurrentPagePath();return this.bindPageTarget(null==(n=this.runtime)||null==(i=n.currentPage)?void 0:i.element,{path:a}),a}}class cs{container;fileSystemNamespace;nativeModulesCallHandler;webSdkDebugger;onError;apiEnvironment;previewTarget=new cr;widget=null;runtime=null;constructor(e){if(!e.container)throw Error("Widget preview controller requires a container element");this.container=e.container,this.fileSystemNamespace=e.fileSystemNamespace,this.nativeModulesCallHandler=e.nativeModulesCallHandler,this.webSdkDebugger=e.webSdkDebugger,this.onError=e.onError,this.apiEnvironment=e.apiEnvironment??dI()}async render(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.webSdkDebugger.getState(),r=function(e,t){if(t.widgetId)return t.widgetId;if(!e.widgetSelection)throw Error("No widget selected");return e.widgetSelection.item.widgetId}(t,e),i=e.viewport??sd,n=r2(e.initData??{}),a=e.globalProps??sm(i);this.clear();let s=new tT({resolveManifestUrl:()=>t.manifestUrl,resourceUrlVersion:t.resourceUrlVersion});s.setPackage({manifest:t.manifest,manifestUrl:String(t.manifestUrl)}),this.runtime=new rK({manifest:t.manifest,manifestUrl:t.manifestUrl,packageManager:s,sandboxUrl:void 0,apiRegistry:this.apiEnvironment.apiRegistry,fileSystemNamespace:this.fileSystemNamespace,nativeModulesCallHandler:this.handleNativeModulesCall,onError:this.onError}),this.widget=new rJ({runtime:this.runtime,appId:t.manifest.appId,container:this.container,globalProps:a,initData:n,onError:this.onError,widgetId:r});let o=await this.widget.render();return this.previewTarget.set(o),o}getCurrentTarget(){return this.previewTarget.current}subscribeTarget(e){return this.previewTarget.subscribe(e)}reload(){var e,t;null==(e=this.widget)||e.reload(),this.previewTarget.set((null==(t=this.widget)?void 0:t.element)??null)}clear(){this.disposeWidget(),this.previewTarget.reset()}destroy(){this.disposeWidget(),this.previewTarget.destroy()}disposeWidget(){var e,t;null==(e=this.widget)||e.destroy(),this.widget=null,null==(t=this.runtime)||t.destroy(),this.runtime=null,this.container.replaceChildren()}handleNativeModulesCall=(e,t,r,i)=>{var n;let a=ct(e,t,r);return a?void this.previewTarget.dispatch(a):null==(n=this.nativeModulesCallHandler)?void 0:n.call(this,e,t,r,i)}}var co=e=>(0,s.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",width:13.6,height:13.6,fill:"none",overflow:"visible",preserveAspectRatio:"none",style:{display:"block"},viewBox:"0 0 13.6 13.6",...e,children:(0,s.jsx)("path",{fill:"#999",d:"M.8 8.667a.8.8 0 0 1 .8.8V9.6c0 .573.001.955.025 1.248.023.284.064.415.106.497a1.2 1.2 0 0 0 .524.524c.083.042.213.083.497.106C3.045 12 3.427 12 4 12h.133a.8.8 0 0 1 0 1.6H4c-.547 0-1.005 0-1.379-.03-.383-.031-.747-.1-1.092-.275a2.8 2.8 0 0 1-1.224-1.223c-.176-.346-.244-.71-.275-1.093C0 10.606 0 10.147 0 9.6v-.133a.8.8 0 0 1 .8-.8m12 0a.8.8 0 0 1 .8.8V9.6c0 .547 0 1.006-.03 1.38-.031.382-.1.746-.275 1.092a2.8 2.8 0 0 1-1.223 1.223c-.346.176-.71.244-1.093.275-.373.03-.832.03-1.379.03h-.133a.8.8 0 0 1 0-1.6H9.6c.573 0 .955 0 1.248-.025.284-.023.415-.064.497-.106a1.2 1.2 0 0 0 .524-.524c.042-.082.083-.213.106-.497C12 10.555 12 10.173 12 9.6v-.133a.8.8 0 0 1 .8-.8M10.8 6a.8.8 0 0 1 0 1.6h-8a.8.8 0 0 1 0-1.6zM4.133 0a.8.8 0 0 1 0 1.6H4c-.573 0-.955.001-1.248.025-.284.023-.414.064-.497.106a1.2 1.2 0 0 0-.524.524c-.042.083-.083.213-.106.497C1.601 3.045 1.6 3.427 1.6 4v.133a.8.8 0 0 1-1.6 0V4c0-.547 0-1.005.03-1.379.031-.383.1-.747.275-1.092A2.8 2.8 0 0 1 1.53.305C1.874.13 2.239.061 2.62.03 2.995 0 3.453 0 4 0zM9.6 0c.547 0 1.006 0 1.38.03.382.031.746.1 1.092.275a2.8 2.8 0 0 1 1.223 1.224c.176.345.244.71.275 1.092.03.374.03.832.03 1.379v.133a.8.8 0 0 1-1.6 0V4c0-.573 0-.955-.025-1.248-.023-.284-.064-.414-.106-.497a1.2 1.2 0 0 0-.524-.524c-.082-.042-.213-.083-.497-.106-.293-.024-.675-.025-1.248-.025h-.133a.8.8 0 0 1 0-1.6z"})});function cl(e){let t=(0,iD.useRef)(e);t.current=e;let r=(0,iD.useRef)();return r.current??=function(){for(var e=arguments.length,r=Array(e),i=0;i<e;i++)r[i]=arguments[i];return t.current(...r)},r.current}let cd={revision:0,phase:"idle",canCancel:!1,canRetry:!1},cu=(0,iD.createContext)({});function cc(e){let{capability:t,children:r,getAppIdentity:i}=e;return(0,s.jsx)(cu.Provider,{value:{capability:t,getAppIdentity:i},children:r})}async function cp(e){let t=await e.json();if(!e.ok){var r;throw Error("error"in t&&(null==(r=t.error)?void 0:r.message)||"真机调试请求失败")}return t}function ch(){var e,t,r,i,n,a,o,l;let{capability:d,getAppIdentity:u}=(0,iD.useContext)(cu),[c,p]=(0,iD.useState)(!1),[h,m]=(0,iD.useState)(cd),[g,f]=(0,iD.useState)(),[v,y]=(0,iD.useState)("modern"),[b,w]=(0,iD.useState)(),_=(0,iD.useId)(),S=(0,iD.useRef)(!1),x=(0,iD.useRef)(cd),I=(0,iD.useRef)(null),k=cl(e=>{e.revision<x.current.revision||(x.current=e,m(e))}),C=cl(async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!d)throw Error("真机调试能力不可用");return cp(await fetch(e,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","X-DBX-Real-Device-Token":d.accessToken},body:JSON.stringify(t)}))}),E=cl(async()=>{if(d)try{let e=await C(d.stateEndpoint);k(e),f(void 0)}catch(e){f(e instanceof Error?e.message:String(e))}}),N=cl(async()=>{if(d){f(void 0);try{let e=await C(d.startEndpoint);if(!S.current&&e.operationId&&e.canCancel&&"web"===e.owner)return void await C(d.cancelEndpoint,{operationId:e.operationId}).catch(()=>void 0);k(e)}catch(e){f(e instanceof Error?e.message:String(e))}}}),T=cl(async()=>{let e=x.current;if(d&&e.operationId&&e.canCancel&&"web"===e.owner)try{let t=await C(d.cancelEndpoint,{operationId:e.operationId});k(t)}catch{}}),A=cl(()=>{S.current=!1,p(!1),T()});if((0,iD.useEffect)(()=>{if(!c||!d)return;E();let e=window.setInterval(()=>void E(),d.pollIntervalMs);return()=>window.clearInterval(e)},[d,c,E]),(0,iD.useEffect)(()=>{if(!c)return;let e=e=>{var t;(null==(t=I.current)?void 0:t.contains(e.target))||A()},t=e=>{"Escape"===e.key&&A()};return window.addEventListener("pointerdown",e),window.addEventListener("keydown",t),()=>{window.removeEventListener("pointerdown",e),window.removeEventListener("keydown",t)}},[A,c]),(0,iD.useEffect)(()=>{h.qr&&"modern"===v&&!h.qr.modernAvailable&&h.qr.legacyAvailable&&y("legacy")},[v,h.qr]),(0,iD.useEffect)(()=>{let e=!1;return c&&d&&h.operationId&&"waiting_for_scan"===h.phase&&h.qr&&("modern"===v?h.qr.modernAvailable:h.qr.legacyAvailable)?(w(void 0),f(void 0),fetch(d.qrEndpoint,{method:"POST",headers:{"Content-Type":"application/json","X-DBX-Real-Device-Token":d.accessToken},body:JSON.stringify({operationId:h.operationId,kind:v})}).then(e=>{if(!e.ok)throw Error("二维码暂不可用");return e.blob()}).then(t=>{e||w(URL.createObjectURL(t))}).catch(t=>{e||f(t instanceof Error?t.message:String(t))}),()=>{e=!0}):void w(void 0)},[d,c,v,h.connectionMode,h.operationId,h.phase,null==(e=h.qr)?void 0:e.legacyAvailable,null==(t=h.qr)?void 0:t.modernAvailable,null==(r=h.qr)?void 0:r.revision]),(0,iD.useEffect)(()=>{if(b)return()=>URL.revokeObjectURL(b)},[b]),!d)return null;let M=function(e){switch(e.phase){case"preparing":return"正在准备真机调试环境";case"downloading":return"正在下载 Desktop 工具";case"installing_tool":return"正在安装 Desktop 工具";case"reusing_client":return"检测到已连接客户端,正在继续真机调试";case"waiting_for_scan":return"使用已登录的豆包客户端扫码";case"waiting_for_install":return"设备已连接,正在安装调试包";case"launching_tool":return"正在启动 Desktop 工具";case"connected":return"环境已就绪";case"timed_out":return"等待设备连接超时";case"cancelled":return"已取消真机调试";case"failed":var t;return(null==(t=e.error)?void 0:t.message)||"真机调试启动失败";default:return"准备开始真机调试"}}(h),R=null==(i=h.progress)?void 0:i.percentage,j="number"==typeof R&&"downloading"===h.phase,P="waiting_for_scan"===h.phase&&!!h.qr,L=!!b&&P,O="waiting_for_scan"!==h.phase&&"connected"!==h.phase,D="failed"===h.phase||"timed_out"===h.phase||!!g,U=D?"二维码暂不可用":"connected"===h.phase?"连接成功,请勿重复扫码":"准备完成后可扫码",q="existing_client"===h.connectionMode?"已复用当前连接,无需扫码":"扫码成功",$=null==u?void 0:u(),B=[null==$||null==(n=$.appName)?void 0:n.trim(),null==$||null==(a=$.appKey)?void 0:a.trim()].filter(Boolean).join(" · ");return(0,s.jsxs)("div",{className:"wsd-physical-device-wrapper",ref:I,children:[(0,s.jsx)("button",{"aria-expanded":c,"aria-haspopup":"dialog","aria-label":"真机调试","aria-pressed":c,"aria-describedby":_,className:(0,rL.$)("wsd-device-toolbar-icon",c&&"is-active"),onClick:()=>{c?A():(y("modern"),S.current=!0,p(!0),N())},type:"button",children:(0,s.jsx)(co,{"aria-hidden":"true"})}),(0,s.jsx)("span",{className:"wsd-physical-device-tooltip",id:_,role:"tooltip",children:"真机调试"}),c?(0,s.jsxs)("dialog",{"aria-label":"真机调试",className:"wsd-physical-device-popover",open:!0,children:[(0,s.jsxs)("header",{className:"wsd-physical-device-header",children:[(0,s.jsx)("h2",{children:"真机调试"}),(0,s.jsx)("p",{children:"使用已登录的客户端扫码,创建新的真机调试对话"})]}),(0,s.jsxs)("div",{className:"wsd-physical-device-content",children:[(0,s.jsxs)("div",{"aria-label":"客户端版本",className:"wsd-physical-device-client-tabs",role:"tablist",children:[(0,s.jsx)("button",{"aria-selected":"modern"===v,className:(0,rL.$)("modern"===v&&"is-active"),disabled:!P||!(null==(o=h.qr)?void 0:o.modernAvailable),onClick:()=>y("modern"),role:"tab",type:"button",children:"新版客户端"}),(0,s.jsx)("button",{"aria-selected":"legacy"===v,className:(0,rL.$)("legacy"===v&&"is-active"),disabled:!P||!(null==(l=h.qr)?void 0:l.legacyAvailable),onClick:()=>y("legacy"),role:"tab",type:"button",children:"旧版客户端"})]}),(0,s.jsx)("div",{className:(0,rL.$)("wsd-physical-device-qr",!L&&"is-locked"),children:L&&b?(0,s.jsx)("img",{alt:"modern"===v?"新版客户端真机调试二维码":"旧版客户端真机调试二维码",src:b}):(0,s.jsx)("div",{className:"wsd-physical-device-placeholder",children:(0,s.jsx)("strong",{children:U})})})]}),"waiting_for_scan"===h.phase?(0,s.jsx)("div",{className:"wsd-physical-device-notice",children:"使用豆包 14.70 以上版本扫码"}):"connected"===h.phase?(0,s.jsx)("div",{className:"wsd-physical-device-notice is-success",children:q}):null,j?(0,s.jsx)("div",{className:"wsd-physical-device-progress","aria-label":`下载进度 ${Math.round(R)}%`,children:(0,s.jsx)("span",{style:{width:`${Math.max(0,Math.min(100,R))}%`}})}):null,O?(0,s.jsxs)("div",{className:"wsd-physical-device-details",children:[B?(0,s.jsx)("div",{"aria-label":"小程序信息",className:"wsd-physical-device-app-identity",title:B,children:B}):null,(0,s.jsxs)("div",{className:(0,rL.$)("wsd-physical-device-status",D&&"is-error"),children:[["preparing","downloading","installing_tool","reusing_client","waiting_for_scan","waiting_for_install","launching_tool"].includes(h.phase)&&!j?(0,s.jsx)("span",{className:"wsd-physical-device-spinner","aria-hidden":"true"}):null,(0,s.jsx)("div",{children:(0,s.jsx)("strong",{children:g||M})})]})]}):null,(h.canRetry||g)&&D?(0,s.jsx)("button",{className:"wsd-physical-device-retry",onClick:()=>void N(),type:"button",children:"重新尝试"}):null]}):null]})}let cm=(0,iD.createContext)(null);function cg(e){let t=function(e){let t=(0,iD.useContext)(cm),r=e??t;if(!r)throw Error("WebSdkDebuggerProvider is missing");return r}(e),r=(0,iD.useCallback)(e=>t.subscribe(e),[t]),i=(0,iD.useCallback)(()=>t.getState(),[t]);return(0,iD.useSyncExternalStore)(r,i,i)}var cf=r(30566),cv=r(98905),cy=r(88487),cb=r(30737),cw=r(19040),c_=r(66742),cS=r(39081);function cx(e){let{fallbackName:t,selector:r}=e;return r?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("span",{className:"wsd-runtime-highlight-selector-tag",children:r.tagName}),r.id?(0,s.jsxs)("span",{className:"wsd-runtime-highlight-selector-id",children:["#",r.id]}):null,r.classNames.map(e=>(0,s.jsxs)("span",{className:"wsd-runtime-highlight-selector-class",children:[".",e]},e))]}):(0,s.jsx)("span",{className:"wsd-runtime-highlight-selector-tag",children:t??"element"})}function cI(e){let{focusable:t}=e;return t?(0,s.jsx)("span",{children:"true"}):(0,s.jsx)("span",{"aria-label":"not focusable",className:"wsd-runtime-highlight-not-focusable"})}function ck(e){var t,r,i,n,a;let{highlightRect:o,overlay:l,runtimeFrameRef:d,runtimeFrameScaleBoxRef:u,runtimeScaleMode:c,runtimeShellRef:p,runtimeStyle:h,runtimeTargetRef:m}=e,g=(0,iD.useSyncExternalStore)(l9.subscribe,l9.getSnapshot),f=(0,iD.useRef)(null),[v,y]=(0,iD.useState)(null),b=function(e,t){let r=e[t];if("number"==typeof r)return r;if("string"!=typeof r)return null;let i=Number.parseFloat(r);return Number.isFinite(i)?i:null}(h,"--wsd-runtime-height"),w=o&&v&&null!==b&&o.top+o.height+v.gap+v.height>b&&o.top>v.gap+v.height,_=o?{"--wsd-highlight-content-height":`${(null==(t=o.boxModel)?void 0:t.content.height)??o.height}px`,"--wsd-highlight-content-left":`${(null==(r=o.boxModel)?void 0:r.content.left)??0}px`,"--wsd-highlight-content-top":`${(null==(i=o.boxModel)?void 0:i.content.top)??0}px`,"--wsd-highlight-content-width":`${(null==(n=o.boxModel)?void 0:n.content.width)??o.width}px`,"--wsd-highlight-height":`${o.height}px`,"--wsd-highlight-left":`${o.left}px`,"--wsd-highlight-top":`${o.top}px`,"--wsd-highlight-width":`${o.width}px`}:void 0,S=cl(e=>{let t=Number.parseFloat(getComputedStyle(e).getPropertyValue("--wsd-highlight-popover-gap")),r={gap:Number.isFinite(t)?t:0,height:e.offsetHeight};y(e=>(null==e?void 0:e.gap)===r.gap&&e.height===r.height?e:r)}),x=cl(e=>{var t;if(null==(t=f.current)||t.disconnect(),f.current=null,!e||(S(e),"u"<typeof ResizeObserver))return;let r=new ResizeObserver(()=>S(e));r.observe(e),f.current=r});return(0,s.jsx)("section",{className:"wsd-device-preview","data-scale-mode":c,ref:p,children:(0,s.jsx)("div",{className:"wsd-device-preview-scale-box",ref:u,style:h,children:(0,s.jsxs)("div",{className:"wsd-device-preview-frame",ref:d,style:{filter:`brightness(${g.brightness})`},children:[m?(0,s.jsx)("div",{className:"wsd-runtime-target",ref:m}):null,o?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("div",{"aria-hidden":"true",className:"wsd-runtime-highlight",style:_,children:(0,s.jsx)("div",{className:"wsd-runtime-highlight-content-frame"})}),(0,s.jsxs)("div",{"aria-hidden":"true",className:(0,rL.$)("wsd-runtime-highlight-popover",w&&"is-above"),ref:x,style:_,children:[(0,s.jsxs)("div",{className:"wsd-runtime-highlight-header",children:[(0,s.jsx)("span",{"aria-hidden":"true",className:"wsd-runtime-highlight-node-icon"}),(0,s.jsx)("strong",{className:"wsd-runtime-highlight-selector",children:(0,s.jsx)(cx,{fallbackName:o.nodeName,selector:o.selector})}),(0,s.jsx)("span",{className:"wsd-runtime-highlight-dimensions",children:o.dimensions??`${o.width} \xd7 ${o.height}`})]}),(null==(a=o.styles)?void 0:a.length)?(0,s.jsx)("dl",{className:"wsd-runtime-highlight-details",children:o.styles.map(e=>(0,s.jsxs)("div",{className:"wsd-runtime-highlight-detail",children:[(0,s.jsx)("dt",{children:e.name}),(0,s.jsxs)("dd",{children:[e.swatch?(0,s.jsx)("span",{className:"wsd-runtime-highlight-swatch",style:{backgroundColor:e.swatch}}):null,(0,s.jsx)("span",{children:e.value})]})]},e.name))}):null,o.accessibility?(0,s.jsxs)("section",{className:"wsd-runtime-highlight-accessibility",children:[(0,s.jsx)("div",{className:"wsd-runtime-highlight-section-title",children:(0,s.jsx)("span",{children:"ACCESSIBILITY"})}),(0,s.jsxs)("dl",{className:"wsd-runtime-highlight-details",children:[(0,s.jsxs)("div",{className:"wsd-runtime-highlight-detail",children:[(0,s.jsx)("dt",{children:"Name"}),(0,s.jsx)("dd",{children:o.accessibility.name})]}),(0,s.jsxs)("div",{className:"wsd-runtime-highlight-detail",children:[(0,s.jsx)("dt",{children:"Role"}),(0,s.jsx)("dd",{children:o.accessibility.role})]}),(0,s.jsxs)("div",{className:"wsd-runtime-highlight-detail",children:[(0,s.jsx)("dt",{children:"Keyboard-focusable"}),(0,s.jsx)("dd",{children:(0,s.jsx)(cI,{focusable:o.accessibility.keyboardFocusable})})]})]})]}):null]})]}):null,l]})})})}function cC(e){let t,r,i,{cashier:n,onCancel:a,onConfirm:o}=e,[l,d]=(0,iD.useState)(!1),[u,c]=(0,iD.useState)(""),[p,h]=(0,iD.useState)(n.paymentTypes[0].id),m=n.paymentTypes.find(e=>{let{id:t}=e;return t===p})||n.paymentTypes[0],g=n.paymentTypes.length>1,f=async()=>{if(!l){d(!0),c("");try{await o(p)}catch(e){d(!1),c(lT(e))}}};return(0,s.jsxs)("div",{className:"wsd-simulator-overlay-layer wsd-sandbox-cashier-layer",children:[(0,s.jsx)("div",{"aria-hidden":"true",className:"wsd-simulator-overlay-backdrop wsd-sandbox-cashier-backdrop"}),(0,s.jsxs)("dialog",{"aria-label":"支付收银台","aria-modal":"true",className:"wsd-sandbox-cashier",open:!0,children:[(0,s.jsx)("button",{"aria-label":"关闭收银台",className:"wsd-sandbox-cashier-close",disabled:l,onClick:a,type:"button",children:"×"}),(0,s.jsx)("section",{className:"wsd-sandbox-cashier-amount",children:(0,s.jsx)("strong",{children:(r=(t=n.totalAmount.replace(/^0+(?=\d)/,"").padStart(3,"0")).slice(0,-2)||"0",i=t.slice(-2),`\xa5${r.replace(/\B(?=(\d{3})+(?!\d))/g,",")}.${i}`)})}),(0,s.jsxs)("section",{className:"wsd-sandbox-cashier-payment",children:[(0,s.jsx)("h2",{children:"支付方式"}),g?(0,s.jsx)("div",{className:"wsd-sandbox-cashier-payment-options",children:n.paymentTypes.map(e=>{let t=e.id===p;return(0,s.jsxs)("button",{"aria-pressed":t,className:"wsd-sandbox-cashier-payment-option",disabled:l,onClick:()=>{h(e.id)},type:"button",children:[(0,s.jsx)("span",{children:e.name}),t?(0,s.jsx)("span",{"aria-hidden":"true",children:"✓"}):null]},e.id)})}):(0,s.jsx)("div",{className:"wsd-sandbox-cashier-payment-trigger is-static",children:m.name}),u?(0,s.jsxs)("p",{className:"wsd-sandbox-cashier-error",role:"alert",children:["支付失败,请重试:",u]}):null]}),(0,s.jsx)("footer",{className:"wsd-sandbox-cashier-actions",children:(0,s.jsx)("button",{"aria-busy":l,className:"wsd-sandbox-cashier-button",disabled:l,onClick:()=>void f(),type:"button",children:l?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("svg",{"aria-hidden":"true",className:"wsd-sandbox-cashier-spinner",viewBox:"0 0 16 16",children:[(0,s.jsx)("circle",{className:"wsd-sandbox-cashier-spinner-track",cx:"8",cy:"8",fill:"none",r:"6",strokeWidth:"2"}),(0,s.jsx)("path",{className:"wsd-sandbox-cashier-spinner-indicator",d:"M 8 2 A 6 6 0 0 1 14 8",fill:"none",strokeLinecap:"round",strokeWidth:"2"})]}),"支付中"]}):"模拟支付"})})]})]})}function cE(){let[e,t]=(0,iD.useState)(),r=(0,iD.useRef)(null),i=(0,iD.useRef)(null),n=(0,iD.useRef)(!1),a=cl((e,n)=>r.current?Promise.reject(Error("Sandbox cashier is already open")):new Promise(a=>{r.current=a,i.current=n,t(e)})),s=cl(e=>{let n=r.current;n&&(r.current=null,i.current=null,t(void 0),n(e))}),o=cl(()=>{n.current||s(!1)}),l=cl(async e=>{let t=i.current;if(!t)throw Error("Sandbox cashier is unavailable");if(!n.current){n.current=!0;try{await t(e),s(!0)}finally{n.current=!1}}});return(0,iD.useEffect)(()=>()=>{let e=r.current;r.current=null,i.current=null,n.current=!1,null==e||e(!1)},[]),{cashier:e,cancelCashier:o,confirmCashier:l,showCashier:a}}let cN=new WeakMap;async function cT(e,t,r){cN.set(e,t);try{await e.sendSimulatorQuery(r)}finally{cN.get(e)===t&&cN.delete(e)}}function cA(e,t){let r=cN.get(e);if(r&&(!t||r===t))return cN.delete(e),e.cancelSimulatorQuery(),r}var cM=e=>(0,s.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:15,height:15,fill:"none",viewBox:"0 0 15 15",...e,children:[(0,s.jsx)("path",{fill:"#999",fillRule:"evenodd",d:"M7.333 4.545a2.788 2.788 0 1 0 0 5.576 2.788 2.788 0 0 0 0-5.576m0 1.334a1.455 1.455 0 1 0 0 2.909 1.455 1.455 0 0 0 0-2.91",clipRule:"evenodd"}),(0,s.jsx)("path",{fill:"#999",fillRule:"evenodd",d:"M5.067 1.862c.489-2.483 4.045-2.483 4.533 0 2.1-1.41 4.615 1.104 3.205 3.205 2.482.489 2.482 4.044 0 4.533 1.41 2.1-1.104 4.615-3.205 3.205-.488 2.483-4.044 2.482-4.533 0-2.1 1.41-4.615-1.104-3.205-3.205-2.483-.488-2.483-4.045 0-4.533-1.41-2.1 1.105-4.615 3.205-3.205m1.307.266c.202-1.06 1.718-1.06 1.92 0a1.322 1.322 0 0 0 2.042.846c.891-.607 1.964.466 1.357 1.357a1.322 1.322 0 0 0 .846 2.043c1.06.201 1.06 1.718 0 1.92a1.322 1.322 0 0 0-.846 2.042c.607.891-.466 1.963-1.357 1.357a1.322 1.322 0 0 0-2.042.846c-.202 1.06-1.719 1.06-1.92 0a1.322 1.322 0 0 0-2.043-.846c-.891.607-1.963-.466-1.357-1.357a1.322 1.322 0 0 0-.846-2.043c-1.06-.201-1.06-1.718 0-1.92l.44-.083A1.028 1.028 0 0 0 3.225 4.7l-.251-.37c-.607-.891.466-1.964 1.357-1.357a1.322 1.322 0 0 0 2.043-.846",clipRule:"evenodd"})]});function cR(){return(0,s.jsxs)("div",{className:"wsd-doubao-status-bar","aria-hidden":"true",children:[(0,s.jsx)("span",{className:"wsd-doubao-status-time",children:"9:41"}),(0,s.jsx)("span",{className:"wsd-doubao-status-indicators"})]})}function cj(e){let{className:t,fallback:r,src:i}=e,[n,a]=(0,iD.useState)(!1);return(0,iD.useEffect)(()=>{a(!1)},[i]),(0,s.jsx)("span",{className:`${t}-box`,"aria-hidden":"true",children:i&&!n?(0,s.jsx)("img",{alt:"",className:t,onError:()=>a(!0),src:i}):(0,s.jsx)("span",{className:`${t}-fallback`,children:(null==r?void 0:r.trim().slice(0,1))||"服"})})}function cP(e){let t=Number(e);if(!Number.isFinite(t))return;let r=new Date(t);return Number.isFinite(r.getTime())?r:void 0}function cL(e){let{notices:t,onAction:r,onBack:i,status:n}=e;return(0,s.jsxs)("section",{"aria-label":"服务通知",className:"wsd-service-notice-panel",children:[(0,s.jsxs)("header",{className:"wsd-service-notice-chrome",children:[(0,s.jsx)(cR,{}),(0,s.jsxs)("div",{className:"wsd-service-notice-title-bar",children:[(0,s.jsx)("button",{"aria-label":"返回对话",className:"wsd-service-notice-nav-button is-back",onClick:i,type:"button",children:(0,s.jsx)("span",{"aria-hidden":"true"})}),(0,s.jsx)("h1",{children:"服务通知"}),(0,s.jsx)("button",{"aria-label":"服务通知设置",className:"wsd-service-notice-nav-button is-settings",type:"button",children:(0,s.jsx)(cM,{"aria-hidden":"true"})})]})]}),(0,s.jsx)("div",{className:"wsd-service-notice-list",children:"loading"===n&&0===t.length?(0,s.jsx)("p",{className:"wsd-service-notice-empty",children:"正在加载服务通知..."}):t.length>0?t.map(e=>{let t=e.title||"服务通知",i=cP(e.created_at_ms),n=e.redirect_url;return(0,s.jsxs)("div",{className:"wsd-service-notice-item",children:[(0,s.jsx)("time",{dateTime:null==i?void 0:i.toISOString(),children:function(e){let t=cP(e);if(!t)return"";let r=new Date,i=new Date(r.getFullYear(),r.getMonth(),r.getDate()).getTime(),n=new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime(),a=new Intl.DateTimeFormat("zh-CN",{hour:"2-digit",hour12:!1,minute:"2-digit"}).format(t);return n===i?a:n===i-864e5?`昨天 ${a}`:`${t.getMonth()+1}月${t.getDate()}日 ${a}`}(e.created_at_ms)}),(0,s.jsxs)("article",{"aria-label":n?`${t},查看详情`:void 0,className:`wsd-service-notice-card${n?" is-clickable":""}`,onClick:()=>{n&&(null==r||r(n))},onKeyDown:e=>{n&&("Enter"===e.key||" "===e.key)&&(e.preventDefault(),null==r||r(n))},role:n?"link":void 0,tabIndex:n?0:void 0,children:[(0,s.jsxs)("div",{className:"wsd-service-notice-app",children:[(0,s.jsx)(cj,{className:"wsd-service-notice-icon",fallback:e.app_name,src:e.app_icon_url}),(0,s.jsx)("span",{children:e.app_name||"应用插件"})]}),(0,s.jsxs)("div",{className:"wsd-service-notice-body",children:[(0,s.jsx)("h2",{children:t}),e.fields.length>0?(0,s.jsx)("dl",{children:e.fields.map((e,t)=>(0,s.jsxs)("div",{children:[(0,s.jsx)("dt",{children:e.name}),(0,s.jsx)("dd",{children:e.value})]},`${e.name}-${t}`))}):e.brief?(0,s.jsx)("p",{children:e.brief}):null]})]})]},e.notice_id)}):(0,s.jsx)("p",{className:"wsd-service-notice-empty",children:"暂无服务通知"})})]})}let cO=new Set([1,2,3]);function cD(e){return e.filter(e=>1!==e.display_status&&cO.has(e.status))}function cU(e){let{onAction:t,onClose:r,onRemove:i,onRemoveAction:n,removingTaskIds:a,tasks:o}=e,l=cD(o);async function d(e){var t,r;let a=null==(t=e.remove_action)?void 0:t.confirm;(null==a||!a.need_confirm||window.confirm([a.title||"移除任务",a.content||"确定要移除这个任务吗?"].join("\n")))&&((null==(r=e.remove_action)?void 0:r.target)&&await (null==n?void 0:n(e.remove_action.target)),await i(e.task_id))}async function u(e,i){await (null==t?void 0:t(e,i))&&r()}return((0,iD.useEffect)(()=>{let e=e=>{"Escape"===e.key&&r()};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[r]),(0,iD.useEffect)(()=>{0===l.length&&r()},[l.length,r]),0===l.length)?null:(0,s.jsxs)("div",{className:"wsd-sandbox-task-overlay-layer",children:[(0,s.jsx)("button",{"aria-label":"关闭进行中的任务",className:"wsd-sandbox-task-overlay-backdrop",onClick:r,type:"button"}),(0,s.jsx)("dialog",{"aria-label":"进行中的任务","aria-modal":"true",className:"wsd-sandbox-task-overlay",open:!0,children:(0,s.jsx)("div",{className:"wsd-sandbox-task-list",children:l.map(e=>{var t,r,i,n,o,l;let c=(null==(t=e.display_data)?void 0:t.title)||"未命名任务",p=(null==(r=e.display_data)?void 0:r.sub_title)||(null==(i=e.progress)?void 0:i.text),h=null==(n=e.primary_action)?void 0:n.target,m=a.has(e.task_id);return(0,s.jsxs)("article",{"aria-label":h?`${c},${(null==(o=e.primary_action)?void 0:o.text)||"查看详情"}`:void 0,className:(0,rL.A)("wsd-sandbox-task-card",h&&"is-clickable"),onClick:()=>{h&&u(h,e)},onKeyDown:t=>{h&&("Enter"===t.key||" "===t.key)&&(t.preventDefault(),u(h,e))},role:h?"button":void 0,tabIndex:h?0:void 0,children:[(0,s.jsx)(cj,{className:"wsd-sandbox-task-icon",fallback:c,src:null==(l=e.display_data)?void 0:l.icon_url}),(0,s.jsxs)("span",{className:"wsd-sandbox-task-copy",children:[(0,s.jsx)("strong",{children:c}),p?(0,s.jsx)("span",{children:p}):null]}),(0,s.jsx)("button",{"aria-label":`移除任务:${c}`,className:"wsd-sandbox-task-remove",disabled:m,onClick:t=>{t.stopPropagation(),d(e)},type:"button",children:(0,s.jsx)("span",{"aria-hidden":"true"})})]},e.task_id)})})})]})}let cq={bridgeLogs:[],clearBridgeLogs:()=>Promise.reject(Error("服务端日志接口不可用")),hasUnreadNotices:!1,hasUnreadTasks:!1,markServiceNoticesRead:()=>void 0,markTasksRead:()=>void 0,localConnectionStatus:"unavailable",notices:[],reconnect:()=>void 0,removeTask:async()=>void 0,removingTaskIds:new Set,status:"unavailable",tasks:[]},c$=(0,iD.createContext)(cq),cB={logs:[],updatedAtMs:0};function cF(){return{eventSequence:0,generation:0,instanceId:"",simulatorEventSequence:0}}function cz(e,t){try{let r=BigInt(e),i=BigInt(t);return r===i?0:r>i?1:-1}catch{return String(e).localeCompare(String(t),void 0,{numeric:!0})}}function cW(e){if(rP(e)&&"string"==typeof e.id&&rP(e.request)&&"string"==typeof e.status&&["error","pending","success"].includes(e.status)&&"number"==typeof e.timestamp&&"number"==typeof e.updatedAtMs)return{errorMessage:"string"==typeof e.errorMessage?e.errorMessage:void 0,id:e.id,logIds:Array.isArray(e.logIds)?e.logIds.filter(e=>"string"==typeof e):[],request:e.request,requestId:"string"==typeof e.requestId?e.requestId:"",response:rP(e.response)?e.response:void 0,sandboxSessionId:"string"==typeof e.sandboxSessionId?e.sandboxSessionId:"",status:e.status,timestamp:e.timestamp,updatedAtMs:e.updatedAtMs}}function cH(e){if(rP(e)&&("remove"===e.action||"upsert"===e.action)&&("notice"===e.resource||"task"===e.resource)&&"string"==typeof e.resourceId&&("number"==typeof e.revision||"string"==typeof e.revision)&&"number"==typeof e.sequence)return{action:e.action,eventId:"string"==typeof e.eventId?e.eventId:"",occurredAtMs:"number"==typeof e.occurredAtMs?e.occurredAtMs:void 0,resource:e.resource,resourceId:e.resourceId,revision:e.revision,sequence:e.sequence}}function cV(e){if(rP(e)&&("card_delta"===e.type||"get_simulator_card_snapshots"===e.type)&&rP(e.payload)&&("get_simulator_card_snapshots"!==e.type||"string"==typeof e.payload.event_id)&&"number"==typeof e.sequence)return{payload:e.payload,sequence:e.sequence,type:e.type}}function cG(e){let{children:t,enabled:r,connection:i,onMessage:n,webSdkDebugger:a}=e,[o,l]=(0,iD.useState)([]),[d,u]=(0,iD.useState)([]),[c,p]=(0,iD.useState)(!1),[h,m]=(0,iD.useState)(!1),[g,f]=(0,iD.useState)(r&&i?"loading":"unavailable"),[v,y]=(0,iD.useState)(cB),[b,w]=(0,iD.useState)(r&&i?"connecting":"unavailable"),[_,S]=(0,iD.useState)(new Set),x=(0,iD.useRef)(new Map),I=(0,iD.useRef)(new Map),k=(0,iD.useRef)(new Map),C=(0,iD.useRef)(new Map),E=(0,iD.useRef)({notice:void 0,task:void 0}),N=(0,iD.useRef)({}),T=(0,iD.useRef)(new Set),A=(0,iD.useRef)(!1),M=(0,iD.useRef)(),R=(0,iD.useRef)(cF()),j=(0,iD.useRef)(0),P=(0,iD.useRef)(n);P.current=n;let L=cl(async e=>{let t="string"==typeof e.payload.event_id?e.payload.event_id:"";if("card_delta"===e.type){null==a||a.applySimulatorCardDelta(e.payload);return}if(T.current.has(t))return;T.current.add(t);let r=(()=>{try{if(!a)throw Error("Web SDK debugger is unavailable");return{card_snapshots:aQ(a.getState().simulator.messages)}}catch{return{error:{code:"SNAPSHOT_COLLECTION_FAILED",message:"failed to collect simulator state"}}}})();await lB(t,r)}),O=cl(()=>{l([...x.current.values()].sort((e,t)=>Number(e.created_at_ms)-Number(t.created_at_ms)))}),D=cl(()=>{u([...I.current.values()].sort((e,t)=>Number(t.updated_at_ms)-Number(e.updated_at_ms)))}),U=cl(function(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1],r=!1;for(let t of e.notices??[]){let e=k.current.get(t.notice_id);(void 0===e||cz(t.revision,e)>0)&&(k.current.set(t.notice_id,t.revision),x.current.set(t.notice_id,t),r=!0)}for(let t of e.removed_notices??[]){let e=k.current.get(t.resource_id);(void 0===e||cz(t.revision,e)>=0)&&(k.current.set(t.resource_id,t.revision),x.current.delete(t.resource_id))}r&&t&&p(!0),O()}),q=cl(e=>{let t=C.current.get(e.resource_id);(void 0===t||cz(e.revision,t)>=0)&&(C.current.set(e.resource_id,e.revision),I.current.delete(e.resource_id),D())}),$=cl(e=>{let t=!1;for(let r of e.tasks??[]){let e=C.current.get(r.task_id);void 0!==e&&0>=cz(r.revision,e)||(C.current.set(r.task_id,r.revision),t=!0,1===r.display_status?I.current.delete(r.task_id):I.current.set(r.task_id,r))}for(let r of e.removed_tasks??[]){let e=C.current.get(r.resource_id);(void 0===e||cz(r.revision,e)>=0)&&(C.current.set(r.resource_id,r.revision),I.current.delete(r.resource_id),t=!0)}t&&m(!0),D()}),B=cl(async function(e,t){let r,i=!(arguments.length>2)||void 0===arguments[2]||arguments[2];do{let n=E.current[e],a="notice"===e?await lU({cursor:n,limit:100}):await lq({cursor:n,limit:100});if(j.current!==t)return;if("notice"===e?U(a,i):$(a),a.has_more&&!a.next_cursor)throw Error(`Sandbox ${e} pull returned has_more without next_cursor`);a.next_cursor&&(E.current[e]=a.next_cursor),r=a.has_more}while(r)}),F=cl(function(e,t){let r=!(arguments.length>2)||void 0===arguments[2]||arguments[2],i=N.current[e];if(i)return i;let n=B(e,t,r).finally(()=>{N.current[e]===n&&delete N.current[e]});return N.current[e]=n,n}),z=cl(async(e,t)=>{if(j.current===t){if("remove"===e.action){let t={resource_id:e.resourceId,revision:e.revision,updated_at_ms:e.occurredAtMs??Date.now()};if("notice"===e.resource){let t=k.current.get(e.resourceId);(void 0===t||cz(e.revision,t)>=0)&&(k.current.set(e.resourceId,e.revision),x.current.delete(e.resourceId),O())}else q(t);return}if("notice"===e.resource){let r=await lU({notice_ids:[e.resourceId]});j.current===t&&U(r)}else{let r=await lq({task_ids:[e.resourceId]});j.current===t&&$(r)}}}),W=cl(function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];e||(x.current.clear(),k.current.clear(),p(!1),l([])),I.current.clear(),C.current.clear(),E.current={notice:void 0,task:void 0},N.current={},m(!1),u([])}),H=cl(async()=>{if(!i)throw Error("服务端日志接口不可用");await i.clearSandboxLogs()}),V=cl(()=>null==i?void 0:i.start());(0,iD.useEffect)(()=>{let e;if(!i){W(),A.current=!1,M.current=void 0,R.current=cF(),y(cB),w("unavailable"),f("unavailable");return}let t=!1,n=++j.current,a=!1,s=-1,o=!1,l=M.current!==i;l||!A.current?(W(),A.current=!1,l&&(R.current=cF())):N.current={},M.current=i,f(r?"loading":"unavailable");let d=e=>{var r;if(t)return;let i=e instanceof Error?e.message:String(e);f("error"),null==(r=P.current)||r.call(P,`Sandbox 资源同步失败:${i}`,!0)},u=function(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return o?Promise.resolve():Promise.all([F("notice",n,e),F("task",n)])},c=async(i,l)=>{var d;if(t)return;if(i.bridgeLogs){let e={logs:(i.bridgeLogs??[]).map(cW).filter(e=>!!e),updatedAtMs:i.bridgeLogsUpdatedAtMs??0};y(t=>t.updatedAtMs===e.updatedAtMs?t:e)}if(!r)return;let c=i.connectionStatus!==e;e=i.connectionStatus;let p=R.current,h=!!p.instanceId&&i.instanceId!==p.instanceId||0!==p.generation&&i.generation!==p.generation;if(p.instanceId||(p.instanceId=i.instanceId),0===p.generation&&(p.generation=i.generation),h&&(p.instanceId=i.instanceId,p.generation=i.generation,p.eventSequence=0,p.simulatorEventSequence=0,T.current.clear(),o=!1,n=++j.current,a=!1,W(A.current),f("loading")),l&&(await u(A.current),A.current=!0,a=!0),i.updatedAtMs!==s){for(let e of(s=i.updatedAtMs,i.simulatorEvents.filter(e=>e.sequence>p.simulatorEventSequence).sort((e,t)=>e.sequence-t.sequence)))try{await L(e)}catch(t){let e=t instanceof Error?t.message:String(t);null==(d=P.current)||d.call(P,`Sandbox 模拟器事件处理失败:${e}`,!0)}finally{p.simulatorEventSequence=Math.max(p.simulatorEventSequence,e.sequence)}if(h&&!l&&(await u(),a=!0),o)return;let e=i.events.filter(e=>e.sequence>p.eventSequence).sort((e,t)=>e.sequence-t.sequence);for(let t of(p.eventSequence>0&&e[0]&&e[0].sequence>p.eventSequence+1&&await u(),e))await z(t,n),p.eventSequence=Math.max(p.eventSequence,t.sequence)}!o&&("reconnecting"===i.connectionStatus&&c?(f("reconnecting"),await u()):a&&"connected"===i.connectionStatus&&f("connected"))},p=async(e,t)=>{try{await c(e,t)}catch(e){(function(e){if(!(e instanceof lg))return!1;let t=e.remoteCode??e.options.httpStatus;return -1===t||401===t||403===t||404===t})(e)&&(o||(o=!0,d(e)),1)||d(e)}},h=!0,m=Promise.resolve(),g=i.subscribe(e=>{if("status"===e.type)w(e.status),"connected"!==e.status&&(h=!0);else if("sandbox"===e.type){let t=function(e){if(rP(e)&&["connected","connecting","reconnecting"].includes(String(e.connectionStatus))&&"number"==typeof e.generation&&"number"==typeof e.updatedAtMs)return{bridgeLogs:Array.isArray(e.bridgeLogs)?e.bridgeLogs:void 0,bridgeLogsUpdatedAtMs:"number"==typeof e.bridgeLogsUpdatedAtMs?e.bridgeLogsUpdatedAtMs:void 0,connectionStatus:e.connectionStatus,events:Array.isArray(e.events)?e.events.map(cH).filter(e=>!!e):[],generation:e.generation,instanceId:"string"==typeof e.instanceId?e.instanceId:"",simulatorEvents:Array.isArray(e.simulatorEvents)?e.simulatorEvents.map(cV).filter(e=>!!e):[],updatedAtMs:e.updatedAtMs}}(e.data);if(!t)return void d(Error("本地调试服务事件格式错误"));let r=h;h=!1,m=m.then(()=>p(t,r))}});return()=>{t=!0,j.current+=1,g()}},[r,i,L,F,z,W]);let G=cl(async e=>{S(t=>new Set(t).add(e));try{let t=await l$(e);q(t)}finally{S(t=>{let r=new Set(t);return r.delete(e),r})}}),J=cl(()=>{p(!1)}),K=cl(()=>{m(!1)}),Z=(0,iD.useMemo)(()=>({bridgeLogs:v.logs,clearBridgeLogs:H,hasUnreadNotices:c,hasUnreadTasks:h,localConnectionStatus:b,markServiceNoticesRead:J,markTasksRead:K,notices:o,reconnect:V,removeTask:G,removingTaskIds:_,status:g,tasks:d}),[v.logs,H,c,h,b,J,K,o,V,G,_,g,d]);return(0,s.jsx)(c$.Provider,{value:Z,children:t})}function cJ(){return(0,iD.useContext)(c$)}var cK=r(64031),cZ=r(88460);let cX={a(e){let{children:t,href:r}=e;return r&&function(e){if(!e)return!1;if(e.startsWith("#"))return!0;try{let t=new URL(e,"http://localhost");return["http:","https:","mailto:"].includes(t.protocol)}catch{return!1}}(r)?(0,s.jsx)("a",{href:r,rel:"noreferrer",target:"_blank",children:t}):(0,s.jsx)(s.Fragment,{children:t})}};function cY(e){let{text:t}=e;return(0,s.jsx)("div",{className:"wsd-widget-chat-text markdown-body wsd-widget-chat-markdown",children:(0,s.jsx)(cK.oz,{components:cX,remarkPlugins:[cZ.A],children:t})})}async function cQ(e,t){var r,i;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:globalThis.fetch,a=new URL(e,null==(r=globalThis.location)?void 0:r.href);t&&a.searchParams.set("version_tag",t);let s=await n(a.toString());if(!s.ok)throw Error(`Get Web CDN URL failed with HTTP ${s.status}`);let o=await s.json();if(0!==o.code){let e=o.message??o.msg??o.log_id??"";throw Error(`Get Web CDN URL failed: ${o.code} ${e}`.trim())}let l=null==(i=o.data)?void 0:i.web_cdn_url;if(!l)throw Error("Web CDN URL response did not include data.web_cdn_url");return l}let c0=new class extends tT{options;constructor(e={}){super(e),this.options=e}async getPackageSource(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e)throw Error("OnlinePackageManager requires appId");let r=await this.cached(`cdn:${e}\0${t.versionTag??""}`,()=>cQ(this.options.requestUrl??`https://developer.doubao.com/app_developer/resource_api/apps/${encodeURIComponent(e)}/web_cdn_url`,t.versionTag,this.options.fetcher),t);return{manifestUrl:new URL("base/manifest.json",r).href,resourceRoot:r}}async fetchPackage(e,t){let r=this.options.fetcher??globalThis.fetch,i=await r(e);if(!i.ok)throw Error(`Failed to load Web manifest: ${i.status}`);let n=await i.json();if(!(null==n?void 0:n.appId)||!n.applet)throw Error("Invalid online Web manifest");return{manifestUrl:e,resourceRoot:t,manifest:new c({...n,applet:{...n.applet,pages:n.applet.pages??[]},widgets:n.widgets??[]})}}};function c1(e){return{"doubao.callMcpTool":async t=>_(t,await lz({...e,params:t.params}))}}function c2(e){return{"doubao.updateWidget":t=>{if(!rP(t.params))return S(t,"Invalid updateWidget parameters",104);let r=e(t.params);return"updated"===r.status?_(t,{}):S(t,r.message,"not_found"===r.status?116:104)}}}function c3(e,t,r){var i;return{request_id:t,trace_id:r,card_id:e.card_id,widget_id:e.widget_id,card_type:e.card_type,entity_id:e.entity_id,source_tool_call_id:null==(i=e.source)?void 0:i.tool_call_id,render_data:e.render_data}}function c4(e){let{packageManager:t=c0,apiEnvironment:r,appId:i,fileSystemNamespace:n,card:a,inspectableTargetKey:o,reloadKey:l,nativeModulesCallHandler:d,onInspectableTargetChange:u,onTraceEvent:c,onUpdateWidget:p,requestId:h,runtimeConsoleTarget:m,traceId:g,viewport:f,widgets:v}=e,y=(0,iD.useRef)(null),b=(0,iD.useRef)(null),w=(0,iD.useRef)(a);w.current=a;let _=a.widget_id,S=f??sd,x=!!_&&((null==v?void 0:v.some(e=>e.widgetId===_))??!1),[I,k]=(0,iD.useState)(),[C,E]=(0,iD.useState)(0),[N,T]=(0,iD.useState)({status:"idle"}),A=I??S.width,M={height:`${C||Math.round(1.35*A)}px`},R=(0,iD.useMemo)(()=>{let e=(null==r?void 0:r.apiRegistry.fork())??dx();return e.registerMany(c1({appKey:a.app_id||i||"",scene:"widget",widgetId:_||"",widgetInstanceId:a.card_id||""}),{override:!0}),p&&e.registerMany(c2(p),{override:!0}),e},[null==r?void 0:r.apiRegistry,i,a.app_id,a.card_id,p,_]),j=(0,iD.useMemo)(()=>(e,t,r,i)=>{let n=ct(e,t,r);return n?void s_(m??i.element,n):null==d?void 0:d(e,t,r,i)},[d,m]);return(0,iD.useEffect)(()=>{let e=y.current;if(!e)return;let t=()=>{let t=e.clientWidth;(t>0||"u"<typeof ResizeObserver)&&k(t||S.width)};if(t(),"u"<typeof ResizeObserver)return window.addEventListener("resize",t),()=>{window.removeEventListener("resize",t)};let r=new ResizeObserver(t);return r.observe(e),()=>{r.disconnect()}},[S.width]),(0,iD.useEffect)(()=>{let e,r,a=y.current;if(!a||void 0===I)return;let s=w.current;if(a.replaceChildren(),E(0),o&&(null==u||u(o,null)),!_){let e="缺少 widget_id,已展示 fallback";T({status:"skipped",message:e}),null==c||c({category:"card",event:"simulator_card_render_skipped",reason:"missing_widget_id",summary:e,...c3(s,h,g)});return}if(!i){let e="缺少 appId,已展示 fallback";T({status:"skipped",message:e}),null==c||c({category:"card",event:"simulator_card_render_skipped",reason:"missing_app_id",summary:e,...c3(s,h,g)});return}if(!x){let e=`Manifest 中找不到 widget_id: ${_}`;T({status:"skipped",message:e}),null==c||c({category:"card",event:"simulator_card_render_skipped",reason:"widget_not_found",summary:e,...c3(s,h,g)});return}let l=!1,d=null,p=null,m=new AbortController,f=sm({...S,width:I}),v=()=>{l||E(Math.ceil(a.scrollHeight||a.getBoundingClientRect().height))},k=()=>{"u"<typeof window?v():(void 0!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(v))},C=Date.now();return T({status:"rendering"}),(async()=>(p=new rK({appId:i,signal:m.signal,packageManager:t,apiRegistry:R,fileSystemNamespace:n,sandboxUrl:void 0,nativeModulesCallHandler:j}),l)?void p.destroy():(b.current=d=new rJ({runtime:p,appId:i,viewContext:{appId:i,widgetId:_,widgetInstanceId:s.card_id},container:a,globalProps:f,initData:r2(s.render_data),onError:e=>{null==c||c({category:"card",event:"simulator_card_runtime_error",elapsed_ms:Date.now()-C,summary:e.message,...c3(s,h,g)})},widgetId:_}),d.render()))().then(e=>{!l&&e&&(null==d||d.updateData(r2(w.current.render_data)),T({status:"rendered"}),o&&(null==u||u(o,e,I)),k(),"u">typeof ResizeObserver&&(r=new ResizeObserver(k)).observe(a),null==c||c({category:"card",event:"simulator_card_rendered",elapsed_ms:Date.now()-C,...c3(s,h,g)}))}).catch(e=>{if(l)return;let t=r5(e);T({status:"error",message:t}),o&&(null==u||u(o,null)),null==c||c({category:"card",event:"simulator_card_render_failed",elapsed_ms:Date.now()-C,summary:t,...c3(s,h,g)})}),()=>{l=!0,m.abort(),void 0!==e&&window.cancelAnimationFrame(e),null==r||r.disconnect(),b.current=null,null==d||d.destroy(),null==p||p.destroy(),a.replaceChildren(),o&&(null==u||u(o,null))}},[t,r,R,i,n,a.card_id,a.refresh_key,j,o,u,c,l,S,I,x,_]),(0,iD.useEffect)(()=>{var e;null==(e=b.current)||e.updateData(r2(a.render_data))},[a.render_data]),(0,s.jsxs)("div",{className:"wsd-widget-chat-card-runtime",children:[(0,s.jsx)("div",{className:"wsd-widget-chat-card-runtime-viewport",style:M,children:(0,s.jsx)("div",{className:"wsd-widget-chat-card-runtime-target",ref:y})}),"rendering"===N.status?(0,s.jsx)("span",{className:"wsd-widget-chat-card-runtime-status",children:"卡片渲染中..."}):null,"skipped"===N.status||"error"===N.status?(0,s.jsx)("span",{className:"wsd-widget-chat-card-runtime-status",children:N.message}):null]})}let c6="mcp-privacy-login-card",c5="__doubao_apps__expired-widget";function c8(e){return e.title||e.fallback_text||e.card_type||e.card_id||"卡片"}function c9(e,t){return(null==e?void 0:e.some(e=>e.widgetId===t))?e:[...e??[],{widgetId:t}]}function c7(e,t){return`${e.messageId}:${t.blockId}:${t.card.card_id||t.blockId}`}function pe(e){let{packageManager:t,apiEnvironment:r,appId:i,fileSystemNamespace:n,block:a,cardReloadKey:o,message:l,nativeModulesCallHandler:d,onInspectableCardTargetChange:u,grantingItemIndex:c,onGrantingCardOpen:p,onGrantingPermissionDecision:h,onGrantingCardSkip:m,onTraceEvent:g,onUpdateWidget:f,runtimeConsoleTarget:v,widgetViewport:y,widgets:b}=e,w=(0,iD.useMemo)(()=>"card"===a.type&&a.card.widget_id===c5?c9(b,c5):b,[a,b]);if((0,iD.useEffect)(()=>{var e;"card"!==a.type||"permission_apply"===a.card.card_type||a.card.widget_id||null==g||g({category:"card",event:"simulator_card_render_skipped",reason:"missing_widget_id",summary:"缺少 widget_id,已展示 fallback",...(e=a.card,{request_id:l.requestId,trace_id:l.traceId,card_id:e.card_id,widget_id:e.widget_id,card_type:e.card_type})})},[a,l.requestId,l.traceId,g]),"text"===a.type)return(0,s.jsx)(cY,{text:a.text});if("image"===a.type)return(0,s.jsx)("img",{alt:a.image.name||"对话图片",className:"wsd-widget-chat-image",src:a.image.previewUrl});if("permission_apply"===a.card.card_type){var _;let e=c7(l,a),t=(null==(_=pi(a.card,c))?void 0:_.itemIndex)??0;return(0,s.jsx)(pa,{card:a.card,grantingItemIndex:t,onLogin:()=>null==p?void 0:p(a.card,e,t),onPermissionDecision:r=>null==h?void 0:h(a.card,e,t,r),onSkip:r=>null==m?void 0:m(r,a.card,e,t),onTraceEvent:g})}return a.card.widget_id?(0,s.jsx)("article",{className:"wsd-widget-chat-card has-runtime",children:(0,s.jsx)(c4,{packageManager:t,apiEnvironment:r,appId:i,fileSystemNamespace:n,card:a.card,inspectableTargetKey:c7(l,a),reloadKey:o,nativeModulesCallHandler:d,onInspectableTargetChange:u,onTraceEvent:g,onUpdateWidget:f,requestId:l.requestId,runtimeConsoleTarget:v,traceId:l.traceId,viewport:y,widgets:w})}):(0,s.jsxs)("article",{className:"wsd-widget-chat-card",children:[(0,s.jsx)("span",{className:"wsd-widget-chat-card-kicker",children:a.card.card_type||"卡片"}),(0,s.jsx)("strong",{children:c8(a.card)}),a.card.fallback_text&&a.card.fallback_text!==c8(a.card)?(0,s.jsx)("span",{className:"wsd-widget-chat-card-summary",children:a.card.fallback_text}):null]})}function pt(e){var t;return null==(t=e.render_data)?void 0:t.grantingData}function pr(e){return"pending"===e.permissionStatus||"revoked"===e.permissionStatus}function pi(e,t){let r=pt(e),i=(null==r?void 0:r.grantingList.findIndex(pr))??-1,n="number"==typeof t&&(null==r?void 0:r.grantingList[t])?t:-1===i?0:i;if(n<0)return;let a=null==r?void 0:r.grantingList[n];return a&&r?{grantingData:r,item:a,itemIndex:n}:void 0}function pn(e){let{appIcon:t}=e,[r,i]=(0,iD.useState)(!1);return((0,iD.useEffect)(()=>{i(!1)},[t]),!t||r)?null:(0,s.jsx)("img",{alt:"",className:"wsd-widget-granting-prompt-logo",onError:()=>i(!0),src:t})}function pa(e){let{card:t,grantingItemIndex:r,onLogin:i,onPermissionDecision:n,onSkip:a,onTraceEvent:o}=e,l=(0,iD.useMemo)(()=>pi(t,r),[t,r]),d=null==l?void 0:l.grantingData,u=null==l?void 0:l.item,c=(null==d?void 0:d.doubaoAppletName)||"应用插件",p=(null==u?void 0:u.grantingName)==="permission",h=(null==u?void 0:u.relatedData.scopeName)??"",m=(0,iD.useMemo)(()=>sH(h),[h]),[g,f]=(0,iD.useState)(),[v,y]=(0,iD.useState)(),b=oi.isLocationScope(h),w=void 0!==v,_=b&&"granted"===v,S=p&&(null==d?void 0:d.cardStatus)==="expired",x=p&&!g&&(!w||b)&&!S&&((null==u?void 0:u.permissionStatus)==="pending"||(null==u?void 0:u.permissionStatus)==="revoked"),I=p?m.title:`在豆包内使用 ${c}`,k=p?"granted"===g?`已允许${c}获取`:"refused"===g?`已拒绝${c}获取`:S?"已过期,暂无法操作":(null==u?void 0:u.relatedData.scopeDescription)||m.description:(null==u?void 0:u.relatedData.bizLoginDescription)||((null==u?void 0:u.grantingName)==="privacy"?"需同意后才可以继续使用":"需登录后才可以继续使用");async function C(e){if(!w){y(e?"granted":"refused"),null==o||o({category:"card",event:"simulator_granting_prompt_permission_click",granted:e,scope:h});try{let t=await (null==n?void 0:n(e));!1!==t&&f(e?"granted":"refused")}finally{y(void 0)}}}return(0,iD.useEffect)(()=>{f(void 0),y(void 0)},[t.card_id,null==d?void 0:d.cardStatus,r,null==u?void 0:u.permissionStatus,h]),(0,s.jsxs)("article",{className:(0,rL.$)("wsd-widget-granting-prompt-card",p&&"is-permission"),children:[(0,s.jsxs)("header",{className:"wsd-widget-granting-prompt-brand",children:[(0,s.jsx)(pn,{appIcon:null==d?void 0:d.doubaoAppletIcon}),(0,s.jsx)("span",{children:c})]}),(0,s.jsx)("strong",{className:"wsd-widget-granting-prompt-title",children:I}),(0,s.jsx)("p",{className:"wsd-widget-granting-prompt-description",children:k}),p?x?(0,s.jsxs)("footer",{className:"wsd-widget-granting-prompt-actions",children:[(0,s.jsx)("button",{className:"wsd-widget-granting-prompt-secondary",disabled:w,onClick:()=>void C(!1),type:"button",children:"拒绝"}),(0,s.jsxs)("button",{"aria-busy":_,className:"wsd-widget-granting-prompt-primary",disabled:w,onClick:()=>void C(!0),type:"button",children:[_?(0,s.jsxs)("svg",{"aria-hidden":"true",className:"wsd-widget-granting-prompt-spinner",viewBox:"0 0 16 16",children:[(0,s.jsx)("circle",{className:"wsd-widget-granting-prompt-spinner-track",cx:"8",cy:"8",fill:"none",r:"6",strokeWidth:"2"}),(0,s.jsx)("path",{className:"wsd-widget-granting-prompt-spinner-indicator",d:"M 8 2 A 6 6 0 0 1 14 8",fill:"none",strokeLinecap:"round",strokeWidth:"2"})]}):null,"允许"]})]}):null:(0,s.jsxs)("footer",{className:"wsd-widget-granting-prompt-actions",children:[(0,s.jsx)("button",{className:"wsd-widget-granting-prompt-secondary",onClick:function(){null==o||o({category:"card",event:"simulator_granting_prompt_skip_click",granting_name:null==u?void 0:u.grantingName}),null==a||a((null==u?void 0:u.grantingName)==="privacy"?"privacy":"login")},type:"button",children:"暂不登录"}),(0,s.jsx)("button",{className:"wsd-widget-granting-prompt-primary",onClick:function(){null==o||o({category:"card",event:"simulator_granting_prompt_login_click",granting_name:null==u?void 0:u.grantingName}),null==i||i()},type:"button",children:"登录"})]})]})}function ps(e){let{packageManager:t,apiEnvironment:r,appId:i,fileSystemNamespace:n,card:a,grantingItemIndex:o,inspectableTargetKey:l,nativeModulesCallHandler:d,onInspectableTargetChange:u,onTraceEvent:c,runtimeConsoleTarget:p,widgets:h}=e,m=(0,iD.useMemo)(()=>c9(h,c6),[h]),g=(0,iD.useMemo)(()=>(function(e,t){let r,i,n,a,s,o,l,d;return{...e,card_id:`${e.card_id||"permission_apply"}:${c6}`,card_type:"permission_apply",render_data:{...e.render_data,viewData:(i=null==(r=pi(e,t))?void 0:r.grantingData,a=(null==(n=null==r?void 0:r.item)?void 0:n.relatedData)??{},s=(null==i?void 0:i.doubaoAppletName)||"应用插件",o=(null==n?void 0:n.grantingName)==="privacy",l=a.mobileMask??"",d=o?a.bizPrivacyContent||`${s} 需要你同意隐私政策后继续。`:a.bizLoginDescription||"登录后继续使用相关服务",{type:(null==n?void 0:n.grantingName)==="privacy"?"agreePrivacyAuthorization":"getPhoneNumber",currentPage:"chat",brand:{name:s,logo:(null==i?void 0:i.doubaoAppletIcon)||""},content:{title:o?"隐私协议提示":"申请获取并验证你的手机号",description:d},buttons:o?{primary:{text:"同意并继续",loadingText:"处理中..."},secondary:{text:"暂不同意"}}:{primary:{text:l,loadingText:"登录中...",subtext:"豆包绑定号码"},secondary:{text:"暂不登录"},other:{text:"其他登录方式"}},agreement:{text:[{text:`已阅读并同意${s}的`},{text:"服务协议",url:a.termsOfServiceURL},{text:"和"},{text:"隐私政策",url:a.privacyURL}]},warningToast:"请先阅读并同意协议"})},widget_id:c6}})(a,o),[a,o]),f=(0,iD.useMemo)(()=>({key:"simulator-login-sheet",label:"登录半屏",width:393,density:3}),[]);return(0,s.jsx)("dialog",{className:"wsd-widget-granting-card has-runtime",open:!0,children:(0,s.jsx)(c4,{packageManager:t,apiEnvironment:r,appId:i,fileSystemNamespace:n,card:g,inspectableTargetKey:l,nativeModulesCallHandler:d,onInspectableTargetChange:u,onTraceEvent:c,runtimeConsoleTarget:p,viewport:f,widgets:m})})}function po(e){let{packageManager:t,apiEnvironment:r,appId:i,fileSystemNamespace:n,cardReloadKey:a,grantingItemIndexes:o,message:l,nativeModulesCallHandler:d,onInspectableCardTargetChange:u,onGrantingCardOpen:c,onGrantingPermissionDecision:p,onGrantingCardSkip:h,onTraceEvent:m,onTraceSelect:g,onUpdateWidget:f,runtimeConsoleTarget:v,selectedTraceId:y,widgetViewport:b,widgets:w}=e,_="assistant"===l.role,S=(l.blocks.length>0?l.blocks:l.text.trim()?[{blockId:`${l.messageId}-text`,type:"text",text:l.text}]:[]).reduce((e,t)=>{let r=e[e.length-1];return"text"===t.type&&(null==r?void 0:r.type)==="text"?e[e.length-1]={...r,text:`${r.text}${t.text}`}:e.push(t),e},[]),x=S.some(e=>"card"===e.type),I=S.some(e=>"image"===e.type),k=S.some(e=>"text"===e.type&&e.text.trim()),C=l.traceId,E=!!(C&&g),N=!!(C&&C===y);return(0,s.jsxs)("article",{"aria-pressed":E?N:void 0,className:(0,rL.$)("wsd-widget-chat-message",_?"is-assistant":"is-user",k&&"has-text",x&&"has-card",I&&"has-image",E&&"is-trace-selectable",N&&"is-trace-selected"),onClick:e=>{!C||!g||pl(e.target)||g(C)},onKeyDown:e=>{!C||!g||pl(e.target)||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),g(C))},role:E?"button":void 0,tabIndex:E?0:void 0,children:[_?(0,s.jsx)("span",{className:"wsd-widget-chat-avatar",children:"AI"}):null,(0,s.jsxs)("div",{className:"wsd-widget-chat-bubble",children:[S.map(e=>(0,s.jsx)(pe,{packageManager:t,apiEnvironment:r,appId:i,fileSystemNamespace:n,block:e,cardReloadKey:a,grantingItemIndex:"card"===e.type?null==o?void 0:o[c7(l,e)]:void 0,message:l,nativeModulesCallHandler:d,onGrantingCardOpen:c,onGrantingPermissionDecision:p,onGrantingCardSkip:h,onInspectableCardTargetChange:u,onTraceEvent:m,onUpdateWidget:f,runtimeConsoleTarget:v,widgetViewport:b,widgets:w},e.blockId)),"streaming"===l.status&&S.every(e=>"text"!==e.type||!e.text)?(0,s.jsx)("span",{className:"wsd-widget-chat-placeholder",children:"正在思考..."}):null]})]})}function pl(e){return e instanceof Element&&!!e.closest("button,a,input,textarea,select,.wsd-widget-chat-card")}let pd="mcp-login-page";function pu(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return JSON.stringify([e,...t.map(e=>e.resource_uri)])}function pc(e){return e.split(":")[0]||""}function pp(e){var t,r,i;let{messageInputDisabled:n=!1,packageManager:a,apiEnvironment:o,appId:l,fileSystemNamespace:d,cardReloadKey:u,controlCommand:c,nativeModulesCallHandler:p,onGrantingSheetTargetChange:h,onControlResult:m,onInspectableCardTargetChange:g,onNavigateToPage:f,onQuerySubmit:v,onSandboxLocationConfigOpen:y,onTraceEvent:b,onTraceMessageSelect:w,runtimeConsoleTarget:_,sandboxLoginHint:S,simulator:x,selectedTraceId:I,widgetViewport:k,widgets:C,webSdkDebugger:E,onMessage:N}=e,[T,A]=(0,iD.useState)(""),[M,R]=(0,iD.useState)(),[j,P]=(0,iD.useState)(!1),[L,O]=(0,iD.useState)(!1),[D,U]=(0,iD.useState)(!1),q=cJ(),$=(0,iD.useMemo)(()=>cD(q.tasks).length>0,[q.tasks]),B=(0,iD.useRef)(null),F=(0,iD.useRef)(x.messages.length),z=(0,iD.useRef)(0),W=(0,iD.useRef)(),H=(0,iD.useRef)(),V=(0,iD.useRef)(0),G=(0,iD.useRef)(!0),[J,K]=(0,iD.useState)(),[Z,X]=(0,iD.useState)({}),Y=(0,iD.useRef)(new Set),Q=(0,iD.useRef)(),ee=(0,iD.useRef)(new Set),et=(0,iD.useRef)(new Set),er=(0,iD.useRef)(new Set),ei="streaming"===x.streamStatus,en=(null==M?void 0:M.uploadStatus)==="uploading",ea=!!(T.trim()||(null==M?void 0:M.uploadedImage))&&!en&&!ei,es=(r=null==J?void 0:J.card)?null==(i=pt(r))?void 0:i.doubaoAppletKey:void 0,eo=l||es,el=cl(e=>{(K(void 0),f)?f({url:e}):E.navigateToPage(e)}),ed=cl(()=>{var e;null==o||null==(e=o.uiPresenter)||e.showToast({duration:3e3,icon:"warn",message:"请先在模拟器顶部“设置 → 定位”配置位置",type:"warning"}),null==y||y()}),eu=cl(e=>E.updateSimulatorWidget(e)),ec=cl((e,t)=>{let r=af(E,{grantingMessageId:(null==t?void 0:t.grantingMessageId)??(J?pc(J.key):void 0),noLogin:null==t?void 0:t.noLogin});if("not_found"===r.status){null==N||N("未找到需要重发的原始消息",!0);return}if("streaming"===r.status){null==N||N("当前仍在生成中,暂不重发授权后的消息",!0);return}K(void 0),null==b||b({category:"card",event:"simulator_granting_resend_query",granting_type:e,no_login:(null==t?void 0:t.noLogin)===!0,removed_message_ids:r.target.messageIds,query_preview:r.target.query.slice(0,80)}),null==v||v(),r.completion.catch(e=>{null==N||N(e.message,!0)})}),ep=cl(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};null==b||b({category:"card",event:e,card_id:t.cardId,request_id:t.requestId,source_tool_call_id:t.sourceToolCallId,tool_name:t.toolName,...r})}),eh=cl(async(e,t)=>{ep("simulator_location_directive_started",e);try{let r=await oi.requestLocationForHostDirective();if("success"!==r.status){ed(),ep("simulator_location_directive_unavailable",e,{failure_type:r.code?`browser_geolocation_${r.code}`:"browser_geolocation_unavailable",location_status:r.status});return}try{let e=oi.createBusinessLocationInfo(r.location);await lY(JSON.stringify(e))}catch(t){ep("simulator_location_directive_report_failed",e,{failure_type:t instanceof Error?t.name:typeof t}),null==N||N(`位置信息上报失败:${t instanceof Error?t.message:String(t)}`,!0);return}if(ep("simulator_location_directive_reported",e),"completed"!==E.getState().simulator.streamStatus){ep("simulator_location_directive_unavailable",e,{failure_type:"simulator_stream_not_completed"}),null==N||N("当前仍在生成中,暂不重发定位后的消息",!0);return}er.current.add(t.key),E.removeSimulatorMessages(t.messageIds),ep("simulator_location_directive_resend_started",e),null==v||v();try{await (t.images?E.sendSimulatorQuery(t.query,{images:t.images}):E.sendSimulatorQuery(t.query))}catch(e){null==N||N(e.message,!0)}}finally{et.current.delete(t.key)}});(0,iD.useEffect)(()=>{let e=x.locationDirective;if(!e||"completed"!==x.streamStatus||ee.current.has(e.cardId))return;ee.current.add(e.cardId),E.consumeSimulatorLocationDirective(e.cardId);let t=function(e,t){let r=t.replyMessageId?e.findIndex(e=>e.messageId===t.replyMessageId):e.findIndex(e=>"assistant"===e.role&&e.requestId===t.requestId),i=e.find(e=>"user"===e.role&&e.messageId===t.queryMessageId)??e.findLast((e,t)=>(-1===r||t<r)&&"user"===e.role&&(!!e.text.trim()||e.blocks.some(e=>"image"===e.type)));if(!i)return;let n=i.text.trim(),a=i.blocks.filter(e=>"image"===e.type).map(e=>e.image);if(n||0!==a.length)return{images:a.length>0?a:void 0,key:pu(n,a),messageIds:[i.messageId,...-1===r?[]:[e[r].messageId]],query:n}}(x.messages,e);if(!t)return void ep("simulator_location_directive_unavailable",e,{failure_type:"original_query_not_found"});if(et.current.has(t.key)||er.current.has(t.key)){ep("simulator_location_directive_loop_prevented",e),null==N||N("位置已上报但平台仍要求定位,请检查“设置 → 定位”中的位置状态",!0);return}et.current.add(t.key),eh(e,t)},[eh,N,x.locationDirective,x.messages,x.streamStatus,ep]);let em=cl((e,t,r,i)=>{var n;let a=pi(e,r);if(!a){null==N||N("索权卡缺少有效的授权项",!0);return}let s=`${t}:${r}`;if(Y.current.has(s))return;Y.current.add(s);let o=function(e,t){let r=pt(e);if(!r)return;let i=r.grantingList.findIndex((e,r)=>r>t&&pr(e));return -1===i?void 0:i}(e,r),l=function(e){switch(e){case"permission":case"privacy":return e;default:return"login"}}(a.item.grantingName);if(!i&&!1!==a.item.required)return void ec(l,{grantingMessageId:pc(t),noLogin:!0});if(void 0!==o){X(e=>({...e,[t]:o})),K(e=>(null==e?void 0:e.key)===t?void 0:e),null==b||b({category:"card",event:"simulator_granting_item_advanced",granted:i,granting_name:a.item.grantingName,next_granting_name:null==(n=pi(e,o))?void 0:n.item.grantingName});return}ec(l,{grantingMessageId:pc(t)})}),eg=cl((e,t,r)=>{var i,n;let a;(null==(a=null==(i=pi(e,r))?void 0:i.item)?void 0:a.grantingName)==="privacy"||(null==a||null==(n=a.relatedData.mobileMask)?void 0:n.trim())?K({card:e,itemIndex:r,key:t}):(null==b||b({category:"card",event:"simulator_granting_custom_login_navigate",reason:"missing_mobile_mask",url:pd}),el(pd))}),ef=cl(async(e,t,r,i)=>{let n,a=function(e,t){var r;let i=pi(e,t),n=null==i?void 0:i.grantingData,a=null==i?void 0:i.item,s=(null==n?void 0:n.doubaoAppletKey.trim())??"",o=(null==a||null==(r=a.relatedData.scopeName)?void 0:r.trim())??"";if((null==a?void 0:a.grantingName)==="permission"&&s&&o)return{appId:s,appName:(null==n?void 0:n.doubaoAppletName)||"应用插件",required:!1!==a.required,scope:o}}(e,r);if(!a)return null==N||N("索权卡缺少有效的应用插件 appId 或 scopeName",!0),!1;if(oi.isLocationScope(a.scope)&&(oi.updateUserAuthorization(i),i)){let e=await oi.requestLocation();if("success"!==e.status)return"browser_unauthorized"===e.status&&ed(),null==b||b({category:"card",event:"simulator_granting_location_unavailable",location_status:e.status,scope:a.scope}),!1;n=oi.createBusinessLocationInfo(e.location)}try{await lF({appletId:a.appId,granted:i,scopeName:a.scope})}catch(t){let e=t instanceof Error?t.message:String(t);return null==b||b({category:"card",event:"simulator_granting_permission_report_failed",applet_id:a.appId,granted:i,scope:a.scope}),null==N||N(`权限授权状态上报失败:${e}`,!0),!1}if(n){try{await lY(JSON.stringify(n))}catch(t){let e=t instanceof Error?t.message:String(t);return null==b||b({category:"card",event:"simulator_granting_location_report_failed",scope:a.scope}),null==N||N(`位置信息上报失败:${e}`,!0),!1}null==b||b({category:"card",event:"simulator_granting_location_reported",scope:a.scope})}return sG(a.appId,a.scope,i?"granted":"denied"),null==b||b({category:"card",event:"simulator_granting_permission_reported",applet_id:a.appId,granted:i,scope:a.scope}),em(e,t,r,i),!0}),ev=cl((e,t,r,i)=>{em(t,r,i,!1)}),ey=(0,iD.useMemo)(()=>{var e,t;if(!J)return;let r=(e=J.key,t=J.itemIndex,`${e}:${t}`);return dI({appId:eo,baseAPIRegistry:null==o?void 0:o.apiRegistry,onGrantingCompleted:(e,t)=>em(J.card,J.key,J.itemIndex,!(null==t?void 0:t.noLogin)),onCustomLoginNavigate:el,onPrivacyLoginCardClose:()=>{Promise.resolve().then(()=>{Y.current.has(r)||em(J.card,J.key,J.itemIndex,!1)})},scanCodePresenter:null==o?void 0:o.scanCodePresenter,uiPresenter:null==o?void 0:o.uiPresenter})},[J,o,eo,em,el]),eb=cl((e,t,r)=>{null==g||g(e,t,r),null==h||h(t)}),ew=cl(async e=>!1!==(f?await f(e):E.navigateToPage(e.url,{routeMode:e.routeMode}))),e_=cl(async e=>{try{let t=r1(e,E.getState().manifest.appId);if(await ew(t))return}catch{}let t=function(e,t){try{let r=new URL(e,t);return"http:"===r.protocol||"https:"===r.protocol?r.toString():void 0}catch{return}}(e,window.location.href);t&&window.open(t,"_blank","noopener,noreferrer")}),eS=cl(async(e,t)=>{try{if(!q.tasks.includes(t))throw Error("任务资源已失效,请刷新后重试");let r=r1(e,E.getState().manifest.appId);if(!await ew(r)){let e=E.getState().status;throw e.error??Error(e.message||"页面导航失败")}return!0}catch(t){var r;console.error("[web-sdk-debugger] Task navigation failed",t);let e="任务跳转失败,请检查任务配置后重试";return null==o||null==(r=o.uiPresenter)||r.showToast({duration:3e3,icon:"warn",message:e,type:"warning"}),null==N||N(e,!0),!1}}),ex=cl(()=>{U(!1)}),eI=cl(async e=>{try{await q.removeTask(e)}catch(e){null==N||N(e.message,!0)}});function ek(e){let t=W.current;t&&t.previewUrl!==(null==e?void 0:e.previewUrl)&&URL.revokeObjectURL(t.previewUrl),W.current=e,R(e)}async function eC(e){var t,r;if(ei)return;try{n4(e)}catch(t){let e=t instanceof Error?t.message:String(t);null==o||null==(r=o.uiPresenter)||r.showToast({duration:3e3,message:e,type:"error"}),null==N||N(e,!0);return}let i={name:e.name,previewUrl:URL.createObjectURL(e),uploadStatus:"uploading"},n=++V.current,a=new AbortController;null==(t=H.current)||t.abort(),H.current=a,ek(i);try{let t=await E.uploadSimulatorImage(e,a.signal);if(n!==V.current)return;ek({...i,uploadStatus:"uploaded",uploadedImage:{...t,name:e.name,previewUrl:i.previewUrl}})}catch(e){n===V.current&&"AbortError"!==e.name&&(ek({...i,uploadStatus:"failed"}),null==N||N(e.message,!0))}finally{n===V.current&&(H.current=void 0)}}(0,iD.useEffect)(()=>{let e=B.current,t=F.current,r=x.messages.at(-1),i=x.messages.length>t&&(null==r?void 0:r.role)==="user";F.current=x.messages.length,e&&(G.current||i)&&(e.scrollTop=e.scrollHeight,G.current=!0)},[null==(t=x.error)?void 0:t.message,x.messages,x.streamStatus]);let eE=cl(async(e,t)=>{er.current.delete(pu(e)),null==v||v(),await (t?cT(E,t,e):E.sendSimulatorQuery(e))});return((0,iD.useEffect)(()=>()=>{var e;V.current+=1,null==(e=H.current)||e.abort(),W.current&&URL.revokeObjectURL(W.current.previewUrl)},[]),(0,iD.useEffect)(()=>{if((null==c?void 0:c.type)!=="submit_chat_query"||Q.current===c.commandId)return;Q.current=c.commandId;let e=E.getState();if("ready"!==e.status.type){null==m||m(c.commandId,{ok:!1,error:{code:"CHAT_NOT_READY",message:"Web SDK debugger is not ready to submit a chat query"}});return}if("streaming"===e.simulator.streamStatus){null==m||m(c.commandId,{ok:!1,error:{code:"CHAT_BUSY",message:"A chat query is already streaming"}});return}let t=e.simulator.messages.length;eE(c.query,c.commandId).then(()=>{var e,r;let i=E.getState().simulator,n=null==(e=i.messages.slice(t).reverse().find(e=>"assistant"===e.role&&!!e.requestId))?void 0:e.requestId;if("completed"!==i.streamStatus||!n)throw Error((null==(r=i.error)?void 0:r.message)??"Chat query did not complete with a request ID");null==m||m(c.commandId,{ok:!0,result:{completed:!0,query:c.query,requestId:n}})}).catch(e=>{null==m||m(c.commandId,{ok:!1,error:{code:"CHAT_SUBMIT_FAILED",message:e.message}})})},[c,m,eE,E]),(0,iD.useEffect)(()=>{L&&q.hasUnreadNotices&&q.markServiceNoticesRead()},[q.hasUnreadNotices,q.markServiceNoticesRead,L]),L)?(0,s.jsx)(cL,{notices:q.notices,onAction:e_,onBack:()=>O(!1),status:q.status}):(0,s.jsxs)("div",{className:"wsd-widget-chat-panel",children:[(0,s.jsxs)("header",{className:"wsd-doubao-simulator-chrome","aria-label":"豆包模拟器标题栏",children:[(0,s.jsx)(cR,{}),(0,s.jsxs)("div",{className:"wsd-doubao-title-bar",children:[(0,s.jsxs)("div",{className:"wsd-doubao-title-actions is-left",children:[(0,s.jsx)("button",{"aria-label":q.hasUnreadNotices?"打开菜单,有更新":"打开菜单",className:(0,rL.$)("wsd-doubao-icon-button",q.hasUnreadNotices&&"has-badge"),onClick:()=>O(!0),type:"button",children:(0,s.jsx)("span",{className:"wsd-doubao-menu-icon","aria-hidden":"true"})}),(0,s.jsx)("button",{"aria-label":"打开应用入口",className:"wsd-doubao-icon-button",type:"button",children:(0,s.jsx)("span",{className:"wsd-doubao-mask-icon is-circle4","aria-hidden":"true"})})]}),(0,s.jsxs)("div",{className:"wsd-doubao-title-stack",children:[(0,s.jsxs)("span",{className:"wsd-doubao-title",children:["豆包",(0,s.jsx)("span",{"aria-hidden":"true",children:"›"})]}),(0,s.jsx)("span",{className:"wsd-doubao-subtitle",children:"doubao.com"})]}),(0,s.jsxs)("div",{className:"wsd-doubao-title-actions",children:[(0,s.jsx)("button",{"aria-label":"语音通话",className:"wsd-doubao-icon-button",type:"button",children:(0,s.jsx)("span",{className:"wsd-doubao-mask-icon is-phone","aria-hidden":"true"})}),(0,s.jsx)("button",{"aria-label":"静音",className:"wsd-doubao-icon-button",type:"button",children:(0,s.jsx)("span",{className:"wsd-doubao-mask-icon is-mute","aria-hidden":"true"})})]})]})]}),S?(0,s.jsxs)("div",{className:(0,rL.$)("wsd-doubao-login-banner",!S.available&&"is-unavailable"),children:[(0,s.jsxs)("button",{className:"wsd-doubao-login-banner-open",onClick:S.onOpen,type:"button",children:[(0,s.jsx)("span",{children:S.available?"配置登录信息,模拟登录后场景":"平台服务不可用,查看原因"}),(0,s.jsx)("span",{"aria-hidden":"true",className:"wsd-doubao-login-banner-arrow",children:"→"})]}),(0,s.jsx)("button",{"aria-label":"关闭登录信息配置提示",className:"wsd-doubao-login-banner-close",onClick:S.onClose,type:"button",children:"×"})]}):null,(0,s.jsxs)("div",{"aria-label":"对话预览",className:"wsd-widget-chat-messages",onScroll:function(e){let t=e.currentTarget;G.current=t.scrollHeight-t.scrollTop-t.clientHeight<=24},ref:B,children:[x.messages.length>0?x.messages.map(e=>(0,s.jsx)(po,{packageManager:a,apiEnvironment:o,appId:l,fileSystemNamespace:d,cardReloadKey:u,grantingItemIndexes:Z,message:e,nativeModulesCallHandler:p,onGrantingCardOpen:eg,onGrantingPermissionDecision:ef,onGrantingCardSkip:ev,onInspectableCardTargetChange:g,onTraceEvent:b,onTraceSelect:w,onUpdateWidget:eu,runtimeConsoleTarget:_,selectedTraceId:I,widgetViewport:k,widgets:C},e.messageId)):null,x.error?(0,s.jsx)("div",{className:"wsd-widget-chat-error",children:x.error.message}):null]}),!n&&(0,s.jsx)("div",{className:"wsd-widget-chat-input-dock",children:(0,s.jsxs)("form",{className:(0,rL.$)("wsd-widget-chat-composer",M&&"has-image",j&&"is-dragging-image"),onDragEnter:function(e){!ei&&Array.from(e.dataTransfer.types).includes("Files")&&(e.preventDefault(),z.current+=1,P(!0))},onDragLeave:function(e){e.preventDefault(),z.current=Math.max(0,z.current-1),0===z.current&&P(!1)},onDragOver:function(e){!ei&&Array.from(e.dataTransfer.types).includes("Files")&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},onDrop:function(e){if(e.preventDefault(),z.current=0,P(!1),ei)return;let t=Array.from(e.dataTransfer.files),r=t.find(e=>e.type.startsWith("image/"))??t[0];r&&eC(r)},onSubmit:function(e){e.preventDefault();let t=T.trim(),r=null==M?void 0:M.uploadedImage;if((t||r)&&!en&&!ei){if(A(""),r){er.current.delete(pu(t,[r])),W.current=void 0,R(void 0),null==v||v(),E.sendSimulatorQuery(t,{images:[r]}).catch(e=>{null==N||N(e.message,!0)});return}M&&ek(),eE(t).catch(e=>{null==N||N(e.message,!0)})}},children:[M?(0,s.jsxs)("div",{className:(0,rL.$)("wsd-widget-chat-image-preview",`is-${M.uploadStatus}`),children:[(0,s.jsx)("img",{alt:M.name||"待发送图片",src:M.previewUrl}),"uploading"===M.uploadStatus?(0,s.jsx)("output",{"aria-label":"图片上传中",className:"wsd-widget-chat-image-status is-uploading",children:(0,s.jsx)("span",{"aria-hidden":"true",className:"wsd-widget-chat-image-spinner"})}):null,"failed"===M.uploadStatus?(0,s.jsxs)("span",{className:"wsd-widget-chat-image-status is-failed",role:"alert",children:[(0,s.jsx)("strong",{children:"!"}),(0,s.jsx)("span",{children:"上传失败"})]}):null,(0,s.jsx)("button",{"aria-label":"移除图片",className:"wsd-widget-chat-image-remove",onClick:function(){var e;V.current+=1,null==(e=H.current)||e.abort(),H.current=void 0,ek()},type:"button",children:"×"})]}):null,(0,s.jsx)("input",{"aria-label":"输入消息",className:"wsd-widget-chat-input",disabled:ei,onChange:e=>A(e.currentTarget.value),onPaste:function(e){let t=Array.from(e.clipboardData.files).find(e=>e.type.startsWith("image/"));t&&eC(t)},placeholder:"发消息或粘贴图片...",type:"text",value:T}),(0,s.jsx)("button",{"aria-label":ei?"取消生成":"发送消息",className:"wsd-widget-chat-send",disabled:!ei&&!ea,onClick:function(){ei&&E.cancelSimulatorQuery()},type:ei?"button":"submit",children:ei?(0,s.jsx)("span",{"aria-hidden":"true",className:"wsd-doubao-cancel-icon"}):(0,s.jsx)("span",{"aria-hidden":"true",className:"wsd-doubao-send-icon"})})]})}),$&&!D?(0,s.jsx)("button",{"aria-label":"展开进行中的任务",className:"wsd-sandbox-task-collapsed-entry",onClick:()=>{q.markTasksRead(),U(!0)},type:"button",children:(0,s.jsx)("span",{"aria-hidden":"true"})}):null,J?(0,s.jsxs)("div",{className:"wsd-simulator-overlay-layer wsd-widget-granting-sheet-layer",children:[(0,s.jsx)("div",{className:"wsd-simulator-overlay-backdrop wsd-widget-granting-sheet-backdrop"}),(0,s.jsx)("div",{className:"wsd-widget-granting-sheet",children:(0,s.jsx)(ps,{packageManager:a,apiEnvironment:ey,appId:eo,fileSystemNamespace:d,card:J.card,grantingItemIndex:J.itemIndex,inspectableTargetKey:J.key,nativeModulesCallHandler:p,onInspectableTargetChange:eb,onTraceEvent:b,runtimeConsoleTarget:_,widgets:C})})]}):null,D?(0,s.jsx)(cU,{onAction:eS,onClose:ex,onRemove:eI,onRemoveAction:e_,removingTaskIds:q.removingTaskIds,tasks:q.tasks}):null]})}var ph=e=>(0,s.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",width:13,height:13,fill:"none",viewBox:"0 0 13 13",...e,children:(0,s.jsx)("path",{fill:"#999",d:"M6.346 0a6.33 6.33 0 0 1 4.763 2.153V.75a.667.667 0 0 1 1.334 0v2.813a1 1 0 0 1-1 1H8.63a.667.667 0 0 1 0-1.334h1.639a4.997 4.997 0 0 0-3.923-1.896 5.012 5.012 0 1 0 4.517 7.188.667.667 0 0 1 1.2.58A6.346 6.346 0 1 1 6.347 0"})}),pm=r(35668),pg=r(27860),pf=r(26661),pv=e=>(0,s.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",width:12,height:15,fill:"none",viewBox:"0 0 12 15",...e,children:(0,s.jsx)("path",{fill:"#999",d:"M6.667 0c1.866 0 2.8 0 3.513.363l.116.062c.574.322 1.041.807 1.34 1.395l.065.136C12 2.653 12 3.583 12 5.333v4l-.006 1.237c-.017 1.083-.085 1.742-.357 2.276a3.34 3.34 0 0 1-1.457 1.457l-.136.064c-.511.22-1.148.278-2.141.294l-1.236.006H5.333l-1.236-.006c-.993-.016-1.63-.074-2.14-.294l-.137-.064a3.34 3.34 0 0 1-1.395-1.34l-.062-.117c-.272-.534-.34-1.193-.357-2.276L0 9.333v-4c0-1.866 0-2.8.363-3.513.32-.627.83-1.137 1.457-1.457C2.533 0 3.467 0 5.333 0zM5.333 1.333c-.955 0-1.591.001-2.08.041-.474.039-.69.108-.828.177a2 2 0 0 0-.874.874c-.07.137-.138.354-.177.828-.04.489-.04 1.125-.04 2.08v4c0 .956 0 1.592.04 2.081.039.473.108.69.177.828a2 2 0 0 0 .874.873c.137.07.354.139.828.177.489.04 1.125.041 2.08.041h1.334c.955 0 1.591 0 2.08-.04.474-.04.69-.108.828-.178a2 2 0 0 0 .874-.873c.07-.138.138-.355.177-.828.04-.489.04-1.125.04-2.08v-4c0-.956 0-1.592-.04-2.081-.039-.474-.107-.69-.177-.828a2 2 0 0 0-.874-.874c-.137-.07-.354-.138-.828-.177-.489-.04-1.125-.04-2.08-.04zM8 2.667A.667.667 0 1 1 8 4H4a.667.667 0 0 1 0-1.333z"})});let py={"not determined":"尚未决定",full:"已授权",authorized:"已授权",denied:"已拒绝",restricted:"受系统限制",limited:"有限授权","add only":"仅允许添加","read only":"仅允许读取","write only":"仅允许写入",provisional:"临时授权",partial:"部分授权","foreground precise":"前台精确定位","foreground approximate":"前台模糊定位","background precise":"后台精确定位","background approximate":"后台模糊定位"},pb={none:"未中断",temporary:"临时中断",forced:"强制中断"},pw={high:"高精度",medium:"中精度",low:"低精度",unreliable:"读数不可靠","no-contact":"无法测量(无接触)"},p_={wifi:"Wi-Fi","2g":"2G","3g":"3G","4g":"4G","5g":"5G",unknown:"已连接(类型未知)",none:"断网"},pS={request:"网络请求",upload:"文件上传",download:"文件下载",socket:"WebSocket"};function px(){let e=(0,iD.useSyncExternalStore)(sI.subscribe,sI.getSnapshot),t=(0,iD.useSyncExternalStore)(sP.subscribe,sP.getSnapshot),[r,i]=(0,iD.useState)(""),n=cl(async e=>{try{await sP.control(e),i("")}catch(e){i(e instanceof Error?e.message:String(e))}});return(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"背景音频播控"}),(0,s.jsx)("p",{children:"应用插件设置资源后,可模拟系统播控。上一首和下一首只触发事件,由应用插件切换资源。"}),(0,s.jsx)("p",{children:"播放控制即时生效,状态只保留在当前调试会话中。关闭浏览器或结束应用调试时停止播放。"}),(0,s.jsx)("div",{className:"wsd-virtual-hardware-actions",children:[["play","播放"],["pause","暂停"],["stop","停止"],["prev","上一首"],["next","下一首"]].map(e=>{let[r,i]=e;return(0,s.jsx)("button",{type:"button",disabled:!t.src,onClick:()=>n(r),children:i},r)})}),(0,s.jsxs)("label",{className:"wsd-virtual-hardware-range",children:[(0,s.jsxs)("span",{children:["场景音量 ",(0,s.jsxs)("output",{children:[Math.round(100*e.volumeFactor),"%"]})]}),(0,s.jsx)("input",{type:"range","aria-label":"背景音频场景音量",min:0,max:1,step:.01,value:e.volumeFactor,onChange:e=>sI.setVolumeFactor(e.currentTarget.valueAsNumber)})]}),(0,s.jsx)("div",{className:"wsd-virtual-hardware-actions",children:[["temporary","背景音频临时中断"],["forced","背景音频强制中断"],["none","结束背景音频中断"]].map(e=>{let[t,r]=e;return(0,s.jsx)("button",{type:"button",onClick:()=>sI.setInterruption(t),children:r},t)})}),(0,s.jsxs)("p",{role:"status",children:["背景音频中断状态:",pb[e.interruption]]}),(0,s.jsx)("p",{children:"临时中断结束后恢复播放,强制中断保持暂停;主动暂停、停止、切换音频资源或退出应用后,不再自动恢复播放。"}),r?(0,s.jsx)("p",{role:"alert",children:r}):null,(0,s.jsx)("pre",{"aria-label":"背景音频状态",children:JSON.stringify(t,null,2)})]})}function pI(){let{interruption:e,volumeFactor:t}=(0,iD.useSyncExternalStore)(sx.subscribe,sx.getSnapshot);return(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"应用内音频中断"}),(0,s.jsxs)("label",{className:"wsd-virtual-hardware-range",children:[(0,s.jsxs)("span",{children:["场景音量 ",(0,s.jsxs)("output",{children:[Math.round(100*t),"%"]})]}),(0,s.jsx)("input",{type:"range","aria-label":"应用内音频场景音量",min:0,max:1,step:.01,value:t,onChange:e=>sx.setVolumeFactor(e.currentTarget.valueAsNumber)})]}),(0,s.jsx)("p",{children:"实际播放音量为应用设置的音量乘以此处的百分比,不改变播放状态。"}),(0,s.jsxs)("div",{className:"wsd-virtual-hardware-actions",children:[(0,s.jsx)("button",{type:"button",onClick:()=>sx.setInterruption("temporary"),children:"临时中断"}),(0,s.jsx)("button",{type:"button",onClick:()=>sx.setInterruption("forced"),children:"强制中断"}),(0,s.jsx)("button",{type:"button",onClick:()=>sx.setInterruption("none"),children:"结束中断"})]}),(0,s.jsxs)("p",{role:"status",children:["应用内音频中断状态:",pb[e]]}),(0,s.jsx)("p",{children:"临时中断结束后恢复播放;强制中断保持暂停。应用插件主动暂停、停止或销毁的实例不自动恢复。"}),(0,s.jsx)("p",{children:"只影响模拟器中的应用音频,不改变电脑的音频播放。中断期间调用 play 返回 -2009。"})]})}function pk(e){let{namespace:t}=e,[r,i]=(0,iD.useState)(),[n,a]=(0,iD.useState)(""),[o,l]=(0,iD.useState)(""),[d,u]=(0,iD.useState)(!1),[c,p]=(0,iD.useState)(),[h,m]=(0,iD.useState)(""),g=(0,iD.useRef)(null),[f,v]=(0,iD.useState)("temp");(0,iD.useEffect)(()=>{if(!t)return;let e=!0,r=ef(t),n=ew(r=>{e&&r.fileSystemNamespace===t&&i(ey(t))});return r.ready.then(()=>{e&&i(ey(t))}).catch(t=>{e&&a(String(t))}),()=>{e=!1,n(),r.release()}},[t]);let y=cl(async(e,t)=>{u(!0),a(""),l("");try{await e(),l(t)}catch(e){a(e instanceof Error?e.message:String(e))}finally{u(!1)}}),b=Object.values((null==r?void 0:r.storageSnapshot)??{}),w=Object.entries((null==r?void 0:r.fileSystemSnapshot.entries)??{}).filter(e=>{let[,t]=e;return"file"===t.type}),_=e=>{let t=w.filter(t=>{let[r]=t;return r.startsWith(e)}),r=t.reduce((e,t)=>{let[,r]=t;return e+("file"===r.type?3*r.data.length/4-(r.data.endsWith("==")?2:+!!r.data.endsWith("=")):0)},0);return`${t.length} 个文件 \xb7 ${(r/1024).toFixed(1)} KiB`};return(0,s.jsxs)("fieldset",{"aria-label":"存储与文件",disabled:d||!r,children:[(0,s.jsx)("p",{children:"管理当前应用插件的数据。Storage、持久文件和临时文件按应用隔离,切换应用后仍会保留。"}),(0,s.jsxs)("dl",{className:"wsd-storage-summary",children:[(0,s.jsx)("dt",{children:"Storage"}),(0,s.jsxs)("dd",{children:[b.length," 个键 ·"," ",(b.reduce((e,t)=>e+new TextEncoder().encode(t).byteLength,0)/1024).toFixed(1)," ","KiB"]}),(0,s.jsx)("dt",{children:"持久文件"}),(0,s.jsx)("dd",{children:_("/user/")}),(0,s.jsx)("dt",{children:"临时文件"}),(0,s.jsx)("dd",{children:_("/temp/")})]}),(0,s.jsx)("button",{type:"button",onClick:()=>void y(async()=>{var e;let r,i;e=await ev(t,()=>({format:"doubao-web-storage",version:1,...ey(t)})),r=URL.createObjectURL(new Blob([JSON.stringify(e,null,2)],{type:"application/json"})),(i=document.createElement("a")).href=r,i.download="app-storage-and-files.json",i.click(),setTimeout(()=>URL.revokeObjectURL(r),1e3)},"已导出当前应用的存储与文件"),children:"导出存储与文件"}),(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"导入备份"}),(0,s.jsx)("input",{ref:g,hidden:!0,"aria-label":"导入存储与文件",type:"file",accept:".json,application/json",onChange:e=>{var t;let r=null==(t=e.currentTarget.files)?void 0:t[0];e.currentTarget.value="",r&&(m(r.name),p(void 0),y(async()=>{let e;try{e=JSON.parse(await r.text())}catch(e){throw Error("无法读取备份,请选择模拟器导出的存储与文件备份",{cause:e})}eC(e),p(e)},"备份格式校验通过,确认后导入"))}}),(0,s.jsxs)("div",{className:"wsd-storage-import-actions",children:[(0,s.jsx)("button",{type:"button",onClick:()=>{var e;return null==(e=g.current)?void 0:e.click()},children:"选择文件"}),(0,s.jsx)("button",{type:"button",disabled:!c,onClick:()=>void y(async()=>{await (eC(c),ev(t,()=>ex(t,{clearStorage:!0,storageChanges:c.storageSnapshot,fileSystemChanges:eS(eb(t).entries,c.fileSystemSnapshot.entries)}))),p(void 0),m("")},"已导入存储与文件"),children:"确认导入并覆盖"})]}),(0,s.jsx)("p",{className:"wsd-storage-import-filename",children:h||"未选择文件"}),(0,s.jsx)("p",{children:"备份包含 Storage、持久文件和临时文件。导入会覆盖当前应用的数据;其他应用不受影响。"})]}),(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"清理数据"}),(0,s.jsxs)("label",{className:"wsd-virtual-hardware-row",children:["数据范围",(0,s.jsxs)("select",{value:f,onChange:e=>v(e.currentTarget.value),children:[(0,s.jsx)("option",{value:"temp",children:"临时文件"}),(0,s.jsx)("option",{value:"storage",children:"Storage"}),(0,s.jsx)("option",{value:"all",children:"全部存储与文件"})]})]}),(0,s.jsx)("button",{type:"button",onClick:()=>{window.confirm("确认清理当前应用所选的数据?此操作无法撤销。")&&y(()=>ev(t,()=>{let e=eb(t).entries,r="all"===f?ec().entries:Object.fromEntries(Object.entries(e).filter(e=>{let[t]=e;return!t.startsWith("/temp/")}));return ex(t,{clearStorage:"temp"!==f,fileSystemChanges:"storage"===f?void 0:eS(e,r)})}),"已清理所选数据")},children:"清理所选数据"})]}),n?(0,s.jsx)("p",{role:"alert",children:n}):null,o?(0,s.jsx)("p",{role:"status",children:o}):null,t?null:(0,s.jsx)("p",{role:"alert",children:"当前应用未提供存储作用域"})]})}function pC(e){let{label:t,value:r,example:i,description:n,exampleActionLabel:a="填入示例",onChange:o}=e,l=(0,iD.useId)(),d=(0,iD.useRef)(null),[u,c]=(0,iD.useState)(()=>JSON.stringify(r,null,2)),[p,h]=(0,iD.useState)(""),m=JSON.stringify(i,null,2),g=cl(e=>{var t;c(e);let r="";try{o(JSON.parse(e))}catch(e){r=e instanceof SyntaxError?"JSON 格式错误,请检查双引号、逗号和括号":e instanceof Error?e.message:String(e)}null==(t=d.current)||t.setCustomValidity(r),h(r)});return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("label",{className:"wsd-virtual-hardware-json",children:[t,(0,s.jsx)("textarea",{ref:d,"aria-label":t,"aria-invalid":!!p,"aria-describedby":p?`${l}-format ${l}-error`:`${l}-format`,required:!0,spellCheck:!1,placeholder:m,value:u,onChange:e=>g(e.currentTarget.value)})]}),p?(0,s.jsx)("p",{id:`${l}-error`,role:"alert",children:p}):null,(0,s.jsx)("p",{id:`${l}-format`,children:n}),(0,s.jsxs)("details",{className:"wsd-virtual-json-example",children:[(0,s.jsx)("summary",{children:"查看示例"}),(0,s.jsx)("pre",{"aria-label":`${t}示例`,children:m})]}),(0,s.jsx)("button",{type:"button",onClick:()=>g(m),children:a})]})}function pE(e){let{label:t,onClick:r}=e;return(0,s.jsx)("button",{"aria-label":t,className:"wsd-virtual-hardware-link",onClick:r,title:t,type:"button",children:(0,s.jsx)("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round",children:(0,s.jsx)("path",{d:"m5.5 3 5 5-5 5"})})})}function pN(e){let{beacon:t,onChange:r,locationAuthorization:i,onOpenAuthorization:n}=e;return(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"iBeacon 广播"}),(0,s.jsxs)("div",{className:"wsd-virtual-permission-row",children:[(0,s.jsx)("span",{children:"定位授权"}),(0,s.jsx)("span",{children:py[i]}),(0,s.jsx)(pE,{label:"前往定位授权设置",onClick:n})]}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:t.rangingAvailable,onChange:e=>r({...t,rangingAvailable:e.currentTarget.checked})}),"Beacon 测距可用"]}),(0,s.jsx)(pC,{label:"虚拟 Beacon 广播(JSON)",value:t.beacons,example:iF.beacons,description:"输入广播数组,必填 uuid(完整 UUID)、major/minor(0–65535 的整数)、proximity(0–3 的整数)、accuracy(不小于 -1 的米数)、rssi(-127–20 的整数 dBm)。UUID/major/minor 组合不可重复。",onChange:e=>{let i={...t,beacons:e};i$(i),r(i)}}),(0,s.jsx)("p",{children:"与上方设备共用蓝牙开关。停止搜索保留已发现缓存,重新开始清空缓存。"})]})}function pT(e){let{bluetooth:t,onChange:r,authorization:i,onOpenAuthorization:n}=e;return(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"蓝牙设备"}),[["available","蓝牙硬件可用"],["enabled","蓝牙开关"]].map(e=>{let[i,n]=e;return(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:t[i],onChange:e=>r({...t,[i]:e.currentTarget.checked})}),n]},i)}),(0,s.jsxs)("div",{className:"wsd-virtual-permission-row",children:[(0,s.jsx)("span",{children:"蓝牙授权"}),(0,s.jsx)("span",{children:py[i]}),(0,s.jsx)(pE,{label:"前往蓝牙授权设置",onClick:n})]}),(0,s.jsx)(pC,{label:"虚拟蓝牙设备(JSON)",value:t.devices,example:iG.devices,exampleActionLabel:"恢复默认设备",description:"输入设备数组,必填 deviceId(非空字符串)、name(字符串)、RSSI(-127–20 的整数 dBm)、connectable(布尔值)、advertisServiceUUIDs(UUID 数组)。deviceId 不可重复;广播、特征值和 PIN 使用 Base64。",onChange:e=>{let i={...t,devices:e};iH(i),r(i)}}),(0,s.jsx)("p",{children:"默认 GATT 服务 FFF0 / 特征 FFF1 支持读写与通知;PIN 为 MDAwMDAw(000000),最大 MTU 247。 connectionDelayMs 为 0–60000 的整数毫秒,可模拟连接延迟与超时;maxMTU 为 23–517 的整数。"})]})}async function pA(e,t,r){try{if(!navigator.clipboard)throw Error("Clipboard API is unavailable");return await navigator.clipboard.writeText(t),null==r||r(`${e} copied`),!0}catch(t){return null==r||r(`${e}: ${t.message}`,!0),!1}}function pM(e){let{settings:t,onChange:r,authorization:i,onOpenAuthorization:n}=e,[a,o]=(0,iD.useState)(t.timeZone),[l,d]=(0,iD.useState)(""),u=(0,iD.useSyncExternalStore)(sY.subscribe,sY.getEvents),[c,p]=(0,iD.useState)("structured"),[h,m]=(0,iD.useState)(""),[g,f]=(0,iD.useState)(!1),v=JSON.stringify(u,null,2),y=cl(async()=>{let e=await pA("虚拟日历事件 JSON",v);m(e?v:""),f(!e)});return(0,s.jsxs)("fieldset",{"aria-label":"日历",children:[(0,s.jsxs)("div",{className:"wsd-virtual-permission-row",children:[(0,s.jsx)("span",{children:"日历授权"}),(0,s.jsx)("span",{children:py[i]}),(0,s.jsx)(pE,{label:"前往日历授权设置",onClick:n})]}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:t.accountAvailable,onChange:e=>r({...t,accountAvailable:e.currentTarget.checked})}),"有可写日历账户"]}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:t.writeSucceeds,onChange:e=>r({...t,writeSucceeds:e.currentTarget.checked})}),"日历写入成功"]}),(0,s.jsx)("p",{children:"系统日历写入授权在“系统设置与授权”中配置,应用权限使用本地授权弹层。"}),(0,s.jsxs)("label",{className:"wsd-virtual-hardware-row",children:["日历时区",(0,s.jsx)("input",{type:"text",required:!0,value:a,onChange:e=>{let i=e.currentTarget.value;o(i);try{sX({...t,timeZone:i}),e.currentTarget.setCustomValidity(""),d(""),r({...t,timeZone:i})}catch{let t="请输入有效的 IANA 时区,例如 Asia/Shanghai";e.currentTarget.setCustomValidity(t),d(t)}}})]}),l?(0,s.jsx)("p",{role:"alert",children:l}):null,(0,s.jsx)("p",{children:"事件保存在当前浏览器,不写入电脑日历。时间、重复周期、结束时间和提醒参数可在下方查看。"}),(0,s.jsxs)("p",{role:"status",children:["虚拟日历事件:",u.length," 条"]}),(0,s.jsxs)("div",{className:"wsd-calendar-events-toolbar",children:[(0,s.jsxs)("div",{role:"group","aria-label":"日历事件显示方式",children:[(0,s.jsx)("button",{type:"button","aria-pressed":"structured"===c,onClick:()=>p("structured"),children:"结构化"}),(0,s.jsx)("button",{type:"button","aria-pressed":"json"===c,onClick:()=>p("json"),children:"JSON"})]}),(0,s.jsx)("button",{type:"button",className:"wsd-calendar-events-copy","aria-label":"复制日历事件 JSON",onClick:()=>void y(),children:h===v?"已复制":"复制 JSON"})]}),g?(0,s.jsx)("p",{role:"alert",children:"复制失败,请切换到 JSON 视图后手动复制。"}):null,"json"===c?(0,s.jsx)("textarea",{className:"wsd-calendar-events-json","aria-label":"虚拟日历事件 JSON",readOnly:!0,value:v}):u.length>0?(0,s.jsx)("ul",{className:"wsd-calendar-events-list","aria-label":"虚拟日历事件",children:u.map(e=>(0,s.jsx)(pj,{event:e},e.id))}):(0,s.jsx)("p",{children:"暂无日历事件"}),(0,s.jsx)("div",{className:"wsd-virtual-hardware-actions",children:(0,s.jsx)("button",{type:"button",disabled:0===u.length,onClick:()=>sY.clear(),children:"清空虚拟日历"})})]})}let pR={day:"每天",week:"每周",month:"每月",year:"每年"};function pj(e){let{event:t}=e,r=new Intl.DateTimeFormat("zh-CN",{timeZone:t.timeZone,dateStyle:"medium",timeStyle:t.allDay?void 0:"short",hour12:!1}).format,i=t.alarmOffset%60==0?`${t.alarmOffset/60} 分钟`:`${t.alarmOffset} 秒`,n=[["开始时间",r(1e3*t.startTime)],["结束时间",r(1e3*t.endTime)],["时区",`${t.allDay?"全天 · ":""}${t.timeZone}`],["地点",t.location],["重复",t.repeatInterval?`${pR[t.repeatInterval]},${void 0===t.repeatEndTime?"无截止日期":`截至 ${r(1e3*t.repeatEndTime)}`}`:"不重复"],["提醒",t.alarm?0===t.alarmOffset?"开始时提醒":`提前 ${i}`:"不提醒"],["备注",t.description]];return(0,s.jsxs)("li",{children:[(0,s.jsx)("strong",{children:t.title}),(0,s.jsx)("dl",{children:n.map(e=>{let[t,r]=e;return r?(0,s.jsxs)(iD.Fragment,{children:[(0,s.jsx)("dt",{children:t}),(0,s.jsx)("dd",{children:r})]},t):null})})]})}let pP=[["accelerometer","加速度计","m/s²"],["gyroscope","陀螺仪","rad/s"]],pL={ArrowLeft:[-20,0],ArrowRight:[20,0],ArrowUp:[0,-20],ArrowDown:[0,20]},pO={x:0,y:0,z:0,rx:0,ry:0,rz:0,sample:nr},pD=(e,t)=>Math.max(-t,Math.min(t,e)),pU=Math.PI/4;function pq(e){let{availability:t,onAvailabilityChange:r}=e,i=(0,iD.useRef)(null),n=(0,iD.useRef)(),a=(0,iD.useRef)(),o=(0,iD.useRef)({x:0,y:0,z:0,vx:0,vy:0,vz:0,ax:0,ay:0,az:0,rx:0,ry:0,rz:0,targetX:0,targetY:0,targetZ:0,targetRz:0,maxX:140,maxY:36,time:0}),[l,d]=(0,iD.useState)(pO),[u,c]=(0,iD.useState)(!1),p=cl(e=>{let t=o.current,r=Math.max(1/240,Math.min((e-t.time)/1e3,.05)),i=1-Math.exp(-18*r),a=t.x+(t.targetX-t.x)*i,s=t.y+(t.targetY-t.y)*i,l=t.z+(t.targetZ-t.z)*i,u=t.rz+(t.targetRz-t.rz)*i,c=(a-t.x)/r*.002,h=-(.002*((s-t.y)/r)),m=(l-t.z)/r*.002,g=t.ax+(pD((c-t.vx)/r,40)-t.ax)*i,f=t.ay+(pD((h-t.vy)/r,40)-t.ay)*i,v=t.az+(pD((m-t.vz)/r,40)-t.az)*i,y=.05>Math.abs(a-t.targetX)&&.05>Math.abs(s-t.targetY)&&.05>Math.abs(l-t.targetZ)&&5e-4>Math.abs(u-t.targetRz)&&.005>Math.hypot(c,h,m)&&.05>Math.hypot(g,f,v);y&&(a=t.targetX,s=t.targetY,l=t.targetZ,u=t.targetRz,c=h=m=g=f=v=0);let b=pD(-(.5*h),.65),w=pD(.5*c,.65),_=nr.accelerometer.z,S={accelerometer:{x:g-_*Math.sin(w),y:f+_*Math.sin(b)*Math.cos(w),z:v+_*Math.cos(b)*Math.cos(w)},gyroscope:y?nr.gyroscope:{x:pD((b-t.rx)/r,12),y:pD((w-t.ry)/r,12),z:pD((u-t.rz)/r,12)}};Object.assign(t,{x:a,y:s,z:l,vx:c,vy:h,vz:m,ax:g,ay:f,az:v,rx:b,ry:w,rz:u,time:e}),nL.setMotionSample(S),d({x:a,y:s,z:l,rx:b,ry:w,rz:u,sample:S}),n.current=y?void 0:window.requestAnimationFrame(p)}),h=()=>{void 0===n.current&&(o.current.time=performance.now(),n.current=window.requestAnimationFrame(p))},m=()=>{let e=i.current;e&&(o.current.maxX=Math.max(1,e.clientWidth/2-38),o.current.maxY=Math.max(1,e.clientHeight/2-54))},g=cl(()=>{window.cancelAnimationFrame(n.current??0),n.current=void 0,a.current=void 0,Object.assign(o.current,{x:0,y:0,z:0,vx:0,vy:0,vz:0,ax:0,ay:0,az:0,rx:0,ry:0,rz:0,targetX:0,targetY:0,targetZ:0,targetRz:0}),nL.setMotionSample(nr),d(pO),c(!1)});(0,iD.useEffect)(()=>{let e=()=>{document.hidden&&g()};return window.addEventListener("blur",g),document.addEventListener("visibilitychange",e),()=>{window.removeEventListener("blur",g),document.removeEventListener("visibilitychange",e),window.cancelAnimationFrame(n.current??0),nL.setMotionSample(nr)}},[g]);let f=cl(e=>{0!==e.button||a.current||(e.preventDefault(),e.currentTarget.focus({preventScroll:!0}),e.currentTarget.setPointerCapture(e.pointerId),m(),a.current={id:e.pointerId,originX:e.clientX+(e.shiftKey?o.current.rz/.005:-o.current.x),originY:e.clientY+(e.shiftKey?o.current.z:-o.current.y),depth:e.shiftKey},o.current.targetX=o.current.x,o.current.targetY=o.current.y,o.current.targetZ=o.current.z,o.current.targetRz=o.current.rz,c(!0),h())}),v=cl(e=>{let t=a.current;(null==t?void 0:t.id)===e.pointerId&&(t.depth?(o.current.targetZ=pD(t.originY-e.clientY,60),o.current.targetRz=pD((t.originX-e.clientX)*.005,pU)):(o.current.targetX=pD(e.clientX-t.originX,o.current.maxX),o.current.targetY=pD(e.clientY-t.originY,o.current.maxY)),h())}),y=()=>{o.current.targetX=o.current.targetY=o.current.targetZ=o.current.targetRz=0,c(!1),h()},b=cl(e=>{var t;(null==(t=a.current)?void 0:t.id)===e.pointerId&&(a.current=void 0,y())}),w=cl(e=>{let t=pL[e.key];t&&!a.current&&(e.preventDefault(),m(),e.shiftKey?(o.current.targetZ=pD(o.current.targetZ-t[1],60),o.current.targetRz=pD(o.current.targetRz-.005*t[0],pU)):(o.current.targetX=pD(o.current.targetX+t[0],o.current.maxX),o.current.targetY=pD(o.current.targetY+t[1],o.current.maxY)),c(!0),h())}),_=cl(e=>{e.key in pL&&!a.current&&y()});return(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"运动模拟"}),(0,s.jsx)("div",{className:"wsd-motion-stage",ref:i,children:(0,s.jsx)("button",{type:"button","aria-label":"拖动手机模拟运动","aria-describedby":"wsd-motion-help",className:(0,rL.$)("wsd-motion-phone",u&&"is-dragging"),style:{transform:`translate3d(${l.x}px, ${l.y}px, ${l.z}px) rotateZ(${-l.rz}rad) rotateY(${l.ry}rad) rotateX(${-l.rx}rad)`},onPointerDown:f,onPointerMove:v,onPointerUp:b,onPointerCancel:b,onLostPointerCapture:b,onKeyDown:w,onKeyUp:_,onBlur:g,children:"拖动"})}),(0,s.jsx)("p",{id:"wsd-motion-help",children:"按住手机拖动,快速往返可模拟摇动。按住 Shift 时,上下拖动模拟前后移动,左右拖动模拟绕 Z 轴旋转;方向键支持相同操作。停住后运动加速度和角速度归零,Z 轴保留重力,松开后自动复位。"}),pP.map(e=>{let[i,n,a]=e;return(0,s.jsxs)("fieldset",{children:[(0,s.jsxs)("legend",{children:[n,"(",a,")"]}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:t[i],onChange:e=>r({...t,[i]:e.currentTarget.checked})}),n,"可用"]}),(0,s.jsx)("dl",{className:"wsd-motion-readings",children:["x","y","z"].map(e=>(0,s.jsxs)("div",{children:[(0,s.jsx)("dt",{children:e.toUpperCase()}),(0,s.jsx)("dd",{children:(0,s.jsx)("output",{"aria-live":"off","aria-label":`${n} ${e.toUpperCase()}(${a})`,children:.005>Math.abs(l.sample[i][e])?"0.00":l.sample[i][e].toFixed(2)})})]},e))})]},i)})]})}function p$(e){let{network:t,onChange:r}=e,i=t.domainPolicy??iZ;return(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"网络状态"}),(0,s.jsxs)("label",{className:"wsd-virtual-hardware-row",children:["网络制式",(0,s.jsx)("select",{value:t.networkType,onChange:e=>r({...t,networkType:e.currentTarget.value}),children:iJ.map(e=>(0,s.jsx)("option",{value:e,children:p_[e]},e))})]}),(0,s.jsx)("p",{children:"在“网络制式”中选择“断网”后,会阻止联网 API 调用,并中断网络请求、文件上传下载、WebSocket 连接和网络媒体的加载或播放;恢复联网后需重新发起相关操作。联网时仍通过本机网络访问服务,所选制式与信号强度不会限制实际带宽。"}),(0,s.jsxs)("label",{className:"wsd-virtual-hardware-row",children:["Wi-Fi 信号(dBm)",(0,s.jsx)("input",{type:"number",min:-126,max:-1,step:1,required:!0,disabled:"wifi"!==t.networkType,value:Number.isFinite(t.signalStrength)?t.signalStrength:"",onChange:e=>r({...t,signalStrength:e.currentTarget.valueAsNumber})})]}),(0,s.jsx)("p",{children:"Wi-Fi 信号强度仅在模拟 Android 设备时返回,≤ -80 dBm 时标记为弱网;模拟 iOS 设备时不返回信号强度和弱网标记。下方可配置 Wi-Fi 列表与连接。"}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:t.hasSystemProxy,onChange:e=>r({...t,hasSystemProxy:e.currentTarget.checked})}),"模拟检测到系统代理"]}),(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"网络白名单"}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:!i.enabled,onChange:e=>r({...t,domainPolicy:{...i,enabled:!e.currentTarget.checked}})}),"绕过网络白名单校验"]}),i.enabled?(0,s.jsxs)(s.Fragment,{children:[iK.map(e=>(0,s.jsxs)("label",{className:"wsd-virtual-domain-list",children:[pS[e],"域名白名单",(0,s.jsx)("textarea",{value:i[e],placeholder:"socket"===e?"wss://example.com":"https://example.com",onChange:n=>r({...t,domainPolicy:{...i,[e]:n.currentTarget.value}})})]},e)),(0,s.jsx)("p",{children:"每行或逗号分隔一个地址,留空则拒绝该类联网调用;网络请求和文件上传下载使用 HTTPS,WebSocket 使用 WSS。域名和显式端口精确匹配, 不匹配子域名或通配符,路径不参与匹配。修改只影响新调用。"})]}):(0,s.jsx)("p",{children:"完全绕过网络请求、文件上传下载和 WebSocket 的域名白名单校验;取消勾选后可分别配置。"})]})]})}let pB=[["camera","摄像头授权",i2],["contacts","联系人授权",i2],["microphone","麦克风授权",i2],["album","相册授权",i3],["locationAuthorization","定位授权",i9],["bluetoothAuthorization","蓝牙授权",i8],["phoneCalendar","日历授权",i4],["notification","通知授权",i6],["notificationAlert","通知提醒",i5],["notificationBadge","通知角标",i5],["notificationSound","通知声音",i5]],pF={locationAuthorization:"location",bluetoothAuthorization:"bluetooth",phoneCalendar:"calendar"};function pz(e){let{system:t,onChange:r,authorizationFallbacks:i,onHardwareChange:n}=e,a=t.healthData,o={...t,...i};return(0,s.jsxs)("fieldset",{"aria-label":"系统设置与授权",children:[(0,s.jsxs)("label",{className:"wsd-virtual-hardware-row",children:[(0,s.jsx)("span",{children:"系统主题"}),(0,s.jsxs)("select",{value:t.theme??"",onChange:e=>r({...t,theme:e.currentTarget.value||void 0}),children:[(0,s.jsx)("option",{value:"",children:"跟随浏览器"}),(0,s.jsx)("option",{value:"light",children:"浅色"}),(0,s.jsx)("option",{value:"dark",children:"深色"})]})]}),pB.map(e=>{let[i,a,l]=e,d=pF[i];return(0,s.jsxs)("div",{className:"wsd-virtual-permission-row",children:[(0,s.jsx)("label",{htmlFor:`wsd-system-permission-${i}`,children:a}),(0,s.jsx)("select",{id:`wsd-system-permission-${i}`,value:o[i]??"not determined",onChange:e=>r({...t,[i]:e.currentTarget.value}),children:l.map(e=>(0,s.jsx)("option",{value:e,children:py[e]},e))}),d?(0,s.jsx)(pE,{label:`前往${a.replace("授权","")}设置`,onClick:()=>n(d)}):null]},i)}),(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"健康授权模拟"}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:!!a,onChange:e=>{r({...t,healthData:e.currentTarget.checked?{requestCompleted:!0,readStatus:{}}:void 0})}}),"启用健康授权模拟"]}),(0,s.jsx)("p",{children:"直接返回配置的状态,不读取真实健康数据;适用于所有模拟设备。"}),a&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:a.requestCompleted,onChange:e=>r({...t,healthData:{...a,requestCompleted:e.currentTarget.checked}})}),"健康授权流程成功"]}),(0,s.jsx)(pC,{label:"健康读取状态 JSON",value:a.readStatus,example:{heart_rate:2},description:"输入 JSON 对象,键为非空的健康数据类型,值为数字状态:-1 未知或不支持、0 需要授权、1 推断已拒绝、2 未发现授权错误。允许使用空对象 {}。",onChange:e=>{let i={...t,healthData:{...a,readStatus:e}};i7(i),r(i)}})]})]})]})}let pW=[{ssid:"Example Wi-Fi",bssid:"10:20:30:40:50:60",password:"wifi-password",secure:!0,signalStrength:88,frequency:2462}];function pH(e){let{wifi:t,onChange:r}=e;return(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"Wi-Fi 连接与设备"}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{checked:t.available,type:"checkbox",onChange:e=>r({...t,available:e.currentTarget.checked})}),"Wi-Fi 硬件可用"]}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{checked:t.enabled,type:"checkbox",onChange:e=>r({...t,enabled:e.currentTarget.checked})}),"Wi-Fi 开关"]}),(0,s.jsxs)("label",{className:"wsd-virtual-hardware-row",children:["当前连接",(0,s.jsxs)("select",{value:t.connectedNetworkKey,onChange:e=>r({...t,connectedNetworkKey:e.currentTarget.value}),children:[(0,s.jsx)("option",{value:"",children:"未连接"}),t.networks.map(e=>(0,s.jsxs)("option",{value:ns(e),children:[e.ssid,e.bssid?` (${e.bssid})`:""]},ns(e)))]})]}),(0,s.jsx)(pC,{label:"虚拟 Wi-Fi 网络(JSON)",value:t.networks,example:pW,description:"输入网络数组,必填 ssid(非空字符串)、password(字符串,开放网络使用空字符串)。可选 bssid 为 MAC 地址,secure 为布尔值,signalStrength 为 0–100 的数值,frequency 为正整数 MHz。SSID/BSSID 组合不可重复。",onChange:e=>{let i={...t,networks:e,connectedNetworkKey:""};no(i),e.some(e=>ns(e)===t.connectedNetworkKey)&&(i.connectedNetworkKey=t.connectedNetworkKey),r(i)}})]})}let pV=[["北",80,12],["东",148,80],["南",80,148],["西",12,80]];function pG(e){let{direction:t,onChange:r}=e,i=(0,iD.useRef)(),n=t%360,a=e=>{let t=e.currentTarget.getBoundingClientRect(),r=e.clientX-t.left-t.width/2,i=e.clientY-t.top-t.height/2;if(!(8>Math.hypot(r,i)))return 180*Math.atan2(r,-i)/Math.PI},o=cl(e=>{0!==e.button||i.current||(e.preventDefault(),e.currentTarget.focus({preventScroll:!0}),e.currentTarget.setPointerCapture(e.pointerId),i.current={id:e.pointerId,angle:a(e),heading:n})}),l=cl(e=>{let t=i.current;if((null==t?void 0:t.id)!==e.pointerId)return;let s=a(e);if(void 0===s||void 0===t.angle){t.angle=s,t.heading=n;return}r((Math.round(t.heading+t.angle-s)+360)%360)}),d=e=>{var t;(null==(t=i.current)?void 0:t.id)===e.pointerId&&(i.current=void 0)},u=cl(e=>{if(i.current)return;let t=e.shiftKey?10:1,a=n;switch(e.key){case"ArrowUp":case"ArrowRight":a+=t;break;case"ArrowDown":case"ArrowLeft":a-=t;break;case"Home":a=0;break;case"End":a=359;break;default:return}e.preventDefault(),r((a+360)%360)});return(0,s.jsxs)("div",{className:"wsd-compass-control",children:[(0,s.jsx)("span",{className:"wsd-compass-heading",children:"设备朝向"}),(0,s.jsxs)("button",{type:"button",role:"slider","aria-label":"设备朝向","aria-valuemin":0,"aria-valuemax":360,"aria-valuenow":n,"aria-valuetext":`${n}\xb0`,"aria-describedby":"wsd-compass-help",className:"wsd-compass-dial",onPointerDown:o,onPointerMove:l,onPointerUp:d,onPointerCancel:d,onLostPointerCapture:d,onBlur:()=>{i.current=void 0},onKeyDown:u,children:[(0,s.jsx)("svg",{viewBox:"0 0 160 160","aria-hidden":"true",children:(0,s.jsxs)("g",{transform:`rotate(${-n} 80 80)`,children:[Array.from({length:24},(e,t)=>(0,s.jsx)("line",{x1:"80",y1:"23",x2:"80",y2:t%6==0?"31":"27",transform:`rotate(${15*t} 80 80)`},t)),pV.map(e=>{let[t,r,i]=e;return(0,s.jsx)("text",{x:r,y:i,transform:`rotate(${n} ${r} ${i})`,children:t},t)})]})}),(0,s.jsxs)("output",{"aria-hidden":"true",children:[n,"°"]})]}),(0,s.jsx)("p",{id:"wsd-compass-help",children:"拖动方位盘模拟转向,方向键微调,Shift + 方向键每次调整 10°。"})]})}function pJ(e){let{onClose:t,storageNamespace:r,selectedHardware:i,onHardwareChange:n}=e,a=(0,iD.useRef)(null),o=(0,iD.useRef)(null),l=cl(e=>{let t=e.currentTarget===a.current?o.current:a.current;t&&(t.scrollTop=e.currentTarget.scrollTop)});(0,iD.useEffect)(()=>{let e=a.current,t=o.current,r=null==t?void 0:t.firstElementChild;if(!e||!t||!r)return;let i=()=>{r.style.height=e.scrollHeight>e.clientHeight?`${e.scrollHeight}px`:"0px",t.scrollTop=e.scrollTop},n=new ResizeObserver(i);for(let t of(n.observe(e),e.children))n.observe(t);return i(),()=>n.disconnect()},[i]);let[d,u,c]=pK(nL.getBattery,e=>nL.setBattery(e)),[p,h,m]=pK(()=>({accelerometer:nL.getAccelerometer().available,gyroscope:nL.getGyroscope().available}),e=>{e.accelerometer!==nL.getAccelerometer().available&&nL.setAccelerometer({available:e.accelerometer}),e.gyroscope!==nL.getGyroscope().available&&nL.setGyroscope({available:e.gyroscope})}),[g,f,v]=pK(nL.getCompass,e=>nL.setCompass(e)),[y,b,w]=pK(nL.getWifi,e=>nL.setWifi(e)),[_,S,x]=pK(nL.getNetwork,e=>nL.setNetwork(e)),[I,k,C]=pK(nL.getBluetooth,e=>nL.setBluetooth(e)),[E,N,T]=pK(nL.getBeacon,e=>nL.setBeacon(e)),[A,M,R]=pK(nL.getSystem,e=>nL.setSystem(e)),j=A.bluetoothAuthorization??(I.authorized?"full":"denied"),P=A.locationAuthorization??(E.locationAuthorized?A.locationReducedAccuracy?"foreground approximate":"foreground precise":"denied"),[L,O,D]=pK(nL.getScreen,e=>nL.setScreen(e)),[U,q,$]=pK(nL.getKeyboard,e=>nL.setKeyboard(e)),[B,F,z]=pK(nL.getAccessibility,e=>nL.setAccessibility(e)),[W,H,V]=pK(nL.getCommunication,e=>nL.setCommunication(e)),[G,J,K]=pK(sY.getSettings,e=>sY.setSettings(e)),Z=(0,iD.useSyncExternalStore)(oi.subscribe,oi.getSnapshot,oi.getSnapshot),[X,Y]=(0,iD.useState)(()=>{var e,t;return{longitude:(null==(e=Z.longitude)?void 0:e.toString())??"",latitude:(null==(t=Z.latitude)?void 0:t.toString())??""}});(0,iD.useEffect)(()=>{if("browser"===Z.source){var e,t;Y({longitude:(null==(e=Z.longitude)?void 0:e.toString())??"",latitude:(null==(t=Z.latitude)?void 0:t.toString())??""})}},[Z.source,Z.longitude,Z.latitude]);let Q=(0,iD.useSyncExternalStore)(l9.subscribe,l9.getSnapshot),[ee,et,er]=pK(nL.getDeviceMotion,e=>nL.setDeviceMotion(e)),[ei,en]=(0,iD.useState)(""),[ea,es]=(0,iD.useState)(""),eo=cl(e=>{Y(e);try{if(e.longitude||e.latitude){if(!e.longitude||!e.latitude)throw Error("请填写完整的经纬度");oi.setManualLocation({longitude:Number(e.longitude),latitude:Number(e.latitude)})}es("")}catch(e){es(e instanceof Error?e.message:String(e))}}),el={battery:c,sensors:m||v||er,network:x||w,bluetooth:C||T||R,system:R,screen:D||$,accessibility:z,communication:V,calendar:K,location:ea||R,audio:"",storage:""},ed=cl(async()=>{es(""),await oi.requestBrowserLocation()});return(0,s.jsx)("dialog",{"aria-label":"模拟器设置",className:"wsd-preview-toolbar-menu wsd-virtual-hardware-settings",open:!0,children:(0,s.jsxs)("div",{className:"wsd-virtual-hardware-layout",children:[(0,s.jsxs)("div",{className:"wsd-virtual-hardware-header",children:[(0,s.jsx)("strong",{children:"模拟器设置"}),el[i]?(0,s.jsx)("p",{role:"alert",children:el[i]}):null,(0,s.jsxs)("label",{className:"wsd-virtual-hardware-category",children:["设置类别",(0,s.jsxs)("select",{value:i,onChange:e=>{n(e.currentTarget.value)},children:[(0,s.jsx)("option",{value:"system",children:"系统设置与授权"}),(0,s.jsx)("option",{value:"storage",children:"存储与文件"}),(0,s.jsx)("option",{value:"battery",children:"电池"}),(0,s.jsx)("option",{value:"network",children:"网络与 Wi-Fi"}),(0,s.jsx)("option",{value:"location",children:"定位"}),(0,s.jsx)("option",{value:"bluetooth",children:"蓝牙与 iBeacon"}),(0,s.jsx)("option",{value:"sensors",children:"传感器"}),(0,s.jsx)("option",{value:"screen",children:"屏幕与键盘"}),(0,s.jsx)("option",{value:"audio",children:"音频与中断"}),(0,s.jsx)("option",{value:"accessibility",children:"无障碍"}),(0,s.jsx)("option",{value:"calendar",children:"日历"}),(0,s.jsx)("option",{value:"communication",children:"电话与短信"})]})]})]}),(0,s.jsxs)("div",{className:"wsd-virtual-hardware-content",ref:a,onScroll:l,children:["storage"===i?(0,s.jsx)(pk,{namespace:r},r):null,"battery"===i?(0,s.jsxs)("fieldset",{"aria-label":"电池",children:[(0,s.jsxs)("label",{className:"wsd-virtual-hardware-range",children:[(0,s.jsxs)("span",{children:["电量 ",(0,s.jsxs)("output",{children:[d.level,"%"]})]}),(0,s.jsx)("input",{max:100,min:0,step:1,type:"range","aria-label":"电量",value:d.level,onChange:e=>{u({...d,level:Number(e.currentTarget.value)})}})]}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{checked:d.isCharging,type:"checkbox",onChange:e=>{u({...d,isCharging:e.currentTarget.checked})}}),"充电中"]}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{checked:d.isLowPowerModeEnabled,type:"checkbox",onChange:e=>{u({...d,isLowPowerModeEnabled:e.currentTarget.checked})}}),"省电模式"]})]}):null,"location"===i?(0,s.jsxs)("fieldset",{"aria-label":"定位",children:[(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:A.locationEnabled,onChange:e=>{M({...A,locationEnabled:e.currentTarget.checked})}}),"系统定位开关"]}),(0,s.jsxs)("div",{className:"wsd-virtual-permission-row",children:[(0,s.jsx)("span",{children:"定位授权"}),(0,s.jsx)("span",{children:py["denied"===Z.browserAuthorization?"denied":P]}),(0,s.jsx)(pE,{label:"前往定位授权设置",onClick:()=>n("system")})]}),(0,s.jsx)("p",{children:"此授权也用于 iBeacon。"}),["longitude","latitude"].map(e=>(0,s.jsxs)("label",{className:"wsd-virtual-hardware-row",children:["longitude"===e?"经度":"纬度",(0,s.jsx)("input",{type:"number",min:"longitude"===e?-180:-90,max:"longitude"===e?180:90,step:"any",required:!!X["longitude"===e?"latitude":"longitude"],value:X[e],onChange:t=>{eo({...X,[e]:t.currentTarget.value})}})]},e)),(0,s.jsx)("p",{children:"坐标用于应用插件定位和对话中的位置权限请求。经纬度均留空时,沿用已有定位配置;尚未配置时,在应用请求位置时使用浏览器定位。手动输入使用 GCJ-02 坐标系,浏览器位置会自动转换。"}),(0,s.jsx)("p",{role:"error"===Z.tone?"alert":"status",children:Z.message}),Z.errorMessage?(0,s.jsx)("p",{role:"alert",children:Z.errorMessage}):null,(0,s.jsx)("button",{type:"button",disabled:"pending"===Z.tone,onClick:ed,children:"使用浏览器定位"})]}):null,"sensors"===i?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(pq,{availability:p,onAvailabilityChange:h}),(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"罗盘"}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{checked:g.available,type:"checkbox",onChange:e=>{f({...g,available:e.currentTarget.checked})}}),"罗盘可用"]}),(0,s.jsx)(pG,{direction:g.direction,onChange:e=>f({...g,direction:e})}),(0,s.jsxs)("label",{className:"wsd-virtual-hardware-row",children:["罗盘精度",(0,s.jsx)("select",{value:g.accuracy,onChange:e=>{f({...g,accuracy:e.currentTarget.value})},children:nu.map(e=>(0,s.jsx)("option",{value:e,children:pw[e]},e))})]})]}),(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"设备方向(rad)"}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{checked:ee.available,type:"checkbox",onChange:e=>{et({...ee,available:e.currentTarget.checked})}}),"设备方向可用"]}),(0,s.jsx)("div",{className:"wsd-virtual-sensor-axes",children:["alpha","beta","gamma"].map(e=>(0,s.jsxs)("label",{children:[e,(0,s.jsx)("input",{"aria-label":`设备方向 ${e}(rad)`,required:!0,step:"any",type:"number",value:Number.isFinite(ee[e])?ee[e]:"",onChange:t=>{et({...ee,[e]:t.currentTarget.valueAsNumber})}})]},e))})]})]}):null,"network"===i?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(p$,{network:_,onChange:S}),(0,s.jsx)(pH,{wifi:y,onChange:b})]}):null,"bluetooth"===i?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(pT,{bluetooth:I,authorization:j,onOpenAuthorization:()=>n("system"),onChange:e=>{k(e)}}),(0,s.jsx)(pN,{beacon:E,onChange:N,locationAuthorization:P,onOpenAuthorization:()=>n("system")})]}):null,"system"===i?(0,s.jsx)(pz,{system:A,onChange:M,authorizationFallbacks:{bluetoothAuthorization:j,locationAuthorization:P},onHardwareChange:n}):null,"screen"===i?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"屏幕"}),(0,s.jsxs)("label",{className:"wsd-virtual-hardware-range",children:[(0,s.jsxs)("span",{children:["基准亮度 ",(0,s.jsxs)("output",{children:[Math.round(100*L.brightness),"%"]})]}),(0,s.jsx)("input",{min:0,max:1,step:.01,type:"range","aria-label":"基准亮度",value:L.brightness,onChange:e=>{O({...L,brightness:Number(e.currentTarget.value)})}})]}),(0,s.jsx)("p",{children:"亮度作用于手机预览。应用通过 API 设置的亮度仅在页面显示时生效,页面关闭后恢复基准亮度。"}),(0,s.jsxs)("p",{children:["当前模拟亮度:",Q.brightness,";常亮状态:",Q.keepScreenOn?"开启":"关闭","。常亮开关只记录模拟状态。"]}),(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:L.recording,onChange:e=>{O({...L,recording:e.currentTarget.checked})}}),"正在录屏"]}),(0,s.jsxs)("p",{children:["录屏保护:",Q.screenRecordDisabled?"开启":"关闭"]}),(0,s.jsx)("p",{children:"截屏和录屏使用模拟输入,浏览器或系统截图不受此处保护开关限制。"}),(0,s.jsx)("button",{type:"button",onClick:()=>{en(l9.capture().protected?"模拟捕获结果:应用内容受保护":"模拟捕获结果:应用内容可见")},children:"模拟截屏"}),(0,s.jsx)("p",{role:"status",children:ei})]}),(0,s.jsxs)("fieldset",{children:[(0,s.jsx)("legend",{children:"键盘"}),(0,s.jsxs)("label",{className:"wsd-virtual-hardware-row",children:["键盘高度",(0,s.jsx)("input",{"aria-label":"键盘高度(Android dp / iOS pt)",type:"number",min:0,max:1e3,step:"any",required:!0,value:Number.isFinite(U.height)?U.height:"",onChange:e=>{q({height:e.currentTarget.valueAsNumber})}})]}),(0,s.jsx)("p",{children:"高度单位为 Android dp / iOS pt。页面内文本输入获得焦点时报告此高度,失去焦点或调用 hideKeyboard 时报告 0。"}),(0,s.jsx)("p",{children:"使用电脑键盘输入,不绘制手机软键盘,也不改变浏览器窗口尺寸。"})]})]}):null,"accessibility"===i?(0,s.jsxs)("fieldset",{"aria-label":"无障碍状态",children:[[["available","Android 无障碍服务可用"],["androidEnabled","Android 无障碍服务已开启"],["touchExplorationEnabled","Android 触摸探索已开启"],["voiceOverRunning","iOS VoiceOver 已开启"],["switchControlRunning","iOS 开关控制已开启"]].map(e=>{let[t,r]=e;return(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:B[t],onChange:e=>{F({...B,[t]:e.currentTarget.checked})}}),r]},t)}),(0,s.jsx)("p",{children:"Android 同时开启服务与触摸探索时返回 true;iOS 开启 VoiceOver 或开关控制时返回 true。"}),(0,s.jsx)("p",{children:"只模拟查询结果,不改变电脑的辅助功能。"})]}):null,"communication"===i?(0,s.jsxs)("fieldset",{"aria-label":"电话与短信",children:[[["phoneAvailable","设备支持电话"],["phoneOpenSucceeds","拨号面板打开成功"],["smsAvailable","设备支持短信"],["smsOpenSucceeds","短信面板打开成功"],["smsSendSucceeds","模拟发送短信成功"]].map(e=>{let[t,r]=e;return(0,s.jsxs)("label",{children:[(0,s.jsx)("input",{type:"checkbox",checked:W[t],onChange:e=>{H({...W,[t]:e.currentTarget.checked})}}),r]},t)}),(0,s.jsx)("p",{children:"短信等待模拟发送或取消后返回结果。所有交互均在模拟器内完成。"})]}):null,"calendar"===i?(0,s.jsx)(pM,{settings:G,onChange:J,authorization:A.phoneCalendar,onOpenAuthorization:()=>n("system")}):null,"audio"===i?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(pI,{}),(0,s.jsx)(px,{})]}):null]},i),(0,s.jsx)("div",{"aria-hidden":"true",className:"wsd-virtual-hardware-scrollbar",ref:o,tabIndex:-1,onScroll:l,children:(0,s.jsx)("div",{})}),(0,s.jsx)("div",{className:"wsd-virtual-hardware-actions",children:(0,s.jsx)("button",{onClick:t,type:"button",children:"关闭"})})]})})}function pK(e,t){let[r,i]=(0,iD.useState)(e),[n,a]=(0,iD.useState)(""),s=cl(n=>{let s=Object.fromEntries(Object.entries(n).filter(e=>{let[t,i]=e;return!Object.is(i,r[t])}));try{t({...e(),...s}),i(e()),a("")}catch(e){i(n),a(e instanceof Error?e.message:String(e))}});return[r,s,n]}let pZ=[{key:"conversation",label:"对话"},{key:"tool",label:"工具"},{key:"card",label:"卡片"},{key:"page",label:"全页"}],pX=[{label:"iOS",devices:so.filter(e=>e.key.startsWith("iphone"))},{label:"Android",devices:so.filter(e=>e.key.startsWith("pixel")||e.key.startsWith("galaxy"))},{label:"平板",devices:so.filter(e=>e.key.startsWith("ipad"))}];function pY(e){let{activeView:t,children:r,hasTools:i=!1,onActiveViewChange:n,onDeviceChange:a,selectedDeviceKey:o,storageNamespace:l}=e,d=pZ.filter(e=>"tool"!==e.key||i),[u,c]=(0,iD.useState)(!1),[p,h]=(0,iD.useState)(!1),[m,g]=(0,iD.useState)(ni["0"]),[f,v]=(0,iD.useState)(),y=su(o??ss),[b,w]=(0,iD.useState)(()=>String(y.width)),[_,S]=(0,iD.useState)(()=>String(y.height)),x=(0,iD.useRef)(null),I=(null==o?void 0:o.startsWith("custom-"))===!0&&y.key===o,k=(e,t)=>{let r=`custom-${e}x${t}`;su(r).key===r&&(null==a||a(r))};return(0,iD.useEffect)(()=>{let e=e=>{let t=e.detail;"string"==typeof t&&ni.includes(t)&&(g(t),v("settings"),c(!1),h(!0))},t=e=>{var t;(null==(t=x.current)?void 0:t.contains(e.target))||(c(!1),h(!1))},r=e=>{"Escape"===e.key&&(c(!1),h(!1))};return window.addEventListener("pointerdown",t),window.addEventListener("keydown",r),window.addEventListener(nn,e),()=>{window.removeEventListener("pointerdown",t),window.removeEventListener("keydown",r),window.removeEventListener(nn,e)}},[]),(0,s.jsxs)("header",{className:"wsd-preview-device-toolbar",ref:x,children:[(0,s.jsxs)("div",{className:"wsd-device-toolbar-leading",children:[(0,s.jsx)("button",{"aria-label":"手机预览","aria-expanded":u,"aria-haspopup":"dialog","aria-pressed":"phone"===f,className:(0,rL.$)("wsd-device-toolbar-icon","phone"===f&&"is-active"),onClick:()=>{v("phone"),h(!1),u||(w(String(y.width)),S(String(y.height))),c(e=>!e)},type:"button",children:(0,s.jsx)(pv,{"aria-hidden":"true"})}),u?(0,s.jsxs)("dialog",{"aria-label":"选择模拟器类型",className:"wsd-preview-toolbar-menu",open:!0,children:[(0,s.jsx)("div",{className:"wsd-custom-device-size-label",children:"自定义"}),(0,s.jsxs)("div",{className:(0,rL.$)("wsd-custom-device-size",I&&"is-selected"),children:[(0,s.jsx)("input",{"aria-label":"自定义宽度",className:"wsd-custom-device-size-input",max:9999,min:1,onChange:e=>{let t=e.currentTarget.value;w(t),k(t,_)},step:1,type:"number",value:b}),(0,s.jsx)("span",{"aria-hidden":"true",className:"wsd-custom-device-size-separator",children:"×"}),(0,s.jsx)("input",{"aria-label":"自定义高度",className:"wsd-custom-device-size-input",max:9999,min:1,onChange:e=>{let t=e.currentTarget.value;S(t),k(b,t)},step:1,type:"number",value:_}),(0,s.jsx)("span",{"aria-hidden":"true",className:"wsd-custom-device-size-check",children:"✓"})]}),(0,s.jsx)(pm.o,{"aria-label":"选择预设机型",className:"wsd-preview-toolbar-device-menu",selectedKeys:!I&&o?[o]:[],selectionMode:"single",onAction:e=>{null==a||a(String(e)),c(!1)},children:pX.map(e=>(0,s.jsx)(pg.g,{showDivider:e!==pX.at(-1),title:e.label,children:e.devices.map(e=>(0,s.jsx)(pf.Y,{title:e.label,children:e.label},e.key))},e.label))})]}):null,(0,s.jsx)("button",{"aria-label":"设置","aria-expanded":p,"aria-haspopup":"dialog","aria-pressed":"settings"===f,className:(0,rL.$)("wsd-device-toolbar-icon","settings"===f&&"is-active"),onClick:()=>{v("settings"),c(!1),h(e=>!e)},type:"button",children:(0,s.jsx)(cM,{"aria-hidden":"true"})}),p?(0,s.jsx)(pJ,{selectedHardware:m,storageNamespace:l,onHardwareChange:g,onClose:()=>h(!1)}):null]}),(0,s.jsx)("div",{className:"wsd-debug-mode-slot",children:(0,s.jsx)("nav",{"aria-label":"调试视图",className:"wsd-debug-mode-tabs",role:"tablist",children:d.map(e=>(0,s.jsx)("span",{"aria-selected":t===e.key,className:(0,rL.$)("wsd-debug-mode-tab",t===e.key&&"is-active"),onClick:()=>null==n?void 0:n(e.key),onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),null==n||n(e.key))},role:"tab",tabIndex:0,children:e.label},e.key))})}),(0,s.jsxs)("div",{className:"wsd-page-toolbar-actions",children:[(0,s.jsx)(ch,{}),r]})]})}function pQ(e){var t;let{children:r,runtime:i,showReloadButton:n=!0,toolbarView:a=i.activeView}=e,o="card"===i.activeView?i.devtoolsTarget:i.devtoolsTarget??(null==(t=i.conversationControlTarget)?void 0:t.target)??null,l=(0,iD.useMemo)(()=>({consoleTarget:"conversation"===i.activeView?i.conversationConsoleTarget:void 0,controlCommand:i.controlCommand,controlTarget:o,debugState:i.debugState,frontendUrl:i.chromeDevToolsFrontendUrl,getRuntimeFrame:i.getRuntimeFrame,onConsoleSnapshotChange:i.setRuntimeConsoleSnapshot,onControlResult:i.onControlResult,onDebugAction:i.handleDebugAction,onHighlightChange:i.setHighlightRect,onRuntimeSnapshotChange:i.setRuntimeDomSnapshot,runtimeSnapshotTarget:i.runtimeSnapshotTarget,resolveTargetAtPoint:"conversation"===i.activeView?i.resolveConversationInspectTarget:void 0,showPanelId:i.devToolsPanelId,showPanelRequestId:i.latestDevToolsPanelRequestId,target:o}),[i.activeView,o,i.chromeDevToolsFrontendUrl,i.controlCommand,i.conversationConsoleTarget,i.debugState,i.devToolsPanelId,i.devtoolsTarget,i.getRuntimeFrame,i.handleDebugAction,i.latestDevToolsPanelRequestId,i.onControlResult,i.resolveConversationInspectTarget,i.runtimeSnapshotTarget,i.setHighlightRect,i.setRuntimeConsoleSnapshot,i.setRuntimeDomSnapshot]);return(0,iD.useEffect)(()=>{var e;null==(e=i.onChromeDevToolsPanelChange)||e.call(i,l)},[l,i.onChromeDevToolsPanelChange]),(0,s.jsxs)("div",{className:(0,rL.$)("wsd-widget-preview-column","card"===i.activeView&&"is-card-debug"),children:[(0,s.jsx)(pY,{activeView:a,storageNamespace:i.fileSystemNamespace,hasTools:Object.keys(i.state.manifest.raw.tools??{}).length>0,onActiveViewChange:i.onActiveViewChange,onDeviceChange:i.setSelectedDeviceKey,selectedDeviceKey:i.selectedDeviceKey,children:n?(0,s.jsx)("button",{"aria-label":"刷新资源并重载卡片",className:"wsd-icon-button",disabled:!i.canReloadResources,onClick:i.reloadResources,title:"streaming"===i.simulatorState.streamStatus?"对话生成中暂不能刷新资源":"刷新资源并重载卡片",type:"button",children:(0,s.jsx)(ph,{"aria-hidden":"true"})}):null}),r]})}function p0(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return{type:"callback",callbackId:e.callbackId,params:{code:1,data:t}}}function p1(e){let{appIcon:t}=e,[r,i]=(0,iD.useState)(!1);return((0,iD.useEffect)(()=>{i(!1)},[t]),!t||r)?null:(0,s.jsx)("img",{alt:"",className:"wsd-simulator-permission-app-icon",onError:()=>i(!0),src:t})}function p2(e){let{onAllow:t,onReject:r,permission:i}=e;return(0,s.jsxs)("div",{className:"wsd-simulator-permission-layer",children:[(0,s.jsx)("div",{"aria-hidden":"true",className:"wsd-simulator-permission-backdrop"}),(0,s.jsxs)("dialog",{"aria-label":`${i.appName}权限申请`,"aria-modal":"true",className:"wsd-simulator-permission-dialog",open:!0,children:[(0,s.jsxs)("header",{className:"wsd-simulator-permission-brand",children:[(0,s.jsx)(p1,{appIcon:i.appIcon}),(0,s.jsx)("strong",{children:i.appName})]}),(0,s.jsxs)("section",{className:"wsd-simulator-permission-content",children:[(0,s.jsx)("h2",{children:i.title}),(0,s.jsx)("p",{children:i.description})]}),(0,s.jsxs)("footer",{className:"wsd-simulator-permission-actions",children:[(0,s.jsx)("button",{className:"is-primary",onClick:t,type:"button",children:"允许"}),(0,s.jsx)("button",{className:"is-secondary",onClick:r,type:"button",children:"拒绝"})]})]})]})}function p3(){let[e,t]=(0,iD.useState)(),[r,i]=(0,iD.useState)(),n=(0,iD.useRef)(null),a=(0,iD.useRef)(null),o=cl(e=>{var t;null==(t=a.current)||t.call(a,e)}),l=cl(e=>n.current||a.current?Promise.reject(Error("openSetting is already in progress")):e.signal.aborted?Promise.reject(Error("settings view was destroyed")):new Promise((t,r)=>{let n=()=>o(Error("settings view was destroyed"));a.current=s=>{e.signal.removeEventListener("abort",n),a.current=null,i(void 0),s?r(s):t()},e.signal.addEventListener("abort",n,{once:!0}),i(e)})),d=cl(e=>{var r;return(null==(r=e.signal)?void 0:r.aborted)?Promise.resolve(!1):n.current||a.current?Promise.reject(Error("Simulator permission prompt is already open")):new Promise(r=>{var i;let a=()=>s(!1),s=i=>{var o;n.current===s&&(n.current=null,null==(o=e.signal)||o.removeEventListener("abort",a),t(void 0),r(i))};n.current=s,null==(i=e.signal)||i.addEventListener("abort",a,{once:!0}),t(e)})}),u=cl(e=>{let t=n.current;t&&t(e)}),c=cl(()=>u(!0)),p=cl(()=>u(!1));return(0,iD.useEffect)(()=>()=>{var e;let t=n.current;null==t||t(!1),null==(e=a.current)||e.call(a,Error("settings presenter was destroyed"))},[]),{allowPermission:c,permission:e,rejectPermission:p,showPermission:d,showSettings:l,overlay:r?(0,s.jsx)(p4,{settings:r,onClose:()=>o()}):e?(0,s.jsx)(p2,{permission:e,onAllow:c,onReject:p}):null}}function p4(e){let{settings:t,onClose:r}=e,[i,n]=(0,iD.useState)(t.authSetting);return(0,s.jsxs)("div",{className:"wsd-simulator-permission-layer",children:[(0,s.jsx)("div",{"aria-hidden":"true",className:"wsd-simulator-permission-backdrop"}),(0,s.jsxs)("dialog",{"aria-label":`${t.appName}授权设置`,"aria-modal":"true",className:"wsd-simulator-permission-dialog wsd-simulator-permission-settings",open:!0,children:[(0,s.jsxs)("header",{className:"wsd-simulator-permission-brand",children:[(0,s.jsx)(p1,{appIcon:t.appIcon}),(0,s.jsx)("strong",{children:t.appName})]}),(0,s.jsxs)("section",{className:"wsd-simulator-permission-content",children:[(0,s.jsx)("h2",{children:"应用权限设置"}),(0,s.jsx)("p",{children:"仅显示已请求过的权限,修改立即生效。"})]}),(0,s.jsxs)("div",{className:"wsd-simulator-permission-scopes",children:[Object.entries(i).map(e=>{let[r,i]=e;return(0,s.jsxs)("label",{children:[(0,s.jsx)("span",{children:sH(r).title}),(0,s.jsx)("input",{"aria-label":r,checked:i,onChange:e=>{let i=e.currentTarget.checked;t.onChange(r,i),n(e=>({...e,[r]:i}))},type:"checkbox"})]},r)}),0===Object.keys(i).length?(0,s.jsx)("p",{children:"尚未请求任何应用权限"}):null]}),(0,s.jsx)("footer",{className:"wsd-simulator-permission-actions",children:(0,s.jsx)("button",{className:"is-primary",onClick:r,type:"button",children:"完成"})})]})]})}let p6=["agreeMain","agreeSub","reject"],p5=e=>nL.subscribe("network",e),p8={success:"M12 21.91a9.95 9.95 0 1 0 0-19.92 9.95 9.95 0 0 0 0 19.92Zm-1.09-5.2a.88.88 0 0 1-.86-.46L7.6 13.24a1.05 1.05 0 0 1-.24-.64c0-.22.08-.41.23-.56a.75.75 0 0 1 .55-.25c.14 0 .27.03.38.09.12.06.24.17.36.33l1.98 2.56 4.17-6.7c.18-.3.42-.45.7-.45.21 0 .4.07.57.2.17.14.25.32.25.55 0 .11-.02.22-.08.33-.05.11-.1.21-.16.31l-4.59 7.24a1.1 1.1 0 0 1-.82.46Z",error:"M4.43 21.18c-.55 0-1.03-.12-1.42-.35a2.4 2.4 0 0 1-.92-.96 2.75 2.75 0 0 1-.32-1.34c0-.47.12-.93.38-1.37L9.72 3.96c.25-.44.58-.77.99-1 .41-.22.84-.34 1.29-.34s.88.12 1.28.34c.41.23.74.56 1 1l7.57 13.2c.12.22.22.44.28.68.07.23.1.46.1.69 0 .5-.1.94-.32 1.34-.21.4-.52.72-.92.96-.4.23-.87.35-1.42.35H4.43Zm7.58-6.54c.5 0 .77-.26.77-.8l.15-5.31a.81.81 0 0 0-.27-.63.9.9 0 0 0-.66-.27c-.27 0-.5.09-.67.26a.8.8 0 0 0-.25.63l.13 5.32c.01.54.28.8.8.8Zm0 3.28c.29 0 .55-.1.76-.3.22-.21.33-.45.33-.75 0-.29-.11-.54-.33-.74a1.08 1.08 0 0 0-.76-.31c-.3 0-.56.1-.77.31-.22.2-.32.45-.32.74 0 .3.1.54.32.75.22.2.47.3.77.3Z",warn:"M12 21.91a9.95 9.95 0 1 0 0-19.92 9.95 9.95 0 0 0 0 19.92Zm0-8.14c-.52 0-.79-.27-.8-.8l-.13-5.33a.8.8 0 0 1 .25-.63c.18-.17.4-.26.67-.26.27 0 .49.09.67.27.18.17.27.38.26.63l-.15 5.32c0 .53-.26.8-.77.8Zm0 3.27c-.3 0-.56-.1-.77-.3a1 1 0 0 1-.32-.75c0-.29.1-.54.32-.74.21-.21.47-.31.77-.31.29 0 .55.1.76.31.22.2.33.45.33.74 0 .3-.11.54-.33.75-.21.2-.47.3-.76.3Z"},p9={error:"error",success:"success",warning:"warn"};function p7(e){return Array.isArray(e.itemList)?e.itemList:[]}function he(e){let t=new DOMParser().parseFromString(e,"text/html");return t.doctype||0!==t.documentElement.attributes.length||0!==t.head.attributes.length||0!==t.head.childNodes.length||0!==t.body.attributes.length?null:function e(t){let r=[];for(let i of Array.from(t)){let t=function(t){if(t.nodeType===Node.TEXT_NODE)return{type:"text",value:t.textContent??""};if(t.nodeType!==Node.ELEMENT_NODE)return null;let r=e(t.childNodes);if(!r)return null;if("a"===t.localName){if(1!==t.attributes.length||!t.hasAttribute("href"))return null;try{let e=new URL(t.getAttribute("href")??"");if("http:"!==e.protocol&&"https:"!==e.protocol)return null;return{children:r,href:e.href,type:"link"}}catch{return null}}return 0!==t.attributes.length||"p"!==t.localName&&"b"!==t.localName?null:{children:r,type:"p"===t.localName?"paragraph":"bold"}}(i);if(!t)return null;r.push(t)}return r}(t.body.childNodes)}function ht(e){let{content:t}=e,r=(0,iD.useMemo)(()=>he(t)??[],[t]);return(0,s.jsx)("div",{className:"wsd-simulator-bottom-sheet-content",children:function e(t){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"content";return t.map((t,i)=>{if("text"===t.type)return t.value;let n=`${r}-${i}`,a=e(t.children,n);return"paragraph"===t.type?(0,s.jsx)("p",{children:a},n):"bold"===t.type?(0,s.jsx)("b",{children:a},n):"link"===t.type?(0,s.jsx)("a",{href:t.href,rel:"noreferrer",target:"_blank",children:a},n):null})}(r)})}function hr(e){let{scanner:t}=e,r=(0,iD.useRef)(null),i=(0,iD.useRef)(null);return(0,iD.useEffect)(()=>{let e=i.current;e&&t.options.onVideoReady(e)},[t.options]),(0,s.jsxs)("div",{"aria-label":"扫码",className:"wsd-simulator-scan-code",children:[(0,s.jsx)("video",{autoPlay:!0,muted:!0,playsInline:!0,ref:i}),(0,s.jsx)("div",{className:"wsd-simulator-scan-code-message",children:t.message}),(0,s.jsxs)("div",{className:"wsd-simulator-scan-code-actions",children:[(0,s.jsx)("button",{onClick:t.options.onCancel,type:"button",children:"关闭"}),(0,s.jsx)("button",{onClick:t.options.onCapture,type:"button",children:"识别"}),t.options.allowImageUpload?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("button",{onClick:()=>{var e;return null==(e=r.current)?void 0:e.click()},type:"button",children:"相册"}),(0,s.jsx)("input",{accept:"image/*",hidden:!0,onChange:e=>{var r;let i=null==(r=e.currentTarget.files)?void 0:r[0];e.currentTarget.value="",i&&t.options.onFile(i)},ref:r,type:"file"})]}):null]})]})}function hi(e){let{children:t,className:r,exiting:i=!1,onDismiss:n}=e;return(0,s.jsxs)("div",{className:`wsd-simulator-overlay-interaction${r?` ${r}`:""}${i?" is-exiting":""}`,children:[(0,s.jsx)("div",{"aria-hidden":"true",className:"wsd-simulator-overlay-backdrop",onClick:n}),t]})}function hn(e){var t;let{interaction:r,onActionSheetSelect:i,onBottomSheetSelect:n,onDismiss:a,onModalResult:o}=e,[l,d]=(0,iD.useState)(""),u=cl(e=>d(e.currentTarget.value)),c=()=>a(r);if("modal"===r.kind){let{params:e}=r,t=!1!==e.showCancel;return(0,s.jsx)(hi,{className:"is-modal",exiting:r.exiting,onDismiss:c,children:(0,s.jsxs)("dialog",{"aria-label":e.title||"提示","aria-modal":"true",className:`wsd-simulator-modal${e.title?" has-title":""}`,onClick:e=>e.stopPropagation(),open:!0,children:[e.title?(0,s.jsx)("h2",{className:"wsd-simulator-modal-title",children:e.title}):null,(0,s.jsx)("p",{className:"wsd-simulator-modal-message",children:e.content||""}),e.editable?(0,s.jsx)("input",{"aria-label":e.placeholderText||"输入内容",className:"wsd-simulator-modal-input",onChange:u,placeholder:e.placeholderText,value:l}):null,(0,s.jsxs)("footer",{className:`wsd-simulator-modal-actions${t?"":" is-single"}`,children:[t?(0,s.jsx)("button",{className:"wsd-simulator-modal-button is-cancel",onClick:()=>o(r.id,"cancel"),style:e.cancelColor?{color:e.cancelColor}:void 0,type:"button",children:e.cancelText||"cancel"}):null,(0,s.jsx)("button",{className:"wsd-simulator-modal-button is-confirm",onClick:()=>o(r.id,"confirm",e.editable?l:void 0),style:e.confirmColor?{color:e.confirmColor}:void 0,type:"button",children:e.confirmText||"confirm"})]})]})})}if("actionSheet"===r.kind){let e=p7(r.params);return(0,s.jsx)(hi,{onDismiss:c,children:(0,s.jsxs)("dialog",{"aria-label":r.params.title||"操作菜单","aria-modal":"true",className:"wsd-simulator-overlay-sheet wsd-simulator-action-sheet",onClick:e=>e.stopPropagation(),open:!0,children:[r.params.title?(0,s.jsx)("h2",{children:r.params.title}):null,(0,s.jsx)("div",{className:"wsd-simulator-overlay-list",children:e.map((e,t)=>(0,s.jsx)("button",{className:"wsd-simulator-overlay-list-item",onClick:()=>i(r.id,t),style:r.params.itemColor?{color:r.params.itemColor}:void 0,type:"button",children:e},`${e}-${t}`))})]})})}let p=Array.isArray((t=r.params).buttons)?t.buttons:[];return(0,s.jsx)(hi,{onDismiss:c,children:(0,s.jsxs)("dialog",{"aria-label":r.params.title||"底部弹窗","aria-modal":"true",className:"wsd-simulator-overlay-sheet wsd-simulator-bottom-sheet",onClick:e=>e.stopPropagation(),open:!0,children:[r.params.title?(0,s.jsx)("h2",{children:r.params.title}):null,r.params.content?(0,s.jsx)(ht,{content:r.params.content}):null,(0,s.jsx)("div",{className:"wsd-simulator-overlay-actions",children:p.map(e=>(0,s.jsx)("button",{className:`wsd-simulator-overlay-button ${"reject"===e.role?"is-secondary":"is-primary"}`,onClick:()=>n(r.id,e.role),type:"button",children:e.text},e.role))})]})})}function ha(e){let{imagePreview:t,interaction:r,loading:i,onActionSheetSelect:n,onBottomSheetSelect:a,onDismiss:o,onImagePreviewClose:l,onImagePreviewNavigate:d,onModalResult:u,scanner:c,toast:p}=e,h=(0,iD.useSyncExternalStore)(p5,nL.getNetwork),m=null==t?void 0:t.urls[t.currentIndex],g=m&&nq(m)&&"none"===h.networkType;return(0,s.jsxs)("div",{className:"wsd-simulator-overlay-layer wsd-simulator-overlay-host",children:[i?(0,s.jsxs)("div",{"aria-live":"polite",className:"wsd-simulator-loading",children:[(0,s.jsx)("span",{className:"wsd-simulator-loading-spinner"}),(0,s.jsx)("span",{children:"Loading..."})]}):null,p?(0,s.jsxs)("output",{"aria-live":"polite",className:`wsd-simulator-toast is-${p.type}${p.exiting?" is-exiting":""}`,children:[function(e){if(e.customIcon)return(0,s.jsx)("img",{alt:"",className:"wsd-simulator-toast-icon",src:e.customIcon});let t=e.icon||p9[e.type];return t?(0,s.jsx)("svg",{"aria-hidden":"true",className:`wsd-simulator-toast-icon is-${t}`,focusable:"false",viewBox:"0 0 24 24",children:(0,s.jsx)("path",{d:p8[t]})}):null}(p),(0,s.jsx)("span",{className:"wsd-simulator-toast-message",children:p.message})]},p.id):null,c?(0,s.jsx)(hr,{scanner:c}):null,t?(0,s.jsxs)("div",{className:"wsd-simulator-image-preview",children:[g?(0,s.jsx)("p",{role:"status",children:"模拟网络已断开"}):(0,s.jsx)("img",{alt:`图片 ${t.currentIndex+1}`,onContextMenu:t.showmenu?void 0:e=>e.preventDefault(),referrerPolicy:t.referrerPolicy,src:m}),(0,s.jsx)("button",{"aria-label":"关闭图片预览",className:"wsd-simulator-image-preview-close",onClick:l,type:"button",children:"×"}),t.urls.length>1?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("button",{"aria-label":"上一张图片",className:"wsd-simulator-image-preview-navigation is-previous",onClick:()=>d(-1),type:"button",children:"‹"}),(0,s.jsx)("button",{"aria-label":"下一张图片",className:"wsd-simulator-image-preview-navigation is-next",onClick:()=>d(1),type:"button",children:"›"}),(0,s.jsxs)("span",{className:"wsd-simulator-image-preview-counter",children:[t.currentIndex+1," / ",t.urls.length]})]}):null]}):null,r?(0,s.jsx)(hn,{interaction:r,onActionSheetSelect:n,onBottomSheetSelect:a,onDismiss:o,onModalResult:u},r.id):null]})}function hs(){let e=function(){let[e,t]=(0,iD.useState)(null),r=(0,iD.useRef)(null),i=(0,iD.useRef)(0),n=cl((e,i)=>{let n=r.current;(null==n?void 0:n.id)===e&&(r.current=null,n.cleanup(),n.resolve(i),t(null))}),a=cl((e,a)=>{if(a.aborted||r.current)throw Error("The communication panel is unavailable");let s=++i.current,o=()=>n(s,"cancel");return{closed:new Promise(i=>{let n={id:s,params:e,resolve:i,cleanup:()=>a.removeEventListener("abort",o)};r.current=n,t(n),a.addEventListener("abort",o,{once:!0})})}});(0,iD.useEffect)(()=>()=>{var e,t;null==(e=r.current)||e.cleanup(),null==(t=r.current)||t.resolve("cancel"),r.current=null},[]);let o=(null==e?void 0:e.params.kind)==="sms";return{show:a,overlay:e?(0,s.jsx)("div",{className:"wsd-simulator-overlay-layer wsd-simulator-overlay-host",children:(0,s.jsxs)("div",{className:"wsd-simulator-overlay-interaction is-modal",children:[(0,s.jsx)("div",{"aria-hidden":"true",className:"wsd-simulator-overlay-backdrop",onClick:()=>n(e.id,"cancel")}),(0,s.jsxs)("dialog",{open:!0,"aria-modal":"true","aria-label":o?"模拟短信":"模拟拨号盘",className:"wsd-simulator-modal has-title",children:[(0,s.jsx)("h2",{className:"wsd-simulator-modal-title",children:o?"模拟短信":"模拟拨号盘"}),(0,s.jsx)("p",{className:"wsd-simulator-modal-message",children:o?"此面板只模拟短信编辑与结果,不会发送真实短信。":"此面板只模拟拨号界面,不会发起真实呼叫。"}),(0,s.jsxs)("div",{className:"wsd-simulator-communication-fields",children:[(0,s.jsxs)("label",{children:[o?"收件号码":"电话号码",(0,s.jsx)("input",{className:"wsd-simulator-modal-input",defaultValue:e.params.phoneNumber,type:"tel"})]}),o?(0,s.jsxs)("label",{children:["短信内容",(0,s.jsx)("textarea",{className:"wsd-simulator-modal-input",defaultValue:e.params.message,rows:4})]}):null,o?(0,s.jsxs)("p",{children:["本次模拟发送结果:",e.params.sendSucceeds?"成功":"失败"]}):null]},e.id),(0,s.jsxs)("footer",{className:`wsd-simulator-modal-actions${o?"":" is-single"}`,children:[(0,s.jsx)("button",{className:"wsd-simulator-modal-button is-cancel",type:"button",onClick:()=>n(e.id,"cancel"),children:o?"取消":"关闭"}),o?(0,s.jsx)("button",{className:"wsd-simulator-modal-button is-confirm",type:"button",onClick:()=>n(e.id,e.params.sendSucceeds?"sent":"failed"),children:"模拟发送"}):null]})]})]})}):null}}(),[t,r]=(0,iD.useState)(null),[i,n]=(0,iD.useState)(null),[a,o]=(0,iD.useState)(!1),[l,d]=(0,iD.useState)(null),u=(0,iD.useRef)(null),c=(0,iD.useRef)(),p=(0,iD.useRef)(0),h=(0,iD.useRef)(0),m=(0,iD.useRef)(0),g=(0,iD.useRef)(null),[f,v]=(0,iD.useState)(null),y=(0,iD.useRef)(null),b=(0,iD.useRef)(),w=(0,iD.useRef)(),_=cl((e,t,r)=>{let i=u.current;i&&i.id===e&&(c.current&&(clearTimeout(c.current),c.current=void 0),r?i.reject(r):i.resolve(t),u.current=null,n(null))}),S=cl(()=>{let e=u.current;e&&("modal"===e.kind?_(e.id,{action:"cancel"}):"bottomSheet"===e.kind?_(e.id,{action:"cancel",source:"unknown"}):_(e.id,void 0,Error("action sheet selection was cancelled")))}),x=cl((e,t,r,i)=>{c.current&&(clearTimeout(c.current),c.current=void 0),S();let a={exiting:!1,id:++p.current,kind:e,params:t,reject:i,resolve:r};u.current=a,n({exiting:a.exiting,id:a.id,kind:a.kind,params:a.params})}),I=cl(()=>{w.current&&(clearTimeout(w.current),w.current=void 0),b.current&&(clearTimeout(b.current),b.current=void 0)}),k=cl(e=>{var t;(null==(t=y.current)?void 0:t.id)===e&&(y.current=null,b.current=void 0,d(null))}),C=cl(()=>{let e=y.current;if(!e||e.exiting)return;w.current&&(clearTimeout(w.current),w.current=void 0);let t={...e,exiting:!0};y.current=t,d(t),b.current=setTimeout(()=>k(e.id),180)}),E=cl(e=>{I();let t="number"==typeof e.duration&&e.duration>=0?e.duration:2e3,r={customIcon:e.customIcon,exiting:!1,id:++m.current,icon:e.icon,message:"string"==typeof e.message?e.message:"",type:e.type||"default"};y.current=r,d(r),t>0&&(w.current=setTimeout(C,Math.max(0,t-180)))}),N=cl(e=>{var t;(null==(t=g.current)?void 0:t.id)===e&&(g.current=null,v(null))}),T=cl((e,t)=>{let r=g.current;if((null==r?void 0:r.id)!==e)return;let i={...r,message:t};g.current=i,v(i)}),A=cl(e=>{var t;null==(t=g.current)||t.options.onCancel();let r=++h.current,i={id:r,message:"正在打开摄像头...",options:e};return g.current=i,v(i),{close:()=>N(r),setMessage:e=>T(r,e)}}),M=(0,iD.useMemo)(()=>({previewImage:e=>{let t=Array.isArray(e.urls)?e.urls.filter(e=>"string"==typeof e):[];if(0===t.length)throw Error("urls must contain at least one image");r({currentIndex:function(e,t){if("number"==typeof e.current&&Number.isInteger(e.current))return Math.min(Math.max(e.current,0),t.length-1);if("string"==typeof e.current){let r=t.indexOf(e.current);return r<0?0:r}return 0}(e,t),referrerPolicy:["","no-referrer","no-referrer-when-downgrade","origin","origin-when-cross-origin","same-origin","strict-origin","strict-origin-when-cross-origin","unsafe-url"].find(t=>t===e.referrerPolicy),showmenu:!1!==e.showmenu,urls:t})}}),[]),R=cl(()=>r(null)),j=cl(e=>{r(t=>t?{...t,currentIndex:(t.currentIndex+e+t.urls.length)%t.urls.length}:null)}),P=cl((e,t)=>{let r;return(null==t?void 0:t.aborted)?Promise.resolve({action:"cancel"}):new Promise((i,n)=>{x("modal",e,i,n);let a=u.current.id;r=()=>_(a,{action:"cancel"}),null==t||t.addEventListener("abort",r,{once:!0})}).finally(()=>{r&&(null==t||t.removeEventListener("abort",r))})}),L=cl(e=>new Promise((t,r)=>{0===p7(e).length?r(Error("itemList must contain at least one item")):x("actionSheet",e,t,r)})),O=cl(e=>new Promise((t,r)=>{let i=function(e){if("string"!=typeof e.title||""===e.title.trim())return"title must not be empty";if("string"!=typeof e.content||""===e.content.trim())return"content must not be empty";if(!he(e.content))return"content contains unsupported HTML";let t=e.buttons;if(!Array.isArray(t)||t.length<1||t.length>3)return"buttons must contain between one and three buttons";let r=new Set;for(let e of t){if("object"!=typeof e||null===e)return"button must be an object";let t="role"in e?e.role:void 0,i=p6.find(e=>e===t);if(!i)return"button role is invalid";if(r.has(i))return"button roles must be unique";r.add(i);let n="text"in e?e.text:void 0;if("string"!=typeof n||""===n.trim())return"button text must not be empty"}return null}(e);i?r(Error(i)):x("bottomSheet",e,t,r)})),D=cl((e,t)=>{let r=u.current;r&&r.id===e&&"modal"===r.kind&&(r.resolve(t),u.current=null,n(t=>(null==t?void 0:t.id)===e?{...t,exiting:!0}:t),c.current=setTimeout(()=>{c.current=void 0,n(t=>(null==t?void 0:t.id)===e?null:t)},200))}),U=cl((e,t,r)=>{let i=u.current;i&&i.id===e&&D(e,{action:t,...void 0!==r?{content:r}:{}})}),q=cl((e,t)=>{let r=u.current;r&&r.id===e&&"actionSheet"===r.kind&&_(e,{tapIndex:t})}),$=cl((e,t)=>{let r=u.current;r&&r.id===e&&"bottomSheet"===r.kind&&_(e,{action:"buttonClick",role:t})}),B=cl(e=>{let t=u.current;if(t&&t.id===e.id)if("modal"===e.kind){if(!1===e.params.tapMaskToDismiss)return;D(e.id,{action:"mask"})}else if("bottomSheet"===e.kind){var r;if((null==(r=e.params.behavior)?void 0:r.dismissOnMaskTap)===!1)return;_(e.id,{action:"cancel",source:"mask"})}else _(e.id,void 0,Error("action sheet selection was cancelled"))});(0,iD.useEffect)(()=>()=>{var e;I(),y.current=null,c.current&&(clearTimeout(c.current),c.current=void 0);let t=u.current;t&&(t.reject(Error("simulator overlay was unmounted")),u.current=null),null==(e=g.current)||e.options.onCancel(),g.current=null},[]);let F=(0,iD.useMemo)(()=>({hideLoading:()=>o(!1),hideToast:C,showActionSheet:L,showBottomSheet:O,showLoading:()=>o(!0),showModal:P,showCommunication:e.show,showToast:E}),[C,L,O,P,E,e.show]);return{overlay:(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(ha,{imagePreview:t,interaction:i,loading:a,onActionSheetSelect:q,onBottomSheetSelect:$,onDismiss:B,onImagePreviewClose:R,onImagePreviewNavigate:j,onModalResult:U,scanner:f,toast:l}),e.overlay]}),imagePreviewController:M,presenter:F,scanCodePresenter:A}}function ho(e){let{debugContext:t,sources:r}=e;return{launch_dir:t.launchDir,manifest_url:e.manifestUrl,app_id:e.appId,app_name:e.appName,mcp_endpoint:t.mcpEndpoint,mcp_original_endpoint:r.mcp.original,mcp_proxy_endpoint:r.mcp.proxy,simulator_endpoint:e.simulatorEndpoint,simulator_manifest_original_url:r.manifest.original,simulator_manifest_proxy_url:r.manifest.proxy,simulator_manifest_url:t.simulatorManifestUrl,simulator_skills_directory_original_url:r.skill.original,simulator_skills_index_proxy_url:r.skill.proxy,simulator_skills_index_url:t.simulatorSkillsIndexUrl,web_url:t.webUrl}}function hl(e){return(null==e?void 0:e.sandboxPhoneNumberUploaded)===void 0?void 0:!1===e.sandboxCsrRequired?e.sandboxPhoneNumberUploaded:void 0!==e.sandboxCsrUploaded?e.sandboxCsrUploaded&&e.sandboxPhoneNumberUploaded:void 0}function hd(e){return(null==e?void 0:e.raw)??{}}function hu(e,t){for(let r=e.length-1;r>=0;r-=1){let i=e[r].payload;if((null==i?void 0:i.event)===t)return i}}function hc(e,t,r){return!e||function(e,t){if(!e)return!1;try{return new URL(e,"http://localhost").pathname===t}catch{return!1}}(e,r)&&!t?"":e}function hp(e,t,r){let i=new Set(["missing","fetch_started","load_started","fetch_failed","load_failed","fetch_succeeded","loaded","empty"].map(e=>`simulator_${t}_${e}`)),n=e.map(e=>e.payload).findLast(e=>i.has(e.event)),a=(null==n?void 0:n.event)||"",s=function(){for(var e=arguments.length,r=Array(e),i=0;i<e;i++)r[i]=arguments[i];return r.some(e=>a===`simulator_${t}_${e}`)};if(n&&s("fetch_succeeded","loaded")){let e="skill"===t&&Array.isArray(n.skill_paths)?n.skill_paths.filter(Boolean).map(e=>e.startsWith("./")?e:`./${e}`):[];return{bytes:n.bytes??n.skill_length??n.skills_length,detail:n.url||r,details:e.length>0?e:void 0,label:"已加载",tone:"success"}}return s("empty")?{detail:r||"未配置",label:"空内容",tone:"muted"}:s("missing")||!r?{detail:r,label:"未配置",tone:"muted"}:n&&s("fetch_failed","load_failed")?{detail:n.error||n.url||r,label:"加载失败",tone:"error"}:n&&s("fetch_started","load_started")?{detail:n.url||r,label:"加载中",tone:"pending"}:{detail:r,label:"检查中",tone:"pending"}}function hh(e){return"string"==typeof e?e.trim():e.name||e.id||""}function hm(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return t.map((e,t)=>0===t?e.replace(/\/+$/g,""):e.replace(/^\/+|\/+$/g,"")).filter(Boolean).join("/")}function hg(e,t,r,i){if(!e)return"";if(i.startsWith(`${t}/`)){let e=i.replace(/\.web\.bundle$/g,"").replace(/\.bundle$/g,"").replace(/\.template\.js$/g,"").replace(/\.js$/g,"");return hm("src",/\.(tsx|ts|jsx|js)$/.test(e)?e:`${e}.tsx`)}return!r||r.startsWith("__")?"":hm("src",t,r,"index.tsx")}function hf(e){var t,r,i,n,a;let s,o,l,d,u,c,p,h,m,g,f,{context:v,events:y,manifest:b,pages:w=[],widgets:_}=e,S=(null==v?void 0:v.launchDir)||"",x=(null==v?void 0:v.mcpEndpoint)||(null==v?void 0:v.mcpProxyEndpoint)||"",I=(null==v?void 0:v.mcpOriginalEndpoint)||(null==(o=hd(b).mcp_server)?void 0:o.end_point)||(null==o?void 0:o.endpoint)||(null==o?void 0:o.url)||(null==o?void 0:o.mcp_endpoint)||"",k=(null==v?void 0:v.mcpProxyEndpoint)||(null==v?void 0:v.mcpEndpoint)||"",C=(null==v?void 0:v.simulatorManifestOriginalUrl)||"",E=(null==v?void 0:v.simulatorManifestProxyUrl)||(null==v?void 0:v.simulatorManifestUrl)||"",N=(null==v?void 0:v.simulatorManifestRelativePath)||"",T=(null==v?void 0:v.simulatorBusinessTemplatesOriginalUrl)||"",A=(null==v?void 0:v.simulatorBusinessTemplatesRelativePath)||"",M=(null==v?void 0:v.simulatorManifestUrl)||(null==v?void 0:v.simulatorManifestProxyUrl)||"",R=(null==v?void 0:v.simulatorSkillsDirectoryOriginalUrl)||(null==v?void 0:v.simulatorSkillsIndexOriginalUrl)||"",j=(null==v?void 0:v.simulatorSkillsIndexProxyUrl)||(null==v?void 0:v.simulatorSkillsIndexUrl)||"",P=(null==v?void 0:v.simulatorSkillsDirectoryRelativePath)||"",L=(null==v?void 0:v.simulatorSkillsIndexUrl)||(null==v?void 0:v.simulatorSkillsIndexProxyUrl)||"",O=hc(M,C,"/__simulator_manifest/manifest.yaml"),D=hc(L,R,"/__simulator_skills/index.json"),U=hc(x,(null==v?void 0:v.mcpOriginalEndpoint)||"","/__mcp_proxy"),q=function(e){let t=new Set;for(let r of e){let e=r.payload;for(let r of e.tools??[]){let e=hh(r);e&&t.add(e)}for(let r of e.mcp_servers??[])for(let e of r.tools??[]){let r=hh(e);r&&t.add(r)}}return[...t]}(y),$=function(e){let t=new Map,r=function(e,r){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",n="string"==typeof r?r:r.widget_id||r.widgetId||r.widget,a="string"==typeof r?i:r.entity_type||r.entityType||r.entity||i;e&&n&&t.set(`${e}:${n}:${a}`,{entityType:a,toolName:e,widgetId:n})},i=hd(e);for(let[e,t]of Object.entries(i.tool_card_binding??{}))r(e,t);for(let[e,t]of Object.entries(i.entities??{})){let i=t.entity_type||t.entityType||e;for(let[e,n]of Object.entries(t.tool_card_binding??{}))r(e,n,i)}return[...t.values()]}(b),B={manifest:hp(y,"manifest",O),mcp:(l=hu(y,"local_mcp_missing"),d=hu(y,"local_mcp_tools_load_started"),u=hu(y,"local_mcp_tools_load_failed"),c=hu(y,"local_mcp_tools_loaded"),p=hu(y,"client_tools_resolved"),h=hu(y,"client_tools_empty"),c?{detail:c.mcp_endpoint||U,label:"已连接",tone:"success"}:u?{detail:u.error||u.mcp_endpoint||U,label:"连接失败",tone:"error"}:p?{detail:`${p.tool_count??0} tools`,label:"客户端工具",tone:"success"}:h?{detail:"manifest.yaml 未声明 tools",label:"无客户端工具",tone:"muted"}:l||!U?{detail:U,label:"未配置",tone:"muted"}:d?{detail:d.mcp_endpoint||U,label:"连接中",tone:"pending"}:{detail:U,label:"检查中",tone:"pending"}),skill:hp(y,"skill",D)},F=!!O||"success"===B.manifest.tone,z=!!D||"success"===B.skill.tone,W=!!U||"success"===B.mcp.tone,H={businessTemplates:T?{detail:A||T,label:"已加载",tone:"success"}:{detail:"",label:"未配置",tone:"muted"},manifest:{...B.manifest,detail:N||B.manifest.detail},mcp:B.mcp,skill:{...B.skill,detail:P||B.skill.detail}};return{appId:(m=hd(b),(null==b?void 0:b.appId)||m.appId||m.app_key||(null==(t=m.applet)?void 0:t.appletId)||""),sandboxAppId:null==v?void 0:v.sandboxAppId,appName:(g=hd(b),(null==b?void 0:b.name)||g.name||g.app_name||(null==(r=g.applet)?void 0:r.name)||""),context:{launchDir:function(e,t){if(!t||!e.startsWith(t))return e;let r=e.slice(t.length);return""===r||/^[\\/]/.test(r)?`~${r.replaceAll("\\","/")}`:e}(S,(null==v?void 0:v.homeDir)||"")},mcpTools:q,pages:(i=b,f=(null==(s=function(e,t){if(t)return e.find(e=>t.startsWith("/")?e.path===t:e.id===t)}(n=w,null==(a=hd(i).applet)?void 0:a.appletEntry)??n.find(e=>"index"===e.id||"/pages/index"===e.path||"/pages/index/index"===e.path)??n[0])?void 0:s.path)||"",w.map(e=>({entry:hg(S,"pages",e.path.slice(1).replace(/^pages\//,"").replace(/\/index$/,""),e.entry||""),isHome:!!f&&e.path===f,name:e.name||e.title||"",pageId:e.id,path:e.path}))),resources:H,sources:{manifest:{original:F?C:"",proxy:F?E||M:""},mcp:{original:W?I:"",proxy:W?k:""},skill:{original:z?R:"",proxy:z?j||L:""}},widgets:function(e,t,r){let i=new Map;for(let e of t){let t=i.get(e.widgetId)??[];t.push(e.toolName),i.set(e.widgetId,t)}return e.filter(nY).map(e=>({boundTools:i.get(e.widgetId)??[],entry:hg(r,"widgets",e.widgetId,e.entry||""),name:e.name||"",widgetId:e.widgetId}))}(_,$,S)}}function hv(e,t,r){return!!(e&&t&&t!==r&&e.sourceTarget===t)}function hy(e,t){return{pages:e.pages.map(e=>{let{isHome:t,name:r,pageId:i,path:n}=e;return{isHome:t,name:r,pageId:i,path:n}}),widgets:e.widgets.map(e=>{let{name:t,widgetId:r}=e;return{name:t,widgetId:r}}),currentTarget:t}}function hb(e,t,r){let i=0,n=!1,a=()=>{n=!0},s=e=>{if(i>=5e3)return n=!0,null;i+=1;let t=e.children.map(s).filter(e=>null!==e);return{uid:e.id,type:e.type,name:"text"===e.type?"#text":uF(e),attributes:"element"===e.type?u$(e).map(e=>{var t;return{name:e.name,value:(t=e.value,t.length<=500?t:(a(),`${t.slice(0,499)}…`))}}):[],children:t,accessibility:e.accessibility,text:e.textContent}};return{root:e?s(e):null,selectedUid:t,nodeCount:i,truncated:n,sourceTarget:r,updatedAtMs:Date.now()}}let hw={message:"未上传",tone:"muted"},h_={message:"已上传",tone:"success"},hS=hw,hx=new Set;function hI(e){return hx.add(e),()=>hx.delete(e)}function hk(){return hS}function hC(e){for(let t of(hS=e,hx))t()}function hE(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:hw.message;hC({message:e,tone:"muted",updatedAtMs:Date.now()})}function hN(e){let t=(0,iD.useSyncExternalStore)(hI,hk,hk);return(0,iD.useEffect)(()=>{void 0!==e&&hC(e?h_:hw)},[e]),t}let hT={message:"可用",tone:"success"},hA={message:"不可用",tone:"error"},hM=hT,hR=new Set;function hj(e){return hR.add(e),()=>hR.delete(e)}function hP(){return hM}function hL(e){for(let t of(hM=e,hR))t()}function hO(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0],t=(0,iD.useSyncExternalStore)(hj,hP,hP);return(0,iD.useEffect)(()=>{hL(e?hT:hA)},[e]),t}function hD(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("open-location-settings"===e.kind)return na("location"),!0;if("clear-sandbox-bridge-logs"===e.kind){if(!t.onClearLogs){var r;return null==(r=t.onMessage)||r.call(t,"服务端日志接口不可用",!0),!0}return t.onClearLogs().then(()=>{var e;return null==(e=t.onMessage)?void 0:e.call(t,"服务端交互日志已清空")}).catch(e=>{var r;return null==(r=t.onMessage)?void 0:r.call(t,e.message,!0)}),!0}return"recreate-sandbox-session"===e.kind?(hL({message:"正在重建",tone:"pending",updatedAtMs:Date.now()}),lQ({csrPem:e.csrPem,phoneNum:e.phoneNum}).then(r=>{var i,n,a,s,o;let l=(null==(i=r.data)?void 0:i.business_info_uploaded)===!0;l?hC({message:"已上传",tone:"success",updatedAtMs:Date.now()}):hE(),hL({message:"已重建",tone:"success",updatedAtMs:Date.now()}),l?null==(s=t.onUpdated)||s.call(t):null==(o=t.onRecreated)||o.call(t),null==(a=t.onMessage)||a.call(t,`调试会话已重建${l?`,${e.csrPem.trim()?"手机号和证书":"手机号"}已自动上传`:""}:${(null==(n=r.data)?void 0:n.sandbox_session_id)??""}`)}).catch(e=>{var r,i;let n=`重建调试会话失败:${e.message}`;hE(),hL({errorMessage:n,message:"重建失败",tone:"error",updatedAtMs:Date.now()}),null==(r=t.onRecreated)||r.call(t),null==(i=t.onMessage)||i.call(t,n,!0)}),!0):"update-sandbox-business-info"===e.kind&&(hC({message:"正在上传...",tone:"pending",updatedAtMs:Date.now()}),lX({csrPem:e.csrPem,phoneNum:e.phoneNum}).then(()=>{var e,r;hC({message:"上传成功",tone:"success",updatedAtMs:Date.now()}),null==(e=t.onUpdated)||e.call(t),null==(r=t.onMessage)||r.call(t,"上传成功")}).catch(e=>{var r;let i=e&&"object"==typeof e&&"logId"in e&&"string"==typeof e.logId?e.logId:"";hC({errorMessage:e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message?e.message:"",message:"上传失败",tone:"error",updatedAtMs:Date.now()}),console.error("Sandbox business info upload failed",e,{logId:i}),null==(r=t.onMessage)||r.call(t,"上传失败",!0)}),!0)}function hU(e){let[t,r]=(0,iD.useState)(),i=(0,iD.useRef)(),n=(0,iD.useRef)(),a=cl((e,t)=>{if(n.current===e.commandId)return!1;n.current=e.commandId;let a={previousTarget:t,command:e};return i.current=a,r(a),!0}),s=cl((t,n)=>{var a;(null==(a=i.current)?void 0:a.command.commandId)===t&&(i.current=void 0,r(void 0),null==e||e(t,n))});return{accept:a,pending:t,pendingRef:i,report:s}}let hq="u"<typeof window?iD.useEffect:iD.useLayoutEffect;function h$(e,t){let[r,i]=(0,iD.useState)(ss),[n,a]=(0,iD.useState)("fit"),s=(0,iD.useRef)(),o=(0,iD.useMemo)(()=>su(r),[r]),l=sl.find(e=>e.key===n)??sl.find(e=>"fit"===e.key)??sl[0],d="fit"===l.key,{fitScale:u,setRuntimeShellRef:c}=function(e){let{deviceHeight:t,deviceWidth:r,enabled:i}=e,[n,a]=(0,iD.useState)(.88),s=(0,iD.useRef)(null),o=(0,iD.useRef)(null),l=(0,iD.useCallback)(()=>{let e=s.current;if(!e)return;let i=getComputedStyle(e),n=Number.parseFloat(i.paddingLeft)+Number.parseFloat(i.paddingRight),o=Number.parseFloat(i.paddingTop)+Number.parseFloat(i.paddingBottom),l=Math.floor(1e3*Math.max(.1,Math.min(1,(e.clientWidth-n-12)/r,(e.clientHeight-o-12)/t)))/1e3;a(e=>Math.abs(e-l)>.001?l:e)},[t,r]),d=(0,iD.useCallback)(e=>{var t;if(null==(t=o.current)||t.disconnect(),o.current=null,s.current=e,!e||!i)return;let r=new ResizeObserver(l);r.observe(e),o.current=r,l()},[i,l]);return hq(()=>{i&&l()},[i,l]),hq(()=>()=>{var e;null==(e=o.current)||e.disconnect()},[]),{fitScale:n,setRuntimeShellRef:d}}({deviceHeight:o.height,deviceWidth:o.width,enabled:d}),p=d?u:l.scale,h=d?"fit":"fixed",m={"--wsd-runtime-width":`${o.width}px`,"--wsd-runtime-height":`${o.height}px`,"--wsd-runtime-layout-width":`${o.width*p}px`,"--wsd-runtime-layout-height":`${o.height*p}px`,"--wsd-runtime-radius":`${o.radius}px`,"--wsd-runtime-home-indicator-display":o.homeIndicator?"block":"none","--wsd-runtime-safe-area-bottom":`${o.safeArea.bottom}px`,"--wsd-runtime-scale":p};return(0,iD.useEffect)(()=>{if((null==e?void 0:e.type)!=="set_viewport"||s.current===e.commandId)return;let n=`custom-${e.width}x${e.height}`;r!==n?i(n):(s.current=e.commandId,null==t||t(e.commandId,{ok:!0,result:{width:e.width,height:e.height}}))},[e,t,r]),{runtimeScaleMode:h,runtimeStyle:m,selectedDevice:o,selectedDeviceKey:r,selectedScaleKey:n,setRuntimeShellRef:c,setSelectedDeviceKey:i,setSelectedScaleKey:a}}function hB(e,t,r){let i=!(arguments.length>3)||void 0===arguments[3]||arguments[3];(0,iD.useEffect)(()=>{if(!e||!i)return;let n=setTimeout(()=>e.publishSnapshot(t,r),500);return()=>clearTimeout(n)},[e,i,t,r])}let hF={appEntries:[],entries:[],updatedAtMs:0};function hz(e,t){var r;return!t||e.traceId===t||(null==(r=e.trace)?void 0:r.trace_id)===t}function hW(e,t){var r;let{activeView:i,chromeDevToolsFrontendUrl:n,controlCommand:a,controlClientId:s,debugContext:o,onChromeDevToolsPanelChange:l,onActiveViewChange:d,onControlResult:u,onMessage:c,onNavigateToPage:p,onWidgetNavigateBack:h,onWidgetExitApp:m,apiEnvironment:g,showDebugTrace:f,connection:y,webSdkDebugger:b}=e,w=cg(b),x=(0,iD.useMemo)(()=>w.widgets.filter(nY),[w.widgets]),I=(0,iD.useRef)(null),k=(0,iD.useRef)(null),C=(0,iD.useRef)(null),E=(0,iD.useRef)(null),N=(0,iD.useRef)(null);!N.current&&"u">typeof document&&(N.current=document.createElement("div"));let[T,A]=(0,iD.useState)(0),M=cl(()=>k.current),[R,j]=(0,iD.useState)(null),[P,L]=(0,iD.useState)(!1),[O,D]=(0,iD.useState)(0),[U,q]=(0,iD.useState)(!1),[$,B]=(0,iD.useState)([]),[F,z]=(0,iD.useState)(hF),[W,H]=(0,iD.useState)(null),[V,G]=(0,iD.useState)(null),[J,K]=(0,iD.useState)(null),[Z,X]=(0,iD.useState)(),[Y,Q]=(0,iD.useState)(0),[ee,et]=(0,iD.useState)(0),er=cE(),ei=hs(),en=p3(),ea=(null==o?void 0:o.sandboxSessionAvailable)!==!1,es=hl(o),[eo,el]=(0,iD.useState)(!0!==es),ed=hN(es),eu=hO(ea),{bridgeLogs:ec,clearBridgeLogs:ep}=cJ(),eh=(0,iD.useRef)(null),em=(0,iD.useMemo)(()=>E.current,[T]),{accept:eg,pending:ef,pendingRef:ev,report:ey}=hU(u),eb=(0,iD.useRef)(),ew=(0,iD.useRef)(new Map),e_=(0,iD.useRef)(new Map),eS=(0,iD.useRef)(0),{runtimeScaleMode:ex,runtimeStyle:eI,selectedDevice:ek,selectedDeviceKey:eC,setRuntimeShellRef:eE,setSelectedDeviceKey:eN}=h$(a,u),eT=(0,iD.useRef)(eC),eA=(null==(r=w.widgetSelection)?void 0:r.item.widgetId)??"",eM=(0,iD.useRef)(eA),eR=w.simulator,ej=(0,iD.useRef)(eR.toolCalls),eP=!!w.widgetSelection&&"streaming"!==eR.streamStatus&&!U,eL=(0,iD.useMemo)(()=>({...sd,device:ek,density:ek.density,label:ek.label,width:Math.max(1,ek.width-38)}),[ek]);(0,iD.useEffect)(()=>{ej.current=eR.toolCalls},[eR.toolCalls]);let eO=cl(e=>{let t=function(e,t){var r;if(!rP(e))return{};let i=e.source_tool_call_id,n=i?t.find(e=>e.toolCallId===i):void 0;if(!n)return e;let a=e.trace??{};return{...e,request_id:e.request_id||n.requestId,trace_id:e.trace_id||a.trace_id||(null==(r=n.trace)?void 0:r.trace_id)}}(e,ej.current),r=++eS.current,i={display:ah(t),id:`trace-${r}`,order:r,payload:t,timestamp:Date.now()};B(e=>[...e,i].slice(-200))}),eD=cl(()=>{B([])}),eU=(0,iD.useMemo)(()=>[...eR.traceEvents.map((e,t)=>({event:e,sortOrder:e.order??t})),...$.map((e,t)=>({event:e,sortOrder:e.order??eR.traceEvents.length+t}))].sort((e,t)=>e.event.timestamp-t.event.timestamp||e.sortOrder-t.sortOrder||e.event.id.localeCompare(t.event.id)).map(e=>{let{event:t}=e;return t}),[$,eR.traceEvents]),eq=(0,iD.useMemo)(()=>({...o,manifestUrl:w.manifestUrl,simulatorEndpoint:eR.endpoint}),[o,eR.endpoint,w.manifestUrl]),e$=(0,iD.useMemo)(()=>hf({context:eq,events:eU,manifest:w.manifest,pages:w.pages,widgets:w.widgets}),[eU,eq,w.manifest,w.pages,w.widgets]),eB=e$.appId,eF=e$.appName,ez=(0,iD.useMemo)(()=>({type:"widget",appId:eB,appName:eF,widgetId:eA,viewport:{key:ek.key,label:ek.label,width:Math.max(1,ek.width-38),height:ek.height,density:ek.density}}),[eB,eF,ek,eA]),eW=(0,iD.useMemo)(()=>hy(e$,"card"===t&&w.widgetSelection?ez:null==J?void 0:J.targetInfo),[t,J,ez,e$.pages,e$.widgets,w.widgetSelection]),eH=!!(ef&&hv(W,em,ef.previousTarget)&&"card"===t&&eA===ef.command.widgetId),eV=(0,iD.useMemo)(()=>{let e="card"===t?em:null==J?void 0:J.target,r="card"===t?ez:null==J?void 0:J.targetInfo;return e&&r&&(null==W?void 0:W.sourceTarget)===e?{target:r,root:W.root,nodeCount:W.nodeCount,selectedUid:W.selectedUid,truncated:W.truncated,updatedAtMs:W.updatedAtMs}:void 0},[t,J,ez,W,em]),eG=(0,iD.useMemo)(()=>({exported_at:new Date().toISOString(),client_id:s,command_id:eH?null==ef?void 0:ef.command.commandId:void 0,context:{...ho({appId:eB,appName:e$.appName,debugContext:eq,manifestUrl:w.manifestUrl,simulatorEndpoint:eR.endpoint,sources:e$.sources}),widget_id:eA},render_targets:eW,runtime_snapshot:eV,simulator:{stream_status:eR.streamStatus,active_request_id:eR.activeRequestId,active_reply_message_id:eR.activeReplyMessageId,error:eR.error,answer_finish:eR.answerFinish,messages:eR.messages,tool_calls:eR.toolCalls,trace_events:eR.traceEvents},runtime_console:{app:{entries:F.appEntries,updated_at_ms:F.updatedAtMs},widget:{entries:F.entries,updated_at_ms:F.updatedAtMs}},widget_runtime_trace_events:$}),[$,e$.sources.manifest.original,e$.sources.manifest.proxy,e$.sources.mcp.original,e$.sources.mcp.proxy,e$.sources.skill.original,e$.sources.skill.proxy,eq.launchDir,eq.mcpEndpoint,eq.simulatorManifestUrl,eq.simulatorSkillsIndexUrl,eq.webUrl,F,eA,eR,eB,s,eH,null==ef?void 0:ef.command.commandId,eW,w.manifest.name,w.manifestUrl,eV]),eJ=cl(e=>{b.approveSimulatorToolCall(e).catch(e=>{null==c||c(e.message,!0)})}),eK=cl(e=>{b.rejectSimulatorToolCall(e).catch(e=>{null==c||c(e.message,!0)})}),eZ=cl(e=>{"clear-trace-filter"===e.kind?X(void 0):hD(e,{onClearLogs:ep,onMessage:c,onRecreated:()=>el(!0),onUpdated:()=>el(!1)})||("approve-tool-call"===e.kind||"reject-tool-call"===e.kind)&&("approve-tool-call"===e.kind?eJ:eK)(e.toolCallId)}),eX=cl(e=>{X(t=>t===e?void 0:e)}),eY=cl(()=>{Q(e=>Math.max(e,ee)+1)});(0,iD.useEffect)(()=>{"success"===ed.tone&&el(!1)},[ed.tone]),(0,iD.useEffect)(()=>{void 0!==es&&el(!es)},[es]);let eQ=cl(()=>{et(e=>Math.max(e,Y)+1)}),e0=cl(()=>{na("location")}),e1=cl(e=>{e.stopPropagation(),el(!1)}),e2=Math.max(Y,ee);(0,iD.useEffect)(()=>{Z&&!eR.messages.some(e=>hz(e,Z))&&X(void 0)},[Z,eR.messages]);let e3=(0,iD.useMemo)(()=>f?eU:eU.filter(e=>{var t;return!(null==(t=e.display)?void 0:t.debugOnly)}),[eU,f]),e4="conversation"===t?V:em,e6=cl(e=>{G(e)}),e5=()=>{for(let e of eR.messages.slice().reverse())for(let t of e.blocks.slice().reverse()){if("card"!==t.type)continue;let r=e_.current.get(c7(e,t));if(null==r?void 0:r.target.isConnected)return r}let e=Array.from(e_.current.values()).reverse();return e.find(e=>e.target.isConnected)??e[0]??null},e8=cl((e,t,r)=>{if(t){let i=eR.messages.slice().reverse().flatMap(t=>{let r=t.blocks.find(r=>"card"===r.type&&c7(t,r)===e);return(null==r?void 0:r.type)==="card"?[{card:r.card,message:t}]:[]})[0],n={target:t,targetInfo:{...ez,viewport:{...ez.viewport,width:r??ez.viewport.width},appId:null==i?void 0:i.card.app_id,widgetId:null==i?void 0:i.card.widget_id,cardId:null==i?void 0:i.card.card_id,requestId:null==i?void 0:i.message.requestId}};e_.current.set(e,n),K(e5());return}let i=e_.current.get(e);e_.current.delete(e),K(e=>i&&(null==e?void 0:e.target)===i.target?e5():e)}),e9=cl((e,t)=>{var r;return(null==(r=Array.from(e_.current.values()).reverse().find(r=>{let i,{target:n}=r;return n.isConnected&&(i=n.getBoundingClientRect()).width>0&&i.height>0&&e>=i.left&&e<=i.right&&t>=i.top&&t<=i.bottom}))?void 0:r.target)??null}),e7=(0,iD.useMemo)(()=>iI(e3,{debug:f,messages:eR.messages,traceId:Z}),[Z,f,eR.messages,e3]),te=(0,iD.useMemo)(()=>Z?eR.toolCalls.filter(e=>hz(e,Z)):eR.toolCalls,[Z,eR.toolCalls]),tt=(0,iD.useMemo)(()=>ix(eG,{debug:f,traceId:Z}),[Z,f,eG]),tr=(0,iD.useMemo)(()=>iw(tt),[tt]),ti=(0,iD.useMemo)(()=>({debugData:e$,events:e7,logSnapshot:tt,logSnapshotText:tr,sandbox:{available:ea,csrRequired:(null==o?void 0:o.sandboxCsrRequired)!==!1,input:{csrPem:(null==o?void 0:o.sandboxCsrPem)??"",phoneNum:(null==o?void 0:o.sandboxPhoneNum)??""},logs:ec,businessInfoStatus:ed,sessionStatus:eu},showDebugTrace:f,traceFilterId:Z??"",traceSurface:"conversation",toolCalls:te,updatedAtMs:Date.now()}),[e$,te,e7,tt,tr,ec,ea,ed,eu,null==o?void 0:o.sandboxCsrRequired,Z,f]);hB(y,eG,W,!i||i===t),(0,iD.useEffect)(()=>{if((null==a?void 0:a.type)==="render_widget"&&eg(a,em))try{b.selectWidget(a.widgetId)}catch(e){ey(a.commandId,{ok:!1,error:{code:"TARGET_NOT_FOUND",message:e.message}})}},[eg,a,ey,b,em]),(0,iD.useEffect)(()=>{ef&&eH&&ey(ef.command.commandId,{ok:!0,target:ez,snapshot:iS(eG)})},[ez,eH,ef,ey,eG]);let tn=(0,iD.useMemo)(()=>{let e=(e,t,r)=>{var i;if("AppletBridgeModule"===r&&("postMessage"===e||"postMessageSync"===e)&&rP(i=t)&&"call"===i.type&&"string"==typeof i.name&&"number"==typeof i.callbackId){if("mind.getAgentTraceSwitch"===t.name)return p0(t,{value:!0});if("mind.reportAgentTraceEvent"===t.name)return eO(t.params??{}),p0(t)}};return(t,r,i,n)=>{if("AppletBridgeModule"===i&&"postMessage"===t&&v(r)&&"doubao.navigateBack"===r.name)return Promise.resolve().then(async()=>await (null==h?void 0:h(r.params??{}))?_(r,{}):S(r,"No host Page is available to navigate back",102)).catch(e=>S(r,e instanceof Error?e.message:String(e),102));if("AppletBridgeModule"===i&&"postMessage"===t&&v(r)&&["doubao.navigateTo","doubao.redirectTo","doubao.reLaunch"].includes(r.name)){let e=r.params;if(!rP(e)||"string"!=typeof e.url||!e.url.trim())return S(r,"invalid url",104);let t=e.url;try{tO({url:t},w.manifest)}catch(e){return S(r,e instanceof Error?e.message:String(e),104)}if(!p)return S(r,"No host page presenter is available",102);let i="doubao.navigateTo"===r.name?"navigate":"doubao.redirectTo"===r.name?"redirect":"relaunch";return Promise.resolve().then(()=>p({url:t,routeMode:i})).then(e=>!1===e?S(r,"Opening a Page from the chat card failed",102):(null==c||c(`卡片 ${r.name.slice(7)}: ${t}`),_(r,{})),e=>S(r,e instanceof Error?e.message:String(e),102))}return e(t,r,i,n)}},[eO,c,p,h,w.manifest]),ta=(0,iD.useCallback)(e=>dI({appId:eB,appIcon:w.manifest.iconSrc,appName:eF,exitAppFromWidget:m,declaredScopes:Object.keys(w.manifest.raw.permissions??{}),baseAPIRegistry:null==g?void 0:g.apiRegistry,imagePreviewController:ei.imagePreviewController,onCustomLoginNavigate:e=>null==p?void 0:p({url:e}),openPageFromWidget:async e=>{let{url:t}=e;if(!1===(!!p&&await p({url:t,routeMode:"relaunch"})))throw Error("Opening a Page from the chat card failed")},sendFollowUpMessage:e=>{let{content:t}=e;return b.sendSimulatorFollowUpMessage(t)},multiMediaBroadcastContainer:e,scanCodePresenter:ei.scanCodePresenter,showSandboxCashier:er.showCashier,uiPresenter:ei.presenter,showSimulatorPermission:en.showPermission,showSimulatorPermissionSettings:en.showSettings,vibrationContainer:C.current}),[g,eB,eF,p,m,er.showCashier,ei.imagePreviewController,ei.scanCodePresenter,ei.presenter,en.showPermission,en.showSettings,w.manifest.iconSrc,w.manifest.raw.permissions,b]),ts=(0,iD.useMemo)(()=>ta(),[ta]),to=cl(e=>{E.current!==e&&(E.current=e,A(e=>e+1)),j(null)});(0,iD.useEffect)(()=>{let e=I.current;if(!e)return;let t=ta(e),r=new cs({container:e,fileSystemNamespace:null==o?void 0:o.fileSystemNamespace,nativeModulesCallHandler:tn,webSdkDebugger:b,onError:e=>{null==c||c(`Widget runtime error ${eA}: ${e.message}`,!0)},apiEnvironment:t});eh.current=r;let i=r.subscribeTarget(to);return to(r.getCurrentTarget()),()=>{i(),r.destroy(),eh.current=null,to(null)}},[t,ta,null==o?void 0:o.fileSystemNamespace,tn,c,eA,to,b]);let tl=cl(async function(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=eh.current,i=t.widgetId??(null==(e=w.widgetSelection)?void 0:e.item.widgetId);if(!r||!i)return!1;let n=t.initData??ew.current.get(i);void 0!==t.initData&&ew.current.set(i,t.initData),eD();try{return await r.render({widgetId:i,initData:n,viewport:{...sd,device:ek,density:ek.density,label:ek.label,width:Math.max(1,ek.width-38)}}),eT.current=eC,L(!0),null==c||c(`Rendered widget ${i}`),!0}catch(t){L(!1),null==c||c(t.message,!0);let e=ev.current;return(null==e?void 0:e.command.widgetId)===i&&ey(e.command.commandId,{ok:!1,error:{code:"RENDER_FAILED",message:t.message}}),!1}});(0,iD.useEffect)(()=>{let e=ev.current;e&&"card"===t&&eh.current&&eb.current!==e.command.commandId&&(eb.current=e.command.commandId,tl({widgetId:e.command.widgetId,initData:e.command.structuredContent}))},[t,ef,tl]),(0,iD.useEffect)(()=>{var e,t;let r=eM.current;if((eM.current=eA,r!==eA)&&(null==(e=ev.current)?void 0:e.command.widgetId)!==eA){if(w.widgetSelection)return void tl();eD(),L(!1),null==(t=eh.current)||t.clear()}},[eD,tl,eA,w.widgetSelection]),(0,iD.useEffect)(()=>{!ev.current&&P&&eT.current!==eC&&tl()},[P,tl,eC]);let td=cl(async()=>{if(!eP)return!1;q(!0);try{if(await b.reloadResources(),D(e=>e+1),P&&!await tl())return!1;return null==c||c("已刷新卡片资源"),!0}catch(e){return null==c||c(e.message,!0),!1}finally{q(!1)}});return{activeView:t,fileSystemNamespace:null==o?void 0:o.fileSystemNamespace,appendAgentTraceEvent:eO,canReloadResources:eP,cardReloadKey:O,chromeDevToolsFrontendUrl:n,controlCommand:a,conversationAPIEnvironment:ts,conversationConsoleTarget:N.current,conversationControlTarget:J,conversationWidgetViewport:eL,currentDebugAppId:eB,currentDebugAppName:eF,debugState:ti,devtoolsTarget:e4,devToolsPanelId:ee===e2&&e2>0?"wsd-sandbox":Y>0?"wsd-trace":void 0,getRuntimeFrame:M,handleDebugAction:eZ,handleGrantingSheetTargetChange:e6,handleInspectableCardTargetChange:e8,handleQuerySubmit:eY,handleSandboxLoginHintClick:eQ,handleSandboxLoginHintClose:e1,handleSandboxLocationConfigOpen:e0,handleTraceMessageSelect:eX,hasRenderedPreview:P,highlightRect:R,latestDevToolsPanelRequestId:e2,nativeModulesCallHandler:tn,onActiveViewChange:d,onChromeDevToolsPanelChange:l,onControlResult:u,onMessage:c,onNavigateToPage:p,reloadResources:td,renderSelectedWidget:tl,resolveConversationInspectTarget:e9,runtimeFrameRef:k,runtimeFrameScaleBoxRef:C,runtimeScaleMode:ex,runtimeStyle:eI,runtimeSnapshotTarget:"conversation"===t?(null==J?void 0:J.targetInfo)??ez:ez,runtimeTargetRef:I,sandboxCashier:er,simulatorUI:ei,simulatorPermissionPrompt:en,simulatorSkillsIndexUrl:null==o?void 0:o.simulatorSkillsIndexUrl,selectedDeviceKey:eC,selectedTraceId:Z,selectedWidgetId:eA,setHighlightRect:j,setRuntimeConsoleSnapshot:z,setRuntimeDomSnapshot:H,setSelectedDeviceKey:eN,setRuntimeShellRef:eE,sandboxLoginAvailable:ea,showSandboxLoginHint:eo,simulatorState:eR,state:w,visibleWidgets:x,webSdkDebugger:b}}function hH(e){var t;let r=hW(e,"conversation"),{isOpen:i,onOpen:n,onOpenChange:a,onClose:o}=(0,cf.j)(),l=null==(t=e.debugContext)?void 0:t.sandboxSessionError,d=(null==l?void 0:l.category)??"platform",u={local:"请检查应用插件的 Manifest、业务模板和调试环境配置,修正后重新启动调试。",network:"请检查网络连接和代理配置,恢复后重新启动调试。",platform:`请按下方错误提示处理。
|
|
47
|
+
如需协助,请向平台支持提供错误信息${(null==l?void 0:l.logId)?"和 Log ID":""}。`}[d],{manifest:c,manifestUrl:p,resourceUrlVersion:h}=r.state,m=(0,iD.useMemo)(()=>{let e=new tT({resolveManifestUrl:()=>p,resourceUrlVersion:h});return e.setPackage({manifest:c,manifestUrl:String(p)}),e},[c,p,h]);return(0,s.jsxs)(pQ,{runtime:r,children:[(0,s.jsx)(cv.Y,{classNames:{base:"rounded-3xl",closeButton:"right-4 top-4 size-6 p-1 bg-default-100 text-default-500 hover:bg-default-200 hover:text-default-700 [&>svg]:size-4",header:"flex-col items-start gap-4 px-6 pb-0 pt-6 text-base font-medium",body:"gap-4 px-6 pb-0 pt-3 text-sm leading-[1.43]",footer:"p-6 text-sm font-medium"},isOpen:i,onOpenChange:a,placement:"center",scrollBehavior:"inside",size:"md",children:(0,s.jsxs)(cy.g,{children:[(0,s.jsxs)(cb.c,{children:[(0,s.jsx)("span",{"aria-hidden":"true",className:"flex size-10 items-center justify-center rounded-full bg-warning/15",style:{color:"color-mix(in oklab, hsl(var(--heroui-warning)) 80%, hsl(var(--heroui-foreground)) 70%)"},children:(0,s.jsxs)("svg",{fill:"none",height:"20",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",width:"20",children:[(0,s.jsx)("path",{d:"M10.3 3.9 2.2 18a2 2 0 0 0 1.7 3h16.2a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0Z"}),(0,s.jsx)("path",{d:"M12 9v4m0 4h.01"})]})}),{local:"请检查调试环境",network:"暂时无法连接平台",platform:"平台服务暂时不可用"}[d]]}),(0,s.jsxs)(cw.h,{children:[(0,s.jsx)("p",{className:"whitespace-pre-line",children:u}),(0,s.jsxs)("div",{className:"space-y-2 font-mono text-default-600",children:[(0,s.jsx)("pre",{className:"whitespace-pre-wrap break-words",children:(null==l?void 0:l.message)??"服务端未提供错误详情,请查看启动调试的终端输出。"}),(null==l?void 0:l.logId)?(0,s.jsxs)("p",{className:"break-words",children:["Log ID:",l.logId]}):null]})]}),(0,s.jsx)(c_.q,{children:(0,s.jsx)(cS.T,{color:"primary",onPress:o,radius:"full",children:"关闭"})})]})}),(0,s.jsx)(ck,{highlightRect:r.highlightRect,overlay:(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("section",{"aria-label":"对话",className:"wsd-widget-phone-scroll is-conversation",children:(0,s.jsx)(pp,{messageInputDisabled:e.messageInputDisabled,packageManager:m,apiEnvironment:r.conversationAPIEnvironment,appId:r.currentDebugAppId,fileSystemNamespace:r.fileSystemNamespace,cardReloadKey:r.cardReloadKey,controlCommand:r.controlCommand,nativeModulesCallHandler:r.nativeModulesCallHandler,onControlResult:r.onControlResult,onMessage:r.onMessage,onGrantingSheetTargetChange:r.handleGrantingSheetTargetChange,onInspectableCardTargetChange:r.handleInspectableCardTargetChange,onNavigateToPage:r.onNavigateToPage,onQuerySubmit:r.handleQuerySubmit,onSandboxLocationConfigOpen:r.handleSandboxLocationConfigOpen,onTraceEvent:r.appendAgentTraceEvent,onTraceMessageSelect:r.handleTraceMessageSelect,runtimeConsoleTarget:r.conversationConsoleTarget,sandboxLoginHint:r.showSandboxLoginHint?{available:r.sandboxLoginAvailable,onClose:r.handleSandboxLoginHintClose,onOpen:r.sandboxLoginAvailable?r.handleSandboxLoginHintClick:n}:void 0,selectedTraceId:r.selectedTraceId,simulator:r.simulatorState,webSdkDebugger:r.webSdkDebugger,widgetViewport:r.conversationWidgetViewport,widgets:r.state.widgets})}),r.simulatorUI.overlay,r.sandboxCashier.cashier?(0,s.jsx)(cC,{cashier:r.sandboxCashier.cashier,onCancel:r.sandboxCashier.cancelCashier,onConfirm:r.sandboxCashier.confirmCashier}):null,r.simulatorPermissionPrompt.overlay]}),runtimeFrameRef:r.runtimeFrameRef,runtimeFrameScaleBoxRef:r.runtimeFrameScaleBoxRef,runtimeScaleMode:r.runtimeScaleMode,runtimeShellRef:r.setRuntimeShellRef,runtimeStyle:r.runtimeStyle})]})}var hV=r(18017),hG=r(1136),hJ=r(80405);function hK(e){let{actionDisabled:t,actionLabel:r,JsonEditorComponent:i,label:n,minHeight:a=96,onAction:o,onChange:l,onMessage:d,value:u}=e;return(0,s.jsxs)("form",{className:"wsd-debug-inputs",onSubmit:function(e){e.preventDefault(),null==o||o()},children:[(0,s.jsxs)("div",{className:"wsd-debug-editor-block",children:[(0,s.jsxs)("div",{className:"wsd-editor-toolbar",children:[(0,s.jsx)("span",{className:"wsd-section-label",children:n}),(0,s.jsxs)("div",{className:"wsd-editor-actions",children:[(0,s.jsx)("button",{className:"wsd-button wsd-button-ghost",onClick:function(){try{l(JSON.stringify(sg("JSON",u),null,2)),null==d||d(`${n} formatted`)}catch(e){null==d||d(e.message,!0)}},type:"button",children:"格式化"}),(0,s.jsx)("button",{className:"wsd-button wsd-button-ghost",onClick:()=>{pA(n,u,d)},type:"button",children:"复制"})]})]}),i?(0,s.jsx)(i,{ariaLabel:n,minHeight:a,onChange:l,value:u}):(0,s.jsx)("textarea",{"aria-label":n,className:"wsd-json-textarea",onChange:e=>l(e.currentTarget.value),spellCheck:!1,style:{minHeight:a},value:u})]}),r?(0,s.jsx)("div",{className:"wsd-debug-action-bar",children:(0,s.jsx)("button",{className:"wsd-button wsd-button-primary",disabled:t,type:"submit",children:r})}):null]})}function hZ(){return{inputError:"",inputMode:"form",inputParams:{},inputText:"{}"}}function hX(e){return Array.isArray(e)?e.map(hX):rP(e)?Object.fromEntries(Object.entries(e).map(e=>{let[t,r]=e;return"type"===t&&"int"===r?[t,"integer"]:"type"===t&&"float"===r?[t,"number"]:[t,hX(r)]})):e}function hY(e){let{id:t,name:r,onChange:i,onError:n,type:a,value:o}=e,[l,d]=(0,iD.useState)(JSON.stringify(o??("array"===a?[]:{}),null,2));function u(e){try{let t=JSON.parse(e);if(!("array"===a?Array.isArray(t):rP(t)))throw Error(`expected a JSON ${a}`);i(t)}catch(e){n(`${r}: ${e.message}`)}}return(0,s.jsx)("textarea",{"aria-label":`参数 ${r}`,className:"wsd-schema-complex-input",id:t,onBlur:()=>u(l),onChange:e=>{let t=e.currentTarget.value;d(t),u(t)},spellCheck:!1,value:l})}function hQ(e){let{onChange:t,schema:r,value:i}=e,n=(0,iD.useId)(),a=(0,iD.useRef)(new Map),o=rP(r.properties)?r.properties:{},l=new Set(Array.isArray(r.required)?r.required.filter(e=>"string"==typeof e):[]);function d(){return a.current.values().next().value??""}function u(e,r){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];n&&a.current.delete(e);let s={...i};void 0===r?delete s[e]:s[e]=r,t(s,d())}return 0===Object.keys(o).length?(0,s.jsx)("div",{className:"wsd-schema-empty-input",children:"无需输入参数"}):(0,s.jsx)("div",{className:"wsd-schema-input-form",children:Object.entries(o).map(e=>{let[r,o]=e,c=rP(o)?o:{},p=c.type||"string",h="string"==typeof c.description?c.description:"",m=Array.isArray(c.enum)?c.enum:void 0,g=i[r],f=`${n}-${r}`;return(0,s.jsxs)("label",{className:"wsd-schema-form-field",htmlFor:f,children:[(0,s.jsxs)("span",{className:"wsd-schema-form-field-title",children:[(0,s.jsx)("strong",{children:r}),l.has(r)?(0,s.jsx)("em",{children:"必填"}):null,(0,s.jsx)("small",{children:`${p}${m?" · enum":""}`})]}),h?(0,s.jsx)("span",{className:"wsd-schema-form-field-description",children:h}):null,m?(0,s.jsxs)("select",{"aria-label":`参数 ${r}`,id:f,onChange:e=>u(r,e.currentTarget.value?JSON.parse(e.currentTarget.value):void 0),value:void 0===g?"":JSON.stringify(g),children:[(0,s.jsx)("option",{value:"",children:"请选择"}),m.map(e=>(0,s.jsx)("option",{value:JSON.stringify(e),children:String(e)},JSON.stringify(e)))]}):"boolean"===p?(0,s.jsxs)("select",{"aria-label":`参数 ${r}`,id:f,onChange:e=>u(r,""===e.currentTarget.value?void 0:"true"===e.currentTarget.value),value:"boolean"==typeof g?String(g):"",children:[(0,s.jsx)("option",{value:"",children:"请选择"}),(0,s.jsx)("option",{value:"true",children:"true"}),(0,s.jsx)("option",{value:"false",children:"false"})]}):"null"===p?(0,s.jsxs)("select",{"aria-label":`参数 ${r}`,id:f,onChange:e=>u(r,"null"===e.currentTarget.value?null:void 0),value:null===g?"null":"",children:[(0,s.jsx)("option",{value:"",children:"请选择"}),(0,s.jsx)("option",{value:"null",children:"null"})]}):"array"===p||"object"===p?(0,s.jsx)(hY,{id:f,name:r,onChange:e=>u(r,e,!0),onError:e=>{a.current.set(r,e),t(i,d())},type:p,value:g}):(0,s.jsx)("input",{"aria-label":`参数 ${r}`,id:f,onChange:e=>{u(r,function(e,t){if(e)return"number"===t||"integer"===t?Number(e):e}(e.currentTarget.value,p))},step:"integer"===p?1:"any",type:"number"===p||"integer"===p?"number":"text",value:"string"==typeof g||"number"==typeof g?g:""})]},r)})})}function h0(e){let{heading:t,jsonLabel:r,minHeight:i=160,onChange:n,onMessage:a,schema:o,value:l}=e;return(0,s.jsxs)("div",{className:"wsd-schema-input-editor",children:[(0,s.jsxs)("div",{className:"wsd-schema-input-heading",children:[(0,s.jsx)("span",{children:t}),(0,s.jsx)("button",{className:"wsd-button wsd-button-ghost",onClick:function(){if("form"===l.inputMode)return void n({inputMode:"text"});try{let e=sg(r,l.inputText);n({inputError:"",inputMode:"form",inputParams:e,inputText:JSON.stringify(e,null,2)})}catch(e){n({inputError:e.message})}},type:"button",children:"form"===l.inputMode?"文本模式":"表单模式"})]}),"form"===l.inputMode?(0,s.jsx)(hQ,{onChange:function(e,t){n({inputError:t,inputParams:e,inputText:JSON.stringify(e,null,2)})},schema:o,value:l.inputParams}):(0,s.jsx)(hK,{label:r,minHeight:i,onChange:e=>n({inputError:"",inputText:e}),onMessage:a,value:l.inputText}),l.inputError?(0,s.jsx)("span",{className:"wsd-schema-input-error",children:l.inputError}):null]})}function h1(e){var t;let{events:r,onMessage:i,onTrigger:n}=e,a=(0,iD.useRef)(null),[o,l]=(0,iD.useState)(!1),[d,u]=(0,iD.useState)((null==(t=r[0])?void 0:t.name)??""),[c,p]=(0,iD.useState)(hZ),[h,m]=(0,iD.useState)(""),g=r.find(e=>e.name===d)??r[0],f=cl(()=>l(!1));(0,iD.useEffect)(()=>{if(!g){u(""),p(hZ()),l(!1);return}g.name!==d&&(u(g.name),p(hZ()))},[g,d]),(0,iD.useEffect)(()=>{if(o)return document.addEventListener("mousedown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",t)};function e(e){var t;(null==(t=a.current)?void 0:t.contains(e.target))||f()}function t(e){"Escape"===e.key&&f()}},[f,o]);let v=cl(()=>{let e;if(g&&!c.inputError){try{e=sg("事件参数",c.inputText)}catch(e){p(t=>({...t,inputError:e.message}));return}try{n(g.name,e),p(t=>({...t,inputError:"",inputParams:e})),m(`已触发 ${g.name}`),null==i||i(`Agent event ${g.name} triggered`),f()}catch(t){let e=t.message;m(e),null==i||i(e,!0)}}});return(0,s.jsxs)("div",{className:"wsd-agent-event-debug",ref:a,children:[(0,s.jsxs)("button",{"aria-expanded":o,"aria-haspopup":"dialog","aria-label":"调试 Agent 事件",className:"wsd-agent-event-button",onClick:()=>l(e=>!e),title:"触发 Agent 事件",type:"button",children:[(0,s.jsx)("span",{"aria-hidden":"true",children:"+"}),"事件"]}),o&&g?(0,s.jsxs)("dialog",{"aria-label":"Agent 事件调试",className:"wsd-agent-event-popup",open:!0,children:[(0,s.jsxs)("header",{className:"wsd-agent-event-header",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)("strong",{children:"触发事件"}),(0,s.jsx)("span",{children:"发送到当前小程序的 App runtime"})]}),(0,s.jsx)("button",{"aria-label":"关闭事件调试",onClick:f,type:"button",children:"×"})]}),(0,s.jsxs)("label",{className:"wsd-agent-event-select-control",children:[(0,s.jsx)("span",{children:"事件"}),(0,s.jsx)("select",{"aria-label":"调试事件",onChange:e=>{u(e.currentTarget.value),p(hZ()),m("")},value:g.name,children:r.map(e=>(0,s.jsx)("option",{value:e.name,children:e.name},e.name))})]}),g.description?(0,s.jsx)("p",{className:"wsd-agent-event-description",children:g.description}):null,(0,s.jsx)(h0,{heading:"事件参数 · PAYLOADSCHEMA",jsonLabel:"事件参数",minHeight:132,onChange:e=>p(t=>({...t,...e})),onMessage:i,schema:g.payloadSchema,value:c},g.name),(0,s.jsxs)("footer",{className:"wsd-agent-event-footer",children:[h?(0,s.jsx)("span",{"aria-live":"polite",children:h}):(0,s.jsx)("span",{}),(0,s.jsx)("button",{className:"wsd-button wsd-button-primary wsd-agent-event-trigger",onClick:v,type:"button",children:"触发"})]})]}):null]})}async function h2(e,t,r){let i=await r(e,{cache:"no-store",headers:{Accept:"application/json"}});if(!i.ok)throw Error(`加载 ${t}失败:HTTP ${i.status} ${i.statusText}`);return i.json()}async function h3(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/__web_sdk_debug_scenes",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:fetch;var r=await h2(e,"Scene ",t);if(!rP(r)||!Array.isArray(r.scenes)||!Array.isArray(r.errors))throw Error("Scene 发现接口返回了无效数据");let i=r.scenes.flatMap(e=>rP(e)&&"string"==typeof e.name&&rP(e.content)?[{content:e.content,name:e.name}]:[]);return{errors:r.errors.flatMap(e=>rP(e)&&"string"==typeof e.name&&"string"==typeof e.message?[{name:e.name,message:e.message}]:[]),scenes:i}}let h4={appEntries:[],entries:[],updatedAtMs:0},h6="scene:";function h5(e){let{showTooltip:t=!1,value:r}=e,i=r.indexOf("?"),n=i<0?r:r.slice(0,i),a=i<0?"":r.slice(i),o=(0,s.jsxs)("span",{className:"wsd-page-route-label",children:[(0,s.jsx)("span",{className:"wsd-page-route-path",children:n}),a?(0,s.jsx)("span",{className:"wsd-page-route-query",children:a}):null]});return t?(0,s.jsx)(hV.I,{closeDelay:0,content:r,delay:300,placement:"right",children:o}):o}function h8(){return(0,s.jsx)("svg",{"aria-hidden":"true",className:"wsd-page-route-arrow is-back",viewBox:"0 0 16 16",children:(0,s.jsx)("path",{d:"M3 8h10M9 4l4 4-4 4",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5"})})}function h9(e){var t,r,i,n,a,o;let{activeView:l,chromeDevToolsFrontendUrl:d,controlCommand:u,controlClientId:c,debugContext:p,onChromeDevToolsPanelChange:h,onActiveViewChange:m,onControllerChange:g,onControlResult:f,onMessage:v,apiEnvironment:y,showDebugTrace:b,connection:w,webSdkDebugger:_}=e,S=cg(_),x=(0,iD.useMemo)(()=>S.pages.filter(nY),[S.pages]),[I,k]=(0,iD.useState)({errors:[],scenes:[]}),[C,E]=(0,iD.useState)([]),[N,T]=(0,iD.useState)(""),[A,M]=(0,iD.useState)(null),[R,j]=(0,iD.useState)(null),[P,L]=(0,iD.useState)(null),[O,D]=(0,iD.useState)(null),[U,q]=(0,iD.useState)(null),[$,B]=(0,iD.useState)(0),[F,z]=(0,iD.useState)(""),[W,H]=(0,iD.useState)(null),[V,G]=(0,iD.useState)(h4),J=cE(),K=hs(),Z=(null==p?void 0:p.sandboxSessionAvailable)!==!1,X=hN(hl(p)),Y=hO(Z),{bridgeLogs:Q,clearBridgeLogs:ee}=cJ(),[et,er]=(0,iD.useState)(null),ei=p3(),en=(0,iD.useRef)(null),ea=(0,iD.useRef)(null),{accept:es,pending:eo,pendingRef:el,report:ed}=hU(f),{runtimeScaleMode:eu,runtimeStyle:ec,selectedDevice:ep,selectedDeviceKey:eh,setRuntimeShellRef:em,setSelectedDeviceKey:eg}=h$(u,f),ef=(null==(t=S.pageSelection)?void 0:t.item.id)??"",ev=(null==(r=S.pageSelection)?void 0:r.item.path)??"",ey=cl(e=>{null==v||v(e,!0)});(0,iD.useEffect)(()=>{let e=null==p?void 0:p.eventsConfigUrl;if(!e)return void E([]);let t=new AbortController;return fetch(e,{cache:"no-store",headers:{Accept:"application/json"},signal:t.signal}).then(async e=>{if(!e.ok)throw Error(`Failed to load events.json: HTTP ${e.status}`);return e.json()}).then(e=>E(rP(e)&&Array.isArray(e.events)?e.events.flatMap(e=>{if(!rP(e))return[];let t="string"==typeof e.name?e.name.trim():"",r=hX(e.payloadSchema);return t&&rP(r)?[{description:"string"==typeof e.description?e.description:"",name:t,payloadSchema:r}]:[]}):[])).catch(e=>{t.signal.aborted||(E([]),ey(e.message))}),()=>t.abort()},[null==p?void 0:p.eventsConfigUrl,ey]);let eb=(0,iD.useMemo)(()=>I.scenes.flatMap(e=>{let t=rA(e.content);if("page"!==t.type||t.unresolvedVariables.length>0)return[];try{return tO({url:t.url},S.manifest),[{key:`${h6}${e.name}`,label:t.url,type:"scene",url:t.url}]}catch{return[]}}),[I.scenes,S.manifest]),ew=(0,iD.useMemo)(()=>[...x.map(e=>({key:e.path,url:e.path})),...eb],[eb,x]),e_=F||(null==(i=S.pageSelection)?void 0:i.routeUrl)||ev,eS=e_.split("?")[0],ex=(null==(n=eb.find(e=>e.key===N&&e.url===e_))?void 0:n.key)??"",eI=(null==(a=ew.find(e=>!e.key.startsWith(h6)&&e.url===eS))?void 0:a.key)??"",ek=(0,iD.useMemo)(()=>({...p,manifestUrl:S.manifestUrl,simulatorEndpoint:S.simulator.endpoint}),[p,S.manifestUrl,S.simulator.endpoint]),eC=(0,iD.useMemo)(()=>hf({context:ek,events:S.simulator.traceEvents,manifest:S.manifest,pages:S.pages,widgets:S.widgets}),[ek,S.manifest,S.pages,S.simulator.traceEvents,S.widgets]),eE=eC.appId,eN=eC.appName,eT=(0,iD.useMemo)(()=>({type:"page",appId:eE,appName:eN,pageId:ef,pagePath:ev,url:e_,viewport:{key:ep.key,label:ep.label,width:ep.width,height:ep.height,density:ep.density}}),[eE,eN,ep,ef,ev,e_]),eA=(0,iD.useMemo)(()=>hy(eC,S.pageSelection?eT:void 0),[eT,eC.pages,eC.widgets,S.pageSelection]),eM=!!(eo&&hv(et,O,eo.previousTarget)&&(null==(o=S.pageSelection)?void 0:o.routeUrl)===eo.command.url),eR=(0,iD.useMemo)(()=>(null==et?void 0:et.sourceTarget)===O?{target:eT,root:et.root,nodeCount:et.nodeCount,selectedUid:et.selectedUid,truncated:et.truncated,updatedAtMs:et.updatedAtMs}:void 0,[eT,O,et]),ej=(0,iD.useMemo)(()=>({exported_at:new Date().toISOString(),client_id:c,command_id:eM?null==eo?void 0:eo.command.commandId:void 0,context:{...ho({appId:eE,appName:eC.appName,debugContext:ek,manifestUrl:S.manifestUrl,simulatorEndpoint:S.simulator.endpoint,sources:eC.sources}),page_id:ef,page_path:ev},render_targets:eA,runtime_snapshot:eR,page_runtime_trace_events:[],runtime_console:{app:{entries:V.appEntries,updated_at_ms:V.updatedAtMs},page:{entries:V.entries,updated_at_ms:V.updatedAtMs}},simulator:{stream_status:S.simulator.streamStatus,messages:S.simulator.messages,trace_events:S.simulator.traceEvents,tool_calls:S.simulator.toolCalls}}),[eC.appId,eC.appName,eC.sources.manifest.original,eC.sources.manifest.proxy,eC.sources.mcp.original,eC.sources.mcp.proxy,eC.sources.skill.original,eC.sources.skill.proxy,ek.launchDir,ek.mcpEndpoint,ek.simulatorManifestUrl,ek.simulatorSkillsIndexUrl,ek.webUrl,V,ef,ev,eE,c,eM,null==eo?void 0:eo.command.commandId,eA,S.manifest.name,S.manifestUrl,S.simulator.endpoint,S.simulator.messages,S.simulator.streamStatus,S.simulator.toolCalls,S.simulator.traceEvents,eR]),eP=(0,iD.useMemo)(()=>b?S.simulator.traceEvents:S.simulator.traceEvents.filter(e=>{var t;return!(null==(t=e.display)?void 0:t.debugOnly)}),[b,S.simulator.traceEvents]),eL=(0,iD.useMemo)(()=>iI(eP,{debug:b,messages:S.simulator.messages}),[b,S.simulator.messages,eP]),eO=(0,iD.useMemo)(()=>ix(ej,{debug:b}),[b,ej]),eD=(0,iD.useMemo)(()=>iw(eO),[eO]);(0,iD.useEffect)(()=>{let e=!0;return h3(null==p?void 0:p.debugScenesEndpoint).then(t=>{if(e)for(let e of(k(t),t.errors))null==v||v(`${e.name}: ${e.message}`,!0)}).catch(t=>{e&&(k({errors:[],scenes:[]}),null==v||v(t.message,!0))}),()=>{e=!1}},[null==p?void 0:p.debugScenesEndpoint,v]);let eU=cl(e=>{var t,r;let i=(null==(t=en.current)?void 0:t.getCurrentTarget())??(null==(r=en.current)?void 0:r.getCurrentAppTarget()),n=`[Debug Scene] ${e}`;i?s_(i,{level:"error",message:n,pagePath:ev}):console.error(n)}),eq=cl(e=>{eb.some(e=>{var t;return e.key===N&&e.url===(null==(t=S.pageSelection)?void 0:t.routeUrl)})?eU(e):null==v||v(e,!0)}),e$=async()=>{var e;await _.reloadResources(),null==(e=en.current)||e.reload()},eB=cl(e=>{let t=ew.find(t=>t.key===e);t&&(t.key.startsWith(h6)?T(t.key):T(""),_.navigateToPage(t.url))}),eF=cl(e=>{hD(e,{onClearLogs:ee,onMessage:v})}),ez=(0,iD.useMemo)(()=>({debugData:{...eC,appId:(null==p?void 0:p.sandboxCsrRequired)?p.sandboxAppId||"":eC.appId},events:eL,logSnapshot:eO,logSnapshotText:eD,sandbox:{available:Z,csrRequired:(null==p?void 0:p.sandboxCsrRequired)!==!1,input:{csrPem:(null==p?void 0:p.sandboxCsrPem)??"",phoneNum:(null==p?void 0:p.sandboxPhoneNum)??""},logs:Q,businessInfoStatus:X,sessionStatus:Y},showDebugTrace:b,traceSurface:"page",toolCalls:S.simulator.toolCalls,updatedAtMs:Date.now()}),[eC,eL,eO,eD,Q,X,Z,Y,null==p?void 0:p.sandboxCsrRequired,null==p?void 0:p.sandboxAppId,b,S.simulator.toolCalls]);hB(w,ej,et,"page"===l),(0,iD.useEffect)(()=>{if((null==u?void 0:u.type)==="render_page"&&es(u,O))try{T(""),_.navigateToPage(u.url)}catch(e){ed(u.commandId,{ok:!1,error:{code:"TARGET_NOT_FOUND",message:e.message}})}},[es,u,O,ed,_]),(0,iD.useEffect)(()=>{eo&&eM&&ed(eo.command.commandId,{ok:!0,target:eT,snapshot:iS(ej)})},[eT,eM,eo,ed,ej]);let eW=cl((e,t)=>{let r=af(_,{noLogin:null==t?void 0:t.noLogin});if("not_found"===r.status){null==v||v("未找到需要重发的原始消息",!0);return}if("streaming"===r.status){null==v||v("当前仍在生成中,暂不重发授权后的消息",!0);return}_.appendSimulatorTraceEvent({category:"card",event:"simulator_granting_resend_query",granting_type:e,no_login:(null==t?void 0:t.noLogin)===!0,removed_message_ids:r.target.messageIds,query_preview:r.target.query.slice(0,80),source:"custom_login_page"}),r.completion.catch(e=>{null==v||v(e.message,!0)})}),eH=cl((e,t)=>{eW(e,t),"login"===e&&(null==m||m("conversation"))}),eV=cl(async e=>{let t=en.current;if(!t)throw Error("No Page runtime is active");await t.openPage(e)}),eG=(0,iD.useMemo)(()=>{let e=dI({appId:eE,appIcon:S.manifest.iconSrc,appName:eN,declaredScopes:Object.keys(S.manifest.raw.permissions??{}),baseAPIRegistry:null==y?void 0:y.apiRegistry,imagePreviewController:K.imagePreviewController,onGrantingCompleted:eH,openPageFromWidget:eV,sendFollowUpMessage:e=>{let{content:t}=e;return _.sendSimulatorFollowUpMessage(t)},multiMediaBroadcastContainer:A,scanCodePresenter:K.scanCodePresenter,showSandboxCashier:J.showCashier,uiPresenter:K.presenter,showSimulatorPermission:ei.showPermission,showSimulatorPermissionSettings:ei.showSettings,vibrationContainer:P});return e.apiRegistry.registerMany(c1({appKey:eE,scene:"page"}),{override:!0}),e.apiRegistry.registerMany(c2(e=>_.updateSimulatorWidget(e)),{override:!0}),e},[y,eH,eV,eE,eN,K.imagePreviewController,P,A,J.showCashier,K.scanCodePresenter,K.presenter,ei.showPermission,ei.showSettings,S.manifest.iconSrc,S.manifest.raw.permissions,_]),eJ=cl(async(e,t)=>"confirm"===(await K.presenter.showModal({content:e,showCancel:!0,confirmText:"确认",cancelText:"取消"},t)).action);(0,iD.useEffect)(()=>{if(!A)return;let e=new ca({container:A,fileSystemNamespace:null==p?void 0:p.fileSystemNamespace,webSdkDebugger:_,onExitApp:()=>null==m?void 0:m("conversation"),onHideApp:()=>null==m?void 0:m("conversation"),confirmBeforeUnload:eJ,onError:e=>{null==v||v(`Page runtime error: ${e.message}`,!0)},apiEnvironment:eG});en.current=e,null==g||g(e);let t=e.subscribeTarget(t=>{D(t),B(e.getPageStackSize()),z(e.getCurrentPageUrl()??""),H(null)}),r=e.subscribeAppTarget(e=>{q(e)});return D(e.getCurrentTarget()),q(e.getCurrentAppTarget()),B(e.getPageStackSize()),z(e.getCurrentPageUrl()??""),()=>{t(),r(),e.destroy(),en.current=null,null==g||g(null),D(null),q(null),B(0),z(""),H(null)}},[eJ,null==p?void 0:p.fileSystemNamespace,m,g,v,eG,A,_]);let eK=cl((e,t)=>{let r=en.current;if(!r)throw Error("Page runtime is not ready");r.sendAgentEvent(e,t)});(0,iD.useEffect)(()=>{let e=en.current;if(!e||!S.pageSelection){null==e||e.clear();return}let t=ea.current===S.pageSelection?void 0:S.pageSelection.routeMode;ea.current=S.pageSelection;let r=!1;return e.render({device:ep,routeMode:t}).catch(e=>{if(r||rP(e)&&"AbortError"===e.name)return;eq(e.message);let t=el.current;t&&ed(t.command.commandId,{ok:!1,error:{code:"RENDER_FAILED",message:e.message}})}),()=>{r=!0}},[eq,ed,A,ep,ef,S.pageSelection]);let eZ=(0,iD.useMemo)(()=>({appTarget:U,controlCommand:u,controlTarget:S.pageSelection?O:null,debugState:ez,frontendUrl:d,onConsoleSnapshotChange:G,onControlResult:f,onDebugAction:eF,onHighlightChange:H,onRuntimeSnapshotChange:er,preserveConsoleOnTargetChange:!0,runtimeSnapshotTarget:eT,runtimeFrame:R,target:S.pageSelection?O:null}),[U,d,u,eT,ez,eF,f,O,R,S.pageSelection]);return(0,iD.useEffect)(()=>{"page"===l&&(null==h||h(eZ))},[l,eZ,h]),(0,iD.useEffect)(()=>{var e;null==(e=en.current)||e.setVisible("page"===l)},[l,A]),(0,s.jsxs)("div",{className:"wsd-page-preview-column",hidden:"page"!==l,children:[(0,s.jsx)(pY,{activeView:l??"page",storageNamespace:null==p?void 0:p.fileSystemNamespace,hasTools:Object.keys(S.manifest.raw.tools??{}).length>0,onActiveViewChange:m,onDeviceChange:eg,selectedDeviceKey:eh,children:(0,s.jsx)("button",{"aria-label":"Reload",className:"wsd-icon-button",disabled:!S.pageSelection,onClick:()=>void e$(),title:"Reload",type:"button",children:(0,s.jsx)(ph,{"aria-hidden":"true"})})}),(0,s.jsxs)("div",{className:"wsd-page-route-control",children:[(0,s.jsx)("div",{className:"wsd-page-route-navigation",children:(0,s.jsx)("button",{"aria-label":"返回",className:"wsd-page-route-button",disabled:0===$,onClick:()=>{var e;return null==(e=en.current)?void 0:e.closeCurrentPage()},title:"返回",type:"button",children:(0,s.jsx)(h8,{})})}),(0,s.jsx)("div",{className:"wsd-page-route-select-wrapper",children:(0,s.jsx)(hG.d,{"aria-label":"页面路径",className:"wsd-page-route-select",classNames:{listbox:"wsd-page-path-listbox",popoverContent:"wsd-page-path-popover",selectorIcon:"wsd-page-path-icon",trigger:"wsd-page-path-select",value:"wsd-page-path-value"},isDisabled:0===x.length&&0===eb.length,listboxProps:{itemClasses:{base:"wsd-page-path-option",selectedIcon:"wsd-page-path-selected-icon"}},onChange:e=>eB(e.target.value),placeholder:e_||"No page",popoverProps:{offset:0},renderValue:()=>(0,s.jsx)(h5,{value:e_||ev}),selectedKeys:ex?[ex]:eI?[eI]:[],size:"sm",children:ew.map(e=>(0,s.jsx)(hJ.y,{textValue:e.url,children:(0,s.jsx)(h5,{showTooltip:!0,value:e.url})},e.key))})}),S.pageSelection&&C.length>0?(0,s.jsx)(h1,{events:C,onMessage:v,onTrigger:eK}):null]}),S.pageSelection?(0,s.jsx)(ck,{highlightRect:W,overlay:(0,s.jsxs)(s.Fragment,{children:[K.overlay,J.cashier?(0,s.jsx)(cC,{cashier:J.cashier,onCancel:J.cancelCashier,onConfirm:J.confirmCashier}):null,ei.overlay]}),runtimeFrameRef:j,runtimeFrameScaleBoxRef:L,runtimeScaleMode:eu,runtimeShellRef:em,runtimeStyle:ec,runtimeTargetRef:M}):(0,s.jsx)("div",{className:"wsd-page-empty",children:"No page"})]})}let h7=0;function me(){return{...hZ(),callError:"",isRunning:!1,selectedOutputIndex:0,selectedToolName:""}}function mt(e){var t;let r=null==e||null==(t=e.debug)?void 0:t.mcp_output,i=!1,n=(r?[r]:[]).flatMap(e=>{var t;if(Array.isArray(e.structuredContent)){i=!0;let t=e.structuredContent;return t.length>0?t.map(t=>({...e,structuredContent:t})):[e]}if(!Array.isArray(null==(t=e.structuredContent)?void 0:t.entities))return[e];i=!0;let r=e.structuredContent.entities;return r.length>0?r.map(t=>({...e,structuredContent:t})):[e]});return{collectionType:i?"entity":void 0,outputs:n}}function mr(e){return((null==e?void 0:e.content)??[]).map(e=>"text"===e.type&&e.text||"").filter(Boolean).join("\n")}function mi(e){var t;let{onSessionChange:r,onUseWidgetOutput:i,session:n,...a}=e,o=hW(a,"card"),l=null==(t=a.debugContext)?void 0:t.toolsConfigUrl,d=cl(e=>{var t;null==(t=a.onMessage)||t.call(a,e,!0)}),[u,c]=(0,iD.useState)({}),p=(0,iD.useMemo)(()=>{var e;return e=o.state.manifest.raw,Object.entries(e.tools??{}).map(t=>{let[r,i]=t;return{description:i.description||"",inputSchema:u[r]??hX(i.input_schema??{}),name:r,widgetId:function(e,t){for(let i of Object.values(e.entities??{})){var r;let e=null==(r=i.tool_card_binding)?void 0:r[t];if(e)return e}}(e,r)}})},[o.state.manifest,u]),{callError:h,copiedResultSection:m,inputError:g,inputText:f,isRunning:v,result:y,selectedOutputIndex:b,selectedToolName:w}=n,_=p.find(e=>e.name===w)??p[0],S=null==_?void 0:_.widgetId,x=mt(y),I=x.outputs,k=I[b]??I[0],C=Array.isArray(null==k?void 0:k.structuredContent)||null==k?void 0:k.structuredContent,E=null==k?void 0:k._meta,N=mr(k);async function T(){let e;if(!_||g)return;try{e=sg("调用参数",f)}catch(e){r(t=>({...t,inputError:e.message}));return}let t=h7+=1;r(r=>({...r,activeInvocationId:t,callError:"",copiedResultSection:void 0,inputError:"",inputParams:e,isRunning:!0,result:void 0,selectedOutputIndex:0}));try{let i=await o.webSdkDebugger.callSimulatorTool({params:e,toolName:_.name});r(e=>{let r;return e.activeInvocationId===t?{...e,result:i,selectedOutputIndex:(r=mt(i).outputs.findIndex(e=>e.structuredContent))<0?0:r}:e})}catch(e){r(r=>r.activeInvocationId===t?{...r,callError:e.message}:r)}finally{r(e=>e.activeInvocationId===t?{...e,activeInvocationId:void 0,isRunning:!1}:e)}}async function A(e,t){await pA("meta"===e?"META JSON":"STRUCTUREDCONTENT JSON",JSON.stringify(t,null,2),o.onMessage)&&r(t=>({...t,copiedResultSection:e}))}return(0,iD.useEffect)(()=>{if(!l)return void c({});let e=new AbortController;return fetch(l,{cache:"no-store",headers:{Accept:"application/json"},signal:e.signal}).then(async e=>{if(!e.ok)throw Error(`Failed to load tools.json: HTTP ${e.status}`);return e.json()}).then(e=>{c(rP(e)&&Array.isArray(e.tools)?Object.fromEntries(e.tools.flatMap(e=>rP(e)&&"string"==typeof e.name&&rP(e.inputSchema)?[[e.name,e.inputSchema]]:[])):{})}).catch(t=>{e.signal.aborted||d(t.message)}),()=>e.abort()},[d,l]),(0,iD.useEffect)(()=>{_&&_.name!==w&&r(e=>({...e,selectedToolName:_.name}))},[r,_,w]),(0,s.jsx)(pQ,{runtime:o,showReloadButton:!1,toolbarView:"tool",children:(0,s.jsx)("div",{className:"wsd-tool-debug",children:_?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("section",{className:"wsd-tool-debug-card",children:[(0,s.jsxs)("label",{className:"wsd-tool-select-control",children:[(0,s.jsx)("span",{children:"工具"}),(0,s.jsx)("select",{"aria-label":"调试工具",onChange:e=>{var t;return t=e.currentTarget.value,void r({...me(),selectedToolName:t})},value:_.name,children:p.map(e=>(0,s.jsx)("option",{value:e.name,children:e.name},e.name))})]}),(0,s.jsx)("h2",{children:_.name}),_.description?(0,s.jsx)("p",{children:_.description}):null,(0,s.jsx)(h0,{heading:"输入参数 · INPUTSCHEMA",jsonLabel:"调用参数",onChange:e=>r(t=>({...t,...e})),onMessage:o.onMessage,schema:_.inputSchema,value:n},_.name),(0,s.jsx)("button",{className:"wsd-button wsd-button-primary wsd-tool-run-button",disabled:v,onClick:()=>void T(),type:"button",children:v?"运行中…":"▶ 运行"})]}),y||h?(0,s.jsxs)("section",{className:"wsd-tool-debug-result","aria-live":"polite",children:[(0,s.jsxs)("div",{className:"wsd-tool-result-title",children:[(0,s.jsx)("span",{children:"输出结果"}),(0,s.jsx)("strong",{className:(null==y?void 0:y.status)==="succeeded"?"is-success":"is-error",children:(null==y?void 0:y.status)==="succeeded"?"运行成功":"运行失败"})]}),x.collectionType&&I.length>0?(0,s.jsxs)("label",{className:"wsd-tool-select-control wsd-tool-output-select-control",children:[(0,s.jsx)("span",{children:"entity"===x.collectionType?"Entity 元素":"数组元素"}),(0,s.jsx)("select",{"aria-label":"entity"===x.collectionType?"Entity 元素":"数组元素",onChange:e=>{let t=Number(e.currentTarget.value);r(e=>({...e,copiedResultSection:void 0,selectedOutputIndex:t}))},value:b,children:I.map((e,t)=>{let r,i,n;return(0,s.jsx)("option",{value:t,children:(i=[null==(r=Array.isArray(e.structuredContent)?void 0:e.structuredContent)?void 0:r.name,null==r?void 0:r.title].find(e=>"string"==typeof e&&e.trim()),n=mr(e).split("\n")[0],`${t+1}. ${i||n||"空结果"}`)},t)})})]}):null,h||(null==y?void 0:y.error)?(0,s.jsxs)("div",{className:"wsd-tool-result-block",children:[(0,s.jsx)("span",{children:"ERROR"}),(0,s.jsx)("pre",{children:h||JSON.stringify(null==y?void 0:y.error,null,2)})]}):null,N?(0,s.jsxs)("div",{className:"wsd-tool-result-block",children:[(0,s.jsx)("span",{children:"CONTENT"}),(0,s.jsx)("p",{children:N})]}):null,C?(0,s.jsxs)("div",{className:"wsd-tool-result-block",children:[(0,s.jsxs)("div",{className:"wsd-tool-result-block-heading",children:[(0,s.jsx)("span",{children:"STRUCTUREDCONTENT"}),(0,s.jsx)("button",{"aria-label":"复制 STRUCTUREDCONTENT JSON",className:"wsd-button wsd-button-ghost",onClick:()=>void A("structuredContent",C),type:"button",children:"structuredContent"===m?"已复制":"复制 JSON"})]}),(0,s.jsx)("pre",{children:JSON.stringify(C,null,2)})]}):null,E?(0,s.jsxs)("div",{className:"wsd-tool-result-block",children:[(0,s.jsxs)("div",{className:"wsd-tool-result-block-heading",children:[(0,s.jsx)("span",{children:"META"}),(0,s.jsx)("button",{"aria-label":"复制 META JSON",className:"wsd-button wsd-button-ghost",onClick:()=>void A("meta",E),type:"button",children:"meta"===m?"已复制":"复制 JSON"})]}),(0,s.jsx)("pre",{children:JSON.stringify(E,null,2)})]}):null,(null==y?void 0:y.status)==="succeeded"&&S&&C?(0,s.jsxs)("button",{className:"wsd-button wsd-button-primary wsd-tool-use-widget-output",onClick:()=>i({viewData:C,widgetId:S}),type:"button",children:["填入 ",S," 卡片预览"]}):null]}):null]}):null})})}var mn=e=>(0,s.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",width:12,height:12,fill:"none",viewBox:"0 0 12 12",...e,children:(0,s.jsx)("path",{fill:"#BABABA",d:"M1.162 4.61a.5.5 0 1 1 .707-.706l4.06 4.06a.1.1 0 0 0 .142 0l4.06-4.06a.5.5 0 0 1 .707.707l-4.06 4.06a1.1 1.1 0 0 1-1.556 0z"})}),ma=r(48986),ms=r(80704),mo=r(51290),ml=r(36091);let md=mo.Lz.theme({"&":{height:"100%",backgroundColor:"#fbfcff",color:"#172033",fontSize:"12px"},"&.cm-focused":{outline:"none"},".cm-scroller":{fontFamily:"'SFMono-Regular', Consolas, monospace",lineHeight:"1.55"},".cm-content":{padding:"8px 0"},".cm-line":{padding:"0 10px 0 8px"},".cm-gutters":{borderRight:"1px solid #dfe5ee",backgroundColor:"#f4f7fb",color:"#8a98ab"},".cm-activeLine":{backgroundColor:"rgba(36, 84, 198, 0.05)"},".cm-activeLineGutter":{backgroundColor:"rgba(36, 84, 198, 0.08)"},".cm-tooltip":{border:"1px solid #c7d0dd",borderRadius:"7px",boxShadow:"0 12px 28px rgba(28, 39, 56, 0.16)"}}),mu=[(0,ma.Pq)(),(0,ms.pJ)(),(0,ms.bu)((0,ma.cp)()),mo.Lz.lineWrapping,md];function mc(e){let{ariaLabel:t,minHeight:r=96,onChange:i,value:n}=e,a={"--json-editor-min-height":`${r}px`};return(0,s.jsx)("div",{"aria-label":t,className:"json-editor-shell",style:a,children:(0,s.jsx)(ml.Ay,{basicSetup:{autocompletion:!0,bracketMatching:!0,closeBrackets:!0,foldGutter:!0,highlightActiveLine:!0,highlightActiveLineGutter:!0,lineNumbers:!0,searchKeymap:!0},extensions:mu,minHeight:`${r}px`,onChange:i,value:n})})}function mp(e){return rP(e)?Object.fromEntries(Object.entries(e).flatMap(e=>{let[t,r]=e;return rP(r)?[[t,r]]:[]})):{}}async function mh(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/__web_sdk_widget_view_data_templates",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:fetch,r=await t(e,{cache:"no-store",headers:{Accept:"application/json"}});if(!r.ok)throw Error(`加载 Widget viewData 模板失败:HTTP ${r.status} ${r.statusText}`);let i=await r.json();if(!rP(i)||!rP(i.templatesByEntry)&&!rP(i.templatesByWidget))throw Error("Widget viewData 模板接口返回了无效数据");return{templatesByEntry:mp(i.templatesByEntry),templatesByWidget:mp(i.templatesByWidget)}}let mm="输入数据(structuredContent)",mg={};function mf(e){var t,r,i;let{initDataDraft:n,...a}=e,o=hW(a,"card"),[l,d]=(0,iD.useState)("{}"),[u,c]=(0,iD.useState)([]),[p,h]=(0,iD.useState)({templatesByEntry:{},templatesByWidget:{}}),m=(0,iD.useRef)(!1),g=(0,iD.useRef)(o.selectedWidgetId),f=((null==(t=o.state.widgetSelection)?void 0:t.item.entry)??"").replaceAll("\\","/").replace(/^src\//,"").replace(/\.(?:bundle|tsx?|jsx?)$/,""),v=p.templatesByWidget[o.selectedWidgetId]??p.templatesByEntry[f]??mg,y=(0,iD.useMemo)(()=>u.flatMap(e=>{let t=rA(e.content);return"widget"===t.type&&t.id===o.selectedWidgetId?[{...t,sceneName:e.name}]:[]}),[u,o.selectedWidgetId]);(0,iD.useEffect)(()=>{var e;(null==(e=a.controlCommand)?void 0:e.type)==="render_widget"&&a.controlCommand.widgetId===o.selectedWidgetId&&(m.current=!0,d(JSON.stringify(a.controlCommand.structuredContent,null,2)))},[a.controlCommand,o.selectedWidgetId]),(0,iD.useEffect)(()=>{var e;let t=g.current!==o.selectedWidgetId;g.current=o.selectedWidgetId,((null==(e=a.controlCommand)?void 0:e.type)!=="render_widget"||a.controlCommand.widgetId!==o.selectedWidgetId)&&(t&&(m.current=!1),m.current||d(JSON.stringify(v,null,2)))},[v,a.controlCommand,o.selectedWidgetId]),(0,iD.useEffect)(()=>{var e;let t=!0;return h3(null==(e=a.debugContext)?void 0:e.debugScenesEndpoint).then(e=>{t&&c(e.scenes)}).catch(e=>{if(t){var r;c([]),null==(r=o.onMessage)||r.call(o,e.message,!0)}}),()=>{t=!1}},[null==(r=a.debugContext)?void 0:r.debugScenesEndpoint,o.onMessage]);let b=cl(async function(){var e,t;let r=arguments.length>0&&void 0!==arguments[0]&&arguments[0];try{let t=await mh(null==(e=a.debugContext)?void 0:e.widgetViewDataTemplatesEndpoint);r&&(m.current=!1),h(t)}catch(e){h({templatesByEntry:{},templatesByWidget:{}}),null==(t=o.onMessage)||t.call(o,e.message,!0)}});(0,iD.useEffect)(()=>{b()},[null==(i=a.debugContext)?void 0:i.widgetViewDataTemplatesEndpoint,b]);let w=cl(e=>{m.current=!0,d(e)}),_=cl(async()=>{let e=await o.reloadResources();return e&&await b(!0),e});function S(){try{let e=sg(mm,l);o.renderSelectedWidget({initData:{viewData:e}})}catch(t){var e;null==(e=o.onMessage)||e.call(o,t.message,!0)}}return(0,iD.useEffect)(()=>{n&&(m.current=!0,d(JSON.stringify(n,null,2)))},[n]),(0,s.jsx)(pQ,{runtime:{...o,reloadResources:_},children:o.state.widgetSelection?(0,s.jsx)(ck,{highlightRect:o.highlightRect,overlay:(0,s.jsxs)("section",{"aria-label":"卡片调试",className:(0,rL.$)("wsd-widget-card-debug",{"has-rendered-preview":o.hasRenderedPreview}),children:[(0,s.jsx)(cR,{}),(0,s.jsxs)("section",{className:"wsd-widget-card-form",children:[(0,s.jsxs)("label",{className:"wsd-widget-card-template-control",children:[(0,s.jsx)("span",{children:"卡片模板:"}),(0,s.jsx)("span",{className:"wsd-widget-card-template-value",children:o.selectedWidgetId}),(0,s.jsx)(mn,{"aria-hidden":"true"}),(0,s.jsx)("select",{"aria-label":"卡片模板",disabled:0===o.visibleWidgets.length,onChange:e=>o.webSdkDebugger.selectWidget(e.currentTarget.value),value:o.selectedWidgetId,children:o.visibleWidgets.map(e=>(0,s.jsx)("option",{value:e.widgetId,children:e.widgetId},e.widgetId))})]}),y.length>0?(0,s.jsx)("div",{"aria-label":"Debug Scene 预设",className:"wsd-widget-scene-presets",children:y.map(e=>(0,s.jsx)("button",{className:"wsd-widget-scene-preset",onClick:()=>{m.current=!0,d(JSON.stringify(e.resolvedInput,null,2))},type:"button",children:e.sceneName},e.sceneName))}):null,(0,s.jsx)(hK,{JsonEditorComponent:mc,label:mm,minHeight:200,onAction:S,onChange:w,onMessage:o.onMessage,value:l}),(0,s.jsx)("button",{className:"wsd-button wsd-button-primary wsd-widget-card-render-button",onClick:S,type:"button",children:"渲染卡片"})]}),(0,s.jsxs)("section",{className:"wsd-widget-card-preview-section",children:[(0,s.jsx)("span",{children:"以下是卡片渲染预览"}),(0,s.jsxs)("div",{className:"wsd-widget-card-preview-canvas",children:[(0,s.jsx)("div",{className:(0,rL.$)({"wsd-widget-card-preview-target":o.hasRenderedPreview}),ref:o.runtimeTargetRef}),o.hasRenderedPreview?null:(0,s.jsx)("span",{className:"wsd-widget-card-preview-empty",children:"未传入内容"}),o.simulatorUI.overlay,o.sandboxCashier.cashier?(0,s.jsx)(cC,{cashier:o.sandboxCashier.cashier,onCancel:o.sandboxCashier.cancelCashier,onConfirm:o.sandboxCashier.confirmCashier}):null,o.simulatorPermissionPrompt.overlay]})]})]}),runtimeFrameRef:o.runtimeFrameRef,runtimeFrameScaleBoxRef:o.runtimeFrameScaleBoxRef,runtimeScaleMode:o.runtimeScaleMode,runtimeShellRef:o.setRuntimeShellRef,runtimeStyle:o.runtimeStyle}):(0,s.jsx)("div",{className:"wsd-page-empty",children:"No widget"})})}var mv=r(85624);function my(e,t){let r=Math.max(0,e.scrollWidth-e.clientWidth),i=Math.max(0,e.scrollHeight-e.clientHeight);return(r>0||i>0)&&(void 0===t.x||0===t.x||r>0)&&(void 0===t.y||0===t.y||i>0)}async function mb(e,t,r){let i=e.uid?t.getElement(e.uid):null,n=e.uid?i?{element:i,uid:e.uid}:null:function(e,t,r){let i=t.getInspectorSnapshot().root,n=i?[i]:[],a=null;for(let i=0;i<n.length;i+=1){let s=n[i];n.push(...s.children);let o=t.getElement(s.id);if(!o||!my(o,e))continue;let l=function(e,t){if(!e.isConnected)return 0;let r=getComputedStyle(e);if("none"===r.display||"hidden"===r.visibility||"collapse"===r.visibility)return 0;let i=e.getBoundingClientRect(),n=t.getBoundingClientRect();return Math.max(0,Math.min(i.right,n.right)-Math.max(i.left,n.left))*Math.max(0,Math.min(i.bottom,n.bottom)-Math.max(i.top,n.top))}(o,r);l>0&&(!a||l>a.area)&&(a={area:l,element:o,uid:s.id})}return a}(e,t,r);if(!n||!my(n.element,e))return null;let a=Math.max(0,n.element.scrollWidth-n.element.clientWidth),s=Math.max(0,n.element.scrollHeight-n.element.clientHeight);void 0!==e.x&&(n.element.scrollLeft=Math.min(e.x,a)),void 0!==e.y&&(n.element.scrollTop=Math.min(e.y,s)),await new Promise(e=>{requestAnimationFrame(()=>requestAnimationFrame(()=>e()))});let o=Math.max(0,n.element.scrollWidth-n.element.clientWidth),l=Math.max(0,n.element.scrollHeight-n.element.clientHeight);return{uid:n.uid,x:Math.max(0,Math.min(n.element.scrollLeft,o)),y:Math.max(0,Math.min(n.element.scrollTop,l)),maxX:o,maxY:l,viewportWidth:n.element.clientWidth,viewportHeight:n.element.clientHeight}}let mw="wsd-cdp-adapter",m_={jpeg:"image/jpeg",png:"image/png",webp:"image/webp"};function mS(e,t){return{ok:!1,error:{code:e,message:t}}}async function mx(e,t,r,i){if("take_snapshot"===e.type){if(!t||!r||!i)return mS("TARGET_NOT_FOUND","No Page or Widget target is currently rendered");let e=t.getInspectorSnapshot(),n=hb(e.root,e.selectedUid,r);return{ok:!0,result:{runtimeSnapshot:{target:i,root:n.root,nodeCount:n.nodeCount,selectedUid:n.selectedUid,truncated:n.truncated,updatedAtMs:n.updatedAtMs}}}}if(!t||!r)return mS("TARGET_NOT_FOUND","No Page or Widget target is currently rendered");if("scroll_to"===e.type){if(e.uid&&!t.getElement(e.uid))return mS("ELEMENT_NOT_FOUND",`Element uid ${e.uid} was not found`);let i=await mb(e,t,r);return i?{ok:!0,result:i}:mS("SCROLL_FAILED",e.uid?`Element uid ${e.uid} is not scrollable`:"No visible scrollable container was found")}if("get_computed_style"===e.type){let r=t.getComputedStyles(e.uid,e.properties);return r?{ok:!0,result:{uid:e.uid,computedStyle:r}}:mS("ELEMENT_NOT_FOUND",`Element uid ${e.uid} was not found`)}if("get_element_rect"===e.type){let r=t.getElementRect(e.uid);return r?{ok:!0,result:{uid:e.uid,...r}}:mS("ELEMENT_NOT_FOUND",`Element uid ${e.uid} was not found`)}let n=e.uid?t.getElement(e.uid):r;if(!n)return mS("ELEMENT_NOT_FOUND",`Element uid ${e.uid} was not found`);let a=m_[e.format],s=n.getBoundingClientRect(),o=n.offsetWidth||s.width,l=n.offsetHeight||s.height;try{let t=await (0,mv.TC)(n,{height:l,scale:3,type:a,width:o,quality:void 0!==e.quality&&"png"!==e.format?e.quality/100:void 0,onCloneEachNode:e=>{if(!(e instanceof HTMLElement)||"raw-text"!==e.localName)return;let t=e.getAttribute("text");null!==t&&(e.textContent=t)}}),r=`data:${a};base64,`,i=t.startsWith(r)?t.slice(r.length):"";if(!i||i.length>8388608)return mS("SCREENSHOT_FAILED",i?"Screenshot exceeds the 8 MiB debugger limit":"Screenshot returned invalid image data");return{ok:!0,result:{data:i,format:e.format,mimeType:a,width:Math.floor(3*o),height:Math.floor(3*l),uid:e.uid}}}catch(e){return mS("SCREENSHOT_FAILED",e instanceof Error?e.message:String(e))}}function mI(e){let{controlCommand:t,controlTarget:r,debugState:i,frontendUrl:n,onDebugAction:a,onConsoleSnapshotChange:o,onControlResult:l,onHighlightChange:d,onRuntimeSnapshotChange:u,preserveConsoleOnTargetChange:c,resolveTargetAtPoint:p,getRuntimeFrame:h,runtimeFrame:m,runtimeSnapshotTarget:g,showPanelId:f,showPanelRequestId:v,appTarget:y,consoleTarget:b,target:w}=e,_=(0,iD.useRef)(null),S=(0,iD.useRef)(i),x=(0,iD.useRef)(m??null),I=(0,iD.useRef)(y??null),k=(0,iD.useRef)(w),C=(0,iD.useRef)({consoleTarget:b,getRuntimeFrame:h,onConsoleSnapshotChange:o,onDebugAction:a,onHighlightChange:d,onRuntimeSnapshotChange:u,preserveConsoleOnTargetChange:c,resolveTargetAtPoint:p}),E=(0,iD.useRef)(),N=(0,iD.useRef)(null),T=(0,iD.useRef)(null),A=(0,iD.useRef)(null),M=(0,iD.useRef)(null),R=(0,iD.useMemo)(()=>(function(e){let t,r=null==e?void 0:e.trim();if(!r||"u"<typeof window)return null;try{t=new URL(r,window.location.href)}catch{return null}if("http:"!==t.protocol&&"https:"!==t.protocol)return null;t.origin===window.location.origin&&window.localStorage.setItem("navigator-just-my-code","true"),t.searchParams.set("wsdCdpTransport","postmessage");let i=t.searchParams.get("panel");return i&&"wsd-mcp"!==i&&"wsd-view"!==i||t.searchParams.set("panel","wsd-overview"),{origin:t.origin,url:t.toString()}})(n),[n]),j=(null==R?void 0:R.url)??null;C.current={consoleTarget:b,getRuntimeFrame:h,onConsoleSnapshotChange:o,onDebugAction:a,onHighlightChange:d,onRuntimeSnapshotChange:u,preserveConsoleOnTargetChange:c,resolveTargetAtPoint:p};let P=(0,iD.useCallback)(e=>{var t,r;R&&(null==(r=_.current)||null==(t=r.contentWindow)||t.postMessage({source:mw,type:"wsd-show-panel",panelId:e},R.origin))},[R]),L=cl(()=>{var e,t;let r=S.current;r&&R&&(null==(t=_.current)||null==(e=t.contentWindow)||e.postMessage({source:mw,type:"wsd-debug-state",state:r},R.origin))});(0,iD.useEffect)(()=>{x.current=m??null},[m]),(0,iD.useEffect)(()=>{var e;I.current=y??null,null==(e=T.current)||e.call(T)},[y]),(0,iD.useEffect)(()=>{S.current=i,L()},[i,L,j]);let O=cl(()=>{L(),f&&P(f)});return((0,iD.useEffect)(()=>{f&&v&&P(f)},[P,f,v]),(0,iD.useEffect)(()=>{C.current.onHighlightChange(null);let e=null==R?void 0:R.origin;M.current??=document.createElement("div");let t=new u8(k.current??M.current,{consoleTarget:C.current.consoleTarget,getAppTarget:()=>I.current,getRuntimeFrame:()=>C.current.getRuntimeFrame?C.current.getRuntimeFrame():x.current,onHighlightChange:e=>C.current.onHighlightChange(e),get preserveConsoleOnTargetChange(){return C.current.preserveConsoleOnTargetChange},resolveTargetAtPoint:(e,t)=>{var r,i;return(null==(r=(i=C.current).resolveTargetAtPoint)?void 0:r.call(i,e,t))??null}});N.current=t;let r=0,i=e=>{var i;let n=null==(i=t.dispatch({id:--r,method:e}).result)?void 0:i.entries;return Array.isArray(n)?n:[]},n=()=>{var e,t;null==(e=(t=C.current).onConsoleSnapshotChange)||e.call(t,{appEntries:i("WSD.getAppConsoleEntries"),entries:i("WSD.getConsoleEntries"),updatedAtMs:Date.now()})},a=()=>{var e,r,i,n;let a=k.current;if(!a){null==(i=(n=C.current).onRuntimeSnapshotChange)||i.call(n,null);return}let s=t.getInspectorSnapshot();null==(e=(r=C.current).onRuntimeSnapshotChange)||e.call(r,hb(s.root,s.selectedUid,a))},s=t=>{var r,i;e&&(null==(i=_.current)||null==(r=i.contentWindow)||r.postMessage({source:mw,type:"cdp-raw-message",message:JSON.stringify(t)},e))};T.current=n,A.current=a;let o=t.subscribe(e=>{"WSD.consoleUpdated"===e.method||"WSD.appConsoleUpdated"===e.method?n():(s(e),("DOM.documentUpdated"===e.method||"DOM.inlineStyleInvalidated"===e.method||"Overlay.inspectNodeRequested"===e.method)&&a())});s({method:"DOM.documentUpdated"}),n(),a();let l=r=>{var i,n,a,o,l,d,u,c,p;if(!e||r.source!==(null==(i=_.current)?void 0:i.contentWindow)||r.origin!==e)return;let h=r.data;if((null==h?void 0:h.source)==="wsd-chrome-devtools-frontend"){if("ready"===h.type)return void O();if("wsd-debug-ready"===h.type)return void L();if("wsd-debug-action"===h.type){let e=h.action;if((null==e?void 0:e.kind)==="clear-sandbox-bridge-logs"||(null==e?void 0:e.kind)==="clear-trace-filter"||(null==e?void 0:e.kind)==="open-location-settings"){null==(n=(a=C.current).onDebugAction)||n.call(a,e);return}if((null==e?void 0:e.kind)==="update-sandbox-business-info"&&"string"==typeof e.phoneNum&&"string"==typeof e.csrPem){null==(o=(l=C.current).onDebugAction)||o.call(l,e);return}if((null==e?void 0:e.kind)==="recreate-sandbox-session"&&"string"==typeof e.phoneNum&&"string"==typeof e.csrPem){null==(d=(u=C.current).onDebugAction)||d.call(u,e);return}e&&("approve-tool-call"===e.kind||"reject-tool-call"===e.kind)&&"string"==typeof e.toolCallId&&(null==(c=(p=C.current).onDebugAction)||c.call(p,e));return}if("wsd-preact-devtools-message"===h.type)return void t.sendPreactDevtoolsMessage(h.payload);if("wsd-preact-highlight"===h.type){let e=h.uniqueId;t.highlightLynxNode("number"==typeof e?e:null);return}if("cdp-raw-message"===h.type&&"string"==typeof h.message){let e;try{e=JSON.parse(h.message)}catch{return}s(t.dispatch(e));return}}},d=t=>{let r=t.detail;if((null==r?void 0:r.type)==="PreactDevtools"&&"string"==typeof r.data)try{var i,n,a;i={type:"wsd-preact-devtools-message",payload:JSON.parse(r.data)},e&&(null==(a=_.current)||null==(n=a.contentWindow)||n.postMessage({source:mw,...i},e))}catch{}};return e&&(window.addEventListener("message",l),document.addEventListener("devtoolMessage",d)),()=>{window.removeEventListener("message",l),document.removeEventListener("devtoolMessage",d),o(),T.current===n&&(T.current=null),A.current===a&&(A.current=null),N.current===t&&(N.current=null),t.destroy(),C.current.onHighlightChange(null)}},[O,L,R]),(0,iD.useEffect)(()=>{var e,t,r,i;k.current=w,M.current??=document.createElement("div"),null==(e=N.current)||e.setConsoleTarget(b),null==(t=N.current)||t.setTarget(w??M.current),null==(r=T.current)||r.call(T),null==(i=A.current)||i.call(A)},[b,w]),(0,iD.useEffect)(()=>{if(!t||"render_page"===t.type||"render_widget"===t.type||"set_viewport"===t.type||"submit_chat_query"===t.type||"execute_sandbox_tool_call"===t.type||E.current===t.commandId)return;let e=void 0===r?k.current:r;if(("take_snapshot"===t.type||"take_screenshot"===t.type&&!t.uid)&&(!e||"take_snapshot"===t.type&&!g)){let e=window.setTimeout(()=>{E.current!==t.commandId&&(E.current=t.commandId,null==l||l(t.commandId,mS("TARGET_NOT_FOUND","No Page or Widget target is currently rendered")))},2e3);return()=>window.clearTimeout(e)}E.current=t.commandId,(async()=>{let r;try{r=await mx(t,N.current,e,g)}catch(e){r=mS("take_screenshot"===t.type?"SCREENSHOT_FAILED":"take_snapshot"===t.type?"SNAPSHOT_FAILED":"scroll_to"===t.type?"SCROLL_FAILED":"INSPECTION_FAILED",e instanceof Error?e.message:String(e))}null==l||l(t.commandId,r)})()},[t,r,l,g,w]),j)?(0,s.jsx)("aside",{className:"wsd-chrome-devtools",children:(0,s.jsx)("iframe",{allow:"clipboard-write",className:"wsd-chrome-devtools-frame",onLoad:O,ref:_,sandbox:"allow-scripts allow-same-origin allow-forms",src:j,title:"Chrome DevTools"})}):(0,s.jsx)("aside",{className:"wsd-chrome-devtools",children:(0,s.jsx)("div",{className:"wsd-chrome-devtools-empty",children:"Chrome DevTools frontend is not configured"})})}function mk(e,t,r){return Math.min(Math.max(e,t),r)}function mC(e,t,r,i){if(!t)return mk(e,r,i);let n=t.getBoundingClientRect().width;if(!n)return mk(e,r,i);let a=Math.min(i,Math.max(r,n-8-340));return mk(e,r,a)}function mE(){let{localConnectionStatus:e,reconnect:t}=cJ();return"disconnected"!==e?null:(0,s.jsxs)("div",{className:"wsd-local-debug-connection-warning",role:"alert",children:[(0,s.jsx)("span",{children:"与本地调试服务的链接已断开"}),(0,s.jsx)("button",{onClick:t,type:"button",children:"重新连接"})]})}function mN(e){var t;let{activeView:r="conversation",className:i,onActiveViewChange:n,...a}=e,o=cg(a.webSdkDebugger),l="tool"===r&&0===Object.keys(o.manifest.raw.tools??{}).length?"conversation":r,[d,u]=(0,iD.useState)(me),[c,p]=(0,iD.useState)(),[h,m]=(0,iD.useState)("page"===l),[g,f]=(0,iD.useState)("conversation"===l),v=(0,iD.useRef)(null),y=cl(e=>{v.current=e}),b=cl(e=>{var t;return(null==(t=v.current)?void 0:t.navigateBack(e))??!1}),w=cl(()=>{var e;null==(e=v.current)||e.exitApp(),null==n||n("conversation")}),[_,S]=(0,iD.useState)({onHighlightChange:()=>void 0,target:null}),x=cl(e=>{S(e)}),{isResizing:I,panelStyle:k,separatorProps:C}=function(){let{defaultWidth:e=520,minWidth:t=420,maxWidth:r=640}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},[i,n]=(0,iD.useState)(e),[a,s]=(0,iD.useState)(!1),o=(0,iD.useRef)(null),l=(0,iD.useMemo)(()=>({"--wsd-preview-column-width":`${i}px`}),[i]),d=cl((e,i)=>{if(!i)return;let a=i.getBoundingClientRect();a.width&&n(mC(e-a.left,i,t,r))});(0,iD.useEffect)(()=>()=>{var e;null==(e=o.current)||e.call(o)},[]);let u=cl(e=>{var t,r;if(0!==e.button)return;let i=e.currentTarget,n=i.parentElement;if(!n)return;e.preventDefault(),null==(t=o.current)||t.call(o),null==(r=i.setPointerCapture)||r.call(i,e.pointerId),d(e.clientX,n),s(!0);let a=document.body.style.cursor,l=document.body.style.userSelect;document.body.style.cursor="col-resize",document.body.style.userSelect="none";let u=e=>{d(e.clientX,n)},c=()=>{o.current===c&&(o.current=null,window.removeEventListener("pointermove",u),window.removeEventListener("pointerup",c),window.removeEventListener("pointercancel",c),document.body.style.cursor=a,document.body.style.userSelect=l,s(!1))};o.current=c,window.addEventListener("pointermove",u),window.addEventListener("pointerup",c),window.addEventListener("pointercancel",c)}),c=cl(e=>{let i=e.currentTarget.parentElement;if("ArrowLeft"===e.key){e.preventDefault(),n(e=>mC(e-24,i,t,r));return}if("ArrowRight"===e.key){e.preventDefault(),n(e=>mC(e+24,i,t,r));return}if("Home"===e.key){e.preventDefault(),n(mC(t,i,t,r));return}"End"===e.key&&(e.preventDefault(),n(mC(r,i,t,r)))});return{isResizing:a,panelStyle:l,separatorProps:{"aria-label":"Resize preview and DevTools","aria-orientation":"vertical","aria-valuemax":r,"aria-valuemin":t,"aria-valuenow":Math.round(i),onKeyDown:c,onPointerDown:u,role:"separator",tabIndex:0}}}({defaultWidth:340,maxWidth:560,minWidth:300}),E={...a,onWidgetNavigateBack:b,onWidgetExitApp:w,onChromeDevToolsPanelChange:x};(0,iD.useEffect)(()=>{"ready"===o.status.type&&r!==l&&(null==n||n(l))},[l,n,r,o.status.type]),(0,iD.useEffect)(()=>{"page"===l&&m(!0),"conversation"===l&&f(!0)},[l]);let N="tool"===l?(0,s.jsx)(mi,{...E,onActiveViewChange:n,onSessionChange:u,onUseWidgetOutput:e=>{let{viewData:t,widgetId:r}=e;a.webSdkDebugger.selectWidget(r),p(t),null==n||n("card")},session:d}):"card"===l?(0,s.jsx)(mf,{...E,initDataDraft:c,onActiveViewChange:n}):null;return(0,s.jsxs)("section",{className:(0,rL.$)("page"===l?"wsd-page-panel":"wsd-widget-panel",I&&"is-resizing",i),style:k,children:[(0,s.jsxs)(cG,{enabled:!!((null==(t=a.debugContext)?void 0:t.sandboxEventsAvailable)&&!1!==a.debugContext.sandboxSessionAvailable),connection:a.connection,onMessage:a.onMessage,webSdkDebugger:a.webSdkDebugger,children:[(0,s.jsx)(mE,{}),"page"===l||h?(0,s.jsx)(h9,{...E,activeView:l,onActiveViewChange:n,onControllerChange:y}):null,"conversation"===l||g?(0,s.jsx)("div",{hidden:"conversation"!==l,style:{display:"conversation"===l?"contents":"none"},children:(0,s.jsx)(hH,{...E,activeView:l,controlCommand:"conversation"===l?a.controlCommand:void 0,onActiveViewChange:n,onChromeDevToolsPanelChange:"conversation"===l?x:void 0})}):null,N]}),(0,s.jsx)("div",{className:"wsd-runtime-splitter",...C}),(0,s.jsx)(mI,{..._})]})}function mT(e,t){var r,i,n;null==e||e({category:(null==(r=t.event)?void 0:r.startsWith("simulator_manifest_"))||(null==(i=t.event)?void 0:i.startsWith("simulator_skill_"))||(null==(n=t.event)?void 0:n.startsWith("simulator_resources_"))?"resource":"mcp",source:"local_mcp",...t})}function mA(e){return rR(e,{allowRootRelative:!0,baseUrl:window.location.href})}function mM(e){let t=function(e){let t={};for(let r of["content-type","content-length","x-tt-logid"]){let i=e.headers.get(r);i&&(t[r]=i)}return t}(e);return{status:e.status,status_text:e.statusText,response_headers:Object.keys(t).length>0?t:void 0}}function mR(e,t,r){mT(e,{event:`simulator_${t}_fetch_started`,phase:"request",url:r})}function mj(e,t,r,i){let n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};mT(e,{event:`simulator_${t}_fetch_succeeded`,phase:"response",url:r,...mM(i),...n})}function mP(e,t,r,i,n){mT(e,{event:`simulator_${t}_fetch_failed`,phase:"error",url:r,...n?mM(n):{},error:i instanceof Error?i.message:String(i)})}function mL(e,t,r){return Error(`Simulator ${e} failed: ${r.status} ${r.statusText} (${t})`)}let mO="web-sdk-debugger-demo",mD="mock_local_mcp",mU="mock_lookup",mq=["template-transport-card","template-price-action-card","weather-card","flight-card","api-demo-card","summary-card","configured-widget-id"],m$=[{server_id:mD,name:"Mock Local MCP",description:"Web SDK Debugger 本地模拟 MCP server",tools:[{name:mU,description:"返回用于本地调试的应用插件结构化结果",input_schema_json:JSON.stringify({type:"object",properties:{keyword:{type:"string"}},required:["keyword"]})}]}];function mB(e,t){return`id: evt_mock_${t.toString().padStart(4,"0")}
|
|
47
48
|
event: ${e.event}
|
|
48
49
|
data: ${JSON.stringify(e)}
|
|
49
50
|
|
|
50
|
-
`}function mL(e,t){return t.find(t=>null==e?void 0:e.widgets.some(e=>e.widgetId===t))}function mO(e,t,r,i){var n;return{event:t,request_id:i.requestId,reply_message_id:i.replyMessageId,trace:{trace_id:(null==(n=e.trace)?void 0:n.trace_id)||`trace_mock_${e.idempotency_key??i.requestId}`,component:"mock_simulator",stage:t,sampled:!0},...r}}let mD=async e=>{var t;let r=`找到和 ${(null==(t=e.arguments)?void 0:t.keyword)||"调试数据"} 相关的模拟结果`,i={content:[{type:"text",text:r}],structuredContent:{entities:[{entity_type:"debug_item",entity_id:"debug-item-1",name:"调试示例数据"}]},isError:!1},n=JSON.stringify(i);return{status:"succeeded",result:i.structuredContent,raw_result_text:r,raw_mcp_result_json:n,miniapp:{is_mini_app:!0,mcp_channel:"flow_miniapp"},debug:{mock:!0}}},mU=n0(nX),mq=dI({requestHandler:async(e,t,r)=>{let i=e.params,n=r??nJ(i);return nF(n.url,"request"),nB(async t=>{var r,a;let s,o,l=await fetch("/__web_sdk_request_proxy__",{signal:t,body:JSON.stringify((s=new Headers(n.headers),{data:(o=n.body instanceof ArrayBuffer)?nH(n.body):n.body,dataEncoding:o?"base64":void 0,header:Object.fromEntries(s),method:n.method,url:n.url})),headers:{"content-type":"application/json"},method:"POST"}),d=(null==(r=l.headers.get("content-type"))?void 0:r.toLowerCase())??"",u=await l.text();if(!d.includes("application/json"))throw Error(`Request proxy returned a non-JSON response. Make sure the debugger is started with the local request proxy. Response starts with: ${u.slice(0,120)}`);let c=u?JSON.parse(u):{};if(!l.ok)throw Error((null==c?void 0:c.message)||`Request proxy failed with status ${l.status}`);if((null==c?void 0:c.dataEncoding)==="base64"&&"string"==typeof c.data){let t=nV((a=c.data,Uint8Array.from(atob(a),e=>e.charCodeAt(0)).buffer),i.dataType);return _(e,{statusCode:c.statusCode,header:c.header,data:t})}return _(e,c)})}});function m$(e,t){if(e.has(t))return!1;if(e.add(t),e.size>100){let t=e.values().next().value;t&&e.delete(t)}return!0}function mB(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";return new URL(window.location.href).searchParams.get(e)||r||t}async function mF(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:fetch;try{var t;let r=await e("/__web_sdk_debug_context",{cache:"no-store",headers:{Accept:"application/json"}});return r.ok?!(t=await r.json())||"object"!=typeof t||Array.isArray(t)?{}:t:{}}catch{return{}}}async function mz(e,t){let r=t.skills,i=t.mcpServers,n=[];if("function"==typeof r&&n.push(Promise.resolve(r()).catch(()=>void 0)),"function"==typeof i){let t=e.getState();n.push(Promise.resolve(i({appKey:t.manifest.appId,appName:t.manifest.name,manifest:t.manifest.raw})).catch(()=>void 0))}await Promise.all(n)}function mW(){return(0,s.jsx)("main",{className:"chrome-devtools-unavailable-page",children:(0,s.jsx)("section",{className:"wsd-chrome-devtools",children:(0,s.jsx)("div",{className:"wsd-chrome-devtools-empty",children:"Chrome DevTools frontend is unavailable"})})})}function mH(e){let{serverDebugContext:t}=e,r=(0,iD.useMemo)(()=>(function(e){let t=e.searchParams.get("messages");if(null!==t)try{let e=JSON.parse(t);if(Array.isArray(e))return e;console.error("Failed to read initial messages: messages must be an array")}catch(e){console.error("Failed to read initial messages",e)}})(new URL(window.location.href)),[]),i=(0,iD.useMemo)(()=>new URL(window.location.href).searchParams.get("manifest")||nZ,[]),n=void 0!==r,a=(0,iD.useMemo)(()=>mB("mcp","",void 0),[]),o=(0,iD.useMemo)(()=>{let e;return(e=new URL(window.location.href)).searchParams.get("mcpOriginal")||e.searchParams.get("mcpEndpoint")||""},[]),l=(0,iD.useMemo)(()=>mB("simulatorManifest","/__simulator_manifest/manifest.yaml",void 0),[]),d=(0,iD.useMemo)(()=>new URL(window.location.href).searchParams.get("simulatorManifestOriginal")||"",[]),u=(0,iD.useMemo)(()=>mB("simulatorSkills","/__simulator_skills/index.json",void 0),[]),c=(0,iD.useMemo)(()=>new URL(window.location.href).searchParams.get("simulatorSkillsOriginal")||"",[]),p=(0,iD.useMemo)(()=>n0(new URL(window.location.href).searchParams.get("simulator")||mU),[]),h=(0,iD.useMemo)(()=>{let e;return(e=new URL(window.location.href)).searchParams.get("launchDir")||e.searchParams.get("projectPath")||e.searchParams.get("cwd")||""},[]),m=(0,iD.useMemo)(()=>`${window.location.origin}${window.location.pathname}`,[]),g=(0,iD.useMemo)(()=>{let e;return null!==(e=new URL(window.location.href).searchParams.get("DEBUG"))&&"0"!==e&&"false"!==e.toLowerCase()},[]),f=(0,iD.useMemo)(()=>"1"===new URL(window.location.href).searchParams.get("simulatorMock")||"true"===String((void 0)??"").toLowerCase(),[]),v=(0,iD.useRef)(null),y=(0,iD.useMemo)(()=>new iL,[]),b=y.clientId,[w,_]=(0,iD.useState)(),S=(0,iD.useRef)(new Set),x=(0,iD.useMemo)(()=>(function(e){var t,r,i,n,a,s;let o,l,d=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},u={mcpEndpoint:mx((t={mcpEndpoint:e,simulatorManifestUrl:d.simulatorManifestUrl,simulatorSkillsIndexUrl:d.simulatorSkillsIndexUrl}).mcpEndpoint),simulatorManifestUrl:mx(t.simulatorManifestUrl),simulatorSkillsIndexUrl:mx(t.simulatorSkillsIndexUrl)},c=function(){let e,t,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{mcpServers:async e=>{let t=Object.entries(Object.fromEntries(Object.entries((e.manifest??{}).tools??{}).filter(e=>{let[,t]=e;return!0===t.is_client_tool}))).map(e=>{let[t,r]=e;return{name:t,description:r.description,input_schema_json:function e(t){if(Array.isArray(t))return t.map(e);if(!rP(t))return t;let r={};for(let[i,n]of Object.entries(t))r[i]="type"===i&&"int"===n?"integer":"type"===i&&"float"===n?"number":e(n);return r}(r.input_schema)}});return 0===t.length?(aW(r.onTraceEvent,{event:"client_tools_empty",app_key:e.appKey,server_id:aB,tool_count:0,tools:[]}),[]):(aW(r.onTraceEvent,{event:"client_tools_resolved",app_key:e.appKey,server_id:aB,tool_count:t.length,tools:t.map(e=>e.name)}),[{server_id:aB,name:"Client Tool",description:"Client Tool runtime for simulator debugging",tools:t}])},toolExecutor:((t=async t=>{let i,n;try{i=function(e){let t=e.arguments;if(void 0===t){if(void 0===e.argumentsJson)t={};else if(void 0===(t=r3(e.argumentsJson)))throw Error("Tool arguments must be valid JSON")}if(!rP(t))throw Error("Tool arguments must be a JSON object");return t}(t),n="string"==typeof t.argumentsJson&&t.argumentsJson.trim()?t.argumentsJson:r5(i)}catch(e){return aK("CLIENT_TOOL_INVALID_ARGUMENTS",r6(e),!1)}try{var a;aW(r.onTraceEvent,{event:"client_tool_call_started",request_id:t.requestId,trace_id:t.trace.trace_id,app_key:t.appKey,server_id:t.serverId,tool_call_id:t.toolCallId,tool_name:t.toolName,arguments:i,arguments_json:r5(i)});let s=await (()=>{var t,i;let n=null==(t=r.getRuntimeUrl)?void 0:t.call(r);if(!n)throw Error("Client Tool runtime is unavailable. Build the app with a Web Client Tool entry.");if(!e||e.runtimeUrl!==n){null==e||e.dispose();let t=(r.runtimeFactory??function(e,t){return new aH(e,t)})(n,null==(i=r.getRuntimeGlobalProps)?void 0:i.call(r));e=new aJ(n,t,r.onTraceEvent),aW(r.onTraceEvent,{event:"client_tool_runtime_started",runtime_url:n})}return e})().invokeTool({toolId:t.toolName,input:n,context:{callbackId:t.toolCallId,conversationId:t.requestId,featureMap:void 0,msgId:t.replyMessageId,questionId:t.requestId},signal:t.signal}),o=function(e,t){var r,i;if(0===e.result)try{let i=function(e,t){if(!rP(e)||!Array.isArray(e.content))throw Error(`Client Tool "${t}" must return an MCP tool output object`);return e}(e.output,t.toolName),n=!0===i.isError?i:function(e,t){let r=aU(t.manifest,t.toolName);if(!r||"string"!=typeof r.kind)throw Error(`Client Tool "${t.toolName}" manifest output is required`);if("execution_result"===r.kind)return e;if("entities"!==r.kind)throw Error(`Client Tool "${t.toolName}" has unsupported output kind "${r.kind}"`);if(!rP(e)||!Array.isArray(e.structuredContent))throw Error(`Client Tool "${t.toolName}" must return structuredContent as an array`);return aq(e,t.manifest,t.toolName)}(i,t);return r=a$(n,{businessErrorCode:"CLIENT_TOOL_BUSINESS_ERROR",protocol:az,source:"client_tool"}),{...r,debug:{...r.debug,mcp_output:i}}}catch(e){return aK("CLIENT_TOOL_INVALID_RESULT",r6(e),!1)}let n=void 0===(i=e.reason)?"":rP(i)?"string"==typeof i.message?i.message:r5(i):r6(i);return 2===e.result?aK("CLIENT_TOOL_NOT_FOUND",`Client Tool not found: ${e.toolId}`,!1):1===e.result?aK("CLIENT_TOOL_FAILED",n||`Client Tool failed: ${e.toolId}`,!1):aK("CLIENT_TOOL_UNKNOWN_RESULT",`Client Tool returned unknown status: ${String(e.result)}`,!1)}(s,t);return aW(r.onTraceEvent,{event:"succeeded"===o.status?"client_tool_call_succeeded":"client_tool_call_failed",request_id:t.requestId,app_key:t.appKey,server_id:t.serverId,tool_call_id:t.toolCallId,tool_name:t.toolName,status:o.status,result:o.result,raw_mcp_result_json:o.raw_mcp_result_json,error:null==(a=o.error)?void 0:a.message}),o}catch(i){let e=r6(i);return aW(r.onTraceEvent,{event:"client_tool_call_failed",request_id:t.requestId,app_key:t.appKey,server_id:t.serverId,tool_call_id:t.toolCallId,tool_name:t.toolName,error:e}),aK("CLIENT_TOOL_CALL_FAILED",e,!0)}}).dispose=()=>{null==e||e.dispose(),e=void 0},t)}}({getRuntimeGlobalProps:d.getClientToolRuntimeGlobalProps,getRuntimeUrl:d.getClientToolRuntimeUrl,onTraceEvent:d.onTraceEvent}),p=c.toolExecutor,h=c.mcpServers,m=()=>{var e;return l??=Promise.resolve(u.mcpEndpoint||(null==(e=d.getMcpEndpoint)?void 0:e.call(d))).then(e=>{let t=mx(e);return o=t?function(e){let t=rR(e.endpoint);if(!t)return{};let r=function(e,t){if(null==t?void 0:t.trim())return t.trim();let r=new URL(e);return`${r.hostname}_${r.port||r.protocol.replace(":","")}${r.pathname}`.replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/^_+|_+$/g,"")||"local_mcp"}(t,e.serverId);return{mcpServers:async i=>{let n;try{dC(e.onTraceEvent,{event:"local_mcp_tools_load_started",app_key:i.appKey,mcp_endpoint:t,server_id:r},i),n=await dN(t,{...e,signal:i.signal});let a=await n.client.listTools(void 0,{signal:i.signal}),s=n.client.getServerVersion(),o={server_id:r,name:(null==s?void 0:s.name)||r,description:n.client.getInstructions()||"",tools:a.tools.map(dE).filter(e=>e.name)};return dC(e.onTraceEvent,{event:"local_mcp_tools_loaded",app_key:i.appKey,mcp_endpoint:t,server_id:o.server_id,server_version:s,tools:o.tools.map(e=>e.name)},i),[o]}catch(n){var a;return null==(a=i.signal)||a.throwIfAborted(),dC(e.onTraceEvent,{event:"local_mcp_tools_load_failed",app_key:i.appKey,mcp_endpoint:t,server_id:r,error:r6(n),request_will_continue:!0,tool_count:0,tools:[]},i),console.warn("[web-sdk-debugger] Failed to load MCP tools",n),[]}finally{n&&await dT(n)}},toolExecutor:async r=>{var i;let n,a=r.arguments??r3(r.argumentsJson)??{},s=r.argumentsJson||r5(a),o=Date.now();try{dC(e.onTraceEvent,{event:"local_mcp_call_started",request_id:r.requestId,trace_id:r.trace.trace_id,app_key:r.appKey,server_id:r.serverId,tool_call_id:r.toolCallId,tool_name:r.toolName,arguments:a,arguments_json:s,mcp_endpoint:t}),n=await dN(t,{...e,signal:r.signal,headers:function(e,t){if(!e&&!t)return;let r=new Headers(e);for(let[e,i]of Object.entries(t??{}))r.set(e,i);return r}(e.headers,r.headers)}),null==(i=r.signal)||i.throwIfAborted();let l=await n.client.callTool({name:r.toolName,arguments:a,_meta:{request_id:r.requestId,trace_id:r.trace.trace_id,app_key:r.appKey,server_id:r.serverId,tool_call_id:r.toolCallId,tool_name:r.toolName,arguments_json:s}},{signal:r.signal}),d=!0===l.isError?l:aq(l,r.manifest,r.toolName),u=a$(d,{businessErrorCode:"LOCAL_MCP_BUSINESS_ERROR",protocol:"streamable_http",source:"local_mcp"});return u.debug={...u.debug,mcp_output:l},dC(e.onTraceEvent,{event:"local_mcp_call_succeeded",request_id:r.requestId,trace_id:r.trace.trace_id,app_key:r.appKey,server_id:r.serverId,tool_call_id:r.toolCallId,tool_name:r.toolName,status:u.status,result:u.result,raw_result_text:u.raw_result_text,raw_mcp_result:d,elapsed_ms:Date.now()-o,mcp_endpoint:t}),u}catch(n){if(aT(n))throw n;let i=r6(n);return dC(e.onTraceEvent,{event:"local_mcp_call_failed",request_id:r.requestId,trace_id:r.trace.trace_id,app_key:r.appKey,server_id:r.serverId,tool_call_id:r.toolCallId,tool_name:r.toolName,error:i,elapsed_ms:Date.now()-o,mcp_endpoint:t}),{status:"failed",result:{error:i},error:{code:"LOCAL_MCP_CALL_FAILED",message:i,retryable:!0,stage:"tool_execute"},raw_result_text:i}}finally{n&&await dT(n)}}}}({endpoint:t,onTraceEvent:d.onTraceEvent}):void 0})},g=async e=>{let[t,r]=await Promise.all([m(),h(e)]);if(!t)return r;let i=t.mcpServers;return[...await i(e),...r]},f=async e=>{if(e.serverId===aB)return p(e);let t=await m();if(!t){let e="Local MCP is not configured";return{status:"failed",result:{error:e},error:{code:"LOCAL_MCP_NOT_CONFIGURED",message:e,retryable:!1,stage:"tool_execute"},raw_result_text:e}}return t.toolExecutor(e)};return f.dispose=()=>{var e,t,r;null==(e=p.dispose)||e.call(p),null==o||null==(r=o.toolExecutor)||null==(t=r.dispose)||t.call(r)},{simulatorManifest:u.simulatorManifestUrl?(r=u.simulatorManifestUrl,i=d.onTraceEvent,n=d.getAppId,async e=>{let t;mk(i,"manifest",r);try{if(!(t=await fetch(r,{signal:e,cache:"no-store",headers:{Accept:"application/yaml, text/yaml, text/x-yaml, application/json, text/plain"}})).ok)throw mN("manifest",r,t);let a=await t.text(),s=function(e){let t=(0,aD.qg)(e);if(!rP(t))throw Error("Simulator manifest must be a YAML object");return t}(a),o=s.app_key?void 0:await (null==n?void 0:n());if(n&&!o&&!s.app_key)throw Error("Sandbox 调试应用尚未就绪,请重建调试会话后重试。");let l=o?{...s,app_key:o}:s;return mC(i,"manifest",r,t,{bytes:a.length}),{...l,raw_manifest_yaml:o?(0,aD.As)(l):a}}catch(e){throw mE(i,"manifest",r,e,t),console.warn("[web-sdk-debugger] Failed to load simulator manifest supplement",e),e}}):void 0,skills:u.simulatorSkillsIndexUrl?(a=u.simulatorSkillsIndexUrl,s=d.onTraceEvent,async e=>{let t;mk(s,"skill",a);try{var r;if(!(t=await fetch(a,{signal:e,cache:"no-store",headers:{Accept:"application/json"}})).ok)throw mN("skill",a,t);let i=await t.text();if(((null==(r=t.headers.get("content-type"))?void 0:r.toLowerCase())??"").includes("text/html")||/^<!doctype html\b|^<html[\s>]/i.test(i.trimStart()))throw Error(`Simulator skills index returned HTML instead of JSON (${a})`);let n=function(e){if(!rP(e)||!Array.isArray(e.skills))throw Error("Simulator skills index must contain a skills array");return e.skills.map((e,t)=>{var r;if(!(rP(r=e)&&"string"==typeof r.relativePath&&"string"==typeof r.content))throw Error(`Simulator skills index contains an invalid entry at index ${t}`);return e}).sort((e,t)=>e.relativePath<t.relativePath?-1:+(e.relativePath>t.relativePath))}(JSON.parse(i));return mC(s,"skill",a,t,{bytes:i.length,skill_paths:n.map(e=>e.relativePath)}),n}catch(e){throw mE(s,"skill",a,e,t),console.warn("[web-sdk-debugger] Failed to load simulator skills",e),e}}):void 0,mcpServers:g,toolExecutor:f}})(a,{getClientToolRuntimeGlobalProps:()=>{var e;let t=null==(e=v.current)?void 0:e.getState().manifest;return t?t$(t):void 0},getClientToolRuntimeUrl:()=>{var e;let t=null==(e=v.current)?void 0:e.getState();return t?function(e,t,r){var i,n,a,s,o,l;let d,u=(null==(a=t.applet)||null==(n=a.web)||null==(i=n.toolRuntimeEntry)?void 0:i.trim())||(null==(o=t.applet)||null==(s=o.toolRuntimeEntry)?void 0:s.trim());if(!u)return;let c=new URL(u,((d=new URL(String(e),(null==(l=globalThis.location)?void 0:l.href)||"http://localhost/")).pathname.endsWith("/base/manifest.json")?d.pathname=d.pathname.slice(0,-18):d.pathname=d.pathname.replace(/\/[^/]*$/,"/"),d.search="",d.hash="",d));return r&&c.searchParams.set("__doubao_resource_reload",r),c.toString()}(t.manifestUrl,t.manifest.raw,t.resourceUrlVersion):void 0},getMcpEndpoint:async()=>t.mcpProxyEndpoint,getAppId:async()=>(await mF()).sandboxAppId,onTraceEvent:e=>{var t;return null==(t=v.current)?void 0:t.appendSimulatorTraceEvent(e)},simulatorManifestUrl:l,simulatorSkillsIndexUrl:u}),[a,l,u,t.mcpProxyEndpoint]),I=(0,iD.useMemo)(()=>{let e=f?{appKey:mT,appName:"调试示例应用插件",mcpServers:mj,simulatorFetch:function(e){let{getDebuggerState:t}=e;return async(e,r)=>{var i,n,a,s,o,l,d,u;let c,p,h,m,g,f,v,y,b=String(e);if(b.endsWith("/simulator/tool/report")){let e="string"==typeof(null==r?void 0:r.body)?JSON.parse(r.body):{};return new Response(JSON.stringify({code:0,message:"OK",request_id:e.request_id,tool_call_id:e.tool_call_id,trace:e.trace}),{headers:{"Content-Type":"application/json"},status:200,statusText:"OK"})}return b.endsWith("/simulator/chat")?(y=(i="string"!=typeof(null==r?void 0:r.body)?{}:JSON.parse(r.body),s=t(),p=((c=new URL(window.location.href).searchParams.get("simulatorMockWidget"))?mL(s,[c]):void 0)||mL(s,mR)||(null==s||null==(o=s.widgetSelection)?void 0:o.item.widgetId)||(null==(l=s)||null==(d=l.widgets.find(e=>{var t;return null==(t=e.web)?void 0:t.entry}))?void 0:d.widgetId)||(null==l||null==(u=l.widgets[0])?void 0:u.widgetId)||"weather-card",h=Date.now().toString(36),m={requestId:`req_mock_server_${h}`,replyMessageId:`msg_mock_reply_${h}`},g=(null==(n=i.message)?void 0:n.content)||"模拟请求",f=`call_mock_${h}`,v={applet_id:i.app_id||mT,widget_id:p,entity_id:"mock-entity-1",viewData:{source:"web-sdk-debugger-mock",keyword:g,widgetId:p},extra:{"doubao/outputTemplate":"mock.output.template"}},[mO(i,"ack",{ack:{request_id:m.requestId,message_id:m.replyMessageId,local_message_id:null==(a=i.message)?void 0:a.local_message_id}},m),mO(i,"tool_call",{tool_call:{tool_call_id:f,tool_name:mM,server_id:mA,app_key:i.app_id||mT,arguments_json:JSON.stringify({keyword:g}),status:"PENDING",timeout_ms:2e3}},m),mO(i,"tool_status",{tool_status:{tool_call_id:f,status:"RUNNING",progress:.6,message:"Mock tool running"}},m),mO(i,"text_delta",{text_delta:{block_id:"block_mock_text",op:"append",delta:`Mock 已收到:${g}`}},m),mO(i,"card_delta",{card_delta:{block_id:"block_mock_card",op:"append",card_id:`card_mock_${h}`,source_tool_call_id:f,source_entity_ids:["mock-entity-1"],is_final:!0,card:{card_id:`card_mock_${h}`,card_type:"mock_widget_card",title:"Mock 应用插件卡片",fallback_text:`使用 ${p} 渲染`,props_json:JSON.stringify(v)}}},m),mO(i,"debug",{debug_event:{category:"mock",title:"Mock Simulator",summary:"本地 mock SSE 已生成 text/card/tool 事件",data:{widget_id:p},redaction_level:"none"}},m),mO(i,"answer_finish",{answer_finish:{status:"completed",finish_reason:"stop",usage:{output_tokens:12}}},m),mO(i,"reply_finish",{reply_finish:{status:"completed",finish_reason:"stop",event_count:7}},m)]).map(mP).join(""),new Response(new ReadableStream({start(e){e.enqueue(new TextEncoder().encode(y)),e.close()}}),{headers:{"Content-Type":"text/event-stream"},status:200,statusText:"OK"})):new Response(JSON.stringify({ok:!1,error:"Unknown mock simulator endpoint"}),{status:404,statusText:"Not Found"})}}({getDebuggerState:()=>{var e;return(null==(e=v.current)?void 0:e.getState())??null}}),toolExecutor:mD}:{},t=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return new si(e)}({manifestUrl:i,simulatorEndpoint:p,...x,...e});return r&&t.pushMessages(r),v.current=t,t},[i,p,x,f,r]),[k,C]=(0,iD.useState)(()=>{let e,t,r;return t=(e=new URL(window.location.href)).searchParams.get("view"),r=e.searchParams.get("debugMode")||e.searchParams.get("mode"),"conversation"===t||"tool"===t||"card"===t||"page"===t?t:"conversation"===r||"tool"===r||"card"===r||"page"===r?r:"conversation"}),E=cl((e,t)=>{m$(S.current,e)&&y.reportResult({commandId:e,...t}).catch(e=>console.error(e)).finally(()=>{_(t=>(null==t?void 0:t.commandId)===e?void 0:t)})}),N=cl(e=>{if("cancel_chat_query"===e.type){cx(I,e.commandId),E(e.commandId,{ok:!1,error:{code:"CHAT_TIMEOUT",message:"Chat query was cancelled after the debugger control timeout"}});return}"execute_sandbox_tool_call"===e.type?I.executeSandboxToolCall(e.toolCall).then(t=>{E(e.commandId,{ok:!0,result:{reported:t.reported,request_id:t.requestId,tool_call_id:t.toolCallId}})}).catch(t=>{E(e.commandId,{error:{code:"TOOL_CALL_FAILED",message:t instanceof Error?t.message:String(t)},ok:!1})}):(_(e),("render_page"===e.type||"render_widget"===e.type||"submit_chat_query"===e.type)&&C("render_page"===e.type?"page":"render_widget"===e.type?"card":"conversation"))}),T=cl(e=>{try{return I.navigateToPage(e.url,{routeMode:e.routeMode}),C("page"),!0}catch{return!1}}),A=cl(()=>{let{manifest:e}=I.getState();return{appKey:e.appId,appName:e.name}});(0,iD.useEffect)(()=>{let e=y.subscribe(e=>{if("control"===e.type)N(e.data);else if("status"===e.type&&"connected"!==e.status){let e=cx(I);e&&m$(S.current,e),_(void 0)}});return y.start(),()=>{e(),y.stop()}},[y,N,I]),(0,iD.useEffect)(()=>{if(n)return window.webSdkDebugger=I,()=>{window.webSdkDebugger===I&&delete window.webSdkDebugger}},[n,I]),(0,iD.useEffect)(()=>(function(e){let t=document.modelContext;if(!t)return()=>{};let r=new AbortController,i=new URL("/__wsd_mcp",window.location.href);async function n(e){let t=await dN(i.href,{});try{return await e(t.client)}finally{await dT(t)}}return i.searchParams.set("clientId",e),(async function(){let{tools:e}=await n(e=>e.listTools());for(let a of e){var i;r.signal.throwIfAborted(),await t.registerTool({name:a.name,description:a.description??"",inputSchema:a.inputSchema,annotations:{readOnlyHint:(null==(i=a.annotations)?void 0:i.readOnlyHint)===!0,untrustedContentHint:!0},execute:async function(e){let{signal:t}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return r.signal.throwIfAborted(),null==t||t.throwIfAborted(),n(async r=>{null==t||t.throwIfAborted();let i=await r.callTool({name:a.name,arguments:e},{signal:t,timeout:13e4}),n=JSON.stringify(i);if(i.isError)throw Error(n);return n})}},{signal:r.signal})}})().catch(e=>{r.signal.aborted||(r.abort(),console.warn("[web-sdk-debugger] Failed to register WebMCP tools",e))}),()=>r.abort()})(b),[b]),(0,iD.useEffect)(()=>{let e=!1;return I.loadManifest(i).then(()=>{if(!e){let e;return e=new URL(window.location.href),i===nZ?e.searchParams.delete("manifest"):e.searchParams.set("manifest",i),window.history.replaceState(null,"",e),mz(I,x)}}).catch(()=>{}),()=>{e=!0,I.destroy(),v.current===I&&(v.current=null)}},[i,x,I]);let M=(0,iD.useMemo)(()=>({launchDir:h,simulatorManifestOriginalUrl:d,simulatorManifestProxyUrl:l,simulatorManifestUrl:l,simulatorSkillsIndexOriginalUrl:c,simulatorSkillsIndexProxyUrl:u,simulatorSkillsIndexUrl:u,webUrl:m,...t,mcpEndpoint:a||t.mcpProxyEndpoint,mcpOriginalEndpoint:o||t.mcpOriginalEndpoint,mcpProxyEndpoint:a||t.mcpProxyEndpoint}),[h,a,o,d,l,c,u,m,t]);return(0,s.jsx)(iO.M,{children:(0,s.jsx)("section",{className:"workspace",children:(0,s.jsx)("section",{className:"debug-workspace",children:(0,s.jsx)("section",{className:"debug-mode-panel",children:(0,s.jsx)(cc,{capability:M.realDeviceDebug,getAppIdentity:A,children:(0,s.jsx)(m_,{messageInputDisabled:n,activeView:k,apiEnvironment:mq,chromeDevToolsFrontendUrl:"/chrome-devtools/inspector.html",controlCommand:w,controlClientId:b,debugContext:M,onActiveViewChange:C,onControlResult:E,onNavigateToPage:T,showDebugTrace:g,connection:y,webSdkDebugger:I})})})})})})}function mV(e){let{serverDebugContext:t}=e;return window.location.pathname.startsWith("/chrome-devtools/")?(0,s.jsx)(mW,{}):(0,s.jsx)(mH,{serverDebugContext:t})}async function mG(){let e=await mF();e.webViewOrigin&&(tK=t=>({messageTransport:"window",url:`${e.webViewOrigin}/__webview/bootstrap?${new URLSearchParams({url:t,parentOrigin:location.origin})}`}));let t=document.querySelector("#app");if(!t)throw Error("Cannot find #app");(0,rZ.H)(t).render((0,s.jsx)(mV,{serverDebugContext:e}))}(async function(){if("serviceWorker"in navigator){let e=e=>(null==e?void 0:e.scriptURL)===new URL("/__webview/sw.js",location.origin).href,t=e(navigator.serviceWorker.controller),r=await navigator.serviceWorker.getRegistrations();if(await Promise.all(r.filter(t=>e(t.active)||e(t.waiting)||e(t.installing)).map(e=>e.unregister())),t)return void location.reload()}await mG()})().catch(mG)}},h={};function m(e){var t=h[e];if(void 0!==t)return t.exports;var r=h[e]={id:e,exports:{}};return p[e].call(r.exports,r,r.exports,m),r.exports}m.m=p,m.c=h,t=(e="function"==typeof Symbol)?Symbol("rspack queues"):"__rspack_queues",r=m.aE=e?Symbol("rspack exports"):"__webpack_exports__",i=e?Symbol("rspack error"):"__rspack_error",n=e?Symbol("rspack done"):"__rspack_done",a=m.zS=e?Symbol("rspack defer"):"__rspack_defer",m.zT=e=>{if(e.some(e=>{var t=h[e];return!t||!1===t[n]}))return{then:(t,r)=>Promise.all(e.map(m)).then(t,r)}},s=e=>{e&&e.d<1&&(e.d=1,e.forEach(e=>e.r--),e.forEach(e=>e.r--?e.r++:e()))},m.a=(e,o,l,d)=>{l&&((u=[]).d=-1);var u,c,p,h,g=new Set,f=e.exports,v=new Promise((e,t)=>{h=t,p=e});v[r]=f,v[t]=e=>{u&&e(u),g.forEach(e),v.catch(()=>{})},e.exports=v;var y=e;d&&((y=Object.create(e)).exports=f),o(e=>{c=e.map(e=>{if(null!==e&&"object"==typeof e){if(!e[t]&&e[a]){var n=m.zT(e[a]);if(!n)return e;var o=e;e={then(e,t){n.then(()=>e(o),t)}}}if(e[t])return e;if(e.then){var l=[];l.d=0,e.then(e=>{d[r]=e,s(l)},e=>{d[i]=e,s(l)});var d={};return d[a]=!1,d[t]=e=>e(l),d}}var u={};return u[t]=()=>{},u[r]=e,u});var n,o=()=>c.map(e=>{if(e[a])return e;if(e[i])throw e[i];return e[r]}),l=new Promise(e=>{(n=()=>e(o)).r=0;var r=e=>e!==u&&!g.has(e)&&(g.add(e),e&&!e.d&&(n.r++,e.push(n)));c.map(e=>e[a]||e[t](r))});return n.r?l:o()},e=>(e?h(v[i]=e):(d&&(f=v[r]=y.exports),p(f)),s(u),v[n]=!0),y),u&&u.d<0&&(u.d=0)},m.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return m.d(t,{a:t}),t},m.d=(e,t,r)=>{var i=(t,r)=>{for(var i in t)m.o(t,i)&&!m.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,[r]:t[i]})};i(t,"get"),i(r,"value")},m.f={},m.e=(e,t)=>Promise.all(Object.keys(m.f).reduce((r,i)=>(m.f[i](e,r,t),r),[])),m.u=e=>"static/js/async/"+(({166:"xmarkdown-deps",350:"web-core-template-loader-thread",724:"web-elements",778:"legacy-wasm-js",894:"web-core-main-chunk",97:"web-core-worker-chunk"})[e]||e)+"."+({166:"c4c1321ad5",257:"4d55bd5ce8",350:"73428c5c1e",503:"259fed5610",724:"6807f163ca",778:"53cc49def0",894:"d1b32950a5",97:"cf495a4ab8"})[e]+".js",m.miniCssF=e=>""+e+".css",m.g=(()=>{if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}})(),m.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),o={},m.l=function(e,t,r,i,n){if(o[e])return void o[e].push(t);if(void 0!==r)for(var a,s,l=document.getElementsByTagName("script"),d=0;d<l.length;d++){var u=l[d];if(u.getAttribute("src")==e||u.getAttribute("data-rspack")=="@byted-doubao-apps/web-sdk-debugger-app:"+r){a=u;break}}a||(s=!0,(a=document.createElement("script")).timeout=120,m.nc&&a.setAttribute("nonce",m.nc),a.setAttribute("data-rspack","@byted-doubao-apps/web-sdk-debugger-app:"+r),n&&a.setAttribute("fetchpriority",n),a.src=e),o[e]=[t];var c=function(t,r){a.onerror=a.onload=null,clearTimeout(p);var i=o[e];if(delete o[e],a.parentNode&&a.parentNode.removeChild(a),i&&i.forEach(function(e){return e(r)}),t)return t(r)},p=setTimeout(c.bind(null,void 0,{type:"timeout",target:a}),12e4);a.onerror=c.bind(null,a.onerror),a.onload=c.bind(null,a.onload),s&&document.head.appendChild(a)},m.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},l=[],m.O=(e,t,r,i)=>{if(t){i=i||0;for(var n=l.length;n>0&&l[n-1][2]>i;n--)l[n]=l[n-1];l[n]=[t,r,i];return}for(var a=1/0,n=0;n<l.length;n++){for(var[t,r,i]=l[n],s=!0,o=0;o<t.length;o++)(!1&i||a>=i)&&Object.keys(m.O).every(e=>m.O[e](t[o]))?t.splice(o--,1):(s=!1,i<a&&(a=i));if(s){l.splice(n--,1);var d=r();void 0!==d&&(e=d)}}return e},m.p="/",m.j="410",m.b=document.baseURI||self.location.href,d={410:0},m.f.j=function(e,t,r){var i=m.o(d,e)?d[e]:void 0;if(0!==i)if(i)t.push(i[2]);else{var n=new Promise((t,r)=>i=d[e]=[t,r]);t.push(i[2]=n);var a=m.p+m.u(e),s=Error();m.l(a,function(t){if(m.o(d,e)&&(0!==(i=d[e])&&(d[e]=void 0),i)){var r=t&&("load"===t.type?"missing":t.type),n=t&&t.target&&t.target.src;s.message="Loading chunk "+e+" failed.\n("+r+": "+n+")",s.name="ChunkLoadError",s.type=r,s.request=n,i[1](s)}},"chunk-"+e,e,r)}},m.O.j=e=>0===d[e],u=(e,t)=>{var r,i,[n,a,s]=t,o=0;if(n.some(e=>0!==d[e])){for(r in a)m.o(a,r)&&(m.m[r]=a[r]);if(s)var l=s(m)}for(e&&e(t);o<n.length;o++)i=n[o],m.o(d,i)&&d[i]&&d[i][0](),d[i]=0;return m.O(l)},(c=globalThis.rspackChunk_byted_doubao_apps_web_sdk_debugger_app||=[]).forEach(u.bind(null,0)),c.push=u.bind(null,c.push.bind(c));var g=m.O(void 0,["493","783","270","275"],()=>m(23556));g=m.O(g)})();
|
|
51
|
+
`}function mF(e,t){return t.find(t=>null==e?void 0:e.widgets.some(e=>e.widgetId===t))}function mz(e,t,r,i){var n;return{event:t,request_id:i.requestId,reply_message_id:i.replyMessageId,trace:{trace_id:(null==(n=e.trace)?void 0:n.trace_id)||`trace_mock_${e.idempotency_key??i.requestId}`,component:"mock_simulator",stage:t,sampled:!0},...r}}let mW=async e=>{var t;let r=`找到和 ${(null==(t=e.arguments)?void 0:t.keyword)||"调试数据"} 相关的模拟结果`,i={content:[{type:"text",text:r}],structuredContent:{entities:[{entity_type:"debug_item",entity_id:"debug-item-1",name:"调试示例数据"}]},isError:!1},n=JSON.stringify(i);return{status:"succeeded",result:i.structuredContent,raw_result_text:r,raw_mcp_result_json:n,miniapp:{is_mini_app:!0,mcp_channel:"flow_miniapp"},debug:{mock:!0}}},mH=n0(nX),mV=dI({requestHandler:async(e,t,r)=>{let i=e.params,n=r??nJ(i);return nF(n.url,"request"),nB(async t=>{var r,a;let s,o,l=await fetch("/__web_sdk_request_proxy__",{signal:t,body:JSON.stringify((s=new Headers(n.headers),{data:(o=n.body instanceof ArrayBuffer)?nH(n.body):n.body,dataEncoding:o?"base64":void 0,header:Object.fromEntries(s),method:n.method,url:n.url})),headers:{"content-type":"application/json"},method:"POST"}),d=(null==(r=l.headers.get("content-type"))?void 0:r.toLowerCase())??"",u=await l.text();if(!d.includes("application/json"))throw Error(`Request proxy returned a non-JSON response. Make sure the debugger is started with the local request proxy. Response starts with: ${u.slice(0,120)}`);let c=u?JSON.parse(u):{};if(!l.ok)throw Error((null==c?void 0:c.message)||`Request proxy failed with status ${l.status}`);if((null==c?void 0:c.dataEncoding)==="base64"&&"string"==typeof c.data){let t=nV((a=c.data,Uint8Array.from(atob(a),e=>e.charCodeAt(0)).buffer),i.dataType);return _(e,{statusCode:c.statusCode,header:c.header,data:t})}return _(e,c)})}});function mG(e,t){if(e.has(t))return!1;if(e.add(t),e.size>100){let t=e.values().next().value;t&&e.delete(t)}return!0}function mJ(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";return new URL(window.location.href).searchParams.get(e)||r||t}async function mK(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:fetch;try{var t;let r=await e("/__web_sdk_debug_context",{cache:"no-store",headers:{Accept:"application/json"}});return r.ok?!(t=await r.json())||"object"!=typeof t||Array.isArray(t)?{}:t:{}}catch{return{}}}async function mZ(e,t){let r=t.skills,i=t.mcpServers,n=[];if("function"==typeof r&&n.push(Promise.resolve(r()).catch(()=>void 0)),"function"==typeof i){let t=e.getState();n.push(Promise.resolve(i({appKey:t.manifest.appId,appName:t.manifest.name,manifest:t.manifest.raw})).catch(()=>void 0))}await Promise.all(n)}function mX(){return(0,s.jsx)("main",{className:"chrome-devtools-unavailable-page",children:(0,s.jsx)("section",{className:"wsd-chrome-devtools",children:(0,s.jsx)("div",{className:"wsd-chrome-devtools-empty",children:"Chrome DevTools frontend is unavailable"})})})}function mY(e){let{serverDebugContext:t}=e,r=(0,iD.useMemo)(()=>(function(e){let t=e.searchParams.get("messages");if(null!==t)try{let e=JSON.parse(t);if(Array.isArray(e))return e;console.error("Failed to read initial messages: messages must be an array")}catch(e){console.error("Failed to read initial messages",e)}})(new URL(window.location.href)),[]),i=(0,iD.useMemo)(()=>new URL(window.location.href).searchParams.get("manifest")||nZ,[]),n=void 0!==r,a=(0,iD.useMemo)(()=>mJ("mcp","",void 0),[]),o=(0,iD.useMemo)(()=>{let e;return(e=new URL(window.location.href)).searchParams.get("mcpOriginal")||e.searchParams.get("mcpEndpoint")||""},[]),l=(0,iD.useMemo)(()=>mJ("simulatorManifest","/__simulator_manifest/manifest.yaml",void 0),[]),d=(0,iD.useMemo)(()=>new URL(window.location.href).searchParams.get("simulatorManifestOriginal")||"",[]),u=(0,iD.useMemo)(()=>mJ("simulatorSkills","/__simulator_skills/index.json",void 0),[]),c=(0,iD.useMemo)(()=>new URL(window.location.href).searchParams.get("simulatorSkillsOriginal")||"",[]),p=(0,iD.useMemo)(()=>n0(new URL(window.location.href).searchParams.get("simulator")||mH),[]),h=(0,iD.useMemo)(()=>{let e;return(e=new URL(window.location.href)).searchParams.get("launchDir")||e.searchParams.get("projectPath")||e.searchParams.get("cwd")||""},[]),m=(0,iD.useMemo)(()=>`${window.location.origin}${window.location.pathname}`,[]),g=(0,iD.useMemo)(()=>{let e;return null!==(e=new URL(window.location.href).searchParams.get("DEBUG"))&&"0"!==e&&"false"!==e.toLowerCase()},[]),f=(0,iD.useMemo)(()=>"1"===new URL(window.location.href).searchParams.get("simulatorMock")||"true"===String((void 0)??"").toLowerCase(),[]),v=(0,iD.useRef)(null),y=(0,iD.useMemo)(()=>new iL,[]),b=y.clientId,[w,_]=(0,iD.useState)(),S=(0,iD.useRef)(new Set),x=(0,iD.useMemo)(()=>(function(e){var t,r,i,n,a,s;let o,l,d=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},u={mcpEndpoint:mA((t={mcpEndpoint:e,simulatorManifestUrl:d.simulatorManifestUrl,simulatorSkillsIndexUrl:d.simulatorSkillsIndexUrl}).mcpEndpoint),simulatorManifestUrl:mA(t.simulatorManifestUrl),simulatorSkillsIndexUrl:mA(t.simulatorSkillsIndexUrl)},c=function(){let e,t,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{mcpServers:async e=>{let t=Object.entries(Object.fromEntries(Object.entries((e.manifest??{}).tools??{}).filter(e=>{let[,t]=e;return!0===t.is_client_tool}))).map(e=>{let[t,r]=e;return{name:t,description:r.description,input_schema_json:function e(t){if(Array.isArray(t))return t.map(e);if(!rP(t))return t;let r={};for(let[i,n]of Object.entries(t))r[i]="type"===i&&"int"===n?"integer":"type"===i&&"float"===n?"number":e(n);return r}(r.input_schema)}});return 0===t.length?(aW(r.onTraceEvent,{event:"client_tools_empty",app_key:e.appKey,server_id:aB,tool_count:0,tools:[]}),[]):(aW(r.onTraceEvent,{event:"client_tools_resolved",app_key:e.appKey,server_id:aB,tool_count:t.length,tools:t.map(e=>e.name)}),[{server_id:aB,name:"Client Tool",description:"Client Tool runtime for simulator debugging",tools:t}])},toolExecutor:((t=async t=>{let i,n;try{i=function(e){let t=e.arguments;if(void 0===t){if(void 0===e.argumentsJson)t={};else if(void 0===(t=r3(e.argumentsJson)))throw Error("Tool arguments must be valid JSON")}if(!rP(t))throw Error("Tool arguments must be a JSON object");return t}(t),n="string"==typeof t.argumentsJson&&t.argumentsJson.trim()?t.argumentsJson:r6(i)}catch(e){return aK("CLIENT_TOOL_INVALID_ARGUMENTS",r5(e),!1)}try{var a;aW(r.onTraceEvent,{event:"client_tool_call_started",request_id:t.requestId,trace_id:t.trace.trace_id,app_key:t.appKey,server_id:t.serverId,tool_call_id:t.toolCallId,tool_name:t.toolName,arguments:i,arguments_json:r6(i)});let s=await (()=>{var t,i;let n=null==(t=r.getRuntimeUrl)?void 0:t.call(r);if(!n)throw Error("Client Tool runtime is unavailable. Build the app with a Web Client Tool entry.");if(!e||e.runtimeUrl!==n){null==e||e.dispose();let t=(r.runtimeFactory??function(e,t){return new aH(e,t)})(n,null==(i=r.getRuntimeGlobalProps)?void 0:i.call(r));e=new aJ(n,t,r.onTraceEvent),aW(r.onTraceEvent,{event:"client_tool_runtime_started",runtime_url:n})}return e})().invokeTool({toolId:t.toolName,input:n,context:{callbackId:t.toolCallId,conversationId:t.requestId,featureMap:void 0,msgId:t.replyMessageId,questionId:t.requestId},signal:t.signal}),o=function(e,t){var r,i;if(0===e.result)try{let i=function(e,t){if(!rP(e)||!Array.isArray(e.content))throw Error(`Client Tool "${t}" must return an MCP tool output object`);return e}(e.output,t.toolName),n=!0===i.isError?i:function(e,t){let r=aU(t.manifest,t.toolName);if(!r||"string"!=typeof r.kind)throw Error(`Client Tool "${t.toolName}" manifest output is required`);if("execution_result"===r.kind)return e;if("entities"!==r.kind)throw Error(`Client Tool "${t.toolName}" has unsupported output kind "${r.kind}"`);if(!rP(e)||!Array.isArray(e.structuredContent))throw Error(`Client Tool "${t.toolName}" must return structuredContent as an array`);return aq(e,t.manifest,t.toolName)}(i,t);return r=a$(n,{businessErrorCode:"CLIENT_TOOL_BUSINESS_ERROR",protocol:az,source:"client_tool"}),{...r,debug:{...r.debug,mcp_output:i}}}catch(e){return aK("CLIENT_TOOL_INVALID_RESULT",r5(e),!1)}let n=void 0===(i=e.reason)?"":rP(i)?"string"==typeof i.message?i.message:r6(i):r5(i);return 2===e.result?aK("CLIENT_TOOL_NOT_FOUND",`Client Tool not found: ${e.toolId}`,!1):1===e.result?aK("CLIENT_TOOL_FAILED",n||`Client Tool failed: ${e.toolId}`,!1):aK("CLIENT_TOOL_UNKNOWN_RESULT",`Client Tool returned unknown status: ${String(e.result)}`,!1)}(s,t);return aW(r.onTraceEvent,{event:"succeeded"===o.status?"client_tool_call_succeeded":"client_tool_call_failed",request_id:t.requestId,app_key:t.appKey,server_id:t.serverId,tool_call_id:t.toolCallId,tool_name:t.toolName,status:o.status,result:o.result,raw_mcp_result_json:o.raw_mcp_result_json,error:null==(a=o.error)?void 0:a.message}),o}catch(i){let e=r5(i);return aW(r.onTraceEvent,{event:"client_tool_call_failed",request_id:t.requestId,app_key:t.appKey,server_id:t.serverId,tool_call_id:t.toolCallId,tool_name:t.toolName,error:e}),aK("CLIENT_TOOL_CALL_FAILED",e,!0)}}).dispose=()=>{null==e||e.dispose(),e=void 0},t)}}({getRuntimeGlobalProps:d.getClientToolRuntimeGlobalProps,getRuntimeUrl:d.getClientToolRuntimeUrl,onTraceEvent:d.onTraceEvent}),p=c.toolExecutor,h=c.mcpServers,m=()=>{var e;return l??=Promise.resolve(u.mcpEndpoint||(null==(e=d.getMcpEndpoint)?void 0:e.call(d))).then(e=>{let t=mA(e);return o=t?function(e){let t=rR(e.endpoint);if(!t)return{};let r=function(e,t){if(null==t?void 0:t.trim())return t.trim();let r=new URL(e);return`${r.hostname}_${r.port||r.protocol.replace(":","")}${r.pathname}`.replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/^_+|_+$/g,"")||"local_mcp"}(t,e.serverId);return{mcpServers:async i=>{let n;try{dC(e.onTraceEvent,{event:"local_mcp_tools_load_started",app_key:i.appKey,mcp_endpoint:t,server_id:r},i),n=await dN(t,{...e,signal:i.signal});let a=await n.client.listTools(void 0,{signal:i.signal}),s=n.client.getServerVersion(),o={server_id:r,name:(null==s?void 0:s.name)||r,description:n.client.getInstructions()||"",tools:a.tools.map(dE).filter(e=>e.name)};return dC(e.onTraceEvent,{event:"local_mcp_tools_loaded",app_key:i.appKey,mcp_endpoint:t,server_id:o.server_id,server_version:s,tools:o.tools.map(e=>e.name)},i),[o]}catch(n){var a;return null==(a=i.signal)||a.throwIfAborted(),dC(e.onTraceEvent,{event:"local_mcp_tools_load_failed",app_key:i.appKey,mcp_endpoint:t,server_id:r,error:r5(n),request_will_continue:!0,tool_count:0,tools:[]},i),console.warn("[web-sdk-debugger] Failed to load MCP tools",n),[]}finally{n&&await dT(n)}},toolExecutor:async r=>{var i;let n,a=r.arguments??r3(r.argumentsJson)??{},s=r.argumentsJson||r6(a),o=Date.now();try{dC(e.onTraceEvent,{event:"local_mcp_call_started",request_id:r.requestId,trace_id:r.trace.trace_id,app_key:r.appKey,server_id:r.serverId,tool_call_id:r.toolCallId,tool_name:r.toolName,arguments:a,arguments_json:s,mcp_endpoint:t}),n=await dN(t,{...e,signal:r.signal,headers:function(e,t){if(!e&&!t)return;let r=new Headers(e);for(let[e,i]of Object.entries(t??{}))r.set(e,i);return r}(e.headers,r.headers)}),null==(i=r.signal)||i.throwIfAborted();let l=await n.client.callTool({name:r.toolName,arguments:a,_meta:{request_id:r.requestId,trace_id:r.trace.trace_id,app_key:r.appKey,server_id:r.serverId,tool_call_id:r.toolCallId,tool_name:r.toolName,arguments_json:s}},{signal:r.signal}),d=!0===l.isError?l:aq(l,r.manifest,r.toolName),u=a$(d,{businessErrorCode:"LOCAL_MCP_BUSINESS_ERROR",protocol:"streamable_http",source:"local_mcp"});return u.debug={...u.debug,mcp_output:l},dC(e.onTraceEvent,{event:"local_mcp_call_succeeded",request_id:r.requestId,trace_id:r.trace.trace_id,app_key:r.appKey,server_id:r.serverId,tool_call_id:r.toolCallId,tool_name:r.toolName,status:u.status,result:u.result,raw_result_text:u.raw_result_text,raw_mcp_result:d,elapsed_ms:Date.now()-o,mcp_endpoint:t}),u}catch(n){if(aT(n))throw n;let i=r5(n);return dC(e.onTraceEvent,{event:"local_mcp_call_failed",request_id:r.requestId,trace_id:r.trace.trace_id,app_key:r.appKey,server_id:r.serverId,tool_call_id:r.toolCallId,tool_name:r.toolName,error:i,elapsed_ms:Date.now()-o,mcp_endpoint:t}),{status:"failed",result:{error:i},error:{code:"LOCAL_MCP_CALL_FAILED",message:i,retryable:!0,stage:"tool_execute"},raw_result_text:i}}finally{n&&await dT(n)}}}}({endpoint:t,onTraceEvent:d.onTraceEvent}):void 0})},g=async e=>{let[t,r]=await Promise.all([m(),h(e)]);if(!t)return r;let i=t.mcpServers;return[...await i(e),...r]},f=async e=>{if(e.serverId===aB)return p(e);let t=await m();if(!t){let e="Local MCP is not configured";return{status:"failed",result:{error:e},error:{code:"LOCAL_MCP_NOT_CONFIGURED",message:e,retryable:!1,stage:"tool_execute"},raw_result_text:e}}return t.toolExecutor(e)};return f.dispose=()=>{var e,t,r;null==(e=p.dispose)||e.call(p),null==o||null==(r=o.toolExecutor)||null==(t=r.dispose)||t.call(r)},{simulatorManifest:u.simulatorManifestUrl?(r=u.simulatorManifestUrl,i=d.onTraceEvent,n=d.getAppId,async e=>{let t;mR(i,"manifest",r);try{if(!(t=await fetch(r,{signal:e,cache:"no-store",headers:{Accept:"application/yaml, text/yaml, text/x-yaml, application/json, text/plain"}})).ok)throw mL("manifest",r,t);let a=await t.text(),s=function(e){let t=(0,aD.qg)(e);if(!rP(t))throw Error("Simulator manifest must be a YAML object");return t}(a),o=s.app_key?void 0:await (null==n?void 0:n());if(n&&!o&&!s.app_key)throw Error("Sandbox 调试应用尚未就绪,请重建调试会话后重试。");let l=o?{...s,app_key:o}:s;return mj(i,"manifest",r,t,{bytes:a.length}),{...l,raw_manifest_yaml:o?(0,aD.As)(l):a}}catch(e){throw mP(i,"manifest",r,e,t),console.warn("[web-sdk-debugger] Failed to load simulator manifest supplement",e),e}}):void 0,skills:u.simulatorSkillsIndexUrl?(a=u.simulatorSkillsIndexUrl,s=d.onTraceEvent,async e=>{let t;mR(s,"skill",a);try{var r;if(!(t=await fetch(a,{signal:e,cache:"no-store",headers:{Accept:"application/json"}})).ok)throw mL("skill",a,t);let i=await t.text();if(((null==(r=t.headers.get("content-type"))?void 0:r.toLowerCase())??"").includes("text/html")||/^<!doctype html\b|^<html[\s>]/i.test(i.trimStart()))throw Error(`Simulator skills index returned HTML instead of JSON (${a})`);let n=function(e){if(!rP(e)||!Array.isArray(e.skills))throw Error("Simulator skills index must contain a skills array");return e.skills.map((e,t)=>{var r;if(!(rP(r=e)&&"string"==typeof r.relativePath&&"string"==typeof r.content))throw Error(`Simulator skills index contains an invalid entry at index ${t}`);return e}).sort((e,t)=>e.relativePath<t.relativePath?-1:+(e.relativePath>t.relativePath))}(JSON.parse(i));return mj(s,"skill",a,t,{bytes:i.length,skill_paths:n.map(e=>e.relativePath)}),n}catch(e){throw mP(s,"skill",a,e,t),console.warn("[web-sdk-debugger] Failed to load simulator skills",e),e}}):void 0,mcpServers:g,toolExecutor:f}})(a,{getClientToolRuntimeGlobalProps:()=>{var e;let t=null==(e=v.current)?void 0:e.getState().manifest;return t?t$(t):void 0},getClientToolRuntimeUrl:()=>{var e;let t=null==(e=v.current)?void 0:e.getState();return t?function(e,t,r){var i,n,a,s,o,l;let d,u=(null==(a=t.applet)||null==(n=a.web)||null==(i=n.toolRuntimeEntry)?void 0:i.trim())||(null==(o=t.applet)||null==(s=o.toolRuntimeEntry)?void 0:s.trim());if(!u)return;let c=new URL(u,((d=new URL(String(e),(null==(l=globalThis.location)?void 0:l.href)||"http://localhost/")).pathname.endsWith("/base/manifest.json")?d.pathname=d.pathname.slice(0,-18):d.pathname=d.pathname.replace(/\/[^/]*$/,"/"),d.search="",d.hash="",d));return r&&c.searchParams.set("__doubao_resource_reload",r),c.toString()}(t.manifestUrl,t.manifest.raw,t.resourceUrlVersion):void 0},getMcpEndpoint:async()=>t.mcpProxyEndpoint,getAppId:async()=>(await mK()).sandboxAppId,onTraceEvent:e=>{var t;return null==(t=v.current)?void 0:t.appendSimulatorTraceEvent(e)},simulatorManifestUrl:l,simulatorSkillsIndexUrl:u}),[a,l,u,t.mcpProxyEndpoint]),I=(0,iD.useMemo)(()=>{let e=f?{appKey:mO,appName:"调试示例应用插件",mcpServers:m$,simulatorFetch:function(e){let{getDebuggerState:t}=e;return async(e,r)=>{var i,n,a,s,o,l,d,u;let c,p,h,m,g,f,v,y,b=String(e);if(b.endsWith("/simulator/tool/report")){let e="string"==typeof(null==r?void 0:r.body)?JSON.parse(r.body):{};return new Response(JSON.stringify({code:0,message:"OK",request_id:e.request_id,tool_call_id:e.tool_call_id,trace:e.trace}),{headers:{"Content-Type":"application/json"},status:200,statusText:"OK"})}return b.endsWith("/simulator/chat")?(y=(i="string"!=typeof(null==r?void 0:r.body)?{}:JSON.parse(r.body),s=t(),p=((c=new URL(window.location.href).searchParams.get("simulatorMockWidget"))?mF(s,[c]):void 0)||mF(s,mq)||(null==s||null==(o=s.widgetSelection)?void 0:o.item.widgetId)||(null==(l=s)||null==(d=l.widgets.find(e=>{var t;return null==(t=e.web)?void 0:t.entry}))?void 0:d.widgetId)||(null==l||null==(u=l.widgets[0])?void 0:u.widgetId)||"weather-card",h=Date.now().toString(36),m={requestId:`req_mock_server_${h}`,replyMessageId:`msg_mock_reply_${h}`},g=(null==(n=i.message)?void 0:n.content)||"模拟请求",f=`call_mock_${h}`,v={applet_id:i.app_id||mO,widget_id:p,entity_id:"mock-entity-1",viewData:{source:"web-sdk-debugger-mock",keyword:g,widgetId:p},extra:{"doubao/outputTemplate":"mock.output.template"}},[mz(i,"ack",{ack:{request_id:m.requestId,message_id:m.replyMessageId,local_message_id:null==(a=i.message)?void 0:a.local_message_id}},m),mz(i,"tool_call",{tool_call:{tool_call_id:f,tool_name:mU,server_id:mD,app_key:i.app_id||mO,arguments_json:JSON.stringify({keyword:g}),status:"PENDING",timeout_ms:2e3}},m),mz(i,"tool_status",{tool_status:{tool_call_id:f,status:"RUNNING",progress:.6,message:"Mock tool running"}},m),mz(i,"text_delta",{text_delta:{block_id:"block_mock_text",op:"append",delta:`Mock 已收到:${g}`}},m),mz(i,"card_delta",{card_delta:{block_id:"block_mock_card",op:"append",card_id:`card_mock_${h}`,source_tool_call_id:f,source_entity_ids:["mock-entity-1"],is_final:!0,card:{card_id:`card_mock_${h}`,card_type:"mock_widget_card",title:"Mock 应用插件卡片",fallback_text:`使用 ${p} 渲染`,props_json:JSON.stringify(v)}}},m),mz(i,"debug",{debug_event:{category:"mock",title:"Mock Simulator",summary:"本地 mock SSE 已生成 text/card/tool 事件",data:{widget_id:p},redaction_level:"none"}},m),mz(i,"answer_finish",{answer_finish:{status:"completed",finish_reason:"stop",usage:{output_tokens:12}}},m),mz(i,"reply_finish",{reply_finish:{status:"completed",finish_reason:"stop",event_count:7}},m)]).map(mB).join(""),new Response(new ReadableStream({start(e){e.enqueue(new TextEncoder().encode(y)),e.close()}}),{headers:{"Content-Type":"text/event-stream"},status:200,statusText:"OK"})):new Response(JSON.stringify({ok:!1,error:"Unknown mock simulator endpoint"}),{status:404,statusText:"Not Found"})}}({getDebuggerState:()=>{var e;return(null==(e=v.current)?void 0:e.getState())??null}}),toolExecutor:mW}:{},t=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return new si(e)}({manifestUrl:i,simulatorEndpoint:p,...x,...e});return r&&t.pushMessages(r),v.current=t,t},[i,p,x,f,r]),[k,C]=(0,iD.useState)(()=>{let e,t,r;return t=(e=new URL(window.location.href)).searchParams.get("view"),r=e.searchParams.get("debugMode")||e.searchParams.get("mode"),"conversation"===t||"tool"===t||"card"===t||"page"===t?t:"conversation"===r||"tool"===r||"card"===r||"page"===r?r:"conversation"}),E=cl((e,t)=>{mG(S.current,e)&&y.reportResult({commandId:e,...t}).catch(e=>console.error(e)).finally(()=>{_(t=>(null==t?void 0:t.commandId)===e?void 0:t)})}),N=cl(e=>{if("cancel_chat_query"===e.type){cA(I,e.commandId),E(e.commandId,{ok:!1,error:{code:"CHAT_TIMEOUT",message:"Chat query was cancelled after the debugger control timeout"}});return}"execute_sandbox_tool_call"===e.type?I.executeSandboxToolCall(e.toolCall).then(t=>{E(e.commandId,{ok:!0,result:{reported:t.reported,request_id:t.requestId,tool_call_id:t.toolCallId}})}).catch(t=>{E(e.commandId,{error:{code:"TOOL_CALL_FAILED",message:t instanceof Error?t.message:String(t)},ok:!1})}):(_(e),("render_page"===e.type||"render_widget"===e.type||"submit_chat_query"===e.type)&&C("render_page"===e.type?"page":"render_widget"===e.type?"card":"conversation"))}),T=cl(e=>{try{return I.navigateToPage(e.url,{routeMode:e.routeMode}),C("page"),!0}catch{return!1}}),A=cl(()=>{let{manifest:e}=I.getState();return{appKey:e.appId,appName:e.name}});(0,iD.useEffect)(()=>{let e=y.subscribe(e=>{if("control"===e.type)N(e.data);else if("status"===e.type&&"connected"!==e.status){let e=cA(I);e&&mG(S.current,e),_(void 0)}});return y.start(),()=>{e(),y.stop()}},[y,N,I]),(0,iD.useEffect)(()=>{if(n)return window.webSdkDebugger=I,()=>{window.webSdkDebugger===I&&delete window.webSdkDebugger}},[n,I]),(0,iD.useEffect)(()=>(function(e){let t=document.modelContext;if(!t)return()=>{};let r=new AbortController,i=new URL("/__wsd_mcp",window.location.href);async function n(e){let t=await dN(i.href,{});try{return await e(t.client)}finally{await dT(t)}}return i.searchParams.set("clientId",e),(async function(){let{tools:e}=await n(e=>e.listTools());for(let a of e){var i;r.signal.throwIfAborted(),await t.registerTool({name:a.name,description:a.description??"",inputSchema:a.inputSchema,annotations:{readOnlyHint:(null==(i=a.annotations)?void 0:i.readOnlyHint)===!0,untrustedContentHint:!0},execute:async function(e){let{signal:t}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return r.signal.throwIfAborted(),null==t||t.throwIfAborted(),n(async r=>{null==t||t.throwIfAborted();let i=await r.callTool({name:a.name,arguments:e},{signal:t,timeout:13e4}),n=JSON.stringify(i);if(i.isError)throw Error(n);return n})}},{signal:r.signal})}})().catch(e=>{r.signal.aborted||(r.abort(),console.warn("[web-sdk-debugger] Failed to register WebMCP tools",e))}),()=>r.abort()})(b),[b]),(0,iD.useEffect)(()=>{let e=!1;return I.loadManifest(i).then(()=>{if(!e){let e;return e=new URL(window.location.href),i===nZ?e.searchParams.delete("manifest"):e.searchParams.set("manifest",i),window.history.replaceState(null,"",e),mZ(I,x)}}).catch(()=>{}),()=>{e=!0,I.destroy(),v.current===I&&(v.current=null)}},[i,x,I]);let M=(0,iD.useMemo)(()=>({launchDir:h,simulatorManifestOriginalUrl:d,simulatorManifestProxyUrl:l,simulatorManifestUrl:l,simulatorSkillsIndexOriginalUrl:c,simulatorSkillsIndexProxyUrl:u,simulatorSkillsIndexUrl:u,webUrl:m,...t,mcpEndpoint:a||t.mcpProxyEndpoint,mcpOriginalEndpoint:o||t.mcpOriginalEndpoint,mcpProxyEndpoint:a||t.mcpProxyEndpoint}),[h,a,o,d,l,c,u,m,t]);return(0,s.jsx)(iO.M,{children:(0,s.jsx)("section",{className:"workspace",children:(0,s.jsx)("section",{className:"debug-workspace",children:(0,s.jsx)("section",{className:"debug-mode-panel",children:(0,s.jsx)(cc,{capability:M.realDeviceDebug,getAppIdentity:A,children:(0,s.jsx)(mN,{messageInputDisabled:n,activeView:k,apiEnvironment:mV,chromeDevToolsFrontendUrl:"/chrome-devtools/inspector.html",controlCommand:w,controlClientId:b,debugContext:M,onActiveViewChange:C,onControlResult:E,onNavigateToPage:T,showDebugTrace:g,connection:y,webSdkDebugger:I})})})})})})}function mQ(e){let{serverDebugContext:t}=e;return window.location.pathname.startsWith("/chrome-devtools/")?(0,s.jsx)(mX,{}):(0,s.jsx)(mY,{serverDebugContext:t})}async function m0(){let e=await mK();e.webViewOrigin&&(tK=t=>({messageTransport:"window",url:`${e.webViewOrigin}/__webview/bootstrap?${new URLSearchParams({url:t,parentOrigin:location.origin})}`}));let t=document.querySelector("#app");if(!t)throw Error("Cannot find #app");(0,rZ.H)(t).render((0,s.jsx)(mQ,{serverDebugContext:e}))}(async function(){if("serviceWorker"in navigator){let e=e=>(null==e?void 0:e.scriptURL)===new URL("/__webview/sw.js",location.origin).href,t=e(navigator.serviceWorker.controller),r=await navigator.serviceWorker.getRegistrations();if(await Promise.all(r.filter(t=>e(t.active)||e(t.waiting)||e(t.installing)).map(e=>e.unregister())),t)return void location.reload()}await m0()})().catch(m0)}},h={};function m(e){var t=h[e];if(void 0!==t)return t.exports;var r=h[e]={id:e,exports:{}};return p[e].call(r.exports,r,r.exports,m),r.exports}m.m=p,m.c=h,t=(e="function"==typeof Symbol)?Symbol("rspack queues"):"__rspack_queues",r=m.aE=e?Symbol("rspack exports"):"__webpack_exports__",i=e?Symbol("rspack error"):"__rspack_error",n=e?Symbol("rspack done"):"__rspack_done",a=m.zS=e?Symbol("rspack defer"):"__rspack_defer",m.zT=e=>{if(e.some(e=>{var t=h[e];return!t||!1===t[n]}))return{then:(t,r)=>Promise.all(e.map(m)).then(t,r)}},s=e=>{e&&e.d<1&&(e.d=1,e.forEach(e=>e.r--),e.forEach(e=>e.r--?e.r++:e()))},m.a=(e,o,l,d)=>{l&&((u=[]).d=-1);var u,c,p,h,g=new Set,f=e.exports,v=new Promise((e,t)=>{h=t,p=e});v[r]=f,v[t]=e=>{u&&e(u),g.forEach(e),v.catch(()=>{})},e.exports=v;var y=e;d&&((y=Object.create(e)).exports=f),o(e=>{c=e.map(e=>{if(null!==e&&"object"==typeof e){if(!e[t]&&e[a]){var n=m.zT(e[a]);if(!n)return e;var o=e;e={then(e,t){n.then(()=>e(o),t)}}}if(e[t])return e;if(e.then){var l=[];l.d=0,e.then(e=>{d[r]=e,s(l)},e=>{d[i]=e,s(l)});var d={};return d[a]=!1,d[t]=e=>e(l),d}}var u={};return u[t]=()=>{},u[r]=e,u});var n,o=()=>c.map(e=>{if(e[a])return e;if(e[i])throw e[i];return e[r]}),l=new Promise(e=>{(n=()=>e(o)).r=0;var r=e=>e!==u&&!g.has(e)&&(g.add(e),e&&!e.d&&(n.r++,e.push(n)));c.map(e=>e[a]||e[t](r))});return n.r?l:o()},e=>(e?h(v[i]=e):(d&&(f=v[r]=y.exports),p(f)),s(u),v[n]=!0),y),u&&u.d<0&&(u.d=0)},m.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return m.d(t,{a:t}),t},m.d=(e,t,r)=>{var i=(t,r)=>{for(var i in t)m.o(t,i)&&!m.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,[r]:t[i]})};i(t,"get"),i(r,"value")},m.f={},m.e=(e,t)=>Promise.all(Object.keys(m.f).reduce((r,i)=>(m.f[i](e,r,t),r),[])),m.u=e=>"static/js/async/"+(({166:"xmarkdown-deps",350:"web-core-template-loader-thread",724:"web-elements",778:"legacy-wasm-js",894:"web-core-main-chunk",97:"web-core-worker-chunk"})[e]||e)+"."+({166:"c4c1321ad5",257:"4d55bd5ce8",350:"73428c5c1e",503:"259fed5610",724:"6807f163ca",778:"53cc49def0",894:"d1b32950a5",97:"cf495a4ab8"})[e]+".js",m.miniCssF=e=>""+e+".css",m.g=(()=>{if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}})(),m.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),o={},m.l=function(e,t,r,i,n){if(o[e])return void o[e].push(t);if(void 0!==r)for(var a,s,l=document.getElementsByTagName("script"),d=0;d<l.length;d++){var u=l[d];if(u.getAttribute("src")==e||u.getAttribute("data-rspack")=="@byted-doubao-apps/web-sdk-debugger-app:"+r){a=u;break}}a||(s=!0,(a=document.createElement("script")).timeout=120,m.nc&&a.setAttribute("nonce",m.nc),a.setAttribute("data-rspack","@byted-doubao-apps/web-sdk-debugger-app:"+r),n&&a.setAttribute("fetchpriority",n),a.src=e),o[e]=[t];var c=function(t,r){a.onerror=a.onload=null,clearTimeout(p);var i=o[e];if(delete o[e],a.parentNode&&a.parentNode.removeChild(a),i&&i.forEach(function(e){return e(r)}),t)return t(r)},p=setTimeout(c.bind(null,void 0,{type:"timeout",target:a}),12e4);a.onerror=c.bind(null,a.onerror),a.onload=c.bind(null,a.onload),s&&document.head.appendChild(a)},m.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},l=[],m.O=(e,t,r,i)=>{if(t){i=i||0;for(var n=l.length;n>0&&l[n-1][2]>i;n--)l[n]=l[n-1];l[n]=[t,r,i];return}for(var a=1/0,n=0;n<l.length;n++){for(var[t,r,i]=l[n],s=!0,o=0;o<t.length;o++)(!1&i||a>=i)&&Object.keys(m.O).every(e=>m.O[e](t[o]))?t.splice(o--,1):(s=!1,i<a&&(a=i));if(s){l.splice(n--,1);var d=r();void 0!==d&&(e=d)}}return e},m.p="/",m.j="410",m.b=document.baseURI||self.location.href,d={410:0},m.f.j=function(e,t,r){var i=m.o(d,e)?d[e]:void 0;if(0!==i)if(i)t.push(i[2]);else{var n=new Promise((t,r)=>i=d[e]=[t,r]);t.push(i[2]=n);var a=m.p+m.u(e),s=Error();m.l(a,function(t){if(m.o(d,e)&&(0!==(i=d[e])&&(d[e]=void 0),i)){var r=t&&("load"===t.type?"missing":t.type),n=t&&t.target&&t.target.src;s.message="Loading chunk "+e+" failed.\n("+r+": "+n+")",s.name="ChunkLoadError",s.type=r,s.request=n,i[1](s)}},"chunk-"+e,e,r)}},m.O.j=e=>0===d[e],u=(e,t)=>{var r,i,[n,a,s]=t,o=0;if(n.some(e=>0!==d[e])){for(r in a)m.o(a,r)&&(m.m[r]=a[r]);if(s)var l=s(m)}for(e&&e(t);o<n.length;o++)i=n[o],m.o(d,i)&&d[i]&&d[i][0](),d[i]=0;return m.O(l)},(c=globalThis.rspackChunk_byted_doubao_apps_web_sdk_debugger_app||=[]).forEach(u.bind(null,0)),c.push=u.bind(null,c.push.bind(c));var g=m.O(void 0,["493","783","270","131"],()=>m(23556));g=m.O(g)})();
|