@doubao-dev/kit 0.8.0-rc.2 → 0.8.0-rc.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/277~0.js +1 -1
- package/dist/assets/web-sdk-debugger/__doubao_web_sdk_native_modules/applet-bridge-module-core.js +1 -1
- package/dist/assets/web-sdk-debugger/assets/framework/doubao-apps-api.template.js +0 -0
- package/dist/assets/web-sdk-debugger/assets/framework/doubao-apps-framework.template.js +0 -0
- package/dist/assets/web-sdk-debugger/index.html +1 -1
- package/dist/assets/web-sdk-debugger/static/js/{index.84ba26caa4.js → index.88cba49f74.js} +2 -2
- package/dist/cli/index.js +1 -1
- package/dist/sdk.js +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(()=>{"use strict";var e,t,r,i,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.3"}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 {
|
|
2
2
|
position: absolute !important;
|
|
3
3
|
margin: 0 !important;
|
|
4
4
|
padding: 0 !important;
|
|
@@ -43,7 +43,7 @@ registerProcessor('doubao-recorder', CaptureProcessor);`;function oI(){var e;ret
|
|
|
43
43
|
}
|
|
44
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}"] {
|
|
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 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)||""),sandboxAppId:null==v?void 0:v.sandboxAppId,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")}
|
|
47
47
|
event: ${e.event}
|
|
48
48
|
data: ${JSON.stringify(e)}
|
|
49
49
|
|