@doubao-dev/cli 0.0.32 → 0.0.33
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/2168.js +16 -16
- package/dist/275.js +12 -14
- package/dist/2932.js +1 -1
- package/dist/318.js +1 -1
- package/dist/3974.js +22 -22
- package/dist/4525.js +1 -1
- package/dist/4880.js +1 -1
- package/dist/4931.js +2 -2
- package/dist/7410.js +1 -1
- package/dist/7417.js +204 -0
- package/dist/7417.js.LICENSE.txt +107 -0
- package/dist/7945.js +1 -0
- package/dist/8079.js +126 -0
- package/dist/{1560.js → 9091.js} +2 -2
- package/dist/9667.js +78 -0
- package/dist/{8891.js.LICENSE.txt → 9667.js.LICENSE.txt} +0 -108
- package/dist/@byted-doubao-apps/create.js +1 -1
- package/dist/@byted-doubao-apps/kit.js +1 -0
- package/dist/@byted-doubao-apps/login.js +1 -1
- package/dist/@byted-doubao-apps/login~1.js +1 -1
- package/dist/@byted-doubao-apps/template-empty/package.json +3 -3
- package/dist/@byted-doubao-apps/template-starter/package.json +3 -3
- package/dist/@byted-hdt/cli.js +1 -1
- package/dist/@inquirer/select.js +1 -1
- package/dist/app.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/index.html +1 -1
- package/dist/assets/web-sdk-debugger/static/js/index.d1bb36b355.js +44 -0
- package/dist/assets/web-sdk-debugger/wsd/doubao-apps-api.template.js +0 -0
- package/dist/assets/web-sdk-debugger/wsd/doubao-apps-framework.template.js +0 -0
- package/dist/build.js +1 -1
- package/dist/build~1.js +6 -6
- package/dist/check.js +1 -1
- package/dist/demo-server.js +1 -1
- package/dist/dev-config.js +1 -1
- package/dist/dev-shell.js +1 -1
- package/dist/dev.js +10 -10
- package/dist/devtools.js +1 -1
- package/dist/gen-explore.js +1 -1
- package/dist/gen-trajectory.js +1 -1
- package/dist/init.js +4 -4
- package/dist/ink.js +1 -1
- package/dist/inquirer.js +1 -0
- package/dist/json-file.js +1 -1
- package/dist/kit-dev-options.js +1 -1
- package/dist/legacy-upload.js +1 -1
- package/dist/lepus.js +1 -1
- package/dist/ora.js +1 -1
- package/dist/project-layout.js +1 -1
- package/dist/prompt.js +1 -1
- package/dist/prompts.js +1 -1
- package/dist/report.js +1 -1
- package/dist/run-registry.js +1 -1
- package/dist/run.js +44 -44
- package/dist/sandbox.js +1 -1
- package/dist/scan.js +1 -1
- package/dist/sdk.js +63 -188
- package/dist/sdk~1.js +50 -50
- package/dist/server.js +1 -1
- package/dist/skill.js +1 -1
- package/dist/skills.js +1 -1
- package/dist/skills~1.js +2 -1
- package/dist/static/assets/web-view-proxy-bootstrap.js +1 -0
- package/dist/static/assets/web-view-proxy-page-client.js +1 -1
- package/dist/static/assets/web-view-proxy-service-worker.js +1 -1
- package/dist/status~1.js +1 -1
- package/dist/stop.js +1 -1
- package/dist/sync.js +1 -1
- package/dist/templates/README.md +0 -1
- package/dist/update.js +1 -1
- package/dist/workspace.js +1 -1
- package/dist/wrapper.js +1 -0
- package/dist/yaml.js +1 -1
- package/package.json +2 -2
- package/skills/dbx-eval/SKILL.md +15 -7
- package/skills/doubao-agentic-service-development/SKILL.md +1 -1
- package/skills/doubao-agentic-service-development/references/auth.md +1 -1
- package/skills/doubao-agentic-service-development/references/dev-debug.md +3 -3
- package/skills/doubao-agentic-service-development/references/frontend/components/map-canvas.md +1 -1
- package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/07-/347/225/214/351/235/242.md +0 -6
- package/skills/doubao-agentic-service-development/references/frontend/guides/debugger-mcp.md +2 -2
- package/skills/doubao-agentic-service-development/references/frontend/widget-templates/props.md +1 -1
- package/skills/doubao-agentic-service-development/references/frontend-dev.md +3 -3
- package/skills/doubao-agentic-service-development/references/local-debug/overview.md +2 -2
- package/skills/doubao-agentic-service-development/references/overview.md +16 -31
- package/skills/doubao-agentic-service-development/scripts/workspace.py +6 -89
- package/dist/180.js +0 -1
- package/dist/8891.js +0 -280
- package/dist/9635.js +0 -1
- package/dist/assets/web-sdk-debugger/static/js/index.75528d6de7.js +0 -26
- package/dist/dbx.js +0 -3
- package/dist/skills~2.js +0 -2
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
(()=>{"use strict";var e,t,r,n,a,i,s,o,l,d,u,c,p={51441(e,t,r){let n,a;r(52205),r(40768),r(76235),r(15254),r(42949),r(18723),r(37891);var i=r(63159);r(76181);var s=r(50347);function o(e){return(null==e?void 0:e.type)==="call"}function l(e){return(null==e?void 0:e.type)==="callback"}class d 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 u(e,t){return{type:"callback",callbackId:e.callbackId,params:{code:1,data:t}}}function c(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:t;return{type:"callback",callbackId:e.callbackId,params:{code:0,msg:t,errNo:r,errMsg:n}}}function p(e){return e instanceof Error?e.message:String(e)}function m(e,t){return t instanceof d?c(e,t.message,t.errNo,t.errMsg):c(e,p(t))}function h(){return null==n?void 0:n.getPackageInfo()}function g(e){var t;let{screenWidth:r,statusBarHeight:n}=e??(null==(t=globalThis.lynx)?void 0:t.__globalProps),a=Math.round(n)+4,i=Math.round(r)-12;return{bottom:a+36,height:36,left:i-84,right:i,top:a,width:84}}r(49678),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(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),r(14104);class f{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 n=this.registry.get(e),a="function"==typeof t?{handler:t,canIUse:!0}:{...t,canIUse:t.canIUse??!0};return this.registry.set(e,a),this.handlers[e]=a.handler,()=>{if(this.registry.get(e)===a){if(n){this.registry.set(e,n),this.handlers[e]=n.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[n,a]of Object.entries(e))r.push(this.register(n,a,t))}catch(e){for(let e of r.reverse())e();throw e}return()=>{for(let e of r.reverse())e()}}get(e){var t;return null==(t=this.registry.get(e))?void 0:t.handler}getSyncResults(e){let t={};for(let[r,n]of this.registry)n.syncResult&&this.canIUse(r,e)&&(t[r]="function"==typeof n.syncResult?n.syncResult({...e,apiRegistry:this}):n.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 n=this.eventSources.get(e),a="function"==typeof t?{source:t}:t;return this.stopEventSource(e),this.eventSources.set(e,a),(this.eventSourceRetainCounts.get(e)??0)>0&&this.startEventSource(e,a),()=>{if(this.eventSources.get(e)===a){if(this.stopEventSource(e),n){this.eventSources.set(e,n),(this.eventSourceRetainCounts.get(e)??0)>0&&this.startEventSource(e,n);return}this.eventSources.delete(e)}}}registerEventSources(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=[];try{for(let[n,a]of Object.entries(e))r.push(this.registerEventSource(n,a,t))}catch(e){for(let e of r.reverse())e();throw e}return()=>{for(let e of r.reverse())e()}}canIUse(e,t){let r=this.registry.get(e);if(r)return"function"==typeof r.canIUse?r.canIUse({...t,apiRegistry:this}):r.canIUse;let n=this.eventSources.get(e);return!!n&&("function"==typeof n.canIUse?n.canIUse({...t,apiRegistry:this}):n.canIUse??!0)}dispatch(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!o(e))return;let r={...t,apiRegistry:this};if(this.canIUse(e.name,r))return function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!o(e))return;let n=t[e.name];if(!n)return c(e,`API ${e.name} is not implemented in Doubao Web SDK`);try{let t=n(e,r);if(t instanceof Promise)return t.catch(t=>m(e,t));return t??c(e,`API ${e.name} is not implemented in Doubao Web SDK`)}catch(t){return m(e,t)}}(e,this.handlers,r);let n=r.onUnsupportedAPI;if(!n)return c(e,`API ${e.name} is not implemented in Doubao Web SDK`);try{let t=n(e.name);return t instanceof Promise?t.then(()=>u(e,{})).catch(t=>m(e,t)):u(e,{})}catch(t){return m(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 n of this.eventControllers)r=n.emit(e,t)||r;return r}createEventController(e){return new v(this,e)}fork(){let e=new f(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)}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 v{apiRegistry;dispatch;cleanupRegistry;subscribedEventNames=new Set;constructor(e,t){this.apiRegistry=e,this.dispatch=t,this.cleanupRegistry=this.apiRegistry.attachEventController(this)}subscribe(e){this.subscribedEventNames.has(e)||(this.subscribedEventNames.add(e),this.apiRegistry.retainEventSource(e))}unsubscribe(e){this.subscribedEventNames.delete(e)&&this.apiRegistry.releaseEventSource(e)}emit(e,t){return!!this.subscribedEventNames.has(e)&&(this.dispatch(e,t),!0)}destroy(){for(let e of this.subscribedEventNames)this.apiRegistry.releaseEventSource(e);this.subscribedEventNames.clear(),this.cleanupRegistry()}}let y=new f;function _(){return(navigator.language||"zh-CN").replace("-","_")}function b(){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 w(){return"u"<typeof DoubaoAppsSDKVersion?void 0:DoubaoAppsSDKVersion}function S(){return navigator.userAgentData}function x(){var e;let t=null==(e=S())?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 n=navigator.userAgent??"";return/edg\//i.test(n)?"Microsoft Edge":/chrome|crios/i.test(n)?"Chrome":/firefox|fxios/i.test(n)?"Firefox":/safari/i.test(n)?"Safari":"Browser"}function I(){var e,t;let r=null==(e=S())?void 0:e.brands,n=null==r?void 0:r.find(e=>{let{brand:t}=e;return!/not.a.brand/i.test(t)});if(null==n?void 0:n.version)return n.version;let a=navigator.userAgent??"";return(null==(t=/(?:edg|chrome|crios|firefox|fxios|version)\/([\d.]+)/i.exec(a))?void 0:t[1])??void 0}function E(){var e;let t=navigator.userAgent??"",r=navigator.platform??"",n=(null==(e=S())?void 0:e.platform)??"",a=`${n} ${r} ${t}`,i=navigator.maxTouchPoints??0;return/android/i.test(a)?{platform:"android",brand:"Android"}:/iphone/i.test(a)?{platform:"ios",brand:"iPhone"}:/ipad/i.test(a)||/mac/i.test(r)&&i>1?{platform:"ios",brand:"iPad"}:/mac/i.test(a)?{platform:"mac",brand:"Mac"}:/win/i.test(a)?{platform:"windows",brand:"Windows"}:/linux/i.test(a)?{platform:"linux",brand:"Linux"}:{platform:"web",brand:"Browser"}}function C(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:h();return{appId:(null==e?void 0:e.appId)??"",name:(null==e?void 0:e.name)??"",iconSrc:null==e?void 0:e.iconSrc}}function k(){var e,t,r,n,a;let i=Math.round((null==(n=window.visualViewport)?void 0:n.width)??window.innerWidth??0),s=Math.round((null==(a=window.visualViewport)?void 0:a.height)??window.innerHeight??0),o=window.devicePixelRatio??1,l=Math.round((null==(e=window.screen)?void 0:e.width)??i),d=Math.round((null==(t=window.screen)?void 0:t.height)??s),u=Math.round((null==(r=window.visualViewport)?void 0:r.offsetTop)??0);return{pixelRatio:o,screenWidth:l,screenHeight:d,windowWidth:i,windowHeight:s,statusBarHeight:u,safeArea:{left:0,right:i,top:u,bottom:s,width:i,height:Math.max(0,s-u)},screenTop:u}}function N(){return E().platform}function T(){var e,t,r,n,a;let i=navigator.userAgent??"",s=N();return"android"===s?null==(e=/android\s+([\d.]+)/i.exec(i))?void 0:e[1]:"ios"===s?null==(r=/(?:iphone os|cpu os)\s+([\d_]+)/i.exec(i))||null==(t=r[1])?void 0:t.replace(/_/g,"."):"mac"===s?null==(a=/mac os x\s+([\d_]+)/i.exec(i))||null==(n=a[1])?void 0:n.replace(/_/g,"."):void 0}function R(){return{isConnected:!0,networkType:"unknown",hasSystemProxy:!1,weakNet:!1}}function M(){let e,t=E(),r=navigator.platform||N();return{abi:r,deviceAbi:r,benchmarkLevel:-1,brand:t.brand,model:function(){let e=navigator.userAgent??"",t=N();if("android"===t){var r,n;return(null==(n=/android\s+[\d.]+;\s*([^;)]+)/i.exec(e))||null==(r=n[1])?void 0:r.trim())||"Android"}return"ios"===t?E().brand:"mac"===t||"windows"===t||"linux"===t?navigator.platform||E().brand:x()}(),system:function(){let e=N(),t=T();if("android"===e)return t?`Android ${t}`:"Android";if("ios"===e)return t?`iOS ${t}`:"iOS";if("mac"===e)return t?`macOS ${t}`:"macOS";if("windows"===e)return"Windows";if("linux"===e)return"Linux";let r=I(),n=x();return r?`${n} ${r}`:"Web"}(),platform:t.platform,cpuType:r,memorySize:"number"==typeof(e=navigator.deviceMemory)&&Number.isFinite(e)?String(Math.round(1024*e)):""}}function A(){let e=M(),t=k(),r=t.windowWidth>t.windowHeight;return{os:e.platform,osVersion:T(),deviceBrand:e.brand,deviceModel:e.model,deviceType:e.model,channel:"debug",screenOrientation:+!!r,isLandscape:+!!r,abi:e.abi}}function P(){let e=k(),t=M();return{...e,brand:t.brand,model:t.model,language:_(),version:I(),system:t.system,platform:t.platform,SDKVersion:w(),theme:b(),benchmarkLevel:-1,enableDebug:!0,deviceOrientation:e.windowWidth>e.windowHeight?"landscape":"portrait",abi:t.abi}}function j(){let e=k();return{bluetoothEnabled:!1,locationEnabled:!0,wifiEnabled:R().isConnected,deviceOrientation:e.windowWidth>e.windowHeight?"landscape":"portrait"}}function L(){let e=R();return{networkType:e.networkType,signalStrength:e.signalStrength,hasSystemProxy:e.hasSystemProxy??!1,weakNet:e.weakNet??!1}}function D(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:h();return{SDKVersion:w(),enableDebug:!0,host:{appId:C(e).appId},language:_(),version:I(),theme:b()}}function O(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:h();return{miniProgram:{appId:C(e).appId,envVersion:"develop",version:(null==e?void 0:e.versionName)??""}}}function U(e){return null==e?void 0:e.packageInfo}function q(e){return"object"==typeof e&&null!==e}function $(e,t){var r;let n=null==(r=globalThis.navigator)?void 0:r.clipboard;if(!n||"function"!=typeof n[t])throw Error(`${e} is not supported in this browser`);return n}function B(e,t){let r=t instanceof Error?t.message:String(t);return`${e} failed: ${r}`}async function F(e){let t=$("setClipboardData","writeText");try{await t.writeText(e)}catch(e){throw Error(B("setClipboardData",e))}}async function W(){let e=$("getClipboardData","readText");try{let t=await e.readText();if("string"==typeof t)return t}catch(e){throw Error(B("getClipboardData",e))}throw Error("getClipboardData failed: clipboard did not return text")}function H(){return{pages:(null==n?void 0:n.getCurrentPages())??[]}}y.handlers,r(46455);let z="doubao-web-sdk:storage:";function V(e){return`${z}${e}`}function G(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 J(e){if(K(e)>1048576)throw Error("data size must be less than or equal to 1048576 bytes")}function K(e){return new TextEncoder().encode(e).byteLength}function X(e){return Object.values(e).reduce((e,t)=>e+K(t),0)}function Q(e){if(e>0xa00000)throw new d("total storage size exceeded",1600002)}function Y(e){let t={};for(let r=0;r<e.length;r+=1){let n=e.key(r);(null==n?void 0:n.startsWith(z))&&(t[n.slice(z.length)]=e.getItem(n)??"")}return t}function Z(e,t){if(!q(e))return;let r=e[t];return"string"==typeof r&&r.length>0?r:void 0}function ee(e){if(!q(e)||!q(e.packageInfo))return;let{appId:t,iconSrc:r,name:n,versionName:a}=e.packageInfo;return{appId:"string"==typeof t?t:void 0,iconSrc:"string"==typeof r?r:void 0,name:"string"==typeof n?n:void 0,versionName:"string"==typeof a?a:void 0}}function et(e){let t=ee(e),r=(null==t?void 0:t.appId)??Z(e,"appName")??"unknown-app",n=Z(e,"userId")??Z(e,"userID")??"anonymous";return`${encodeURIComponent(r)}:${encodeURIComponent(n)}`}function er(){let e=Date.now();return{entries:{"/":{type:"directory",createTime:e,lastModifiedTime:e},"/temp":{type:"directory",createTime:e,lastModifiedTime:e},"/user":{type:"directory",createTime:e,lastModifiedTime:e}}}}function en(e){return`doubao-web-sdk:file-system:${encodeURIComponent(e)}`}function ea(e,t){var r;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:et(e),a=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:y;return e.getSupportedNames({apiRegistry:e})}(t);return{fileSystemNamespace:n,fileSystemSnapshot:function(e){let t=localStorage.getItem(en(e));if(!t)return er();try{let e=JSON.parse(t);if(q(e)&&q(e.entries))return e}catch{}return er()}(n),apiResults:(r=ee(e),(t??y).getSyncResults({globalProps:e,packageInfo:r})),storageSnapshot:Y(localStorage),supportedAPIs:a}}r(21301);let ei={"doubao.getClipboardData":async e=>u(e,{data:await W()}),"doubao.setClipboardData":async e=>{let{data:t}=function(e){if(!q(e)||"string"!=typeof e.data)throw Error("data must be a string");return{data:e.data}}(e.params);return await F(t),u(e,{})},"applet.subscribeEvent":(e,t)=>{let r=q(e.params)&&"string"==typeof e.params.eventName?e.params.eventName:"";if(r){var n;null==t||null==(n=t.events)||n.subscribe(r)}return u(e,{})},"applet.unsubscribeEvent":(e,t)=>{let r=q(e.params)&&"string"==typeof e.params.eventName?e.params.eventName:"";if(r){var n;null==t||null==(n=t.events)||n.unsubscribe(r)}return u(e,{})},"doubao.getCurrentPages":{handler:e=>u(e,H()),syncResult:H},"doubao.navigateTo":e=>{var t;return(t=e.params,null==n||n.navigateTo(t),n)?u(e,{}):c(e,"No active Runtime to navigate")},"doubao.redirectTo":e=>{var t;return(t=e.params,null==n||n.redirectTo(t),n)?u(e,{}):c(e,"No active Runtime to redirect")},"doubao.reLaunch":e=>{var t;return(t=e.params,null==n||n.reLaunch(t),n)?u(e,{}):c(e,"No active Runtime to relaunch")},"doubao.navigateBack":e=>{var t;return(t=e.params??{},null==n||n.navigateBack(t),n)?u(e,{}):c(e,"No active Runtime to navigate back")},"doubao.exitApp":e=>(null==n||n.exitApp(),n)?u(e,{}):c(e,"No active Runtime to exit app"),"doubao.close":e=>{var t;return(t=e.params??{},null==n||n.close(t),n)?u(e,{}):c(e,"No active Runtime to close page")},"doubao.setStorage":e=>{var t;let r,n,{key:a,data:i}=e.params,s=(t=Y(localStorage),r=G(a),J(i),n=Object.prototype.hasOwnProperty.call(t,r)?t[r]:void 0,Q(X(t)-(void 0===n?0:K(n))+K(i)),r);return localStorage.setItem(V(s),i),u(e,{})},"doubao.getStorage":e=>{let{key:t}=e.params;return u(e,{data:Y(localStorage)[G(t)]})},"doubao.removeStorage":e=>{let{key:t}=e.params,r=G(t);return localStorage.removeItem(V(r)),u(e,{})},"doubao.clearStorage":e=>{for(let e of Object.keys(Y(localStorage)))localStorage.removeItem(V(e));return u(e,{})},"doubao.getStorageInfo":e=>{var t;return u(e,{keys:Object.keys(t=Y(localStorage)),currentSize:Math.ceil(X(t)/1024),limitSize:10240})},"doubao.__webSyncBridgePersist":(e,t)=>{var r,n,a;let i=q(r=e.params)&&q(r.storageSnapshot)?r.storageSnapshot:void 0,s=q(n=e.params)&&"string"==typeof n.fileSystemNamespace?n.fileSystemNamespace:void 0,o=null==t?void 0:t.fileSystemNamespace,l=q(a=e.params)&&q(a.fileSystemSnapshot)?a.fileSystemSnapshot:void 0;return i&&function(e){let t=[];for(let[t,r]of Object.entries(e))G(t),J(r);Q(X(e));for(let e=0;e<localStorage.length;e+=1){let r=localStorage.key(e);(null==r?void 0:r.startsWith(z))&&t.push(r)}for(let e of t)localStorage.removeItem(e);for(let[t,r]of Object.entries(e))localStorage.setItem(V(t),r)}(i),o&&s===o&&l&&localStorage.setItem(en(o),JSON.stringify(l)),u(e,{})},"doubao.authorize":{handler:e=>u(e,{}),syncResult:{}},"doubao.canIUse":{handler:(e,t)=>{let{schema:r}=e.params;return u(e,{result:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:y;return t.canIUse(e,{apiRegistry:t})}(r,null==t?void 0:t.apiRegistry)})}},"doubao.getAccountInfo":{handler:e=>u(e,O()),syncResult:e=>O(U(e))},"doubao.getPackageInfo":{handler:e=>u(e,C()),syncResult:e=>C(U(e))},"doubao.getAppBaseInfo":{handler:e=>u(e,D()),syncResult:e=>D(U(e))},"doubao.getMenuButtonBoundingClientRect":{handler:(e,t)=>u(e,g(null==t?void 0:t.globalProps)),syncResult:e=>g(null==e?void 0:e.globalProps)},"doubao.getSystemInfo":{handler:e=>u(e,P()),syncResult:P},"doubao.getSystemSetting":{handler:e=>u(e,j()),syncResult:j},"doubao.getWindowInfo":{handler:e=>u(e,k()),syncResult:k},"doubao.getDeviceInfo":{handler:e=>u(e,M()),syncResult:M},"doubao.getNetworkType":{handler:e=>u(e,L()),syncResult:L}};function es(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.apiRegistry??y;return(r,n,a)=>{if(("AppletJSModule"!==a||"log"!==r)&&"AppletBridgeModule"===a&&"postMessage"===r)return t.dispatch(n,e)}}function eo(e){if(!e.resourceUrl)throw Error("Container.render requires a resourceUrl");return e.resourceUrl}function el(e){return e.containerType??"PAGE"}function ed(e){return"WIDGET"===e?"content":"fill"}y.registerMany(ei,{override:!0}),y.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}),r(74678),r(55910),r(76691),r(72919);let eu="embed-webview",ec="__channel_ack__",ep=new WeakMap,em=e=>({url:e});function eh(e){if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}}function eg(e){return"string"==typeof e?e:JSON.stringify(e??{})}let ef=globalThis.HTMLElement??class{};r(31178);let ev="region-to-decode";function ey(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:n,height:a}=e;return![t,r,n,a].every(Number.isFinite)||t<0||r<0||n<=0||a<=0?null:{x:t,y:r,width:n,height:a}}class e_{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,ev,{configurable:!0,get:()=>ey(e.getAttribute(ev)),set:t=>{let r=ey(t);r?e.setAttribute(ev,JSON.stringify(r)):e.removeAttribute(ev)}})}connectedCallback(){this.attributes.observe(this.element,{attributes:!0,attributeFilter:[ev,"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;let r=ey(this.element.getAttribute(ev)),n=this.image;if(!r||!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,i=n.naturalHeight;if(!n.complete||!a||!i||n.getAttribute("src")!==this.element.getAttribute("src"))return void this.clearCrop();let s=Math.min(r.width,a-r.x),o=Math.min(r.height,i-r.y),l=getComputedStyle(this.element),d=Number.parseFloat(l.paddingLeft)||0,u=Number.parseFloat(l.paddingTop)||0,c=(null==(e=this.viewSize)?void 0:e.width)??this.element.clientWidth-d-(Number.parseFloat(l.paddingRight)||0),p=(null==(t=this.viewSize)?void 0:t.height)??this.element.clientHeight-u-(Number.parseFloat(l.paddingBottom)||0);if(s<=0||o<=0||c<=0||p<=0)return void this.clearCrop();let m=c/s,h=p/o,g=this.element.getAttribute("mode");"aspectFit"===g?m=h=Math.min(m,h):"aspectFill"===g?m=h=Math.max(m,h):"center"===g&&(m=h=1);let f=d+(c-s*m)/2-r.x*m,v=u+(p-o*h)/2-r.y*h;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
|
+
position: absolute !important;
|
|
3
|
+
margin: 0 !important;
|
|
4
|
+
padding: 0 !important;
|
|
5
|
+
border: 0 !important;
|
|
6
|
+
max-width: none !important;
|
|
7
|
+
max-height: none !important;
|
|
8
|
+
min-width: 0 !important;
|
|
9
|
+
min-height: 0 !important;
|
|
10
|
+
width: ${a*m}px !important;
|
|
11
|
+
height: ${i*h}px !important;
|
|
12
|
+
left: ${f}px !important;
|
|
13
|
+
top: ${v}px !important;
|
|
14
|
+
right: auto !important;
|
|
15
|
+
bottom: auto !important;
|
|
16
|
+
object-fit: fill !important;
|
|
17
|
+
clip-path: inset(${r.y*h}px ${(a-r.x-s)*m}px
|
|
18
|
+
${(i-r.y-o)*h}px ${r.x*m}px) !important;
|
|
19
|
+
}`};dispose(){this.attributes.disconnect(),this.stopRendering()}}let eb=new Set;class ew{element;static observedAttributes=[];constructor(e){this.element=e}forwardLinkEvent=e=>{this.element.dispatchEvent(new CustomEvent("link",{detail:e.detail,bubbles:!0,composed:!0}))};connectedCallback(){this.element.addEventListener("bindlink",this.forwardLinkEvent);let e=this.element.markdownStyle??{};this.element.markdownStyle={...e,link:{...e.link,textDecoration:"none"},orderedList:{...e.orderedList,paddingLeft:0},unorderedList:{...e.unorderedList,paddingLeft:0}}}}function eS(e){var t;null==(t=e.registerPlugin)||t.call(e,ew)}let ex="x-video-engine",eI=globalThis.HTMLElement??class{};if("object"!=typeof customElements||customElements.get(eu)||customElements.define(eu,class e extends ef{static observedAttributes=["src"];#e=null;#t=null;#r=!1;messageOrigin;connectedCallback(){this.#r=!0,this.style.display||(this.style.display="block"),this.#n(),this.#a()}disconnectedCallback(){var e;this.#r=!1,this.#i(),null==(e=this.#e)||e.remove(),this.#e=null,window.removeEventListener("message",this.#s)}attributeChangedCallback(e){"src"===e&&this.#r&&this.#a()}get src(){return this.getAttribute("src")}set src(e){null===e?this.removeAttribute("src"):this.setAttribute("src",e)}reload(){this.#a(!0)}postMessage(e){let t=q(e)?e.data:void 0;this.#o({type:"event",name:"message",params:{data:t},timestamp:Date.now()})}eval(e){let t=q(e)&&"string"==typeof e.func?e.func:"";if(t)try{if(this.messageOrigin){var r,n;null==(n=this.#e)||null==(r=n.contentWindow)||r.postMessage({type:"__doubao_web_view_eval__",code:t},this.messageOrigin);return}let e=this.#l();null==e||e.eval(t)}catch{}}onGoBack(){return{consumed:!1}}#n(){if(this.#e)return this.#e;let e=this.shadowRoot??this.attachShadow({mode:"open"}),t=document.createElement("iframe");return t.style.cssText="display:block;width:100%;height:100%;border:none;",t.addEventListener("load",this.#d),t.addEventListener("error",this.#u),e.replaceChildren(t),this.#e=t,window.addEventListener("message",this.#s),t}#a(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.#n(),r=this.getAttribute("src");if(!r)return;let n=em(r);this.messageOrigin="window"===n.messageTransport?new URL(n.url,document.baseURI).origin:void 0,(e||t.getAttribute("src")!==n.url)&&(this.#i(),t.toggleAttribute("credentialless",!0===n.credentialless),t.src=n.url)}#i(){var e;null==(e=this.#t)||e.close(),this.#t=null}#l(){try{var e;let t=(null==(e=this.#e)?void 0:e.contentWindow)??null;return null==t||t.document,t}catch{return null}}#d=()=>{this.messageOrigin||(this.#c(),this.#p(),this.#m()),this.#h("load",{url:this.getAttribute("src")??""})};#u=()=>{this.#h("error",{errorMsg:`Failed to load ${this.getAttribute("src")??""}`,errorCode:-1})};#s=e=>{if(!this.#e||e.source!==this.#e.contentWindow||this.messageOrigin&&e.origin!==this.messageOrigin||e.data===ec)return;let t=eh(e.data);this.#g(t)||this.#f(eg(e.data))};#c(){var e;this.#i();let t=null==(e=this.#e)?void 0:e.contentWindow;if(!t)return;let r=new MessageChannel;r.port1.onmessage=e=>{e.data!==ec&&this.#g(eh(e.data))},this.#t=r.port1,t.postMessage("__channel_init__","*",[r.port2])}#p(){let e=this.#l();e&&!e.AppletBridgeModule&&(e.AppletBridgeModule={postMessage:e=>(this.#g(eh(e)),Promise.resolve({})),postMessageSync:e=>{let t=eh(e);return o(t)?c(t,"Sync AppletBridgeModule APIs are not supported in Doubao Web SDK web-view"):void 0}})}#m(){let e=this.#l();e&&this.#f(JSON.stringify({type:"__doubao_web_view_set_title__",title:e.document.title||""}))}#g(e){if(q(e)&&"event"===e.type)return"__bridge_ready__"===e.name;if(!o(e))return!1;if("doubao.postMessage"===e.name){let t=q(e.params)?e.params.data:void 0;return this.#f(eg(t)),this.#o(u(e,{})),!0}return this.#v(e),!0}async #v(e){let t=function(e){let t=e;for(;t;){if(t instanceof Element){let e=ep.get(t);if(e)return e}let e=t.parentNode;t=e instanceof ShadowRoot?e.host:e}}(this);if(!t)return void this.#o(c(e,`API ${e.name} is not available in this web-view host`));let r=await t(e);this.#o(r??c(e,`API ${e.name} is not implemented in Doubao Web SDK`))}#o(e){var t,r,n;let a=JSON.stringify(e);if(this.messageOrigin){null==(n=this.#e)||null==(r=n.contentWindow)||r.postMessage({type:"__doubao_web_view_message__",payload:a},this.messageOrigin);return}if(this.#t)return void this.#t.postMessage(a);let i=this.#l();null==i||null==(t=i.onWebViewMessage)||t.call(i,a)}#f(e){this.#h("message",{msg:e,data:e})}#h(e,t){for(let r of[e,`bind${e}`])this.dispatchEvent(new CustomEvent(r,{bubbles:!0,composed:!0,detail:t}))}}),"object"==typeof customElements&&!a){let e=customElements.get("x-markdown");e?(eS(e),a=Promise.resolve()):a=customElements.whenDefined("x-markdown").then(e=>{eS(e)})}if("object"!=typeof customElements||customElements.get(ex)||customElements.define(ex,class e extends eI{static observedAttributes=["play-url","video-model","vid","auto-prepare","initial-time","objectfit","muted","loop","volume","speed"];video=null;prepared=!1;firstFrame=!1;stopped=!0;playbackState=-1;playRequest=0;connectedCallback(){if(this.video)return;let e=this.shadowRoot??this.attachShadow({mode:"open"}),t=document.createElement("style");t.textContent=":host{display:block;width:100%;height:100%}video{display:block;width:100%;height:100%}";let r=document.createElement("video");this.video=r,r.playsInline=!0,e.replaceChildren(t,r);let n=(e,t)=>r.addEventListener(e,e=>{e.stopPropagation(),this.video===r&&this.isConnected&&t()});n("loadedmetadata",()=>{r.currentTime=this.numberAttribute("initial-time",0)/1e3}),n("canplay",()=>this.notifyPrepared()),n("loadeddata",()=>{this.firstFrame||(this.firstFrame=!0,this.emit("firstframe"))}),n("playing",()=>{this.stopped=!1,this.setPlaybackState(1)}),n("pause",()=>this.setPlaybackState(2*!this.stopped)),n("seeked",()=>this.emit("seek")),n("timeupdate",()=>this.emit("timeupdate",{current:1e3*r.currentTime,total:Number.isFinite(r.duration)?1e3*r.duration:0})),n("ended",()=>{this.stopped=!0,this.setPlaybackState(0),this.emit("completion")}),n("error",()=>{var e,t;return this.reportError((null==(e=r.error)?void 0:e.message)||"Video resource could not be played",null==(t=r.error)?void 0:t.code)}),document.addEventListener("visibilitychange",this.handleVisibility),this.syncAttributes(),this.syncSource()}disconnectedCallback(){var e;let t=this.video;this.video=null,this.playRequest++,document.removeEventListener("visibilitychange",this.handleVisibility),t&&(t.pause(),t.removeAttribute("src"),t.load()),null==(e=this.shadowRoot)||e.replaceChildren()}attributeChangedCallback(e,t,r){this.video&&t!==r&&(["play-url","video-model","vid"].includes(e)?this.syncSource():(this.syncAttributes(),"auto-prepare"!==e||this.booleanAttribute("auto-prepare",!0)||(this.video.preload="none")))}booleanAttribute(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.getAttribute(e);return null===r?t:"false"!==r&&"0"!==r}numberAttribute(e,t){let r=this.getAttribute(e),n=null===r||""===r.trim()?NaN:Number(r);return Number.isFinite(n)&&n>=0?n:t}syncAttributes(){let e=this.video;e.muted=this.booleanAttribute("muted"),e.loop=this.booleanAttribute("loop"),e.volume=Math.min(1,this.numberAttribute("volume",1));try{e.playbackRate=this.numberAttribute("speed",1)||1,e.defaultPlaybackRate=e.playbackRate}catch(e){this.reportError(String(e))}let t=this.getAttribute("objectfit")??"contain";e.style.objectFit=["contain","cover","fill"].includes(t)?t:"contain",this.booleanAttribute("auto-prepare",!0)&&(e.preload="auto",e.controls=!0)}syncSource(){let e=this.video,t=this.getAttribute("play-url")||"";t&&e.getAttribute("src")===t||(this.playRequest++,this.prepared=this.firstFrame=!1,this.stopped=!0,this.playbackState=-1,e.pause(),e.preload=this.booleanAttribute("auto-prepare",!0)?"auto":"none",e.controls="auto"===e.preload,t?e.src=t:e.removeAttribute("src"),e.load(),queueMicrotask(()=>{this.isConnected&&this.video===e&&(this.getAttribute("play-url")||"")===t&&(t?this.emit("redirect"):(this.getAttribute("video-model")||this.getAttribute("vid"))&&this.reportError("Web VideoEngine requires play-url; video-model and vid are not supported"))}))}notifyPrepared(){var e;this.prepared||(null==(e=this.video)?void 0:e.preload)!=="auto"||(this.prepared=!0,this.emit("canplay"))}emit(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:"error"!==e}))}setPlaybackState(e){this.playbackState!==e&&(this.playbackState=e,this.emit("playbackstatechanged",{playbackState:e}))}reportError(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;this.emit("error",{errorCode:t,errorMsg:e})}getMedia(){var e;if(!(null==(e=this.video)?void 0:e.getAttribute("src")))throw Error("Web VideoEngine requires play-url");return this.video}handleVisibility=()=>{var e;document.hidden&&this.booleanAttribute("pause-on-hide")&&(null==(e=this.video)?void 0:e.getAttribute("src"))&&this.pause()};prepare(){let e=this.getMedia();e.preload="auto",e.controls=!0,this.prepared=!1,e.readyState>=3?queueMicrotask(()=>{this.video===e&&this.notifyPrepared()}):e.load()}play(){let e=this.getMedia();this.stopped=!1;let t=++this.playRequest;e.play().catch(r=>{this.video===e&&t===this.playRequest&&this.reportError(String(r))})}pause(){let e=this.getMedia();this.playRequest++,this.stopped=!1,e.pause(),this.setPlaybackState(2)}stop(){let e=this.getMedia();this.playRequest++,this.stopped=!0,e.pause(),e.currentTime=0,this.setPlaybackState(0)}seek(e){if(!e||!Number.isFinite(e.position)||e.position<0)throw Error("seek.position must be a non-negative number in milliseconds");let t=this.getMedia(),r=Math.min(e.position/1e3,Number.isFinite(t.duration)?t.duration:1/0);e.play||this.pause(),t.currentTime===r?queueMicrotask(()=>{this.video===t&&this.emit("seek")}):t.currentTime=r,e.play&&this.play()}getDuration(){let e=this.getMedia().duration;if(!Number.isFinite(e))throw Error("Video duration is not available yet");return{duration:1e3*e}}}),"object"==typeof customElements)for(let e of["x-image","filter-image"]){if(eb.has(e))continue;eb.add(e);let t=e=>{if(!(ev in e.prototype)){var t;null==(t=e.registerPlugin)||t.call(e,e_)}},r=customElements.get(e);r?t(r):customElements.whenDefined(e).then(t)}let eE="AppletBridgeModule",eC="postMessage";function ek(e,t,r){t===eC&&l(r)&&eT(e,r)}function eN(e,t,r){eT(e,{type:"event",name:t,params:r,timestamp:Date.now()})}function eT(e,t){"function"==typeof(null==e?void 0:e.sendGlobalEvent)&&e.sendGlobalEvent("__APPLET_BRIDGE__",[t])}class eR{container;className;options;runtimeContext;bridgeEvents=null;view=null;constructor(e,t={environment:"direct"}){const r=e.container;if(!r)throw Error("Container requires a container element");this.container=r,this.className=e.className??"doubao-web-container-view",this.options=e,this.runtimeContext=t}get element(){return this.view}prepare(){this.clear()}render(e){var t,r,n,a,i,d,u;let m,h,g,f,v,_,b,w;this.clear();let S=document.createElement("lynx-view"),x=el(e),I=ed(x);S.className=this.className,e.groupId&&S.setAttribute("lynx-group-id",e.groupId),S.dataset.containerType=x,S.dataset.webSizing=I,S.style.display="APP"===x||"TOOL"===x?"none":"block",S.style.width="100%",S.style.height="content"===I?"auto":"100%","content"===I&&S.setAttribute("height","auto"),S.url=eo(e),S.initData=e.initData??{};let E={...A(),...e.globalProps??{}},C="sandbox"===this.runtimeContext.environment?this.runtimeContext.syncBridgeData:ea(E,this.options.apiRegistry,this.options.fileSystemNamespace);t=this.runtimeContext.environment,m=new URL("./__doubao_web_sdk_native_modules/",(null==(r=globalThis.document)?void 0:r.baseURI)??(null==(n=globalThis.location)?void 0:n.href)??"http://localhost/").href,h=new URL("applet-bridge-module.js",m).href,g=new URL("applet-js-module.js",m).href,_={AppletBridgeModule:((v=new URLSearchParams((f=new URL(h)).hash.slice(1))).set("__doubao_sync_bridge",JSON.stringify({...C,fileSystemSnapshot:er()})),f.hash=v.toString(),f.href),AppletJSModule:g},"direct"===t&&(_.LynxConsoleModule=new URL("console-module.js",m).href,"APP"===x&&(_.LynxDevToolSetModule=g)),S.nativeModulesMap=_,(0,s.B)(S),S.globalProps={...E,__DOUBAO_WEB_SDK_SYNC_BRIDGE__:C};let k=this.options.apiRegistry??y;return this.bridgeEvents=k.createEventController((e,t)=>eN(S,e,t)),a=this.options,i=this.bridgeEvents,d=C.fileSystemNamespace,b="sandbox"===this.runtimeContext.environment,w=es({apiRegistry:a.apiRegistry,emitEvent:(e,t)=>i.emit(e,t),events:i,fileSystemNamespace:d,globalProps:E,onUnsupportedAPI:a.onUnsupportedAPI}),S.onNativeModulesCall=async(e,t,r)=>{var n,i;let s=a.appletSessionMessageHandler?await a.appletSessionMessageHandler(t,{containerType:x,element:S}):void 0;if(null==s?void 0:s.routed)return await s.result;let d=r===eE&&e===eC&&l(t);if(r===eE&&e===eC&&(null==t?void 0:t.type)==="event"&&"__bridge_ready__"===t.name&&(null==(n=a.onReady)||n.call(a)),d&&!b&&"TOOL"!==x)return ek(S,e,t),t;try{let n=await (null==(i=a.nativeModulesCallHandler)?void 0:i.call(a,e,t,r,{containerType:x,element:S}));if(d)return void 0!==n||b||ek(S,e,t),void 0===n?t:n;let s=void 0===n?await w(e,t,r):n;return ek(S,e,s),s}catch(n){let r=o(t)?c(t,p(n)):void 0;return ek(S,e,r),r}},u=e=>k.dispatch(e,{apiRegistry:k,globalProps:E,onUnsupportedAPI:this.options.onUnsupportedAPI}),ep.set(S,u),S.transformVW=!0,S.transformVH="content"!==I,S.transformREM=!0,S.addEventListener("error",e=>{var t,r;let n;null==(t=(r=this.options).onError)||t.call(r,(null==(n=e.detail)?void 0:n.error)instanceof Error?n.error:Error(String((null==n?void 0:n.error)??n??"Unknown Container runtime error")),e)}),this.view=S,this.container.replaceChildren(S),S}clear(){var e,t;null==(e=this.bridgeEvents)||e.destroy(),this.bridgeEvents=null,null==(t=this.view)||t.remove(),this.view=null,this.container.replaceChildren()}sendEvent(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};eN(this.view,e,t)}sendBridgeMessage(e){eT(this.view,e)}sendGlobalEvent(e,t){var r,n;null==(n=this.view)||null==(r=n.sendGlobalEvent)||r.call(n,e,t)}reload(){var e,t;null==(t=this.view)||null==(e=t.reload)||e.call(t)}}function eM(){return"0.3.0-rc.2"}let eA=/(?:^|[.-])[a-f\d]{8,}(?=[.-]|$)/i;function eP(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 ej{container;options;sandboxUrl;targetOrigin;bridgeEvents=null;connected=!1;failed=!1;handshakeTimer=null;loaded=!1;loadCount=0;port=null;preparedForRender=!1;preparedContainerType=null;renderMessage=null;view=null;constructor(e,t){const r=new URL(t);if("https:"!==r.protocol&&!("http:"===r.protocol&&function(e){return"localhost"===e||"::1"===e||/^127(?:\.\d{1,3}){3}$/.test(e)}(r.hostname)))throw Error("iframe isolation url must use HTTPS (HTTP is only allowed on localhost)");this.container=e.container,this.options=e,this.sandboxUrl=function(e){let t=new URL(e),r=t.pathname.slice(t.pathname.lastIndexOf("/")+1),n=eM();return n&&!eA.test(r)&&t.searchParams.set("__doubao_resource_reload",n),t.href}(r),this.targetOrigin=r.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;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 r=document.createElement("iframe");r.className=this.options.className??"doubao-web-container-view",r.dataset.containerType=e,r.dataset.webSizing=ed(e),r.referrerPolicy="no-referrer",r.title="Doubao app content",r.sandbox.add("allow-scripts","allow-same-origin"),r.setAttribute("allow","picture-in-picture 'none'"),r.src=this.sandboxUrl,r.style.display="APP"===e||"TOOL"===e?"none":"block",r.style.border="0",r.style.width="100%",r.style.height="WIDGET"===e?"0px":"100%",r.addEventListener("load",()=>this.handleLoad()),this.view=r,this.preparedContainerType=e,this.container.replaceChildren(r);let n=this.options.apiRegistry??y;return this.bridgeEvents=n.createEventController((e,t)=>this.postOrFail({type:"global-event",name:e,params:t})),r}render(e){this.preparedForRender||this.clear(),this.preparedForRender=!1;let t=el(e),r=new URL(eo(e),document.baseURI).href,n=e.initData??{},a={...A(),...e.globalProps??{}},i=ea(a,this.options.apiRegistry,this.options.fileSystemNamespace);this.renderMessage={type:"render",resourceUrl:r,containerType:t,initData:n,globalProps:a,syncBridgeData:i};try{let e=this.createView(t);return this.connected?this.postOrFail(this.renderMessage):this.loaded&&this.connect(),e}catch(e){throw this.clear(),e}}clear(){var e,t;this.connected&&this.post({type:"dispose"}),this.destroyChannel(),null==(e=this.bridgeEvents)||e.destroy(),this.bridgeEvents=null,null==(t=this.view)||t.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()}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})}reload(){this.post({type:"reload"})}abortRender(e){var t,r;throw null==(t=(r=this.options).onError)||t.call(r,e,eP(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:eM()??""};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,n;if(!e.data||"object"!=typeof e.data)return void this.fail(Error("iframe sandbox sent an invalid protocol message"),e);let a=e.data;if(!this.connected)return"connected"!==a.type||1!==a.protocolVersion?void this.fail(Error("iframe sandbox protocol version mismatch"),e):(this.connected=!0,this.clearHandshakeTimer(),void(this.renderMessage&&this.postOrFail(this.renderMessage)));switch(a.type){case"ready":null==(t=(r=this.options).onReady)||t.call(r);break;case"error":this.fail(Error(a.message),e);break;case"resize":(null==(n=this.renderMessage)?void 0:n.containerType)!=="WIDGET"||!Number.isFinite(a.height)||a.height<0?this.fail(Error("only Widget containers may resize the iframe"),e):this.view&&(this.view.style.height=`${a.height}px`,this.view.height=String(a.height));break;case"native-call":!Number.isSafeInteger(a.requestId)||a.requestId<=0||("AppletBridgeModule"!==a.moduleName||"postMessage"!==a.name)&&("AppletJSModule"!==a.moduleName&&"LynxConsoleModule"!==a.moduleName&&"Console"!==a.moduleName||"log"!==a.name)?this.fail(Error("iframe sandbox sent an invalid bridge call"),e):this.handleNativeCall(a);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=es({apiRegistry:this.options.apiRegistry??y,emitEvent:(e,t)=>{var r;return(null==(r=this.bridgeEvents)?void 0:r.emit(e,t))??!1},events:this.bridgeEvents??void 0,fileSystemNamespace:this.renderMessage.syncBridgeData.fileSystemNamespace,globalProps:this.renderMessage.globalProps,onUnsupportedAPI:this.options.onUnsupportedAPI});try{var n,a,i,s;let o=await (null==(n=(a=this.options).appletSessionMessageHandler)?void 0:n.call(a,e.data,{containerType:this.renderMessage.containerType,element:this.view}));t=(null==o?void 0:o.routed)?await o.result:await ((null==(i=(s=this.options).nativeModulesCallHandler)?void 0:i.call(s,e.name,e.data,e.moduleName,{containerType:this.renderMessage.containerType,element:this.view}))??r(e.name,e.data,e.moduleName))}catch(t){this.postOrFail({type:"bridge-result",requestId:e.requestId,error:p(t)});return}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,n,a;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:eP(e);this.failed||(this.failed=!0,this.destroyChannel(),null==(t=this.bridgeEvents)||t.destroy(),this.bridgeEvents=null,null==(r=this.view)||r.remove(),this.view=null,this.renderMessage=null,null==(n=(a=this.options).onError)||n.call(a,e,i))}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}}function eL(e){return q(e.web)&&"string"==typeof e.web.entry}function eD(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"])}function eO(e,t){let r=new Map;for(let n of e){let e=t(n);e&&!r.has(e)&&r.set(e,n)}return r}class eU{raw;appEntry;pageEntries;pageIdEntryMap;pagePathEntryMap;widgetEntries;widgetEntryMap;constructor(e){this.raw=e,this.appEntry=function(e){var t;let r=(null==(t=e.applet.web)?void 0:t.appRuntimeEntry)??e.applet.appRuntimeEntry;return"string"==typeof r&&r?{entry:r}:null}(e),this.pageEntries=e.applet.pages.filter(eL),this.pageIdEntryMap=eO(this.pageEntries,e=>e.id),this.pagePathEntryMap=eO(this.pageEntries,e=>e.path),this.widgetEntries=e.widgets.filter(eL),this.widgetEntryMap=eO(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 eD(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]}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=e?this.widgetEntryMap.get(e):this.widgetEntries[0];if(!t)throw Error(e?`Unknown widgets entry: ${e}`:"No widgets entries in Web manifest");return t}}async function eq(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.fetcher??fetch,n=await r(e,{cache:"no-store",headers:{Accept:"application/json"}});if(!n.ok)throw Error(`Failed to load Web manifest: ${n.status} ${n.statusText}`);let a=await n.json();if(!q(a))throw Error("Invalid Web manifest: expected a JSON object");return new eU(a)}function e$(e,t,r){var n;let a="item"in t?t.item:t,i="web"in a&&q(a.web)&&"string"==typeof a.web.entry?function(e){if(q(e.web)&&"string"==typeof e.web.entry)return e.web.entry;throw Error(`No Web entry configured for manifest entry: ${"widgetId"in e?e.widgetId:e.id}`)}(a):a.entry,s=new URL(e,r??(null==(n=globalThis.location)?void 0:n.href)??"http://localhost/");return s.pathname.endsWith("/web/manifest.json")?s.pathname=s.pathname.slice(0,-17):s.pathname.endsWith("/base/manifest.json")?s.pathname=s.pathname.slice(0,-18):s.pathname=s.pathname.replace(/\/[^/]*$/,"/"),s.search="",s.hash="",new URL(i,s).toString()}function eB(){var e;return(null==(e=globalThis.location)?void 0:e.href)??"http://localhost/"}function eF(e){return new URL(e,eB()).toString()}function eW(e,t){if(!t)return e;let r=new URL(e,eB());return r.searchParams.set("__doubao_resource_reload",t),r.toString()}class eH{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 getManifestUrl(e){if(!this.resolveManifestUrl)throw Error("PackageManagerService requires resolveManifestUrl");return this.resolveManifestUrl({appId:e})}async loadPackage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=eF(await this.getManifestUrl(e)),n=this.packages.get(r);if(n&&!t.forceReload)return n;let a=eq(r,{fetcher:this.options.fetcher}).then(e=>({manifest:e,manifestUrl:r}));return a.catch(()=>{this.packages.get(r)===a&&this.packages.delete(r)}),this.packages.set(r,a),a}deletePackage(e){this.packages.delete(eF(e))}clearPackageCache(e){e?this.deletePackage(e):this.packages.clear()}async resolveWidget(e,t){let r=await this.loadPackage(e),n=r.manifest.getWidgetEntry(t);return{appId:r.manifest.appId,entry:n,iconSrc:r.manifest.iconSrc,appName:r.manifest.name,resourceUrl:eW(e$(r.manifestUrl,n),this.resourceUrlVersion)}}}let ez=new eH,eV="https://apps-web-sdk-sandbox.doubaocdn.com/sandbox",eG=eV,eJ=Object.freeze({mode:"iframe",createContainer:e=>new ej(e,eG)}),eK=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
20
|
+
<path d="M3.74902 7.91113C4.90234 7.91131 5.83691 8.84664 5.83691 10C5.83674 11.1532 4.90223 12.0877 3.74902 12.0879C2.59566 12.0879 1.66033 11.1533 1.66016 10C1.66016 8.84653 2.59555 7.91113 3.74902 7.91113ZM9.99805 7.91113C11.1514 7.91131 12.0859 8.84664 12.0859 10C12.0858 11.1532 11.1513 12.0877 9.99805 12.0879C8.84469 12.0879 7.90936 11.1533 7.90918 10C7.90918 8.84653 8.84458 7.91113 9.99805 7.91113ZM16.249 7.91113C17.4023 7.91131 18.3369 8.84664 18.3369 10C18.3367 11.1532 17.4022 12.0877 16.249 12.0879C15.0957 12.0879 14.1603 11.1533 14.1602 10C14.1602 8.84653 15.0956 7.91113 16.249 7.91113Z" fill="black"/>
|
|
21
|
+
</svg>`,eX=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
22
|
+
<path d="M9.99622 18.176C8.86678 18.176 7.8086 17.9623 6.82166 17.5348C5.83472 17.1126 4.96653 16.5267 4.21709 15.7773C3.46765 15.0331 2.87919 14.1676 2.45169 13.1806C2.02947 12.1884 1.81836 11.1276 1.81836 9.99817C1.81836 8.86873 2.02947 7.81055 2.45169 6.82361C2.87919 5.8314 3.46765 4.96057 4.21709 4.21113C4.96653 3.46169 5.83472 2.87586 6.82166 2.45364C7.8086 2.03142 8.86678 1.82031 9.99622 1.82031C11.1257 1.82031 12.1838 2.03142 13.1708 2.45364C14.163 2.87586 15.0338 3.46169 15.7833 4.21113C16.5327 4.96057 17.1185 5.8314 17.5408 6.82361C17.9682 7.81055 18.182 8.86873 18.182 9.99817C18.182 11.1276 17.9682 12.1884 17.5408 13.1806C17.1185 14.1676 16.5327 15.0331 15.7833 15.7773C15.0338 16.5267 14.163 17.1126 13.1708 17.5348C12.1838 17.9623 11.1257 18.176 9.99622 18.176ZM9.99622 16.561C10.904 16.561 11.7537 16.3895 12.5454 16.0465C13.337 15.7087 14.0337 15.239 14.6354 14.6373C15.2423 14.0356 15.7147 13.339 16.0524 12.5473C16.3902 11.7557 16.5591 10.9059 16.5591 9.99817C16.5591 9.0904 16.3902 8.24068 16.0524 7.44902C15.7147 6.65208 15.2423 5.95542 14.6354 5.35904C14.0337 4.75738 13.337 4.28766 12.5454 3.94988C11.7537 3.60683 10.904 3.4353 9.99622 3.4353C9.09373 3.4353 8.24401 3.60683 7.44707 3.94988C6.65541 4.28766 5.95875 4.75738 5.35708 5.35904C4.75542 5.95542 4.28306 6.65208 3.94001 7.44902C3.60224 8.24068 3.43335 9.0904 3.43335 9.99817C3.43335 10.9059 3.60224 11.7557 3.94001 12.5473C4.28306 13.339 4.75542 14.0356 5.35708 14.6373C5.95875 15.239 6.65541 15.7087 7.44707 16.0465C8.24401 16.3895 9.09373 16.561 9.99622 16.561ZM10.0041 13.0856C9.43414 13.0856 8.91164 12.9458 8.43665 12.6661C7.96693 12.3863 7.59221 12.0116 7.31249 11.5419C7.03277 11.0722 6.89291 10.5523 6.89291 9.98234C6.89291 9.41234 7.03277 8.89248 7.31249 8.42277C7.59221 7.95305 7.96693 7.57833 8.43665 7.29861C8.91164 7.01361 9.43414 6.87111 10.0041 6.87111C10.5741 6.87111 11.0914 7.01361 11.5558 7.29861C12.0255 7.57833 12.4002 7.95305 12.68 8.42277C12.9597 8.89248 13.0995 9.41234 13.0995 9.98234C13.0995 10.5523 12.9597 11.0722 12.68 11.5419C12.4002 12.0116 12.0255 12.3863 11.5558 12.6661C11.0914 12.9458 10.5741 13.0856 10.0041 13.0856Z" fill="black"/>
|
|
23
|
+
</svg>`,eQ="doubao-apps-page",eY={body:`${eQ}__body`,capsule:`${eQ}__capsule`,capsuleAction:`${eQ}__capsule-action`,capsuleCloseIcon:`${eQ}__capsule-close-icon`,capsuleMoreIcon:`${eQ}__capsule-more-icon`,root:eQ};class eZ{host;options;runtimeKernel;container=null;root=null;constructor(e,t){if(!e.container)throw Error("Page requires a container element");this.host=e.container,this.options=e,this.runtimeKernel=t}get element(){var e;return(null==(e=this.container)?void 0:e.element)??null}render(e){var t;let r;this.clear();let n=document.createElement("div");n.className=eY.root,void 0!==(r=null==(t=e.pageCapsule)?void 0:t.statusBarHeight)&&n.style.setProperty("--doubao-page-capsule-top",`${r+4}px`);let a=document.createElement("div");return a.className=eY.body,n.append(a,this.createCapsule()),this.host.replaceChildren(n),this.root=n,this.container=this.runtimeKernel.createContainer({apiRegistry:this.options.apiRegistry,container:a,className:this.options.className,fileSystemNamespace:this.options.fileSystemNamespace,nativeModulesCallHandler:this.options.nativeModulesCallHandler,onError:this.options.onError,onReady:this.options.onReady}),this.container.render({resourceUrl:function(e){if(!e.resourceUrl)throw Error("Page.render requires a resourceUrl");return e.resourceUrl}(e),groupId:e.groupId,containerType:"PAGE",initData:e.initData,globalProps:e.globalProps})}clear(){var e,t;null==(e=this.container)||e.clear(),this.container=null,null==(t=this.root)||t.remove(),this.root=null,this.host.replaceChildren()}sendEvent(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};null==(t=this.container)||t.sendEvent(e,r)}reload(){var e;null==(e=this.container)||e.reload()}dispatchCapsuleEvent(e,t){t.stopPropagation(),this.host.dispatchEvent(new CustomEvent(e,{bubbles:!0}))}createCapsuleSvg(e){let t=document.createElement("template");t.innerHTML=e.trim();let r=t.content.firstElementChild;if(!r||"svg"!==r.tagName.toLowerCase())throw Error("Invalid Page capsule icon SVG");return r}createCapsuleAction(e,t,r,n){let a=this.createCapsuleSvg(r);return a.classList.add(eY.capsuleAction,e),a.setAttribute("role","button"),a.setAttribute("aria-label",t),a.setAttribute("tabindex","0"),a.setAttribute("focusable","true"),a.addEventListener("click",e=>{this.dispatchCapsuleEvent(n,e)}),a.addEventListener("keydown",e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),this.dispatchCapsuleEvent(n,e))}),a}createCapsuleMoreIcon(){return this.createCapsuleAction(eY.capsuleMoreIcon,"More",eK,"doubao:page-capsule-more")}createCapsuleCloseIcon(){return this.createCapsuleAction(eY.capsuleCloseIcon,"Close app",eX,"doubao:page-capsule-close")}createCapsule(){let e=document.createElement("div");return e.className=eY.capsule,e.style.display="flex",e.style.flexDirection="row",e.setAttribute("role","group"),e.setAttribute("aria-label","Page actions"),e.append(this.createCapsuleMoreIcon(),this.createCapsuleCloseIcon()),e}}let e0=/\{\{\s*([^{}\s]+)\s*\}\}/g;function e1(e){return"string"==typeof e?e:JSON.stringify(e)}function e2(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={...e.input||{},...function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={};for(let[n,a]of Object.entries(e.variables||{}))Object.prototype.hasOwnProperty.call(t,n)?r[n]=t[n]:null!==a&&(r[n]=a);return{...r,...t}}(e,t)};if("page"===e.type){let t=function(e,t){var r;let n=new Set(Array.from(e.url.matchAll(e0),e=>e[1])),a=(r=e.url,r.replace(e0,(e,r)=>{if(!Object.prototype.hasOwnProperty.call(t,r))return e;let n=e1(t[r]);return void 0===n?e:encodeURIComponent(n)})),i=a.indexOf("#"),s=i<0?a:a.slice(0,i),o=i<0?"":a.slice(i),l=s.indexOf("?"),d=new Set(new URLSearchParams(l<0?"":s.slice(l+1)).keys()),u=new URLSearchParams;for(let[e,r]of Object.entries(t)){if(n.has(e)||d.has(e))continue;let t=e1(r);void 0!==t&&u.set(e,t)}let c=u.toString();if(!c)return a;let p=l<0?"?":s.endsWith("?")||s.endsWith("&")?"":"&";return`${s}${p}${c}${o}`}(e,r);return{type:"page",unresolvedVariables:function(e){let t=new Set;for(let r of e.matchAll(e0))t.add(r[1]);return Array.from(t)}(t),url:t}}return"widget"===e.type?{type:"widget",id:e.id,resolvedInput:r,botId:e.botId}:{type:"tool",id:e.id,resolvedInput:r}}function e3(e){var t;let{addProtocolToBareHost:r=!1,allowRootRelative:n=!1,defaultProtocol:a="http"}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(/^https?:\/\//i.test(e))return e;if(e.startsWith("//"))return`${e5(a,e.slice(2))}:${e}`;if(n&&e.startsWith("/"))return e;return/^(?:\[[^\]]+\]|[a-z0-9.-]+):\d+(?:[/?#]|$)/i.test(e)||r&&(t=e,/^(?:\[[^\]]+\]|[a-z0-9.-]+)(?:[/?#]|$)/i.test(t))?`${e5(a,e)}://${e}`:e}function e4(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=String(e??"").trim();if(!r)return;let n=e3(r,t);try{let e=t.baseUrl?new URL(n,t.baseUrl):new URL(n);if("http:"!==e.protocol&&"https:"!==e.protocol)return;return e.toString()}catch{return}}function e5(e,t){return"function"==typeof e?e(t):e}function e8(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}var e6=r(70851);let e7="doubao-apps-widget",e9={body:`${e7}__body`,header:`${e7}__header`,icon:`${e7}__icon`,root:e7,title:`${e7}__title`};class te{container;options;runtimeKernel;root=null;body=null;title=null;icon=null;runtimeContainer=null;renderToken=0;constructor(e,t){if(!e.container)throw Error("Widget requires a container element");this.container=e.container,this.options=e,this.runtimeKernel=t}get element(){var e;return(null==(e=this.runtimeContainer)?void 0:e.element)??null}async render(){this.clear();let e=this.renderToken,t=await ez.resolveWidget(this.options.appId,this.options.widgetId);if(this.renderToken!==e){let e;throw(e=Error("Widget render was cancelled")).name="AbortError",e}return this.renderResource({...this.options,appId:t.appId??this.options.appId,globalProps:{...this.options.globalProps,packageInfo:{appId:t.appId,name:t.appName,iconSrc:t.iconSrc}},appName:t.appName,titleType:t.entry.titleType??0,resourceUrl:t.resourceUrl})}renderResource(e){this.clear(),++this.renderToken;let t=document.createElement("section");t.className=(0,e6.$)(e9.root,this.options.className);let r=document.createElement("div");r.className=e9.body;let n=null;if(2!==e.titleType){(n=document.createElement("header")).className=e9.header,n.hidden=!0;let e=document.createElement("img");e.alt="",e.className=e9.icon,e.height=16,e.width=16;let r=document.createElement("div");r.className=e9.title,n.append(e,r),t.append(n),this.icon=e,this.title=r}return t.append(r),this.container.replaceChildren(t),this.root=t,this.body=r,this.updateHeader(e.appName,e.icon),this.runtimeContainer=this.runtimeKernel.createContainer({apiRegistry:this.options.apiRegistry,container:r,fileSystemNamespace:this.options.fileSystemNamespace,nativeModulesCallHandler:this.options.nativeModulesCallHandler,onError:this.options.onError,onReady:()=>{n&&(n.hidden=!1)}}),this.runtimeContainer.render({containerType:"WIDGET",resourceUrl:e.resourceUrl,initData:e.initData,globalProps:e.globalProps})}clear(){var e,t;this.renderToken+=1,null==(e=this.runtimeContainer)||e.clear(),this.runtimeContainer=null,null==(t=this.root)||t.remove(),this.root=null,this.body=null,this.title=null,this.icon=null,this.container.replaceChildren()}reload(){var e;null==(e=this.runtimeContainer)||e.reload()}destroy(){this.clear()}updateHeader(e,t){this.title&&(this.title.textContent=e??""),this.icon&&(t?(this.icon.src=t,this.icon.hidden=!1):(this.icon.removeAttribute("src"),this.icon.hidden=!0))}}let tt=Object.freeze({mode:"inline",createContainer:e=>new eR(e)});r(84086);let tr="onDestroy",tn="onShow";function ta(e,t){e.style.display=t?"block":"none"}function ti(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 n={};return new URLSearchParams(-1===t?"":e.slice(t+1)).forEach((e,t)=>{n[t]=e}),{pageId:r,viewData:n}}(e.url),n=JSON.stringify(r);return{pageId:t,initData:{viewData:r,viewContext:{}},globalProps:{__LOCATION__:e.url,__RENDER_DATA__:n,__VIEW_CONTEXT__:{}}}}(e);return{...r,entry:t.getPageEntry(r.pageId)}}function ts(e,t){var r;let n=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}${n?`?${n}`:""}`}}function to(e,t){return e&&"object"==typeof e?{packageInfo:t,...e}:{packageInfo:t}}function tl(e){return{appId:e.appId,name:e.name,iconSrc:e.iconSrc,versionName:e.versionName}}function td(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return to(t,tl(e))}function tu(e){if(q(e))return{...e};if("string"!=typeof e)return{};try{let t=JSON.parse(e);return q(t)?t:{}}catch{return{}}}class tc{container;className;apiRegistry;nativeModulesCallHandler;onError;appGlobalProps;appInitData;getRuntimeGlobalProps;runtimeHost;configuredFileSystemNamespace;runtimeKernel;cleanupBridgeController;cleanupEmptyState;emptyState;manifest;manifestUrl;pageCapsule;fileSystemNamespace;appRuntime=null;clearingAppRuntime=!1;stack=[];pendingPages=[];nextPageIndex=0;resourceUrlVersion=0;constructor(e,t=eJ){if(!e.container)throw Error("Runtime requires a container element");if(this.container=e.container,this.runtimeKernel=t,this.manifest=e.manifest,this.manifestUrl=e.manifestUrl,this.pageCapsule=e.pageCapsule,this.apiRegistry=e.apiRegistry,this.className=e.className,this.nativeModulesCallHandler=e.nativeModulesCallHandler,this.onError=e.onError,this.appGlobalProps=e.appGlobalProps,this.appInitData=e.appInitData,this.getRuntimeGlobalProps=e.getRuntimeGlobalProps,this.runtimeHost=e.runtimeHost,this.configuredFileSystemNamespace=e.fileSystemNamespace,this.fileSystemNamespace=this.resolveFileSystemNamespace(),this.emptyState=function(e){if(!(null==e?void 0:e.mountRuntimeEmptyState))return null;let t=document.createElement("div");return t.className="doubao-runtime-empty",t}(this.runtimeHost),this.emptyState){var r,a;this.container.append(this.emptyState);const e=null==(a=this.runtimeHost)||null==(r=a.mountRuntimeEmptyState)?void 0:r.call(a,this.emptyState);this.cleanupEmptyState="function"==typeof e?e:()=>{}}else this.cleanupEmptyState=()=>{};this.updateEmptyState(),e.registerPageController??!0?this.cleanupBridgeController=function(e){return n=e,()=>{n===e&&(n=void 0)}}({getCurrentPages:()=>this.getCurrentPages(),getPackageInfo:()=>this.getPackageInfo(),navigateTo:e=>this.navigateToBridgePage(e),redirectTo:e=>this.redirectToBridgePage(e),reLaunch:e=>this.reLaunchBridgePage(e),navigateBack:e=>this.navigateBackBridgePage(e),exitApp:()=>this.exitBridgeApp(),close:e=>this.closeBridgePage(e)}):this.cleanupBridgeController=()=>{}}get pages(){return this.stack.map(e=>this.toStackEntry(e))}get currentPage(){let e=this.getCurrentStackItem();return e?this.toStackEntry(e):null}setManifest(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.manifestUrl;this.clear(),this.manifest=e,this.manifestUrl=t,this.fileSystemNamespace=this.resolveFileSystemNamespace()}pushPage(){var e;let t,r,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},a=this.resolvePageEntry(n),i=e$(this.manifestUrl,a);if(!i)throw Error(`No Web entry configured for page entry: ${a.id}`);let s={...n,globalProps:{...q(n.globalProps)?n.globalProps:{},...null==(e=this.getRuntimeGlobalProps)?void 0:e.call(this)}},o=eW(i,this.resourceUrlVersion?String(this.resourceUrlVersion):void 0),l=n.pageCapsule??this.pageCapsule,d=`page-${++this.nextPageIndex}`,u=(t=q(s.globalProps)?tu(s.globalProps.__VIEW_CONTEXT__):{},{...q(s.initData)?tu(s.initData.viewContext):{},...t,viewId:d,pageName:a.id,pageUrl:a.path}),c=((r=document.createElement("div")).className="doubao-runtime-page",r.style.display="block",r.style.width="100%",r.style.height="100%",r),p=null,m=new eZ({apiRegistry:this.apiRegistry,className:this.className,container:c,fileSystemNamespace:this.fileSystemNamespace,nativeModulesCallHandler:this.nativeModulesCallHandler,onError:this.onError,onReady:()=>{p&&this.stack.includes(p)&&(p.isReady=!0,this.flushPageLifecycleEvents(p))}},this.runtimeKernel);void 0!==n.pageCapsule&&(this.pageCapsule=n.pageCapsule),this.ensureAppRuntime(),this.container.append(c),this.pendingPages.push(ts(a.path,n));try{let e,t,r=m.render({resourceUrl:o,groupId:this.manifest.appId,initData:q(s.initData)?{...s.initData,viewContext:u}:{viewContext:u},globalProps:(e=null==l?void 0:l.statusBarHeight,t="number"==typeof e&&Number.isFinite(e)?{statusBarHeight:e}:{},{...q(s.globalProps)?s.globalProps:{},...t,__VIEW_CONTEXT__:u}),pageCapsule:l}),i=this.getCurrentStackItem();return i&&(this.sendPageLifecycleEvent(i,"onHide"),ta(i.frame,!1)),p={id:d,pageId:a.id,route:a.path,resourceUrl:o,entry:a,element:r,frame:c,isReady:!1,options:{...n,entry:a,pageCapsule:l},pendingLifecycleEvents:[],page:m},c.addEventListener("doubao:page-capsule-close",e=>{e.stopPropagation(),this.exitBridgeApp()}),this.stack.push(p),this.updateEmptyState(),this.sendPageLifecycleEvent(p,tn),this.sendAppEvent("onPageOpened",{viewId:p.id}),this.toStackEntry(p)}catch(e){throw m.clear(),c.remove(),this.updateEmptyState(),e}finally{this.pendingPages.pop()}}replacePage(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.stack.pop();return t&&this.removeStackItem(t,!1),this.pushPage(e)}popPage(){let e=this.stack.pop();return e?this.removeStackItem(e,!0):null}clear(){this.clearPages(),this.clearAppRuntime(),this.resourceUrlVersion+=1}restart(){let e=this.stack.map(e=>{let{options:t}=e;return t});for(let t of(this.clear(),e))this.pushPage(t)}reload(){var e;null==(e=this.getCurrentStackItem())||e.page.reload()}destroy(){var e;this.clear(),this.cleanupEmptyState(),null==(e=this.emptyState)||e.remove(),this.cleanupBridgeController()}clearPages(){for(;this.stack.length>0;){let e=this.stack.pop();e&&this.removeStackItem(e,!1)}}removeStackItem(e,t){let r=this.toStackEntry(e);this.sendPageLifecycleEvent(e,tr),e.page.clear(),e.frame.remove();let n=this.getCurrentStackItem();return t&&n&&(ta(n.frame,!0),this.sendPageLifecycleEvent(n,tn)),this.updateEmptyState(),r}ensureAppRuntime(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this.appRuntime||!this.manifest.appRuntimeEntry)return;let r=e$(this.manifestUrl,this.manifest.appRuntimeEntry);if(!r)throw Error("No Web entry configured for app runtime");let n=eW(r,this.resourceUrlVersion?String(this.resourceUrlVersion):void 0),a=((e=document.createElement("div")).className="doubao-runtime-app",e.hidden=!0,e.style.display="none",e),i=this.runtimeKernel.createContainer({apiRegistry:this.apiRegistry,className:this.className,container:a,fileSystemNamespace:this.fileSystemNamespace,nativeModulesCallHandler:this.nativeModulesCallHandler,onError:this.onError,appletSessionMessageHandler:t.appletSessionMessageHandler,onReady:()=>{var e,r;this.clearingAppRuntime||(null==(e=this.appRuntime)?void 0:e.container)!==i||(this.appRuntime.isReady=!0,null==(r=t.onReady)||r.call(t),this.flushAppEvents())}});this.container.append(a),this.appRuntime={container:i,frame:a,isReady:!1,pendingEvents:[]};try{var s;i.render({resourceUrl:n,groupId:null===t.groupId?void 0:t.groupId??this.manifest.appId,containerType:"APP",initData:this.appInitData??{},globalProps:{...td(this.manifest,this.appGlobalProps),...null==(s=this.getRuntimeGlobalProps)?void 0:s.call(this)}}),this.sendAppEvent("onForeground")}catch(e){throw this.appRuntime=null,i.clear(),a.remove(),e}}clearAppRuntime(){if(this.clearingAppRuntime)return;this.clearingAppRuntime=!0;let e=this.appRuntime;(null==e?void 0:e.isReady)&&(e.container.sendEvent("onBackground"),e.container.sendEvent(tr)),null==e||e.container.clear(),null==e||e.frame.remove(),this.appRuntime=null,this.clearingAppRuntime=!1}sendAppEvent(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=this.appRuntime;if(r&&!this.clearingAppRuntime){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,n=(r={viewId:e.id,pageName:e.pageId,pageUrl:e.route},{viewId:e.id,eventName:JSON.stringify(r)});e.isReady?e.page.sendEvent(t,n):e.pendingLifecycleEvents.push({name:t,params:n})}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){return ti(e,this.manifest)}getCurrentStackItem(){return this.stack[this.stack.length-1]??null}updateEmptyState(){this.emptyState&&(this.emptyState.hidden=this.stack.length>0)}getCurrentPages(){return[...this.stack.map(e=>ts(e.route,e.options)),...this.pendingPages]}getPackageInfo(){return tl(this.manifest)}resolveFileSystemNamespace(){return this.configuredFileSystemNamespace?this.configuredFileSystemNamespace:et(to(this.appGlobalProps??{},this.getPackageInfo()))}navigateToBridgePage(e){this.pushPage(this.resolveRoutePageOptions(e))}redirectToBridgePage(e){let t=this.resolveRoutePageOptions(e);this.replacePage(t)}reLaunchBridgePage(e){let t=this.resolveRoutePageOptions(e);this.clearPages(),this.pushPage(t)}navigateBackBridgePage(e){let t=Math.min(Math.max(1,Math.floor(e.delta??1)),Math.max(0,this.stack.length-1));for(let e=0;e<t;e+=1)this.popPage()}exitBridgeApp(){this.clear()}closeBridgePage(e){let t=[];if(e.containerID&&t.push(e.containerID),0===t.length)return void this.popPage();for(let e of t)this.removePage(e)}removePage(e){let t=this.stack.findIndex(t=>t.id===e);if(-1===t)return null;let r=t===this.stack.length-1,[n]=this.stack.splice(t,1);return this.removeStackItem(n,r)}toStackEntry(e){return{id:e.id,pageId:e.pageId,route:e.route,resourceUrl:e.resourceUrl,entry:e.entry,element:e.element}}}function tp(){let e=Error("Widget host call was cancelled");return e.name="AbortError",e}function tm(e,t){if(t.aborted)throw tp();return new Promise((r,n)=>{let a=!1,i=e=>{a||(a=!0,t.removeEventListener("abort",s),e())},s=()=>i(()=>n(tp()));t.addEventListener("abort",s,{once:!0}),Promise.resolve().then(e).then(e=>i(()=>r(e)),e=>i(()=>n(e)))})}function th(e){let{appId:t,versionTag:r,widgetId:n}=e;return`${t}\u0000${r??""}\u0000${n}`}function tg(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];let a=new URL(e);a.search="",a.hash="";let i=r.map(e=>encodeURIComponent(e)).join("/");return a.pathname=`${a.pathname.replace(/\/+$/,"")}/${i}`,a.toString()}async function tf(e,t,r){let n=globalThis.fetch;if(!n)throw Error("Web CDN resource loading requires fetch");let a=new URL(`https://developer.doubao.com/app_developer/resource_api/apps/${encodeURIComponent(e)}/web_cdn_url`);r&&a.searchParams.set("version_tag",r);let i=await n(a.toString(),{method:"GET",signal:t});if(!i.ok)throw Error(`Get Web CDN URL failed with HTTP ${i.status}`);let s=await i.json();if(0!==s.code)throw Error(`Get Web CDN URL failed: ${s.code} ${s.message??s.msg??s.log_id??""}`.trim());var o,l=null==(o=s.data)?void 0:o.web_cdn_url;if(!l)throw Error("Web CDN URL response did not include data.web_cdn_url");let d=new URL(l);if("https:"!==d.protocol)throw Error(`Web CDN URL must use HTTPS: ${l}`);return d.pathname=d.pathname.replace(/\/+$/,""),d.search="",d.hash="",d.toString()}async function tv(e,t){var r,n,a,i,s,o;let l=globalThis.fetch;if(!l)throw Error("Web app metadata loading requires fetch");let d=await l("https://mini-program.doubao.com/api/v1/app_meta/batch_get",{body:JSON.stringify({app_keys:[e]}),credentials:"include",headers:{"content-type":"application/json; encoding=utf-8"},method:"POST",signal:t});if(!d.ok)throw Error(`BatchGetAppMeta failed with HTTP ${d.status}`);let u=await d.json();if(0!==u.code)throw Error(`BatchGetAppMeta failed: ${u.code} ${u.message}`.trim());let c=null==(n=u.data)||null==(r=n.failed_keys)?void 0:r.find(t=>t.app_key===e);if(c)throw Error(`BatchGetAppMeta failed for ${e}: ${c.error_code??""} ${c.error_message??""}`.trim());let p=(null==(i=u.data)||null==(a=i.items)?void 0:a.find(t=>t.app_key===e))??(null==(o=u.data)||null==(s=o.items)?void 0:s[0]);if(!p)throw Error(`BatchGetAppMeta returned empty app meta for ${e}`);return{appName:p.app_name??e,icon:p.icon_url}}async function ty(e,t,r,n){try{let a=await globalThis.fetch(tg(e,"base","manifest.json"),{method:"GET",signal:n});if(!a.ok)return;let i=await a.json();return function(e,t,r,n){var a,i,s;if(e.appId!==r||!e.applet)return;let o=e.applet.name,l=eD(e.applet.icons),d=null==(a=e.widgets)?void 0:a.find(e=>e.widgetId===n),u=null==d||null==(i=d.web)?void 0:i.entry;if(!o)return;if(!u)return{appName:o,icon:l,resourceUrl:""};let c=null==(s=e.applet.web)?void 0:s.appRuntimeEntry;if(!c)return;let p=null==d?void 0:d.titleType;if(void 0===p||[0,1,2].includes(p))return{appName:o,appRuntimeEntry:tg(t,...c.split("/")),icon:l,resourceUrl:tg(t,...u.split("/")),titleType:p}}(i,e,t,r)}catch(e){if(n.aborted||e instanceof Error&&"AbortError"===e.name)throw e;return}}async function t_(e,t){try{let r=await globalThis.fetch(e,{method:"HEAD",signal:t});return 404===r.status}catch(e){if(t.aborted||e instanceof Error&&"AbortError"===e.name)throw e;return!1}}async function tb(e){let{appName:t,icon:r,resourceRoot:n,titleType:a,widgetId:i}=e;return{appRuntimeEntry:tg(n,"base","app.web.bundle"),appName:t,icon:r,titleType:a,resourceUrl:tg(n,i,"index.web.bundle")}}let tw=async e=>{let t,{appId:r,signal:n,versionTag:a,widgetId:i}=e;try{t=await tf(r,n,a)}catch(e){if(n.aborted||e instanceof Error&&"AbortError"===e.name)throw e;return{...await tv(r,n),resourceUrl:""}}let s=await ty(t,r,i,n);if(s)return s;let o=await tb({resourceRoot:t,widgetId:i}),[l,d]=await Promise.all([tv(r,n),t_(o.resourceUrl,n)]);return d?{...l,resourceUrl:""}:{...o,...l}},tS=async e=>{let t,{appId:r,signal:n,versionTag:a,widgetId:i}=e;try{t=await tf(r,n,a)}catch(e){if(n.aborted||e instanceof Error&&"AbortError"===e.name)throw e;return{resourceUrl:""}}return await ty(t,r,i,n)??{resourceUrl:""}};class tx{manifestResourceLoads=new Map;resourceLoads=new Map;clear(){this.manifestResourceLoads.clear(),this.resourceLoads.clear()}load(e){let t=th(e),r=this.resourceLoads.get(t);if(r)return tm(()=>r,e.signal);let n=tw({...e,signal:new AbortController().signal}).then(e=>(e.resourceUrl||this.resourceLoads.get(t)!==n||this.resourceLoads.delete(t),e)).catch(e=>{throw this.resourceLoads.get(t)===n&&this.resourceLoads.delete(t),e});return this.resourceLoads.set(t,n),tm(()=>n,e.signal)}preload(e){let t=th(e),r=this.manifestResourceLoads.get(t);if(r)return tm(()=>r,e.signal);let n=tS({...e,signal:new AbortController().signal}).then(e=>(e.resourceUrl?this.resourceLoads.has(t)||this.resourceLoads.set(t,n):this.manifestResourceLoads.get(t)===n&&this.manifestResourceLoads.delete(t),e)).catch(e=>{throw this.manifestResourceLoads.get(t)===n&&this.manifestResourceLoads.delete(t),e});return this.manifestResourceLoads.set(t,n),tm(()=>n,e.signal)}}new tx;class tI extends eR{constructor(e){super(e)}}class tE extends te{constructor(e){super(e,tt)}}class tC extends tc{constructor(e){super(e,tt)}}var tk=r(75541);function tN(e){return"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=9999}function tT(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0}function tR(e,t){let r=t.trim();r&&!e.includes(r)&&e.push(r)}function tM(e){let t=[];return!function e(t,r,n){if(!("object"!=typeof t||null===t||n.has(t))){if(n.add(t),Array.isArray(t))return void t.forEach(t=>e(t,r,n));if(e8(t))for(let[a,i]of Object.entries(t))"response_headers"===a.toLowerCase()&&function(e,t){if(e8(e)){for(let[r,n]of Object.entries(e))if("x-tt-logid"===r.toLowerCase()&&"string"==typeof n)return void tR(t,n)}}(i,r),"log_ids"===a.toLowerCase()&&function(e,t){if("string"==typeof e)return tR(t,e);if(Array.isArray(e))for(let r of e)"string"==typeof r&&tR(t,r)}(i,r),e(i,r,n)}}(e,t,new WeakSet),t}function tA(e){return e8(e)?e8(e.viewData)?e:{...e,viewData:e}:{viewData:{}}}function tP(e){if("string"==typeof e&&e.trim())try{return JSON.parse(e)}catch{return}}function tj(e){if(e8(e))return e;let t=tP(e);return e8(t)?t:void 0}function tL(e){if("string"==typeof e)return e;try{return JSON.stringify(e??{})}catch{return"{}"}}function tD(e){return e instanceof Error?e.message:String(e)}function tO(e){let t=null==e?void 0:e.toLowerCase();switch(t){case"agent":case"api":case"mcp":case"card":case"resource":case"runtime":case"debug":return t;case"tool":return"agent";default:return"runtime"}}function tU(e){let[t,...r]=e.trim().split(":"),n=t.replace(/_/g," ").trim().split(/\s+/).filter(Boolean).map(tq).join(" ");return 0===r.length?n||e:`${n}: ${r.join(":").trim()}`}function tq(e){let t=function(e){switch(e.toLowerCase()){case"api":return"API";case"mcp":return"MCP";case"sse":return"SSE";case"ack":return"ACK";case"http":return"HTTP";case"json":return"JSON";case"id":return"ID";default:return""}}(e);if(t)return t;if(/^[A-Z0-9]+$/.test(e))return e;let r=e.toLowerCase();return`${r.slice(0,1).toUpperCase()}${r.slice(1)}`}r(78872),r(60972),r(45249),r(12021),r(20789),r(62839),r(66876);let t$=new Set(["local_mcp_missing","local_mcp_tools_load_failed","simulator_chat_fetch_failed","simulator_query_failed","stream_error","tool_executor_missing","tool_result_submit_failed"]),tB={query:0,"tool-call":10,"tool-result":20,"agent-processing":25,card:30,"agent-response":40,error:50};function tF(e,t){return{category:"api",detail:{query:t},key:"query",phase:"request",payload:{event:"query",query:t},source:e,sources:[e],title:"Query"}}function tW(e,t){let r=e.steps.get(t.key);if(!r)return void e.steps.set(t.key,t);let n=function(e,t){if("error"===t.phase)return!0;if(e.key.startsWith("card:")){let r=tG(e.source.payload);return tH(tG(t.source.payload))>tH(r)}return!1}(r,t),a=n?t:r,i=n?r:t;e.steps.set(t.key,{...r,category:"error"===t.phase?t.category:a.category,detail:tY(a.detail,i.detail),phase:"error"===t.phase?t.phase:a.phase,payload:tY(a.payload,i.payload),source:a.source,sources:[...new Map([...r.sources,...t.sources].map(e=>[e.id,e])).values()],title:"error"===t.phase||n?t.title:r.title})}function tH(e){return"simulator_card_render_failed"===e||"simulator_card_runtime_error"===e||"simulator_card_render_skipped"===e?3:"simulator_card_rendered"===e?2:+("card_delta"===e)}function tz(e){let t=t1([...e.steps.values()]);return t.map((r,n)=>{var a,i,s,o,l,d,u;let c,p,m,h,g,f,v,y,_,b,w;return a=r,i=e,s=t,o=n,y=tZ(a.sources.flatMap(tM)),_=tZ(a.sources.map(e=>e.payload.request_id||"")),w=void 0===(b=(l=a,d=s,u=o,c=l.payload.elapsed_ms??l.detail.elapsed_ms,m=(null==(p=l.key.startsWith("agent-processing:")?d.slice(u+1).find(e=>/^(tool-call|card|error):/.test(e.key)||"agent-response"===e.key):d[u+1])?void 0:p.source.timestamp)??l.source.timestamp,h=Number.isFinite(l.source.timestamp)&&Number.isFinite(m)?Math.max(0,m-l.source.timestamp):void 0,f=(g=l.key.startsWith("tool-call:")?l.key.replace("tool-call:","tool-result:"):l.key.startsWith("tool-result:")?l.key.replace("tool-result:","tool-call:"):void 0)?d.find(e=>e.key===g):void 0,void 0!==(v=l.key.startsWith("tool-call:")&&f?f.payload.elapsed_ms??f.detail.elapsed_ms:void 0)?v:l.key.startsWith("tool-result:")&&f?void 0:void 0!==c?void 0===h?c:Math.max(c,h):h))?a.detail:{...a.detail,elapsed_ms:b},{id:a.source.id,order:a.source.order,timestamp:a.source.timestamp,display:{category:a.category,detail:w,phase:a.phase,title:a.title},payload:{request_id:1===_.length?_[0]:void 0,request_ids:_.length>1?_:void 0,...a.payload,trace_id:i.id,run_status:i.status,elapsed_ms:b,log_ids:y.length>0?y:void 0}}})}function tV(e,t){let r=t0(t.payload),n=r?e.runs.find(e=>e.id===r):void 0;if(!n){if(!r)return;n={id:r,order:t.order??e.runs.length,startedAt:t.timestamp,steps:new Map},e.runs.push(n)}return n.startedAt=Math.min(n.startedAt,t.timestamp),n.order=Math.min(n.order,t.order??n.order),n}function tG(e){return e.event||""}function tJ(e,t){return tK(e)||[t0(e)||t.id,e.tool_name||"unknown-tool"].filter(Boolean).join(":")}function tK(e){return e.tool_call_id||""}function tX(e){let t=e.tool_name||tK(e);return t?`: ${t}`:""}function tQ(e){let t={};for(let[r,n]of Object.entries(e))null!=n&&""!==n&&(t[r]=n);return t}function tY(e,t){return Object.fromEntries([...Object.entries(t),...Object.entries(e).filter(e=>{let[,t]=e;return void 0!==t})])}function tZ(e){return[...new Set(e.filter(e=>!!e))]}function t0(e){var t;return e.trace_id||(null==(t=e.trace)?void 0:t.trace_id)||""}function t1(e){return[...e].sort((e,t)=>e.source.timestamp-t.source.timestamp||(e.source.order??0)-(t.source.order??0)||tB[e.key.split(":")[0]]-tB[t.key.split(":")[0]]||e.key.localeCompare(t.key))}function t2(e,t){return e.startedAt-t.startedAt||e.order-t.order||e.id.localeCompare(t.id)}function t3(e,t){return e.timestamp-t.timestamp||(e.order??0)-(t.order??0)||e.id.localeCompare(t.id)}function t4(e){try{return t5(e,2)}catch{var t=e;if("string"==typeof t){let e=t.trim();if(!e)return"";try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}if(void 0===t)return"";try{return JSON.stringify(t,null,2)}catch{return String(t)}}}function t5(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=new WeakSet;return JSON.stringify(e,(e,t)=>{if(t instanceof Error)return{name:t.name,message:t.message,stack:t.stack};if("function"==typeof t)return`[Function ${t.name||"anonymous"}]`;if("object"==typeof t&&null!==t){if(r.has(t))return"[Circular]";r.add(t)}return t},t)}function t8(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=Date.now();return{stored_at:new Date(r).toISOString(),stored_at_ms:r,snapshot:t6(e,t),debug_snapshot:t6(e,{...t,debug:!0,includeRuntimeRoot:!1})}}function t6(e){var t,r;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=n.debug&&!n.traceId?(t=e,r=!1!==n.includeRuntimeRoot,e8(t)&&!r&&e8(t.runtime_snapshot)?{...t,runtime_snapshot:t9(t.runtime_snapshot,!1)}:t):function(e,t){var r;if(!e8(e))return e;let n=e8(e.simulator)?e.simulator:{},a=Array.isArray(n.messages)?n.messages.filter(e=>re(e,t.traceId)):void 0,i=Array.isArray(n.tool_calls)?n.tool_calls.filter(e=>re(e,t.traceId)):void 0,s=t9(e.runtime_snapshot,!1!==t.includeRuntimeRoot);return{...rs(e,["exported_at","client_id","command_id","context","render_targets"]),runtime_snapshot:e8(s)?s:void 0,simulator:e8(e.simulator)?{...rs(n,["stream_status","active_request_id","active_reply_message_id"]),error:n.error?ri(n.error):void 0,selected_card:n.selected_card?ra(n.selected_card):void 0,answer_finish:n.answer_finish?e8(r=n.answer_finish)?rs(r,["messageId","status","finishReason","usage","createdAtMs"]):r:void 0,messages:null==a?void 0:a.map(rt),tool_calls:null==i?void 0:i.map(rn),trace_events:Array.isArray(n.trace_events)?t7(n.trace_events,{debug:t.debug,messages:a,traceId:t.traceId}):void 0}:void 0,widget_runtime_trace_events:Array.isArray(e.widget_runtime_trace_events)?t7(e.widget_runtime_trace_events,{debug:t.debug,traceId:t.traceId}):void 0,page_runtime_trace_events:Array.isArray(e.page_runtime_trace_events)?t7(e.page_runtime_trace_events,{debug:t.debug,traceId:t.traceId}):void 0,runtime_console:e8(e.runtime_console)?e.runtime_console:void 0}}(e,n),i=tM(e);return i.length>0&&e8(a)?{...a,log_ids:i}:a}function t7(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(t.debug&&!t.traceId)return e;if(t.debug){var r,n;return r=e,(n=t.traceId)?r.filter(e=>t0(e.payload)===n):r}let a=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r={runs:[]};for(let t of[...e].sort(t3))!function(e,t){var r,n;let a=t.payload,i=tG(a);if("tool_result_report_started"===i){let r=tV(e,t);if(!r)return;tW(r,function(e){let t=e.payload,r=tQ({tool_call_id:tK(t),tool_name:t.tool_name});return{category:"agent",detail:r,key:`agent-processing:${tJ(t,e)}`,phase:"request",payload:{event:"agent_processing",...r},source:e,sources:[e],title:`Agent Processing${tX(t)}`}}(t));return}if(!((r=i).startsWith("tool_result_report_")||"tool_result_ack"===r)){if("simulator_chat_fetch_started"===i){let r=function(e){var t,r,n;return e.query||(null==(t=e.request)?void 0:t.query)||(null==(n=e.request)||null==(r=n.message)?void 0:r.content)||""}(a);if(!r)return;let n=tV(e,t);if(!n)return;tW(n,tF(t,r));return}if("tool_call"===i||"local_mcp_call_started"===i){let r=tV(e,t);if(!r)return;tW(r,function(e){let t=e.payload,r=tQ({tool_call_id:tK(t),tool_name:t.tool_name,arguments:t.arguments,arguments_json:t.arguments_json});return{category:"agent",detail:r,key:`tool-call:${tJ(t,e)}`,phase:"request",payload:{event:"tool_call",...r},source:e,sources:[e],title:`Tool Call${tX(t)}`}}(t));return}if("local_mcp_call_succeeded"===i||"local_mcp_call_failed"===i){let r=tV(e,t);if(!r)return;tW(r,function(e){let t=e.payload,r="local_mcp_call_failed"===tG(t),n=t.result??t.structured_result??tP(t.structured_result_json)??t.structured_result_json,a=t.raw_mcp_result??tP(t.raw_mcp_result_json)??t.raw_mcp_result_json,i=t.raw_result_text===t.raw_mcp_result_json?void 0:t.raw_result_text,s=tQ({tool_call_id:tK(t),tool_name:t.tool_name,status:t.status,result:n,raw_result_text:i,raw_mcp_result:a,elapsed_ms:t.elapsed_ms,error:t.error});return{category:"mcp",detail:s,key:`tool-result:${tJ(t,e)}`,phase:r?"error":"response",payload:{event:r?"tool_result_failed":"tool_result",...s},source:e,sources:[e],title:`${r?"Tool Result Failed":"Tool Result"}${tX(t)}`}}(t));return}if("card_delta"===(n=i)||"simulator_card_rendered"===n||"simulator_card_render_failed"===n||"simulator_card_runtime_error"===n||"simulator_card_render_skipped"===n){let r=tV(e,t);if(!r)return;tW(r,function(e){var t,r;let n=e.payload,a=tG(n),i="error"in n||a.endsWith("_failed")||a.endsWith("_error"),s=tQ({card_id:n.card_id,widget_id:n.widget_id,card_type:n.card_type,entity_id:n.entity_id,source_tool_call_id:n.source_tool_call_id,elapsed_ms:n.elapsed_ms,error:n.error,summary:n.summary});return{category:"card",detail:s,key:`card:${t=n,r=e,t.card_id||t.source_tool_call_id||[t0(t)||r.id,t.widget_id||r.id].filter(Boolean).join(":")}`,phase:i?"error":"response",payload:{event:i?"card_render_failed":"card_delta"===a?"card_received":"card_rendered",...s},source:e,sources:[e],title:i?"Card Render Failed":"card_delta"===a?"Card Received":"Card Rendered"}}(t));return}if(function(e,t){let r=e.phase,n=e.status;return t$.has(t)||"error"===r||t.endsWith("_failed")||t.endsWith("_missing")||t.endsWith("_aborted")||t.endsWith("_error")||"failed"===n||"error"===n||"number"==typeof n&&n>=400}(a,i)){let r=tV(e,t);if(!r)return;tW(r,function(e){var t,r;let n=e.payload,a=n.detail??{},i=n.event_count??a.event_count,s=tQ({elapsed_ms:n.elapsed_ms??a.elapsed_ms,endpoint:n.endpoint??a.endpoint,error:n.error??a.error,event_count:i,message:n.message??a.message,reason:n.reason??a.reason,status:n.status??a.status,summary:n.summary??a.summary??("simulator_chat_sse_read_failed"===tG(n)&&0===i?"对话流未收到任何事件,未触发 MCP tool 与 tool/report;请结合 log_id 排查生成或下发 tool_call 前的服务端/链路异常。":void 0),response:n.response??a.response,response_text:n.response_text??a.response_text});return{category:(null==(t=e.display)?void 0:t.category)||"runtime",detail:s,key:`error:${e.id}`,phase:"error",payload:{event:tG(n)||"trace_error",...s},source:e,sources:[e],title:(null==(r=e.display)?void 0:r.title)||n.title||"Trace Error"}}(t))}}}(r,t);for(let e of t)!function(e,t){var r,n,a,i,s;let o=(n=t,{id:`trace-message-${n.messageId}`,timestamp:n.createdAtMs,payload:tQ({message_id:n.messageId,request_id:n.requestId,trace_id:n.traceId})}),l=tV(e,o);if(!l)return;let d=(null==(r=t.blocks)?void 0:r.some(e=>"image"===e.type))??!1,u=t.text.trim()||(d?"[图片]":"");"assistant"===t.role&&t.status&&(a=l,i=t.status,s=t.createdAtMs,void 0!==a.statusUpdatedAt&&s<a.statusUpdatedAt||(a.status=i,a.statusUpdatedAt=s)),"user"===t.role&&u&&!l.steps.has("query")&&tW(l,tF(o,u)),"assistant"===t.role&&t.text.trim()&&tW(l,function(e,t){let r=t1([...e.steps.values()]).at(-1),n=Math.max(t.createdAtMs,((null==r?void 0:r.source.timestamp)??t.createdAtMs)+.1),a={id:`trace-agent-response-${t.messageId}`,order:(null==r?void 0:r.source.order)===void 0?void 0:r.source.order+.1,timestamp:n,payload:tQ({message_id:t.messageId,request_id:t.requestId,trace_id:t.traceId})};return{category:"agent",detail:{text:t.text},key:"agent-response",phase:"finish",payload:{event:"agent_response",message_id:t.messageId,text:t.text},source:a,sources:[a],title:"Agent Response"}}(l,t))}(r,e);return r}(e,t.messages);return(t.traceId?a.runs.filter(e=>e.id===t.traceId):a.runs).sort(t2).flatMap(tz)}(e,t)}function t9(e,t){if(!e8(e)||t)return e;let{root:r,...n}=e;return n}function re(e,t){if(!t)return!0;if(!e8(e))return!1;let r=e8(e.trace)?e.trace:{};return e.traceId===t||r.trace_id===t}function rt(e){return e8(e)?{...rs(e,["messageId","localMessageId","requestId","traceId","role","contentType","status","createdAtMs"]),text:"string"==typeof e.text?ro(e.text):void 0,blocks:Array.isArray(e.blocks)?e.blocks.map(rr):void 0,toolCalls:Array.isArray(e.toolCalls)?e.toolCalls:void 0,toolResults:Array.isArray(e.toolResults)?e.toolResults:void 0}:e}function rr(e){return e8(e)?"card"===e.type?{...rs(e,["blockId","type"]),card:ra(e.card)}:"image"===e.type&&e8(e.image)?{...rs(e,["blockId","type"]),image:rs(e.image,["resource_uri","mime_type","size_bytes","width","height","sha256","name"])}:{...rs(e,["blockId","type"]),text:"string"==typeof e.text?ro(e.text):void 0}:e}function rn(e){return e8(e)?{...rs(e,["requestId","runId","replyMessageId","toolCallId","toolName","serverId","appKey","status","createdAtMs","updatedAtMs","requiresUserApproval","timeoutMs","deadlineMs","progress","message","resultSummary","structuredResultSummary","isMiniApp"]),arguments:e.arguments,argumentsJson:void 0===e.arguments&&e.argumentsJson?e.argumentsJson:void 0,error:e.error?ri(e.error):void 0}:e}function ra(e){return e8(e)?rs(e,["reply_message_id","block_id","card_id","widget_id","card_type","app_id","entity_id","title","fallback_text"]):e}function ri(e){return e8(e)?rs(e,["code","message","user_message","retryable","stage","details","name","stack"]):e}function rs(e,t){let r={};for(let n of t)void 0!==e[n]&&(r[n]=e[n]);return r}function ro(e){return e.length>1e3?`${e.slice(0,1e3)}...`:e}let rl=[1e3,2e3,4e3,8e3,16e3];class rd{clientId=crypto.randomUUID();socket;status="disconnected";listeners=new Set;retryTimer;retryIndex=0;sandboxSnapshot;snapshot;sentRuntime;snapshotErrorReported=!1;subscribe(e){return this.listeners.add(e),e({type:"status",status:this.status}),void 0!==this.sandboxSnapshot&&e({type:"sandbox",data:this.sandboxSnapshot}),()=>{this.listeners.delete(e)}}start(){this.stop(),this.retryIndex=0,this.connect()}stop(){clearTimeout(this.retryTimer),this.retryTimer=void 0;let e=this.socket;this.socket=void 0,null==e||e.close(),this.sandboxSnapshot=void 0,this.setStatus("disconnected")}emit(e){for(let t of this.listeners)t(e)}setStatus(e){this.status!==e&&(this.status=e,this.emit({type:"status",status:e}))}connect(){let e;this.setStatus(this.retryIndex?"reconnecting":"connecting");let t=new URL("/__wsd_connection",window.location.href);t.protocol="https:"===t.protocol?"wss:":"ws:",t.searchParams.set("clientId",this.clientId);let r=new WebSocket(t);this.socket=r,r.onopen=()=>{this.socket===r&&(e=Date.now(),this.sentRuntime=void 0,this.sendSnapshot(),this.setStatus("connected"))},r.onmessage=e=>{let t;if(this.socket===r){try{t=JSON.parse(e.data)}catch{r.close(4e3,"Invalid debugger message");return}if(e8(t))if("control"===t.type){let e=function(e){if(!e8(e)||"string"!=typeof e.commandId)return null;if("render_page"===e.type&&"string"==typeof e.url)return{commandId:e.commandId,type:e.type,url:e.url};if("render_widget"===e.type&&"string"==typeof e.widgetId&&e8(e.structuredContent))return{commandId:e.commandId,type:e.type,widgetId:e.widgetId,structuredContent:e.structuredContent};if("set_viewport"===e.type&&tN(e.width)&&tN(e.height))return{commandId:e.commandId,type:e.type,width:e.width,height:e.height};if("submit_chat_query"===e.type&&"string"==typeof e.query&&e.query.trim())return{commandId:e.commandId,type:e.type,query:e.query.trim()};if("cancel_chat_query"===e.type)return{commandId:e.commandId,type:e.type};if("execute_sandbox_tool_call"===e.type){var t;let r="object"==typeof(t=e.toolCall)&&(null==t?void 0:t.tool_call)?t:void 0;return r?{commandId:e.commandId,toolCall:r,type:e.type}:null}if("get_computed_style"===e.type&&"string"==typeof e.uid)return void 0===e.properties||Array.isArray(e.properties)&&e.properties.every(e=>"string"==typeof e)?{commandId:e.commandId,type:e.type,uid:e.uid,properties:e.properties}:null;if("take_snapshot"===e.type&&("current"===e.target||"page"===e.target||"widget"===e.target))return{commandId:e.commandId,type:e.type,target:e.target};if("get_element_rect"===e.type&&"string"==typeof e.uid)return{commandId:e.commandId,type:e.type,uid:e.uid};if("take_screenshot"===e.type){let t=e.format??"png",r=e.quality;return void 0!==e.uid&&"string"!=typeof e.uid||"png"!==t&&"jpeg"!==t&&"webp"!==t||void 0!==r&&("number"!=typeof r||!Number.isFinite(r)||r<0||r>100)?null:{commandId:e.commandId,type:e.type,format:t,uid:"string"==typeof e.uid?e.uid:void 0,quality:"number"==typeof r?r:void 0}}return"scroll_to"===e.type?(void 0===e.uid||"string"==typeof e.uid&&e.uid.trim())&&(void 0===e.x||tT(e.x))&&(void 0===e.y||tT(e.y))?{commandId:e.commandId,type:e.type,uid:"string"==typeof e.uid?e.uid:void 0,x:"number"==typeof e.x?e.x:void 0,y:"number"==typeof e.y?e.y:void 0}:null:null}(t.data);e&&this.emit({type:"control",data:e})}else"sandbox"===t.type&&(this.sandboxSnapshot=t.data,this.emit({type:"sandbox",data:t.data}))}},r.onclose=t=>{if(this.socket!==r)return;this.socket=void 0,this.sandboxSnapshot=void 0,void 0!==e&&Date.now()-e>=3e4&&(this.retryIndex=0);let n=rl[this.retryIndex++];void 0===n||1008===t.code||1009===t.code?this.setStatus("disconnected"):(this.setStatus("reconnecting"),this.retryTimer=setTimeout(()=>this.connect(),n))}}send(e){var t;if(new TextEncoder().encode(e).byteLength>0xa00000)throw Error("本地调试消息超过 10MiB,无法发送");if((null==(t=this.socket)?void 0:t.readyState)!==WebSocket.OPEN)throw Error("本地调试服务未连接");if(this.socket.bufferedAmount>0xa00000)throw this.socket.close(4e3,"Debugger connection is too slow"),Error("本地调试服务发送缓冲区已满");this.socket.send(e)}async reportResult(e){this.send(JSON.stringify({type:"control_result",data:e}))}async clearSandboxLogs(){this.send(JSON.stringify({type:"clear_sandbox_logs"}))}publishSnapshot(e,t){this.snapshot={payload:e,runtime:t},this.sendSnapshot()}sendSnapshot(){var e;if(!this.snapshot||(null==(e=this.socket)?void 0:e.readyState)!==WebSocket.OPEN)return;let{payload:t,runtime:r}=this.snapshot;try{let e=t8(t,{includeRuntimeRoot:r!==this.sentRuntime});this.send(t5({type:"snapshot",data:e})),this.sentRuntime=r,this.snapshotErrorReported=!1}catch(e){this.snapshotErrorReported||console.warn("调试快照上传失败,控制连接保持可用:",e),this.snapshotErrorReported=!0}}}var ru=r(64865),rc=r(11855);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);let rp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",rm=new Uint8Array(256);for(let e=0;e<rp.length;e++)rm[rp.charCodeAt(e)]=e;function rh(e){let t=new Uint8Array(e),r=t.length,n="";for(let e=0;e<r;e+=3)n+=rp[t[e]>>2],n+=rp[(3&t[e])<<4|t[e+1]>>4],n+=rp[(15&t[e+1])<<2|t[e+2]>>6],n+=rp[63&t[e+2]];return r%3==2?n=`${n.substring(0,n.length-1)}=`:r%3==1&&(n=`${n.substring(0,n.length-2)}==`),n}function rg(e){let t,r,n,a,i,s=.75*e.length,o=e.length,l=0;"="===e[e.length-1]&&(s--,"="===e[e.length-2]&&s--);let d=new ArrayBuffer(s),u=new Uint8Array(d);for(t=0;t<o;t+=4)r=rm[e.charCodeAt(t)],n=rm[e.charCodeAt(t+1)],a=rm[e.charCodeAt(t+2)],i=rm[e.charCodeAt(t+3)],u[l++]=r<<2|n>>4,u[l++]=(15&n)<<4|a>>2,u[l++]=(3&a)<<6|63&i;return d}let rf="/__web_artifacts/base/manifest.json",rv="/app_developer";function ry(e){return!e.debugHidden}let r_={chat:"chat","image-upload":"images/upload","tool-report":"tool/report"};function rb(e){let t=e3(String(e??rv).trim(),{addProtocolToBareHost:!0,allowRootRelative:!0,defaultProtocol:rw}).replace(/\/+$/,"");if(t.startsWith("/"))return t;try{let e=new URL(t);if(""===e.pathname||"/"===e.pathname)return e.pathname="/app_developer",e.toString().replace(/\/+$/,"")}catch{}return t}function rw(e){return/^(localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|\[::1\])(?::|\/|$)/i.test(e)?"http":"https"}function rS(e){var t;let r="function"==typeof(null==(t=globalThis.crypto)?void 0:t.randomUUID)?globalThis.crypto.randomUUID().replace(/-/g,""):Math.random().toString(36).slice(2);return`${e}_${Date.now().toString(36)}${r.slice(0,10)}`}function rx(e,t){return`${rb(e)}/api/simulator/${r_[t]}`}function rI(e){if(e.type&&!e.type.startsWith("image/"))throw Error("仅支持图片文件");if(e.size>0xa00000)throw Error("图片不能超过 10 MiB")}var rE=r(75585);let rC=["ack","message_start","text_delta","tool_call","tool_status","card_delta","content_block","stream_error","message_finish","reply_finish","answer_finish","trace_event","heartbeat"];async function rk(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=e.getReader(),a=new TextDecoder,i={...r,fallbackSeq:0},s=(0,rE.C)({onEvent:e=>{let r=function(e,t){var r,n,a;let i,s,o,l,d,u,c=void 0===(l=tP(r=e.data))&&r.trim()?r:l,p=e8(c)?{...c,event:c.event||e.event}:{event:e.event||"message",data:c},{eventType:m,payload:h}=function(e){var t;for(let t of rC){let r=e[t];if(e8(r))return{eventType:t,payload:r};if("content_block"===t&&Array.isArray(r))return{eventType:t,payload:{content_block:r}}}return{eventType:"string"==typeof(t=e.event)&&t?t.toLowerCase():"message",payload:e}}(p),g=e8(h)?h:{},f="number"==typeof p.sequence&&Number.isFinite(p.sequence)?p.sequence:t.fallbackSeq+=1,v=e.id||("string"==typeof p.id?p.id:"")||`evt_${f.toString().padStart(4,"0")}`,y=function(e,t,r){let n=("string"==typeof e.request_id?e.request_id:"")||("ack"===r&&"string"==typeof t.request_id?t.request_id:"");if("ack"===r&&!n)throw Error("Invalid simulator SSE ACK: missing request_id");return n||("string"==typeof e.id?e.id:"")}(p,g,m),_=("string"==typeof p.reply_message_id?p.reply_message_id:"")||("string"==typeof g.message_id?g.message_id:"")||t.replyMessageId;return{event_id:v,event_type:m,seq:f,request_id:y,query_message_id:("string"==typeof p.query_message_id?p.query_message_id:"")||("string"==typeof g.query_message_id?g.query_message_id:""),reply_message_id:_,created_at_ms:"number"==typeof p.timestamp_ms&&Number.isFinite(p.timestamp_ms)?p.timestamp_ms:Date.now(),received_at_ms:Date.now(),trace:(d=e8(p.trace)?p.trace:{},{trace_id:"string"==typeof(u=t.trace??{}).trace_id?u.trace_id:"string"==typeof d.trace_id?d.trace_id:rS("trace"),span_id:"string"==typeof d.span_id?d.span_id:rS("span_sse"),parent_span_id:"string"==typeof d.parent_span_id?d.parent_span_id:"string"==typeof u.span_id?u.span_id:void 0,component:"string"==typeof d.component?d.component:"app_developer_simulator",stage:"string"==typeof d.stage?d.stage:m,sampled:"boolean"==typeof d.sampled?d.sampled:"boolean"!=typeof u.sampled||u.sampled,baggage:{...e8(u.baggage)?u.baggage:{},...e8(d.baggage)?d.baggage:{}}}),payload:(n=g,0===(o=Array.isArray(s=e8(i=null==(a=t.trace)?void 0:a.baggage)?i.log_ids:void 0)?s.filter(e=>"string"==typeof e&&e.trim().length>0):"string"==typeof s&&s.trim()?[s]:[]).length||void 0!==n.log_ids?n:{...n,log_ids:o})}}(e,i);r.reply_message_id&&(i.replyMessageId=r.reply_message_id),t(r)}});for(;;){let{done:e,value:t}=await n.read();if(t&&s.feed(a.decode(t,{stream:!e})),e)break}let o=a.decode();o&&s.feed(o),s.feed("\n\n")}let rN="x-tt-logid";class rT extends Error{responseDebug;constructor(e,t){super(e),this.responseDebug=t,this.name="SimulatorHttpError"}}function rR(e){return e.headers.get(rN)}function rM(e){let t={},r=rR(e);return r&&(t[rN]=r),t}function rA(e){return e8(e.trace)?e.trace:{}}async function rP(e,t){let r=rR(t),n=rM(t),a=await t.text().catch(()=>""),i={status:t.status,status_text:t.statusText,response_headers:Object.keys(n).length>0?n:void 0,log_ids:r?[r]:void 0,response_text:a};return new rT(`${e}: ${t.status} ${t.statusText}`,i)}function rj(e){return e instanceof rT?e.responseDebug:void 0}function rL(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},a=arguments.length>4?arguments[4]:void 0,i=rA(e),s=Date.now();return{event_id:rS("evt_client_debug"),event_type:"debug",seq:0,request_id:"string"==typeof e.idempotency_key?e.idempotency_key:"client_debug",created_at_ms:s,received_at_ms:s,trace:{trace_id:"string"==typeof i.trace_id?i.trace_id:rS("trace"),component:"string"==typeof i.component?i.component:"simulator_web_tester",stage:"string"==typeof i.stage?i.stage:"query",sampled:"boolean"!=typeof i.sampled||i.sampled,baggage:a??(e8(i.baggage)?i.baggage:{})},payload:{event:t,category:"api",elapsed_ms:Date.now()-r,...n}}}async function rD(e){var t;let{endpoint:r,fetcher:n,file:a,signal:i}=e;rI(a);let s=new FormData;s.append("image",a);let o=await (n??fetch)(rx(r,"image-upload"),{method:"POST",headers:{Accept:"application/json"},body:s,signal:i});if(!o.ok)throw await rP("Simulator image upload failed",o);let l=await o.json();if(0!==l.code)throw new rT(l.message||`Simulator image upload failed with code ${l.code}`,{response_body:l,log_ids:l.log_id?[l.log_id]:void 0});let d=null==(t=l.data)?void 0:t.image;if(!(null==d?void 0:d.resource_uri))throw new rT("Simulator image upload response is missing image.resource_uri",{response_body:l,log_ids:l.log_id?[l.log_id]:void 0});return d}async function rO(e){let t,{endpoint:r,fetcher:n,onEvent:a,onSubmitted:i,request:s,signal:o}=e,l=Date.now(),d=rx(r,"chat");a(rL(s,"simulator_chat_fetch_started",l,{endpoint:"chat",phase:"request",request:s,request_json:tL(s),url:d}));let u=setTimeout(()=>{a(rL(s,"simulator_chat_fetch_waiting_for_headers",l,{endpoint:"chat",phase:"wait",url:d,wait_ms:5e3}))},5e3);try{let e=(n??fetch)(d,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(s),signal:o});null==i||i(),t=await e}catch(e){throw clearTimeout(u),a(rL(s,"simulator_chat_fetch_failed",l,{endpoint:"chat",phase:"error",url:d,error:tD(e)})),e}clearTimeout(u);let c=rR(t),p=rM(t),m=rA(s),h={...e8(m.baggage)?m.baggage:{}};if(c&&(h[rN]=c,h.log_ids=[c]),a(rL(s,"simulator_chat_headers_received",l,{event:"simulator_chat_response_meta",endpoint:"chat",phase:"response",status:t.status,status_text:t.statusText,log_ids:c?[c]:void 0,response_headers:Object.keys(p).length>0?p:void 0},h)),!t.ok){let e=await rP("Simulator query failed",t);throw a(rL(s,"simulator_chat_fetch_failed",l,{endpoint:"chat",phase:"error",error:e.message,...e.responseDebug},h)),e}if(!t.body)throw Error("Simulator query response has no SSE body");let g=0,f=!1,v=setTimeout(()=>{f||a(rL(s,"simulator_chat_sse_waiting_for_first_event",l,{endpoint:"chat",wait_ms:5e3},h))},5e3);try{await rk(t.body,e=>{g+=1,f||(f=!0,clearTimeout(v)),a(e)},{trace:{...m,baggage:h}})}catch(e){throw clearTimeout(v),a(rL(s,"simulator_chat_sse_read_failed",l,{endpoint:"chat",phase:"error",event_count:g,error:tD(e)},h)),e}clearTimeout(v)}async function rU(e){let{endpoint:t,fetcher:r,result:n,signal:a}=e,i=await (r??fetch)(rx(t,"tool-report"),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(n),signal:a});if(!i.ok)throw await rP("Simulator tool result failed",i);let s=await rq(i),o=rR(i);return{...s,response_headers:o?{...e8(s.response_headers)?s.response_headers:{},[rN]:o}:s.response_headers,log_ids:o?[o]:s.log_ids}}async function rq(e){let t=await e.text().catch(()=>"");if(!t.trim())return{};try{let e=JSON.parse(t);return e8(e)?e:{response_body:e}}catch{return{response_text:t}}}let r$={label:"Request",tone:"request"},rB={label:"Response",tone:"response"},rF={simulator_query_prepare_started:{debugOnly:!0,title:"Query Prepare Started"},simulator_query_mcp_resolved:{debugOnly:!0,title:"MCP Ready"},simulator_query_aborted:{title:"Query Aborted"},simulator_query_failed:{title:"Query Failed"},simulator_query_cancel_requested:{title:"Query Cancel Requested"},simulator_chat_fetch_started:{badge:r$,title:"Chat"},simulator_chat_fetch_waiting_for_headers:{title:"Chat Waiting"},simulator_chat_response_meta:{badge:rB,title:"Chat"},simulator_chat_fetch_failed:{badge:rB,title:"Chat Failed"},simulator_chat_sse_waiting_for_first_event:{title:"Chat Waiting"},simulator_chat_sse_read_failed:{title:"Chat Stream Failed"},simulator_query_stream_returned:{title:"Chat Complete"},local_mcp_tools_load_started:{badge:r$,debugOnly:!0,title:"MCP Load"},local_mcp_tools_loaded:{badge:rB,debugOnly:!0,title:"MCP Load"},local_mcp_tools_load_failed:{badge:rB,title:"MCP Load Failed"},local_mcp_missing:{title:"MCP Missing"},local_mcp_call_started:{badge:r$,title:e=>`MCP Tool${e}`},local_mcp_call_succeeded:{badge:rB,title:e=>`MCP Tool${e}`},local_mcp_call_failed:{badge:rB,title:e=>`MCP Tool Failed${e}`},tool_result_report_started:{badge:r$,title:e=>`Report Tool Result${e}`},tool_result_report_response_received:{badge:rB,title:e=>`Report Tool Result${e}`},tool_result_report_failed:{badge:rB,title:e=>`Report Tool Result Failed${e}`},tool_result_ack:{title:"Report ACK"},tool_result_submit_skipped:{title:e=>`Report Tool Result Skipped${e}`},tool_result_submit_failed:{badge:rB,title:e=>`Report Tool Result Failed${e}`},tool_executor_missing:{title:e=>`Tool Executor Missing${e}`},tool_call_ignored:{title:e=>`Tool Call Ignored${e}`},tool_call_event_skipped:{title:e=>`Tool Call Skipped${e}`},tool_call_request_id_mismatch:{title:e=>`Tool Call Request Mismatch${e}`},tool_call_server_id_fallback:{title:e=>`Tool Call Server Fallback${e}`},simulator_card_rendered:{title:"Card Rendered"},simulator_card_render_skipped:{title:"Card Render Skipped"},simulator_card_render_failed:{title:"Card Render Failed"},simulator_card_runtime_error:{title:"Card Render Failed"},simulator_manifest_load_started:{badge:r$,debugOnly:!0,title:"Manifest Load"},simulator_manifest_loaded:{badge:rB,debugOnly:!0,title:"Manifest Load"},simulator_manifest_load_failed:{badge:rB,title:"Manifest Load Failed"},simulator_manifest_fetch_started:{badge:r$,debugOnly:!0,title:"Manifest Fetch"},simulator_manifest_fetch_succeeded:{badge:rB,debugOnly:!0,title:"Manifest Fetch"},simulator_manifest_fetch_failed:{badge:rB,title:"Manifest Fetch Failed"},simulator_manifest_missing:{title:"Manifest Missing"},simulator_skill_load_started:{badge:r$,debugOnly:!0,title:"Skill Load"},simulator_skill_loaded:{badge:rB,debugOnly:!0,title:"Skill Load"},simulator_skill_empty:{badge:rB,debugOnly:!0,title:"Skill Empty"},simulator_skill_load_failed:{badge:rB,title:"Skill Load Failed"},simulator_skill_fetch_started:{badge:r$,debugOnly:!0,title:"Skill Fetch"},simulator_skill_fetch_succeeded:{badge:rB,debugOnly:!0,title:"Skill Fetch"},simulator_skill_fetch_failed:{badge:rB,title:"Skill Fetch Failed"},simulator_skill_missing:{title:"Skill Missing"},simulator_resources_check_started:{debugOnly:!0,title:"Resource Check Started"},simulator_resources_check_completed:{debugOnly:!0,title:"Resource Check Completed"},simulator_resource_reload_completed:{title:"Resource Reloaded"}};function rW(e){if(!e8(e))return;let t=rH(e);return{category:t.category,debugOnly:t.debugOnly,detail:t.detail,leftBadges:t.transportBadge?[t.transportBadge]:void 0,phase:t.phase,title:t.title}}function rH(e){var t,r;let n=e.event||"",a=rF[n],i=e.detail??e.data??e,s=e.title?tU(e.title):function(e,t){var r;let n=null==(r=rF[e])?void 0:r.title;if("function"==typeof n){let e;return n((e=t.tool_name||t.tool_call_id)?`: ${e}`:"")}return n||(e?tU(e):"Agent Trace Event")}(n,e),o=e.category?tO(e.category):(t=n).startsWith("local_mcp_")?"mcp":t.startsWith("tool_result_report_")||"tool_result_ack"===t?"api":t.startsWith("tool_result_")||t.startsWith("tool_call_")||"tool_executor_missing"===t?"agent":t.startsWith("simulator_card_")?"card":t.startsWith("simulator_manifest_")||t.startsWith("simulator_skill_")||t.startsWith("simulator_resource_")||t.startsWith("simulator_resources_")?"resource":t.startsWith("simulator_chat_")?"api":t.startsWith("simulator_query_")?"agent":"runtime",l=e.phase||("local_mcp_missing"===(r=n)?"error":/(started|starting)$/.test(r)?"request":/(completed|loaded|resolved|received|returned|succeeded|rendered)$/.test(r)?"response":/(failed|error|aborted|rejected)$/.test(r)?"error":/(empty|skipped|ignored|mismatch|fallback|cancel_requested)$/.test(r)?"status":"tool_result_ack"===r?"ack":"event");return{category:o,debugOnly:(null==a?void 0:a.debugOnly)===!0,detail:i,eventName:n,phase:l,title:s,transportBadge:null==a?void 0:a.badge}}function rz(e){return e.blocks.some(e=>"card"===e.type&&"permission_apply"===e.card.card_type)}function rV(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{messages:r,streamStatus:n}=e.getState().simulator,a=function(e,t){let r=t?e.findIndex(e=>e.messageId===t):e.findLastIndex(rz);if(-1===r)return;let n=e[r];if(rz(n))for(let t=r-1;t>=0;t--){let r=e[t],a="user"===r.role?r.blocks.filter(e=>"image"===e.type).map(e=>e.image):[];if("user"===r.role&&(r.text.trim()||a.length>0))return{followUpContent:r.followUpContent,images:a.length>0?a:void 0,messageIds:[r.messageId,n.messageId],query:r.text.trim()}}}(r,t.grantingMessageId);if(!a)return{status:"not_found"};if("streaming"===n)return{status:"streaming"};e.removeSimulatorMessages(a.messageIds);let i=t.noLogin?{noLogin:!0}:{};return{completion:a.followUpContent?e.sendSimulatorFollowUpMessage(a.followUpContent,i):e.sendSimulatorQuery(a.query,{images:a.images,...i}),status:"started",target:a}}function rG(e){if(!e8(e))return;let t="string"==typeof e.grantingName?e.grantingName:"";if(t){var r;let n;return{grantingName:t,permissionStatus:"string"==typeof e.permissionStatus?e.permissionStatus:"pending",priorityLevel:"number"==typeof e.priorityLevel?e.priorityLevel:0,relatedData:{...n=tj(r=e.relatedData)??(e8(r)?r:{}),bizLoginDescription:"string"==typeof n.bizLoginDescription?n.bizLoginDescription:"",bizPrivacyContent:"string"==typeof n.bizPrivacyContent?n.bizPrivacyContent:"",mobileMask:"string"==typeof n.mobileMask?n.mobileMask:"",privacyURL:"string"==typeof n.privacyURL?n.privacyURL:"",scopeDescription:"string"==typeof n.scopeDescription?n.scopeDescription:"",scopeName:"string"==typeof n.scopeName?n.scopeName:"",termsOfServiceURL:"string"==typeof n.termsOfServiceURL?n.termsOfServiceURL:""},required:!1!==e.required}}}function rJ(e){let t=tj(e);if(!t)return;let r=Array.isArray(t.grantingList)?t.grantingList.map(rG).filter(e=>!!e):[];if(0!==r.length)return{cardStatus:"string"==typeof t.cardStatus?t.cardStatus:"unexpired",doubaoAppletIcon:"string"==typeof t.doubaoAppletIcon?t.doubaoAppletIcon:"",doubaoAppletKey:"string"==typeof t.doubaoAppletKey?t.doubaoAppletKey:"",doubaoAppletName:"string"==typeof t.doubaoAppletName&&t.doubaoAppletName?t.doubaoAppletName:"智能服务",doubaoAppletVersion:"string"==typeof t.doubaoAppletVersion?t.doubaoAppletVersion:"",grantingList:r,raw:t}}function rK(e){var t;switch(null==(t=e.grantingList[0])?void 0:t.grantingName){case"permission":return"权限申请";case"privacy":return"隐私协议提示";default:return"登录授权"}}r(66249);let rX="miniapp_packet_10066";function rQ(e,t,r,n,a){let i=e.find(e=>e.messageId===t);return i?n&&!i.requestId||a&&!i.traceId?e.map(e=>e===i?{...e,requestId:e.requestId||n,traceId:e.traceId||a}:e):e:[...e,{messageId:t,requestId:n,traceId:a,role:"assistant",contentType:"mixed",text:"",blocks:[],status:"streaming",createdAtMs:r}]}function rY(e,t,r){return e.map(e=>e.messageId===t?r(e):e)}function rZ(e,t,r,n){let a={blockId:t,type:"card",card:r};if("replace"===n){let n=r.card_id,i=e.map(e=>e.blockId===t||"card"===e.type&&n&&e.card.card_id===n?a:e);return i.some(e=>e===a)?i:[...e,a]}return e.some(e=>e.blockId===t)?e.map(e=>e.blockId===t?a:e):[...e,a]}function r0(e,t,r){let n=!1,a=!1,i=e.map(e=>{let i=!1,s=e.blocks.map(e=>{if("card"!==e.type||e.card.card_id!==t)return e;n=!0;let s=r(e.card);return s?(a=!0,i=!0,{...e,card:s}):e});return i?{...e,blocks:s}:e});return{messages:a?i:e,found:n,updated:a}}function r1(e){return"debug"===e.event_type?e.payload.data??e.payload:e.payload}function r2(e){let t=e.payload.tool_name||e.payload.tool_call_id,r=e.payload.status;switch(e.event_type){case"ack":return"Chat ACK";case"tool_call":return`Tool Call${t?`: ${t}`:""}`;case"tool_status":return`Tool Status${t?`: ${t}`:""}${r?` (${r})`:""}`;case"card_delta":return"Card Received";case"answer_finish":return"Answer Finished";case"message_finish":return"Message Finished";case"reply_finish":return"Reply Finished";case"stream_error":return"Stream Error";case"trace_event":return tU(e.payload.title||"Agent Trace");case"heartbeat":return"Heartbeat";default:return tU(e.event_type)}}function r3(e){let t=e.payload.category;if(t)return tO(t);switch(e.event_type){case"tool_call":case"tool_status":case"trace_event":default:return"agent";case"card_delta":return"card";case"debug":return"debug"}}function r4(e){switch(e){case"ack":return"accepted";case"message_start":return"message_start";case"text_delta":return"text_delta";case"tool_call":return"request";case"tool_status":return"response";case"card_delta":return"card_delta";case"message_finish":case"reply_finish":case"answer_finish":return"finish";case"stream_error":return"error";case"trace_event":return"trace";default:return e}}function r5(e){return"u">typeof DOMException&&e instanceof DOMException?"AbortError"===e.name:e instanceof Error&&"AbortError"===e.name}function r8(e,t){if(e8(e)&&"code"in e&&"message"in e)return e;let r=e8(e)&&e8(e.responseDebug)?e.responseDebug:void 0,n=tj(null==r?void 0:r.response_text),a="string"==typeof(null==n?void 0:n.message)&&n.message.trim()?n.message.trim():"string"==typeof(null==r?void 0:r.response_text)&&r.response_text.trim()?r.response_text.trim():"";return{code:("string"==typeof(null==n?void 0:n.code)||"number"==typeof(null==n?void 0:n.code)?String(n.code):void 0)??"INTERNAL_ERROR",message:a||tD(e),retryable:!1,stage:t,details:r?{response:r,response_body:n}:void 0}}function r6(e,t){if(e||t)return{...e,...t}}function r7(e,t){var r;let n=(null==(r=e.traceEvents.at(-1))?void 0:r.order)??e.traceEvents.length;return{...e,traceEvents:[...e.traceEvents,{...t,order:n+1}].slice(-200)}}function r9(e,t,r){var n;let a=function(e){let t=e8(e.card)?e.card:{},r=e8(t.state)?t.state:{},n=e.card_id,a=r.widget_id;if("update_state"!==e.op||"miniapp_history_refresh"!==t.card_type||"fixed_style"!==r.refresh_to||!n||!a)return;let i=r.url||r.schema,s=r.title,o=r.detailText;return{cardId:n,state:r,widgetData:{url:i,title:s,detailText:o},widgetId:a}}(t);if(a){let t=r0(e.messages,a.cardId,e=>{let t=e.state??{};if("fixed"!==t.lifecycle_state)return{...e,render_data:{viewData:a.widgetData},widget_id:a.widgetId,state:{...t,...a.state,lifecycle_state:"fixed"}}});return{state:{...e,messages:t.messages},cardRefresh:{cardId:a.cardId,status:t.updated?"updated":t.found?"already_fixed":"not_found"}}}let i=function(e){let t=e.card;if(!e8(t)||t.card_type!==rX)return;let r=e.card_id||t.card_id,n=tj(t.props_json),a=e8(null==n?void 0:n._meta)?n._meta:void 0,i=e8(t.render_data)?t.render_data:void 0,s=e8(null==i?void 0:i.ext)?i.ext:void 0;if(!r||!n||!a||!i||!s||!0!==a.skip_response_validate||"2"!==i.packet_type||"1"!==s._auth_request||"none"!==s.auth_require||"1"!==s.from_mcp||"1"!==s.is_mini_app||"string"!=typeof n.direct_return)return;let o=tj(n.direct_return);if((null==o?void 0:o.mcp_channel)==="flow_miniapp"&&Array.isArray(o.chunk_messages))for(let t of o.chunk_messages){if(!e8(t)||!0!==t.IsFinish||2!==t.MessageType||1005!==t.ContentType||"string"!=typeof t.Content)continue;let n=tj(t.Content);if((null==n?void 0:n.command_type)==="require_location"&&e8(n.require_location))return{cardId:r,appKey:s.app_key,sourceToolCallId:e.source_tool_call_id,toolName:s.tool_name}}}((null==r?void 0:r.payload)??{});if(i&&r)return{state:e,locationDirective:{...i,requestId:r.request_id,queryMessageId:r.query_message_id,replyMessageId:r.reply_message_id??e.activeReplyMessageId}};let s=(null==r?void 0:r.reply_message_id)??e.activeReplyMessageId,o=function(e){var t,r;let n,a=e.card;if(!e8(a))return{};let i=tj(a.props_json)??{},s=function(e){let t,r;if(e.card_type!==rX)return;let n=tj(e.props_json)||tj(e.render_data_json)||(e8(e.render_data)?tj(e.render_data.content_for_display):void 0)||{};return n.permission_data||((r=(Array.isArray(null==(t=e8(n.structuredContent)?n.structuredContent:void 0)?void 0:t.entity_list)?t.entity_list:[]).find(e=>e8(e)&&(Array.isArray(e.grantingList)||e8(e._meta)&&!0===e._meta.is_permission)))&&e8(r)?JSON.stringify(r):void 0)}(a),o=rJ(s),l=e8(i.extra)?i.extra:{},d=Object.keys(i).length>0?(n=tj(i.widget_data))?{viewData:n}:e8(i.viewData)?{viewData:i.viewData}:{viewData:i}:void 0,u={...e8(a.source)?a.source:{},tool_call_id:e.source_tool_call_id||(null==(t=a.source)?void 0:t.tool_call_id),entity_ids:Array.isArray(e.source_entity_ids)?e.source_entity_ids:null==(r=a.source)?void 0:r.entity_ids};return{...{card_id:e.card_id,widget_id:e.widget_id,card_type:e.card_type,app_id:e.app_id},...a,widget_id:i.widget_id||a.widget_id||e.widget_id,app_id:i.applet_id||a.app_id||e.app_id,entity_id:i.entity_id||a.entity_id,source:u,card_type:o?"permission_apply":a.card_type||e.card_type,fallback_text:o?a.fallback_text||"需要授权后继续":a.fallback_text,render_data:o?{grantingData:o,permissionData:s}:d||a.render_data,title:o?a.title||rK(o):a.title,debug:{...e8(a.debug)?a.debug:{},props_json:a.props_json,output_template:l["doubao/outputTemplate"]}}}(t),l=t.block_id||o.card_id||(n=`card_${(null==r?void 0:r.seq)??0}`,o.card_id||o.title||n),d=t.op||"append";if("append"!==d&&"replace"!==d)return{state:e};if(o.card_id){let t=r0(e.messages,o.card_id,e=>{let t,n,a,i;return r?o:(t=r6(e.state,o.state),n=r6(e.source,o.source),a=r6(e.debug,o.debug),i=Object.fromEntries(Object.entries(o).filter(e=>{let[,t]=e;return void 0!==t})),{...e,...i,state:t,source:n,debug:a})});if(t.found)return{state:{...e,messages:t.messages},cardRefresh:{cardId:o.card_id,status:"updated"}}}if(!s)return{state:e};let u=rQ(e.messages,s,(null==r?void 0:r.created_at_ms)??Date.now(),null==r?void 0:r.request_id,null==r?void 0:r.trace.trace_id);return{state:{...e,messages:rY(u,s,e=>({...e,contentType:"mixed",blocks:rZ(e.blocks,l,o,d)}))}}}function ne(e,t){let r="completed"===t?"completed":"cancelled"===t?"interrupted":"failed";return e.map(e=>"assistant"===e.role&&"streaming"===e.status?{...e,status:r}:e)}function nt(e,t,r){return{...e,toolCalls:e.toolCalls.map(e=>e.toolCallId===t?{...e,...r}:e)}}function nr(e,t){let r={tool_call_id:t.toolCallId,tool_name:t.toolName,arguments_summary:t.arguments&&Object.keys(t.arguments).length>0?t.arguments:void 0,status:t.status},n=e.findIndex(e=>e.tool_call_id===t.toolCallId);return n<0?[...e,r]:e.map((e,t)=>t===n?r:e)}r(32037);var nn=r(33680);function na(e,t){var r,n;return null==e||null==(n=e.tools)||null==(r=n[t])?void 0:r.output}function ni(e,t,r){if(!e8(e)||!Array.isArray(e.structuredContent))return e;let n=na(t,r);if(!n||"entities"!==n.kind)return e;if(!e.structuredContent.every(e8))throw Error(`Tool "${r}" structuredContent items must be objects`);return{...e,structuredContent:{entities:e.structuredContent.map(e=>({...e,entity_type:r}))}}}function ns(e,t){let r;if(!e8(e)||!Array.isArray(e.content))throw Error("MCP tool result must be an object with a content array");let n=void 0===(r=e.structuredContent)?{}:r,a=tL(e),i=e.content.filter(e8).map(e=>"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"),s=!0===e.isError;return{status:s?"failed":"succeeded",result:n,error:s?{code:t.businessErrorCode,message:e8(n)&&"string"==typeof n.message?n.message:i||a,retryable:!1,stage:"tool_execute",details:e8(n)?n:{structuredContent:n}}:void 0,raw_result_text:i,raw_mcp_result_json:a,miniapp:{is_mini_app:!0,mcp_channel:"flow_miniapp"},debug:{source:t.source,protocol:t.protocol,mcp_output:e}}}let no="client_tool",nl="__bridge_ready__",nd="lynxview";function nu(e,t){null==e||e({category:"mcp",source:"client_tool",...t})}class nc{runtimeUrl;container;errorListeners=new Set;host;messageListeners=new Set;view=null;constructor(e,t){this.runtimeUrl=e,this.host=function(){var e;if(!(null==(e=globalThis.document)?void 0:e.body))throw Error("Client Tool LynxView runtime requires document.body");let t=document.createElement("div");return t.dataset.doubaoClientToolRuntime="true",t.style.display="none",document.body.append(t),t}(),this.container=new tI({className:"doubao-client-tool-runtime-view",container:this.host,nativeModulesCallHandler:this.handleNativeModulesCall,onError:e=>this.emitError(e),onReady:()=>this.emitMessage({type:"event",name:nl})}),this.view=this.container.render({containerType:"TOOL",globalProps:t,initData:{},resourceUrl:e}),this.view.style.display="none"}addEventListener(e,t){"message"===e?this.messageListeners.add(t):this.errorListeners.add(t)}removeEventListener(e,t){"message"===e?this.messageListeners.delete(t):this.errorListeners.delete(t)}postMessage(e){this.container.sendGlobalEvent("__APPLET_BRIDGE__",[e])}terminate(){this.messageListeners.clear(),this.errorListeners.clear(),this.container.clear(),this.host.remove(),this.view=null}handleNativeModulesCall=(e,t,r)=>{if("AppletBridgeModule"===r&&"postMessage"===e&&e8(t)&&nm(t))return this.emitMessage(t),t};emitMessage(e){let t={data:e};for(let e of this.messageListeners)e(t)}emitError(e){let t=new ErrorEvent("error",{error:e,message:e.message});for(let e of this.errorListeners)e(t)}}function np(e){return Object.assign(Error(e),{name:"AbortError"})}function nm(e){return"callback"===e.type&&"number"==typeof e.callbackId}class nh{runtimeUrl;runtime;onTraceEvent;callbackId=1;ready=!1;readyPromise;rejectReady;resolveReady;pendingCallbacks=new Map;constructor(e,t,r){this.runtimeUrl=e,this.runtime=t,this.onTraceEvent=r,this.runtime.addEventListener("message",this.handleMessage),this.runtime.addEventListener("error",this.handleError)}async invokeTool(e){await this.ensureReady(e.signal);let{signal:t,...r}=e;return this.call("applet.invokeTool",r,{signal:t})}dispose(){var e;let t=Error("Client Tool runtime was disposed");for(let r of(this.runtime.removeEventListener("message",this.handleMessage),this.runtime.removeEventListener("error",this.handleError),this.runtime.terminate(),null==(e=this.rejectReady)||e.call(this,t),this.pendingCallbacks.values()))r.reject(t);this.pendingCallbacks.clear()}ensureReady(e){if(null==e?void 0:e.aborted)return Promise.reject(np("Client Tool call aborted"));if(this.ready)return Promise.resolve();let t=this.readyPromise??(this.readyPromise=new Promise((e,t)=>{this.resolveReady=e,this.rejectReady=t}));return e?new Promise((r,n)=>{let a=()=>{e.removeEventListener("abort",a),n(np("Client Tool call aborted"))};e.addEventListener("abort",a,{once:!0}),t.then(()=>{e.removeEventListener("abort",a),r()},t=>{e.removeEventListener("abort",a),n(t)}),e.aborted&&a()}):t}call(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=this.callbackId;return this.callbackId+=1,new Promise((a,i)=>{let{signal:s}=r;if(null==s?void 0:s.aborted)return void i(np("Client Tool call aborted"));let o=()=>{null==s||s.removeEventListener("abort",l)},l=()=>{this.pendingCallbacks.delete(n),i(np("Client Tool call aborted"))};null==s||s.addEventListener("abort",l,{once:!0}),this.pendingCallbacks.set(n,{reject:e=>{o(),i(e)},resolve:e=>{o(),a(e)}}),this.runtime.postMessage({type:"call",name:e,params:t,callbackId:n,target:{scope:"main",target:"self"}})})}handleMessage=e=>{var t;let r,n=e8(r="string"==typeof e.data?tP(e.data):e.data)?r:void 0;if(!n)return;if("event"===n.type&&n.name===nl){this.ready=!0,null==(t=this.resolveReady)||t.call(this),nu(this.onTraceEvent,{event:"client_tool_runtime_ready",runtime_url:this.runtimeUrl});return}if(!nm(n))return;let a=this.pendingCallbacks.get(n.callbackId);if(a){this.pendingCallbacks.delete(n.callbackId);try{a.resolve(function(e){let t=e8(e.params)?e.params:{};if(1===t.code)return t.data;throw Error("string"==typeof t.msg&&t.msg||`Client Tool runtime callback failed with code ${String(t.code)}`)}(n))}catch(e){a.reject(e)}}};handleError=e=>{var t;let r=Error(e.message||"Client Tool runtime failed");for(let e of(null==(t=this.rejectReady)||t.call(this,r),this.pendingCallbacks.values()))e.reject(r);this.pendingCallbacks.clear()}}function ng(e,t,r){return{status:"failed",result:{error:t},error:{code:e,message:t,retryable:r,stage:"tool_execute"},raw_result_text:t,miniapp:{is_mini_app:!0,mcp_channel:"flow_miniapp"},debug:{source:"client_tool",protocol:nd}}}let nf="simulator_web_tester";function nv(e){var t,r,n;let a=(t=e.messages,r=e.toolCalls,n=e.historyMaxTurns,t.slice(-Math.max(0,2*n)).map(e=>{var t,n,a;let i,s,o,l=(t=e,(i=r.filter(e=>e.replyMessageId===t.messageId&&nb(e.status)).map(e=>({tool_call_id:e.toolCallId,tool_name:e.toolName,arguments_summary:e.arguments&&Object.keys(e.arguments).length>0?e.arguments:void 0,status:e.status}))).length>0?i:(t.toolCalls??[]).filter(e=>nb(e.status))),d=(n=e,(s=r.filter(e=>e.replyMessageId===n.messageId&&nb(e.status)).map(e=>{var t;let r=e.resultSummary?e.resultSummary:(null==(t=e.error)?void 0:t.message)?e.error.message:e.message;return{tool_call_id:e.toolCallId,tool_name:e.toolName,result_summary:r,structured_summary:e.structuredResultSummary,is_mini_app:e.isMiniApp}})).length>0?s:n.toolResults??[]),u=n_(e.blocks.flatMap(e=>"image"===e.type?[e.image]:[]));return{role:"assistant"===e.role?"ASSISTANT":"USER",content:(o=(a=e).text?a.text:a.blocks.filter(e=>"text"===e.type).map(e=>e.text).join(""))||e.blocks.map(e=>{var t;return"image"===e.type?e.image.name?`[图片:${e.image.name}]`:"[图片]":"card"===e.type?(t=e.card).fallback_text||t.title||t.card_type||t.card_id||"卡片":e.text}).filter(Boolean).join("\n"),parts:u.length>0?u:void 0,tool_calls:l.length>0?l.map(e=>({tool_call_id:e.tool_call_id,tool_name:e.tool_name,arguments:e.arguments_summary,status:e.status})):void 0,tool_results:d.length>0?d.map(e=>({tool_call_id:e.tool_call_id,tool_name:e.tool_name,result_summary:e.result_summary,structured_summary:e.structured_summary,is_mini_app:e.is_mini_app})):void 0}})),i=ny(e.messages),s=e.simulatorManifest||e.options.manifest||{},o=s.app_key||"",l=e.options.appKey||e.simulatorAppKey||o||e.manifestAppId||"web-sdk-debugger",d=e.options.appName||e.simulatorAppName||e.manifestAppName||l,u=(e.options.skills??e.simulatorSkills??[]).map(e=>e.content),c=e.options.mcpServers??e.simulatorMcpServers,p=function(e,t){let r=e.raw_manifest_yaml||"",n=t.find(e=>e.server_id===no&&e.tools.length>0);if(!n||!e.tools||null!=e.mcp_server)return r;let a=function(e){if(!e.trim())throw Error("Client Tool simulator manifest requires raw_manifest_yaml");let t=(0,nn.qg)(e);if(!e8(t))throw Error("Client Tool raw_manifest_yaml must contain a YAML object");return t}(r);return null!=a.mcp_server?r:(0,nn.As)({...a,mcp_server:{end_point:n.server_id,description:n.description||n.name}})}(s,c);return{app_id:l,scene:"miniapp_simulator_web_tester",history_messages:a,card_snapshots:i,trace:{trace_id:e.traceId,component:nf,stage:"query",sampled:!0},client:{platform:"web",locale:"zh-CN",timezone:function(){try{return new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"Asia/Shanghai"}}()},ext:{web_tester:"true",stateless_context:"client_history",skill_source:u.length>0?"local_file":"none",no_login:e.options.noLogin?"true":void 0},max_step:e.options.maxStep??e.simulatorMaxStep??20,protocol_version:"v2",idempotency_key:e.idempotencyKey,mini_apps:[{app_key:l,app_name:d,skills:u,manifest:{app_key:l,app_name:d,raw_manifest_yaml:p},mcp_servers:c.map(e=>({server_id:e.server_id,name:e.name,description:e.description||"",tools:e.tools.map(e=>({name:e.name,description:e.description||"",input_schema_json:tL(e.input_schema_json)}))}))}],web_capabilities:{supports_debug_event:!0}}}function ny(e){let t=new Map;for(let r of e)for(let e of r.blocks){if("card"!==e.type)continue;let r=function(e){var t,r,n;let a=tj(null==(t=e.debug)?void 0:t.props_json),i=e.card_id,s=(null==a?void 0:a.applet_id)||e.app_id,o=(null==a?void 0:a.entity_id)||e.entity_id;if(i&&s)return{card_id:i,app_key:s,business_entity_ids:o?[o]:void 0,lifecycle_state:(null==(r=e.state)?void 0:r.lifecycle_state)==="fixed"||(null==(n=e.state)?void 0:n.lifecycle_state)===2?2:1,refresh_key:e.refresh_key}}(e.card);r&&t.set(r.card_id,r)}return[...t.values()]}function n_(e){return e.map(e=>({type:"image",image:{resource_uri:e.resource_uri}}))}function nb(e){return["succeeded","failed","timeout","cancelled","rejected"].includes(e)}function nw(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"tool_execute",n=arguments.length>3?arguments[3]:void 0;return{code:e,message:t,user_message:t,retryable:!1,stage:r,details:n}}async function nS(e){let t,r,n,a,i,s,{executor:o,input:l,record:d,signal:u}=e,c=(t=void 0===d.deadlineMs?void 0:d.deadlineMs-Date.now(),r=d.timeoutMs,void 0===(n=void 0===t?r:void 0===r?t:Math.min(t,r))?void 0:Math.max(0,n)),p=nw("TOOL_EXEC_CANCELLED","Tool execution cancelled"),m=void 0===c?void 0:new AbortController,h=(null==m?void 0:m.signal)??u;if(null==u?void 0:u.aborted)throw p;if(m&&u){let e=()=>{m.abort()};u.addEventListener("abort",e,{once:!0}),i=()=>u.removeEventListener("abort",e)}let g=[Promise.resolve(o({...l,signal:h}))];if(void 0!==c&&m){let e=nw("TOOL_EXEC_TIMEOUT",`Tool execution timed out after ${c}ms`);g.push(new Promise((t,r)=>{a=setTimeout(()=>{m.abort(),r(e)},c)}))}u&&g.push(new Promise((e,t)=>{let r=()=>{t(p)};u.addEventListener("abort",r,{once:!0}),s=()=>u.removeEventListener("abort",r)}));try{return await Promise.race(g)}finally{a&&clearTimeout(a),null==i||i(),null==s||s()}}function nx(e){return e?String(e):rf}function nI(e,t,r){return r?{type:e,message:t,error:r}:{type:e,message:t}}let nE={simulator_manifest_load_failed:"Manifest",simulator_skill_load_failed:"Skill",local_mcp_tools_load_failed:"MCP",simulator_chat_fetch_failed:"对话接口"};function nC(e){return new Set(e.flatMap(e=>e.blocks.flatMap(e=>"image"===e.type&&e.image.previewUrl?[e.image.previewUrl]:[])))}function nk(e,t){return e?{kind:"pages",item:e,routeUrl:t}:null}function nN(e,t){if(!t)return null;try{return nk(ti({url:t},e).entry,t)}catch{return null}}function nT(e){var t,r;return e.raw_result_text||(null==(t=e.error)?void 0:t.message)||(void 0===(r=e.result)?"":"string"==typeof r?r.slice(0,1e3):tL(r).slice(0,1e3))||e.status}function nR(e,t){return e.app_key||e.appKey||e.appId||e.packageName||t}function nM(e,t){var r;return e.name||e.appName||e.app_name||(null==(r=e.applet)?void 0:r.name)||t}function nA(e,t){let r=e.applet??{},n=t.applet??{},a=r.tools??[],i=n.tools??[],s=new Map,o=t.name||t.appName||t.app_name||n.name||"";if(i.length>0)for(let e of[...a,...i])e.id&&s.set(e.id,e);return{...e,manifest_version:t.manifest_version??e.manifest_version,app_key:t.app_key??e.app_key,name:t.name??e.name,appName:t.appName??e.appName,app_name:t.app_name??e.app_name,mcp_server:t.mcp_server??e.mcp_server,tools:t.tools??e.tools,entities:t.entities??e.entities,tool_card_binding:t.tool_card_binding??e.tool_card_binding,raw_manifest_yaml:t.raw_manifest_yaml??e.raw_manifest_yaml,applet:{...r,name:o||r.name,tools:i.length>0?[...s.values()]:a}}}class nP{fetcher;simulatorFetcher;historyMaxTurns;simulatorAppKey;simulatorAppName;simulatorSkills;simulatorManifest;simulatorMaxStep;simulatorMcpServers;simulatorMcpServerProvider;simulatorToolExecutor;sandboxToolCallExecutions=new Map;listeners=new Set;activeSimulatorRun=null;lastResolvedSimulatorMcpServers=[];receivedSimulatorLocationDirectiveCardIds=new Set;resourceUrlVersion;hasSimulatorManifestStateValue=!1;simulatorManifestStateValue;simulatorManifestStatePromise;simulatorRunSeq=0;destroyed=!1;state;constructor(e={}){const t=nx(e.manifestUrl);this.fetcher=e.fetcher,this.simulatorFetcher=e.simulatorFetch,this.historyMaxTurns=e.historyMaxTurns??6,this.simulatorAppKey=e.appKey,this.simulatorAppName=e.appName,this.simulatorSkills=e.skills,this.simulatorManifest=e.simulatorManifest,this.simulatorMaxStep=e.maxStep,"function"==typeof e.mcpServers?(this.simulatorMcpServers=[],this.simulatorMcpServerProvider=e.mcpServers):this.simulatorMcpServers=e.mcpServers??[],this.simulatorToolExecutor=e.toolExecutor,this.state={manifestUrl:t,manifest:new eU({manifestVersion:"3.0",packageName:"",appId:"",versionCode:"",applet:{appletId:"",appRuntimeEntry:"",digest:"",pages:[]},widgets:[]}),pages:[],widgets:[],pageSelection:null,widgetSelection:null,simulator:function(e){return{endpoint:rb(e),messages:[],streamStatus:"idle",toolCalls:[],traceEvents:[]}}(e.simulatorEndpoint),status:nI("idle","Idle")}}clearSimulatorManifestStateValue(){this.hasSimulatorManifestStateValue=!1,this.simulatorManifestStateValue=void 0,this.simulatorManifestStatePromise=void 0}takeSimulatorManifestStateValue(){if(!this.hasSimulatorManifestStateValue)return{found:!1,value:void 0};let e=this.simulatorManifestStateValue;return this.clearSimulatorManifestStateValue(),{found:!0,value:e}}async loadSimulatorManifestForState(){if(void 0!==this.simulatorManifest)return"function"!=typeof this.simulatorManifest?this.simulatorManifest:this.hasSimulatorManifestStateValue?this.simulatorManifestStateValue:(this.simulatorManifestStatePromise||(this.simulatorManifestStatePromise=Promise.resolve(this.simulatorManifest()).then(e=>(this.hasSimulatorManifestStateValue=!0,this.simulatorManifestStateValue=e,e)).finally(()=>{this.simulatorManifestStatePromise=void 0})),this.simulatorManifestStatePromise)}async mergeSimulatorManifestForState(e){if(void 0===this.simulatorManifest)return e;try{let t=await this.loadSimulatorManifestForState();if(!t)return e;return new eU(nA(e.raw,t))}catch(t){return console.warn("[web-sdk-debugger] Failed to merge simulator manifest for debug state",t),e}}async loadManifest(e){this.assertActive();let t=this.state.manifestUrl,r=nx(e??this.state.manifestUrl);this.setState({...this.state,manifestUrl:r,resourceUrlVersion:this.resourceUrlVersion,status:nI("loading",`Loading manifest ${r}`)});try{var n,a,i,s,o,l,d;let e,t,u,c,p,m=await eq(r,{fetcher:this.fetcher}),h=await this.mergeSimulatorManifestForState(m),g=h.pages,f=h.widgets,v=nN(h,null==(n=this.state.pageSelection)?void 0:n.routeUrl)??(o=h,l=g,d=this.state.pageSelection,e=l.filter(ry),t=null==d?void 0:d.item.path,u=function(e,t){if(t)try{return e.getPageEntry(t)}catch{return}}(o,o.raw.applet.appletEntry),nk((t?e.find(e=>e.path===t):void 0)??(u&&ry(u)?u:void 0)??e.find(e=>"index"===e.id||"/pages/index"===e.path||"/pages/index/index"===e.path)??e[0])),y=(a=this.state.widgetSelection,c=f.filter(ry),(i=((p=null==a?void 0:a.item.widgetId)?c.find(e=>e.widgetId===p):void 0)??c[0])?{kind:"widgets",item:i}:null);return s={sandboxUrl:void 0,resolveManifestUrl:()=>r,resourceUrlVersion:this.resourceUrlVersion},"sandboxUrl"in s&&(eG=s.sandboxUrl??eV),ez.configure(s),this.setState({...this.state,manifestUrl:r,manifest:h,pages:g,widgets:f,resourceUrlVersion:this.resourceUrlVersion,pageSelection:v,widgetSelection:y,status:nI("ready",v||y?`Loaded manifest ${r}`:`Manifest has no entries ${r}`)}),this.state}catch(r){let e=r instanceof Error?r:Error(String(r));throw this.setState({...this.state,manifestUrl:t,status:nI("error",`Load failed: ${e.message}`,e)}),e}}navigateToPage(e){this.assertActive();try{let t=nN(this.state.manifest,e);if(!t)throw Error(`Unknown pages route: ${e}`);this.setState({...this.state,pageSelection:t,status:nI("ready",`Navigated page ${t.item.path}`)})}catch(t){let e=t instanceof Error?t:Error(String(t));throw this.setState({...this.state,status:nI("error",e.message,e)}),e}}selectWidget(e){this.assertActive();let t=this.state.widgets.find(t=>t.widgetId===e);if(!t){let t=Error(`Unknown widgets entry: ${e}`);throw this.setState({...this.state,status:nI("error",t.message,t)}),t}this.setState({...this.state,widgetSelection:{kind:"widgets",item:t},status:nI("ready",`Selected widget ${t.widgetId}`)})}async reloadResources(){if(this.assertActive(),"streaming"===this.state.simulator.streamStatus)throw Error("Cannot refresh card resources while simulator query is streaming");let e=this.state.manifestUrl,t=rS("reload");this.resourceUrlVersion=t,this.clearSimulatorManifestStateValue(),ez.clearPackageCache(e);let r=await this.loadManifest(e);return void 0!==this.simulatorSkills&&await this.resolveSimulatorSkillsForQuery(t,{}),this.appendSimulatorDebugEvent({category:"resource",event:"simulator_resource_reload_completed",manifest_url:e,resource_url_version:t,summary:"Card resources refreshed"}),r}async sendSimulatorQuery(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.assertActive();let r=e.trim(),n=(t.images??[]).filter(e=>e.resource_uri);if(r||0!==n.length)return this.sendSimulatorChat({kind:"message",queryText:r},t)}sendSimulatorFollowUpMessage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise((r,n)=>{let a=Error("Simulator follow-up message was cancelled before submission");this.sendSimulatorChat({kind:"follow_up",content:e},t,r,()=>n(a)).then(()=>n(a),n)})}async sendSimulatorChat(e,t,r,n){this.assertActive(),this.cancelSimulatorQuery();let a=rS("local_msg"),i=rS("idem"),s=rS("trace"),o=Date.now(),l=this.state.simulator,d=this.state.manifest.raw,u="message"===e.kind?(t.images??[]).filter(e=>e.resource_uri):[],c="message"===e.kind?{messageId:a,localMessageId:a,traceId:s,role:"user",contentType:u.length>0?"mixed":"text",text:e.queryText,blocks:[...u.map(e=>({blockId:rS("block_image"),type:"image",image:e})),...e.queryText?[{blockId:rS("block_text"),type:"text",text:e.queryText}]:[]],status:"completed",createdAtMs:o}:void 0,p=this.createSimulatorRun(s);p.onCancelledBeforeSubmission=n,this.activeSimulatorRun=p,this.setState({...this.state,simulator:{...l,activeRequestId:void 0,activeReplyMessageId:void 0,error:void 0,locationDirective:void 0,messages:c?[...l.messages,c]:l.messages,streamStatus:"streaming"}}),this.appendSimulatorDebugEvent({event:"simulator_query_prepare_started",trace_id:s,previous_active_request_id:l.activeRequestId,previous_stream_status:l.streamStatus,history_message_count:l.messages.length,query_preview:"message"===e.kind?e.queryText.slice(0,80)||"[图片]":"send_follow_up_message",image_count:u.length});try{var m,h;let n,u=await this.resolveSimulatorManifestForQuery(s,t,d,p.streamAbortController.signal),c=nR(u,this.state.manifest.appId),g=nM(u,this.state.manifest.name);if(!this.isSimulatorRunCurrent(p))return;let f=await this.resolveSimulatorSkillsForQuery(s,t,p.streamAbortController.signal);if(!this.isSimulatorRunCurrent(p))return;let v={signal:p.streamAbortController.signal,trace:{trace_id:s,component:"web_sdk_debugger",stage:"query_prepare",sampled:!0},appKey:t.appKey||this.simulatorAppKey||c,appName:t.appName||this.simulatorAppName||g,manifest:u},y=this.simulatorMcpServerProvider?await this.simulatorMcpServerProvider(v):this.simulatorMcpServers;if(this.lastResolvedSimulatorMcpServers=y,!this.isSimulatorRunCurrent(p))return;this.appendSimulatorDebugEvent({event:"simulator_query_mcp_resolved",trace_id:s,elapsed_ms:Date.now()-o,mcp_server_count:y.length,mcp_servers:y.map(e=>({server_id:e.server_id,tool_count:e.tools.length,tools:e.tools.map(e=>e.name)}))});let _={historyMaxTurns:this.historyMaxTurns,idempotencyKey:i,localMessageId:a,manifestAppId:this.state.manifest.appId,manifestAppName:g,messages:l.messages,toolCalls:l.toolCalls,options:t,simulatorAppKey:this.simulatorAppKey,simulatorAppName:this.simulatorAppName,simulatorSkills:f,simulatorManifest:u,simulatorMaxStep:this.simulatorMaxStep,simulatorMcpServers:y,traceId:s},b="message"===e.kind?(m={..._,queryText:e.queryText},n=n_(m.options.images??[]),{...nv(m),message:{role:"USER",content:m.queryText,local_message_id:m.localMessageId,parts:n.length>0?n:void 0}}):(h={..._,content:e.content},{...nv(h),input_event:{event_type:"send_follow_up_message",params:{content:h.content},local_message_id:h.localMessageId}});if(await rO({endpoint:this.state.simulator.endpoint,fetcher:this.simulatorFetcher,onSubmitted:()=>{p.onCancelledBeforeSubmission=void 0,null==r||r()},request:b,signal:p.streamAbortController.signal,onEvent:t=>this.handleSimulatorEvent(t,p,"follow_up"===e.kind?e.content:void 0)}),!this.isSimulatorRunCurrent(p))return;"streaming"===this.state.simulator.streamStatus&&this.setState({...this.state,simulator:{...this.state.simulator,activeRequestId:void 0,streamStatus:"completed"}}),this.appendSimulatorDebugEvent({event:"simulator_query_stream_returned",trace_id:s,elapsed_ms:Date.now()-o,stream_status:this.state.simulator.streamStatus,active_request_id:this.state.simulator.activeRequestId})}catch(n){if(r5(n))return void this.appendSimulatorDebugEvent({event:"simulator_query_aborted",trace_id:s,elapsed_ms:Date.now()-o,stream_status:this.state.simulator.streamStatus});if(!this.isSimulatorRunCurrent(p))return;let e=r8(n,"query_stream"),t=this.getSimulatorQueryFailureDiagnosis(s,n),r=t?{...e,message:t.summary,user_message:t.summary,details:{...e.details,diagnosis:t,original_error:e.message}}:e;throw this.appendSimulatorDebugEvent({event:"simulator_query_failed",trace_id:s,elapsed_ms:Date.now()-o,error:r}),this.setState({...this.state,simulator:{...this.state.simulator,activeRequestId:void 0,error:r,streamStatus:"error"}}),n}finally{this.finishSimulatorStream(p)}}removeSimulatorMessages(e){this.assertActive();let t=new Set(e.filter(Boolean));if(0===t.size)return;let r=nC(this.state.simulator.messages.filter(e=>t.has(e.messageId)));this.updateSimulatorState(e=>({...e,activeReplyMessageId:e.activeReplyMessageId&&t.has(e.activeReplyMessageId)?void 0:e.activeReplyMessageId,messages:e.messages.filter(e=>!t.has(e.messageId)),selectedCard:e.selectedCard&&t.has(e.selectedCard.reply_message_id)?void 0:e.selectedCard})),queueMicrotask(()=>{let e=nC(this.state.simulator.messages);for(let t of r)e.has(t)||URL.revokeObjectURL(t)})}applySimulatorCardDelta(e){this.assertActive(),this.updateSimulatorState(t=>r9(t,e8(e.card_delta)?e.card_delta:e).state)}consumeSimulatorLocationDirective(e){this.assertActive(),this.updateSimulatorState(t=>{var r;return(null==(r=t.locationDirective)?void 0:r.cardId)===e?{...t,locationDirective:void 0}:t})}cancelSimulatorQuery(){this.assertActive();let e=this.state.simulator.activeRequestId,t=this.activeSimulatorRun;t&&(this.appendSimulatorDebugEvent({event:"simulator_query_cancel_requested",request_id:e,trace_id:t.traceId,stream_status:this.state.simulator.streamStatus}),this.abortSimulatorRun(t)),"streaming"===this.state.simulator.streamStatus&&this.setState({...this.state,simulator:{...this.state.simulator,activeRequestId:void 0,activeReplyMessageId:void 0,toolCalls:this.state.simulator.toolCalls.map(t=>e&&t.requestId===e&&"running"===t.status?{...t,status:"cancelled",updatedAtMs:Date.now()}:t),streamStatus:"cancelled"}})}async callSimulatorTool(e){if(this.assertActive(),!this.simulatorToolExecutor)throw Error("No local simulator tool executor is configured");let t=e.toolName.trim();if(!t)throw Error("toolName must be a non-empty string");let r=rS("req_tool"),n=rS("reply_tool"),a=rS("tool_call"),i=rS("trace"),s={trace_id:i,component:"web_sdk_debugger",stage:"direct_tool_call",sampled:!0},o=Date.now(),l=await this.resolveDirectToolCallServerId(t,e.serverId,s),d={requestId:r,replyMessageId:n,toolCallId:a,toolName:t,serverId:l,appKey:this.simulatorAppKey||nR(this.state.manifest.raw,this.state.manifest.appId)||void 0,arguments:e.params,argumentsJson:e.params?function(e){try{return JSON.stringify(e??{})}catch{return""}}(e.params):void 0,status:"running",createdAtMs:o,updatedAtMs:o,trace:s,timeoutMs:e.timeoutMs};this.updateSimulatorState(e=>({...e,toolCalls:[...e.toolCalls,d]})),this.appendSimulatorDebugEvent({event:"direct_tool_call_started",request_id:r,trace_id:i,tool_call_id:a,tool_name:t,server_id:l,arguments:e.params,arguments_json:d.argumentsJson});let u=Date.now(),c=await this.runSimulatorToolCall(d);return this.updateToolCall(a,{status:c.status,updatedAtMs:Date.now(),error:c.error,resultSummary:nT(c),structuredResultSummary:c.result,isMiniApp:c.miniapp&&"boolean"==typeof c.miniapp.is_mini_app?c.miniapp.is_mini_app:void 0}),this.appendSimulatorDebugEvent({event:"direct_tool_call_completed",request_id:r,trace_id:i,tool_call_id:a,tool_name:t,server_id:l,status:c.status,elapsed_ms:Date.now()-u,result:c.result,error:c.error,raw_result_text:c.raw_result_text}),c}executeSandboxToolCall(e){this.assertActive();let t=`${e.request_id}\u0000${e.tool_call.tool_call_id}`,r=this.sandboxToolCallExecutions.get(t);if(r)return r;let n=this.executeSandboxToolCallOnce(e);return this.sandboxToolCallExecutions.set(t,n),n}async submitToolResult(e,t){let r,n,a,i;this.assertActive();let s=Date.now(),o=(n=void 0===e.result?e.error?{error:e.error.message}:{}:e.result,a=e.raw_mcp_result_json,i=e.raw_result_text||tL(e.error?{error:e.error.message,detail:e.error}:n),{request_id:e.requestId,tool_call_id:e.toolCallId,server_id:e.serverId,tool_name:e.toolName,status:function(e){switch(e){case"succeeded":return"SUCCESS";case"timeout":return"TIMEOUT";case"cancelled":return"CANCELLED";case"rejected":return"REJECTED";default:return"FAILED"}}(e.status),app_key:e.appKey,result:{tool_call_id:e.toolCallId,content:i,structured_json:tL(n)},raw_result_text:i,raw_mcp_result_json:a||"",miniapp:e.miniapp,timing:e.timing,trace:{trace_id:e.trace.trace_id,component:nf,stage:"tool_report",sampled:e.trace.sampled??!0},ext:{reported_by:nf}});this.appendSimulatorDebugEvent({event:"tool_result_report_started",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,server_id:e.serverId,status:o.status,report_request:o,endpoint:this.state.simulator.endpoint});try{r=await rU({endpoint:this.state.simulator.endpoint,fetcher:this.simulatorFetcher,result:o,signal:t})}catch(r){let t=rj(r);throw this.appendSimulatorDebugEvent({event:"tool_result_report_failed",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,elapsed_ms:Date.now()-s,error:tD(r),response:t}),r}this.appendSimulatorDebugEvent({event:"tool_result_report_response_received",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,elapsed_ms:Date.now()-s,response:r});let l=function(e){let t=e.code,r=!1===e.accepted,n=void 0!==t&&0!==t&&"0"!==t;if(!r&&!n)return;let a="string"==typeof e.message&&e.message?e.message:n?`Simulator tool result rejected with code ${String(t)}`:"Simulator tool result was not accepted",i=tM(e)[0];return nw("TOOL_RESULT_REJECTED",i?`${a} (x-tt-logid: ${i})`:a,"tool_result_submit",{gateway_response:e,gateway_code:n?t:void 0,gateway_accepted:!r&&void 0,"x-tt-logid":i})}(r);if(this.appendSimulatorDebugEvent({event:"tool_result_ack",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,accepted:r.accepted,next_action:r.next_action,error:l,response:r}),l)throw l;return r}selectSimulatorCard(e){this.assertActive(),this.updateSimulatorState(t=>({...t,selectedCard:e}))}updateSimulatorWidget(e){let t;if(this.assertActive(),"string"!=typeof e.widgetInstanceId||!e.widgetInstanceId.trim())return{status:"invalid_params",message:"widgetInstanceId must be a non-empty string"};if(void 0!==e.widgetId&&("string"!=typeof e.widgetId||!e.widgetId.trim()))return{status:"invalid_params",message:"widgetId must be a non-empty string when provided"};try{t=JSON.parse(e.widgetData)}catch{return{status:"invalid_widget_data",message:"widgetData must be a JSON object"}}if(!e8(t))return{status:"invalid_widget_data",message:"widgetData must be a JSON object"};let r=r0(this.state.simulator.messages,e.widgetInstanceId,r=>({...r,widget_id:e.widgetId||r.widget_id,render_data:t}));return r.found?(this.updateSimulatorState(e=>({...e,messages:r.messages})),{status:"updated"}):{status:"not_found",message:`Widget instance ${e.widgetInstanceId} was not found`}}appendSimulatorTraceEvent(e){this.assertActive(),this.appendSimulatorDebugEvent(e)}async approveSimulatorToolCall(e){this.assertActive();let t=this.getSimulatorToolCall(e);if(!this.simulatorToolExecutor)throw Error("No local simulator tool executor is configured");if("pending_approval"!==t.status)return;let r=this.getSimulatorToolCallRun(t);if(void 0!==t.runId&&!r)return void this.cancelStaleSimulatorToolCall(t);let n={...t,status:"running",updatedAtMs:Date.now()};null==r||r.pendingApprovalToolCallIds.delete(e),this.updateToolCall(e,{status:n.status,updatedAtMs:n.updatedAtMs}),await this.executeSimulatorToolCall(n,r)}async rejectSimulatorToolCall(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Tool call rejected by user";this.assertActive();let r=this.getSimulatorToolCall(e);if("pending_approval"!==r.status)return;let n=this.getSimulatorToolCallRun(r);if(void 0!==r.runId&&!n)return void this.cancelStaleSimulatorToolCall(r);let a=this.createToolExecutorInput(r),i=nw("TOOL_EXEC_REJECTED",t),s=Date.now();null==n||n.pendingApprovalToolCallIds.delete(e);try{await this.submitExecutedToolResult(a,{status:"rejected",error:i},s,null==n?void 0:n.streamAbortController.signal),this.updateToolCall(e,{status:"rejected",updatedAtMs:Date.now(),error:i,resultSummary:t})}catch(a){if(n&&!this.isSimulatorRunCurrent(n))return void this.appendSimulatorDebugEvent({event:"tool_result_submit_skipped",request_id:r.requestId,trace_id:r.trace.trace_id,tool_call_id:r.toolCallId,tool_name:r.toolName,reason:"stale_or_cancelled_run"});let t=r8(a,"tool_result_submit");throw this.appendSimulatorDebugEvent({event:"tool_result_submit_failed",trace_id:r.trace.trace_id,tool_call_id:e,summary:tD(a)}),this.updateToolCall(e,{status:"failed",updatedAtMs:Date.now(),error:t}),a}finally{n&&this.releaseSimulatorRun(n)}}getState(){return this.state}subscribe(e){return this.assertActive(),this.listeners.add(e),()=>{this.listeners.delete(e)}}getResourceUrl(e){return(this.assertActive(),e)?e$(this.state.manifestUrl,e):null}destroy(){var e,t;if(!this.destroyed){for(let r of(this.cancelSimulatorQuery(),null==(t=this.simulatorToolExecutor)||null==(e=t.dispose)||e.call(t),nC(this.state.simulator.messages)))URL.revokeObjectURL(r);this.destroyed=!0,this.sandboxToolCallExecutions.clear(),this.listeners.clear()}}createSimulatorRun(e){return{id:this.simulatorRunSeq+=1,traceId:e,streamAbortController:new AbortController,streamDone:!1,cancelled:!1,pendingApprovalToolCallIds:new Set,toolAbortControllers:new Set}}isSimulatorRunCurrent(e){return!this.destroyed&&this.activeSimulatorRun===e&&!e.cancelled}abortSimulatorRun(e){var t;for(let r of(e.cancelled=!0,null==(t=e.onCancelledBeforeSubmission)||t.call(e),e.onCancelledBeforeSubmission=void 0,e.streamAbortController.abort(),e.toolAbortControllers))r.abort();this.activeSimulatorRun===e&&(this.activeSimulatorRun=null)}finishSimulatorStream(e){e.streamDone=!0,this.releaseSimulatorRun(e)}releaseSimulatorRun(e){this.activeSimulatorRun===e&&(e.cancelled||e.streamDone&&0===e.pendingApprovalToolCallIds.size&&0===e.toolAbortControllers.size)&&(this.activeSimulatorRun=null)}handleSimulatorEvent(e,t,r){let n="tool_call"===e.event_type;if(!this.isSimulatorRunCurrent(t)){n&&this.appendSimulatorDebugEvent({event:"tool_call_event_skipped",request_id:e.request_id,trace_id:e.trace.trace_id,tool_call_id:e.payload.tool_call_id||"",tool_name:e.payload.tool_name||"",reason:"stale_or_cancelled_run",summary:"Tool call event arrived after its simulator run was cancelled and was not executed"});return}let a=this.state.simulator.activeRequestId;if(a&&e.request_id!==a&&"ack"!==e.event_type&&"debug"!==e.event_type){if(!n&&"tool_status"!==e.event_type)return;this.appendSimulatorDebugEvent({event:"tool_call_request_id_mismatch",request_id:e.request_id,active_request_id:a,trace_id:e.trace.trace_id,tool_call_id:e.payload.tool_call_id||"",tool_name:e.payload.tool_name||"",event_type:e.event_type,summary:"Tool call event request_id differs from the acknowledged request_id"})}let{state:i,toolCall:s,cardRefresh:o,locationDirective:l}=function(e,t,r){var n,a,i,s,o,l,d,u,c,p,m,h;let g,f,v,y,_,b,w,S,x={...e,activeReplyMessageId:t.reply_message_id??e.activeReplyMessageId},I=!function(e){switch(e.event_type){case"ack":case"tool_call":case"tool_status":case"card_delta":case"content_block":case"answer_finish":case"message_finish":case"reply_finish":case"stream_error":case"trace_event":case"debug":return!0;default:return!1}}(t)?x:r7(x,(S=t.received_at_ms??Date.now(),{display:"debug"===(n=t).event_type?rW(n.payload)??{category:"debug",detail:r1(n),phase:"event",title:"Debug"}:{category:r3(n),detail:r1(n),phase:r4(n.event_type),title:r2(n)},id:t.event_id,timestamp:S,payload:(a=t,i=S,g=r3(a),f=r4(a.event_type),v={event:a.event_type,category:g,phase:f,received_at_ms:i,server_timestamp_ms:a.created_at_ms,title:r2(a),detail:r1(a),trace:a.trace},"debug"===a.event_type?{...v,event:a.payload.event||"debug",title:tU(a.payload.title||a.payload.event||"Debug Event"),summary:a.payload.summary,elapsed_ms:a.payload.elapsed_ms,redaction_level:a.payload.redaction_level}:"heartbeat"===a.event_type?{...v,server_time_ms:a.payload.server_time_ms,message:a.payload.message}:"answer_finish"===a.event_type?{...v,status:a.payload.status,finish_reason:a.payload.finish_reason,usage:a.payload.usage}:{...v,...a.payload})}));switch(t.event_type){case"ack":return{state:function(e,t,r){let n=t.payload.local_message_id,a=t.payload.query_message_id,i=t.payload.message_id,s=e8(t.payload.query_message)?t.payload.query_message:void 0,o=(null==s?void 0:s.content)||"",l=e.messages;if(n&&a){let e=l.find(e=>e.localMessageId===n);e?l=l.map(t=>t===e?{...t,messageId:a,followUpContent:r}:t):o&&(l=[...l,{messageId:a,localMessageId:n,requestId:t.request_id,traceId:t.trace.trace_id,followUpContent:r,role:"user",contentType:"text",text:o,blocks:[{blockId:`block_text_${a}`,type:"text",text:o}],status:"completed",createdAtMs:t.created_at_ms}])}return{...e,activeRequestId:t.request_id,activeReplyMessageId:i||e.activeReplyMessageId,messages:l}}(I,t,r.followUpContent)};case"message_start":return{state:(s=I,y=(o=t).payload.message_id||o.reply_message_id||rS("reply"),{...s,activeReplyMessageId:y,messages:rQ(s.messages,y,o.created_at_ms,o.request_id,o.trace.trace_id)})};case"text_delta":return{state:function(e,t){let r=t.reply_message_id??e.activeReplyMessageId;if(!r)return e;let n=t.payload.block_id||`block_text_${t.seq}`,a=t.payload.delta||"",i=t.payload.op||"append";if("append"!==i&&"replace"!==i)return e;let s=rQ(e.messages,r,t.created_at_ms,t.request_id,t.trace.trace_id);return{...e,messages:rY(s,r,e=>({...e,text:"replace"===i?a:`${e.text}${a}`,blocks:function(e,t,r,n){if(!e.find(e=>"text"===e.type&&e.blockId===t)){let a=e[e.length-1];return"append"===n&&(null==a?void 0:a.type)==="text"?e.map(e=>e===a?{...e,text:`${e.text}${r}`}:e):[...e,{blockId:t,type:"text",text:r}]}return e.map(e=>"text"===e.type&&e.blockId===t?{...e,text:"replace"===n?r:`${e.text}${r}`}:e)}(e.blocks,n,a,i)}))}}(I,t)};case"card_delta":return r9(I,t.payload,t);case"content_block":return{state:function(e,t){let r=t.reply_message_id??e.activeReplyMessageId;if(!r)return e;let n=function(e,t){for(let[r,n]of(Array.isArray(e.content_block)?e.content_block:Array.isArray(e.contentBlock)?e.contentBlock:[]).entries()){let a=function(e){if(!e8(e))return;let t=e8(e.content)?e.content:e,r=e8(t.permission_apply_block)?t.permission_apply_block:e8(t.permissionApplyBlock)?t.permissionApplyBlock:void 0;return r?("string"==typeof r.permission_data?r.permission_data:"")||("string"==typeof r.permissionData?r.permissionData:""):""}(n),i=rJ(a);if(!i)continue;let s=(e8(n)&&"string"==typeof n.block_id?n.block_id:"")||(e8(n)&&"string"==typeof n.blockId?n.blockId:"")||`permission_apply_${t.seq}_${r}`;return{blockId:s,card:{card_id:s,card_type:"permission_apply",fallback_text:"需要授权后继续",render_data:{grantingData:i,permissionData:a},title:rK(i)},op:e.op||"append"}}}(t.payload,t);if(!n||"append"!==n.op&&"replace"!==n.op)return e;let a=rQ(e.messages,r,t.created_at_ms,t.request_id,t.trace.trace_id);return{...e,messages:rY(a,r,e=>({...e,contentType:"mixed",blocks:rZ(e.blocks,n.blockId,n.card,n.op)}))}}(I,t)};case"tool_call":return function(e,t,r){let n=t.payload.tool_call_id,a=t.payload.tool_name,i=t.payload.server_id||"",s=t.payload.arguments_json||"",o=t.reply_message_id??e.activeReplyMessageId??rS("reply");if(!n||!a)return{state:r7(e,{id:rS("trace"),timestamp:Date.now(),payload:{event:"tool_call_ignored",request_id:t.request_id,trace_id:t.trace.trace_id,tool_call_id:n,tool_name:a,reason:n?"missing_tool_name":"missing_tool_call_id",tool_call_payload:t.payload,summary:"Tool call event is missing required fields and cannot be executed"}})};let l=t.payload.requires_user_approval??!1,d=l?"pending_approval":r.hasToolExecutor?"running":"pending",u={requestId:t.request_id,runId:r.runId,replyMessageId:o,toolCallId:n,toolName:a,serverId:i,appKey:t.payload.app_key,arguments:e8(t.payload.arguments)?t.payload.arguments:tj(s),argumentsJson:s,mcpHeaders:function(e){if(!e8(e))return;let t=Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1]));return Object.keys(t).length>0?t:void 0}(t.payload.headers),status:d,createdAtMs:t.created_at_ms,updatedAtMs:t.created_at_ms,trace:t.trace,requiresUserApproval:l,timeoutMs:t.payload.timeout_ms,deadlineMs:t.payload.deadline_ms},c=rY(rQ(e.messages,o,t.created_at_ms,t.request_id,t.trace.trace_id),o,e=>({...e,toolCalls:nr(e.toolCalls??[],u)})),p={...e,messages:c,toolCalls:[...e.toolCalls.filter(e=>e.toolCallId!==n),u]};return r.hasToolExecutor?{state:p,toolCall:u}:{state:r7(p,{id:rS("trace"),timestamp:Date.now(),payload:{event:"tool_executor_missing",request_id:u.requestId,trace_id:u.trace.trace_id,tool_call_id:n,tool_name:a,summary:"No local simulator tool executor is configured"}})}}(I,t,r);case"tool_status":return{state:function(e,t){let r=t.payload.tool_call_id,n=function(e){switch(e){case"SUCCESS":return"succeeded";case"FAILED":return"failed";case"RUNNING":return"running";case"TIMEOUT":return"timeout";case"CANCELLED":return"cancelled";case"REJECTED":return"rejected";default:return""}}(t.payload.status||"");if(!r||!n)return e;let a=t.payload.progress,i=t.payload.message,s=t.payload.error?r8(t.payload.error,"tool_execute"):void 0,o=nt(e,r,{status:n,updatedAtMs:t.created_at_ms,progress:a,message:i,error:s}),l=o.toolCalls.find(e=>e.toolCallId===r);return l?{...o,messages:rY(o.messages,l.replyMessageId,e=>({...e,toolCalls:nr(e.toolCalls??[],l)}))}:o}(I,t)};case"trace_event":case"debug":default:return{state:I};case"heartbeat":return{state:(l=I,d=t,{...l,lastHeartbeatMs:d.payload.server_time_ms??d.created_at_ms})};case"answer_finish":return{state:(u=I,c=t,{...u,answerFinish:{messageId:c.reply_message_id,status:c.payload.status,finishReason:c.payload.finish_reason,usage:e8(c.payload.usage)?c.payload.usage:void 0,createdAtMs:c.created_at_ms,trace:c.trace,payload:c.payload}})};case"message_finish":return{state:function(e,t){let r=t.payload.message_id||t.reply_message_id;if(!r)return e;let n=t.payload.status||"completed";return{...e,messages:rY(e.messages,r,e=>({...e,status:function(e){switch(e){case"completed":case"finished":default:return"completed";case"cancelled":case"interrupted":return"interrupted";case"failed":case"error":return"failed"}}(n)}))}}(I,t)};case"reply_finish":return{state:(p=I,b="completed"===(_=t.payload.status||"completed")||"finished"===_?"completed":"cancelled"===_?"cancelled":"error",{...p,activeRequestId:void 0,activeReplyMessageId:void 0,messages:ne(p.messages,b),streamStatus:b})};case"stream_error":return{state:(m=I,w=r8((h=t).payload.error??h.payload,h.payload.stage||"stream"),{...m,activeRequestId:void 0,error:w,messages:ne(m.messages,"error"),streamStatus:"error"})}}}(this.state.simulator,e,{followUpContent:r,hasToolExecutor:!!this.simulatorToolExecutor,runId:t.id}),d=l&&!this.receivedSimulatorLocationDirectiveCardIds.has(l.cardId)?l:void 0;if(d&&this.receivedSimulatorLocationDirectiveCardIds.add(d.cardId),this.updateSimulatorState(()=>d?{...i,locationDirective:d}:i),d?this.appendSimulatorDebugEvent({category:"card",event:"simulator_location_directive_received",card_id:d.cardId,request_id:d.requestId,source_tool_call_id:d.sourceToolCallId,tool_name:d.toolName,trace_id:e.trace.trace_id}):l&&this.appendSimulatorDebugEvent({category:"card",event:"simulator_location_directive_loop_prevented",card_id:l.cardId,reason:"duplicate_card_id",request_id:l.requestId,tool_name:l.toolName,trace_id:e.trace.trace_id}),(null==o?void 0:o.status)==="not_found"&&this.appendSimulatorDebugEvent({category:"card",event:"simulator_history_card_refresh_skipped",reason:"card_not_found",request_id:e.request_id,trace_id:e.trace.trace_id,card_id:o.cardId}),s){let e=this.withFallbackToolCallServerId(s);e.requiresUserApproval?t.pendingApprovalToolCallIds.add(e.toolCallId):this.executeSimulatorToolCall(e,t)}}async executeSandboxToolCallOnce(e){let t=e.tool_call,r=Date.now(),n={trace_id:`bridge_${e.request_id}`,component:"sandbox_bridge",stage:"calltool_execute",sampled:!0},a={appKey:t.app_key,arguments:JSON.parse(t.arguments_json),argumentsJson:t.arguments_json,createdAtMs:r,deadlineMs:t.deadline_ms,mcpHeaders:t.headers,replyMessageId:`bridge_reply_${e.request_id}`,requestId:e.request_id,serverId:t.server_id,status:"running",timeoutMs:t.timeout_ms,toolCallId:t.tool_call_id,toolName:t.tool_name,trace:n,updatedAtMs:r};this.updateSimulatorState(e=>({...e,toolCalls:[...e.toolCalls,a]})),this.appendSimulatorDebugEvent({event:"sandbox_tool_call_started",request_id:a.requestId,trace_id:n.trace_id,tool_call_id:a.toolCallId,app_key:a.appKey,server_id:a.serverId,tool_name:a.toolName,arguments_json:a.argumentsJson,deadline_ms:a.deadlineMs,timeout_ms:a.timeoutMs});let i=Date.now(),s=t.deadline_ms<=i?{status:"timeout",error:nw("TOOL_EXEC_TIMEOUT","Sandbox tool call deadline has expired")}:await this.runSimulatorToolCall(a),o=this.createToolExecutorInput(a);try{await this.submitSandboxToolResultWithRetry(o,s,i)}catch(t){let e=r8(t,"tool_result_submit");throw this.updateToolCall(a.toolCallId,{error:e,resultSummary:e.message,status:"failed",updatedAtMs:Date.now()}),t}return this.updateToolCall(a.toolCallId,{error:s.error,isMiniApp:s.miniapp&&"boolean"==typeof s.miniapp.is_mini_app?s.miniapp.is_mini_app:void 0,resultSummary:nT(s),status:s.status,structuredResultSummary:s.result,updatedAtMs:Date.now()}),this.appendSimulatorDebugEvent({event:"sandbox_tool_call_reported",request_id:a.requestId,trace_id:n.trace_id,tool_call_id:a.toolCallId,app_key:a.appKey,server_id:a.serverId,tool_name:a.toolName,status:s.status,elapsed_ms:Date.now()-i,raw_mcp_result_json:s.raw_mcp_result_json}),{reported:!0,requestId:a.requestId,toolCallId:a.toolCallId}}withFallbackToolCallServerId(e){var t,r;if(e.serverId)return e;let n=this.lastResolvedSimulatorMcpServers,a=(null==(t=n.find(t=>t.tools.some(t=>t.name===e.toolName)))?void 0:t.server_id)||(null==(r=n[0])?void 0:r.server_id)||"local_mcp";return this.appendSimulatorDebugEvent({event:"tool_call_server_id_fallback",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,server_id:a,summary:"Tool call event has no server_id; falling back to a locally resolved MCP server"}),this.updateToolCall(e.toolCallId,{serverId:a}),{...e,serverId:a}}async runSimulatorToolCall(e,t){if(!this.simulatorToolExecutor){let e=nw("TOOL_EXECUTOR_UNAVAILABLE","No local simulator tool executor is configured");return{error:e,result:{error:e.message},status:"failed"}}try{return await nS({executor:this.simulatorToolExecutor,input:this.createToolExecutorInput(e),record:e,signal:t})}catch(t){let e=r8(t,"tool_execute");return{status:"TOOL_EXEC_TIMEOUT"===e.code?"timeout":"TOOL_EXEC_CANCELLED"===e.code||r5(t)?"cancelled":"failed",error:e}}}async executeSimulatorToolCall(e,t){if(t&&!this.isSimulatorRunCurrent(t))return;let r=Date.now(),n=this.createToolExecutorInput(e),a=t?new AbortController:void 0;t&&a&&t.toolAbortControllers.add(a);let i=await this.runSimulatorToolCall(e,null==a?void 0:a.signal);try{if(t&&!this.isSimulatorRunCurrent(t))return void this.appendSimulatorDebugEvent({event:"tool_result_submit_skipped",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,reason:"stale_or_cancelled_run"});if(await this.submitExecutedToolResult(n,i,r,null==a?void 0:a.signal),t&&!this.isSimulatorRunCurrent(t))return;this.updateToolCall(e.toolCallId,{status:i.status,updatedAtMs:Date.now(),error:i.error,resultSummary:nT(i),structuredResultSummary:i.result,isMiniApp:i.miniapp&&"boolean"==typeof i.miniapp.is_mini_app?i.miniapp.is_mini_app:void 0})}catch(n){if(t&&!this.isSimulatorRunCurrent(t))return void this.appendSimulatorDebugEvent({event:"tool_result_submit_skipped",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,reason:"stale_or_cancelled_run"});let r=r8(n,"tool_result_submit");this.appendSimulatorDebugEvent({event:"tool_result_submit_failed",trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,summary:tD(n),error:r}),this.updateToolCall(e.toolCallId,{status:"failed",updatedAtMs:Date.now(),error:r}),this.failActiveSimulatorStream(r)}finally{t&&a&&(t.toolAbortControllers.delete(a),this.releaseSimulatorRun(t))}}uploadSimulatorImage(e,t){return this.assertActive(),rD({endpoint:this.state.simulator.endpoint,fetcher:this.simulatorFetcher,file:e,signal:t})}createToolExecutorInput(e){let t={trace_id:e.trace.trace_id,span_id:rS("span_tool_execute"),parent_span_id:e.trace.span_id,component:"local_mcp",stage:"tool_execute",sampled:e.trace.sampled};return{requestId:e.requestId,replyMessageId:e.replyMessageId,toolCallId:e.toolCallId,toolName:e.toolName,serverId:e.serverId,appKey:e.appKey||this.simulatorAppKey||nR(this.state.manifest.raw,this.state.manifest.appId)||void 0,arguments:e.arguments,argumentsJson:e.argumentsJson,headers:e.mcpHeaders,manifest:this.state.manifest.raw,timeoutMs:e.timeoutMs,deadlineMs:e.deadlineMs,trace:t}}async resolveSimulatorManifestForQuery(e,t,r,n){let a=Date.now(),i=void 0!==t.manifest,s=i?"query_option":void 0===this.simulatorManifest?"loaded_manifest":"debugger_option";this.appendSimulatorDebugEvent({event:"simulator_manifest_load_started",trace_id:e,source:s});try{let o=i?{found:!1,value:void 0}:this.takeSimulatorManifestStateValue(),l=i?t.manifest:o.found?o.value:"function"==typeof this.simulatorManifest?await this.simulatorManifest(n):this.simulatorManifest,d=l?nA(r,l):r;return this.appendSimulatorDebugEvent({event:"simulator_manifest_loaded",trace_id:e,elapsed_ms:Date.now()-a,source:s,manifest:d}),d}catch(t){return n.throwIfAborted(),this.appendSimulatorDebugEvent({event:"simulator_manifest_load_failed",trace_id:e,elapsed_ms:Date.now()-a,error:tD(t),source:s}),r}}async resolveSimulatorSkillsForQuery(e,t,r){let n=Date.now(),a=void 0===t.skills?"debugger_option":"query_option";this.appendSimulatorDebugEvent({event:"simulator_skill_load_started",trace_id:e,source:a});try{let i=t.skills??("function"==typeof this.simulatorSkills?await this.simulatorSkills(r):this.simulatorSkills)??[];return this.appendSimulatorDebugEvent({event:i.length>0?"simulator_skill_loaded":"simulator_skill_empty",trace_id:e,elapsed_ms:Date.now()-n,skills_length:i.reduce((e,t)=>e+t.content.length,0),skill_paths:i.map(e=>e.relativePath),source:a}),i}catch(t){return null==r||r.throwIfAborted(),this.appendSimulatorDebugEvent({event:"simulator_skill_load_failed",trace_id:e,elapsed_ms:Date.now()-n,error:tD(t),source:a}),[]}}async resolveDirectToolCallServerId(e,t,r){var n;let a=null==t?void 0:t.trim();if(a)return a;let i=this.state.manifest.raw,s=this.simulatorAppKey||nR(i,this.state.manifest.appId),o=this.simulatorAppName||nM(i,this.state.manifest.name),l=this.simulatorMcpServerProvider?await this.simulatorMcpServerProvider({trace:r,appKey:s,appName:o,manifest:i}):this.simulatorMcpServers,d=l.find(t=>t.tools.some(t=>t.name===e));return(null==d?void 0:d.server_id)??(null==(n=l[0])?void 0:n.server_id)??"local_mcp"}getSimulatorToolCall(e){let t=this.state.simulator.toolCalls.find(t=>t.toolCallId===e);if(!t)throw Error(`Unknown simulator tool call: ${e}`);return t}getSimulatorToolCallRun(e){let t=this.activeSimulatorRun;if(t&&this.isSimulatorRunCurrent(t))return void 0===e.runId||e.runId===t.id?t:void 0}cancelStaleSimulatorToolCall(e){let t=nw("TOOL_EXEC_CANCELLED","Tool call cancelled because its simulator run is no longer active");this.appendSimulatorDebugEvent({event:"tool_result_submit_skipped",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,reason:"stale_or_cancelled_run"}),this.updateToolCall(e.toolCallId,{status:"cancelled",updatedAtMs:Date.now(),error:t,resultSummary:t.message})}async submitSandboxToolResultWithRetry(e,t,r){let n;for(let a=1;a<=2;a+=1)try{await this.submitExecutedToolResult(e,t,r,void 0,a);return}catch(t){if(n=t,2===a||void 0!==e.deadlineMs&&Date.now()>=e.deadlineMs)throw t;this.appendSimulatorDebugEvent({event:"sandbox_tool_result_report_retry",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,attempt:a+1,error:tD(t)})}throw n}async submitExecutedToolResult(e,t,r,n){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1,i=Date.now();await this.submitToolResult({...e,...t,timing:{started_at_ms:r,ended_at_ms:i,duration_ms:i-r,attempt:a}},n)}updateToolCall(e,t){this.updateSimulatorState(r=>nt(r,e,t))}failActiveSimulatorStream(e){this.activeSimulatorRun&&this.abortSimulatorRun(this.activeSimulatorRun),this.updateSimulatorState(t=>({...t,activeRequestId:void 0,activeReplyMessageId:void 0,error:e,messages:t.messages.map(e=>"assistant"===e.role&&"streaming"===e.status?{...e,status:"failed"}:e),streamStatus:"error"}))}getSimulatorQueryFailureDiagnosis(e,t){let r=new Set;for(let t of this.state.simulator.traceEvents){let n=t.payload,a=nE["string"==typeof n.event?n.event:""];a&&function(e){var t;return e.trace_id||(null==(t=e.trace)?void 0:t.trace_id)||""}(n)===e&&"Failed to fetch"===(n.error||"")&&r.add(a)}if(r.size>=3)return{code:"DEBUG_SERVER_UNREACHABLE",confidence:"high",failed_services:[...r],summary:"调试 Dev Server 或本机网络不可达",suggestion:"检查调试 Dev Server 是否运行,以及浏览器能否访问当前调试端口。"};let n=rj(t),a="number"==typeof(null==n?void 0:n.status)?n.status:void 0;return 404===a?{code:"SIMULATOR_ENDPOINT_NOT_FOUND",confidence:"high",status:a,summary:"模拟器接口未配置或路由不存在",suggestion:"检查 simulator、manifest、skill 或 MCP 的接口地址与代理路由。"}:void 0!==a&&a>=500?{code:"SIMULATOR_ENDPOINT_SERVER_ERROR",confidence:"high",status:a,summary:`模拟器接口服务异常(HTTP ${a})`,suggestion:"接口已可达,但服务端或其上游依赖异常;请查看响应内容和服务端日志。"}:"Failed to fetch"===tD(t)?{code:"SIMULATOR_ENDPOINT_UNREACHABLE",confidence:"unknown",summary:"无法连接模拟器接口",suggestion:"可能是接口服务未启动、端口不可达、浏览器网络异常或 CORS 被拦截。"}:void 0}appendSimulatorDebugEvent(e){let t=tM(e),r={display:rW(e),id:rS("trace"),timestamp:Date.now(),payload:function(e,t){if(!e8(e))return{};let r=rH(e);return{...e,category:r.category,detail:r.detail,phase:r.phase,title:r.title,log_ids:t.length>0?t:void 0}}(e,t)};this.updateSimulatorState(e=>{var t;return{...e,traceEvents:[...e.traceEvents,{...r,order:((null==(t=e.traceEvents.at(-1))?void 0:t.order)??e.traceEvents.length)+1}].slice(-200)}})}updateSimulatorState(e){this.setState({...this.state,simulator:e(this.state.simulator)})}setState(e){for(let t of(this.state=e,this.listeners))t(this.state)}assertActive(){if(this.destroyed)throw Error("WebSdkDebugger has been destroyed")}}let nj="iphone-13",nL=[{key:nj,label:"iPhone 13",width:390,height:844,density:3,radius:47,homeIndicator:!0,statusBarHeight:47,safeArea:{top:47,bottom:34,left:0,right:0}},{key:"iphone-17-pro-max",label:"iPhone 17 Pro Max",width:440,height:956,density:3,radius:55,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-17-pro",label:"iPhone 17 Pro",width:402,height:874,density:3,radius:50,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-17",label:"iPhone 17",width:402,height:874,density:3,radius:50,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-air",label:"iPhone Air",width:420,height:912,density:3,radius:52,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16-pro-max",label:"iPhone 16 Pro Max",width:440,height:956,density:3,radius:55,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16-pro",label:"iPhone 16 Pro",width:402,height:874,density:3,radius:50,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16-plus",label:"iPhone 16 Plus",width:430,height:932,density:3,radius:55,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16",label:"iPhone 16",width:393,height:852,density:3,radius:47,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-16e",label:"iPhone 16e",width:390,height:844,density:3,radius:44,homeIndicator:!0,statusBarHeight:47,safeArea:{top:47,bottom:34,left:0,right:0}},{key:"iphone-15-pro-max",label:"iPhone 15 Pro Max",width:430,height:932,density:3,radius:55,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-15",label:"iPhone 15",width:393,height:852,density:3,radius:47,homeIndicator:!0,statusBarHeight:59,safeArea:{top:59,bottom:34,left:0,right:0}},{key:"iphone-14-plus",label:"iPhone 14 Plus",width:428,height:926,density:3,radius:47,homeIndicator:!0,statusBarHeight:47,safeArea:{top:47,bottom:34,left:0,right:0}},{key:"iphone-13-mini",label:"iPhone 13 mini",width:375,height:812,density:3,radius:44,homeIndicator:!0,statusBarHeight:50,safeArea:{top:50,bottom:34,left:0,right:0}},{key:"iphone-se",label:"iPhone SE",width:375,height:667,density:2,radius:0,homeIndicator:!1,statusBarHeight:20,safeArea:{top:20,bottom:0,left:0,right:0}},{key:"pixel-8-pro",label:"Pixel 8 Pro",width:448,height:998,density:3,radius:30,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"pixel-8",label:"Pixel 8",width:412,height:915,density:2.625,radius:28,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"pixel-7",label:"Pixel 7",width:412,height:915,density:2.625,radius:28,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"galaxy-s24",label:"Galaxy S24",width:360,height:780,density:3,radius:32,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"galaxy-s24-ultra",label:"Galaxy S24 Ultra",width:384,height:854,density:3.75,radius:18,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"galaxy-z-fold-5-cover",label:"Galaxy Z Fold 5 Cover",width:344,height:882,density:3,radius:30,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"galaxy-z-fold-5-inner",label:"Galaxy Z Fold 5 Inner",width:690,height:829,density:2.625,radius:24,homeIndicator:!1,statusBarHeight:24,safeArea:{top:24,bottom:0,left:0,right:0}},{key:"ipad-mini",label:"iPad mini",width:744,height:1133,density:2,radius:18,homeIndicator:!0,statusBarHeight:24,safeArea:{top:24,bottom:20,left:0,right:0}},{key:"ipad-pro-11",label:'iPad Pro 11"',width:834,height:1194,density:2,radius:18,homeIndicator:!0,statusBarHeight:24,safeArea:{top:24,bottom:20,left:0,right:0}}],nD=[{key:"100",label:"100%",scale:1},{key:"85",label:"85%",scale:.85},{key:"75",label:"75%",scale:.75},{key:"50",label:"50%",scale:.5},{key:"fit",label:"自适应",scale:.88}],nO={key:"mobile-393",label:"393px",width:393,density:3};function nU(e){let t=/^custom-([1-9]\d{0,3})x([1-9]\d{0,3})$/.exec(e);if(t){let r=Number(t[1]),n=Number(t[2]);return{key:e,label:`自定义 ${r} \xd7 ${n}`,width:r,height:n,density:1,radius:0,homeIndicator:!1,statusBarHeight:0,safeArea:{top:0,bottom:0,left:0,right:0}}}return nL.find(t=>t.key===e)??nL.find(e=>e.key===nj)??nL[0]}let nq="devtools_web";function n$(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nO,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return{debugger:"web-sdk",density:e.density,screenWidth:e.width,containerWidth:e.width,devicePlatform:"iOS",deviceBrand:"Apple",deviceModel:`Widget preview ${e.label}`,screenOrientation:"portrait",...t,platform:nq}}function nB(e,t){try{let e=t.trim()?JSON.parse(t):{};if(e8(e))return e;throw Error("expected a JSON object")}catch(t){throw Error(`${e}: ${t.message}`)}}function nF(e){return e??document.body}async function nW(e,t){var r;let n,a=nF(t),i=new CustomEvent("doubao:multi-media-broadcast",{bubbles:!0,composed:!0,detail:e});a.dispatchEvent(i),window.dispatchEvent(new CustomEvent("doubao:multi-media-broadcast",{detail:e}));let s=(r=e.mediaId,n=Array.from(nF(t).querySelectorAll("audio,video")),r?n.filter(e=>e.id===r||e.dataset.mediaId===r):n);return await Promise.all(s.map(t=>"play"===e.action?t.play():Promise.resolve(t.pause()))),{affected:s.length}}let nH=[],nz=new Map,nV=!1;function nG(e){for(let t of e)URL.revokeObjectURL(t),nz.delete(t)}function nJ(){for(let e of nH.splice(0))nG(e)}function nK(e){var t;let r=nz.get(e);if(r)return r;let n=e.match(/^data:image\/([^;,]+)/i);if(null==n?void 0:n[1])return n[1].split("+")[0].toLowerCase();let a=e.match(/\.([a-zA-Z0-9]+)(?:[?#].*)?$/);return(null==a||null==(t=a[1])?void 0:t.toLowerCase())??""}function nX(e){return new Promise((t,r)=>{let n=new Image;n.onload=()=>t(n),n.onerror=()=>r(Error(`failed to load image: ${e}`)),n.src=e})}async function nQ(e){if("string"!=typeof e.src||!e.src)throw Error("src must be a non-empty string");let t=await nX(e.src);return{width:t.naturalWidth||t.width,height:t.naturalHeight||t.height,orientation:"up",path:e.src,type:nK(e.src)}}async function nY(e){if("string"!=typeof e.src||!e.src)throw Error("src must be a non-empty string");let t=await nX(e.src),r=document.createElement("canvas"),n=e.compressedWidth??t.naturalWidth??t.width,a=e.compressedHeight??t.naturalHeight??t.height;r.width=n,r.height=a;let i=r.getContext("2d");if(!i)throw Error("canvas 2d context is not available");return i.drawImage(t,0,0,n,a),{tempFilePath:r.toDataURL("image/jpeg",Math.min(100,Math.max(0,e.quality??80))/100)}}let nZ={enableHighAccuracy:!0,maximumAge:0,timeout:1e4};function n0(){return{browserAuthorization:"unknown",message:"未配置",tone:"muted",userAuthorization:"unknown"}}function n1(e){let{longitude:t,latitude:r}=e;if(!Number.isFinite(t)||!Number.isFinite(r)||t<-180||t>180||r<-90||r>90)throw Error("Invalid location coordinates")}class n2{browserAuthorization="unknown";browserLocation;browserWatchId;locationListeners=new Set;manualLocation;pendingBrowserRequest;revision=0;snapshot=n0();snapshotListeners=new Set;updatesActive=!1;userAuthorization="unknown";watchRevision=0;getSnapshot=()=>this.snapshot;subscribe=e=>(this.snapshotListeners.add(e),()=>this.snapshotListeners.delete(e));subscribeLocation=e=>(this.locationListeners.add(e),()=>this.locationListeners.delete(e));isLocationScope(e){return"scope.userLocation"===e||"scope.userFuzzyLocation"===e||"scope.userLocationBackground"===e}updateUserAuthorization(e){this.userAuthorization=e?"granted":"denied",this.updateSnapshot({userAuthorization:this.userAuthorization}),!e&&this.updatesActive&&(this.stopLocationUpdates(),this.emitLocation({status:"user_unauthorized"}))}async requestLocation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nZ;if("granted"!==this.userAuthorization)return{status:"user_unauthorized"};let t=this.getConfiguredLocation();return t||("denied"===this.browserAuthorization?this.createBrowserUnauthorizedResult():this.locateWithBrowser(e))}async requestLocationForHostDirective(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nZ;return this.getConfiguredLocation()??this.locateWithBrowser(e)}async requestBrowserLocation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nZ;return this.manualLocation=void 0,this.locateWithBrowser(e)}setManualLocation(e){n1(e),this.revision+=1,this.pendingBrowserRequest=void 0,this.clearBrowserWatch(),this.manualLocation={...e,accuracy:0,source:"manual",speed:0,timestamp:Date.now()},this.browserAuthorization="granted",this.updateSnapshot({...e,browserAuthorization:"granted",errorMessage:void 0,message:"已配置(手动坐标)",source:"manual",tone:"success",updatedAtMs:Date.now()}),this.updatesActive&&this.emitLocation({location:this.manualLocation,status:"success"})}setConfigurationError(e){this.updateSnapshot({errorMessage:e,message:"定位失败",tone:"error",updatedAtMs:Date.now()})}async startLocationUpdates(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nZ,t=await this.requestLocation(e);return"success"!==t.status?this.emitLocation(t):(this.updatesActive=!0,this.emitLocation(t),"browser"===t.location.source&&this.startBrowserWatch(e)),t}stopLocationUpdates(){this.updatesActive=!1,this.clearBrowserWatch()}createBusinessLocationInfo(e){let t=function(){try{return new Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{return""}}();return{latitude:e.latitude,longitude:e.longitude,city:"",city_code:"",client_time_zone:t,country:"",country_code:"",district:"",impr_time:String(Math.floor(Date.now()/1e3)),province:"",region:"",time_zone:t,town:""}}reset(){this.revision+=1,this.stopLocationUpdates(),this.browserAuthorization="unknown",this.browserLocation=void 0,this.manualLocation=void 0,this.pendingBrowserRequest=void 0,this.userAuthorization="unknown",this.snapshot=n0(),this.emitSnapshot()}getConfiguredLocation(){return this.manualLocation?{location:{...this.manualLocation,timestamp:Date.now()},status:"success"}:"granted"===this.browserAuthorization&&this.browserLocation?{location:this.browserLocation,status:"success"}:void 0}locateWithBrowser(e){if(this.pendingBrowserRequest)return this.pendingBrowserRequest;let t=++this.revision;this.browserAuthorization="pending",this.updateSnapshot({browserAuthorization:"pending",errorMessage:void 0,latitude:void 0,longitude:void 0,message:"定位中...",source:void 0,tone:"pending",updatedAtMs:Date.now()});let r=this.getBrowserPosition(e).then(e=>{let r=this.toBrowserLocation(e);return t===this.revision&&(this.browserAuthorization="granted",this.browserLocation=r,this.updateSnapshot({browserAuthorization:"granted",errorMessage:void 0,latitude:r.latitude,longitude:r.longitude,message:"已配置(浏览器定位)",source:"browser",tone:"success",updatedAtMs:Date.now()})),{location:r,status:"success"}}).catch(e=>this.handleBrowserError(e,t)).finally(()=>{this.pendingBrowserRequest===r&&(this.pendingBrowserRequest=void 0)});return this.pendingBrowserRequest=r,r}getBrowserPosition(e){let t="u"<typeof navigator?void 0:navigator.geolocation;return t?new Promise((r,n)=>{t.getCurrentPosition(r,n,e)}):Promise.reject(Error("Geolocation is not available in the current browser"))}toBrowserLocation(e){return{...function(e,t){var r,n,a,i;if(n1({latitude:t,longitude:e}),e<72.004||e>137.8347||t<.8293||t>55.8271)return{latitude:t,longitude:e};let s=-100+2*(r=e-105)+3*(n=t-35)+.2*n*n+.1*r*n+.2*Math.sqrt(Math.abs(r))+(20*Math.sin(6*r*Math.PI)+20*Math.sin(2*r*Math.PI))*2/3+(20*Math.sin(n*Math.PI)+40*Math.sin(n/3*Math.PI))*2/3+(160*Math.sin(n/12*Math.PI)+320*Math.sin(n*Math.PI/30))*2/3,o=300+(a=e-105)+2*(i=t-35)+.1*a*a+.1*a*i+.1*Math.sqrt(Math.abs(a))+(20*Math.sin(6*a*Math.PI)+20*Math.sin(2*a*Math.PI))*2/3+(20*Math.sin(a*Math.PI)+40*Math.sin(a/3*Math.PI))*2/3+(150*Math.sin(a/12*Math.PI)+300*Math.sin(a/30*Math.PI))*2/3,l=t/180*Math.PI,d=Math.sin(l),u=Math.sqrt(d=1-.006693421622965943*d*d);return{latitude:t+(s=180*s/(6335552.717000426/(d*u)*Math.PI)),longitude:e+(o=180*o/(6378245/u*Math.cos(l)*Math.PI))}}(e.coords.longitude,e.coords.latitude),accuracy:e.coords.accuracy??0,altitude:e.coords.altitude??void 0,altitudeAccuracy:e.coords.altitudeAccuracy??void 0,heading:e.coords.heading??void 0,source:"browser",speed:e.coords.speed??0,timestamp:e.timestamp||Date.now()}}handleBrowserError(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.revision,r=e&&"object"==typeof e&&"code"in e&&"number"==typeof e.code?e.code:void 0,n=1===r?"denied":"unknown",a=function(e){switch(e&&"object"==typeof e&&"code"in e&&"number"==typeof e.code?e.code:void 0){case 1:return"浏览器定位权限被拒绝,请在浏览器设置中允许位置访问后重试";case 2:return"暂时无法获取浏览器位置,请检查设备定位服务后重试";case 3:return"获取浏览器位置超时,请重试";default:return e instanceof Error&&e.message.includes("not available")?"当前浏览器不支持定位,请手动配置坐标":"获取浏览器位置失败,请重试"}}(e);return console.error("Browser geolocation failed",e),t===this.revision&&(this.browserAuthorization=n,this.browserLocation=void 0,this.updateSnapshot({browserAuthorization:n,errorMessage:a,latitude:void 0,longitude:void 0,message:"定位失败",source:void 0,tone:"error",updatedAtMs:Date.now()})),{code:r,message:a,status:"browser_unauthorized"}}createBrowserUnauthorizedResult(){return{message:this.snapshot.errorMessage||"浏览器未授权定位,请在 Sandbox 面板配置位置",status:"browser_unauthorized"}}startBrowserWatch(e){this.clearBrowserWatch();let t=++this.watchRevision,r="u"<typeof navigator?void 0:navigator.geolocation;r?this.browserWatchId=r.watchPosition(e=>{if(t!==this.watchRevision||!this.updatesActive)return;let r=this.toBrowserLocation(e);this.browserAuthorization="granted",this.browserLocation=r,this.updateSnapshot({browserAuthorization:"granted",errorMessage:void 0,latitude:r.latitude,longitude:r.longitude,message:"已配置(浏览器定位)",source:"browser",tone:"success",updatedAtMs:Date.now()}),this.emitLocation({location:r,status:"success"})},e=>{t===this.watchRevision&&this.updatesActive&&this.emitLocation(this.handleBrowserError(e))},e):this.emitLocation(this.handleBrowserError(Error("Geolocation is not available in the current browser")))}clearBrowserWatch(){if(this.watchRevision+=1,void 0===this.browserWatchId)return;let e="u"<typeof navigator?void 0:navigator.geolocation;null==e||e.clearWatch(this.browserWatchId),this.browserWatchId=void 0}updateSnapshot(e){this.snapshot={...this.snapshot,...e,browserAuthorization:this.browserAuthorization,userAuthorization:this.userAuthorization},this.emitSnapshot()}emitSnapshot(){for(let e of this.snapshotListeners)e()}emitLocation(e){for(let t of this.locationListeners)t(e)}}let n3=new n2,n4=new Map,n5={"scope.userLocation":{description:"将使用你的位置信息,用于提供定位及位置相关服务。",title:"申请获取你的位置信息"},"scope.userFuzzyLocation":{description:"将使用你的大致位置信息,用于提供位置相关服务。",title:"申请获取你的模糊位置信息"},"scope.userLocationBackground":{description:"将在智能服务进入后台后继续使用你的位置信息。",title:"申请获取你的后台位置信息"},"scope.record":{description:"将使用你的麦克风,用于录制音频内容或进行语音输入。",title:"申请获取你的麦克风权限"},"scope.bluetooth":{description:"将使用你的蓝牙,用于发现和连接附近设备。",title:"申请获取你的蓝牙权限"},"scope.camera":{description:"将使用你的相机,用于拍摄照片或视频。",title:"申请获取你的相机权限"},"scope.addPhoneContact":{description:"将使用你的通讯录,用于添加或更新联系人。",title:"申请获取你的通讯录读写权限"},"scope.addPhoneCalendar":{description:"将使用你的日历,用于添加或更新日程。",title:"申请获取你的日历读写权限"}};function n8(e,t){return`${e||"unknown-app"}:${t}`}function n6(e){return n5[e]??{description:"需要获得你的授权后才能继续使用此功能。",title:`申请获取你的${e.replace(/^scope\./,"")||"相关"}权限`}}async function n7(e){var t;let{appId:r,appIcon:n,appName:a,presenter:i,scope:s,skipDialogIfDenied:o=!1}=e,l=r||"unknown-app",d=n4.get(n8(l,s));if("granted"===d)return!0;if("denied"===d&&o)return!1;if(!i)return"denied"!==d;let u=await i({appId:l,appIcon:n,appName:a||"智能服务",scope:s,...n6(s)});return t=u?"granted":"denied",n4.set(n8(l,s),t),u}let n9="location_api_not_implemented";function ae(e,t){return c(e,"user_unauthorized"===t.status?"user permission denied":t.message)}async function at(e){let t=await n7({appId:e.appId,appIcon:e.appIcon,appName:e.appName,presenter:e.showSimulatorPermission,scope:"scope.userLocation",skipDialogIfDenied:!0});return n3.updateUserAuthorization(t),t}function ar(e){let t={};return e.forEach((e,r)=>{t[r]=e}),t}function an(e){let t=(e.method??"GET").toUpperCase(),r=new Headers(e.header??{"content-type":"application/json"});return{body:"GET"!==t&&"HEAD"!==t?function(e,t){var r;if(null==e)return;if("string"==typeof e||e instanceof ArrayBuffer)return e;let n=(null==(r=t.get("content-type"))?void 0:r.toLowerCase())??"";if(n.includes("application/x-www-form-urlencoded")&&"object"==typeof e){let t=new URLSearchParams;return Object.entries(e).forEach(e=>{let[r,n]=e;t.set(r,String(n))}),t.toString()}return n.includes("application/json")||"object"==typeof e?JSON.stringify(e):String(e)}(e.data,r):void 0,headers:ar(r),method:t,url:"string"==typeof e.url?e.url:""}}async function aa(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:an(e);if(!e.url)throw Error("url must be a non-empty string");let r=await fetch(e.url,{body:t.body,headers:t.headers,method:t.method}),n=e.dataType??"json",a="arraybuffer"===n?await r.arrayBuffer():await r.text().then(e=>"string"===n||0===e.length?e:JSON.parse(e));return{statusCode:r.status,header:ar(r.headers),data:a}}let ai=new Set,as=new WeakSet,ao=0;function al(){return navigator.connection}function ad(){var e;let t,r=al(),n=null==r?void 0:r.effectiveType;return{isConnected:!1!==navigator.onLine,networkType:(t=null==(e=al())?void 0:e.effectiveType,!1===navigator.onLine?"none":"slow-2g"===t||"2g"===t?"2g":"3g"===t||"4g"===t?t:"unknown"),signalStrength:null==r?void 0:r.downlink,hasSystemProxy:!1,weakNet:"slow-2g"===n||"2g"===n}}function au(){return{timestamp:performance.now()/1e3,wallTime:Date.now()/1e3}}function ac(e){for(let t of ai)try{t(e)}catch(e){console.error("Failed to record doubao.request in Chrome DevTools",e)}}function ap(){let e=ad();return{networkType:e.networkType,signalStrength:e.signalStrength,hasSystemProxy:e.hasSystemProxy??!1,weakNet:e.weakNet??!1}}async function am(e,t,r){let n=await n7({appId:e.appId,appIcon:e.appIcon,appName:e.appName,presenter:e.showSimulatorPermission,scope:t,skipDialogIfDenied:r});return n3.isLocationScope(t)&&n3.updateUserAuthorization(n),n}let ah="app_id_missing",ag="cashier_unavailable",af="create_order_failed",av="developer_order_exists",ay="login_credential_invalid",a_="login_credential_missing",ab="login_authorization_failed",aw="login_authorization_unsupported",aS="login_state_invalid",ax="login_session_unavailable",aI="payment_amount_invalid",aE="payment_authorization_invalid",aC="payment_cancelled",ak="payment_data_invalid",aN="payment_data_missing",aT="payment_data_unavailable",aR="payment_data_unavailable_with_sign",aM="payment_data_unsupported",aA="payment_failed",aP="payment_method_unavailable",aj="payment_order_invalid",aL="payment_parameter_missing",aD="payment_params_invalid",aO="payment_params_unavailable",aU="payment_sign_params_invalid",aq="payment_sign_params_unavailable",a$="payment_incomplete",aB="privacy_state_unavailable",aF="privacy_authorization_failed",aW="pre_order_failed",aH="phone_authorization_failed",az="request_format_invalid",aV="request_params_invalid",aG="sandbox_resource_not_found",aJ="sandbox_service_unavailable",aK="sandbox_session_expired",aX="sandbox_session_forbidden",aQ="sign_order_failed",aY="sign_order_already_exists",aZ="sign_order_not_found",a0="sign_order_params_invalid",a1="sign_order_status_invalid",a2="sign_order_create_failed",a3="sign_page_params_invalid",a4="sign_page_unavailable",a5="sign_page_data_unavailable",a8="请求暂时无法完成,请稍后重试;如持续失败,请提供 log_id";function a6(e,t){return!t||e.includes(t)?e:`${e}(log_id: ${t})`}class a7 extends Error{code;details;logId;constructor(e,t={},r){super(ia(e,t,r)),this.code=e,this.details=t,this.logId=r,this.name="SandboxError"}}class a9 extends Error{remoteCode;options;constructor(e,t,r={}){super(t),this.remoteCode=e,this.options=r,this.name="SandboxRemoteError"}}let ie={[ah]:"当前未配置应用 ID,请先完成应用配置。",[ag]:"无法打开模拟器收银台,请刷新模拟器后重试。",[af]:"暂时无法创建订单,请检查签名参数后稍后重试;如持续失败,请提供 log_id",[av]:"开发者订单号已存在,请查询原订单",[ay]:"登录失败:登录凭证已过期或已使用,请重新发起登录。",[a_]:"登录失败:成功登录回调未携带业务登录凭证,请检查登录实现。",[ab]:"暂时无法完成登录授权,请重新发起授权",[aw]:"当前 Sandbox 无法完成该授权请求,请检查授权方式和会话配置",[aS]:"用户登录状态已失效,请重新登录",[ax]:"登录失败:模拟器会话不可用,请登录开发者账号后重新打开模拟器。",[aI]:"支付金额无效,请使用最小货币单位的整数,并由业务服务端生成金额。",[aE]:"支付授权校验失败,请确认 data 和 dbAuthorization 使用同一个 dev.key 生成,并且模拟器配置了匹配的 dev.csr。",[aC]:"已取消支付。",[ak]:"支付数据格式无效,请检查业务服务端生成的 pay_data。",[aT]:"无法打开收银台:模拟器未返回支付数据,请检查订单状态和预下单响应。",[aR]:"无法打开支付签约收银台:模拟器未返回支付数据,请检查签约参数和订单状态。",[aM]:"当前支付数据不支持模拟器收银台,请检查模拟器支付配置。",[aA]:a8,[aP]:"支付数据中没有可用的支付方式,请检查模拟器支付配置。",[aj]:"订单不存在或不属于当前应用",[aD]:"请求参数不正确,请检查订单信息和金额",[aO]:"暂时无法获取支付参数,请检查订单号后重试;如持续失败,请提供 log_id",[aU]:"请求参数不正确,请检查订单号和签约信息",[aq]:"暂时无法获取支付参数,请稍后重试;如持续失败,请提供 log_id",[a$]:"模拟支付未完成,请检查支付方式和订单状态后重试;如持续失败,请提供 log_id",[aB]:"暂时无法读取或保存授权状态,请稍后重试",[aF]:"隐私授权失败:请刷新模拟器后重试。",[aW]:"预下单失败:模拟器未返回订单 ID,请检查业务服务端预下单响应。",[aH]:"手机号授权失败:无法获取手机号授权凭证,请重试或使用其他登录方式。",[az]:"请求格式不正确,请检查后重试",[aV]:"请求参数不正确,请检查必填字段和字段格式",[aG]:"未找到沙箱会话或相关资源,请重新创建后重试",[aJ]:"沙箱服务暂时不可用,请稍后重试;如持续失败,请提供 log_id",[aK]:"沙箱会话已过期,请重新启动调试会话",[aX]:"当前沙箱会话无权访问该应用,请检查应用和会话是否匹配",[aQ]:"创建签约订单失败:模拟器未返回签约订单 ID,请检查签约参数。",[aY]:"开发者签约单号已存在,请查询原签约单",[aZ]:"签约单不存在或不属于当前应用",[a0]:"签约单参数无效,请检查单号、应用和有效期",[a1]:"当前签约单状态不允许继续签约",[a2]:"暂时无法创建签约单,请检查签名参数后重试;如持续失败,请提供 log_id",[a3]:"签约单参数无效,请检查单号、应用和有效期",[a4]:"暂时无法获取签约页,请稍后重试;如持续失败,请提供 log_id",[a5]:"打开签约页面失败:模拟器未返回签约数据,请检查签约订单状态。"},it={id:"支付方式 ID",name:"支付方式名称",pay_order_no:"支付订单号",pay_status:"支付状态",trade_no:"交易号"},ir={data:"业务服务端生成的 data",dbAuthorization:"业务服务端生成的 dbAuthorization",orderId:"requestOrder 返回的 orderId",signData:"业务服务端生成的 signData",signDbAuthorization:"业务服务端生成的 signDbAuthorization"};function ia(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;return a6(function(e,t){if(e===aN){let e=t.field?it[t.field]:"必要字段";return`支付数据缺少${e},请检查业务服务端生成的 pay_data。`}if(e===aL){let e=t.key?ir[t.key]:"该参数";return`缺少支付参数,请提供${e}。`}return ie[e]}(e,t),r)}function ii(e){if("number"==typeof e&&Number.isInteger(e))return e;if("string"==typeof e&&e.trim()){let t=Number(e);return Number.isInteger(t)?t:void 0}}let is={400:aV,401:aK,403:aX,404:aG,500:aJ};function io(e,t){return 400===t?az:void 0===e?void 0:is[e]}let il={[aR]:aU,[aQ]:a0,[a5]:a3},id={[aW]:af,[aR]:aq,[aQ]:a2,[a5]:a4};function iu(e,t,r){switch(e){case 500:return"payment"===r?a$:aJ;case 4201:return aE;case 0x1dcd6501:return il[t]??aD;case 0x1dcdb322:return av;case 5e8:return id[t]??aO;case 0x1dcdb325:return t===a5?aZ:aj;case 0x1dcdb327:return aY;case 0x1dcdb328:return a1;default:return void 0===e||0===e?t:aA}}let ic={[-1]:ax,4001:ay,2001:aF,502:ab,402:aS,501:aB,400:aV};function ip(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if("code"===r.errorField){let t=io(e,r.httpStatus);if(t)return t}return"data.error_code"===r.errorField&&40001===e?aw:"err_code"===r.errorField&&401===e?aV:1001===e?"phone"===t?aH:ay:void 0===e?aJ:ic[e]??aJ}function im(e,t){return e instanceof a7?e:e instanceof a9?new a7(ip(e.remoteCode,t,e.options),{},e.options.logId):new a7(aJ)}function ih(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:a8,r=arguments.length>2?arguments[2]:void 0;if(e instanceof a7)return ia(e.code,e.details,e.logId??r);if(e instanceof a9){let t="code"===e.options.errorField?io(e.remoteCode,e.options.httpStatus):void 0,n=iu(e.remoteCode,aA,e.options.operation);return ia(e.options.operation?n:t??n,{},e.options.logId??r)}return a6(t,r)}function ig(e,t){let r=e.err_code;if(r)throw new a7(ip(r,t,{errorField:"err_code"}),{},e.log_id)}function iv(e){return!e||"object"!=typeof e||Array.isArray(e)?{}:{code:ii(e.code),logId:"string"==typeof e.log_id?e.log_id:void 0}}function iy(e,t){let{code:r,logId:n}=iv(e);if(r)throw new a9(r,`Sandbox 请求失败,错误码为 ${String(r)}。`,{errorField:"code",httpStatus:t,logId:n})}let i_="web-sdk-debugger",ib=[{id:"douyin",name:"抖音支付"}];async function iw(e){let t=await fetch("/__web_sdk_sandbox_proxy__",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),r=await t.json().catch(()=>({})),{code:n,logId:a}=iv(r);if(!t.ok)throw new a9(n,`Sandbox 代理请求失败,HTTP 状态码为 ${t.status}。`,{errorField:"code",httpStatus:t.status,logId:a});return iy(r,t.status),r}let iS=new class{request=()=>{throw Error("FlowAppDeveloperOpenGatewayService.request is undefined")};baseURL="";constructor(e){this.request=(null==e?void 0:e.request)||this.request,this.baseURL=(null==e?void 0:e.baseURL)||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}FetchPackageDownLoadInfo(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.verson_tag}/packet`);return this.request({url:r,method:"POST"},t)}GetArtifactStatus(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.verson_tag}/artifact`);return this.request({url:r,method:"POST"},t)}GetUserBasicInfo(e,t){let r=e||{},n=this.genBaseURL("/app_developer/api/user/basic"),a={user_name:r.user_name,user_id:r.user_id};return this.request({url:n,method:"GET",params:a},t)}GetConfigRoleList(e,t){let r=this.genBaseURL("/app_developer/api/config/role/role_list");return this.request({url:r,method:"GET"},t)}RoleListByAppid(e,t){let r=this.genBaseURL("/app_developer/api/user/role/role_list");return this.request({url:r,method:"GET"},t)}UpdateUserName(e,t){let r=this.genBaseURL("/app_developer/api/user/basic/update_user_name"),n={user_name:e.user_name};return this.request({url:r,method:"PUT",data:n},t)}GetInviteMemberList(e,t){let r=e||{},n=this.genBaseURL("/app_developer/api/member/member_list"),a={app_key:r.app_key,user_name:r.user_name,page_size:r.page_size,page_num:r.page_num};return this.request({url:n,method:"GET",params:a},t)}SendInviteMember(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/member/invite/send_invite`),n={role_code:e.role_code,target_user_id:e.target_user_id};return this.request({url:r,method:"POST",data:n},t)}UpdateAppMeta(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/meta/update`),n={app_name:e.app_name,description:e.description,privacy_agreement:e.privacy_agreement,icon_url:e.icon_url,extra:e.extra,app_type:e.app_type,login_text:e.login_text};return this.request({url:r,method:"POST",data:n},t)}SubmitRelease(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/release`);return this.request({url:r,method:"POST"},t)}ActivateDeviceCode(e,t){let r=this.genBaseURL("/app_developer/oauth/device/activate"),n={user_code:e.user_code,client_name:e.client_name};return this.request({url:r,method:"POST",data:n},t)}GetPlatformCert(e,t){let r=this.genBaseURL("/app_developer/api/platform/cert");return this.request({url:r,method:"GET"},t)}UploadCsr(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/upload_csr`),n={csr_pem:e.csr_pem};return this.request({url:r,method:"POST",data:n},t)}GetAppCert(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/cert`);return this.request({url:r,method:"GET"},t)}CreateApp(e,t){let r=this.genBaseURL("/app_developer/api/apps"),n={app_name:e.app_name,description:e.description,privacy_agreement:e.privacy_agreement,icon_url:e.icon_url,extra:e.extra,app_type:e.app_type,login_text:e.login_text};return this.request({url:r,method:"POST",data:n},t)}UploadIcon(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/upload_icon`);return this.request({url:r,method:"POST"},t)}SubmitAudit(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/submit_audit`);return this.request({url:r,method:"POST"},t)}IssueDeviceCode(e,t){let r=this.genBaseURL("/app_developer/oauth/device/code"),n={client_name:e.client_name};return this.request({url:r,method:"POST",data:n},t)}GetAppWhitelist(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/whitelist`),n={offset:e.offset,limit:e.limit,keyword:e.keyword};return this.request({url:r,method:"GET",params:n},t)}UpdateAppWhitelist(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/whitelist`),n={action:e.action,subject:e.subject};return this.request({url:r,method:"POST",data:n},t)}ExchangeDeviceToken(e,t){let r=this.genBaseURL("/app_developer/oauth/token"),n={device_code:e.device_code};return this.request({url:r,method:"POST",data:n},t)}ListApps(e,t){let r=e||{},n=this.genBaseURL("/app_developer/api/apps"),a={app_limit:r.app_limit,app_offset:r.app_offset,key_word:r.key_word,app_key:r.app_key};return this.request({url:n,method:"GET",params:a},t)}GetAppMeta(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/meta`),n={limit:e.limit,offset:e.offset,status:e.status};return this.request({url:r,method:"GET",params:n},t)}ToolList(e,t){let r=this.genBaseURL("/developer/api/tools/list"),n={mcp_server_url:e.mcp_server_url,mcp_config:e.mcp_config};return this.request({url:r,method:"GET",params:n},t)}GetMiniAppVersionArtifact(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/artifact`);return this.request({url:r,method:"GET"},t)}UploadMiniAppVersionDraftPackage(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/draft/upload`),n={source_type:e.source_type};return this.request({url:r,method:"POST",params:n},t)}SubmitMiniAppVersionDraft(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/draft/submit`),n={project_config_version:e.project_config_version,app_version_tag:e.app_version_tag};return this.request({url:r,method:"POST",data:n},t)}ListMiniAppVersions(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions`),n={page:e.page,page_size:e.page_size,id:e.id};return this.request({url:r,method:"GET",params:n},t)}VerifyYAML(e,t){let r=this.genBaseURL("/app_developer/api/yaml/verify"),n={yaml:e.yaml,mode:e.mode,yaml_type:e.yaml_type};return this.request({url:r,method:"POST",data:n},t)}GetMiniAppVersionYAML(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/manifest`);return this.request({url:r,method:"GET"},t)}GetMiniAppVersionStructuredManifest(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/manifest_struct`);return this.request({url:r,method:"GET"},t)}QrcodeInfo(e,t){let r=this.genBaseURL("/app_developer/resource_api/package/qrcode_info"),n={app_key:e.app_key};return this.request({url:r,method:"POST",data:n},t)}GetMiniAppVersionDraftPackageDownloadURL(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/app_versions/${e.version_tag}/download_url`),n={source_type_list:e.source_type_list};return this.request({url:r,method:"GET",params:n},t)}GetSubMerchantList(e,t){let r=this.genBaseURL("/app_developer/api/trade/user/get_sub_merchant_list"),n={org_id:e.org_id};return this.request({url:r,method:"GET",params:n},t)}AppBindSubMerchant(e,t){let r=this.genBaseURL(`/app_developer/api/trade/apps/${e.app_key}/app_bind_sub_merchant`),n={sub_merchant_uid:e.sub_merchant_uid,org_id:e.org_id};return this.request({url:r,method:"PUT",data:n},t)}CreateSubMerchant(e,t){let r=this.genBaseURL("/app_developer/api/trade/user/create_sub_merchant"),n={org_id:e.org_id,sub_merchant_name:e.sub_merchant_name};return this.request({url:r,method:"POST",data:n},t)}UnBindSubMerchant(e,t){let r=this.genBaseURL(`/app_developer/api/trade/apps/${e.app_key}/unbind_sub_merchant`),n={sub_merchant_uid:e.sub_merchant_uid,org_id:e.org_id};return this.request({url:r,method:"POST",data:n},t)}GetSubMerchantCaijingUrl(e,t){let r=this.genBaseURL("/app_developer/api/trade/user/get_sub_merchant_url"),n={sub_merchant_uid:e.sub_merchant_uid};return this.request({url:r,method:"POST",data:n},t)}GetAppBindSubMerchants(e,t){let r=this.genBaseURL(`/app_developer/api/trade/apps/${e.app_key}/get_bind_sub_merchants`);return this.request({url:r,method:"GET"},t)}GetAppEventCallbackConf(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/events/get_callback_conf`),n={source:e.source};return this.request({url:r,method:"GET",params:n},t)}UpdateAppEventCallbackConf(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/events/update_callback_conf`),n={source:e.source,callback_address:e.callback_address};return this.request({url:r,method:"PUT",data:n},t)}CreateOrganization(e,t){let r=this.genBaseURL("/app_developer/api/organization"),n={name:e.name};return this.request({url:r,method:"POST",data:n},t)}UpdateOrganization(e,t){let r=this.genBaseURL(`/app_developer/api/organizations/${e.org_code}/update`),n={name:e.name};return this.request({url:r,method:"POST",data:n},t)}FinishMiniAppVersionDraftSourceCodeUploading(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/draft/source_code/upload/finish`),n={upload_token:e.upload_token,size:e.size,sha256:e.sha256};return this.request({url:r,method:"POST",data:n},t)}DeleteOrganization(e,t){let r=this.genBaseURL(`/app_developer/api/organizations/${e.org_code}/delete`);return this.request({url:r,method:"POST"},t)}GetOrganizationToken(e,t){let r=this.genBaseURL("/app_developer/api/organization/get_token"),n={org_code:e.org_code};return this.request({url:r,method:"POST",data:n},t)}StartMiniAppVersionDraftSourceCodeUploading(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/draft/source_code/upload/start`),n={sha256:e.sha256};return this.request({url:r,method:"POST",data:n},t)}ListOrganizations(e,t){let r=this.genBaseURL("/app_developer/api/organizations/list");return this.request({url:r,method:"GET"},t)}CreateAppDomainFile(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/file_create`),n={normalized_domain:e.normalized_domain,domain_category:e.domain_category};return this.request({url:r,method:"POST",data:n},t)}DeleteAppDomain(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/delete`),n={normalized_domain:e.normalized_domain,domain_category:e.domain_category};return this.request({url:r,method:"POST",data:n},t)}VerifyAppDomainFile(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/file_verify`),n={normalized_domain:e.normalized_domain,domain_category:e.domain_category};return this.request({url:r,method:"POST",data:n},t)}CreateAppDomain(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/create`),n={domain:e.domain,domain_category:e.domain_category};return this.request({url:r,method:"POST",data:n},t)}GetAppDomainList(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/domain/list`);return this.request({url:r,method:"GET"},t)}SandboxGetAwemeCommonLoginInfo(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/auth/get_aweme_common_login_info"),n={app_key:e.app_key};return this.request({url:r,method:"POST",data:n},t)}SandboxUpdateMessageCardWidgetData(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/card/update_message_card_widget_data"),n={mixture_card_id:e.mixture_card_id,message_id:e.message_id,widget_id:e.widget_id,widget_data:e.widget_data};return this.request({url:r,method:"POST",data:n},t)}SandboxCreateSignOrder(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/create_sign_order"),n={data:e.data,db_authorization:e.db_authorization,app_key:e.app_key,message_id:e.message_id};return this.request({url:r,method:"POST",data:n},t)}SandboxGetOrderPaymentWithSign(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/get_order_payment_with_sign"),n={order_id:e.order_id,sign_data:e.sign_data,sign_db_authorization:e.sign_db_authorization,app_key:e.app_key,message_id:e.message_id,aweme_bind_status:e.aweme_bind_status};return this.request({url:r,method:"POST",data:n},t)}SandboxRequestOrder(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/request_order"),n={data:e.data,db_authorization:e.db_authorization,app_key:e.app_key,message_id:e.message_id};return this.request({url:r,method:"POST",data:n},t)}SandboxGetSignPageData(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/get_sign_page_data"),n={auth_order_id:e.auth_order_id,app_key:e.app_key,message_id:e.message_id,aweme_bind_status:e.aweme_bind_status};return this.request({url:r,method:"POST",data:n},t)}SandboxGetMessageInfoByMixtureCardID(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/card/get_message_info_by_mixture_card_id"),n={mixture_card_id:e.mixture_card_id};return this.request({url:r,method:"POST",data:n},t)}SandboxGetOrderPayment(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/trade/get_order_payment"),n={order_id:e.order_id,app_key:e.app_key,platform_signed_pt_code:e.platform_signed_pt_code,message_id:e.message_id,aweme_bind_status:e.aweme_bind_status};return this.request({url:r,method:"POST",data:n},t)}SandboxApiGetUserAppsPermissionDetail(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/miniapp_permission/detail"),n={applets_list:e.applets_list};return this.request({url:r,method:"POST",data:n},t)}SandboxApiPostUserAppsPermission(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/miniapp_permission/post"),n={applet_id:e.applet_id,update_scope_info:e.update_scope_info,using_scope_infos:e.using_scope_infos};return this.request({url:r,method:"POST",data:n},t)}SandboxApiGetUserAppsPermissionRecord(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/miniapp_permission/record"),n={applet_id:e.applet_id};return this.request({url:r,method:"POST",data:n},t)}SandboxApiExchangeCode(e,t){let r=e||{},n=this.genBaseURL("/app_developer/api/sandbox/jsb/oauth/token"),a={app_key:r.app_key,code:r.code,device_id:r.device_id,version_tag:r.version_tag};return this.request({url:n,method:"POST",data:a},t)}SandboxApiGetPhoneMask(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/phone_mask");return this.request({url:r,method:"POST"},t)}SandboxApiCheckPrivacyOrLoginStatus(e,t){let r=e||{},n=this.genBaseURL("/app_developer/api/sandbox/jsb/user/privacy_login/check"),a={app_key:r.app_key,version_tag:r.version_tag,check_type:r.check_type};return this.request({url:n,method:"POST",data:a},t)}SandboxApiAcceptPrivacy(e,t){let r=e||{},n=this.genBaseURL("/app_developer/api/sandbox/jsb/user/privacy/accept"),a={app_key:r.app_key,request_id:r.request_id,device_id:r.device_id};return this.request({url:n,method:"POST",data:a},t)}SandboxApiDeleteDataObtainedByTicket(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/user/miniapp_permission/ticket_revoke"),n={applet_id:e.applet_id,scope_name:e.scope_name,permission_ticket_type:e.permission_ticket_type};return this.request({url:r,method:"POST",data:n},t)}ListPublicNoticeTemplates(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/public_notice_templates`),n={category:e.category,subscription_type:e.subscription_type,keyword:e.keyword,page_num:e.page_num,page_size:e.page_size};return this.request({url:r,method:"GET",params:n},t)}SandboxIssueLoginCode(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/passport/open/auth"),n={client_key:e.client_key,aid:e.aid,scope:e.scope,source:e.source,exchange_type:e.exchange_type};return this.request({url:r,method:"POST",data:n},t)}GetSandboxBusinessInfo(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/session/business_info/get"),n={sandbox_session_id:e.sandbox_session_id};return this.request({url:r,method:"POST",data:n},t)}UpdateSandboxBusinessInfo(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/session/business_info/update"),n={sandbox_session_id:e.sandbox_session_id,phone_num:e.phone_num,csr_pem:e.csr_pem,location_info:e.location_info};return this.request({url:r,method:"POST",data:n},t)}SandboxPay(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/payment/pay"),n={trade_no:e.trade_no,pay_type:e.pay_type};return this.request({url:r,method:"POST",data:n},t)}CheckDeveloperAccessWhitelist(e,t){let r=this.genBaseURL("/app_developer/api/user/whitelist/check"),n={invite_code:(e||{}).invite_code};return this.request({url:r,method:"POST",data:n},t)}OIDCGet(e,t){let r=this.genBaseURL("/app_developer/api/oidc_get");return this.request({url:r,method:"GET"},t)}OIDCCallback(e,t){let r=this.genBaseURL("/app_developer/api/oidc_callback"),n={code:e.code,nonce:e.nonce,state:e.state};return this.request({url:r,method:"GET",params:n},t)}AuditDetail(e,t){let r=this.genBaseURL("/app_developer/api/apps/audit/detail"),n={audit_id:e.audit_id,audit_type:e.audit_type};return this.request({url:r,method:"POST",data:n},t)}ListBusinessTemplates(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/business_templates`),n={biz_type:e.biz_type,status:e.status,sync_status:e.sync_status,page_num:e.page_num,page_size:e.page_size};return this.request({url:r,method:"GET",params:n},t)}GetBusinessTemplatesYaml(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/business_templates/yaml`),n={status:e.status};return this.request({url:r,method:"GET",params:n},t)}DeleteBusinessTemplate(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/business_templates/${e.biz_type}/${e.template_key}/delete`);return this.request({url:r,method:"POST"},t)}GetPublicNoticeTemplate(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/public_notice_templates/${e.public_template_key}`);return this.request({url:r,method:"GET"},t)}PullSandboxNotices(e,t){let r=e||{},n=this.genBaseURL("/app_developer/api/sandbox/resources/notices/pull"),a={notice_ids:r.notice_ids,cursor:r.cursor,limit:r.limit};return this.request({url:n,method:"POST",data:a},t)}RemoveSandboxTaskFromUser(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/resources/tasks/remove_from_user"),n={task_id:e.task_id};return this.request({url:r,method:"POST",data:n},t)}PullSandboxTasks(e,t){let r=e||{},n=this.genBaseURL("/app_developer/api/sandbox/resources/tasks/pull"),a={task_ids:r.task_ids,cursor:r.cursor,limit:r.limit};return this.request({url:n,method:"POST",data:a},t)}CreateSandboxSession(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/session/create"),n={sandbox_project_id:e.sandbox_project_id,app_id:e.app_id,bridge_origins:e.bridge_origins,manifest:e.manifest};return this.request({url:r,method:"POST",data:n},t)}PreviewTosFile(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/audit/tos/preview`),n={object_key:e.object_key};return this.request({url:r,method:"GET",params:n},t)}QrcodeShort(e,t){let r=this.genBaseURL("/app_developer/resource_api/package/qrcode_short"),n={url:e.url,ttl:e.ttl};return this.request({url:r,method:"POST",data:n},t)}GetQrcodeURL(e,t){let r=this.genBaseURL("/app_developer/resource_api/package/qrcode_url"),n={token:e.token};return this.request({url:r,method:"POST",data:n},t)}DownloadTosFile(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/audit/tos/download`),n={object_key:e.object_key};return this.request({url:r,method:"GET",params:n},t)}SandboxCallMcpTool(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/jsb/card/call_mcp_tool"),n={tool_name:e.tool_name,tool_args_json:e.tool_args_json,widget_instance_id:e.widget_instance_id,artifact_version_code:e.artifact_version_code,app_key:e.app_key,widget_id:e.widget_id,scene:e.scene,skip_widget_update:e.skip_widget_update};return this.request({url:r,method:"POST",data:n},t)}DeleteMember(e,t){let r=this.genBaseURL(`/app_developer/api/apps/${e.app_key}/member/delete`),n={user_id:e.user_id};return this.request({url:r,method:"POST",data:n},t)}SubmitSandboxEventReport(e,t){let r=this.genBaseURL("/app_developer/api/sandbox/bridge/events/report"),n={event_id:e.event_id,data:e.data},a={"X-DBX-Sandbox-Session-ID":e["X-DBX-Sandbox-Session-ID"]};return this.request({url:r,method:"POST",data:n,headers:a},t)}UploadSimulatorImage(e,t){let r=this.genBaseURL("/app_developer/api/simulator/images/upload"),n={image:e.image};return this.request({url:r,method:"POST",data:n},t)}}({baseURL:"",request:iw});function ix(e,t){if(!e.data)throw Error(e.message||`${t} returned empty data`);return e.data}async function iI(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return ix(await iS.PullSandboxNotices(e),"PullSandboxNotices")}async function iE(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return ix(await iS.PullSandboxTasks(e),"PullSandboxTasks")}async function iC(e){return ix(await iS.RemoveSandboxTaskFromUser({task_id:e}),"RemoveSandboxTaskFromUser").removed_task}async function ik(e,t){return iw({data:{event_id:e,data:t},method:"POST",url:"/app_developer/api/sandbox/bridge/events/report"})}async function iN(e){let{appletId:t,granted:r,scopeName:n}=e;if(!t.trim())throw Error("appletId is required");if(!n.trim())throw Error("scopeName is required");let a=await iS.SandboxApiPostUserAppsPermission({applet_id:t,update_scope_info:{grant_status:r?1:2,scope_name:n}});if(0!==a.err_code)throw Error(a.err_msg||`Sandbox post Agentic Service permission failed with code ${String(a.err_code)}`)}async function iT(e){let{appKey:t,params:r,scene:n}=e;if(!t.trim())throw Error("callTool requires a simulator app context");if("widget"===n&&(!e.widgetId.trim()||!e.widgetInstanceId.trim()))throw Error("callTool requires a simulator conversation card context");let{skipWidgetUpdate:a,toolArgs:i,toolName:s}=function(e){if(!e8(e)||"string"!=typeof e.toolName||!e.toolName.trim()||!e8(e.toolArgs)||void 0!==e.skipWidgetUpdate&&"boolean"!=typeof e.skipWidgetUpdate)throw Error("callTool requires a non-empty toolName, an object toolArgs, and an optional boolean skipWidgetUpdate");return{skipWidgetUpdate:e.skipWidgetUpdate??!1,toolName:e.toolName.trim(),toolArgs:e.toolArgs}}(r),o=await iS.SandboxCallMcpTool({app_key:t,scene:"page"===n?2:1,skip_widget_update:a,tool_args_json:JSON.stringify(i),tool_name:s,..."widget"===n?{widget_id:e.widgetId,widget_instance_id:e.widgetInstanceId}:{}}),l=ii(o.err_code);if(void 0!==l&&0!==l)throw new a9(l,o.err_msg||`callTool failed with code ${l}`,{errorField:"err_code",logId:o.log_id});if(!o.result)throw Error(o.err_msg||"callTool returned an empty result");if(1!==o.result.output_kind&&2!==o.result.output_kind)throw Error("callTool returned an invalid output kind");let d=o.result.card_update_error,u=o.result.tool_error,c=o.result.tool_result_json,p=d?{cardUpdateError:{code:d.code,message:d.message,phase:"render"}}:{};if(u){let e=ii(u.code);if(void 0!==c||void 0===e||"string"!=typeof u.message||!u.message.trim())throw Error("callTool returned an invalid Tool error");return{toolError:{code:e,message:u.message},...p}}if(void 0===c)throw Error("callTool returned neither a Tool result nor a Tool error");return{toolResult:function(e){let t=JSON.parse(e);if(!e8(t))throw Error("callTool returned an invalid ToolResult");return t}(c),...p}}function iR(e){var t;let r=(null==(t=e.getAppId)?void 0:t.call(e))||e.appId;if(!r)throw new a7(ah);return r}function iM(e,t){var r;let n=null==e||null==(r=e[t])?void 0:r.trim();if(!n)throw new a7(aL,{key:t});return n}function iA(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],a=arguments.length>4?arguments[4]:void 0,i=ii(t.err_code),s=a?(a instanceof a9?a.remoteCode:void 0)??(void 0!==i&&0!==i?i:void 0)??-1:i??-1,o=(a instanceof a9?a.options.logId:void 0)??t.log_id,l=a?ih(a,ia(r),o):ia(iu(i,r),{},o),d={code:n?s:void 0,errNo:String(s),errMsg:l,errLogId:o};return{type:"callback",callbackId:e.callbackId,params:{code:0,data:d,errNo:s,errMsg:l,msg:l}}}async function iP(e,t){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];try{return await t()}catch(t){return iA(e,{},aA,r,t)}}async function ij(e,t){let r=function(e){let t;try{t=JSON.parse(e)}catch{throw new a7(ak)}if(!t||"object"!=typeof t||Array.isArray(t))throw new a7(ak);let r=t;if("sandbox_cashier"!==r.type)throw new a7(aM);let n="string"==typeof r.total_amount?r.total_amount.trim():"";if(!n||!/^\d+$/.test(n))throw new a7(aI);let a="string"==typeof r.pay_order_no?r.pay_order_no.trim():"",i="string"==typeof r.pay_status?r.pay_status.trim():"",s="string"==typeof r.trade_no?r.trade_no.trim():"";if(!a||!i||!s)throw new a7(aN,{field:a?i?"trade_no":"pay_status":"pay_order_no"});return{paymentTypes:function(e){if(!Array.isArray(e)||0===e.length)throw new a7(aP);let t=e.map(e=>{if(!e8(e))throw new a7(ak);let t="string"==typeof e.id?e.id.trim():"",r="string"==typeof e.name?e.name.trim():"";if(!t||!r)throw new a7(aN,{field:t?"name":"id"});return{id:t,name:r}});if(new Set(t.map(e=>{let{id:t}=e;return t})).size!==t.length)throw new a7(ak);return t}(r.pay_types??ib),payOrderNo:a,payStatus:i,totalAmount:n,tradeNo:s,type:"sandbox_cashier"}}(e);if(!t.showSandboxCashier)throw new a7(ag);if(!await t.showSandboxCashier(r,async e=>{if(!r.paymentTypes.some(t=>{let{id:r}=t;return r===e}))throw new a7(aP);try{await iS.SandboxPay({trade_no:r.tradeNo,pay_type:e})}catch(e){if(e instanceof a9&&"code"===e.options.errorField&&500===e.remoteCode)throw new a9(e.remoteCode,e.message,{...e.options,operation:"payment"});throw e}}))throw new a7(aC)}async function iL(e,t){let r,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"user_info",a=t?"phone":"login";try{r=await iS.SandboxIssueLoginCode({aid:"482431",client_key:iR(e),scope:n,source:"jsb",exchange_type:t})}catch(e){throw im(e,a)}var i,s,o=ii(null==(i=r.data)?void 0:i.error_code),l=iv(r).logId;if(o)throw new a7(ip(o,a,{errorField:"data.error_code"}),{},l);let d=null==(s=r.data)?void 0:s.code;if(!d)throw new a7(aJ);return d}async function iD(e){try{let t=void 0!==e.locationInfo,r=await iS.UpdateSandboxBusinessInfo({csr_pem:e.csrPem||(t?"":void 0),location_info:e.locationInfo,phone_num:e.phoneNum,sandbox_session_id:""});return iy(r),r}catch(r){let e=r instanceof a9?r.options.logId:r&&"object"==typeof r&&"logId"in r&&"string"==typeof r.logId?r.logId:void 0,t=Error(a6(r instanceof Error?r.message:String(r),e));throw t.logId=e,t}}async function iO(e){return iD(e)}async function iU(e){return iD({csrPem:"",locationInfo:e,phoneNum:""})}async function iq(e){let t=await fetch("/__web_sdk_sandbox_session_recreate__",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),r=await t.json().catch(()=>({}));if(!t.ok)throw Error((null==r?void 0:r.message)||`Sandbox session recreate failed with status ${t.status}`);return r}let i$=["aztec","codabar","code_39","code_93","code_128","data_matrix","ean_8","ean_13","itf","pdf417","qr_code","upc_a","upc_e"],iB={barCode:["codabar","code_39","code_93","code_128","ean_8","ean_13","itf","upc_a","upc_e"],datamatrix:["data_matrix"],pdf417:["pdf417"],qrCode:["qr_code"]};async function iF(e){let t=e.getSupportedFormats;return"function"==typeof t?new Set(await t()):null}function iW(e){var t,r;return{characterSet:"UTF-8",path:"",rawData:(t=e.rawValue,"function"!=typeof btoa||"u"<typeof TextEncoder?t:btoa(String.fromCharCode(...new TextEncoder().encode(t)))),result:e.rawValue,scanType:(r=e.format,i$.includes(r)?"pdf417"===r?"PDF_417":r.toUpperCase():"QR_CODE")}}async function iH(e,t){if("function"==typeof createImageBitmap){let r=await createImageBitmap(t);try{return e.detect(r)}finally{r.close()}}let r=new Image,n=URL.createObjectURL(t);try{return await new Promise((e,t)=>{r.onload=()=>e(),r.onerror=()=>t(Error("Failed to load selected image")),r.src=n}),e.detect(r)}finally{URL.revokeObjectURL(n)}}function iz(e,t,r,n,a){return t()?Promise.resolve():new Promise((i,s)=>{let o=0,l=()=>{for(let t of(window.clearTimeout(o),r))e.removeEventListener(t,d);e.removeEventListener("error",u)},d=()=>{t()&&(l(),i())},u=()=>{l(),s(Error(a))};for(let t of(o=window.setTimeout(()=>{l(),s(Error(a))},n),r))e.addEventListener(t,d);e.addEventListener("error",u)})}async function iV(e,t){e.srcObject=t,await iz(e,()=>e.readyState>=HTMLMediaElement.HAVE_METADATA,["loadedmetadata"],3e3,"Camera stream started, but video metadata was not loaded"),await e.play(),await iz(e,()=>e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA,["loadeddata","canplay","playing"],3e3,"Camera stream started, but no video frame was rendered")}async function iG(e,t){var r;let n,a=globalThis.BarcodeDetector;if(!a)throw Error("BarcodeDetector is not supported in this browser");let i=await iF(a),s=[...new Set((null==(r=e.scanType)?void 0:r.length)?e.scanType.flatMap(e=>iB[e]):i$)].filter(e=>!i||i.has(e));if(0===s.length)throw Error("Requested scanType is not supported in this browser");let o=new a({formats:s}),l=!1,d=!1,u=0,c=null,p=null,m=()=>{null==c||c.getTracks().forEach(e=>e.stop()),c=null,p&&(p.srcObject=null)},h=()=>{l||(l=!0,window.cancelAnimationFrame(u),m(),null==n||n.close())};try{return await new Promise((r,a)=>{let i=e=>{h(),e()},s=e=>{if(!l&&!d){if(!p||p.readyState<HTMLMediaElement.HAVE_CURRENT_DATA){e&&(null==n||n.setMessage("摄像头画面还未准备好"));return}d=!0,o.detect(p).then(t=>{let a=t[0];a?i(()=>r(iW(a))):e&&(null==n||n.setMessage("未识别到二维码或条形码"))}).catch(t=>{e&&(null==n||n.setMessage(t instanceof Error?t.message:String(t)))}).finally(()=>{d=!1})}};n=t({allowImageUpload:!e.onlyFromCamera,onCancel:()=>i(()=>a(Error("scanCode canceled"))),onCapture:()=>s(!0),onFile:e=>{l||(null==n||n.setMessage("正在识别图片..."),iH(o,e).then(e=>{let t=e[0];t?i(()=>r(iW(t))):null==n||n.setMessage("未识别到二维码或条形码,请换一张图片重试")}).catch(e=>{null==n||n.setMessage(e instanceof Error?e.message:String(e))}))},onVideoReady:t=>{var r;if(!p&&!l){if(p=t,!(null==(r=navigator.mediaDevices)?void 0:r.getUserMedia))return e.onlyFromCamera?void i(()=>a(Error("Camera is not available in this browser"))):void(null==n||n.setMessage("无法使用摄像头,请从相册选择二维码或条形码图片"));navigator.mediaDevices.getUserMedia({audio:!1,video:{facingMode:{ideal:"environment"}}}).then(e=>l?void e.getTracks().forEach(e=>e.stop()):(c=e,iV(t,e))).then(()=>{if(l)return;let e=()=>{l||(s(!1),u=window.requestAnimationFrame(e))};e()}).catch(t=>{if(l)return;let r=t instanceof Error?t.message:String(t);if(m(),e.onlyFromCamera){null==n||n.setMessage(r),i(()=>a(t instanceof Error?t:Error(r)));return}null==n||n.setMessage(`无法使用摄像头,请从相册选择二维码或条形码图片:${r}`)})}}})})}catch(e){throw h(),e}}function iJ(){throw Error("Simulator UI presenter is unavailable")}function iK(){return{hideLoading:iJ,hideToast:iJ,showActionSheet:async()=>iJ(),showBottomSheet:async()=>iJ(),showLoading:iJ,showModal:async()=>iJ(),showToast:iJ}}let iX="doubao-web-sdk-debugger-vibration-style",iQ="doubao-web-sdk-debugger-screen-vibrating",iY={heavy:4,light:1,medium:2},iZ=0,i0=null;function i1(e){e.classList.remove(iQ),e.style.removeProperty("--doubao-web-sdk-debugger-vibrate-distance"),e.style.removeProperty("--doubao-web-sdk-debugger-vibrate-duration")}function i2(e,t,r){if(!("function"==typeof navigator.vibrate&&navigator.vibrate(e)&&function(){let e=navigator.maxTouchPoints??0;if(e<=0)return!1;let t=navigator.platform??"",r=navigator.userAgent??"";return/android|iphone|ipad|ipod|mobile/i.test(`${t} ${r}`)||/mac/i.test(t)&&e>1}())){let n;(function(){if(document.getElementById(iX))return;let e=document.createElement("style");e.id=iX,e.textContent=`
|
|
24
|
+
@keyframes doubao-web-sdk-debugger-screen-vibrate {
|
|
25
|
+
0%, 100% { transform: translate3d(0, 0, 0); }
|
|
26
|
+
12.5% { transform: translate3d(calc(var(--doubao-web-sdk-debugger-vibrate-distance) * -1), 0, 0); }
|
|
27
|
+
25% { transform: translate3d(var(--doubao-web-sdk-debugger-vibrate-distance), 0, 0); }
|
|
28
|
+
37.5% { transform: translate3d(0, calc(var(--doubao-web-sdk-debugger-vibrate-distance) * -1), 0); }
|
|
29
|
+
50% { transform: translate3d(0, var(--doubao-web-sdk-debugger-vibrate-distance), 0); }
|
|
30
|
+
62.5% { transform: translate3d(var(--doubao-web-sdk-debugger-vibrate-distance), var(--doubao-web-sdk-debugger-vibrate-distance), 0); }
|
|
31
|
+
75% { transform: translate3d(calc(var(--doubao-web-sdk-debugger-vibrate-distance) * -1), calc(var(--doubao-web-sdk-debugger-vibrate-distance) * -1), 0); }
|
|
32
|
+
87.5% { transform: translate3d(var(--doubao-web-sdk-debugger-vibrate-distance), 0, 0); }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
.${iQ} {
|
|
36
|
+
animation: doubao-web-sdk-debugger-screen-vibrate var(--doubao-web-sdk-debugger-vibrate-duration) linear;
|
|
37
|
+
}
|
|
38
|
+
`,document.head.append(e)})(),window.clearTimeout(iZ),n=r||(document.body??document.documentElement),i0&&i0!==n&&i1(i0),i0=n,i1(n),n.style.setProperty("--doubao-web-sdk-debugger-vibrate-distance",`${t}px`),n.style.setProperty("--doubao-web-sdk-debugger-vibrate-duration",`${e}ms`),n.offsetWidth,n.classList.add(iQ),iZ=window.setTimeout(()=>{i1(n),i0===n&&(i0=null)},e+50)}}let i3="socketStatusChanged",i4="socketDataReceived",i5=1,i8=new Map;function i6(e,t,r){var n,a;null!=e&&null!=(n=e.apiRegistry)&&n.emitEvent(t,r)||null==e||null==(a=e.emitEvent)||a.call(e,t,r)}function i7(){return{...M(),platform:nq}}function i9(){var e,t;let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=(null==(e=r.baseAPIRegistry)?void 0:e.fork())??new f(ei);return n.registerMany(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.uiPresenter??iK(),r=e.scanCodePresenter;return{"doubao.request":function(e){if(as.has(e))return e;let t=(t,r)=>{let n=`wsd-request-${++ao}`,a=t.params??{},i=function(e){try{return an(e)}catch{return}}(a);ac({phase:"request",request:i??{headers:{},method:"string"==typeof a.method?a.method.toUpperCase():"GET",url:"string"==typeof a.url?a.url:""},requestId:n,...au()});let s=e=>ac({errorText:e,phase:"failure",requestId:n,...au()}),o=e=>((null==e?void 0:e.params.code)===1?ac({phase:"response",requestId:n,response:e.params.data,...au()}):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 n=e(t,r,i);return n instanceof Promise?n.then(e=>o(e),l):o(n)}catch(e){return l(e)}};return as.add(t),t}(e.requestHandler??(async(e,t,r)=>u(e,await aa(e.params,r)))),"doubao.getDeviceInfo":{handler:e=>u(e,i7()),syncResult:i7},"doubao.getNetworkType":{handler:e=>u(e,ap()),syncResult:ap},"doubao.scanCode":async e=>{if(!r)throw Error("Simulator scan-code presenter is unavailable");return u(e,await iG(e.params,r))},"doubao.vibrateLong":async t=>(await void i2(400,3,e.vibrationContainer),u(t,{})),"doubao.vibrateShort":async t=>(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;i2(15,iY[r],t)}(t.params,e.vibrationContainer),u(t,{})),...(!nV&&"u">typeof window&&(window.addEventListener("pagehide",nJ),nV=!0),{"doubao.chooseImage":async e=>{var t;let r,n,a,i,s;return u(e,await (a=(n=(r="string"==typeof(t=e.params).imageId?document.getElementById(t.imageId):null)instanceof HTMLInputElement?r:document.createElement("input"))!==r,i=t.count??9,n.type="file",n.accept="image/*",n.multiple=i>1,n.capture=(s=Array.isArray(t.sourceType)?t.sourceType:[]).includes("album")?"":s.includes("user")?"user":s.some(e=>"camera"===e||"environment"===e)?"environment":"",n.style.display="none",n.value="",a&&document.body.append(n),new Promise((e,t)=>{let r=()=>{n.removeEventListener("change",s),n.removeEventListener("cancel",o),a&&n.remove()},s=()=>{let a,s=Array.from(n.files??[]).slice(0,i);if(r(),0===s.length)return void t(Error("chooseImage was cancelled"));let o=[];try{a=s.map(e=>{let t=URL.createObjectURL(e);o.push(t);let r=e.type.startsWith("image/")?e.type.slice(6).split("+")[0].toLowerCase():nK(e.name);return r&&nz.set(t,r),{path:t,size:e.size,type:e.type,originalFileObj:e}})}catch(e){nG(o),t(e);return}for(nH.push(o);nH.length>20;)nG(nH.shift()??[]);e({tempFilePaths:a.map(e=>e.path),tempFiles:a})},o=()=>{r(),t(Error("chooseImage was cancelled"))};n.addEventListener("change",s,{once:!0}),n.addEventListener("cancel",o,{once:!0}),n.click()})))},"doubao.getImageInfo":async e=>u(e,await nQ(e.params)),"doubao.compressImage":async e=>u(e,await nY(e.params)),"doubao.saveImageToPhotosAlbum":e=>{var t=e.params;if("string"!=typeof t.filePath||!t.filePath)throw Error("filePath must be a non-empty string");let r=document.createElement("a");return r.href=t.filePath,r.download=t.filePath.split("/").pop()||"image",r.style.display="none",document.body.append(r),r.click(),r.remove(),u(e,{})}}),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{"doubao.getLocation":async t=>{var r;await at(e);let n=await n3.requestLocation(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{enableHighAccuracy:void 0===e.mode||2===e.mode,maximumAge:"number"==typeof e.maxCacheMs&&e.maxCacheMs>=0?e.maxCacheMs:0,timeout:"number"==typeof e.timeoutMs&&e.timeoutMs>=0?e.timeoutMs:3e4}}(t.params));return"success"===n.status?u(t,{latitude:(r=n.location).latitude,longitude:r.longitude,timestamp:new Date(r.timestamp).toISOString(),speed:r.speed,accuracy:r.accuracy}):ae(t,n)},"doubao.chooseLocation":async t=>await at(e)?c(t,n9):c(t,"user permission denied"),"doubao.openLocation":async t=>await at(e)?c(t,n9):c(t,"user permission denied"),"doubao.startLocationUpdate":async t=>{await at(e);let r=await n3.startLocationUpdates();return"success"===r.status?u(t,{}):ae(t,r)},"doubao.stopLocationUpdate":e=>(n3.stopLocationUpdates(),u(e,{}))}}(e),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.presenter??iK();return{"applet.showToast":e=>(t.showToast(e.params),u(e,{})),"doubao.hideToast":e=>(t.hideToast(),u(e,{})),"doubao.showLoading":e=>(t.showLoading(),u(e,{})),"doubao.hideLoading":e=>(t.hideLoading(),u(e,{})),"doubao.showModal":async e=>u(e,await t.showModal(e.params)),"doubao.showActionSheet":async e=>u(e,await t.showActionSheet(e.params)),"doubao.showBottomSheet":async e=>u(e,await t.showBottomSheet(e.params)),"doubao.hideKeyboard":e=>(document.activeElement.blur(),u(e,{}))}}({presenter:t}),...{"doubao.connectSocket":(e,t)=>u(e,function(e,t){if("string"!=typeof e.url||!e.url)throw Error("url must be a non-empty string");let r=i5++,n=new WebSocket(e.url,e.protocols);return n.binaryType="arraybuffer",i8.set(r,n),n.addEventListener("open",()=>{i6(t,i3,{socketTaskId:r,status:"connected",header:{},protocolType:n.protocol})}),n.addEventListener("message",e=>{var n;"string"==typeof(n=e.data)?i6(t,i4,{socketTaskId:r,data:n,dataType:"string"}):n instanceof ArrayBuffer&&i6(t,i4,{socketTaskId:r,data:rh(n),dataType:"base64"})}),n.addEventListener("close",e=>{i8.delete(r),i6(t,i3,{socketTaskId:r,status:"closed",code:e.code,reason:e.reason,protocolType:n.protocol})}),n.addEventListener("error",()=>{i8.delete(r),i6(t,i3,{socketTaskId:r,status:"failed",errMsg:"WebSocket error",protocolType:n.protocol})}),{socketTaskId:r}}(e.params,t)),"doubao.sendSocketData":e=>{var t;return function(e){let t=e.socketTaskId,r="number"==typeof t?i8.get(t):void 0;if(!r)throw Error(`socket not found: ${t}`);let n=e.data;if("string"!=typeof n&&!(n instanceof ArrayBuffer))throw Error("data must be a string or ArrayBuffer");r.send(n)}({socketTaskId:(t=e.params).socketTaskId,data:"base64"===t.dataType&&"string"==typeof t.data?rg(t.data):t.data}),u(e,{})},"doubao.closeSocket":e=>{var t=e.params;let r=t.socketTaskId,n="number"==typeof r?i8.get(r):void 0;if(!n)throw Error(`socket not found: ${r}`);return n.close(t.code,t.reason),u(e,{})}},...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{"doubao.requestOrder":t=>iP(t,async()=>{let r=await iS.SandboxRequestOrder({app_key:iR(e),data:iM(t.params,"data"),db_authorization:iM(t.params,"dbAuthorization")});return r.err_code||!r.order_id?iA(t,r,aW):u(t,{orderId:r.order_id,logId:r.log_id||""})}),"doubao.getOrderPayment":t=>iP(t,async()=>{var r,n;let a=iM(t.params,"orderId"),i=await iS.SandboxGetOrderPayment({app_key:iR(e),aweme_bind_status:!0,order_id:a,platform_signed_pt_code:null==(n=t.params)||null==(r=n.platformSignedPtCode)?void 0:r.trim()});if(i.err_code||!i.pay_data)return iA(t,i,aT);try{await ij(i.pay_data,e)}catch(e){return iA(t,i,aT,!1,e)}return u(t,{orderId:a,logId:i.log_id||""})}),"doubao.getOrderPaymentWithSign":t=>iP(t,async()=>{let r=iM(t.params,"orderId"),n=await iS.SandboxGetOrderPaymentWithSign({app_key:iR(e),aweme_bind_status:!0,order_id:r,sign_data:iM(t.params,"signData"),sign_db_authorization:iM(t.params,"signDbAuthorization")});if(n.err_code||!n.pay_data)return iA(t,n,aR);try{await ij(n.pay_data,e)}catch(e){return iA(t,n,aR,!1,e)}return u(t,{orderId:r,logId:n.log_id||""})}),"doubao.getPlatformSignInfo":e=>u(e,{signInfo:""}),"doubao.createSignOrder":t=>iP(t,async()=>{let r=await iS.SandboxCreateSignOrder({app_key:iR(e),data:iM(t.params,"data"),db_authorization:iM(t.params,"dbAuthorization")});return r.err_code||!r.auth_order_id?iA(t,r,aQ):u(t,{authOrderId:r.auth_order_id,logId:r.log_id||""})}),"doubao.sign":t=>iP(t,async()=>{let r=await iS.SandboxGetSignPageData({app_key:iR(e),auth_order_id:iM(t.params,"orderId"),aweme_bind_status:!0});return r.err_code||!r.data?iA(t,r,a5,!0):u(t,{})},!0),"doubao.login":async t=>u(t,{code:await iL(e)}),"doubao.loginWithDoubaoWidget":e=>u(e,{result:!0}),"doubao.postLoginResult":async t=>{var r,n,a,i;let s,o=t.params;if(!1===o.result)return null==(a=e.onPrivacyLoginCardClose)||a.call(e,"login"),await (null==(i=e.onGrantingCompleted)?void 0:i.call(e,"login",{noLogin:!0})),u(t,{});let l=o.code;if(!l)throw new a7(a_);try{s=await iS.SandboxApiExchangeCode({app_key:iR(e),code:l,version_tag:i_})}catch(e){throw im(e,"login")}return ig(s,"login"),null==(r=e.onPrivacyLoginCardClose)||r.call(e,"login"),await (null==(n=e.onGrantingCompleted)?void 0:n.call(e,"login")),u(t,{})},"doubao.getPrivacySetting":async t=>{var r;let n;try{n=await iS.SandboxApiCheckPrivacyOrLoginStatus({app_key:iR(e),check_type:1,version_tag:i_})}catch(e){throw im(e,"privacy")}return ig(n,"privacy"),u(t,{needAuthorization:(null==(r=n.data)?void 0:r.PrivacyAgreed)===!1})},"applet.agreePrivacyAuthorization":async t=>{var r,n;let a;try{a=await iS.SandboxApiAcceptPrivacy({app_key:iR(e)})}catch(e){throw im(e,"privacy")}return ig(a,"privacy"),null==(r=e.onPrivacyLoginCardClose)||r.call(e,"privacy"),await (null==(n=e.onGrantingCompleted)?void 0:n.call(e,"privacy")),u(t,{result:!0})},"applet.getPhoneNumber":async t=>u(t,{code:await iL(e,"profile","user_info,mobile"),message:"success"}),"applet.openLoginPage":t=>{var r,n;let a=null==(r=t.params)?void 0:r.url;return a&&(null==(n=e.onCustomLoginNavigate)||n.call(e,a)),u(t,{})},"applet.closePrivacyLoginCard":t=>{var r,n;return null==(n=e.onPrivacyLoginCardClose)||n.call(e,(null==(r=t.params)?void 0:r.type)||""),u(t,{})},"applet.reportAppLog":e=>u(e,{}),"applet.open":e=>{var t;let r=null==(t=e.params)?void 0:t.schema;return r&&window.open(r,"_blank","noopener,noreferrer"),u(e,{})},"doubao.__debuggerUpdateSandboxBusinessInfo":async e=>{let t=e.params,r=t.csrPem,n=t.locationInfo;return u(e,await iD({csrPem:r,locationInfo:n,phoneNum:t.phoneNum||""}))},...e.onCustomLoginNavigate?{"doubao.navigateTo":t=>{var r,n;let a=null==(r=t.params)?void 0:r.url;return a&&(null==(n=e.onCustomLoginNavigate)||n.call(e,a)),u(t,{})}}:{}}}(e),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{"doubao.authorize":async t=>{var r,n;let a=(null==(n=t.params)||null==(r=n.scope)?void 0:r.trim())||"";return a?await am(e,a,!1)?u(t,{}):c(t,"user permission denied"):c(t,"scope is required")},"doubao.operateRecorder":async t=>{var r,n;return"start"!==(null==(n=t.params)||null==(r=n.operationType)?void 0:r.trim())||await am(e,"scope.record",!1)?u(t,{}):c(t,"user permission denied")}}}(e),...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(!e8(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(!e8(e.data)||"string"!=typeof e.data.name||!e.data.name.trim()||!e8(e.data.arguments))throw Error("api/call content must include a name and arguments object");continue}if("responseHint"===e.type){if(!e8(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)),u(t,{})},"doubao.multiMediaBroadcast":async t=>u(t,await nW(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))}}(e)}}({...r,requestHandler:r.requestHandler??(null==(t=r.baseAPIRegistry)?void 0:t.get("doubao.request"))}),{override:!0}),n.registerEventSources({...{"doubao.onNetworkStatusChange":e=>{var t;let r;return t=t=>e({isConnected:t.isConnected,networkType:t.networkType}),addEventListener("online",r=()=>t(ad())),addEventListener("offline",r),()=>{removeEventListener("online",r),removeEventListener("offline",r)}}},...{"doubao.onLocationChange":e=>n3.subscribeLocation(t=>{var r;"success"===t.status&&e({latitude:(r=t.location).latitude,longitude:r.longitude,speed:r.speed,accuracy:r.accuracy,altitude:r.altitude,verticalAccuracy:r.altitudeAccuracy,horizontalAccuracy:r.accuracy})}),"doubao.onLocationChangeError":e=>n3.subscribeLocation(t=>{"success"!==t.status&&e("user_unauthorized"===t.status?{errMsg:"user permission denied"}:{errCode:t.code,errMsg:t.message})})},...{[i3]:()=>void 0,[i4]:()=>void 0}},{override:!0}),n}function se(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{apiRegistry:e.apiRegistry??i9(e),runtimeHost:e.runtimeHost??{},scanCodePresenter:e.scanCodePresenter,uiPresenter:e.uiPresenter}}var st=r(17228);function sr(e,t,r){var n;null==e||e({category:"mcp",source:"local_mcp",trace_id:null==r||null==(n=r.trace)?void 0:n.trace_id,trace:null==r?void 0:r.trace,...t})}function sn(e){return{name:e.name,description:e.description||"",input_schema_json:tL(e.inputSchema??{type:"object",additionalProperties:!0})}}async function sa(e,t){var r,n,a;null==(r=t.signal)||r.throwIfAborted();let i=new st.Kj({name:"web-sdk-debugger",version:"0.0.1"},{versionNegotiation:{mode:"auto"}}),s=new st.jS(new URL(e),{fetch:t.fetcher,requestInit:t.headers?{headers:t.headers}:void 0}),o=()=>{si(l)},l={client:i,transport:s,removeAbortListener:()=>{var e;return null==(e=t.signal)?void 0:e.removeEventListener("abort",o)}};null==(n=t.signal)||n.addEventListener("abort",o,{once:!0});try{await i.connect(s,{signal:t.signal}),null==(a=t.signal)||a.throwIfAborted()}catch(e){throw await si(l),e}return l}async function si(e){e.removeAbortListener(),await e.transport.close().catch(()=>void 0),await e.client.close().catch(()=>void 0)}let ss="wsd:runtime-console",so=new WeakMap;function sl(e,t){if(!e.dispatchEvent(new CustomEvent(ss,{cancelable:!0,detail:t})))return;let r=so.get(e)??[];r.push(t),so.set(e,r)}let sd=["log","info","warn","error","debug"];function su(){return{entries:[],nextEntryId:0}}function sc(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 sp(e){return"number"==typeof e&&Number.isFinite(e)?Math.max(e-1,0):0}function sm(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 sh(e,t){var r;let n=e.trim(),a=n.match(/^(.*):(\d+):(\d+)$/)??n.match(/^(.*):(\d+)$/);if(!a)return null;let[,i,s,o]=a;if(!i)return null;let l=t&&("<anonymous>"===i||i.endsWith(", <anonymous>")||/^eval at\b.*<anonymous>$/.test(i))?t:void 0,d=l&&/\.web\.bundle(?:[?#]|$)/.test(l)?2:0;return{url:l??i,lineNumber:Math.max(sp(Number(s))-d,0),columnNumber:void 0===o?0:"number"==typeof(r=Number(o))&&Number.isFinite(r)?Math.max(r-1,0):0}}function sg(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(),n=r.startsWith("at ")?r.slice(3).trim():r,a=n.match(/^(.*?)\s+\((.*)\)$/);if(a){let[,e,r]=a,n=sh(r,t);return n?{functionName:e,scriptId:"",...n}:null}let i=sh(n,t);return i?{functionName:"",scriptId:"",...i}:null})(e,t.fallbackSourceUrl)).filter(e=>!!e),n=t.dropFirstFrame&&r.length>1?r.slice(1):r,a=n.filter(e=>!(e.url.includes("console-recorder")||e.url.includes("web-sdk-debugger")||/capture.*Stack|console\.(?:log|info|warn|error|debug)/.test(e.functionName))),i=a.length>0?a:n;return i.length>0?{callFrames:i}:void 0}function sf(e){let t=null==e?void 0:e.callFrames[0];return t?{url:t.url,lineNumber:t.lineNumber,columnNumber:t.columnNumber}:void 0}function sv(e){return e?{callFrames:[{functionName:"",scriptId:"",...e}]}:void 0}function sy(e){return e?`[${e}] `:""}class s_{target;store;listeners=new Set;constructor(e,t=su()){this.target=e,this.store=t,this.target.addEventListener("error",this.handleRuntimeError),this.target.addEventListener(ss,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 n=r.eval(e),a=sc(n);return this.addEntry("eval","iframe"===t?"iframe":"eval",a),{ok:!0,value:a}}catch(t){let e=sc(t);return this.addEntry("error","eval",e),{ok:!1,value:e}}}destroy(){this.target.removeEventListener("error",this.handleRuntimeError),this.target.removeEventListener(ss,this.handleRuntimeConsole),this.listeners.clear()}addEntry(e,t,r){let n=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,...n}),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,n,a,i,s=(r=null==(t=e.detail)?void 0:t.error,n=e.currentTarget instanceof HTMLElement?sm(e.currentTarget):void 0,i=sf(a=sg(null==r?void 0:r.stack,{fallbackSourceUrl:n}))??function(e){var t,r,n,a,i,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:sp(null==(n=e.sourceMap)||null==(r=n.offset)?void 0:r.line),columnNumber:"number"==typeof(s=null==(i=e.sourceMap)||null==(a=i.offset)?void 0:a.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:i,stackTrace:a??sv(i)}}:{message:sc(r??t??e),metadata:{location:i,stackTrace:a??sv(i)}});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=so.get(e)??[],so.delete(e),t))this.addRuntimeConsoleEntry(r)}addRuntimeConsoleEntry(e){var t;let r=e.stackTrace??sg(e.stack,{dropFirstFrame:!0,fallbackSourceUrl:sm(this.target)}),n=e.location??sf(r),a="string"==typeof e.message?e.message:(e.args??[]).map(sc).join(" "),i="string"==typeof e.pagePath&&e.pagePath?e.pagePath:void 0,s="string"==typeof e.label&&e.label?e.label:i;this.addEntry((t=e.level,sd.includes(t)?t:"log"),"runtime",`${sy(s)}${a}`,{args:function(e,t){if(!e||!t)return e;let r=sy(t);if(0===e.length)return[r.trim()];let[n,...a]=e;return"string"==typeof n?[`${r}${n}`,...a]:[r.trim(),n,...a]}(e.args,s),location:n,pagePath:i,stackTrace:r??sv(n)})}notify(){for(let e of this.listeners)e()}}let sb="doubao-component",sw="doubao-host-attrs",sS=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 sx(e){return e.getAttribute(sb)||null}function sI(e){let t=e.tagName.toLowerCase();return sx(e)??sS.get(t)??t}function sE(e){return Array.from(e).filter(e=>e&&!e.startsWith("doubao-"))}let sC=new Set(["IFRAME","LINK","SCRIPT","STYLE","TEMPLATE"]),sk=new Set(["data-wsd-node-id"]),sN=new Set(["part","lynx-default-overflow-visible"]),sT=new Set(["style","data-wsd-node-id"]);function sR(e){return e.nodeType===Node.ELEMENT_NODE&&!sC.has(e.tagName)}function sM(e){var t;return e.nodeType===Node.TEXT_NODE&&!!(null==(t=e.textContent)?void 0:t.trim())}function sA(e){return e.nodeType===Node.DOCUMENT_FRAGMENT_NODE?"#shadow-root":e.nodeType===Node.TEXT_NODE?"#text":e.tagName.toLowerCase()}function sP(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 sj(e){return Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0")}function sL(e){let t=e.trim(),r=Number.parseFloat(t);return Number.isFinite(r)&&0===r?"0":t}function sD(e){let t=Number.parseFloat(e);return Number.isFinite(t)?t:0}function sO(e){var t,r,n;let a=null==(t=e.getAttribute("aria-label"))?void 0:t.trim();if(a)return a;let i=null==(r=e.getAttribute("title"))?void 0:r.trim();if(i)return i;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==(n=e.textContent)?void 0:n.replace(/\s+/g," ").trim())??"":""}function sU(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 sq(e){return!e.hasAttribute("disabled")&&"true"!==e.getAttribute("aria-disabled")&&(!!(e.isContentEditable||e instanceof HTMLAnchorElement&&e.hasAttribute("href"))||e.tabIndex>=0)}function s$(e){return Array.from(e.attributes).filter(e=>!sk.has(e.name)).map(e=>({name:e.name,value:e.value}))}function sB(e){let t=document.createElement("template");return t.innerHTML=e,t.content}function sF(e){return sk.has(e)||sN.has(e)}function sW(e){return"DIV"===e.tagName&&"page"===e.getAttribute("part")}function sH(e,t){return sk.has(t)||sW(e)&&sF(t)}function sz(e,t){for(let r of t)sH(e,r.name)||e.setAttribute(r.name,r.value)}function sV(e){return s$(e).filter(t=>!sH(e,t.name))}function sG(e,t,r){let n=new Map(t.map(e=>[e.name,e.value])),a=new Map(r.map(e=>[e.name,e.value])),i=r.filter(e=>n.get(e.name)!==e.value),s=t.filter(e=>!a.has(e.name)).map(e=>e.name);return i.length||s.length?[{type:"attributes",nodeId:e,before:t,modified:i,removed:s}]:[]}function sJ(e){return Array.from(e.childNodes).filter(e=>sR(e)||sM(e))}function sK(e,t,r){let n=("elementFromPoint"in e&&"function"==typeof e.elementFromPoint?e.elementFromPoint.bind(e):document.elementFromPoint.bind(document))(t,r);for(;(null==n?void 0:n.shadowRoot)&&"function"==typeof n.shadowRoot.elementFromPoint;){let e=n.shadowRoot.elementFromPoint(t,r);if(!e||e===n)break;n=e}return n}function sX(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(t>8)return null;let r=null;for(let n of Array.from(e.children)){let e=n.getBoundingClientRect(),a=e.width>0||e.height>0?{rect:e,styleSource:n}:n.shadowRoot&&sX(n.shadowRoot,t+1)||sX(n,t+1);a&&(r=r?{rect:function(e,t){let r=Math.min(e.left,t.left),n=Math.min(e.top,t.top);return new DOMRect(r,n,Math.max(e.right,t.right)-r,Math.max(e.bottom,t.bottom)-n)}(r.rect,a.rect),styleSource:r.styleSource}:a)}return r}function sQ(e){let t=e.getBoundingClientRect();return t.width>0||t.height>0?{rect:t,styleSource:e}:e.shadowRoot&&sX(e.shadowRoot)||sX(e)||{rect:t,styleSource:e}}function sY(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement??null;for(;t;){if(sC.has(t.tagName))return!0;t=t.parentElement}return!1}class sZ{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 n=function(e){let t=e.trim();if(!t)return[];let r=document.createElement("template");r.innerHTML=`<div ${t}></div>`;let n=r.content.firstElementChild;return n?s$(n):[]}(t),a=null==r?void 0:r.trim();return this.editElementAttributes(e,e=>{a&&!sH(e,a)&&e.removeAttribute(a),sz(e,n)})}setAttributeValue(e,t,r){let n=t.trim();return n?this.editElementAttributes(e,e=>{if(sH(e,n))return!1;e.setAttribute(n,r)}):[]}removeAttribute(e,t){let r=t.trim();return r?this.editElementAttributes(e,e=>{if(sH(e,r))return!1;e.removeAttribute(r)}):[]}setNodeValue(e,t){return this.runWithoutObservation(()=>{let r=this.getNode(e),n=(null==r?void 0:r.textContent)??"";return(null==r?void 0:r.nodeType)!==Node.TEXT_NODE||n===t?[]:(r.textContent=t,[{type:"characterData",nodeId:e,value:t,previousValue:n}])})}setNodeName(e,t){return this.runWithoutObservation(()=>{let r=this.getElement(e),n=t.trim();if(!r||!n)return{nodeId:null,mutations:[]};if(sW(r))return{nodeId:e,mutations:[]};let a=r.parentNode,i=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,n);return{nodeId:this.getNodeId(s),mutations:a?[this.getChildListMutation(a,[e],[{previousNodeId:i,node:this.serializeNode(s)}])]:[]}})}setOuterHTML(e,t){return this.runWithoutObservation(()=>{let r=this.getNode(e);if(!r)return[];if(r instanceof DocumentFragment){let e=sJ(r).map(e=>this.getNodeId(e)),n=sB(t);return r.replaceChildren(...Array.from(n.childNodes)),[this.getChildListMutation(r,e,this.getInsertedNodeMutations(r,null,sJ(r)))]}if(r instanceof Element&&sW(r)){let n=sV(r),a=sJ(r).map(e=>this.getNodeId(e));!function(e,t){let r=sB(t),n=r.firstElementChild;if(!n)return e.replaceChildren(...Array.from(r.childNodes));for(let t of Array.from(e.attributes))sF(t.name)||e.removeAttribute(t.name);sz(e,s$(n)),e.replaceChildren(...Array.from(n.childNodes))}(r,t);let i=this.getInsertedNodeMutations(r,null,sJ(r));return[...sG(e,n,sV(r)),this.getChildListMutation(r,a,i)]}let n=r.parentNode;if(!n)return[];let a=this.getPreviousInspectableSiblingId(r),i=sB(t),s=sJ(i);return n.replaceChild(i,r),[this.getChildListMutation(n,[e],this.getInsertedNodeMutations(n,a,s))]})}getNodeIdAtPoint(e,t){let r,n,a=this.getRoot(),i=this.target.shadowRoot,s=(r=null,(n=a=>{for(let i of(sR(a)&&function(e,t,r){let{rect:n}=sQ(e);return n.width>0&&n.height>0&&t>=n.left&&t<=n.right&&r>=n.top&&r<=n.bottom}(a,e,t)&&(r=a),Array.from(a.childNodes)))sR(i)&&n(i)})(a),r),o=i?sK(i,e,t):sK(document,e,t),l=(s&&a.contains(s)?s:null)??(o&&a.contains(o)?o:null);if(!l)return null;let d=l;for(;d&&!sR(d);)d=d.parentNode??function(e){let t=e.getRootNode();return t instanceof ShadowRoot?t.host:null}(d);return d&&a.contains(d)?this.getNodeId(d):null}findLynxViews(){return function(e){let t=[],r=[e];for(;r.length;){let e=r.shift();for(let n of(e instanceof HTMLElement&&"LYNX-VIEW"===e.tagName&&t.push(e),e instanceof Element&&e.shadowRoot&&r.push(e.shadowRoot),e.children??[]))r.push(n)}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,n;let a,i,s,o,l,d,u,c,p,m,h,g,f,v,y=this.getElement(e);if(!y||!y.isConnected)return null;let{rect:_,styleSource:b}=sQ(y),w=t.getBoundingClientRect(),S=t.offsetWidth?w.width/t.offsetWidth:1,x=t.offsetHeight?w.height/t.offsetHeight:1,I=_.width/S,E=_.height/x,C=getComputedStyle(b),k=C.backgroundColor.trim(),N=(r=C.paddingTop,n=C.paddingRight,(a=[r,n,C.paddingBottom,C.paddingLeft].map(sL)).every(e=>"0"===e)?null:a.every(e=>e===a[0])?a[0]:a[0]===a[2]&&a[1]===a[3]?`${a[0]} ${a[1]}`:a[1]===a[3]?`${a[0]} ${a[1]} ${a[2]}`:a.join(" "));return{left:(_.left-w.left)/S,top:(_.top-w.top)/x,width:I,height:E,nodeName:sI(y),selector:function(e){let t=e.id.trim();if(sx(e)){let t=(e.getAttribute(sw)??"").split(/\s+/).filter(Boolean).includes("class")?e.firstElementChild:e;return{tagName:sI(e),classNames:sE((null==t?void 0:t.classList)??[])}}return{tagName:sI(e),id:t,classNames:Array.from(e.classList).filter(Boolean)}}(y),boxModel:(i=sD(C.borderTopWidth),s=sD(C.borderRightWidth),o=sD(C.borderBottomWidth),l=sD(C.borderLeftWidth),d=sD(C.paddingTop),u=sD(C.paddingRight),c=sD(C.paddingBottom),p=l+sD(C.paddingLeft),{content:{left:p,top:m=i+d,width:Math.max(0,I-p-s-u),height:Math.max(0,E-m-o-c)}}),dimensions:`${sP(I)} \xd7 ${sP(E)}`,styles:[...k?[{name:"Background",value:(g=(h=k.trim()).match(/^rgb\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*\)$/i),f=h.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))?`#${sj(Math.round(Number(v[1])))}${sj(Math.round(Number(v[2])))}${sj(Math.round(Number(v[3])))}`:h),swatch:k}]:[],...N?[{name:"Padding",value:N}]:[]],accessibility:{name:sO(y),role:sU(y),keyboardFocusable:sq(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 n=sV(r);return!1===t(r)?[]:sG(e,n,sV(r))})}getPreviousInspectableSiblingId(e){let t=e.parentNode;if(!t)return null;let r=sJ(t),n=r.findIndex(t=>t===e),a=n>0?r[n-1]:null;return a?this.getNodeId(a):null}getChildListMutation(e,t,r){return{type:"childList",parentNodeId:this.getNodeId(e),removedNodeIds:t,insertedNodes:r,childNodeCount:sJ(e).length}}getInsertedNodeMutations(e,t,r){let n=[],a=t;for(let t of r){if((t.parentNode??(t instanceof ShadowRoot?t.host:null))!==e)continue;let r=this.serializeNode(t);n.push({previousNodeId:a,node:r}),a=r.id}return n}runWithoutObservation(e){var t,r;let n=null!==this.mutationObserver;n&&(null==(t=this.mutationObserver)||t.disconnect());try{return e()}finally{n&&(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:sA(e),attributes:[],children:[],textContent:(t=(e.textContent??"").replace(/\s+/g," ").trim()).length>120?`${t.slice(0,120)}...`:t}}let n=e instanceof HTMLElement?e:null;return{id:r,type:t&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE?"document":"element",name:sA(e),attributes:e instanceof Element?s$(e):[],children:sJ(e).map(e=>this.serializeNode(e)),...n?{accessibility:{name:sO(n),role:sU(n),keyboardFocusable:sq(n)}}:{}}}observe(){let e=this.target.shadowRoot??this.target;this.mutationObserver=new MutationObserver(e=>{e.some(e=>(function(e){if(sY(e.target))return!1;if("attributes"===e.type)return e.target instanceof Element&&sR(e.target)&&!sT.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!sY(t)&&(!!(sR(t)||sM(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 s0="data-wsd-node-id";function s1(e){let t=[];for(let r=0;r<e.length;r++){let n="function"==typeof e.item?e.item(r):e[r];if(!n)continue;let a=e.getPropertyValue(n);t.push({name:n,value:a,priority:e.getPropertyPriority(n),active:!0})}return t}function s2(e){return"u">typeof CSSStyleRule&&e instanceof CSSStyleRule}function s3(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",a=r.trim();a?e.setProperty(t,a,n):e.removeProperty(t)}function s4(e){return`${e.name}: ${e.value}${e.priority?` !${e.priority}`:""};`}function s5(e){return e.map(e=>({...e}))}function s8(e){return`inline:${e}`}function s6(e){return`rule:${e}`}class s7{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 n=e.item(r);t.push({name:n,value:e.getPropertyValue(n)})}return t}(r)}}setInlineDeclaration(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",a=!(arguments.length>4)||void 0===arguments[4]||arguments[4],i=this.elementInspector.getElement(e);if(!i)return;let s=s8(e);this.rememberStyleTextDeclaration(s,s1(i.style),t,r,n,a),s3(i.style,t,a?r:"")}setInlineDeclarations(e,t){let r=this.elementInspector.getElement(e);if(r){for(let e of(r.style.cssText="",t))e.active&&s3(r.style,e.name,e.value,e.priority);this.styleTextSnapshots.set(s8(e),s5(t))}}setRuleDeclaration(e,t,r,n){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"",i=!(arguments.length>5)||void 0===arguments[5]||arguments[5],s=this.rules.get(t),o=s6(t);if(this.rememberStyleTextDeclaration(o,s?s1(s.style):[],r,n,a,i),!i){if(s)try{s3(s.style,r,"")}catch{this.setOverrideDeclaration(e,r,"")}else this.setOverrideDeclaration(e,r,"");return}if(!s)return void this.setOverrideDeclaration(e,r,n,a);try{s3(s.style,r,n,a)}catch{this.setOverrideDeclaration(e,r,n,a)}}setRuleDeclarations(e,t,r){let n=this.rules.get(t),a=r.filter(e=>e.active);if(this.styleTextSnapshots.set(s6(t),s5(r)),!n)return void this.setOverrideDeclarations(e,a);try{for(let e of(n.style.cssText="",a))s3(n.style,e.name,e.value,e.priority)}catch{this.setOverrideDeclarations(e,a)}}addRule(e,t,r){let n=this.elementInspector.getElement(e),a=t.trim();if(!n||!a)return null;let i=this.getInspectorRuleStyleSheet();if(!i)return null;let s=`${a} { ${r.map(s4).join(" ")} }`;try{let e=i.cssRules.length;i.insertRule(s,e);let t=i.cssRules[e];if(t&&s2(t))return this.toMatchedStyleRule(t,getComputedStyle(n))}catch{}return null}setRuleSelector(e,t,r){let n=this.elementInspector.getElement(e),a=this.rules.get(t),i=r.trim();if(!n||!a||!i)return null;try{return a.selectorText=i,this.toMatchedStyleRule(a,getComputedStyle(n))}catch{return null}}setOverrideDeclaration(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",a=this.elementInspector.getElement(e);if(!a)return;a.setAttribute(s0,e),this.overriddenElements.add(a);let i=this.overrides.get(e)??new Map,s=r.trim();s?i.set(t,{value:s,priority:n}):i.delete(t),i.size>0?this.overrides.set(e,i):this.overrides.delete(e),this.renderOverrideStyleSheet()}setOverrideDeclarations(e,t){let r=this.elementInspector.getElement(e);if(!r)return;r.setAttribute(s0,e),this.overriddenElements.add(r);let n=new Map;for(let e of t)e.value.trim()&&n.set(e.name,{value:e.value.trim(),priority:e.priority});n.size>0?this.overrides.set(e,n):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(s0);this.overriddenElements.clear(),this.rules.clear()}getInlineStyle(e,t,r){return{id:"inline",selectorText:"element.style",editable:!0,declarations:this.getStyleTextSnapshot(s8(e))??s1(t.style)}}getMatchedRules(e,t){let r,n=this.target.shadowRoot??this.target,a=[];for(let i of(this.rules.clear(),r=[],"styleSheets"in n&&r.push(...Array.from(n.styleSheets)),"adoptedStyleSheets"in n&&r.push(...n.adoptedStyleSheets),r))this.collectRulesFromList(i,e,t,a);return a}collectRulesFromList(e,t,r,n,a){let i;try{i=e.cssRules}catch{return}for(let e of Array.from(i)){if(s2(e)){if(!function(e,t){try{return e.matches(t)}catch{return!1}}(t,e.selectorText))continue;n.push(this.toMatchedStyleRule(e,r,a));continue}if("cssRules"in e){let i=function(e){if("conditionText"in e&&"string"==typeof e.conditionText)return e.conditionText}(e);this.collectRulesFromList(e,t,r,n,a&&i?`${a} and ${i}`:i??a)}}}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 n=this.getRuleId(e);return this.rules.set(n,e),{id:n,selectorText:e.selectorText,conditionText:r,editable:!0,source:this.isOverrideRule(e)?"override":"rule",declarations:this.getStyleTextSnapshot(s6(n))??s1(e.style)}}getStyleTextSnapshot(e){let t=this.styleTextSnapshots.get(e);return t?s5(t):void 0}rememberStyleTextDeclaration(e,t,r,n){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"",i=!(arguments.length>5)||void 0===arguments[5]||arguments[5],s=this.getStyleTextSnapshot(e)??s5(t),o=n.trim(),l=s.findIndex(e=>e.name===r);if(o||!i){let e={name:r,value:o||(l>=0?s[l].value:""),priority:a,active:i};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,n=Array.from(r.entries()).map(e=>{let[t,r]=e;return` ${t}: ${r.value}${r.priority?` !${r.priority}`:""};`}).join("\n");return`[${s0}="${t}"] {
|
|
39
|
+
${n}
|
|
40
|
+
}`});this.getOverrideStyleElement().textContent=t.join("\n\n")}}class s9{listeners=new Set;elementInspector;styleInspector;consoleRecorder;selectedNodeId=null;consoleUnsubscribe=null;constructor(e,t={}){this.elementInspector=new sZ(e,()=>this.notify({type:"document"})),this.styleInspector=new s7(e,this.elementInspector),this.consoleRecorder=new s_(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,n,a){this.styleInspector.setInlineDeclaration(e,t,r,n,a),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,n,a,i){this.styleInspector.setRuleDeclaration(e,t,r,n,a,i),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 n=this.styleInspector.addRule(e,t,r);return this.notify({type:"style",styleSheetId:n?`rule:${n.id}`:"inspector:main"}),n}setRuleSelector(e,t,r){let n=this.styleInspector.setRuleSelector(e,t,r);return this.notify({type:"style",styleSheetId:n?`rule:${n.id}`:`rule:${t}`}),n}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 oe(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 n=new URL(r,window.location.href);n.pathname+=".map";let a=await fetch(n.href).catch(()=>void 0);if(!(null==a?void 0:a.ok))return;let i=await a.text();return{content:"",sourceMapURL:`data:application/json;charset=utf-8,${encodeURIComponent(i)}`,url:r}}let ot=new Set(["class","style"]);function or(e){var t;return"element"!==e.type?null:(null==(t=e.attributes.find(e=>e.name===sb))?void 0:t.value)??null}function on(e){var t;return(null==(t=e.attributes.find(e=>"doubao-children"===e.name))?void 0:t.value)==="all"}function oa(e){return e.attributes.some(e=>"doubao-slot"===e.name)}function oi(e){return e.attributes.filter(e=>ot.has(e.name)).map(e=>"class"===e.name?{name:e.name,value:sE(e.value.split(/\s+/)).join(" ")}:e).filter(e=>e.value)}function os(e){return Array.isArray(e)?"array":void 0}function oo(e){return Array.isArray(e)?`Array(${e.length})`:ol(e)}function ol(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 od(e,t){let r=ou(t),n="object"==typeof t&&null!==t||"function"==typeof t;return{name:e,type:r,subtype:n?os(t):void 0,value:n?oo(t):String(t)}}function ou(e){return null===e?"object":typeof e}function oc(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:ou(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:os(e),className:"function"==typeof e?"Function":ol(e),description:"function"==typeof e?e.toString():oo(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:os(e),description:oo(e),overflow:r.length>5,properties:r.slice(0,5).map(t=>{try{let r=Object.getOwnPropertyDescriptor(e,t);return od(t,r&&"value"in r?r.value:void 0)}catch{return od(t,void 0)}})})}}return{type:ou(e),value:e,description:String(e)}}function op(e,t){return(e.args??[e.message]).map(e=>oc(e,t))}function om(e,t){return{startLine:0,startColumn:e,endLine:0,endColumn:t}}function oh(e,t){let r=0,n="",a=t.map(e=>{let t=`${e.name}: ${e.value}${e.priority?` !${e.priority}`:""};`,a=e.active?t:`/* ${t} */`,i=om(r,r+a.length);return n+=`${a} `,r=n.length,{name:e.name,value:e.value,important:"important"===e.priority,disabled:!e.active,parsedOk:!0,implicit:!1,text:a,range:i}});return{styleSheetId:e,cssText:n.trim(),range:om(0,Math.max(0,n.trim().length)),shorthandEntries:[],cssProperties:a}}function og(e){let t=e.indexOf(":");return t<0?{kind:e,id:""}:{kind:e.slice(0,t),id:e.slice(t+1)}}function of(e){let t,r=e.includes("{")?e.slice(e.indexOf("{")+1,e.lastIndexOf("}")):e,n=[],a=/\/\*([\s\S]*?)\*\//g,i=0;for(;t=a.exec(r);)n.push(...ov(r.slice(i,t.index),!0)),n.push(...ov(t[1],!1)),i=t.index+t[0].length;return n.push(...ov(r.slice(i),!0)),n}function ov(e,t){let r=[];for(let n of e.split(";")){let e=n.indexOf(":");if(e<=0)continue;let a=n.slice(0,e).trim(),i=n.slice(e+1).trim(),s="";/!\s*important$/i.test(i)&&(i=i.replace(/!\s*important$/i,"").trim(),s="important"),a&&r.push({name:a,value:i,priority:s,active:t})}return r}function oy(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 o_(e){return oy(e)?e.attributes.filter(e=>"part"!==e.name&&"lynx-default-overflow-visible"!==e.name):e.attributes}function ob(e){return o_(e).flatMap(e=>[e.name,e.value])}function ow(e){return oy(e)?"page":sS.get(e.name)??e.name}function oS(e,t){var r;return null==(r=e.attributes.find(e=>e.name===t))?void 0:r.value}function ox(e,t){return e.type===t.type&&e.name===t.name&&(t.id?oS(e,"id")===t.id:!t.className||oS(e,"class")===t.className)}function oI(e,t){let r=Number(e);return Number.isFinite(r)?r<0?1/0:r:t}function oE(e){return e===1/0?e:Math.max(0,e-1)}function oC(e){if("text"===e.type)return e.textContent??"";if("document"===e.type)return ok(e);let t=o_(e).map(e=>` ${e.name}="${e.value}"`).join(""),r=e.children.map(e=>oC(e)).join(""),n=ow(e);return`<${n}${t}>${r}</${n}>`}function ok(e){return e.children.map(e=>oC(e)).join("")}function oN(e,t){let r=(e,n)=>{let a=[...n,e];if(e.id===t)return a;for(let t of e.children){let e=r(t,a);if(e)return e}return null};return r(e,[])}let oT="__wsd_document__";function oR(e){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation()}let oM="wsd-main-frame";function oA(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function oP(e){var t;let r;if(e instanceof ArrayBuffer)return{base64Encoded:!0,body:rh(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 oj(e){throw Object.assign(Error(e),{code:-32602})}function oL(e,t,r){return e??oj(null===e?r:t)}class oD{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,ai.add(r),()=>ai.delete(r)),this.enabledSessions.set(t,{maxPostDataSize:oA(null==e?void 0:e.maxPostDataSize,65536),maxTotalBufferSize:oA(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=oL(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=oL(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 n=void 0===e.request.body?void 0:oP(e.request.body),a={request:e.request,sessions:new Set(this.enabledSessions.keys())};this.requests.set(e.requestId,a),n&&this.storePayload(a,"requestBody",n);let i=(r=(t=e.request.url).indexOf("#"))<0?{url:t}:{url:t.slice(0,r),urlFragment:t.slice(r)};for(let t of a.sessions){let r=this.enabledSessions.get(t);if(!r)continue;let a=n&&!n.base64Encoded&&n.byteLength<=r.maxPostDataSize;this.emit({method:"Network.requestWillBeSent",params:{documentURL:i.url,frameId:oM,initiator:{type:"script"},loaderId:oM,redirectHasExtraInfo:!1,request:{...i,hasPostData:!!n,headers:e.request.headers,initialPriority:"High",isSameSite:!0,method:e.request.method,mixedContentType:"none",postData:a?n.body:void 0,referrerPolicy:"no-referrer"},requestId:e.requestId,timestamp:e.timestamp,type:"XHR",wallTime:e.wallTime}},t)}}handleResponseReceived(e,t){var r;let n=e.response??{},a=!(r=n.header)||"object"!=typeof r||Array.isArray(r)?{}:Object.fromEntries(Object.entries(r).map(e=>{let[t,r]=e;return[t,String(r)]})),i=oP(n.data),{charset:s,mimeType:o}=function(e){var t,r;let n,a=(null==(n=Object.entries(e).find(e=>{let[t]=e;return"content-type"===t.toLowerCase()}))?void 0:n[1])??"",[i=""]=a.split(";");return{charset:(null==(r=/(?:^|;)\s*charset\s*=\s*["']?([^;"']+)/i.exec(a))||null==(t=r[1])?void 0:t.trim())??"",mimeType:i.trim()}}(a),l="number"==typeof n.statusCode&&Number.isFinite(n.statusCode)?n.statusCode:0;this.storePayload(t,"responseBody",i),this.emitForRequest(t,{method:"Network.responseReceived",params:{frameId:oM,hasExtraInfo:!1,loaderId:oM,requestId:e.requestId,response:{charset:s,connectionId:0,connectionReused:!1,encodedDataLength:i.byteLength,fromDiskCache:!1,fromPrefetchCache:!1,fromServiceWorker:!1,headers:a,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:i.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?oj("requestId must be a non-empty string"):e.requestId,n=this.requests.get(r);return(null==n?void 0:n.sessions.has(t))?n:oj(`Unknown requestId: ${r}`)}storePayload(e,t,r){let n=e[t];n&&(this.payloads.delete(n),this.storedPayloadSize-=n.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,n]]=e;this.payloads.delete(t),this.storedPayloadSize-=t.byteLength,r[n]=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 oO{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(oT),n=oE(t),a=t>0?[this.toCdpNode(e,n,r)]:void 0,i={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:a};return this.cdpNodes.set(r,i),i}toCdpNode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1/0,r=arguments.length>2?arguments[2]:void 0,n=this.getCdpNodeId(e.id),a=oE(t),i=t>0?e.children.map(e=>this.toCdpNode(e,a,n)):void 0,s="text"===e.type,o="document"===e.type,l=ow(e),d={nodeId:n,backendNodeId:n,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?ob(e):void 0,children:i};return this.cdpNodes.set(n,d),d}}function oU(e){return e.map(e=>({...e}))}function oq(e){return"attributes"===e.type||"characterData"===e.type}class o${adapter;consoleAdapter=null;appAdapter=null;appTarget=null;target;listeners=new Set;options;nodeStore=new oO;network;consoleStore=su();appConsoleStore=su();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 oD((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 n=null==(r=this.adapter.getMatchedStyles(e))?void 0:r.computedStyles;if(!n)return null;if(!(null==t?void 0:t.length))return n;let a=new Set(t);return n.filter(e=>a.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(n){let t,r={id:e.id,error:{code:"number"==typeof(t=null==n?void 0:n.code)?t:-32603,message:n instanceof Error?n.message:String(n)}};return e.sessionId&&(r.sessionId=e.sessionId),r}}destroy(){var e,t,r,n,a;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==(n=this.unsubscribeAppAdapter)||n.call(this),this.unsubscribeAppAdapter=null,null==(a=this.appAdapter)||a.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 s9(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 s9(e,{consoleStore:this.options.preserveConsoleOnTargetChange?this.consoleStore:void 0})}createAppTargetAdapter(e){return new s9(e,{consoleStore:this.appConsoleStore})}subscribeAppAdapter(){var e;this.unsubscribeAppAdapter=(null==(e=this.appAdapter)?void 0:e.subscribe(e=>{"console"===e.type&&(this.emitNewConsoleEntries("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.emitNewConsoleEntries(),this.emit({method:"WSD.consoleUpdated"}))}setTarget(e){var t;if(this.target===e)return;let r=!!this.options.preserveConsoleOnTargetChange,n=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),n&&this.clearConsoleForTargetScopeChange(),this.emit({method:"DOM.documentUpdated"}),this.emitNewConsoleEntries(),this.emit({method:"WSD.consoleUpdated"})}handleConsoleChange(){this.emitNewConsoleEntries(),this.emit({method:"WSD.consoleUpdated"})}getAppAdapter(){var e,t,r,n,a,i;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==(n=this.appAdapter)||n.destroy(),this.appTarget=s,this.appAdapter=this.createAppTargetAdapter(s),this.subscribeAppAdapter(),this.loadAppSource(s),this.emit({method:"WSD.appConsoleUpdated"})),this.appAdapter):(null==(a=this.unsubscribeAppAdapter)||a.call(this),this.unsubscribeAppAdapter=null,null==(i=this.appAdapter)||i.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.emitNewConsoleEntriesForSession(e.sessionId),this.getAppAdapter(),this.emitNewConsoleEntriesForSession(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.emitNewConsoleEntries("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.emitNewConsoleEntries("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(),n=oI(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,n):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),n=this.nodeStore.resolveInspectorNodeId(r),a=oI(null==e?void 0:e.depth,1),i=this.getInspectorDocument(),s=n===oT?null:this.findInspectorNode(n),o=n===oT?i?[this.nodeStore.toCdpNode(i,oE(a),r)]:[]:(null==s?void 0:s.children.map(e=>this.nodeStore.toCdpNode(e,oE(a),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 n=Number(e),a=this.nodeStore.getInspectorNodeId(n);return r&&a&&this.materializeInspectorNodePath(r,a,t)?n:0})}}materializeInspectorNodePath(e,t,r){let n=oN(e,t);if(!n)return!1;let a=this.nodeStore.getCdpNodeId(oT);for(let t of(this.emit({method:"DOM.setChildNodes",params:{parentId:a,nodes:[this.nodeStore.toCdpNode(e,0,a)]}},r),this.emit({method:"DOM.childNodeCountUpdated",params:{nodeId:a,childNodeCount:1}},r),n.slice(0,-1))){let e=this.nodeStore.getCdpNodeId(t.id),n=t.children.map(t=>this.nodeStore.toCdpNode(t,0,e));this.emit({method:"DOM.setChildNodes",params:{parentId:e,nodes:n}},r),this.emit({method:"DOM.childNodeCountUpdated",params:{nodeId:e,childNodeCount:n.length}},r)}return!0}revealDocumentAfterUpdate(e,t,r){if(!(null==r?void 0:r.length))return;let n=this.findInspectorNodeBySignaturePath(e,r??null),a=n??this.findDocumentRevealNode(e);if(!a||!this.materializeInspectorNodePath(e,a.id,t))return;let i=this.nodeStore.getCdpNodeId(a.id),s=!!n||!(null==r?void 0:r.length);this.selectInspectorNode(a.id,{rememberPreferred:s}),s&&(this.pendingDocumentRevealSignaturePath=null),this.emit({method:"Overlay.nodeHighlightRequested",params:{nodeId:i}},t),this.emit({method:"Overlay.inspectNodeRequested",params:{backendNodeId:i}},t)}findDocumentRevealNode(e){let t=this.adapter.getSelectedNodeId();if(t){let r=oN(e,t);if(r)return r[r.length-1]}let r=this.findInspectorNodeBySignaturePath(e,this.selectedNodeSignaturePath);if(r)return r;let n=e;for(let e=0;e<3;e+=1){let e=n.children.find(e=>"element"===e.type);if(!e)break;n=e}return n}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?oN(t,e):null;if(r){let e=r.map(e=>({type:e.type,name:e.name,className:oS(e,"class"),id:oS(e,"id")}));return this.selectedNodeSignaturePath=e,e}return null}findInspectorNodeBySignaturePath(e,t){if(!(null==t?void 0:t.length)||!ox(e,t[0]))return null;let r=e;for(let e of t.slice(1)){let t=r.children.find(t=>ox(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),n=this.findInspectorNode(r),a=this.getInspectorDocument();return{node:r===oT&&a?this.nodeStore.toDocumentCdpNode(a):n?this.nodeStore.toCdpNode(n):null}}getAttributes(e){let t=this.findInspectorNode(this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId));return{attributes:t?ob(t):[]}}getOuterHTML(e){let t=this.nodeStore.resolveInspectorNodeId((null==e?void 0:e.nodeId)??(null==e?void 0:e.backendNodeId)),r=this.findInspectorNode(t),n=this.getInspectorDocument();return{outerHTML:t===oT&&n?oC(n):r?oC(r):""}}setAttributesAsText(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),n=String((null==e?void 0:e.text)??""),a="string"==typeof(null==e?void 0:e.name)?e.name:void 0,i=this.applyDomEdit(()=>this.adapter.setAttributesAsText(r,n,a));return this.emitDomMutations(i,t),{}}setAttributeValue(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),n=String((null==e?void 0:e.name)??""),a=String((null==e?void 0:e.value)??""),i=this.applyDomEdit(()=>this.adapter.setAttributeValue(r,n,a));return this.emitDomMutations(i,t),{}}removeAttribute(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),n=String((null==e?void 0:e.name)??""),a=this.applyDomEdit(()=>this.adapter.removeAttribute(r,n));return this.emitDomMutations(a,t),{}}setNodeValue(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),n=String((null==e?void 0:e.value)??""),a=this.applyDomEdit(()=>this.adapter.setNodeValue(r,n));return this.emitDomMutations(a,t),{}}setNodeName(e,t){let r=this.nodeStore.resolveInspectorNodeId(null==e?void 0:e.nodeId),n=String((null==e?void 0:e.name)??""),a=this.applyDomEdit(()=>this.adapter.setNodeName(r,n),!0);return this.emitDomMutations(a.mutations,t),{nodeId:a.nodeId?this.nodeStore.getCdpNodeId(a.nodeId):0}}setOuterHTML(e,t){let r=this.nodeStore.resolveInspectorNodeId((null==e?void 0:e.nodeId)??(null==e?void 0:e.backendNodeId)),n=String((null==e?void 0:e.outerHTML)??""),a=this.applyDomEdit(()=>this.adapter.setOuterHTML(r,n),!0);return this.emitDomMutations(a,t),{}}applyDomEdit(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=t?this.adapter.getDocument():null,n=r?this.createDomRootSnapshot(r):null,a=e(),i=Array.isArray(a)?a:a.mutations,s=i.filter(oq),o=null;return i.length>0&&s.length===i.length?o={type:"mutations",mutations:s}:i.length>0&&n&&(o=n),o&&this.rememberDomUndoEntry(o),a}createDomRootSnapshot(e){return{type:"rootSnapshot",rootHtml:"document"===e.type?ok(e):oC(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 n of r.removedNodeIds)this.emit({method:"DOM.childNodeRemoved",params:{parentNodeId:e,nodeId:this.nodeStore.getCdpNodeId(n)}},t);for(let n of r.insertedNodes)this.emit({method:"DOM.childNodeInserted",params:{parentNodeId:e,previousNodeId:n.previousNodeId?this.nodeStore.getCdpNodeId(n.previousNodeId):0,node:this.nodeStore.toCdpNode(n.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:oh(`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?oh(`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??""),n=of(String(e.text??"")),{id:a,kind:i}=og(t),s=this.adapter.getSelectedNodeId(),o="inline"===i?a:s,l=this.getDeclarationsForStyleSheet(t);"inline"===i?this.adapter.setInlineDeclarations(a,n):"rule"===i&&s&&this.adapter.setRuleDeclarations(s,a,n),r.push(this.getStylePayloadForStyleSheet(t,n)),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)??""),n=String((null==e?void 0:e.value)??"");return r&&this.adapter.setInlineDeclaration(t,r,n),{}}addRule(e){let t=String((null==e?void 0:e.ruleText)??""),r=this.getRuleSelectorText(t),n=of(t).map(e=>({...e,active:!0})),a=this.adapter.getSelectedNodeId(),i=a?this.adapter.addRule(a,r,n):null;return{rule:i?this.toCdpRulePayload(i):{origin:"inspector",selectorList:this.toSelectorList(r),style:oh("inspector:main",n)}}}setRuleSelector(e){let t=String((null==e?void 0:e.selector)??(null==e?void 0:e.text)??"").trim(),{id:r,kind:n}=og(String((null==e?void 0:e.styleSheetId)??"")),a=this.adapter.getSelectedNodeId(),i="rule"===n&&a?this.adapter.setRuleSelector(a,r,t):null;return{selectorList:this.toSelectorList((null==i?void 0:i.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 n=Object.getOwnPropertyDescriptor(e,r),a={name:r,configurable:(null==n?void 0:n.configurable)??!0,enumerable:(null==n?void 0:n.enumerable)??!0,isOwn:!0};return n&&"value"in n&&(a.value=oc(n.value,t),a.writable=n.writable),a})}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:oc(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.emitNewConsoleEntriesForSession(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:n,onNodeHighlightRequested:a,onNodeInspected:i}=e;t.classList.add("is-inspecting");let s=e=>{let t=r(e.clientX,e.clientY);t&&a(t)},o=()=>{n(null)},l=e=>{if(0!==e.button)return;let n=r(e.clientX,e.clientY);n&&(oR(e),function(e){let t=["mousedown","mouseup","pointerup","pointercancel","click","dblclick","auxclick","contextmenu"],r=[e,e.ownerDocument],n=e.ownerDocument.defaultView;n&&r.push(n);let a=null,i=()=>{for(let e of(null!==a&&(window.clearTimeout(a),a=null),r))for(let r of t)e.removeEventListener(r,s,!0)},s=e=>{oR(e),("click"===e.type||"dblclick"===e.type||"auxclick"===e.type)&&i()};for(let e of r)for(let r of t)e.addEventListener(r,s,!0);a=window.setTimeout(i,800)}(t),i(n))};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),n(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,n;let a=null==(r=(n=this.options).resolveTargetAtPoint)?void 0:r.call(n,e,t);a&&this.setTarget(a);let i=this.adapter.getNodeIdAtPoint(e,t),s=this.options.getRuntimeFrame();if(!i||!s)return this.options.onHighlightChange(null),null;let o=function(e,t){if(!e)return t;let r=(e,n)=>{let a=n??(or(e)?e.id:null);if(e.id===t)return a??e.id;let i=oa(e)||on(e)?null:a;for(let t of e.children){let e=r(t,i);if(e)return e}return null};return r(e,null)??t}(this.adapter.getDocument(),i);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(),n=String((null==e?void 0:e.value)??""),a="string"==typeof(null==e?void 0:e.ruleId)?e.ruleId:null;if(!r)throw Error("CSS property name is required");return a?this.adapter.setRuleDeclaration(t,a,r,n):this.adapter.setInlineDeclaration(t,r,n),{}}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 n=this.adapter.setOuterHTML(r.id,e.rootHtml);return 0!==n.length&&(this.emitDomMutations(n,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)),n=new Set(e.removed),a=[];for(let r of e.modified)t.has(r.name)||a.push(...this.adapter.removeAttribute(e.nodeId,r.name));for(let t of e.before)(r.has(t.name)||n.has(t.name))&&a.push(...this.adapter.setAttributeValue(e.nodeId,t.name,t.value));return a}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,n){var a;t&&JSON.stringify(r)!==JSON.stringify(n)&&((null==(a=this.pendingUndoEntry)?void 0:a.type)!=="style"||this.pendingUndoEntry.entry.styleSheetId!==e||this.pendingUndoEntry.entry.nodeId!==t)&&this.setPendingUndoEntry({type:"style",entry:{styleSheetId:e,nodeId:t,previousDeclarations:oU(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}=og(e.styleSheetId);this.isApplyingStyleEdit=!0;try{"inline"===r?this.adapter.setInlineDeclarations(t,oU(e.previousDeclarations)):"rule"===r&&this.adapter.setRuleDeclarations(e.nodeId,t,oU(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(),n=r?this.adapter.getNodeHighlight(t,r):null,a=(null==n?void 0:n.left)??0,i=(null==n?void 0:n.top)??0,s=(null==n?void 0:n.width)??0,o=(null==n?void 0:n.height)??0,l=[a,i,a+s,i,a+s,i+o,a,i+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=or(t);if(r){let n,a,i=on(t)?t:function e(t){let r=!(arguments.length>1)||void 0===arguments[1]||arguments[1];if(!r&&or(t))return null;if(oa(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:(n=oi(t),a=(function(e){var t;let r=null==(t=e.attributes.find(e=>e.name===sw))?void 0:t.value.split(/\s+/).filter(Boolean);if(!(null==r?void 0:r.length))return[];let n=e.children.find(e=>"element"===e.type);return n?oi(n).filter(e=>r.includes(e.name)):[]})(t).filter(e=>!n.some(t=>t.name===e.name)),[...n,...a]),children:i?i.children.map(t=>e(t)):[]}}let n=t.children.map(t=>e(t));return n.some((e,r)=>e!==t.children[r])?{...t,children:n}: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,n;let{id:a,kind:i}=og(e),s=t.map(e=>({name:e.name,value:e.value,priority:e.priority,active:e.active}));if("inline"===i)return oh(e,(null==(r=this.adapter.getMatchedStyles(a))?void 0:r.inlineStyle.declarations)??s);if("rule"===i){let t=this.adapter.getSelectedNodeId(),r=t?null==(n=this.adapter.getMatchedStyles(t))?void 0:n.matchedRules.find(e=>e.id===a):null;return oh(e,(null==r?void 0:r.declarations)??s)}return oh(e,s)}getDeclarationsForStyleSheet(e){var t,r;let{id:n,kind:a}=og(e);if("inline"===a)return oU((null==(t=this.adapter.getMatchedStyles(n))?void 0:t.inlineStyle.declarations)??[]);if("rule"===a){let e=this.adapter.getSelectedNodeId(),t=e?null==(r=this.adapter.getMatchedStyles(e))?void 0:r.matchedRules.find(e=>e.id===n):null;return oU((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:om(0,e.length)}],text:e}}toCdpRulePayload(e){let t=`rule:${e.id}`,r=oh(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:op(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 n=r.get(t)??new Set;return r.set(t,n),n}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 oe(e);t===this.sourceLoadId&&(r&&this.sourceScriptsById.set(this.getScriptId(r.url),r),this.emitSourceScriptsForEnabledSessions())}async loadAppSource(e){let t=await oe(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 n;let a=this.getScriptId(e),i=this.getParsedScriptIds(t);if(!this.debuggerEnabledSessions.has(t)||i.has(a))return;i.add(a);let s=(null==r?void 0:r.content.split("\n"))??[""];this.emit({method:"Debugger.scriptParsed",params:{scriptId:a,url:r?"":e,startLine:0,startColumn:0,endLine:r?s.length-1:1,endColumn:r?(null==(n=s.at(-1))?void 0:n.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),n=1;n<t;n++)r[n-1]=arguments[n];let a=r.length>0?r[0]:this.activeSessionId,i=a?{...e,sessionId:a}:e;for(let e of this.listeners)e(i)}emitRuntimeExecutionContext(e){this.emit({method:"Runtime.executionContextCreated",params:{context:{id:1,origin:"wsd://runtime",name:"Doubao",auxData:{isDefault:!0,frameId:"wsd-main-frame"}}}},e)}emitNewConsoleEntries(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"current";for(let t of this.runtimeEnabledSessions)this.emitNewConsoleEntriesForSession(t,e)}emitNewConsoleEntriesForSession(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(),n=this.getKnownConsoleEntryIds(e,t);for(let t of r){var a;if(n.has(t.id)||(n.add(t.id),"host"===t.source))continue;let r=this.toCdpStackTrace(t.stackTrace),i={type:"warn"===(a=t.level)?"warning":"eval"===a?"log":a,args:op(t,this.remoteObjectStore),executionContextId:1,timestamp:t.timestamp};r&&(i.stackTrace=r),this.emit({method:"Runtime.consoleAPICalled",params:i},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 oB(e){let{onReopen:t}=e;return(0,i.jsxs)("div",{className:"wsd-runtime-empty",children:[(0,i.jsx)("div",{"aria-hidden":"true",className:"wsd-runtime-empty-icon"}),(0,i.jsx)("div",{className:"wsd-runtime-empty-title",children:"页面已关闭"}),(0,i.jsx)("div",{className:"wsd-runtime-empty-description",children:"当前页面栈为空,可从调试面板重新选择页面渲染。"}),(0,i.jsx)("button",{className:"wsd-runtime-empty-action",onClick:t,type:"button",children:"重新打开当前页面"})]})}let oF=new Set(["log","info","warn","error","debug"]);function oW(e){return"AppletJSModule"===e||"LynxConsoleModule"===e}function oH(e,t,r){if("log"!==e)return null;let n="object"!=typeof t||null===t?null:"string"==typeof t.message||Array.isArray(t.args)?{level:oF.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 n?oW(r)?n:null:oW(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 oz{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):sl(this.current,e)}flush(){if(this.current)for(let e of this.runtimeConsoleEvents.splice(0))sl(this.current,e)}}let oV=new Set(["doubao.navigateTo","doubao.redirectTo","doubao.reLaunch","doubao.navigateBack","doubao.exitApp","doubao.close"]);function oG(e){"function"==typeof queueMicrotask?queueMicrotask(e):Promise.resolve().then(e)}class oJ{container;fileSystemNamespace;nativeModulesCallHandler;webSdkDebugger;onExitApp;onError;apiEnvironment;previewTarget=new oz;appPreviewTarget=new oz;pageRoutesByTarget=new WeakMap;targetObserver=null;runtime=null;runtimeManifestUrl=null;lastRenderOptions=null;pageDevice=nL["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.onError=e.onError,this.apiEnvironment=e.apiEnvironment??se(),"u">typeof MutationObserver&&(this.targetObserver=new MutationObserver(this.handleRuntimeContainerMutation),this.targetObserver.observe(this.container,{childList:!0}))}render(){var e,t;let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=this.webSdkDebugger.getState(),a=!r.entry&&(null==(e=n.pageSelection)?void 0:e.routeUrl)?ti({url:n.pageSelection.routeUrl},n.manifest):void 0,i=(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,r),s=r.device??nL["0"];this.pageDevice=s;let o=(null==a?void 0:a.initData)??r.initData??{},l=a?{...r.globalProps,...a.globalProps}:r.globalProps,d=this.getRuntime(n),u=a?null==(t=n.pageSelection)?void 0:t.routeUrl:void 0,c=i.path;if(u){let e=u.indexOf("?");c+=e<0?"":u.slice(e)}this.lastRenderOptions=r,this.isRuntimeTargetChanging=!0,this.deferredPageRoute={path:i.path,url:c};try{let e=d.replacePage({entry:i,initData:o,globalProps:l,pageCapsule:r.pageCapsule??{statusBarHeight:s.statusBarHeight}});return this.bindPageTarget(e.element,{path:i.path,url:c}),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?(null==(t=this.pageRoutesByTarget.get(r.element))?void 0:t.url)??r.route:null}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(){var e;2>this.getPageStackSize()||(null==(e=this.runtime)||e.popPage(),this.syncCurrentRuntimeTarget())}reopenCurrentPage(){try{this.render(this.lastRenderOptions??{})}catch(t){var e;null==(e=this.onError)||e.call(this,t,new Event("error"))}}restartRuntime(){var e,t;this.previewTarget.reset(),this.appPreviewTarget.reset();try{null==(e=this.runtime)||e.restart()}catch(e){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()}getRuntime(e){let t=e.manifestUrl;if(!this.runtime){let r={container:this.container,manifest:e.manifest,manifestUrl:t,apiRegistry:this.apiEnvironment.apiRegistry,fileSystemNamespace:this.fileSystemNamespace,nativeModulesCallHandler:this.handleNativeModulesCall,onError:this.onError,getRuntimeGlobalProps:()=>(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nL["0"],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.key.startsWith("iphone")||e.key.startsWith("ipad");return{debugger:"web-sdk",density:e.density,screenWidth:e.width,screenHeight:e.height,containerWidth:e.width,containerHeight:e.height,statusBarHeight:e.statusBarHeight,safeArea:{marginTop:e.safeArea.top,marginBottom:e.safeArea.bottom,marginLeft:e.safeArea.left,marginRight:e.safeArea.right},topHeight:e.safeArea.top,bottomHeight:e.safeArea.bottom,devicePlatform:r?"iOS":"Android",deviceBrand:r?"Apple":"Google",deviceModel:e.label,screenOrientation:"portrait",...t,platform:nq}})(this.pageDevice),runtimeHost:{...this.apiEnvironment.runtimeHost,mountRuntimeEmptyState:e=>{var t;let r;return t=()=>this.reopenCurrentPage(),(r=(0,tk.H)(e)).render((0,i.jsx)(oB,{onReopen:t})),()=>r.unmount()}}};return this.runtime=new tC(r),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,n)=>{var a;if((null==n?void 0:n.containerType)==="APP"&&function(e,t,r){if("invokeCdp"!==e||"LynxDevToolSetModule"!==r||"string"!=typeof t)return!1;try{var n;return(null==(n=JSON.parse(t))?void 0:n.method)==="Page.reload"}catch{return!1}}(e,t,r))return oG(()=>this.restartRuntime()),JSON.stringify({result:{}});let i=function(e,t,r){if("AppletBridgeModule"===r&&"postMessage"===e&&"object"==typeof t&&null!==t&&"call"===t.type&&"string"==typeof t.name&&oV.has(t.name))return t.name}(e,t,r);i&&(this.navigationSourceTarget=this.previewTarget.current,this.deferredPageRoute=this.resolveNavigationPageRoute(t),this.scheduleRuntimeTargetSync("doubao.exitApp"===i?this.onExitApp:void 0));let s=oH(e,t,r);if(s){if((null==n?void 0:n.containerType)==="APP")this.syncAppRuntimeTarget(n.element),this.appPreviewTarget.dispatch({...s,label:"app"});else{let e=this.getRuntimeConsolePagePath(n);this.previewTarget.dispatch(e?{...s,pagePath:e}:s,this.isRuntimeTargetChanging)}return}return null==(a=this.nativeModulesCallHandler)?void 0:a.call(this,e,t,r,n)};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()};oG(()=>{(this.syncCurrentRuntimeTarget(),this.previewTarget.current!==t)?r():oG(()=>{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,n=r!==this.navigationSourceTarget?this.deferredPageRoute:void 0;(r&&this.bindPageTarget(r,{path:(null==n?void 0:n.path)??this.getCurrentPagePath(),url:null==n?void 0:n.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),n=t.path??(null==r?void 0:r.path),a=t.url??(null==r?void 0:r.url)??n;(n||a)&&this.pageRoutesByTarget.set(e,{path:n,url:a})}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 n=r.indexOf("?"),a=n<0?"":r.slice(n);try{let e=ti({url:r},this.webSdkDebugger.getState().manifest).entry;return{path:e.path,url:`${e.path}${a}`}}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,n,a;if((null==e?void 0:e.containerType)!=="PAGE")return;let i=(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==(a=this.runtime)||null==(n=a.currentPage)?void 0:n.element,{path:i}),i}}class oK{container;fileSystemNamespace;nativeModulesCallHandler;webSdkDebugger;onError;apiEnvironment;previewTarget=new oz;widget=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??se()}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),n=e.viewport??nO,a=tA(e.initData??{}),i=e.globalProps??n$(n);this.clear(),this.widget=new tE({appId:t.manifest.appId,apiRegistry:this.apiEnvironment.apiRegistry,container:this.container,fileSystemNamespace:this.fileSystemNamespace,globalProps:i,initData:a,nativeModulesCallHandler:this.handleNativeModulesCall,onError:this.onError,runtimeHost:this.apiEnvironment.runtimeHost,widgetId:r});let s=await this.widget.render();return this.previewTarget.set(s),s}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;null==(e=this.widget)||e.destroy(),this.widget=null,this.container.replaceChildren()}handleNativeModulesCall=(e,t,r,n)=>{var a;let i=oH(e,t,r);return i?void this.previewTarget.dispatch(i):null==(a=this.nativeModulesCallHandler)?void 0:a.call(this,e,t,r,n)}}var oX=e=>(0,i.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,i.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 oQ(e){let t=(0,rc.useRef)(e);t.current=e;let r=(0,rc.useRef)();return r.current??=function(){for(var e=arguments.length,r=Array(e),n=0;n<e;n++)r[n]=arguments[n];return t.current(...r)},r.current}let oY={revision:0,phase:"idle",canCancel:!1,canRetry:!1},oZ=(0,rc.createContext)({});function o0(e){let{capability:t,children:r,getAppIdentity:n}=e;return(0,i.jsx)(oZ.Provider,{value:{capability:t,getAppIdentity:n},children:r})}async function o1(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 o2(){var e,t,r,n,a,s,o,l;let{capability:d,getAppIdentity:u}=(0,rc.useContext)(oZ),[c,p]=(0,rc.useState)(!1),[m,h]=(0,rc.useState)(oY),[g,f]=(0,rc.useState)(),[v,y]=(0,rc.useState)("modern"),[_,b]=(0,rc.useState)(),w=(0,rc.useId)(),S=(0,rc.useRef)(!1),x=(0,rc.useRef)(oY),I=(0,rc.useRef)(null),E=oQ(e=>{e.revision<x.current.revision||(x.current=e,h(e))}),C=oQ(async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!d)throw Error("真机调试能力不可用");return o1(await fetch(e,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","X-DBX-Real-Device-Token":d.accessToken},body:JSON.stringify(t)}))}),k=oQ(async()=>{if(d)try{let e=await C(d.stateEndpoint);E(e),f(void 0)}catch(e){f(e instanceof Error?e.message:String(e))}}),N=oQ(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);E(e)}catch(e){f(e instanceof Error?e.message:String(e))}}}),T=oQ(async()=>{let e=x.current;if(d&&e.operationId&&e.canCancel&&"web"===e.owner)try{let t=await C(d.cancelEndpoint,{operationId:e.operationId});E(t)}catch{}}),R=oQ(()=>{S.current=!1,p(!1),T()});if((0,rc.useEffect)(()=>{if(!c||!d)return;k();let e=window.setInterval(()=>void k(),d.pollIntervalMs);return()=>window.clearInterval(e)},[d,c,k]),(0,rc.useEffect)(()=>{if(!c)return;let e=e=>{var t;(null==(t=I.current)?void 0:t.contains(e.target))||R()},t=e=>{"Escape"===e.key&&R()};return window.addEventListener("pointerdown",e),window.addEventListener("keydown",t),()=>{window.removeEventListener("pointerdown",e),window.removeEventListener("keydown",t)}},[R,c]),(0,rc.useEffect)(()=>{m.qr&&"modern"===v&&!m.qr.modernAvailable&&m.qr.legacyAvailable&&y("legacy")},[v,m.qr]),(0,rc.useEffect)(()=>{let e=!1;return c&&d&&m.operationId&&"waiting_for_scan"===m.phase&&m.qr&&("modern"===v?m.qr.modernAvailable:m.qr.legacyAvailable)?(b(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:m.operationId,kind:v})}).then(e=>{if(!e.ok)throw Error("二维码暂不可用");return e.blob()}).then(t=>{e||b(URL.createObjectURL(t))}).catch(t=>{e||f(t instanceof Error?t.message:String(t))}),()=>{e=!0}):void b(void 0)},[d,c,v,m.connectionMode,m.operationId,m.phase,null==(e=m.qr)?void 0:e.legacyAvailable,null==(t=m.qr)?void 0:t.modernAvailable,null==(r=m.qr)?void 0:r.revision]),(0,rc.useEffect)(()=>{if(_)return()=>URL.revokeObjectURL(_)},[_]),!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"准备开始真机调试"}}(m),A=null==(n=m.progress)?void 0:n.percentage,P="number"==typeof A&&"downloading"===m.phase,j="waiting_for_scan"===m.phase&&!!m.qr,L=!!_&&j,D="waiting_for_scan"!==m.phase&&"connected"!==m.phase,O="failed"===m.phase||"timed_out"===m.phase||!!g,U=O?"二维码暂不可用":"connected"===m.phase?"连接成功,请勿重复扫码":"准备完成后可扫码",q="existing_client"===m.connectionMode?"已复用当前连接,无需扫码":"扫码成功",$=null==u?void 0:u(),B=[null==$||null==(a=$.appName)?void 0:a.trim(),null==$||null==(s=$.appKey)?void 0:s.trim()].filter(Boolean).join(" · ");return(0,i.jsxs)("div",{className:"wsd-physical-device-wrapper",ref:I,children:[(0,i.jsx)("button",{"aria-expanded":c,"aria-haspopup":"dialog","aria-label":"真机调试","aria-pressed":c,"aria-describedby":w,className:(0,e6.$)("wsd-device-toolbar-icon",c&&"is-active"),onClick:()=>{c?R():(y("modern"),S.current=!0,p(!0),N())},type:"button",children:(0,i.jsx)(oX,{"aria-hidden":"true"})}),(0,i.jsx)("span",{className:"wsd-physical-device-tooltip",id:w,role:"tooltip",children:"真机调试"}),c?(0,i.jsxs)("dialog",{"aria-label":"真机调试",className:"wsd-physical-device-popover",open:!0,children:[(0,i.jsxs)("header",{className:"wsd-physical-device-header",children:[(0,i.jsx)("h2",{children:"真机调试"}),(0,i.jsx)("p",{children:"使用已登录的客户端扫码,创建新的真机调试对话"})]}),(0,i.jsxs)("div",{className:"wsd-physical-device-content",children:[(0,i.jsxs)("div",{"aria-label":"客户端版本",className:"wsd-physical-device-client-tabs",role:"tablist",children:[(0,i.jsx)("button",{"aria-selected":"modern"===v,className:(0,e6.$)("modern"===v&&"is-active"),disabled:!j||!(null==(o=m.qr)?void 0:o.modernAvailable),onClick:()=>y("modern"),role:"tab",type:"button",children:"新版客户端"}),(0,i.jsx)("button",{"aria-selected":"legacy"===v,className:(0,e6.$)("legacy"===v&&"is-active"),disabled:!j||!(null==(l=m.qr)?void 0:l.legacyAvailable),onClick:()=>y("legacy"),role:"tab",type:"button",children:"旧版客户端"})]}),(0,i.jsx)("div",{className:(0,e6.$)("wsd-physical-device-qr",!L&&"is-locked"),children:L&&_?(0,i.jsx)("img",{alt:"modern"===v?"新版客户端真机调试二维码":"旧版客户端真机调试二维码",src:_}):(0,i.jsx)("div",{className:"wsd-physical-device-placeholder",children:(0,i.jsx)("strong",{children:U})})})]}),"waiting_for_scan"===m.phase?(0,i.jsx)("div",{className:"wsd-physical-device-notice",children:"使用豆包 14.70 以上版本扫码"}):"connected"===m.phase?(0,i.jsx)("div",{className:"wsd-physical-device-notice is-success",children:q}):null,P?(0,i.jsx)("div",{className:"wsd-physical-device-progress","aria-label":`下载进度 ${Math.round(A)}%`,children:(0,i.jsx)("span",{style:{width:`${Math.max(0,Math.min(100,A))}%`}})}):null,D?(0,i.jsxs)("div",{className:"wsd-physical-device-details",children:[B?(0,i.jsx)("div",{"aria-label":"小程序信息",className:"wsd-physical-device-app-identity",title:B,children:B}):null,(0,i.jsxs)("div",{className:(0,e6.$)("wsd-physical-device-status",O&&"is-error"),children:[["preparing","downloading","installing_tool","reusing_client","waiting_for_scan","waiting_for_install","launching_tool"].includes(m.phase)&&!P?(0,i.jsx)("span",{className:"wsd-physical-device-spinner","aria-hidden":"true"}):null,(0,i.jsx)("div",{children:(0,i.jsx)("strong",{children:g||M})})]})]}):null,(m.canRetry||g)&&O?(0,i.jsx)("button",{className:"wsd-physical-device-retry",onClick:()=>void N(),type:"button",children:"重新尝试"}):null]}):null]})}let o3=(0,rc.createContext)(null);function o4(e){let t=function(e){let t=(0,rc.useContext)(o3),r=e??t;if(!r)throw Error("WebSdkDebuggerProvider is missing");return r}(e),r=(0,rc.useCallback)(e=>t.subscribe(e),[t]),n=(0,rc.useCallback)(()=>t.getState(),[t]);return(0,rc.useSyncExternalStore)(r,n,n)}function o5(e){let{fallbackName:t,selector:r}=e;return r?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("span",{className:"wsd-runtime-highlight-selector-tag",children:r.tagName}),r.id?(0,i.jsxs)("span",{className:"wsd-runtime-highlight-selector-id",children:["#",r.id]}):null,r.classNames.map(e=>(0,i.jsxs)("span",{className:"wsd-runtime-highlight-selector-class",children:[".",e]},e))]}):(0,i.jsx)("span",{className:"wsd-runtime-highlight-selector-tag",children:t??"element"})}function o8(e){let{focusable:t}=e;return t?(0,i.jsx)("span",{children:"true"}):(0,i.jsx)("span",{"aria-label":"not focusable",className:"wsd-runtime-highlight-not-focusable"})}function o6(e){var t,r,n,a,s;let{highlightRect:o,overlay:l,runtimeFrameRef:d,runtimeFrameScaleBoxRef:u,runtimeScaleMode:c,runtimeShellRef:p,runtimeStyle:m,runtimeTargetRef:h}=e,g=(0,rc.useRef)(null),[f,v]=(0,rc.useState)(null),y=function(e,t){let r=e[t];if("number"==typeof r)return r;if("string"!=typeof r)return null;let n=Number.parseFloat(r);return Number.isFinite(n)?n:null}(m,"--wsd-runtime-height"),_=o&&f&&null!==y&&o.top+o.height+f.gap+f.height>y&&o.top>f.gap+f.height,b=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==(n=o.boxModel)?void 0:n.content.top)??0}px`,"--wsd-highlight-content-width":`${(null==(a=o.boxModel)?void 0:a.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,w=oQ(e=>{let t=Number.parseFloat(getComputedStyle(e).getPropertyValue("--wsd-highlight-popover-gap")),r={gap:Number.isFinite(t)?t:0,height:e.offsetHeight};v(e=>(null==e?void 0:e.gap)===r.gap&&e.height===r.height?e:r)}),S=oQ(e=>{var t;if(null==(t=g.current)||t.disconnect(),g.current=null,!e||(w(e),"u"<typeof ResizeObserver))return;let r=new ResizeObserver(()=>w(e));r.observe(e),g.current=r});return(0,i.jsx)("section",{className:"wsd-device-preview","data-scale-mode":c,ref:p,children:(0,i.jsx)("div",{className:"wsd-device-preview-scale-box",ref:u,style:m,children:(0,i.jsxs)("div",{className:"wsd-device-preview-frame",ref:d,children:[h?(0,i.jsx)("div",{className:"wsd-runtime-target",ref:h}):null,o?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("div",{"aria-hidden":"true",className:"wsd-runtime-highlight",style:b,children:(0,i.jsx)("div",{className:"wsd-runtime-highlight-content-frame"})}),(0,i.jsxs)("div",{"aria-hidden":"true",className:(0,e6.$)("wsd-runtime-highlight-popover",_&&"is-above"),ref:S,style:b,children:[(0,i.jsxs)("div",{className:"wsd-runtime-highlight-header",children:[(0,i.jsx)("span",{"aria-hidden":"true",className:"wsd-runtime-highlight-node-icon"}),(0,i.jsx)("strong",{className:"wsd-runtime-highlight-selector",children:(0,i.jsx)(o5,{fallbackName:o.nodeName,selector:o.selector})}),(0,i.jsx)("span",{className:"wsd-runtime-highlight-dimensions",children:o.dimensions??`${o.width} \xd7 ${o.height}`})]}),(null==(s=o.styles)?void 0:s.length)?(0,i.jsx)("dl",{className:"wsd-runtime-highlight-details",children:o.styles.map(e=>(0,i.jsxs)("div",{className:"wsd-runtime-highlight-detail",children:[(0,i.jsx)("dt",{children:e.name}),(0,i.jsxs)("dd",{children:[e.swatch?(0,i.jsx)("span",{className:"wsd-runtime-highlight-swatch",style:{backgroundColor:e.swatch}}):null,(0,i.jsx)("span",{children:e.value})]})]},e.name))}):null,o.accessibility?(0,i.jsxs)("section",{className:"wsd-runtime-highlight-accessibility",children:[(0,i.jsx)("div",{className:"wsd-runtime-highlight-section-title",children:(0,i.jsx)("span",{children:"ACCESSIBILITY"})}),(0,i.jsxs)("dl",{className:"wsd-runtime-highlight-details",children:[(0,i.jsxs)("div",{className:"wsd-runtime-highlight-detail",children:[(0,i.jsx)("dt",{children:"Name"}),(0,i.jsx)("dd",{children:o.accessibility.name})]}),(0,i.jsxs)("div",{className:"wsd-runtime-highlight-detail",children:[(0,i.jsx)("dt",{children:"Role"}),(0,i.jsx)("dd",{children:o.accessibility.role})]}),(0,i.jsxs)("div",{className:"wsd-runtime-highlight-detail",children:[(0,i.jsx)("dt",{children:"Keyboard-focusable"}),(0,i.jsx)("dd",{children:(0,i.jsx)(o8,{focusable:o.accessibility.keyboardFocusable})})]})]})]}):null]})]}):null,l]})})})}function o7(e){let t,r,n,{cashier:a,onCancel:s,onConfirm:o}=e,[l,d]=(0,rc.useState)(!1),[u,c]=(0,rc.useState)(""),[p,m]=(0,rc.useState)(a.paymentTypes[0].id),h=a.paymentTypes.find(e=>{let{id:t}=e;return t===p})||a.paymentTypes[0],g=a.paymentTypes.length>1,f=async()=>{if(!l){d(!0),c("");try{await o(p)}catch(e){d(!1),c(ih(e))}}};return(0,i.jsxs)("div",{className:"wsd-simulator-overlay-layer wsd-sandbox-cashier-layer",children:[(0,i.jsx)("div",{"aria-hidden":"true",className:"wsd-simulator-overlay-backdrop wsd-sandbox-cashier-backdrop"}),(0,i.jsxs)("dialog",{"aria-label":"支付收银台","aria-modal":"true",className:"wsd-sandbox-cashier",open:!0,children:[(0,i.jsx)("button",{"aria-label":"关闭收银台",className:"wsd-sandbox-cashier-close",disabled:l,onClick:s,type:"button",children:"×"}),(0,i.jsx)("section",{className:"wsd-sandbox-cashier-amount",children:(0,i.jsx)("strong",{children:(r=(t=a.totalAmount.replace(/^0+(?=\d)/,"").padStart(3,"0")).slice(0,-2)||"0",n=t.slice(-2),`\xa5${r.replace(/\B(?=(\d{3})+(?!\d))/g,",")}.${n}`)})}),(0,i.jsxs)("section",{className:"wsd-sandbox-cashier-payment",children:[(0,i.jsx)("h2",{children:"支付方式"}),g?(0,i.jsx)("div",{className:"wsd-sandbox-cashier-payment-options",children:a.paymentTypes.map(e=>{let t=e.id===p;return(0,i.jsxs)("button",{"aria-pressed":t,className:"wsd-sandbox-cashier-payment-option",disabled:l,onClick:()=>{m(e.id)},type:"button",children:[(0,i.jsx)("span",{children:e.name}),t?(0,i.jsx)("span",{"aria-hidden":"true",children:"✓"}):null]},e.id)})}):(0,i.jsx)("div",{className:"wsd-sandbox-cashier-payment-trigger is-static",children:h.name}),u?(0,i.jsxs)("p",{className:"wsd-sandbox-cashier-error",role:"alert",children:["支付失败,请重试:",u]}):null]}),(0,i.jsx)("footer",{className:"wsd-sandbox-cashier-actions",children:(0,i.jsx)("button",{"aria-busy":l,className:"wsd-sandbox-cashier-button",disabled:l,onClick:()=>void f(),type:"button",children:l?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("svg",{"aria-hidden":"true",className:"wsd-sandbox-cashier-spinner",viewBox:"0 0 16 16",children:[(0,i.jsx)("circle",{className:"wsd-sandbox-cashier-spinner-track",cx:"8",cy:"8",fill:"none",r:"6",strokeWidth:"2"}),(0,i.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 o9(){let[e,t]=(0,rc.useState)(),r=(0,rc.useRef)(null),n=(0,rc.useRef)(null),a=(0,rc.useRef)(!1),i=oQ((e,a)=>r.current?Promise.reject(Error("Sandbox cashier is already open")):new Promise(i=>{r.current=i,n.current=a,t(e)})),s=oQ(e=>{let a=r.current;a&&(r.current=null,n.current=null,t(void 0),a(e))}),o=oQ(()=>{a.current||s(!1)}),l=oQ(async e=>{let t=n.current;if(!t)throw Error("Sandbox cashier is unavailable");if(!a.current){a.current=!0;try{await t(e),s(!0)}finally{a.current=!1}}});return(0,rc.useEffect)(()=>()=>{let e=r.current;r.current=null,n.current=null,a.current=!1,null==e||e(!1)},[]),{cashier:e,cancelCashier:o,confirmCashier:l,showCashier:i}}r(35336);let le=new WeakMap;async function lt(e,t,r){le.set(e,t);try{await e.sendSimulatorQuery(r)}finally{le.get(e)===t&&le.delete(e)}}function lr(e,t){let r=le.get(e);if(r&&(!t||r===t))return le.delete(e),e.cancelSimulatorQuery(),r}var ln=e=>(0,i.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:15,height:15,fill:"none",viewBox:"0 0 15 15",...e,children:[(0,i.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,i.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 la(){return(0,i.jsxs)("div",{className:"wsd-doubao-status-bar","aria-hidden":"true",children:[(0,i.jsx)("span",{className:"wsd-doubao-status-time",children:"9:41"}),(0,i.jsx)("span",{className:"wsd-doubao-status-indicators"})]})}function li(e){let{className:t,fallback:r,src:n}=e,[a,s]=(0,rc.useState)(!1);return(0,rc.useEffect)(()=>{s(!1)},[n]),(0,i.jsx)("span",{className:`${t}-box`,"aria-hidden":"true",children:n&&!a?(0,i.jsx)("img",{alt:"",className:t,onError:()=>s(!0),src:n}):(0,i.jsx)("span",{className:`${t}-fallback`,children:(null==r?void 0:r.trim().slice(0,1))||"服"})})}function ls(e){let t=Number(e);if(!Number.isFinite(t))return;let r=new Date(t);return Number.isFinite(r.getTime())?r:void 0}function lo(e){let{notices:t,onAction:r,onBack:n,status:a}=e;return(0,i.jsxs)("section",{"aria-label":"服务通知",className:"wsd-service-notice-panel",children:[(0,i.jsxs)("header",{className:"wsd-service-notice-chrome",children:[(0,i.jsx)(la,{}),(0,i.jsxs)("div",{className:"wsd-service-notice-title-bar",children:[(0,i.jsx)("button",{"aria-label":"返回对话",className:"wsd-service-notice-nav-button is-back",onClick:n,type:"button",children:(0,i.jsx)("span",{"aria-hidden":"true"})}),(0,i.jsx)("h1",{children:"服务通知"}),(0,i.jsx)("button",{"aria-label":"服务通知设置",className:"wsd-service-notice-nav-button is-settings",type:"button",children:(0,i.jsx)(ln,{"aria-hidden":"true"})})]})]}),(0,i.jsx)("div",{className:"wsd-service-notice-list",children:"loading"===a&&0===t.length?(0,i.jsx)("p",{className:"wsd-service-notice-empty",children:"正在加载服务通知..."}):t.length>0?t.map(e=>{let t=e.title||"服务通知",n=ls(e.created_at_ms),a=e.redirect_url;return(null==a?void 0:a.startsWith("sslocal://"))&&(a=""),(0,i.jsxs)("div",{className:"wsd-service-notice-item",children:[(0,i.jsx)("time",{dateTime:null==n?void 0:n.toISOString(),children:function(e){let t=ls(e);if(!t)return"";let r=new Date,n=new Date(r.getFullYear(),r.getMonth(),r.getDate()).getTime(),a=new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime(),i=new Intl.DateTimeFormat("zh-CN",{hour:"2-digit",hour12:!1,minute:"2-digit"}).format(t);return a===n?i:a===n-864e5?`昨天 ${i}`:`${t.getMonth()+1}月${t.getDate()}日 ${i}`}(e.created_at_ms)}),(0,i.jsxs)("article",{"aria-label":a?`${t},查看详情`:void 0,className:`wsd-service-notice-card${a?" is-clickable":""}`,onClick:()=>{a&&(null==r||r(a))},onKeyDown:e=>{a&&("Enter"===e.key||" "===e.key)&&(e.preventDefault(),null==r||r(a))},role:a?"link":void 0,tabIndex:a?0:void 0,children:[(0,i.jsxs)("div",{className:"wsd-service-notice-app",children:[(0,i.jsx)(li,{className:"wsd-service-notice-icon",fallback:e.app_name,src:e.app_icon_url}),(0,i.jsx)("span",{children:e.app_name||"智能服务"})]}),(0,i.jsxs)("div",{className:"wsd-service-notice-body",children:[(0,i.jsx)("h2",{children:t}),e.fields.length>0?(0,i.jsx)("dl",{children:e.fields.map((e,t)=>(0,i.jsxs)("div",{children:[(0,i.jsx)("dt",{children:e.name}),(0,i.jsx)("dd",{children:e.value})]},`${e.name}-${t}`))}):e.brief?(0,i.jsx)("p",{children:e.brief}):null]})]})]},e.notice_id)}):(0,i.jsx)("p",{className:"wsd-service-notice-empty",children:"暂无服务通知"})})]})}let ll=new Set([1,2,3]);function ld(e){return e.filter(e=>1!==e.display_status&&ll.has(e.status))}function lu(e){let{onAction:t,onClose:r,onRemove:n,removingTaskIds:a,tasks:s}=e,o=ld(s);async function l(e){var r,a;let i=null==(r=e.remove_action)?void 0:r.confirm;(null==i||!i.need_confirm||window.confirm([i.title||"移除任务",i.content||"确定要移除这个任务吗?"].join("\n")))&&((null==(a=e.remove_action)?void 0:a.target)&&await (null==t?void 0:t(e.remove_action.target)),await n(e.task_id))}return((0,rc.useEffect)(()=>{let e=e=>{"Escape"===e.key&&r()};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[r]),(0,rc.useEffect)(()=>{0===o.length&&r()},[o.length,r]),0===o.length)?null:(0,i.jsxs)("div",{className:"wsd-sandbox-task-overlay-layer",children:[(0,i.jsx)("button",{"aria-label":"关闭进行中的任务",className:"wsd-sandbox-task-overlay-backdrop",onClick:r,type:"button"}),(0,i.jsx)("dialog",{"aria-label":"进行中的任务","aria-modal":"true",className:"wsd-sandbox-task-overlay",open:!0,children:(0,i.jsx)("div",{className:"wsd-sandbox-task-list",children:o.map(e=>{var r,n,s,o,d,u;let c=(null==(r=e.display_data)?void 0:r.title)||"未命名任务",p=(null==(n=e.display_data)?void 0:n.sub_title)||(null==(s=e.progress)?void 0:s.text),m=null==(o=e.primary_action)?void 0:o.target,h=a.has(e.task_id);return(0,i.jsxs)("article",{"aria-label":m?`${c},${(null==(d=e.primary_action)?void 0:d.text)||"查看详情"}`:void 0,className:(0,e6.A)("wsd-sandbox-task-card",m&&"is-clickable"),onClick:()=>{m&&(null==t||t(m))},onKeyDown:e=>{m&&("Enter"===e.key||" "===e.key)&&(e.preventDefault(),null==t||t(m))},role:m?"button":void 0,tabIndex:m?0:void 0,children:[(0,i.jsx)(li,{className:"wsd-sandbox-task-icon",fallback:c,src:null==(u=e.display_data)?void 0:u.icon_url}),(0,i.jsxs)("span",{className:"wsd-sandbox-task-copy",children:[(0,i.jsx)("strong",{children:c}),p?(0,i.jsx)("span",{children:p}):null]}),(0,i.jsx)("button",{"aria-label":`移除任务:${c}`,className:"wsd-sandbox-task-remove",disabled:h,onClick:t=>{t.stopPropagation(),l(e)},type:"button",children:(0,i.jsx)("span",{"aria-hidden":"true"})})]},e.task_id)})})})]})}let lc={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:[]},lp=(0,rc.createContext)(lc),lm={logs:[],updatedAtMs:0};function lh(){return{eventSequence:0,generation:0,instanceId:"",simulatorEventSequence:0}}function lg(e,t){try{let r=BigInt(e),n=BigInt(t);return r===n?0:r>n?1:-1}catch{return String(e).localeCompare(String(t),void 0,{numeric:!0})}}function lf(e){if(e8(e)&&"string"==typeof e.id&&e8(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:e8(e.response)?e.response:void 0,sandboxSessionId:"string"==typeof e.sandboxSessionId?e.sandboxSessionId:"",status:e.status,timestamp:e.timestamp,updatedAtMs:e.updatedAtMs}}function lv(e){if(e8(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 ly(e){if(e8(e)&&("card_delta"===e.type||"get_simulator_card_snapshots"===e.type)&&e8(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 l_(e){let{children:t,enabled:r,connection:n,onMessage:a,webSdkDebugger:s}=e,[o,l]=(0,rc.useState)([]),[d,u]=(0,rc.useState)([]),[c,p]=(0,rc.useState)(!1),[m,h]=(0,rc.useState)(!1),[g,f]=(0,rc.useState)(r&&n?"loading":"unavailable"),[v,y]=(0,rc.useState)(lm),[_,b]=(0,rc.useState)(r&&n?"connecting":"unavailable"),[w,S]=(0,rc.useState)(new Set),x=(0,rc.useRef)(new Map),I=(0,rc.useRef)(new Map),E=(0,rc.useRef)(new Map),C=(0,rc.useRef)(new Map),k=(0,rc.useRef)({notice:void 0,task:void 0}),N=(0,rc.useRef)({}),T=(0,rc.useRef)(new Set),R=(0,rc.useRef)(!1),M=(0,rc.useRef)(),A=(0,rc.useRef)(lh()),P=(0,rc.useRef)(0),j=(0,rc.useRef)(a);j.current=a;let L=oQ(async e=>{let t="string"==typeof e.payload.event_id?e.payload.event_id:"";if("card_delta"===e.type){null==s||s.applySimulatorCardDelta(e.payload);return}if(T.current.has(t))return;T.current.add(t);let r=(()=>{try{if(!s)throw Error("Web SDK debugger is unavailable");return{card_snapshots:ny(s.getState().simulator.messages)}}catch{return{error:{code:"SNAPSHOT_COLLECTION_FAILED",message:"failed to collect simulator state"}}}})();await ik(t,r)}),D=oQ(()=>{l([...x.current.values()].sort((e,t)=>Number(e.created_at_ms)-Number(t.created_at_ms)))}),O=oQ(()=>{u([...I.current.values()].sort((e,t)=>Number(t.updated_at_ms)-Number(e.updated_at_ms)))}),U=oQ(function(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1],r=!1;for(let t of e.notices??[]){let e=E.current.get(t.notice_id);(void 0===e||lg(t.revision,e)>0)&&(E.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=E.current.get(t.resource_id);(void 0===e||lg(t.revision,e)>=0)&&(E.current.set(t.resource_id,t.revision),x.current.delete(t.resource_id))}r&&t&&p(!0),D()}),q=oQ(e=>{let t=C.current.get(e.resource_id);(void 0===t||lg(e.revision,t)>=0)&&(C.current.set(e.resource_id,e.revision),I.current.delete(e.resource_id),O())}),$=oQ(e=>{let t=!1;for(let r of e.tasks??[]){let e=C.current.get(r.task_id);void 0!==e&&0>=lg(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||lg(r.revision,e)>=0)&&(C.current.set(r.resource_id,r.revision),I.current.delete(r.resource_id),t=!0)}t&&h(!0),O()}),B=oQ(async function(e,t){let r,n=!(arguments.length>2)||void 0===arguments[2]||arguments[2];do{let a=k.current[e],i="notice"===e?await iI({cursor:a,limit:100}):await iE({cursor:a,limit:100});if(P.current!==t)return;if("notice"===e?U(i,n):$(i),i.has_more&&!i.next_cursor)throw Error(`Sandbox ${e} pull returned has_more without next_cursor`);i.next_cursor&&(k.current[e]=i.next_cursor),r=i.has_more}while(r)}),F=oQ(function(e,t){let r=!(arguments.length>2)||void 0===arguments[2]||arguments[2],n=N.current[e];if(n)return n;let a=B(e,t,r).finally(()=>{N.current[e]===a&&delete N.current[e]});return N.current[e]=a,a}),W=oQ(async(e,t)=>{if(P.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=E.current.get(e.resourceId);(void 0===t||lg(e.revision,t)>=0)&&(E.current.set(e.resourceId,e.revision),x.current.delete(e.resourceId),D())}else q(t);return}if("notice"===e.resource){let r=await iI({notice_ids:[e.resourceId]});P.current===t&&U(r)}else{let r=await iE({task_ids:[e.resourceId]});P.current===t&&$(r)}}}),H=oQ(function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];e||(x.current.clear(),E.current.clear(),p(!1),l([])),I.current.clear(),C.current.clear(),k.current={notice:void 0,task:void 0},N.current={},h(!1),u([])}),z=oQ(async()=>{if(!n)throw Error("服务端日志接口不可用");await n.clearSandboxLogs()}),V=oQ(()=>null==n?void 0:n.start());(0,rc.useEffect)(()=>{let e;if(!n){H(),R.current=!1,M.current=void 0,A.current=lh(),y(lm),b("unavailable"),f("unavailable");return}let t=!1,a=++P.current,i=!1,s=-1,o=!1,l=M.current!==n;l||!R.current?(H(),R.current=!1,l&&(A.current=lh())):N.current={},M.current=n,f(r?"loading":"unavailable");let d=e=>{var r;if(t)return;let n=e instanceof Error?e.message:String(e);f("error"),null==(r=j.current)||r.call(j,`Sandbox 资源同步失败:${n}`,!0)},u=function(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return o?Promise.resolve():Promise.all([F("notice",a,e),F("task",a)])},c=async(n,l)=>{var d;if(t)return;if(n.bridgeLogs){let e={logs:(n.bridgeLogs??[]).map(lf).filter(e=>!!e),updatedAtMs:n.bridgeLogsUpdatedAtMs??0};y(t=>t.updatedAtMs===e.updatedAtMs?t:e)}if(!r)return;let c=n.connectionStatus!==e;e=n.connectionStatus;let p=A.current,m=!!p.instanceId&&n.instanceId!==p.instanceId||0!==p.generation&&n.generation!==p.generation;if(p.instanceId||(p.instanceId=n.instanceId),0===p.generation&&(p.generation=n.generation),m&&(p.instanceId=n.instanceId,p.generation=n.generation,p.eventSequence=0,p.simulatorEventSequence=0,T.current.clear(),o=!1,a=++P.current,i=!1,H(R.current),f("loading")),l&&(await u(R.current),R.current=!0,i=!0),n.updatedAtMs!==s){for(let e of(s=n.updatedAtMs,n.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=j.current)||d.call(j,`Sandbox 模拟器事件处理失败:${e}`,!0)}finally{p.simulatorEventSequence=Math.max(p.simulatorEventSequence,e.sequence)}if(m&&!l&&(await u(),i=!0),o)return;let e=n.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 W(t,a),p.eventSequence=Math.max(p.eventSequence,t.sequence)}!o&&("reconnecting"===n.connectionStatus&&c?(f("reconnecting"),await u()):i&&"connected"===n.connectionStatus&&f("connected"))},p=async(e,t)=>{try{await c(e,t)}catch(e){(function(e){if(!(e instanceof a9))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)}},m=!0,h=Promise.resolve(),g=n.subscribe(e=>{if("status"===e.type)b(e.status),"connected"!==e.status&&(m=!0);else if("sandbox"===e.type){let t=function(e){if(e8(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(lv).filter(e=>!!e):[],generation:e.generation,instanceId:"string"==typeof e.instanceId?e.instanceId:"",simulatorEvents:Array.isArray(e.simulatorEvents)?e.simulatorEvents.map(ly).filter(e=>!!e):[],updatedAtMs:e.updatedAtMs}}(e.data);if(!t)return void d(Error("本地调试服务事件格式错误"));let r=m;m=!1,h=h.then(()=>p(t,r))}});return()=>{t=!0,P.current+=1,g()}},[r,n,L,F,W,H]);let G=oQ(async e=>{S(t=>new Set(t).add(e));try{let t=await iC(e);q(t)}finally{S(t=>{let r=new Set(t);return r.delete(e),r})}}),J=oQ(()=>{p(!1)}),K=oQ(()=>{h(!1)}),X=(0,rc.useMemo)(()=>({bridgeLogs:v.logs,clearBridgeLogs:z,hasUnreadNotices:c,hasUnreadTasks:m,localConnectionStatus:_,markServiceNoticesRead:J,markTasksRead:K,notices:o,reconnect:V,removeTask:G,removingTaskIds:w,status:g,tasks:d}),[v.logs,z,c,m,_,J,K,o,V,G,w,g,d]);return(0,i.jsx)(lp.Provider,{value:X,children:t})}function lb(){return(0,rc.useContext)(lp)}var lw=r(64031),lS=r(88460);let lx={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,i.jsx)("a",{href:r,rel:"noreferrer",target:"_blank",children:t}):(0,i.jsx)(i.Fragment,{children:t})}};function lI(e){let{text:t}=e;return(0,i.jsx)("div",{className:"wsd-widget-chat-text markdown-body wsd-widget-chat-markdown",children:(0,i.jsx)(lw.oz,{components:lx,remarkPlugins:[lS.A],children:t})})}function lE(e){return{"doubao.callMcpTool":async t=>u(t,await iT({...e,params:t.params}))}}function lC(e,t,r){var n;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==(n=e.source)?void 0:n.tool_call_id,render_data:e.render_data}}function lk(e){let{apiEnvironment:t,appId:r,card:n,inspectableTargetKey:a,reloadKey:s,nativeModulesCallHandler:o,onInspectableTargetChange:l,onTraceEvent:d,onUpdateWidget:p,requestId:m,runtimeConsoleTarget:h,traceId:g,viewport:f,widgets:v}=e,y=(0,rc.useRef)(null),_=n.widget_id,b=f??nO,w=!!_&&((null==v?void 0:v.some(e=>e.widgetId===_))??!1),[S,x]=(0,rc.useState)(),[I,E]=(0,rc.useState)(0),[C,k]=(0,rc.useState)({status:"idle"}),N=S??b.width,T={height:`${I||Math.round(1.35*N)}px`},R=(0,rc.useMemo)(()=>{let e=(null==t?void 0:t.apiRegistry.fork())??i9();return e.registerMany(lE({appKey:n.app_id||r||"",scene:"widget",widgetId:_||"",widgetInstanceId:n.card_id||""}),{override:!0}),p&&e.register("doubao.updateWidget",{handler:e=>{let t=function(e){if(e8(e)&&"string"==typeof e.widgetInstanceId&&"string"==typeof e.widgetData&&(void 0===e.widgetId||"string"==typeof e.widgetId))return{widgetInstanceId:e.widgetInstanceId,widgetData:e.widgetData,widgetId:"string"==typeof e.widgetId?e.widgetId:void 0}}(e.params);if(!t)return c(e,"Invalid doubao.updateWidget parameters");let r=p(t);return"updated"===r.status?u(e,{}):c(e,r.message)}},{override:!0}),e},[null==t?void 0:t.apiRegistry,r,n.app_id,n.card_id,p,_]),M=(0,rc.useMemo)(()=>(e,t,r,n)=>{let a=oH(e,t,r);return a?void sl(h??n.element,a):null==o?void 0:o(e,t,r,n)},[o,h]);return(0,rc.useEffect)(()=>{let e=y.current;if(!e)return;let t=()=>{let t=e.clientWidth;(t>0||"u"<typeof ResizeObserver)&&x(t||b.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()}},[b.width]),(0,rc.useEffect)(()=>{let e,i,s=y.current;if(!s||void 0===S)return;if(s.replaceChildren(),E(0),a&&(null==l||l(a,null)),!_){let e="缺少 widget_id,已展示 fallback";k({status:"skipped",message:e}),null==d||d({category:"card",event:"simulator_card_render_skipped",reason:"missing_widget_id",summary:e,...lC(n,m,g)});return}if(!r){let e="缺少 appId,已展示 fallback";k({status:"skipped",message:e}),null==d||d({category:"card",event:"simulator_card_render_skipped",reason:"missing_app_id",summary:e,...lC(n,m,g)});return}if(!w){let e=`Manifest 中找不到 widget_id: ${_}`;k({status:"skipped",message:e}),null==d||d({category:"card",event:"simulator_card_render_skipped",reason:"widget_not_found",summary:e,...lC(n,m,g)});return}let o=!1,u=null,c=n$({...b,width:S},n.card_id?{__VIEW_CONTEXT__:{widgetInstanceId:n.card_id}}:{}),p=()=>{o||E(Math.ceil(s.scrollHeight||s.getBoundingClientRect().height))},h=()=>{"u"<typeof window?p():(void 0!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(p))},f=Date.now();k({status:"rendering"});try{u=new tE({appId:r,apiRegistry:R,container:s,globalProps:c,initData:tA(n.render_data),nativeModulesCallHandler:M,onError:e=>{null==d||d({category:"card",event:"simulator_card_runtime_error",elapsed_ms:Date.now()-f,summary:e.message,...lC(n,m,g)})},runtimeHost:null==t?void 0:t.runtimeHost,widgetId:_})}catch(t){let e=tD(t);k({status:"error",message:e}),null==d||d({category:"card",event:"simulator_card_render_failed",elapsed_ms:Date.now()-f,summary:e,...lC(n,m,g)});return}return u.render().then(e=>{o||(k({status:"rendered"}),a&&(null==l||l(a,e,S)),h(),"u">typeof ResizeObserver&&(i=new ResizeObserver(h)).observe(s),null==d||d({category:"card",event:"simulator_card_rendered",elapsed_ms:Date.now()-f,...lC(n,m,g)}))}).catch(e=>{if(o)return;let t=tD(e);k({status:"error",message:t}),a&&(null==l||l(a,null)),null==d||d({category:"card",event:"simulator_card_render_failed",elapsed_ms:Date.now()-f,summary:t,...lC(n,m,g)})}),()=>{o=!0,void 0!==e&&window.cancelAnimationFrame(e),null==i||i.disconnect(),null==u||u.destroy(),s.replaceChildren(),a&&(null==l||l(a,null))}},[t,R,r,n,M,a,l,d,s,b,S,w,_]),(0,i.jsxs)("div",{className:"wsd-widget-chat-card-runtime",children:[(0,i.jsx)("div",{className:"wsd-widget-chat-card-runtime-viewport",style:T,children:(0,i.jsx)("div",{className:"wsd-widget-chat-card-runtime-target",ref:y})}),"rendering"===C.status?(0,i.jsx)("span",{className:"wsd-widget-chat-card-runtime-status",children:"卡片渲染中..."}):null,"skipped"===C.status||"error"===C.status?(0,i.jsx)("span",{className:"wsd-widget-chat-card-runtime-status",children:C.message}):null]})}let lN="mcp-privacy-login-card",lT="__doubao_apps__expired-widget";function lR(e){return e.title||e.fallback_text||e.card_type||e.card_id||"卡片"}function lM(e,t){return(null==e?void 0:e.some(e=>e.widgetId===t))?e:[...e??[],{widgetId:t}]}function lA(e,t){return`${e.messageId}:${t.blockId}:${t.card.card_id||t.blockId}`}function lP(e){let{apiEnvironment:t,appId:r,block:n,cardReloadKey:a,message:s,nativeModulesCallHandler:o,onInspectableCardTargetChange:l,grantingItemIndex:d,onGrantingCardOpen:u,onGrantingPermissionDecision:c,onGrantingCardSkip:p,onTraceEvent:m,onUpdateWidget:h,runtimeConsoleTarget:g,widgetViewport:f,widgets:v}=e,y=(0,rc.useMemo)(()=>"card"===n.type&&n.card.widget_id===lT?lM(v,lT):v,[n,v]);if((0,rc.useEffect)(()=>{var e;"card"!==n.type||"permission_apply"===n.card.card_type||n.card.widget_id||null==m||m({category:"card",event:"simulator_card_render_skipped",reason:"missing_widget_id",summary:"缺少 widget_id,已展示 fallback",...(e=n.card,{request_id:s.requestId,trace_id:s.traceId,card_id:e.card_id,widget_id:e.widget_id,card_type:e.card_type})})},[n,s.requestId,s.traceId,m]),"text"===n.type)return(0,i.jsx)(lI,{text:n.text});if("image"===n.type)return(0,i.jsx)("img",{alt:n.image.name||"对话图片",className:"wsd-widget-chat-image",src:n.image.previewUrl});if("permission_apply"===n.card.card_type){var _;let e=lA(s,n),t=(null==(_=lD(n.card,d))?void 0:_.itemIndex)??0;return(0,i.jsx)(lU,{card:n.card,grantingItemIndex:t,onLogin:()=>null==u?void 0:u(n.card,e,t),onPermissionDecision:r=>null==c?void 0:c(n.card,e,t,r),onSkip:r=>null==p?void 0:p(r,n.card,e,t),onTraceEvent:m})}return n.card.widget_id?(0,i.jsx)("article",{className:"wsd-widget-chat-card has-runtime",children:(0,i.jsx)(lk,{apiEnvironment:t,appId:r,card:n.card,inspectableTargetKey:lA(s,n),reloadKey:a,nativeModulesCallHandler:o,onInspectableTargetChange:l,onTraceEvent:m,onUpdateWidget:h,requestId:s.requestId,runtimeConsoleTarget:g,traceId:s.traceId,viewport:f,widgets:y})}):(0,i.jsxs)("article",{className:"wsd-widget-chat-card",children:[(0,i.jsx)("span",{className:"wsd-widget-chat-card-kicker",children:n.card.card_type||"卡片"}),(0,i.jsx)("strong",{children:lR(n.card)}),n.card.fallback_text&&n.card.fallback_text!==lR(n.card)?(0,i.jsx)("span",{className:"wsd-widget-chat-card-summary",children:n.card.fallback_text}):null]})}function lj(e){var t;return null==(t=e.render_data)?void 0:t.grantingData}function lL(e){return"pending"===e.permissionStatus||"revoked"===e.permissionStatus}function lD(e,t){let r=lj(e),n=(null==r?void 0:r.grantingList.findIndex(lL))??-1,a="number"==typeof t&&(null==r?void 0:r.grantingList[t])?t:-1===n?0:n;if(a<0)return;let i=null==r?void 0:r.grantingList[a];return i&&r?{grantingData:r,item:i,itemIndex:a}:void 0}function lO(e){let{appIcon:t}=e,[r,n]=(0,rc.useState)(!1);return((0,rc.useEffect)(()=>{n(!1)},[t]),!t||r)?null:(0,i.jsx)("img",{alt:"",className:"wsd-widget-granting-prompt-logo",onError:()=>n(!0),src:t})}function lU(e){let{card:t,grantingItemIndex:r,onLogin:n,onPermissionDecision:a,onSkip:s,onTraceEvent:o}=e,l=(0,rc.useMemo)(()=>lD(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",m=(null==u?void 0:u.relatedData.scopeName)??"",h=(0,rc.useMemo)(()=>n6(m),[m]),[g,f]=(0,rc.useState)(),[v,y]=(0,rc.useState)(),_=n3.isLocationScope(m),b=void 0!==v,w=_&&"granted"===v,S=p&&(null==d?void 0:d.cardStatus)==="expired",x=p&&!g&&(!b||_)&&!S&&((null==u?void 0:u.permissionStatus)==="pending"||(null==u?void 0:u.permissionStatus)==="revoked"),I=p?h.title:`在豆包内使用 ${c}`,E=p?"granted"===g?`已允许${c}获取`:"refused"===g?`已拒绝${c}获取`:S?"已过期,暂无法操作":(null==u?void 0:u.relatedData.scopeDescription)||h.description:(null==u?void 0:u.relatedData.bizLoginDescription)||((null==u?void 0:u.grantingName)==="privacy"?"需同意后才可以继续使用":"需登录后才可以继续使用");async function C(e){if(!b){y(e?"granted":"refused"),null==o||o({category:"card",event:"simulator_granting_prompt_permission_click",granted:e,scope:m});try{let t=await (null==a?void 0:a(e));!1!==t&&f(e?"granted":"refused")}finally{y(void 0)}}}return(0,rc.useEffect)(()=>{f(void 0),y(void 0)},[t.card_id,null==d?void 0:d.cardStatus,r,null==u?void 0:u.permissionStatus,m]),(0,i.jsxs)("article",{className:(0,e6.$)("wsd-widget-granting-prompt-card",p&&"is-permission"),children:[(0,i.jsxs)("header",{className:"wsd-widget-granting-prompt-brand",children:[(0,i.jsx)(lO,{appIcon:null==d?void 0:d.doubaoAppletIcon}),(0,i.jsx)("span",{children:c})]}),(0,i.jsx)("strong",{className:"wsd-widget-granting-prompt-title",children:I}),(0,i.jsx)("p",{className:"wsd-widget-granting-prompt-description",children:E}),p?x?(0,i.jsxs)("footer",{className:"wsd-widget-granting-prompt-actions",children:[(0,i.jsx)("button",{className:"wsd-widget-granting-prompt-secondary",disabled:b,onClick:()=>void C(!1),type:"button",children:"拒绝"}),(0,i.jsxs)("button",{"aria-busy":w,className:"wsd-widget-granting-prompt-primary",disabled:b,onClick:()=>void C(!0),type:"button",children:[w?(0,i.jsxs)("svg",{"aria-hidden":"true",className:"wsd-widget-granting-prompt-spinner",viewBox:"0 0 16 16",children:[(0,i.jsx)("circle",{className:"wsd-widget-granting-prompt-spinner-track",cx:"8",cy:"8",fill:"none",r:"6",strokeWidth:"2"}),(0,i.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,i.jsxs)("footer",{className:"wsd-widget-granting-prompt-actions",children:[(0,i.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==s||s((null==u?void 0:u.grantingName)==="privacy"?"privacy":"login")},type:"button",children:"暂不登录"}),(0,i.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==n||n()},type:"button",children:"登录"})]})]})}function lq(e){let{apiEnvironment:t,appId:r,card:n,grantingItemIndex:a,inspectableTargetKey:s,nativeModulesCallHandler:o,onInspectableTargetChange:l,onTraceEvent:d,runtimeConsoleTarget:u,widgets:c}=e,p=(0,rc.useMemo)(()=>lM(c,lN),[c]),m=(0,rc.useMemo)(()=>(function(e,t){let r,n,a,i,s,o,l,d;return{...e,card_id:`${e.card_id||"permission_apply"}:${lN}`,card_type:"permission_apply",render_data:{...e.render_data,viewData:(n=null==(r=lD(e,t))?void 0:r.grantingData,i=(null==(a=null==r?void 0:r.item)?void 0:a.relatedData)??{},s=(null==n?void 0:n.doubaoAppletName)||"智能服务",o=(null==a?void 0:a.grantingName)==="privacy",l=i.mobileMask??"",d=o?i.bizPrivacyContent||`${s} 需要你同意隐私政策后继续。`:i.bizLoginDescription||"登录后继续使用相关服务",{type:(null==a?void 0:a.grantingName)==="privacy"?"agreePrivacyAuthorization":"getPhoneNumber",currentPage:"chat",brand:{name:s,logo:(null==n?void 0:n.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:i.termsOfServiceURL},{text:"和"},{text:"隐私政策",url:i.privacyURL}]},warningToast:"请先阅读并同意协议"})},widget_id:lN}})(n,a),[n,a]),h=(0,rc.useMemo)(()=>({key:"simulator-login-sheet",label:"登录半屏",width:393,density:3}),[]);return(0,i.jsx)("dialog",{className:"wsd-widget-granting-card has-runtime",open:!0,children:(0,i.jsx)(lk,{apiEnvironment:t,appId:r,card:m,inspectableTargetKey:s,nativeModulesCallHandler:o,onInspectableTargetChange:l,onTraceEvent:d,runtimeConsoleTarget:u,viewport:h,widgets:p})})}function l$(e){let{apiEnvironment:t,appId:r,cardReloadKey:n,grantingItemIndexes:a,message:s,nativeModulesCallHandler:o,onInspectableCardTargetChange:l,onGrantingCardOpen:d,onGrantingPermissionDecision:u,onGrantingCardSkip:c,onTraceEvent:p,onTraceSelect:m,onUpdateWidget:h,runtimeConsoleTarget:g,selectedTraceId:f,widgetViewport:v,widgets:y}=e,_="assistant"===s.role,b=(s.blocks.length>0?s.blocks:s.text.trim()?[{blockId:`${s.messageId}-text`,type:"text",text:s.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},[]),w=b.some(e=>"card"===e.type),S=b.some(e=>"image"===e.type),x=b.some(e=>"text"===e.type&&e.text.trim()),I=s.traceId,E=!!(I&&m),C=!!(I&&I===f);return(0,i.jsxs)("article",{"aria-pressed":E?C:void 0,className:(0,e6.$)("wsd-widget-chat-message",_?"is-assistant":"is-user",x&&"has-text",w&&"has-card",S&&"has-image",E&&"is-trace-selectable",C&&"is-trace-selected"),onClick:e=>{!I||!m||lB(e.target)||m(I)},onKeyDown:e=>{!I||!m||lB(e.target)||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),m(I))},role:E?"button":void 0,tabIndex:E?0:void 0,children:[_?(0,i.jsx)("span",{className:"wsd-widget-chat-avatar",children:"AI"}):null,(0,i.jsxs)("div",{className:"wsd-widget-chat-bubble",children:[b.map(e=>(0,i.jsx)(lP,{apiEnvironment:t,appId:r,block:e,cardReloadKey:n,grantingItemIndex:"card"===e.type?null==a?void 0:a[lA(s,e)]:void 0,message:s,nativeModulesCallHandler:o,onGrantingCardOpen:d,onGrantingPermissionDecision:u,onGrantingCardSkip:c,onInspectableCardTargetChange:l,onTraceEvent:p,onUpdateWidget:h,runtimeConsoleTarget:g,widgetViewport:v,widgets:y},e.blockId)),"streaming"===s.status&&b.every(e=>"text"!==e.type||!e.text)?(0,i.jsx)("span",{className:"wsd-widget-chat-placeholder",children:"正在思考..."}):null]})]})}function lB(e){return e instanceof Element&&!!e.closest("button,a,input,textarea,select,.wsd-widget-chat-card")}let lF="mcp-login-page";function lW(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return JSON.stringify([e,...t.map(e=>e.resource_uri)])}function lH(e){return e.split(":")[0]||""}function lz(e){var t,r,n;let{apiEnvironment:a,appId:s,cardReloadKey:o,controlCommand:l,nativeModulesCallHandler:d,onGrantingSheetTargetChange:u,onControlResult:c,onInspectableCardTargetChange:p,onNavigateToPage:m,onQuerySubmit:h,onSandboxLocationConfigOpen:g,onTraceEvent:f,onTraceMessageSelect:v,runtimeConsoleTarget:y,sandboxLoginHint:_,simulator:b,selectedTraceId:w,widgetViewport:S,widgets:x,webSdkDebugger:I,onMessage:E}=e,[C,k]=(0,rc.useState)(""),[N,T]=(0,rc.useState)(),[R,M]=(0,rc.useState)(!1),[A,P]=(0,rc.useState)(!1),[j,L]=(0,rc.useState)(!1),D=lb(),O=(0,rc.useMemo)(()=>ld(D.tasks).length>0,[D.tasks]),U=(0,rc.useRef)(null),q=(0,rc.useRef)(b.messages.length),$=(0,rc.useRef)(0),B=(0,rc.useRef)(),F=(0,rc.useRef)(),W=(0,rc.useRef)(0),H=(0,rc.useRef)(!0),[z,V]=(0,rc.useState)(),[G,J]=(0,rc.useState)({}),K=(0,rc.useRef)(new Set),X=(0,rc.useRef)(),Q=(0,rc.useRef)(new Set),Y=(0,rc.useRef)(new Set),Z=(0,rc.useRef)(new Set),ee="streaming"===b.streamStatus,et=(null==N?void 0:N.uploadStatus)==="uploading",er=!!(C.trim()||(null==N?void 0:N.uploadedImage))&&!et&&!ee,en=(r=null==z?void 0:z.card)?null==(n=lj(r))?void 0:n.doubaoAppletKey:void 0,ea=s||en,ei=oQ(e=>{(V(void 0),m)?m({url:e}):I.navigateToPage(e)}),es=oQ(()=>{var e;null==a||null==(e=a.uiPresenter)||e.showToast({duration:3e3,icon:"warn",message:"请先在 DevTools Sandbox 面板配置位置",type:"warning"}),null==g||g()}),eo=oQ(e=>I.updateSimulatorWidget(e)),el=oQ((e,t)=>{let r=rV(I,{grantingMessageId:(null==t?void 0:t.grantingMessageId)??(z?lH(z.key):void 0),noLogin:null==t?void 0:t.noLogin});if("not_found"===r.status){null==E||E("未找到需要重发的原始消息",!0);return}if("streaming"===r.status){null==E||E("当前仍在生成中,暂不重发授权后的消息",!0);return}V(void 0),null==f||f({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==h||h(),r.completion.catch(e=>{null==E||E(e.message,!0)})}),ed=oQ(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};null==f||f({category:"card",event:e,card_id:t.cardId,request_id:t.requestId,source_tool_call_id:t.sourceToolCallId,tool_name:t.toolName,...r})}),eu=oQ(async(e,t)=>{ed("simulator_location_directive_started",e);try{let r=await n3.requestLocationForHostDirective();if("success"!==r.status){es(),ed("simulator_location_directive_unavailable",e,{failure_type:r.code?`browser_geolocation_${r.code}`:"browser_geolocation_unavailable",location_status:r.status});return}try{let e=n3.createBusinessLocationInfo(r.location);await iU(JSON.stringify(e))}catch(t){ed("simulator_location_directive_report_failed",e,{failure_type:t instanceof Error?t.name:typeof t}),null==E||E(`位置信息上报失败:${t instanceof Error?t.message:String(t)}`,!0);return}if(ed("simulator_location_directive_reported",e),"completed"!==I.getState().simulator.streamStatus){ed("simulator_location_directive_unavailable",e,{failure_type:"simulator_stream_not_completed"}),null==E||E("当前仍在生成中,暂不重发定位后的消息",!0);return}Z.current.add(t.key),I.removeSimulatorMessages(t.messageIds),ed("simulator_location_directive_resend_started",e),null==h||h();try{await (t.images?I.sendSimulatorQuery(t.query,{images:t.images}):I.sendSimulatorQuery(t.query))}catch(e){null==E||E(e.message,!0)}}finally{Y.current.delete(t.key)}});(0,rc.useEffect)(()=>{let e=b.locationDirective;if(!e||"completed"!==b.streamStatus||Q.current.has(e.cardId))return;Q.current.add(e.cardId),I.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),n=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(!n)return;let a=n.text.trim(),i=n.blocks.filter(e=>"image"===e.type).map(e=>e.image);if(a||0!==i.length)return{images:i.length>0?i:void 0,key:lW(a,i),messageIds:[n.messageId,...-1===r?[]:[e[r].messageId]],query:a}}(b.messages,e);if(!t)return void ed("simulator_location_directive_unavailable",e,{failure_type:"original_query_not_found"});if(Y.current.has(t.key)||Z.current.has(t.key)){ed("simulator_location_directive_loop_prevented",e),null==E||E("位置已上报但平台仍要求定位,请检查 Sandbox 位置状态",!0);return}Y.current.add(t.key),eu(e,t)},[eu,E,b.locationDirective,b.messages,b.streamStatus,ed]);let ec=oQ((e,t,r,n)=>{var a;let i=lD(e,r);if(!i){null==E||E("索权卡缺少有效的授权项",!0);return}let s=`${t}:${r}`;if(K.current.has(s))return;K.current.add(s);let o=function(e,t){let r=lj(e);if(!r)return;let n=r.grantingList.findIndex((e,r)=>r>t&&lL(e));return -1===n?void 0:n}(e,r),l=function(e){switch(e){case"permission":case"privacy":return e;default:return"login"}}(i.item.grantingName);if(!n&&!1!==i.item.required)return void el(l,{grantingMessageId:lH(t),noLogin:!0});if(void 0!==o){J(e=>({...e,[t]:o})),V(e=>(null==e?void 0:e.key)===t?void 0:e),null==f||f({category:"card",event:"simulator_granting_item_advanced",granted:n,granting_name:i.item.grantingName,next_granting_name:null==(a=lD(e,o))?void 0:a.item.grantingName});return}el(l,{grantingMessageId:lH(t)})}),ep=oQ((e,t,r)=>{var n,a;let i;(null==(i=null==(n=lD(e,r))?void 0:n.item)?void 0:i.grantingName)==="privacy"||(null==i||null==(a=i.relatedData.mobileMask)?void 0:a.trim())?V({card:e,itemIndex:r,key:t}):(null==f||f({category:"card",event:"simulator_granting_custom_login_navigate",reason:"missing_mobile_mask",url:lF}),ei(lF))}),em=oQ(async(e,t,r,n)=>{var a,i,s;let o,l=function(e,t){var r;let n=lD(e,t),a=null==n?void 0:n.grantingData,i=null==n?void 0:n.item,s=(null==a?void 0:a.doubaoAppletKey.trim())??"",o=(null==i||null==(r=i.relatedData.scopeName)?void 0:r.trim())??"";if((null==i?void 0:i.grantingName)==="permission"&&s&&o)return{appId:s,appName:(null==a?void 0:a.doubaoAppletName)||"智能服务",required:!1!==i.required,scope:o}}(e,r);if(!l)return null==E||E("索权卡缺少有效的智能服务 appId 或 scopeName",!0),!1;if(n3.isLocationScope(l.scope)&&(n3.updateUserAuthorization(n),n)){let e=await n3.requestLocation();if("success"!==e.status)return"browser_unauthorized"===e.status&&es(),null==f||f({category:"card",event:"simulator_granting_location_unavailable",location_status:e.status,scope:l.scope}),!1;o=n3.createBusinessLocationInfo(e.location)}try{await iN({appletId:l.appId,granted:n,scopeName:l.scope})}catch(t){let e=t instanceof Error?t.message:String(t);return null==f||f({category:"card",event:"simulator_granting_permission_report_failed",applet_id:l.appId,granted:n,scope:l.scope}),null==E||E(`权限授权状态上报失败:${e}`,!0),!1}if(o){try{await iU(JSON.stringify(o))}catch(t){let e=t instanceof Error?t.message:String(t);return null==f||f({category:"card",event:"simulator_granting_location_report_failed",scope:l.scope}),null==E||E(`位置信息上报失败:${e}`,!0),!1}null==f||f({category:"card",event:"simulator_granting_location_reported",scope:l.scope})}return a=l.appId,i=l.scope,s=n?"granted":"denied",n4.set(n8(a,i),s),null==f||f({category:"card",event:"simulator_granting_permission_reported",applet_id:l.appId,granted:n,scope:l.scope}),ec(e,t,r,n),!0}),eh=oQ((e,t,r,n)=>{ec(t,r,n,!1)}),eg=(0,rc.useMemo)(()=>{var e,t;if(!z)return;let r=(e=z.key,t=z.itemIndex,`${e}:${t}`);return se({appId:ea,baseAPIRegistry:null==a?void 0:a.apiRegistry,onGrantingCompleted:(e,t)=>ec(z.card,z.key,z.itemIndex,!(null==t?void 0:t.noLogin)),onCustomLoginNavigate:ei,onPrivacyLoginCardClose:()=>{Promise.resolve().then(()=>{K.current.has(r)||ec(z.card,z.key,z.itemIndex,!1)})},runtimeHost:null==a?void 0:a.runtimeHost,scanCodePresenter:null==a?void 0:a.scanCodePresenter,uiPresenter:null==a?void 0:a.uiPresenter})},[z,a,ea,ec,ei]),ef=oQ((e,t,r)=>{null==p||p(e,t,r),null==u||u(t)}),ev=oQ(e=>{L(!1);try{I.navigateToPage(e),null==m||m({url:e})}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")}}),ey=oQ(()=>{L(!1)}),e_=oQ(async e=>{try{await D.removeTask(e)}catch(e){null==E||E(e.message,!0)}});function eb(e){let t=B.current;t&&t.previewUrl!==(null==e?void 0:e.previewUrl)&&URL.revokeObjectURL(t.previewUrl),B.current=e,T(e)}async function ew(e){var t,r;if(ee)return;try{rI(e)}catch(t){let e=t instanceof Error?t.message:String(t);null==a||null==(r=a.uiPresenter)||r.showToast({duration:3e3,message:e,type:"error"}),null==E||E(e,!0);return}let n={name:e.name,previewUrl:URL.createObjectURL(e),uploadStatus:"uploading"},i=++W.current,s=new AbortController;null==(t=F.current)||t.abort(),F.current=s,eb(n);try{let t=await I.uploadSimulatorImage(e,s.signal);if(i!==W.current)return;eb({...n,uploadStatus:"uploaded",uploadedImage:{...t,name:e.name,previewUrl:n.previewUrl}})}catch(e){i===W.current&&"AbortError"!==e.name&&(eb({...n,uploadStatus:"failed"}),null==E||E(e.message,!0))}finally{i===W.current&&(F.current=void 0)}}(0,rc.useEffect)(()=>{let e=U.current,t=q.current,r=b.messages.at(-1),n=b.messages.length>t&&(null==r?void 0:r.role)==="user";q.current=b.messages.length,e&&(H.current||n)&&(e.scrollTop=e.scrollHeight,H.current=!0)},[null==(t=b.error)?void 0:t.message,b.messages,b.streamStatus]);let eS=oQ(async(e,t)=>{Z.current.delete(lW(e)),null==h||h(),await (t?lt(I,t,e):I.sendSimulatorQuery(e))});return((0,rc.useEffect)(()=>()=>{var e;W.current+=1,null==(e=F.current)||e.abort(),B.current&&URL.revokeObjectURL(B.current.previewUrl)},[]),(0,rc.useEffect)(()=>{if((null==l?void 0:l.type)!=="submit_chat_query"||X.current===l.commandId)return;X.current=l.commandId;let e=I.getState();if("ready"!==e.status.type){null==c||c(l.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==c||c(l.commandId,{ok:!1,error:{code:"CHAT_BUSY",message:"A chat query is already streaming"}});return}let t=e.simulator.messages.length;eS(l.query,l.commandId).then(()=>{var e,r;let n=I.getState().simulator,a=null==(e=n.messages.slice(t).reverse().find(e=>"assistant"===e.role&&!!e.requestId))?void 0:e.requestId;if("completed"!==n.streamStatus||!a)throw Error((null==(r=n.error)?void 0:r.message)??"Chat query did not complete with a request ID");null==c||c(l.commandId,{ok:!0,result:{completed:!0,query:l.query,requestId:a}})}).catch(e=>{null==c||c(l.commandId,{ok:!1,error:{code:"CHAT_SUBMIT_FAILED",message:e.message}})})},[l,c,eS,I]),(0,rc.useEffect)(()=>{A&&D.hasUnreadNotices&&D.markServiceNoticesRead()},[D.hasUnreadNotices,D.markServiceNoticesRead,A]),A)?(0,i.jsx)(lo,{notices:D.notices,onAction:ev,onBack:()=>P(!1),status:D.status}):(0,i.jsxs)("div",{className:"wsd-widget-chat-panel",children:[(0,i.jsxs)("header",{className:"wsd-doubao-simulator-chrome","aria-label":"豆包模拟器标题栏",children:[(0,i.jsx)(la,{}),(0,i.jsxs)("div",{className:"wsd-doubao-title-bar",children:[(0,i.jsxs)("div",{className:"wsd-doubao-title-actions is-left",children:[(0,i.jsx)("button",{"aria-label":D.hasUnreadNotices?"打开菜单,有更新":"打开菜单",className:(0,e6.$)("wsd-doubao-icon-button",D.hasUnreadNotices&&"has-badge"),onClick:()=>P(!0),type:"button",children:(0,i.jsx)("span",{className:"wsd-doubao-menu-icon","aria-hidden":"true"})}),(0,i.jsx)("button",{"aria-label":"打开应用入口",className:"wsd-doubao-icon-button",type:"button",children:(0,i.jsx)("span",{className:"wsd-doubao-mask-icon is-circle4","aria-hidden":"true"})})]}),(0,i.jsxs)("div",{className:"wsd-doubao-title-stack",children:[(0,i.jsxs)("span",{className:"wsd-doubao-title",children:["豆包",(0,i.jsx)("span",{"aria-hidden":"true",children:"›"})]}),(0,i.jsx)("span",{className:"wsd-doubao-subtitle",children:"doubao.com"})]}),(0,i.jsxs)("div",{className:"wsd-doubao-title-actions",children:[(0,i.jsx)("button",{"aria-label":"语音通话",className:"wsd-doubao-icon-button",type:"button",children:(0,i.jsx)("span",{className:"wsd-doubao-mask-icon is-phone","aria-hidden":"true"})}),(0,i.jsx)("button",{"aria-label":"静音",className:"wsd-doubao-icon-button",type:"button",children:(0,i.jsx)("span",{className:"wsd-doubao-mask-icon is-mute","aria-hidden":"true"})})]})]})]}),_?(0,i.jsxs)("div",{className:(0,e6.$)("wsd-doubao-login-banner",!_.available&&"is-unavailable"),children:[(0,i.jsxs)("button",{className:"wsd-doubao-login-banner-open",onClick:_.onOpen,type:"button",children:[(0,i.jsx)("span",{children:_.available?"配置登录信息,模拟登录后场景":"无法模拟平台服务"}),_.available?(0,i.jsx)("span",{"aria-hidden":"true",className:"wsd-doubao-login-banner-arrow",children:"→"}):null]}),(0,i.jsx)("button",{"aria-label":"关闭登录信息配置提示",className:"wsd-doubao-login-banner-close",onClick:_.onClose,type:"button",children:"×"})]}):null,(0,i.jsxs)("div",{"aria-label":"对话预览",className:"wsd-widget-chat-messages",onScroll:function(e){let t=e.currentTarget;H.current=t.scrollHeight-t.scrollTop-t.clientHeight<=24},ref:U,children:[b.messages.length>0?b.messages.map(e=>(0,i.jsx)(l$,{apiEnvironment:a,appId:s,cardReloadKey:o,grantingItemIndexes:G,message:e,nativeModulesCallHandler:d,onGrantingCardOpen:ep,onGrantingPermissionDecision:em,onGrantingCardSkip:eh,onInspectableCardTargetChange:p,onTraceEvent:f,onTraceSelect:v,onUpdateWidget:eo,runtimeConsoleTarget:y,selectedTraceId:w,widgetViewport:S,widgets:x},e.messageId)):null,b.error?(0,i.jsx)("div",{className:"wsd-widget-chat-error",children:b.error.message}):null]}),(0,i.jsx)("div",{className:"wsd-widget-chat-input-dock",children:(0,i.jsxs)("form",{className:(0,e6.$)("wsd-widget-chat-composer",N&&"has-image",R&&"is-dragging-image"),onDragEnter:function(e){!ee&&Array.from(e.dataTransfer.types).includes("Files")&&(e.preventDefault(),$.current+=1,M(!0))},onDragLeave:function(e){e.preventDefault(),$.current=Math.max(0,$.current-1),0===$.current&&M(!1)},onDragOver:function(e){!ee&&Array.from(e.dataTransfer.types).includes("Files")&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},onDrop:function(e){if(e.preventDefault(),$.current=0,M(!1),ee)return;let t=Array.from(e.dataTransfer.files),r=t.find(e=>e.type.startsWith("image/"))??t[0];r&&ew(r)},onSubmit:function(e){e.preventDefault();let t=C.trim(),r=null==N?void 0:N.uploadedImage;if((t||r)&&!et&&!ee){if(k(""),r){Z.current.delete(lW(t,[r])),B.current=void 0,T(void 0),null==h||h(),I.sendSimulatorQuery(t,{images:[r]}).catch(e=>{null==E||E(e.message,!0)});return}N&&eb(),eS(t).catch(e=>{null==E||E(e.message,!0)})}},children:[N?(0,i.jsxs)("div",{className:(0,e6.$)("wsd-widget-chat-image-preview",`is-${N.uploadStatus}`),children:[(0,i.jsx)("img",{alt:N.name||"待发送图片",src:N.previewUrl}),"uploading"===N.uploadStatus?(0,i.jsx)("output",{"aria-label":"图片上传中",className:"wsd-widget-chat-image-status is-uploading",children:(0,i.jsx)("span",{"aria-hidden":"true",className:"wsd-widget-chat-image-spinner"})}):null,"failed"===N.uploadStatus?(0,i.jsxs)("span",{className:"wsd-widget-chat-image-status is-failed",role:"alert",children:[(0,i.jsx)("strong",{children:"!"}),(0,i.jsx)("span",{children:"上传失败"})]}):null,(0,i.jsx)("button",{"aria-label":"移除图片",className:"wsd-widget-chat-image-remove",onClick:function(){var e;W.current+=1,null==(e=F.current)||e.abort(),F.current=void 0,eb()},type:"button",children:"×"})]}):null,(0,i.jsx)("input",{"aria-label":"输入消息",className:"wsd-widget-chat-input",disabled:ee,onChange:e=>k(e.currentTarget.value),onPaste:function(e){let t=Array.from(e.clipboardData.files).find(e=>e.type.startsWith("image/"));t&&ew(t)},placeholder:"发消息或粘贴图片...",type:"text",value:C}),(0,i.jsx)("button",{"aria-label":ee?"取消生成":"发送消息",className:"wsd-widget-chat-send",disabled:!ee&&!er,onClick:function(){ee&&I.cancelSimulatorQuery()},type:ee?"button":"submit",children:ee?(0,i.jsx)("span",{"aria-hidden":"true",className:"wsd-doubao-cancel-icon"}):(0,i.jsx)("span",{"aria-hidden":"true",className:"wsd-doubao-send-icon"})})]})}),O&&!j?(0,i.jsx)("button",{"aria-label":"展开进行中的任务",className:"wsd-sandbox-task-collapsed-entry",onClick:()=>{D.markTasksRead(),L(!0)},type:"button",children:(0,i.jsx)("span",{"aria-hidden":"true"})}):null,z?(0,i.jsxs)("div",{className:"wsd-simulator-overlay-layer wsd-widget-granting-sheet-layer",children:[(0,i.jsx)("div",{className:"wsd-simulator-overlay-backdrop wsd-widget-granting-sheet-backdrop"}),(0,i.jsx)("div",{className:"wsd-widget-granting-sheet",children:(0,i.jsx)(lq,{apiEnvironment:eg,appId:ea,card:z.card,grantingItemIndex:z.itemIndex,inspectableTargetKey:z.key,nativeModulesCallHandler:d,onInspectableTargetChange:ef,onTraceEvent:f,runtimeConsoleTarget:y,widgets:x})})]}):null,j?(0,i.jsx)(lu,{onAction:ev,onClose:ey,onRemove:e_,removingTaskIds:D.removingTaskIds,tasks:D.tasks}):null]})}function lV(e){let{appIcon:t}=e,[r,n]=(0,rc.useState)(!1);return((0,rc.useEffect)(()=>{n(!1)},[t]),!t||r)?null:(0,i.jsx)("img",{alt:"",className:"wsd-simulator-permission-app-icon",onError:()=>n(!0),src:t})}function lG(e){let{onAllow:t,onReject:r,permission:n}=e;return(0,i.jsxs)("div",{className:"wsd-simulator-permission-layer",children:[(0,i.jsx)("div",{"aria-hidden":"true",className:"wsd-simulator-permission-backdrop"}),(0,i.jsxs)("dialog",{"aria-label":`${n.appName}权限申请`,"aria-modal":"true",className:"wsd-simulator-permission-dialog",open:!0,children:[(0,i.jsxs)("header",{className:"wsd-simulator-permission-brand",children:[(0,i.jsx)(lV,{appIcon:n.appIcon}),(0,i.jsx)("strong",{children:n.appName})]}),(0,i.jsxs)("section",{className:"wsd-simulator-permission-content",children:[(0,i.jsx)("h2",{children:n.title}),(0,i.jsx)("p",{children:n.description})]}),(0,i.jsxs)("footer",{className:"wsd-simulator-permission-actions",children:[(0,i.jsx)("button",{className:"is-primary",onClick:t,type:"button",children:"允许"}),(0,i.jsx)("button",{className:"is-secondary",onClick:r,type:"button",children:"拒绝"})]})]})]})}function lJ(){let[e,t]=(0,rc.useState)(),r=(0,rc.useRef)(null),n=oQ(e=>r.current?Promise.reject(Error("Simulator permission prompt is already open")):new Promise(n=>{r.current=n,t(e)})),a=oQ(e=>{let n=r.current;n&&(r.current=null,t(void 0),n(e))}),i=oQ(()=>a(!0)),s=oQ(()=>a(!1));return(0,rc.useEffect)(()=>()=>{let e=r.current;r.current=null,null==e||e(!1)},[]),{allowPermission:i,permission:e,rejectPermission:s,showPermission:n}}var lK=e=>(0,i.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",width:13,height:13,fill:"none",viewBox:"0 0 13 13",...e,children:(0,i.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"})}),lX=r(35668),lQ=r(27860),lY=r(26661),lZ=e=>(0,i.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",width:12,height:15,fill:"none",viewBox:"0 0 12 15",...e,children:(0,i.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 l0=[{key:"conversation",label:"对话"},{key:"tool",label:"工具"},{key:"card",label:"卡片"},{key:"page",label:"全页"}],l1=[{label:"iOS",devices:nL.filter(e=>e.key.startsWith("iphone"))},{label:"Android",devices:nL.filter(e=>e.key.startsWith("pixel")||e.key.startsWith("galaxy"))},{label:"平板",devices:nL.filter(e=>e.key.startsWith("ipad"))}];function l2(e){let{activeView:t,children:r,onActiveViewChange:n,onDeviceChange:a,selectedDeviceKey:s}=e,[o,l]=(0,rc.useState)(!1),[d,u]=(0,rc.useState)(),c=nU(s??nj),[p,m]=(0,rc.useState)(()=>String(c.width)),[h,g]=(0,rc.useState)(()=>String(c.height)),f=(0,rc.useRef)(null),v=(null==s?void 0:s.startsWith("custom-"))===!0&&c.key===s,y=(e,t)=>{let r=`custom-${e}x${t}`;nU(r).key===r&&(null==a||a(r))};return(0,rc.useEffect)(()=>{let e=e=>{var t;(null==(t=f.current)?void 0:t.contains(e.target))||l(!1)},t=e=>{"Escape"===e.key&&l(!1)};return window.addEventListener("pointerdown",e),window.addEventListener("keydown",t),()=>{window.removeEventListener("pointerdown",e),window.removeEventListener("keydown",t)}},[]),(0,i.jsxs)("header",{className:"wsd-preview-device-toolbar",ref:f,children:[(0,i.jsxs)("div",{className:"wsd-device-toolbar-leading",children:[(0,i.jsx)("button",{"aria-label":"手机预览","aria-expanded":o,"aria-haspopup":"dialog","aria-pressed":"phone"===d,className:(0,e6.$)("wsd-device-toolbar-icon","phone"===d&&"is-active"),onClick:()=>{u("phone"),o||(m(String(c.width)),g(String(c.height))),l(e=>!e)},type:"button",children:(0,i.jsx)(lZ,{"aria-hidden":"true"})}),o?(0,i.jsxs)("dialog",{"aria-label":"选择模拟器类型",className:"wsd-preview-toolbar-menu",open:!0,children:[(0,i.jsx)("div",{className:"wsd-custom-device-size-label",children:"自定义"}),(0,i.jsxs)("div",{className:(0,e6.$)("wsd-custom-device-size",v&&"is-selected"),children:[(0,i.jsx)("input",{"aria-label":"自定义宽度",className:"wsd-custom-device-size-input",max:9999,min:1,onChange:e=>{let t=e.currentTarget.value;m(t),y(t,h)},step:1,type:"number",value:p}),(0,i.jsx)("span",{"aria-hidden":"true",className:"wsd-custom-device-size-separator",children:"×"}),(0,i.jsx)("input",{"aria-label":"自定义高度",className:"wsd-custom-device-size-input",max:9999,min:1,onChange:e=>{let t=e.currentTarget.value;g(t),y(p,t)},step:1,type:"number",value:h}),(0,i.jsx)("span",{"aria-hidden":"true",className:"wsd-custom-device-size-check",children:"✓"})]}),(0,i.jsx)(lX.o,{"aria-label":"选择预设机型",className:"wsd-preview-toolbar-device-menu",selectedKeys:!v&&s?[s]:[],selectionMode:"single",onAction:e=>{null==a||a(String(e)),l(!1)},children:l1.map(e=>(0,i.jsx)(lQ.g,{showDivider:e!==l1.at(-1),title:e.label,children:e.devices.map(e=>(0,i.jsx)(lY.Y,{title:e.label,children:e.label},e.key))},e.label))})]}):null,(0,i.jsx)("button",{"aria-label":"设置","aria-pressed":"settings"===d,className:(0,e6.$)("wsd-device-toolbar-icon","settings"===d&&"is-active"),onClick:()=>{u("settings"),l(!1)},type:"button",children:(0,i.jsx)(ln,{"aria-hidden":"true"})})]}),(0,i.jsx)("div",{className:"wsd-debug-mode-slot",children:(0,i.jsx)("nav",{"aria-label":"调试视图",className:"wsd-debug-mode-tabs",role:"tablist",children:l0.map(e=>(0,i.jsx)("span",{"aria-selected":t===e.key,className:(0,e6.$)("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,i.jsxs)("div",{className:"wsd-page-toolbar-actions",children:[(0,i.jsx)(o2,{}),r]})]})}function l3(e){var t;let{children:r,runtime:n,showReloadButton:a=!0,toolbarView:s=n.activeView}=e,o="card"===n.activeView?n.devtoolsTarget:n.devtoolsTarget??(null==(t=n.conversationControlTarget)?void 0:t.target)??null,l=(0,rc.useMemo)(()=>({consoleTarget:"conversation"===n.activeView?n.conversationConsoleTarget:void 0,controlCommand:n.controlCommand,controlTarget:o,debugState:n.debugState,frontendUrl:n.chromeDevToolsFrontendUrl,getRuntimeFrame:n.getRuntimeFrame,onConsoleSnapshotChange:n.setRuntimeConsoleSnapshot,onControlResult:n.onControlResult,onDebugAction:n.handleDebugAction,onHighlightChange:n.setHighlightRect,onRuntimeSnapshotChange:n.setRuntimeDomSnapshot,runtimeSnapshotTarget:n.runtimeSnapshotTarget,resolveTargetAtPoint:"conversation"===n.activeView?n.resolveConversationInspectTarget:void 0,showPanelId:n.devToolsPanelId,showPanelRequestId:n.latestDevToolsPanelRequestId,target:o}),[n.activeView,o,n.chromeDevToolsFrontendUrl,n.controlCommand,n.conversationConsoleTarget,n.debugState,n.devToolsPanelId,n.devtoolsTarget,n.getRuntimeFrame,n.handleDebugAction,n.latestDevToolsPanelRequestId,n.onControlResult,n.resolveConversationInspectTarget,n.runtimeSnapshotTarget,n.setHighlightRect,n.setRuntimeConsoleSnapshot,n.setRuntimeDomSnapshot]);return(0,rc.useEffect)(()=>{var e;null==(e=n.onChromeDevToolsPanelChange)||e.call(n,l)},[l,n.onChromeDevToolsPanelChange]),(0,i.jsxs)("div",{className:(0,e6.$)("wsd-widget-preview-column","card"===n.activeView&&"is-card-debug"),children:[(0,i.jsx)(l2,{activeView:s,onActiveViewChange:n.onActiveViewChange,onDeviceChange:n.setSelectedDeviceKey,selectedDeviceKey:n.selectedDeviceKey,children:a?(0,i.jsx)("button",{"aria-label":"刷新资源并重载卡片",className:"wsd-icon-button",disabled:!n.canReloadResources,onClick:n.reloadResources,title:"streaming"===n.simulatorState.streamStatus?"对话生成中暂不能刷新资源":"刷新资源并重载卡片",type:"button",children:(0,i.jsx)(lK,{"aria-hidden":"true"})}):null}),r]})}function l4(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return{type:"callback",callbackId:e.callbackId,params:{code:1,data:t}}}let l5=["agreeMain","agreeSub","reject"],l8={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"},l6={error:"error",success:"success",warning:"warn"};function l7(e){return Array.isArray(e.itemList)?e.itemList:[]}function l9(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 n 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"}}(n);if(!t)return null;r.push(t)}return r}(t.body.childNodes)}function de(e){let{content:t}=e,r=(0,rc.useMemo)(()=>l9(t)??[],[t]);return(0,i.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,n)=>{if("text"===t.type)return t.value;let a=`${r}-${n}`,s=e(t.children,a);return"paragraph"===t.type?(0,i.jsx)("p",{children:s},a):"bold"===t.type?(0,i.jsx)("b",{children:s},a):"link"===t.type?(0,i.jsx)("a",{href:t.href,rel:"noreferrer",target:"_blank",children:s},a):null})}(r)})}function dt(e){let{scanner:t}=e,r=(0,rc.useRef)(null),n=(0,rc.useRef)(null);return(0,rc.useEffect)(()=>{let e=n.current;e&&t.options.onVideoReady(e)},[t.options]),(0,i.jsxs)("div",{"aria-label":"扫码",className:"wsd-simulator-scan-code",children:[(0,i.jsx)("video",{autoPlay:!0,muted:!0,playsInline:!0,ref:n}),(0,i.jsx)("div",{className:"wsd-simulator-scan-code-message",children:t.message}),(0,i.jsxs)("div",{className:"wsd-simulator-scan-code-actions",children:[(0,i.jsx)("button",{onClick:t.options.onCancel,type:"button",children:"关闭"}),(0,i.jsx)("button",{onClick:t.options.onCapture,type:"button",children:"识别"}),t.options.allowImageUpload?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("button",{onClick:()=>{var e;return null==(e=r.current)?void 0:e.click()},type:"button",children:"相册"}),(0,i.jsx)("input",{accept:"image/*",hidden:!0,onChange:e=>{var r;let n=null==(r=e.currentTarget.files)?void 0:r[0];e.currentTarget.value="",n&&t.options.onFile(n)},ref:r,type:"file"})]}):null]})]})}function dr(e){let{children:t,className:r,exiting:n=!1,onDismiss:a}=e;return(0,i.jsxs)("div",{className:`wsd-simulator-overlay-interaction${r?` ${r}`:""}${n?" is-exiting":""}`,children:[(0,i.jsx)("div",{"aria-hidden":"true",className:"wsd-simulator-overlay-backdrop",onClick:a}),t]})}function dn(e){var t;let{interaction:r,onActionSheetSelect:n,onBottomSheetSelect:a,onDismiss:s,onModalResult:o}=e,l=()=>s(r);if("modal"===r.kind){let{params:e}=r,t=!1!==e.showCancel;return(0,i.jsx)(dr,{className:"is-modal",exiting:r.exiting,onDismiss:l,children:(0,i.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,i.jsx)("h2",{className:"wsd-simulator-modal-title",children:e.title}):null,(0,i.jsx)("p",{className:"wsd-simulator-modal-message",children:e.content||""}),(0,i.jsxs)("footer",{className:`wsd-simulator-modal-actions${t?"":" is-single"}`,children:[t?(0,i.jsx)("button",{className:"wsd-simulator-modal-button is-cancel",onClick:()=>o(r.id,"cancel"),type:"button",children:e.cancelText||"cancel"}):null,(0,i.jsx)("button",{className:"wsd-simulator-modal-button is-confirm",onClick:()=>o(r.id,"confirm"),type:"button",children:e.confirmText||"confirm"})]})]})})}if("actionSheet"===r.kind){let e=l7(r.params);return(0,i.jsx)(dr,{onDismiss:l,children:(0,i.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,i.jsx)("h2",{children:r.params.title}):null,(0,i.jsx)("div",{className:"wsd-simulator-overlay-list",children:e.map((e,t)=>(0,i.jsx)("button",{className:"wsd-simulator-overlay-list-item",onClick:()=>n(r.id,t),style:r.params.itemColor?{color:r.params.itemColor}:void 0,type:"button",children:e},`${e}-${t}`))})]})})}let d=Array.isArray((t=r.params).buttons)?t.buttons:[];return(0,i.jsx)(dr,{onDismiss:l,children:(0,i.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,i.jsx)("h2",{children:r.params.title}):null,r.params.content?(0,i.jsx)(de,{content:r.params.content}):null,(0,i.jsx)("div",{className:"wsd-simulator-overlay-actions",children:d.map(e=>(0,i.jsx)("button",{className:`wsd-simulator-overlay-button ${"reject"===e.role?"is-secondary":"is-primary"}`,onClick:()=>a(r.id,e.role),type:"button",children:e.text},e.role))})]})})}function da(e){let{interaction:t,loading:r,onActionSheetSelect:n,onBottomSheetSelect:a,onDismiss:s,onModalResult:o,scanner:l,toast:d}=e;return(0,i.jsxs)("div",{className:"wsd-simulator-overlay-layer wsd-simulator-overlay-host",children:[r?(0,i.jsxs)("div",{"aria-live":"polite",className:"wsd-simulator-loading",children:[(0,i.jsx)("span",{className:"wsd-simulator-loading-spinner"}),(0,i.jsx)("span",{children:"Loading..."})]}):null,d?(0,i.jsxs)("output",{"aria-live":"polite",className:`wsd-simulator-toast is-${d.type}${d.exiting?" is-exiting":""}`,children:[function(e){if(e.customIcon)return(0,i.jsx)("img",{alt:"",className:"wsd-simulator-toast-icon",src:e.customIcon});let t=e.icon||l6[e.type];return t?(0,i.jsx)("svg",{"aria-hidden":"true",className:`wsd-simulator-toast-icon is-${t}`,focusable:"false",viewBox:"0 0 24 24",children:(0,i.jsx)("path",{d:l8[t]})}):null}(d),(0,i.jsx)("span",{className:"wsd-simulator-toast-message",children:d.message})]},d.id):null,l?(0,i.jsx)(dt,{scanner:l}):null,t?(0,i.jsx)(dn,{interaction:t,onActionSheetSelect:n,onBottomSheetSelect:a,onDismiss:s,onModalResult:o}):null]})}function di(){let[e,t]=(0,rc.useState)(null),[r,n]=(0,rc.useState)(!1),[a,s]=(0,rc.useState)(null),o=(0,rc.useRef)(null),l=(0,rc.useRef)(),d=(0,rc.useRef)(0),u=(0,rc.useRef)(0),c=(0,rc.useRef)(0),p=(0,rc.useRef)(null),[m,h]=(0,rc.useState)(null),g=(0,rc.useRef)(null),f=(0,rc.useRef)(),v=(0,rc.useRef)(),y=oQ((e,r,n)=>{let a=o.current;a&&a.id===e&&(l.current&&(clearTimeout(l.current),l.current=void 0),n?a.reject(n):a.resolve(r),o.current=null,t(null))}),_=oQ(()=>{let e=o.current;e&&("modal"===e.kind?y(e.id,{action:"cancel"}):"bottomSheet"===e.kind?y(e.id,{action:"cancel",source:"unknown"}):y(e.id,void 0,Error("action sheet selection was cancelled")))}),b=oQ((e,r,n,a)=>{l.current&&(clearTimeout(l.current),l.current=void 0),_();let i={exiting:!1,id:++d.current,kind:e,params:r,reject:a,resolve:n};o.current=i,t({exiting:i.exiting,id:i.id,kind:i.kind,params:i.params})}),w=oQ(()=>{v.current&&(clearTimeout(v.current),v.current=void 0),f.current&&(clearTimeout(f.current),f.current=void 0)}),S=oQ(e=>{var t;(null==(t=g.current)?void 0:t.id)===e&&(g.current=null,f.current=void 0,s(null))}),x=oQ(()=>{let e=g.current;if(!e||e.exiting)return;v.current&&(clearTimeout(v.current),v.current=void 0);let t={...e,exiting:!0};g.current=t,s(t),f.current=setTimeout(()=>S(e.id),180)}),I=oQ(e=>{w();let t="number"==typeof e.duration&&e.duration>=0?e.duration:2e3,r={customIcon:e.customIcon,exiting:!1,id:++c.current,icon:e.icon,message:"string"==typeof e.message?e.message:"",type:e.type||"default"};g.current=r,s(r),t>0&&(v.current=setTimeout(x,Math.max(0,t-180)))}),E=oQ(e=>{var t;(null==(t=p.current)?void 0:t.id)===e&&(p.current=null,h(null))}),C=oQ((e,t)=>{let r=p.current;if((null==r?void 0:r.id)!==e)return;let n={...r,message:t};p.current=n,h(n)}),k=oQ(e=>{var t;null==(t=p.current)||t.options.onCancel();let r=++u.current,n={id:r,message:"正在打开摄像头...",options:e};return p.current=n,h(n),{close:()=>E(r),setMessage:e=>C(r,e)}}),N=oQ(e=>new Promise((t,r)=>{b("modal",e,t,r)})),T=oQ(e=>new Promise((t,r)=>{0===l7(e).length?r(Error("itemList must contain at least one item")):b("actionSheet",e,t,r)})),R=oQ(e=>new Promise((t,r)=>{let n=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(!l9(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,n=l5.find(e=>e===t);if(!n)return"button role is invalid";if(r.has(n))return"button roles must be unique";r.add(n);let a="text"in e?e.text:void 0;if("string"!=typeof a||""===a.trim())return"button text must not be empty"}return null}(e);n?r(Error(n)):b("bottomSheet",e,t,r)})),M=oQ((e,r)=>{let n=o.current;n&&n.id===e&&"modal"===n.kind&&(n.resolve(r),o.current=null,t(t=>(null==t?void 0:t.id)===e?{...t,exiting:!0}:t),l.current=setTimeout(()=>{l.current=void 0,t(t=>(null==t?void 0:t.id)===e?null:t)},200))}),A=oQ((e,t)=>{let r=o.current;r&&r.id===e&&M(e,{action:t})}),P=oQ((e,t)=>{let r=o.current;r&&r.id===e&&"actionSheet"===r.kind&&y(e,{tapIndex:t})}),j=oQ((e,t)=>{let r=o.current;r&&r.id===e&&"bottomSheet"===r.kind&&y(e,{action:"buttonClick",role:t})}),L=oQ(e=>{let t=o.current;if(t&&t.id===e.id)if("modal"===e.kind){if(!1===e.params.tapMaskToDismiss)return;M(e.id,{action:"mask"})}else if("bottomSheet"===e.kind){var r;if((null==(r=e.params.behavior)?void 0:r.dismissOnMaskTap)===!1)return;y(e.id,{action:"cancel",source:"mask"})}else y(e.id,void 0,Error("action sheet selection was cancelled"))});(0,rc.useEffect)(()=>()=>{var e;w(),g.current=null,l.current&&(clearTimeout(l.current),l.current=void 0);let t=o.current;t&&(t.reject(Error("simulator overlay was unmounted")),o.current=null),null==(e=p.current)||e.options.onCancel(),p.current=null},[]);let D=(0,rc.useMemo)(()=>({hideLoading:()=>n(!1),hideToast:x,showActionSheet:T,showBottomSheet:R,showLoading:()=>n(!0),showModal:N,showToast:I}),[x,T,R,N,I]);return{overlay:(0,i.jsx)(da,{interaction:e,loading:r,onActionSheetSelect:P,onBottomSheetSelect:j,onDismiss:L,onModalResult:A,scanner:m,toast:a}),presenter:D,scanCodePresenter:k}}function ds(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 dl(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 dd(e){return(null==e?void 0:e.raw)??{}}function du(e,t){for(let r=e.length-1;r>=0;r-=1){let n=e[r].payload;if((null==n?void 0:n.event)===t)return n}}function dc(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 dp(e,t,r){let n=new Set(["missing","fetch_started","load_started","fetch_failed","load_failed","fetch_succeeded","loaded","empty"].map(e=>`simulator_${t}_${e}`)),a=e.map(e=>e.payload).findLast(e=>n.has(e.event)),i=(null==a?void 0:a.event)||"",s=function(){for(var e=arguments.length,r=Array(e),n=0;n<e;n++)r[n]=arguments[n];return r.some(e=>i===`simulator_${t}_${e}`)};if(a&&s("fetch_succeeded","loaded")){let e="skill"===t&&Array.isArray(a.skill_paths)?a.skill_paths.filter(Boolean).map(e=>e.startsWith("./")?e:`./${e}`):[];return{bytes:a.bytes??a.skill_length??a.skills_length,detail:a.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"}:a&&s("fetch_failed","load_failed")?{detail:a.error||a.url||r,label:"加载失败",tone:"error"}:a&&s("fetch_started","load_started")?{detail:a.url||r,label:"加载中",tone:"pending"}:{detail:r,label:"检查中",tone:"pending"}}function dm(e){return"string"==typeof e?e.trim():e.name||e.id||""}function dh(){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 dg(e,t,r,n){if(!e)return"";if(n.startsWith(`${t}/`)){let e=n.replace(/\.web\.bundle$/g,"").replace(/\.bundle$/g,"").replace(/\.template\.js$/g,"").replace(/\.js$/g,"");return dh("src",/\.(tsx|ts|jsx|js)$/.test(e)?e:`${e}.tsx`)}return!r||r.startsWith("__")?"":dh("src",t,r,"index.tsx")}function df(e){var t,r,n,a,i;let s,o,l,d,u,c,p,m,h,g,f,{context:v,events:y,manifest:_,pages:b=[],widgets:w}=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=dd(_).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)||"",E=(null==v?void 0:v.mcpProxyEndpoint)||(null==v?void 0:v.mcpEndpoint)||"",C=(null==v?void 0:v.simulatorManifestOriginalUrl)||"",k=(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)||"",R=(null==v?void 0:v.simulatorBusinessTemplatesRelativePath)||"",M=(null==v?void 0:v.simulatorManifestUrl)||(null==v?void 0:v.simulatorManifestProxyUrl)||"",A=(null==v?void 0:v.simulatorSkillsDirectoryOriginalUrl)||(null==v?void 0:v.simulatorSkillsIndexOriginalUrl)||"",P=(null==v?void 0:v.simulatorSkillsIndexProxyUrl)||(null==v?void 0:v.simulatorSkillsIndexUrl)||"",j=(null==v?void 0:v.simulatorSkillsDirectoryRelativePath)||"",L=(null==v?void 0:v.simulatorSkillsIndexUrl)||(null==v?void 0:v.simulatorSkillsIndexProxyUrl)||"",D=dc(M,C,"/__simulator_manifest/manifest.yaml"),O=dc(L,A,"/__simulator_skills/index.json"),U=dc(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=dm(r);e&&t.add(e)}for(let r of e.mcp_servers??[])for(let e of r.tools??[]){let r=dm(e);r&&t.add(r)}}return[...t]}(y),$=function(e){let t=new Map,r=function(e,r){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",a="string"==typeof r?r:r.widget_id||r.widgetId||r.widget,i="string"==typeof r?n:r.entity_type||r.entityType||r.entity||n;e&&a&&t.set(`${e}:${a}:${i}`,{entityType:i,toolName:e,widgetId:a})},n=dd(e);for(let[e,t]of Object.entries(n.tool_card_binding??{}))r(e,t);for(let[e,t]of Object.entries(n.entities??{})){let n=t.entity_type||t.entityType||e;for(let[e,a]of Object.entries(t.tool_card_binding??{}))r(e,a,n)}return[...t.values()]}(_),B={manifest:dp(y,"manifest",D),mcp:(l=du(y,"local_mcp_missing"),d=du(y,"local_mcp_tools_load_started"),u=du(y,"local_mcp_tools_load_failed"),c=du(y,"local_mcp_tools_loaded"),p=du(y,"client_tools_resolved"),m=du(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"}:m?{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:dp(y,"skill",O)},F=!!D||"success"===B.manifest.tone,W=!!O||"success"===B.skill.tone,H=!!U||"success"===B.mcp.tone,z={businessTemplates:T?{detail:R||T,label:"已加载",tone:"success"}:{detail:"",label:"未配置",tone:"muted"},manifest:{...B.manifest,detail:N||B.manifest.detail},mcp:B.mcp,skill:{...B.skill,detail:j||B.skill.detail}};return{appId:(h=dd(_),(null==_?void 0:_.appId)||h.appId||h.app_key||(null==(t=h.applet)?void 0:t.appletId)||""),appName:(g=dd(_),(null==_?void 0:_.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:(n=_,f=(null==(s=function(e,t){if(t)return e.find(e=>t.startsWith("/")?e.path===t:e.id===t)}(a=b,null==(i=dd(n).applet)?void 0:i.appletEntry)??a.find(e=>"index"===e.id||"/pages/index"===e.path||"/pages/index/index"===e.path)??a[0])?void 0:s.path)||"",b.map(e=>({entry:dg(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:z,sources:{manifest:{original:F?C:"",proxy:F?k||M:""},mcp:{original:H?I:"",proxy:H?E:""},skill:{original:W?A:"",proxy:W?P||L:""}},widgets:function(e,t,r){let n=new Map;for(let e of t){let t=n.get(e.widgetId)??[];t.push(e.toolName),n.set(e.widgetId,t)}return e.filter(ry).map(e=>({boundTools:n.get(e.widgetId)??[],entry:dg(r,"widgets",e.widgetId,e.entry||""),name:e.name||"",widgetId:e.widgetId}))}(w,$,S)}}function dv(e,t,r){return!!(e&&t&&t!==r&&e.sourceTarget===t)}function dy(e,t){return{pages:e.pages.map(e=>{let{isHome:t,name:r,pageId:n,path:a}=e;return{isHome:t,name:r,pageId:n,path:a}}),widgets:e.widgets.map(e=>{let{name:t,widgetId:r}=e;return{name:t,widgetId:r}}),currentTarget:t}}function d_(e,t,r){let n=0,a=!1,i=()=>{a=!0},s=e=>{if(n>=5e3)return a=!0,null;n+=1;let t=e.children.map(s).filter(e=>null!==e);return{uid:e.id,type:e.type,name:"text"===e.type?"#text":ow(e),attributes:"element"===e.type?o_(e).map(e=>{var t;return{name:e.name,value:(t=e.value,t.length<=500?t:(i(),`${t.slice(0,499)}…`))}}):[],children:t,accessibility:e.accessibility,text:e.textContent}};return{root:e?s(e):null,selectedUid:t,nodeCount:n,truncated:a,sourceTarget:r,updatedAtMs:Date.now()}}let db={message:"未上传",tone:"muted"},dw={message:"已上传",tone:"success"},dS=db,dx=new Set;function dI(e){return dx.add(e),()=>dx.delete(e)}function dE(){return dS}function dC(e){for(let t of(dS=e,dx))t()}function dk(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:db.message;dC({message:e,tone:"muted",updatedAtMs:Date.now()})}function dN(e){let t=(0,rc.useSyncExternalStore)(dI,dE,dE);return(0,rc.useEffect)(()=>{void 0!==e&&dC(e?dw:db)},[e]),t}let dT={message:"可用",tone:"success"},dR={message:"不可用",tone:"error"},dM=dT,dA=new Set;function dP(e){return dA.add(e),()=>dA.delete(e)}function dj(){return dM}function dL(e){for(let t of(dM=e,dA))t()}function dD(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0],t=(0,rc.useSyncExternalStore)(dP,dj,dj);return(0,rc.useEffect)(()=>{dL(e?dT:dR)},[e]),t}function dO(e){var t,r,n;let a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("locate-sandbox-location"===e.kind)return n3.requestBrowserLocation().then(e=>{var t,r;"success"===e.status?null==(t=a.onMessage)||t.call(a,"浏览器定位已配置"):null==(r=a.onMessage)||r.call(a,`浏览器定位失败:${e.message}`,!0)}),!0;if("update-sandbox-location"===e.kind){try{n3.setManualLocation({latitude:e.latitude,longitude:e.longitude}),null==(t=a.onMessage)||t.call(a,"模拟位置已配置")}catch(t){let e=t instanceof Error?t.message:String(t);n3.setConfigurationError(e),null==(r=a.onMessage)||r.call(a,`坐标配置失败:${e}`,!0)}return!0}return"clear-sandbox-bridge-logs"===e.kind?(a.onClearLogs?a.onClearLogs().then(()=>{var e;return null==(e=a.onMessage)?void 0:e.call(a,"服务端交互日志已清空")}).catch(e=>{var t;return null==(t=a.onMessage)?void 0:t.call(a,e.message,!0)}):null==(n=a.onMessage)||n.call(a,"服务端日志接口不可用",!0),!0):"recreate-sandbox-session"===e.kind?(dL({message:"正在重建",tone:"pending",updatedAtMs:Date.now()}),iq({csrPem:e.csrPem,phoneNum:e.phoneNum}).then(t=>{var r,n,i,s,o;let l=(null==(r=t.data)?void 0:r.business_info_uploaded)===!0;l?dC({message:"已上传",tone:"success",updatedAtMs:Date.now()}):dk(),dL({message:"已重建",tone:"success",updatedAtMs:Date.now()}),l?null==(s=a.onUpdated)||s.call(a):null==(o=a.onRecreated)||o.call(a),null==(i=a.onMessage)||i.call(a,`调试会话已重建${l?`,${e.csrPem.trim()?"手机号和证书":"手机号"}已自动上传`:""}:${(null==(n=t.data)?void 0:n.sandbox_session_id)??""}`)}).catch(e=>{var t,r;let n=`重建调试会话失败:${e.message}`;dk(),dL({errorMessage:n,message:"重建失败",tone:"error",updatedAtMs:Date.now()}),null==(t=a.onRecreated)||t.call(a),null==(r=a.onMessage)||r.call(a,n,!0)}),!0):"update-sandbox-business-info"===e.kind&&(dC({message:"正在上传...",tone:"pending",updatedAtMs:Date.now()}),iO({csrPem:e.csrPem,phoneNum:e.phoneNum}).then(()=>{var e,t;dC({message:"上传成功",tone:"success",updatedAtMs:Date.now()}),null==(e=a.onUpdated)||e.call(a),null==(t=a.onMessage)||t.call(a,"上传成功")}).catch(e=>{var t;let r=e&&"object"==typeof e&&"logId"in e&&"string"==typeof e.logId?e.logId:"";dC({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:r}),null==(t=a.onMessage)||t.call(a,"上传失败",!0)}),!0)}function dU(e){let[t,r]=(0,rc.useState)(),n=(0,rc.useRef)(),a=(0,rc.useRef)(),i=oQ((e,t)=>{if(a.current===e.commandId)return!1;a.current=e.commandId;let i={previousTarget:t,command:e};return n.current=i,r(i),!0}),s=oQ((t,a)=>{var i;(null==(i=n.current)?void 0:i.command.commandId)===t&&(n.current=void 0,r(void 0),null==e||e(t,a))});return{accept:i,pending:t,pendingRef:n,report:s}}let dq="u"<typeof window?rc.useEffect:rc.useLayoutEffect;function d$(e,t){let[r,n]=(0,rc.useState)(nj),[a,i]=(0,rc.useState)("fit"),s=(0,rc.useRef)(),o=(0,rc.useMemo)(()=>nU(r),[r]),l=nD.find(e=>e.key===a)??nD.find(e=>"fit"===e.key)??nD[0],d="fit"===l.key,{fitScale:u,setRuntimeShellRef:c}=function(e){let{deviceHeight:t,deviceWidth:r,enabled:n}=e,[a,i]=(0,rc.useState)(.88),s=(0,rc.useRef)(null),o=(0,rc.useRef)(null),l=(0,rc.useCallback)(()=>{let e=s.current;if(!e)return;let n=getComputedStyle(e),a=Number.parseFloat(n.paddingLeft)+Number.parseFloat(n.paddingRight),o=Number.parseFloat(n.paddingTop)+Number.parseFloat(n.paddingBottom),l=Math.floor(1e3*Math.max(.1,Math.min(1,(e.clientWidth-a-12)/r,(e.clientHeight-o-12)/t)))/1e3;i(e=>Math.abs(e-l)>.001?l:e)},[t,r]),d=(0,rc.useCallback)(e=>{var t;if(null==(t=o.current)||t.disconnect(),o.current=null,s.current=e,!e||!n)return;let r=new ResizeObserver(l);r.observe(e),o.current=r,l()},[n,l]);return dq(()=>{n&&l()},[n,l]),dq(()=>()=>{var e;null==(e=o.current)||e.disconnect()},[]),{fitScale:a,setRuntimeShellRef:d}}({deviceHeight:o.height,deviceWidth:o.width,enabled:d}),p=d?u:l.scale,m=d?"fit":"fixed",h={"--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,rc.useEffect)(()=>{if((null==e?void 0:e.type)!=="set_viewport"||s.current===e.commandId)return;let a=`custom-${e.width}x${e.height}`;r!==a?n(a):(s.current=e.commandId,null==t||t(e.commandId,{ok:!0,result:{width:e.width,height:e.height}}))},[e,t,r]),{runtimeScaleMode:m,runtimeStyle:h,selectedDevice:o,selectedDeviceKey:r,selectedScaleKey:a,setRuntimeShellRef:c,setSelectedDeviceKey:n,setSelectedScaleKey:i}}function dB(){return(0,rc.useSyncExternalStore)(n3.subscribe,n3.getSnapshot,n3.getSnapshot)}function dF(e,t,r){(0,rc.useEffect)(()=>{if(!e)return;let n=setTimeout(()=>e.publishSnapshot(t,r),500);return()=>clearTimeout(n)},[e,t,r])}let dW={appEntries:[],entries:[],updatedAtMs:0};function dH(e,t){var r;return!t||e.traceId===t||(null==(r=e.trace)?void 0:r.trace_id)===t}function dz(e,t){var r;let{chromeDevToolsFrontendUrl:n,controlCommand:a,controlClientId:i,debugContext:s,onChromeDevToolsPanelChange:l,onActiveViewChange:d,onControlResult:c,onMessage:p,onNavigateToPage:m,apiEnvironment:h,showDebugTrace:g,connection:f,webSdkDebugger:v}=e,y=o4(v),_=(0,rc.useMemo)(()=>y.widgets.filter(ry),[y.widgets]),b=(0,rc.useRef)(null),w=(0,rc.useRef)(null),S=(0,rc.useRef)(null),x=(0,rc.useRef)(null),I=(0,rc.useRef)(null);!I.current&&"u">typeof document&&(I.current=document.createElement("div"));let[E,C]=(0,rc.useState)(0),k=oQ(()=>w.current),[N,T]=(0,rc.useState)(null),[R,M]=(0,rc.useState)(!1),[A,P]=(0,rc.useState)(0),[j,L]=(0,rc.useState)(!1),[D,O]=(0,rc.useState)([]),[U,q]=(0,rc.useState)(dW),[$,B]=(0,rc.useState)(null),[F,W]=(0,rc.useState)(null),[H,z]=(0,rc.useState)(null),[V,G]=(0,rc.useState)(),[J,K]=(0,rc.useState)(0),[X,Q]=(0,rc.useState)(0),[Y,Z]=(0,rc.useState)(0),ee=o9(),et=di(),er=lJ(),en=(null==s?void 0:s.sandboxSessionAvailable)!==!1,ea=dl(s),[ei,es]=(0,rc.useState)(!0!==ea),eo=dN(ea),el=dB(),ed=dD(en),{bridgeLogs:eu,clearBridgeLogs:ec}=lb(),ep=(0,rc.useRef)(null),em=(0,rc.useMemo)(()=>x.current,[E]),{accept:eh,pending:eg,pendingRef:ef,report:ev}=dU(c),ey=(0,rc.useRef)(),e_=(0,rc.useRef)(new Map),eb=(0,rc.useRef)(new Map),ew=(0,rc.useRef)(0),{runtimeScaleMode:eS,runtimeStyle:ex,selectedDevice:eI,selectedDeviceKey:eE,setRuntimeShellRef:eC,setSelectedDeviceKey:ek}=d$(a,c),eN=(0,rc.useRef)(eE),eT=(null==(r=y.widgetSelection)?void 0:r.item.widgetId)??"",eR=(0,rc.useRef)(eT),eM=y.simulator,eA=(0,rc.useRef)(eM.toolCalls),eP=!!y.widgetSelection&&"streaming"!==eM.streamStatus&&!j,ej=(0,rc.useMemo)(()=>({...nO,density:eI.density,label:eI.label,width:Math.max(1,eI.width-38)}),[eI.density,eI.label,eI.width]);(0,rc.useEffect)(()=>{eA.current=eM.toolCalls},[eM.toolCalls]);let eL=oQ(e=>{let t=function(e,t){var r;if(!e8(e))return{};let n=e.source_tool_call_id,a=n?t.find(e=>e.toolCallId===n):void 0;if(!a)return e;let i=e.trace??{};return{...e,request_id:e.request_id||a.requestId,trace_id:e.trace_id||i.trace_id||(null==(r=a.trace)?void 0:r.trace_id)}}(e,eA.current),r=++ew.current,n={display:rW(t),id:`trace-${r}`,order:r,payload:t,timestamp:Date.now()};O(e=>[...e,n].slice(-200))}),eD=oQ(()=>{O([])}),eO=(0,rc.useMemo)(()=>[...eM.traceEvents.map((e,t)=>({event:e,sortOrder:e.order??t})),...D.map((e,t)=>({event:e,sortOrder:e.order??eM.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}),[D,eM.traceEvents]),eU=(0,rc.useMemo)(()=>({...s,manifestUrl:y.manifestUrl,simulatorEndpoint:eM.endpoint}),[s,eM.endpoint,y.manifestUrl]),eq=(0,rc.useMemo)(()=>df({context:eU,events:eO,manifest:y.manifest,pages:y.pages,widgets:y.widgets}),[eO,eU,y.manifest,y.pages,y.widgets]),e$=eq.appId,eB=eq.appName,eF=(0,rc.useMemo)(()=>({type:"widget",appId:e$,appName:eB,widgetId:eT,viewport:{key:eI.key,label:eI.label,width:Math.max(1,eI.width-38),height:eI.height,density:eI.density}}),[e$,eB,eI,eT]),eW=(0,rc.useMemo)(()=>dy(eq,"card"===t&&y.widgetSelection?eF:null==H?void 0:H.targetInfo),[t,H,eF,eq.pages,eq.widgets,y.widgetSelection]),eH=!!(eg&&dv($,em,eg.previousTarget)&&"card"===t&&eT===eg.command.widgetId),ez=(0,rc.useMemo)(()=>{let e="card"===t?em:null==H?void 0:H.target,r="card"===t?eF:null==H?void 0:H.targetInfo;return e&&r&&(null==$?void 0:$.sourceTarget)===e?{target:r,root:$.root,nodeCount:$.nodeCount,selectedUid:$.selectedUid,truncated:$.truncated,updatedAtMs:$.updatedAtMs}:void 0},[t,H,eF,$,em]),eV=(0,rc.useMemo)(()=>({exported_at:new Date().toISOString(),client_id:i,command_id:eH?null==eg?void 0:eg.command.commandId:void 0,context:{...ds({appId:e$,appName:eq.appName,debugContext:eU,manifestUrl:y.manifestUrl,simulatorEndpoint:eM.endpoint,sources:eq.sources}),widget_id:eT},render_targets:eW,runtime_snapshot:ez,simulator:{stream_status:eM.streamStatus,active_request_id:eM.activeRequestId,active_reply_message_id:eM.activeReplyMessageId,error:eM.error,answer_finish:eM.answerFinish,messages:eM.messages,tool_calls:eM.toolCalls,trace_events:eM.traceEvents},runtime_console:{app:{entries:U.appEntries,updated_at_ms:U.updatedAtMs},widget:{entries:U.entries,updated_at_ms:U.updatedAtMs}},widget_runtime_trace_events:D}),[D,eq.sources.manifest.original,eq.sources.manifest.proxy,eq.sources.mcp.original,eq.sources.mcp.proxy,eq.sources.skill.original,eq.sources.skill.proxy,eU.launchDir,eU.mcpEndpoint,eU.simulatorManifestUrl,eU.simulatorSkillsIndexUrl,eU.webUrl,U,eT,eM,e$,i,eH,null==eg?void 0:eg.command.commandId,eW,y.manifest.name,y.manifestUrl,ez]),eG=oQ(e=>{v.approveSimulatorToolCall(e).catch(e=>{null==p||p(e.message,!0)})}),eJ=oQ(e=>{v.rejectSimulatorToolCall(e).catch(e=>{null==p||p(e.message,!0)})}),eK=oQ(e=>{"clear-trace-filter"===e.kind?G(void 0):dO(e,{onClearLogs:ec,onMessage:p,onRecreated:()=>es(!0),onUpdated:()=>es(!1)})||("approve-tool-call"===e.kind||"reject-tool-call"===e.kind)&&("approve-tool-call"===e.kind?eG:eJ)(e.toolCallId)}),eX=oQ(e=>{G(t=>t===e?void 0:e)}),eQ=oQ(()=>{K(e=>Math.max(e,X)+1)});(0,rc.useEffect)(()=>{"success"===eo.tone&&es(!1)},[eo.tone]),(0,rc.useEffect)(()=>{void 0!==ea&&es(!ea)},[ea]);let eY=oQ(()=>{Q(e=>Math.max(e,J)+1)}),eZ=oQ(()=>{Q(e=>Math.max(e,J)+1),Z(e=>e+1)}),e0=oQ(e=>{e.stopPropagation(),es(!1)}),e1=Math.max(J,X);(0,rc.useEffect)(()=>{V&&!eM.messages.some(e=>dH(e,V))&&G(void 0)},[V,eM.messages]);let e2=(0,rc.useMemo)(()=>g?eO:eO.filter(e=>{var t;return!(null==(t=e.display)?void 0:t.debugOnly)}),[eO,g]),e3="conversation"===t?F:em,e4=oQ(e=>{W(e)}),e5=()=>{for(let e of eM.messages.slice().reverse())for(let t of e.blocks.slice().reverse()){if("card"!==t.type)continue;let r=eb.current.get(lA(e,t));if(null==r?void 0:r.target.isConnected)return r}let e=Array.from(eb.current.values()).reverse();return e.find(e=>e.target.isConnected)??e[0]??null},e6=oQ((e,t,r)=>{if(t){let n=eM.messages.slice().reverse().flatMap(t=>{let r=t.blocks.find(r=>"card"===r.type&&lA(t,r)===e);return(null==r?void 0:r.type)==="card"?[{card:r.card,message:t}]:[]})[0],a={target:t,targetInfo:{...eF,viewport:{...eF.viewport,width:r??eF.viewport.width},appId:null==n?void 0:n.card.app_id,widgetId:null==n?void 0:n.card.widget_id,cardId:null==n?void 0:n.card.card_id,requestId:null==n?void 0:n.message.requestId}};eb.current.set(e,a),z(e5());return}let n=eb.current.get(e);eb.current.delete(e),z(e=>n&&(null==e?void 0:e.target)===n.target?e5():e)}),e7=oQ((e,t)=>{var r;return(null==(r=Array.from(eb.current.values()).reverse().find(r=>{let n,{target:a}=r;return a.isConnected&&(n=a.getBoundingClientRect()).width>0&&n.height>0&&e>=n.left&&e<=n.right&&t>=n.top&&t<=n.bottom}))?void 0:r.target)??null}),e9=(0,rc.useMemo)(()=>t7(e2,{debug:g,messages:eM.messages,traceId:V}),[V,g,eM.messages,e2]),te=(0,rc.useMemo)(()=>V?eM.toolCalls.filter(e=>dH(e,V)):eM.toolCalls,[V,eM.toolCalls]),tt=(0,rc.useMemo)(()=>t6(eV,{debug:g,traceId:V}),[V,g,eV]),tr=(0,rc.useMemo)(()=>t4(tt),[tt]),tn=(0,rc.useMemo)(()=>({debugData:eq,events:e9,logSnapshot:tt,logSnapshotText:tr,sandbox:{available:en,csrRequired:(null==s?void 0:s.sandboxCsrRequired)!==!1,input:{csrPem:(null==s?void 0:s.sandboxCsrPem)??"",phoneNum:(null==s?void 0:s.sandboxPhoneNum)??""},logs:eu,businessInfoStatus:eo,location:el,locationFocusRequestId:Y,sessionStatus:ed},showDebugTrace:g,traceFilterId:V??"",traceSurface:"conversation",toolCalls:te,updatedAtMs:Date.now()}),[eq,te,e9,tt,tr,eu,en,eo,el,Y,ed,null==s?void 0:s.sandboxCsrRequired,V,g]);dF(f,eV,$),(0,rc.useEffect)(()=>{if((null==a?void 0:a.type)==="render_widget"&&eh(a,em))try{v.selectWidget(a.widgetId)}catch(e){ev(a.commandId,{ok:!1,error:{code:"TARGET_NOT_FOUND",message:e.message}})}},[eh,a,ev,v,em]),(0,rc.useEffect)(()=>{eg&&eH&&ev(eg.command.commandId,{ok:!0,target:eF,snapshot:t8(eV)})},[eF,eH,eg,ev,eV]);let ta=(0,rc.useMemo)(()=>{let e=(e,t,r)=>{var n;if("AppletBridgeModule"===r&&("postMessage"===e||"postMessageSync"===e)&&e8(n=t)&&"call"===n.type&&"string"==typeof n.name&&"number"==typeof n.callbackId){if("mind.getAgentTraceSwitch"===t.name)return l4(t,{value:!0});if("mind.reportAgentTraceEvent"===t.name)return eL(t.params??{}),l4(t)}};return(t,r,n,a)=>"AppletBridgeModule"===n&&"postMessage"===t&&o(r)&&"doubao.navigateTo"===r.name&&e8(r.params)&&"string"==typeof r.params.url?(null==m||m({url:r.params.url}),null==p||p(`卡片 navigateTo: ${r.params.url}`),u(r,{})):e(t,r,n,a)},[eL,p,m]),ti=(0,rc.useCallback)(e=>se({appId:e$,appIcon:y.manifest.iconSrc,appName:eB,baseAPIRegistry:null==h?void 0:h.apiRegistry,onCustomLoginNavigate:e=>null==m?void 0:m({url:e}),sendFollowUpMessage:e=>{let{content:t}=e;return v.sendSimulatorFollowUpMessage(t)},multiMediaBroadcastContainer:e,runtimeHost:null==h?void 0:h.runtimeHost,scanCodePresenter:et.scanCodePresenter,showSandboxCashier:ee.showCashier,uiPresenter:et.presenter,showSimulatorPermission:er.showPermission,vibrationContainer:S.current}),[h,e$,eB,m,ee.showCashier,et.scanCodePresenter,et.presenter,er.showPermission,y.manifest.iconSrc,v]),ts=(0,rc.useMemo)(()=>ti(),[ti]),to=oQ(e=>{x.current!==e&&(x.current=e,C(e=>e+1)),T(null)});(0,rc.useEffect)(()=>{let e=b.current;if(!e)return;let t=ti(e),r=new oK({container:e,fileSystemNamespace:null==s?void 0:s.fileSystemNamespace,nativeModulesCallHandler:ta,webSdkDebugger:v,onError:e=>{null==p||p(`Widget runtime error ${eT}: ${e.message}`,!0)},apiEnvironment:t});ep.current=r;let n=r.subscribeTarget(to);return to(r.getCurrentTarget()),()=>{n(),r.destroy(),ep.current=null,to(null)}},[t,ti,null==s?void 0:s.fileSystemNamespace,ta,p,eT,to,v]);let tl=oQ(async function(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=ep.current,n=t.widgetId??(null==(e=y.widgetSelection)?void 0:e.item.widgetId);if(!r||!n)return!1;let a=t.initData??e_.current.get(n);void 0!==t.initData&&e_.current.set(n,t.initData),eD();try{return await r.render({widgetId:n,initData:a,viewport:{...nO,density:eI.density,label:eI.label,width:Math.max(1,eI.width-38)}}),eN.current=eE,M(!0),null==p||p(`Rendered widget ${n}`),!0}catch(t){M(!1),null==p||p(t.message,!0);let e=ef.current;return(null==e?void 0:e.command.widgetId)===n&&ev(e.command.commandId,{ok:!1,error:{code:"RENDER_FAILED",message:t.message}}),!1}});(0,rc.useEffect)(()=>{let e=ef.current;e&&"card"===t&&ep.current&&ey.current!==e.command.commandId&&(ey.current=e.command.commandId,tl({widgetId:e.command.widgetId,initData:e.command.structuredContent}))},[t,eg,tl]),(0,rc.useEffect)(()=>{var e,t;let r=eR.current;if((eR.current=eT,r!==eT)&&(null==(e=ef.current)?void 0:e.command.widgetId)!==eT){if(y.widgetSelection)return void tl();eD(),M(!1),null==(t=ep.current)||t.clear()}},[eD,tl,eT,y.widgetSelection]),(0,rc.useEffect)(()=>{!ef.current&&R&&eN.current!==eE&&tl()},[R,tl,eE]);let td=oQ(async()=>{if(!eP)return!1;L(!0);try{if(await v.reloadResources(),P(e=>e+1),R&&!await tl())return!1;return null==p||p("已刷新卡片资源"),!0}catch(e){return null==p||p(e.message,!0),!1}finally{L(!1)}});return{activeView:t,appendAgentTraceEvent:eL,canReloadResources:eP,cardReloadKey:A,chromeDevToolsFrontendUrl:n,controlCommand:a,conversationAPIEnvironment:ts,conversationConsoleTarget:I.current,conversationControlTarget:H,conversationWidgetViewport:ej,currentDebugAppId:e$,currentDebugAppName:eB,debugState:tn,devtoolsTarget:e3,devToolsPanelId:X===e1&&e1>0?"wsd-sandbox":J>0?"wsd-trace":void 0,getRuntimeFrame:k,handleDebugAction:eK,handleGrantingSheetTargetChange:e4,handleInspectableCardTargetChange:e6,handleQuerySubmit:eQ,handleSandboxLoginHintClick:eY,handleSandboxLoginHintClose:e0,handleSandboxLocationConfigOpen:eZ,handleTraceMessageSelect:eX,hasRenderedPreview:R,highlightRect:N,latestDevToolsPanelRequestId:e1,nativeModulesCallHandler:ta,onActiveViewChange:d,onChromeDevToolsPanelChange:l,onControlResult:c,onMessage:p,onNavigateToPage:m,reloadResources:td,renderSelectedWidget:tl,resolveConversationInspectTarget:e7,runtimeFrameRef:w,runtimeFrameScaleBoxRef:S,runtimeScaleMode:eS,runtimeStyle:ex,runtimeSnapshotTarget:"conversation"===t?(null==H?void 0:H.targetInfo)??eF:eF,runtimeTargetRef:b,sandboxCashier:ee,simulatorUI:et,simulatorPermissionPrompt:er,simulatorSkillsIndexUrl:null==s?void 0:s.simulatorSkillsIndexUrl,selectedDeviceKey:eE,selectedTraceId:V,selectedWidgetId:eT,setHighlightRect:T,setRuntimeConsoleSnapshot:q,setRuntimeDomSnapshot:B,setSelectedDeviceKey:ek,setRuntimeShellRef:eC,sandboxLoginAvailable:en,showSandboxLoginHint:ei,simulatorState:eM,state:y,visibleWidgets:_,webSdkDebugger:v}}function dV(e){let t=dz(e,"conversation");return(0,i.jsx)(l3,{runtime:t,children:(0,i.jsx)(o6,{highlightRect:t.highlightRect,overlay:(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("section",{"aria-label":"对话",className:"wsd-widget-phone-scroll is-conversation",children:(0,i.jsx)(lz,{apiEnvironment:t.conversationAPIEnvironment,appId:t.currentDebugAppId,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,i.jsx)(o7,{cashier:t.sandboxCashier.cashier,onCancel:t.sandboxCashier.cancelCashier,onConfirm:t.sandboxCashier.confirmCashier}):null,t.simulatorPermissionPrompt.permission?(0,i.jsx)(lG,{onAllow:t.simulatorPermissionPrompt.allowPermission,onReject:t.simulatorPermissionPrompt.rejectPermission,permission:t.simulatorPermissionPrompt.permission}):null]}),runtimeFrameRef:t.runtimeFrameRef,runtimeFrameScaleBoxRef:t.runtimeFrameScaleBoxRef,runtimeScaleMode:t.runtimeScaleMode,runtimeShellRef:t.setRuntimeShellRef,runtimeStyle:t.runtimeStyle})})}var dG=r(18017),dJ=r(29912),dK=r(80405);async function dX(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 dQ(e){let{actionDisabled:t,actionLabel:r,JsonEditorComponent:n,label:a,minHeight:s=96,onAction:o,onChange:l,onMessage:d,value:u}=e;return(0,i.jsxs)("form",{className:"wsd-debug-inputs",onSubmit:function(e){e.preventDefault(),null==o||o()},children:[(0,i.jsxs)("div",{className:"wsd-debug-editor-block",children:[(0,i.jsxs)("div",{className:"wsd-editor-toolbar",children:[(0,i.jsx)("span",{className:"wsd-section-label",children:a}),(0,i.jsxs)("div",{className:"wsd-editor-actions",children:[(0,i.jsx)("button",{className:"wsd-button wsd-button-ghost",onClick:function(){try{l(JSON.stringify(nB("JSON",u),null,2)),null==d||d(`${a} formatted`)}catch(e){null==d||d(e.message,!0)}},type:"button",children:"格式化"}),(0,i.jsx)("button",{className:"wsd-button wsd-button-ghost",onClick:()=>{dX(a,u,d)},type:"button",children:"复制"})]})]}),n?(0,i.jsx)(n,{ariaLabel:a,minHeight:s,onChange:l,value:u}):(0,i.jsx)("textarea",{"aria-label":a,className:"wsd-json-textarea",onChange:e=>l(e.currentTarget.value),spellCheck:!1,style:{minHeight:s},value:u})]}),r?(0,i.jsx)("div",{className:"wsd-debug-action-bar",children:(0,i.jsx)("button",{className:"wsd-button wsd-button-primary",disabled:t,type:"submit",children:r})}):null]})}function dY(){return{inputError:"",inputMode:"form",inputParams:{},inputText:"{}"}}function dZ(e){return Array.isArray(e)?e.map(dZ):e8(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,dZ(r)]})):e}function d0(e){let{id:t,name:r,onChange:n,onError:a,type:s,value:o}=e,[l,d]=(0,rc.useState)(JSON.stringify(o??("array"===s?[]:{}),null,2));function u(e){try{let t=JSON.parse(e);if(!("array"===s?Array.isArray(t):e8(t)))throw Error(`expected a JSON ${s}`);n(t)}catch(e){a(`${r}: ${e.message}`)}}return(0,i.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 d1(e){let{onChange:t,schema:r,value:n}=e,a=(0,rc.useId)(),s=(0,rc.useRef)(new Map),o=e8(r.properties)?r.properties:{},l=new Set(Array.isArray(r.required)?r.required.filter(e=>"string"==typeof e):[]);function d(){return s.current.values().next().value??""}function u(e,r){let a=arguments.length>2&&void 0!==arguments[2]&&arguments[2];a&&s.current.delete(e);let i={...n};void 0===r?delete i[e]:i[e]=r,t(i,d())}return 0===Object.keys(o).length?(0,i.jsx)("div",{className:"wsd-schema-empty-input",children:"无需输入参数"}):(0,i.jsx)("div",{className:"wsd-schema-input-form",children:Object.entries(o).map(e=>{let[r,o]=e,c=e8(o)?o:{},p=c.type||"string",m="string"==typeof c.description?c.description:"",h=Array.isArray(c.enum)?c.enum:void 0,g=n[r],f=`${a}-${r}`;return(0,i.jsxs)("label",{className:"wsd-schema-form-field",htmlFor:f,children:[(0,i.jsxs)("span",{className:"wsd-schema-form-field-title",children:[(0,i.jsx)("strong",{children:r}),l.has(r)?(0,i.jsx)("em",{children:"必填"}):null,(0,i.jsx)("small",{children:`${p}${h?" · enum":""}`})]}),m?(0,i.jsx)("span",{className:"wsd-schema-form-field-description",children:m}):null,h?(0,i.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,i.jsx)("option",{value:"",children:"请选择"}),h.map(e=>(0,i.jsx)("option",{value:JSON.stringify(e),children:String(e)},JSON.stringify(e)))]}):"boolean"===p?(0,i.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,i.jsx)("option",{value:"",children:"请选择"}),(0,i.jsx)("option",{value:"true",children:"true"}),(0,i.jsx)("option",{value:"false",children:"false"})]}):"null"===p?(0,i.jsxs)("select",{"aria-label":`参数 ${r}`,id:f,onChange:e=>u(r,"null"===e.currentTarget.value?null:void 0),value:null===g?"null":"",children:[(0,i.jsx)("option",{value:"",children:"请选择"}),(0,i.jsx)("option",{value:"null",children:"null"})]}):"array"===p||"object"===p?(0,i.jsx)(d0,{id:f,name:r,onChange:e=>u(r,e,!0),onError:e=>{s.current.set(r,e),t(n,d())},type:p,value:g}):(0,i.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 d2(e){let{heading:t,jsonLabel:r,minHeight:n=160,onChange:a,onMessage:s,schema:o,value:l}=e;return(0,i.jsxs)("div",{className:"wsd-schema-input-editor",children:[(0,i.jsxs)("div",{className:"wsd-schema-input-heading",children:[(0,i.jsx)("span",{children:t}),(0,i.jsx)("button",{className:"wsd-button wsd-button-ghost",onClick:function(){if("form"===l.inputMode)return void a({inputMode:"text"});try{let e=nB(r,l.inputText);a({inputError:"",inputMode:"form",inputParams:e,inputText:JSON.stringify(e,null,2)})}catch(e){a({inputError:e.message})}},type:"button",children:"form"===l.inputMode?"文本模式":"表单模式"})]}),"form"===l.inputMode?(0,i.jsx)(d1,{onChange:function(e,t){a({inputError:t,inputParams:e,inputText:JSON.stringify(e,null,2)})},schema:o,value:l.inputParams}):(0,i.jsx)(dQ,{label:r,minHeight:n,onChange:e=>a({inputError:"",inputText:e}),onMessage:s,value:l.inputText}),l.inputError?(0,i.jsx)("span",{className:"wsd-schema-input-error",children:l.inputError}):null]})}function d3(e){var t;let{events:r,onMessage:n,onTrigger:a}=e,s=(0,rc.useRef)(null),[o,l]=(0,rc.useState)(!1),[d,u]=(0,rc.useState)((null==(t=r[0])?void 0:t.name)??""),[c,p]=(0,rc.useState)(dY),[m,h]=(0,rc.useState)(""),g=r.find(e=>e.name===d)??r[0],f=oQ(()=>l(!1));(0,rc.useEffect)(()=>{if(!g){u(""),p(dY()),l(!1);return}g.name!==d&&(u(g.name),p(dY()))},[g,d]),(0,rc.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=s.current)?void 0:t.contains(e.target))||f()}function t(e){"Escape"===e.key&&f()}},[f,o]);let v=oQ(()=>{let e;if(g&&!c.inputError){try{e=nB("事件参数",c.inputText)}catch(e){p(t=>({...t,inputError:e.message}));return}try{a(g.name,e),p(t=>({...t,inputError:"",inputParams:e})),h(`已触发 ${g.name}`),null==n||n(`Agent event ${g.name} triggered`),f()}catch(t){let e=t.message;h(e),null==n||n(e,!0)}}});return(0,i.jsxs)("div",{className:"wsd-agent-event-debug",ref:s,children:[(0,i.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,i.jsx)("span",{"aria-hidden":"true",children:"+"}),"事件"]}),o&&g?(0,i.jsxs)("dialog",{"aria-label":"Agent 事件调试",className:"wsd-agent-event-popup",open:!0,children:[(0,i.jsxs)("header",{className:"wsd-agent-event-header",children:[(0,i.jsxs)("div",{children:[(0,i.jsx)("strong",{children:"触发事件"}),(0,i.jsx)("span",{children:"发送到当前小程序的 App runtime"})]}),(0,i.jsx)("button",{"aria-label":"关闭事件调试",onClick:f,type:"button",children:"×"})]}),(0,i.jsxs)("label",{className:"wsd-agent-event-select-control",children:[(0,i.jsx)("span",{children:"事件"}),(0,i.jsx)("select",{"aria-label":"调试事件",onChange:e=>{u(e.currentTarget.value),p(dY()),h("")},value:g.name,children:r.map(e=>(0,i.jsx)("option",{value:e.name,children:e.name},e.name))})]}),g.description?(0,i.jsx)("p",{className:"wsd-agent-event-description",children:g.description}):null,(0,i.jsx)(d2,{heading:"事件参数 · PAYLOADSCHEMA",jsonLabel:"事件参数",minHeight:132,onChange:e=>p(t=>({...t,...e})),onMessage:n,schema:g.payloadSchema,value:c},g.name),(0,i.jsxs)("footer",{className:"wsd-agent-event-footer",children:[m?(0,i.jsx)("span",{"aria-live":"polite",children:m}):(0,i.jsx)("span",{}),(0,i.jsx)("button",{className:"wsd-button wsd-button-primary wsd-agent-event-trigger",onClick:v,type:"button",children:"触发"})]})]}):null]})}async function d4(e,t,r){let n=await r(e,{cache:"no-store",headers:{Accept:"application/json"}});if(!n.ok)throw Error(`加载 ${t}失败:HTTP ${n.status} ${n.statusText}`);return n.json()}async function d5(){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 d4(e,"Scene ",t);if(!e8(r)||!Array.isArray(r.scenes)||!Array.isArray(r.errors))throw Error("Scene 发现接口返回了无效数据");let n=r.scenes.flatMap(e=>e8(e)&&"string"==typeof e.name&&e8(e.content)?[{content:e.content,name:e.name}]:[]);return{errors:r.errors.flatMap(e=>e8(e)&&"string"==typeof e.name&&"string"==typeof e.message?[{name:e.name,message:e.message}]:[]),scenes:n}}let d8={appEntries:[],entries:[],updatedAtMs:0},d6="scene:";function d7(e){let{showTooltip:t=!1,value:r}=e,n=r.indexOf("?"),a=n<0?r:r.slice(0,n),s=n<0?"":r.slice(n),o=(0,i.jsxs)("span",{className:"wsd-page-route-label",children:[(0,i.jsx)("span",{className:"wsd-page-route-path",children:a}),s?(0,i.jsx)("span",{className:"wsd-page-route-query",children:s}):null]});return t?(0,i.jsx)(dG.I,{closeDelay:0,content:r,delay:300,placement:"right",children:o}):o}function d9(){return(0,i.jsx)("svg",{"aria-hidden":"true",className:"wsd-page-route-arrow is-back",viewBox:"0 0 16 16",children:(0,i.jsx)("path",{d:"M3 8h10M9 4l4 4-4 4",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5"})})}function ue(e){var t,r,n,a,s,o;let{activeView:l,chromeDevToolsFrontendUrl:d,controlCommand:u,controlClientId:c,debugContext:p,onChromeDevToolsPanelChange:m,onActiveViewChange:h,onControlResult:g,onMessage:f,apiEnvironment:v,showDebugTrace:y,connection:_,webSdkDebugger:b}=e,w=o4(b),S=(0,rc.useMemo)(()=>w.pages.filter(ry),[w.pages]),[x,I]=(0,rc.useState)({errors:[],scenes:[]}),[E,C]=(0,rc.useState)([]),[k,N]=(0,rc.useState)(""),[T,R]=(0,rc.useState)(null),[M,A]=(0,rc.useState)(null),[P,j]=(0,rc.useState)(null),[L,D]=(0,rc.useState)(null),[O,U]=(0,rc.useState)(null),[q,$]=(0,rc.useState)(0),[B,F]=(0,rc.useState)(""),[W,H]=(0,rc.useState)(null),[z,V]=(0,rc.useState)(d8),G=o9(),J=di(),K=(null==p?void 0:p.sandboxSessionAvailable)!==!1,X=dN(dl(p)),Q=dB(),Y=dD(K),{bridgeLogs:Z,clearBridgeLogs:ee}=lb(),[et,er]=(0,rc.useState)(null),en=lJ(),ea=(0,rc.useRef)(null),{accept:ei,pending:es,pendingRef:eo,report:el}=dU(g),{runtimeScaleMode:ed,runtimeStyle:eu,selectedDevice:ec,selectedDeviceKey:ep,setRuntimeShellRef:em,setSelectedDeviceKey:eh}=d$(u,g),eg=(null==(t=w.pageSelection)?void 0:t.item.id)??"",ef=(null==(r=w.pageSelection)?void 0:r.item.path)??"",ev=oQ(e=>{null==f||f(e,!0)});(0,rc.useEffect)(()=>{let e=null==p?void 0:p.eventsConfigUrl;if(!e)return void C([]);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=>C(e8(e)&&Array.isArray(e.events)?e.events.flatMap(e=>{if(!e8(e))return[];let t="string"==typeof e.name?e.name.trim():"",r=dZ(e.payloadSchema);return t&&e8(r)?[{description:"string"==typeof e.description?e.description:"",name:t,payloadSchema:r}]:[]}):[])).catch(e=>{t.signal.aborted||(C([]),ev(e.message))}),()=>t.abort()},[null==p?void 0:p.eventsConfigUrl,ev]);let ey=(0,rc.useMemo)(()=>x.scenes.flatMap(e=>{let t=e2(e.content);if("page"!==t.type||t.unresolvedVariables.length>0)return[];try{return ti({url:t.url},w.manifest),[{key:`${d6}${e.name}`,label:t.url,type:"scene",url:t.url}]}catch{return[]}}),[x.scenes,w.manifest]),e_=(0,rc.useMemo)(()=>[...S.map(e=>({key:e.path,url:e.path})),...ey],[ey,S]),eb=B||(null==(n=w.pageSelection)?void 0:n.routeUrl)||ef,ew=eb.split("?")[0],eS=(null==(a=ey.find(e=>e.key===k&&e.url===eb))?void 0:a.key)??"",ex=(null==(s=e_.find(e=>!e.key.startsWith(d6)&&e.url===ew))?void 0:s.key)??"",eI=(0,rc.useMemo)(()=>({...p,manifestUrl:w.manifestUrl,simulatorEndpoint:w.simulator.endpoint}),[p,w.manifestUrl,w.simulator.endpoint]),eE=(0,rc.useMemo)(()=>df({context:eI,events:w.simulator.traceEvents,manifest:w.manifest,pages:w.pages,widgets:w.widgets}),[eI,w.manifest,w.pages,w.simulator.traceEvents,w.widgets]),eC=eE.appId,ek=eE.appName,eN=(0,rc.useMemo)(()=>({type:"page",appId:eC,appName:ek,pageId:eg,pagePath:ef,url:eb,viewport:{key:ec.key,label:ec.label,width:ec.width,height:ec.height,density:ec.density}}),[eC,ek,ec,eg,ef,eb]),eT=(0,rc.useMemo)(()=>dy(eE,w.pageSelection?eN:void 0),[eN,eE.pages,eE.widgets,w.pageSelection]),eR=!!(es&&dv(et,L,es.previousTarget)&&(null==(o=w.pageSelection)?void 0:o.routeUrl)===es.command.url),eM=(0,rc.useMemo)(()=>(null==et?void 0:et.sourceTarget)===L?{target:eN,root:et.root,nodeCount:et.nodeCount,selectedUid:et.selectedUid,truncated:et.truncated,updatedAtMs:et.updatedAtMs}:void 0,[eN,L,et]),eA=(0,rc.useMemo)(()=>({exported_at:new Date().toISOString(),client_id:c,command_id:eR?null==es?void 0:es.command.commandId:void 0,context:{...ds({appId:eC,appName:eE.appName,debugContext:eI,manifestUrl:w.manifestUrl,simulatorEndpoint:w.simulator.endpoint,sources:eE.sources}),page_id:eg,page_path:ef},render_targets:eT,runtime_snapshot:eM,page_runtime_trace_events:[],runtime_console:{app:{entries:z.appEntries,updated_at_ms:z.updatedAtMs},page:{entries:z.entries,updated_at_ms:z.updatedAtMs}},simulator:{stream_status:w.simulator.streamStatus,messages:w.simulator.messages,trace_events:w.simulator.traceEvents,tool_calls:w.simulator.toolCalls}}),[eE.appId,eE.appName,eE.sources.manifest.original,eE.sources.manifest.proxy,eE.sources.mcp.original,eE.sources.mcp.proxy,eE.sources.skill.original,eE.sources.skill.proxy,eI.launchDir,eI.mcpEndpoint,eI.simulatorManifestUrl,eI.simulatorSkillsIndexUrl,eI.webUrl,z,eg,ef,eC,c,eR,null==es?void 0:es.command.commandId,eT,w.manifest.name,w.manifestUrl,w.simulator.endpoint,w.simulator.messages,w.simulator.streamStatus,w.simulator.toolCalls,w.simulator.traceEvents,eM]),eP=(0,rc.useMemo)(()=>y?w.simulator.traceEvents:w.simulator.traceEvents.filter(e=>{var t;return!(null==(t=e.display)?void 0:t.debugOnly)}),[y,w.simulator.traceEvents]),ej=(0,rc.useMemo)(()=>t7(eP,{debug:y,messages:w.simulator.messages}),[y,w.simulator.messages,eP]),eL=(0,rc.useMemo)(()=>t6(eA,{debug:y}),[y,eA]),eD=(0,rc.useMemo)(()=>t4(eL),[eL]);(0,rc.useEffect)(()=>{let e=!0;return d5(null==p?void 0:p.debugScenesEndpoint).then(t=>{if(e)for(let e of(I(t),t.errors))null==f||f(`${e.name}: ${e.message}`,!0)}).catch(t=>{e&&(I({errors:[],scenes:[]}),null==f||f(t.message,!0))}),()=>{e=!1}},[null==p?void 0:p.debugScenesEndpoint,f]);let eO=oQ(e=>{var t,r;let n=(null==(t=ea.current)?void 0:t.getCurrentTarget())??(null==(r=ea.current)?void 0:r.getCurrentAppTarget()),a=`[Debug Scene] ${e}`;n?sl(n,{level:"error",message:a,pagePath:ef}):console.error(a)}),eU=oQ(e=>{ey.some(e=>{var t;return e.key===k&&e.url===(null==(t=w.pageSelection)?void 0:t.routeUrl)})?eO(e):null==f||f(e,!0)}),eq=async()=>{var e;await b.reloadResources(),null==(e=ea.current)||e.reload()},e$=oQ(e=>{let t=e_.find(t=>t.key===e);t&&(t.key.startsWith(d6)?N(t.key):N(""),b.navigateToPage(t.url))}),eB=oQ(e=>{dO(e,{onClearLogs:ee,onMessage:f})}),eF=(0,rc.useMemo)(()=>({debugData:eE,events:ej,logSnapshot:eL,logSnapshotText:eD,sandbox:{available:K,csrRequired:(null==p?void 0:p.sandboxCsrRequired)!==!1,input:{csrPem:(null==p?void 0:p.sandboxCsrPem)??"",phoneNum:(null==p?void 0:p.sandboxPhoneNum)??""},logs:Z,businessInfoStatus:X,location:Q,sessionStatus:Y},showDebugTrace:y,traceSurface:"page",toolCalls:w.simulator.toolCalls,updatedAtMs:Date.now()}),[eE,ej,eL,eD,Z,X,Q,K,Y,null==p?void 0:p.sandboxCsrRequired,y,w.simulator.toolCalls]);dF(_,eA,et),(0,rc.useEffect)(()=>{if((null==u?void 0:u.type)==="render_page"&&ei(u,L))try{N(""),b.navigateToPage(u.url)}catch(e){el(u.commandId,{ok:!1,error:{code:"TARGET_NOT_FOUND",message:e.message}})}},[ei,u,L,el,b]),(0,rc.useEffect)(()=>{es&&eR&&el(es.command.commandId,{ok:!0,target:eN,snapshot:t8(eA)})},[eN,eR,es,el,eA]);let eW=oQ((e,t)=>{let r=rV(b,{noLogin:null==t?void 0:t.noLogin});if("not_found"===r.status){null==f||f("未找到需要重发的原始消息",!0);return}if("streaming"===r.status){null==f||f("当前仍在生成中,暂不重发授权后的消息",!0);return}b.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==f||f(e.message,!0)})}),eH=oQ((e,t)=>{eW(e,t),"login"===e&&(null==h||h("conversation"))}),ez=(0,rc.useMemo)(()=>{let e=se({appId:eC,appIcon:w.manifest.iconSrc,appName:ek,baseAPIRegistry:null==v?void 0:v.apiRegistry,onGrantingCompleted:eH,sendFollowUpMessage:e=>{let{content:t}=e;return b.sendSimulatorFollowUpMessage(t)},multiMediaBroadcastContainer:T,runtimeHost:null==v?void 0:v.runtimeHost,scanCodePresenter:J.scanCodePresenter,showSandboxCashier:G.showCashier,uiPresenter:J.presenter,showSimulatorPermission:en.showPermission,vibrationContainer:P});return e.apiRegistry.registerMany(lE({appKey:eC,scene:"page"}),{override:!0}),e},[v,eH,eC,ek,P,T,G.showCashier,J.scanCodePresenter,J.presenter,en.showPermission,w.manifest.iconSrc,b]);(0,rc.useEffect)(()=>{if(!T)return;let e=new oJ({container:T,fileSystemNamespace:null==p?void 0:p.fileSystemNamespace,webSdkDebugger:b,onExitApp:()=>null==h?void 0:h("conversation"),onError:e=>{null==f||f(`Page runtime error: ${e.message}`,!0)},apiEnvironment:ez});ea.current=e;let t=e.subscribeTarget(t=>{D(t),$(e.getPageStackSize()),F(e.getCurrentPageUrl()??""),H(null)}),r=e.subscribeAppTarget(e=>{U(e)});return D(e.getCurrentTarget()),U(e.getCurrentAppTarget()),$(e.getPageStackSize()),F(e.getCurrentPageUrl()??""),()=>{t(),r(),e.destroy(),ea.current=null,D(null),U(null),$(0),F(""),H(null)}},[null==p?void 0:p.fileSystemNamespace,h,f,ez,T,b]);let eV=oQ((e,t)=>{let r=ea.current;if(!r)throw Error("Page runtime is not ready");r.sendAgentEvent(e,t)});(0,rc.useEffect)(()=>{let e=ea.current;if(!e||!w.pageSelection){null==e||e.clear();return}try{e.render({device:ec})}catch(t){eU(t.message);let e=eo.current;e&&el(e.command.commandId,{ok:!1,error:{code:"RENDER_FAILED",message:t.message}})}},[eU,el,T,ec,eg,w.pageSelection]);let eG=(0,rc.useMemo)(()=>({appTarget:O,controlCommand:u,controlTarget:w.pageSelection?L:null,debugState:eF,frontendUrl:d,onConsoleSnapshotChange:V,onControlResult:g,onDebugAction:eB,onHighlightChange:H,onRuntimeSnapshotChange:er,preserveConsoleOnTargetChange:!0,runtimeSnapshotTarget:eN,runtimeFrame:M,target:w.pageSelection?L:null}),[O,d,u,eN,eF,eB,g,L,M,w.pageSelection]);return(0,rc.useEffect)(()=>{"page"===l&&(null==m||m(eG))},[l,eG,m]),(0,i.jsxs)("div",{className:"wsd-page-preview-column",hidden:"page"!==l,children:[(0,i.jsx)(l2,{activeView:l??"page",onActiveViewChange:h,onDeviceChange:eh,selectedDeviceKey:ep,children:(0,i.jsx)("button",{"aria-label":"Reload",className:"wsd-icon-button",disabled:!w.pageSelection,onClick:()=>void eq(),title:"Reload",type:"button",children:(0,i.jsx)(lK,{"aria-hidden":"true"})})}),(0,i.jsxs)("div",{className:"wsd-page-route-control",children:[(0,i.jsx)("div",{className:"wsd-page-route-navigation",children:(0,i.jsx)("button",{"aria-label":"返回",className:"wsd-page-route-button",disabled:q<2,onClick:()=>{var e;return null==(e=ea.current)?void 0:e.closeCurrentPage()},title:"返回",type:"button",children:(0,i.jsx)(d9,{})})}),(0,i.jsx)("div",{className:"wsd-page-route-select-wrapper",children:(0,i.jsx)(dJ.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===S.length&&0===ey.length,listboxProps:{itemClasses:{base:"wsd-page-path-option",selectedIcon:"wsd-page-path-selected-icon"}},onChange:e=>e$(e.target.value),placeholder:eb||"No page",popoverProps:{offset:0},renderValue:()=>(0,i.jsx)(d7,{value:eb||ef}),selectedKeys:eS?[eS]:ex?[ex]:[],size:"sm",children:e_.map(e=>(0,i.jsx)(dK.y,{textValue:e.url,children:(0,i.jsx)(d7,{showTooltip:!0,value:e.url})},e.key))})}),w.pageSelection&&E.length>0?(0,i.jsx)(d3,{events:E,onMessage:f,onTrigger:eV}):null]}),w.pageSelection?(0,i.jsx)(o6,{highlightRect:W,overlay:(0,i.jsxs)(i.Fragment,{children:[J.overlay,G.cashier?(0,i.jsx)(o7,{cashier:G.cashier,onCancel:G.cancelCashier,onConfirm:G.confirmCashier}):null,en.permission?(0,i.jsx)(lG,{onAllow:en.allowPermission,onReject:en.rejectPermission,permission:en.permission}):null]}),runtimeFrameRef:A,runtimeFrameScaleBoxRef:j,runtimeScaleMode:ed,runtimeShellRef:em,runtimeStyle:eu,runtimeTargetRef:R}):(0,i.jsx)("div",{className:"wsd-page-empty",children:"No page"})]})}let ut=0;function ur(){return{...dY(),callError:"",isRunning:!1,selectedOutputIndex:0,selectedToolName:""}}function un(e){var t;let r=null==e||null==(t=e.debug)?void 0:t.mcp_output,n=!1,a=(r?[r]:[]).flatMap(e=>{var t;if(Array.isArray(e.structuredContent)){n=!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];n=!0;let r=e.structuredContent.entities;return r.length>0?r.map(t=>({...e,structuredContent:t})):[e]});return{collectionType:n?"entity":void 0,outputs:a}}function ua(e){return((null==e?void 0:e.content)??[]).map(e=>"text"===e.type&&e.text||"").filter(Boolean).join("\n")}function ui(e){var t;let{onSessionChange:r,onUseWidgetOutput:n,session:a,...s}=e,o=dz(s,"card"),l=null==(t=s.debugContext)?void 0:t.toolsConfigUrl,d=oQ(e=>{var t;null==(t=s.onMessage)||t.call(s,e,!0)}),[u,c]=(0,rc.useState)({}),p=(0,rc.useMemo)(()=>{var e;return e=o.state.manifest.raw,Object.entries(e.tools??{}).map(t=>{let[r,n]=t;return{description:n.description||"",inputSchema:u[r]??dZ(n.input_schema??{}),name:r,widgetId:function(e,t){for(let n of Object.values(e.entities??{})){var r;let e=null==(r=n.tool_card_binding)?void 0:r[t];if(e)return e}}(e,r)}})},[o.state.manifest,u]),{callError:m,copiedResultSection:h,inputError:g,inputText:f,isRunning:v,result:y,selectedOutputIndex:_,selectedToolName:b}=a,w=p.find(e=>e.name===b)??p[0],S=null==w?void 0:w.widgetId,x=un(y),I=x.outputs,E=I[_]??I[0],C=Array.isArray(null==E?void 0:E.structuredContent)||null==E?void 0:E.structuredContent,k=null==E?void 0:E._meta,N=ua(E);async function T(){let e;if(!w||g)return;try{e=nB("调用参数",f)}catch(e){r(t=>({...t,inputError:e.message}));return}let t=ut+=1;r(r=>({...r,activeInvocationId:t,callError:"",copiedResultSection:void 0,inputError:"",inputParams:e,isRunning:!0,result:void 0,selectedOutputIndex:0}));try{let n=await o.webSdkDebugger.callSimulatorTool({params:e,toolName:w.name});r(e=>{let r;return e.activeInvocationId===t?{...e,result:n,selectedOutputIndex:(r=un(n).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 R(e,t){await dX("meta"===e?"META JSON":"STRUCTUREDCONTENT JSON",JSON.stringify(t,null,2),o.onMessage)&&r(t=>({...t,copiedResultSection:e}))}return(0,rc.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(e8(e)&&Array.isArray(e.tools)?Object.fromEntries(e.tools.flatMap(e=>e8(e)&&"string"==typeof e.name&&e8(e.inputSchema)?[[e.name,e.inputSchema]]:[])):{})}).catch(t=>{e.signal.aborted||d(t.message)}),()=>e.abort()},[d,l]),(0,rc.useEffect)(()=>{w&&w.name!==b&&r(e=>({...e,selectedToolName:w.name}))},[r,w,b]),(0,i.jsx)(l3,{runtime:o,showReloadButton:!1,toolbarView:"tool",children:(0,i.jsx)("div",{className:"wsd-tool-debug",children:w?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("section",{className:"wsd-tool-debug-card",children:[(0,i.jsxs)("label",{className:"wsd-tool-select-control",children:[(0,i.jsx)("span",{children:"工具"}),(0,i.jsx)("select",{"aria-label":"调试工具",onChange:e=>{var t;return t=e.currentTarget.value,void r({...ur(),selectedToolName:t})},value:w.name,children:p.map(e=>(0,i.jsx)("option",{value:e.name,children:e.name},e.name))})]}),(0,i.jsx)("h2",{children:w.name}),w.description?(0,i.jsx)("p",{children:w.description}):null,(0,i.jsx)(d2,{heading:"输入参数 · INPUTSCHEMA",jsonLabel:"调用参数",onChange:e=>r(t=>({...t,...e})),onMessage:o.onMessage,schema:w.inputSchema,value:a},w.name),(0,i.jsx)("button",{className:"wsd-button wsd-button-primary wsd-tool-run-button",disabled:v,onClick:()=>void T(),type:"button",children:v?"运行中…":"▶ 运行"})]}),y||m?(0,i.jsxs)("section",{className:"wsd-tool-debug-result","aria-live":"polite",children:[(0,i.jsxs)("div",{className:"wsd-tool-result-title",children:[(0,i.jsx)("span",{children:"输出结果"}),(0,i.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,i.jsxs)("label",{className:"wsd-tool-select-control wsd-tool-output-select-control",children:[(0,i.jsx)("span",{children:"entity"===x.collectionType?"Entity 元素":"数组元素"}),(0,i.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:_,children:I.map((e,t)=>{let r,n,a;return(0,i.jsx)("option",{value:t,children:(n=[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()),a=ua(e).split("\n")[0],`${t+1}. ${n||a||"空结果"}`)},t)})})]}):null,m||(null==y?void 0:y.error)?(0,i.jsxs)("div",{className:"wsd-tool-result-block",children:[(0,i.jsx)("span",{children:"ERROR"}),(0,i.jsx)("pre",{children:m||JSON.stringify(null==y?void 0:y.error,null,2)})]}):null,N?(0,i.jsxs)("div",{className:"wsd-tool-result-block",children:[(0,i.jsx)("span",{children:"CONTENT"}),(0,i.jsx)("p",{children:N})]}):null,C?(0,i.jsxs)("div",{className:"wsd-tool-result-block",children:[(0,i.jsxs)("div",{className:"wsd-tool-result-block-heading",children:[(0,i.jsx)("span",{children:"STRUCTUREDCONTENT"}),(0,i.jsx)("button",{"aria-label":"复制 STRUCTUREDCONTENT JSON",className:"wsd-button wsd-button-ghost",onClick:()=>void R("structuredContent",C),type:"button",children:"structuredContent"===h?"已复制":"复制 JSON"})]}),(0,i.jsx)("pre",{children:JSON.stringify(C,null,2)})]}):null,k?(0,i.jsxs)("div",{className:"wsd-tool-result-block",children:[(0,i.jsxs)("div",{className:"wsd-tool-result-block-heading",children:[(0,i.jsx)("span",{children:"META"}),(0,i.jsx)("button",{"aria-label":"复制 META JSON",className:"wsd-button wsd-button-ghost",onClick:()=>void R("meta",k),type:"button",children:"meta"===h?"已复制":"复制 JSON"})]}),(0,i.jsx)("pre",{children:JSON.stringify(k,null,2)})]}):null,(null==y?void 0:y.status)==="succeeded"&&S&&C?(0,i.jsxs)("button",{className:"wsd-button wsd-button-primary wsd-tool-use-widget-output",onClick:()=>n({viewData:C,widgetId:S}),type:"button",children:["填入 ",S," 卡片预览"]}):null]}):null]}):(0,i.jsx)("div",{className:"wsd-page-empty",children:"No tool"})})})}var us=e=>(0,i.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",width:12,height:12,fill:"none",viewBox:"0 0 12 12",...e,children:(0,i.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"})}),uo=r(48986),ul=r(80704),ud=r(51290),uu=r(36091);let uc=ud.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)"}}),up=[(0,uo.Pq)(),(0,ul.pJ)(),(0,ul.bu)((0,uo.cp)()),ud.Lz.lineWrapping,uc];function um(e){let{ariaLabel:t,minHeight:r=96,onChange:n,value:a}=e,s={"--json-editor-min-height":`${r}px`};return(0,i.jsx)("div",{"aria-label":t,className:"json-editor-shell",style:s,children:(0,i.jsx)(uu.Ay,{basicSetup:{autocompletion:!0,bracketMatching:!0,closeBrackets:!0,foldGutter:!0,highlightActiveLine:!0,highlightActiveLineGutter:!0,lineNumbers:!0,searchKeymap:!0},extensions:up,minHeight:`${r}px`,onChange:n,value:a})})}function uh(e){return e8(e)?Object.fromEntries(Object.entries(e).flatMap(e=>{let[t,r]=e;return e8(r)?[[t,r]]:[]})):{}}async function ug(){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 n=await r.json();if(!e8(n)||!e8(n.templatesByEntry)&&!e8(n.templatesByWidget))throw Error("Widget viewData 模板接口返回了无效数据");return{templatesByEntry:uh(n.templatesByEntry),templatesByWidget:uh(n.templatesByWidget)}}let uf="输入数据(structuredContent)",uv={};function uy(e){var t,r,n;let{initDataDraft:a,...s}=e,o=dz(s,"card"),[l,d]=(0,rc.useState)("{}"),[u,c]=(0,rc.useState)([]),[p,m]=(0,rc.useState)({templatesByEntry:{},templatesByWidget:{}}),h=(0,rc.useRef)(!1),g=(0,rc.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]??uv,y=(0,rc.useMemo)(()=>u.flatMap(e=>{let t=e2(e.content);return"widget"===t.type&&t.id===o.selectedWidgetId?[{...t,sceneName:e.name}]:[]}),[u,o.selectedWidgetId]);(0,rc.useEffect)(()=>{var e;(null==(e=s.controlCommand)?void 0:e.type)==="render_widget"&&s.controlCommand.widgetId===o.selectedWidgetId&&(h.current=!0,d(JSON.stringify(s.controlCommand.structuredContent,null,2)))},[s.controlCommand,o.selectedWidgetId]),(0,rc.useEffect)(()=>{var e;let t=g.current!==o.selectedWidgetId;g.current=o.selectedWidgetId,((null==(e=s.controlCommand)?void 0:e.type)!=="render_widget"||s.controlCommand.widgetId!==o.selectedWidgetId)&&(t&&(h.current=!1),h.current||d(JSON.stringify(v,null,2)))},[v,s.controlCommand,o.selectedWidgetId]),(0,rc.useEffect)(()=>{var e;let t=!0;return d5(null==(e=s.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=s.debugContext)?void 0:r.debugScenesEndpoint,o.onMessage]);let _=oQ(async function(){var e,t;let r=arguments.length>0&&void 0!==arguments[0]&&arguments[0];try{let t=await ug(null==(e=s.debugContext)?void 0:e.widgetViewDataTemplatesEndpoint);r&&(h.current=!1),m(t)}catch(e){m({templatesByEntry:{},templatesByWidget:{}}),null==(t=o.onMessage)||t.call(o,e.message,!0)}});(0,rc.useEffect)(()=>{_()},[null==(n=s.debugContext)?void 0:n.widgetViewDataTemplatesEndpoint,_]);let b=oQ(e=>{h.current=!0,d(e)}),w=oQ(async()=>{let e=await o.reloadResources();return e&&await _(!0),e});function S(){try{let e=nB(uf,l);o.renderSelectedWidget({initData:{viewData:e}})}catch(t){var e;null==(e=o.onMessage)||e.call(o,t.message,!0)}}return(0,rc.useEffect)(()=>{a&&(h.current=!0,d(JSON.stringify(a,null,2)))},[a]),(0,i.jsx)(l3,{runtime:{...o,reloadResources:w},children:o.state.widgetSelection?(0,i.jsx)(o6,{highlightRect:o.highlightRect,overlay:(0,i.jsxs)("section",{"aria-label":"卡片调试",className:(0,e6.$)("wsd-widget-card-debug",{"has-rendered-preview":o.hasRenderedPreview}),children:[(0,i.jsx)(la,{}),(0,i.jsxs)("section",{className:"wsd-widget-card-form",children:[(0,i.jsxs)("label",{className:"wsd-widget-card-template-control",children:[(0,i.jsx)("span",{children:"卡片模板:"}),(0,i.jsx)("span",{className:"wsd-widget-card-template-value",children:o.selectedWidgetId}),(0,i.jsx)(us,{"aria-hidden":"true"}),(0,i.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,i.jsx)("option",{value:e.widgetId,children:e.widgetId},e.widgetId))})]}),y.length>0?(0,i.jsx)("div",{"aria-label":"Debug Scene 预设",className:"wsd-widget-scene-presets",children:y.map(e=>(0,i.jsx)("button",{className:"wsd-widget-scene-preset",onClick:()=>{h.current=!0,d(JSON.stringify(e.resolvedInput,null,2))},type:"button",children:e.sceneName},e.sceneName))}):null,(0,i.jsx)(dQ,{JsonEditorComponent:um,label:uf,minHeight:200,onAction:S,onChange:b,onMessage:o.onMessage,value:l}),(0,i.jsx)("button",{className:"wsd-button wsd-button-primary wsd-widget-card-render-button",onClick:S,type:"button",children:"渲染卡片"})]}),(0,i.jsxs)("section",{className:"wsd-widget-card-preview-section",children:[(0,i.jsx)("span",{children:"以下是卡片渲染预览"}),(0,i.jsxs)("div",{className:"wsd-widget-card-preview-canvas",children:[(0,i.jsx)("div",{className:(0,e6.$)({"wsd-widget-card-preview-target":o.hasRenderedPreview}),ref:o.runtimeTargetRef}),o.hasRenderedPreview?null:(0,i.jsx)("span",{className:"wsd-widget-card-preview-empty",children:"未传入内容"}),o.simulatorUI.overlay,o.sandboxCashier.cashier?(0,i.jsx)(o7,{cashier:o.sandboxCashier.cashier,onCancel:o.sandboxCashier.cancelCashier,onConfirm:o.sandboxCashier.confirmCashier}):null,o.simulatorPermissionPrompt.permission?(0,i.jsx)(lG,{onAllow:o.simulatorPermissionPrompt.allowPermission,onReject:o.simulatorPermissionPrompt.rejectPermission,permission:o.simulatorPermissionPrompt.permission}):null]})]})]}),runtimeFrameRef:o.runtimeFrameRef,runtimeFrameScaleBoxRef:o.runtimeFrameScaleBoxRef,runtimeScaleMode:o.runtimeScaleMode,runtimeShellRef:o.setRuntimeShellRef,runtimeStyle:o.runtimeStyle}):(0,i.jsx)("div",{className:"wsd-page-empty",children:"No widget"})})}var u_=r(85624);function ub(e,t){let r=Math.max(0,e.scrollWidth-e.clientWidth),n=Math.max(0,e.scrollHeight-e.clientHeight);return(r>0||n>0)&&(void 0===t.x||0===t.x||r>0)&&(void 0===t.y||0===t.y||n>0)}async function uw(e,t,r){let n=e.uid?t.getElement(e.uid):null,a=e.uid?n?{element:n,uid:e.uid}:null:function(e,t,r){let n=t.getInspectorSnapshot().root,a=n?[n]:[],i=null;for(let n=0;n<a.length;n+=1){let s=a[n];a.push(...s.children);let o=t.getElement(s.id);if(!o||!ub(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 n=e.getBoundingClientRect(),a=t.getBoundingClientRect();return Math.max(0,Math.min(n.right,a.right)-Math.max(n.left,a.left))*Math.max(0,Math.min(n.bottom,a.bottom)-Math.max(n.top,a.top))}(o,r);l>0&&(!i||l>i.area)&&(i={area:l,element:o,uid:s.id})}return i}(e,t,r);if(!a||!ub(a.element,e))return null;let i=Math.max(0,a.element.scrollWidth-a.element.clientWidth),s=Math.max(0,a.element.scrollHeight-a.element.clientHeight);void 0!==e.x&&(a.element.scrollLeft=Math.min(e.x,i)),void 0!==e.y&&(a.element.scrollTop=Math.min(e.y,s)),await new Promise(e=>{requestAnimationFrame(()=>requestAnimationFrame(()=>e()))});let o=Math.max(0,a.element.scrollWidth-a.element.clientWidth),l=Math.max(0,a.element.scrollHeight-a.element.clientHeight);return{uid:a.uid,x:Math.max(0,Math.min(a.element.scrollLeft,o)),y:Math.max(0,Math.min(a.element.scrollTop,l)),maxX:o,maxY:l,viewportWidth:a.element.clientWidth,viewportHeight:a.element.clientHeight}}let uS="wsd-cdp-adapter",ux={jpeg:"image/jpeg",png:"image/png",webp:"image/webp"};function uI(e,t){return{ok:!1,error:{code:e,message:t}}}async function uE(e,t,r,n){if("take_snapshot"===e.type){if(!t||!r||!n)return uI("TARGET_NOT_FOUND","No Page or Widget target is currently rendered");let e=t.getInspectorSnapshot(),a=d_(e.root,e.selectedUid,r);return{ok:!0,result:{runtimeSnapshot:{target:n,root:a.root,nodeCount:a.nodeCount,selectedUid:a.selectedUid,truncated:a.truncated,updatedAtMs:a.updatedAtMs}}}}if(!t||!r)return uI("TARGET_NOT_FOUND","No Page or Widget target is currently rendered");if("scroll_to"===e.type){if(e.uid&&!t.getElement(e.uid))return uI("ELEMENT_NOT_FOUND",`Element uid ${e.uid} was not found`);let n=await uw(e,t,r);return n?{ok:!0,result:n}:uI("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}}:uI("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}}:uI("ELEMENT_NOT_FOUND",`Element uid ${e.uid} was not found`)}let a=e.uid?t.getElement(e.uid):r;if(!a)return uI("ELEMENT_NOT_FOUND",`Element uid ${e.uid} was not found`);let i=ux[e.format],s=a.getBoundingClientRect(),o=a.offsetWidth||s.width,l=a.offsetHeight||s.height;try{let t=await (0,u_.TC)(a,{height:l,scale:3,type:i,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:${i};base64,`,n=t.startsWith(r)?t.slice(r.length):"";if(!n||n.length>8388608)return uI("SCREENSHOT_FAILED",n?"Screenshot exceeds the 8 MiB debugger limit":"Screenshot returned invalid image data");return{ok:!0,result:{data:n,format:e.format,mimeType:i,width:Math.floor(3*o),height:Math.floor(3*l),uid:e.uid}}}catch(e){return uI("SCREENSHOT_FAILED",e instanceof Error?e.message:String(e))}}function uC(e){let{controlCommand:t,controlTarget:r,debugState:n,frontendUrl:a,onDebugAction:s,onConsoleSnapshotChange:o,onControlResult:l,onHighlightChange:d,onRuntimeSnapshotChange:u,preserveConsoleOnTargetChange:c,resolveTargetAtPoint:p,getRuntimeFrame:m,runtimeFrame:h,runtimeSnapshotTarget:g,showPanelId:f,showPanelRequestId:v,appTarget:y,consoleTarget:_,target:b}=e,w=(0,rc.useRef)(null),S=(0,rc.useRef)(n),x=(0,rc.useRef)(h??null),I=(0,rc.useRef)(y??null),E=(0,rc.useRef)(b),C=(0,rc.useRef)({consoleTarget:_,getRuntimeFrame:m,onConsoleSnapshotChange:o,onDebugAction:s,onHighlightChange:d,onRuntimeSnapshotChange:u,preserveConsoleOnTargetChange:c,resolveTargetAtPoint:p}),k=(0,rc.useRef)(),N=(0,rc.useRef)(null),T=(0,rc.useRef)(null),R=(0,rc.useRef)(null),M=(0,rc.useRef)(null),A=(0,rc.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 n=t.searchParams.get("panel");return n&&"wsd-mcp"!==n&&"wsd-view"!==n||t.searchParams.set("panel","wsd-overview"),{origin:t.origin,url:t.toString()}})(a),[a]),P=(null==A?void 0:A.url)??null;C.current={consoleTarget:_,getRuntimeFrame:m,onConsoleSnapshotChange:o,onDebugAction:s,onHighlightChange:d,onRuntimeSnapshotChange:u,preserveConsoleOnTargetChange:c,resolveTargetAtPoint:p};let j=(0,rc.useCallback)(e=>{var t,r;A&&(null==(r=w.current)||null==(t=r.contentWindow)||t.postMessage({source:uS,type:"wsd-show-panel",panelId:e},A.origin))},[A]),L=oQ(()=>{var e,t;let r=S.current;r&&A&&(null==(t=w.current)||null==(e=t.contentWindow)||e.postMessage({source:uS,type:"wsd-debug-state",state:r},A.origin))});(0,rc.useEffect)(()=>{x.current=h??null},[h]),(0,rc.useEffect)(()=>{var e;I.current=y??null,null==(e=T.current)||e.call(T)},[y]),(0,rc.useEffect)(()=>{S.current=n,L()},[n,L,P]);let D=oQ(()=>{L(),f&&j(f)});return((0,rc.useEffect)(()=>{f&&v&&j(f)},[j,f,v]),(0,rc.useEffect)(()=>{C.current.onHighlightChange(null);let e=null==A?void 0:A.origin;M.current??=document.createElement("div");let t=new o$(E.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,n;return(null==(r=(n=C.current).resolveTargetAtPoint)?void 0:r.call(n,e,t))??null}});N.current=t;let r=0,n=e=>{var n;let a=null==(n=t.dispatch({id:--r,method:e}).result)?void 0:n.entries;return Array.isArray(a)?a:[]},a=()=>{var e,t;null==(e=(t=C.current).onConsoleSnapshotChange)||e.call(t,{appEntries:n("WSD.getAppConsoleEntries"),entries:n("WSD.getConsoleEntries"),updatedAtMs:Date.now()})},i=()=>{var e,r,n,a;let i=E.current;if(!i){null==(n=(a=C.current).onRuntimeSnapshotChange)||n.call(a,null);return}let s=t.getInspectorSnapshot();null==(e=(r=C.current).onRuntimeSnapshotChange)||e.call(r,d_(s.root,s.selectedUid,i))},s=t=>{var r,n;e&&(null==(n=w.current)||null==(r=n.contentWindow)||r.postMessage({source:uS,type:"cdp-raw-message",message:JSON.stringify(t)},e))};T.current=a,R.current=i;let o=t.subscribe(e=>{"WSD.consoleUpdated"===e.method||"WSD.appConsoleUpdated"===e.method?a():(s(e),("DOM.documentUpdated"===e.method||"DOM.inlineStyleInvalidated"===e.method||"Overlay.inspectNodeRequested"===e.method)&&i())});s({method:"DOM.documentUpdated"}),a(),i();let l=r=>{var n,a,i,o,l,d,u,c,p,m,h,g,f;if(!e||r.source!==(null==(n=w.current)?void 0:n.contentWindow)||r.origin!==e)return;let v=r.data;if((null==v?void 0:v.source)==="wsd-chrome-devtools-frontend"){if("ready"===v.type)return void D();if("wsd-debug-ready"===v.type)return void L();if("wsd-debug-action"===v.type){let e=v.action;if((null==e?void 0:e.kind)==="clear-sandbox-bridge-logs"||(null==e?void 0:e.kind)==="clear-trace-filter"){null==(a=(i=C.current).onDebugAction)||a.call(i,e);return}if((null==e?void 0:e.kind)==="locate-sandbox-location"){null==(o=(l=C.current).onDebugAction)||o.call(l,e);return}if((null==e?void 0:e.kind)==="update-sandbox-location"&&"number"==typeof e.latitude&&Number.isFinite(e.latitude)&&"number"==typeof e.longitude&&Number.isFinite(e.longitude)){null==(d=(u=C.current).onDebugAction)||d.call(u,e);return}if((null==e?void 0:e.kind)==="update-sandbox-business-info"&&"string"==typeof e.phoneNum&&"string"==typeof e.csrPem){null==(c=(p=C.current).onDebugAction)||c.call(p,e);return}if((null==e?void 0:e.kind)==="recreate-sandbox-session"&&"string"==typeof e.phoneNum&&"string"==typeof e.csrPem){null==(m=(h=C.current).onDebugAction)||m.call(h,e);return}e&&("approve-tool-call"===e.kind||"reject-tool-call"===e.kind)&&"string"==typeof e.toolCallId&&(null==(g=(f=C.current).onDebugAction)||g.call(f,e));return}if("wsd-preact-devtools-message"===v.type)return void t.sendPreactDevtoolsMessage(v.payload);if("wsd-preact-highlight"===v.type){let e=v.uniqueId;t.highlightLynxNode("number"==typeof e?e:null);return}if("cdp-raw-message"===v.type&&"string"==typeof v.message){let e;try{e=JSON.parse(v.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 n,a,i;n={type:"wsd-preact-devtools-message",payload:JSON.parse(r.data)},e&&(null==(i=w.current)||null==(a=i.contentWindow)||a.postMessage({source:uS,...n},e))}catch{}};return e&&(window.addEventListener("message",l),document.addEventListener("devtoolMessage",d)),()=>{window.removeEventListener("message",l),document.removeEventListener("devtoolMessage",d),o(),T.current===a&&(T.current=null),R.current===i&&(R.current=null),N.current===t&&(N.current=null),t.destroy(),C.current.onHighlightChange(null)}},[D,L,A]),(0,rc.useEffect)(()=>{var e,t,r,n;E.current=b,M.current??=document.createElement("div"),null==(e=N.current)||e.setConsoleTarget(_),null==(t=N.current)||t.setTarget(b??M.current),null==(r=T.current)||r.call(T),null==(n=R.current)||n.call(R)},[_,b]),(0,rc.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||k.current===t.commandId)return;let e=void 0===r?E.current:r;if(("take_snapshot"===t.type||"take_screenshot"===t.type&&!t.uid)&&(!e||"take_snapshot"===t.type&&!g)){let e=window.setTimeout(()=>{k.current!==t.commandId&&(k.current=t.commandId,null==l||l(t.commandId,uI("TARGET_NOT_FOUND","No Page or Widget target is currently rendered")))},2e3);return()=>window.clearTimeout(e)}k.current=t.commandId,(async()=>{let r;try{r=await uE(t,N.current,e,g)}catch(e){r=uI("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,b]),P)?(0,i.jsx)("aside",{className:"wsd-chrome-devtools",children:(0,i.jsx)("iframe",{allow:"clipboard-write",className:"wsd-chrome-devtools-frame",onLoad:D,ref:w,sandbox:"allow-scripts allow-same-origin allow-forms",src:P,title:"Chrome DevTools"})}):(0,i.jsx)("aside",{className:"wsd-chrome-devtools",children:(0,i.jsx)("div",{className:"wsd-chrome-devtools-empty",children:"Chrome DevTools frontend is not configured"})})}function uk(e,t,r){return Math.min(Math.max(e,t),r)}function uN(e,t,r,n){if(!t)return uk(e,r,n);let a=t.getBoundingClientRect().width;if(!a)return uk(e,r,n);let i=Math.min(n,Math.max(r,a-8-340));return uk(e,r,i)}function uT(){let{localConnectionStatus:e,reconnect:t}=lb();return"disconnected"!==e?null:(0,i.jsxs)("div",{className:"wsd-local-debug-connection-warning",role:"alert",children:[(0,i.jsx)("span",{children:"与本地调试服务的链接已断开"}),(0,i.jsx)("button",{onClick:t,type:"button",children:"重新连接"})]})}function uR(e){var t;let{activeView:r="conversation",className:n,onActiveViewChange:a,...s}=e,[o,l]=(0,rc.useState)(ur),[d,u]=(0,rc.useState)(),[c,p]=(0,rc.useState)("page"===r),[m,h]=(0,rc.useState)({onHighlightChange:()=>void 0,target:null}),g=oQ(e=>{h(e)}),{isResizing:f,panelStyle:v,separatorProps:y}=function(){let{defaultWidth:e=520,minWidth:t=420,maxWidth:r=640}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},[n,a]=(0,rc.useState)(e),[i,s]=(0,rc.useState)(!1),o=(0,rc.useRef)(null),l=(0,rc.useMemo)(()=>({"--wsd-preview-column-width":`${n}px`}),[n]),d=oQ((e,n)=>{if(!n)return;let i=n.getBoundingClientRect();i.width&&a(uN(e-i.left,n,t,r))});(0,rc.useEffect)(()=>()=>{var e;null==(e=o.current)||e.call(o)},[]);let u=oQ(e=>{var t,r;if(0!==e.button)return;let n=e.currentTarget,a=n.parentElement;if(!a)return;e.preventDefault(),null==(t=o.current)||t.call(o),null==(r=n.setPointerCapture)||r.call(n,e.pointerId),d(e.clientX,a),s(!0);let i=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,a)},c=()=>{o.current===c&&(o.current=null,window.removeEventListener("pointermove",u),window.removeEventListener("pointerup",c),window.removeEventListener("pointercancel",c),document.body.style.cursor=i,document.body.style.userSelect=l,s(!1))};o.current=c,window.addEventListener("pointermove",u),window.addEventListener("pointerup",c),window.addEventListener("pointercancel",c)}),c=oQ(e=>{let n=e.currentTarget.parentElement;if("ArrowLeft"===e.key){e.preventDefault(),a(e=>uN(e-24,n,t,r));return}if("ArrowRight"===e.key){e.preventDefault(),a(e=>uN(e+24,n,t,r));return}if("Home"===e.key){e.preventDefault(),a(uN(t,n,t,r));return}"End"===e.key&&(e.preventDefault(),a(uN(r,n,t,r)))});return{isResizing:i,panelStyle:l,separatorProps:{"aria-label":"Resize preview and DevTools","aria-orientation":"vertical","aria-valuemax":r,"aria-valuemin":t,"aria-valuenow":Math.round(n),onKeyDown:c,onPointerDown:u,role:"separator",tabIndex:0}}}({defaultWidth:340,maxWidth:560,minWidth:300}),_={...s,onChromeDevToolsPanelChange:g};(0,rc.useEffect)(()=>{"page"===r&&p(!0)},[r]);let b="tool"===r?(0,i.jsx)(ui,{..._,onActiveViewChange:a,onSessionChange:l,onUseWidgetOutput:e=>{let{viewData:t,widgetId:r}=e;s.webSdkDebugger.selectWidget(r),u(t),null==a||a("card")},session:o}):"card"===r?(0,i.jsx)(uy,{..._,initDataDraft:d,onActiveViewChange:a}):"conversation"===r?(0,i.jsx)(dV,{..._,onActiveViewChange:a}):null;return(0,i.jsxs)("section",{className:(0,e6.$)("page"===r?"wsd-page-panel":"wsd-widget-panel",f&&"is-resizing",n),style:v,children:[(0,i.jsxs)(l_,{enabled:!!((null==(t=s.debugContext)?void 0:t.sandboxEventsAvailable)&&!1!==s.debugContext.sandboxSessionAvailable),connection:s.connection,onMessage:s.onMessage,webSdkDebugger:s.webSdkDebugger,children:[(0,i.jsx)(uT,{}),"page"===r||c?(0,i.jsx)(ue,{..._,activeView:r,onActiveViewChange:a}):null,b]}),(0,i.jsx)("div",{className:"wsd-runtime-splitter",...y}),(0,i.jsx)(uC,{...m})]})}function uM(e,t){var r,n,a;null==e||e({category:(null==(r=t.event)?void 0:r.startsWith("simulator_manifest_"))||(null==(n=t.event)?void 0:n.startsWith("simulator_skill_"))||(null==(a=t.event)?void 0:a.startsWith("simulator_resources_"))?"resource":"mcp",source:"local_mcp",...t})}function uA(e){return e4(e,{allowRootRelative:!0,baseUrl:window.location.href})}function uP(e){let t=function(e){let t={};for(let r of["content-type","content-length","x-tt-logid"]){let n=e.headers.get(r);n&&(t[r]=n)}return t}(e);return{status:e.status,status_text:e.statusText,response_headers:Object.keys(t).length>0?t:void 0}}function uj(e,t,r){uM(e,{event:`simulator_${t}_fetch_started`,phase:"request",url:r})}function uL(e,t,r,n){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};uM(e,{event:`simulator_${t}_fetch_succeeded`,phase:"response",url:r,...uP(n),...a})}function uD(e,t,r,n,a){uM(e,{event:`simulator_${t}_fetch_failed`,phase:"error",url:r,...a?uP(a):{},error:n instanceof Error?n.message:String(n)})}function uO(e,t,r){return Error(`Simulator ${e} failed: ${r.status} ${r.statusText} (${t})`)}let uU="web-sdk-debugger-demo",uq="mock_local_mcp",u$="mock_lookup",uB=["template-transport-card","template-price-action-card","template-ticket-order-card","weather-card","flight-card","api-demo-card","summary-card","configured-widget-id"],uF=[{server_id:uq,name:"Mock Local MCP",description:"Web SDK Debugger 本地模拟 MCP server",tools:[{name:u$,description:"返回用于本地调试的智能服务结构化结果",input_schema_json:JSON.stringify({type:"object",properties:{keyword:{type:"string"}},required:["keyword"]})}]}];function uW(e,t){return`id: evt_mock_${t.toString().padStart(4,"0")}
|
|
41
|
+
event: ${e.event}
|
|
42
|
+
data: ${JSON.stringify(e)}
|
|
43
|
+
|
|
44
|
+
`}function uH(e,t){return t.find(t=>null==e?void 0:e.widgets.some(e=>e.widgetId===t))}function uz(e,t,r,n){var a;return{event:t,request_id:n.requestId,reply_message_id:n.replyMessageId,trace:{trace_id:(null==(a=e.trace)?void 0:a.trace_id)||`trace_mock_${e.idempotency_key??n.requestId}`,component:"mock_simulator",stage:t,sampled:!0},...r}}let uV=async e=>{var t;let r=`找到和 ${(null==(t=e.arguments)?void 0:t.keyword)||"调试数据"} 相关的模拟结果`,n={content:[{type:"text",text:r}],structuredContent:{entities:[{entity_type:"debug_item",entity_id:"debug-item-1",name:"调试示例数据"}]},isError:!1},a=JSON.stringify(n);return{status:"succeeded",result:n.structuredContent,raw_result_text:r,raw_mcp_result_json:a,miniapp:{is_mini_app:!0,mcp_channel:"flow_miniapp"},debug:{mock:!0}}},uG=rb(rv),uJ=se({requestHandler:async e=>{var t,r;let n=await fetch("/__web_sdk_request_proxy__",{body:JSON.stringify((r=e.params).data instanceof ArrayBuffer?{...r,data:rh(r.data),dataEncoding:"base64"}:r),headers:{"content-type":"application/json"},method:"POST"}),a=(null==(t=n.headers.get("content-type"))?void 0:t.toLowerCase())??"",i=await n.text();if(!a.includes("application/json"))throw Error(`Request proxy returned a non-JSON response. Make sure the debugger is started with the local request proxy. Response starts with: ${i.slice(0,120)}`);let s=i?JSON.parse(i):{};if(!n.ok)throw Error((null==s?void 0:s.message)||`Request proxy failed with status ${n.status}`);return(null==s?void 0:s.dataEncoding)==="base64"&&"string"==typeof s.data?u(e,{statusCode:s.statusCode,header:s.header,data:rg(s.data)}):u(e,s)}});function uK(e,t){if(e.has(t))return!1;if(e.add(t),e.size>100){let t=e.values().next().value;t&&e.delete(t)}return!0}function uX(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";return new URL(window.location.href).searchParams.get(e)||r||t}async function uQ(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:fetch;try{var t;let r=await e("/__web_sdk_debug_context",{cache:"no-store",headers:{Accept:"application/json"}});return r.ok?!(t=await r.json())||"object"!=typeof t||Array.isArray(t)?{}:t:{}}catch{return{}}}async function uY(e,t){let r=t.skills,n=t.mcpServers,a=[];if("function"==typeof r&&a.push(Promise.resolve(r()).catch(()=>void 0)),"function"==typeof n){let t=e.getState();a.push(Promise.resolve(n({appKey:t.manifest.appId,appName:t.manifest.name,manifest:t.manifest.raw})).catch(()=>void 0))}await Promise.all(a)}function uZ(){return(0,i.jsx)("main",{className:"chrome-devtools-unavailable-page",children:(0,i.jsx)("section",{className:"wsd-chrome-devtools",children:(0,i.jsx)("div",{className:"wsd-chrome-devtools-empty",children:"Chrome DevTools frontend is unavailable"})})})}function u0(e){let{serverDebugContext:t}=e,r=(0,rc.useMemo)(()=>new URL(window.location.href).searchParams.get("manifest")||rf,[]),n=(0,rc.useMemo)(()=>uX("mcp","",void 0),[]),a=(0,rc.useMemo)(()=>{let e;return(e=new URL(window.location.href)).searchParams.get("mcpOriginal")||e.searchParams.get("mcpEndpoint")||""},[]),s=(0,rc.useMemo)(()=>uX("simulatorManifest","/__simulator_manifest/manifest.yaml",void 0),[]),o=(0,rc.useMemo)(()=>new URL(window.location.href).searchParams.get("simulatorManifestOriginal")||"",[]),l=(0,rc.useMemo)(()=>uX("simulatorSkills","/__simulator_skills/index.json",void 0),[]),d=(0,rc.useMemo)(()=>new URL(window.location.href).searchParams.get("simulatorSkillsOriginal")||"",[]),u=(0,rc.useMemo)(()=>rb(new URL(window.location.href).searchParams.get("simulator")||uG),[]),c=(0,rc.useMemo)(()=>{let e;return(e=new URL(window.location.href)).searchParams.get("launchDir")||e.searchParams.get("projectPath")||e.searchParams.get("cwd")||""},[]),p=(0,rc.useMemo)(()=>`${window.location.origin}${window.location.pathname}`,[]),m=(0,rc.useMemo)(()=>{let e;return null!==(e=new URL(window.location.href).searchParams.get("DEBUG"))&&"0"!==e&&"false"!==e.toLowerCase()},[]),h=(0,rc.useMemo)(()=>"1"===new URL(window.location.href).searchParams.get("simulatorMock")||"true"===String((void 0)??"").toLowerCase(),[]),g=(0,rc.useRef)(null),f=(0,rc.useMemo)(()=>new rd,[]),v=f.clientId,[y,_]=(0,rc.useState)(),b=(0,rc.useRef)(new Set),w=(0,rc.useMemo)(()=>(function(e){var t,r,n,a,i;let s,o,l=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},d={mcpEndpoint:uA((t={mcpEndpoint:e,simulatorManifestUrl:l.simulatorManifestUrl,simulatorSkillsIndexUrl:l.simulatorSkillsIndexUrl}).mcpEndpoint),simulatorManifestUrl:uA(t.simulatorManifestUrl),simulatorSkillsIndexUrl:uA(t.simulatorSkillsIndexUrl)},u=function(){let e,t,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{mcpServers:async e=>{let t=Object.entries(Object.fromEntries(Object.entries((e.manifest??{}).tools??{}).filter(e=>{let[,t]=e;return!0===t.is_client_tool}))).map(e=>{let[t,r]=e;return{name:t,description:r.description,input_schema_json:function e(t){if(Array.isArray(t))return t.map(e);if(!e8(t))return t;let r={};for(let[n,a]of Object.entries(t))r[n]="type"===n&&"int"===a?"integer":"type"===n&&"float"===a?"number":e(a);return r}(r.input_schema)}});return 0===t.length?(nu(r.onTraceEvent,{event:"client_tools_empty",app_key:e.appKey,server_id:no,tool_count:0,tools:[]}),[]):(nu(r.onTraceEvent,{event:"client_tools_resolved",app_key:e.appKey,server_id:no,tool_count:t.length,tools:t.map(e=>e.name)}),[{server_id:no,name:"Client Tool",description:"Client Tool runtime for simulator debugging",tools:t}])},toolExecutor:((t=async t=>{let n,a;try{n=function(e){let t=e.arguments;if(void 0===t){if(void 0===e.argumentsJson)t={};else if(void 0===(t=tP(e.argumentsJson)))throw Error("Tool arguments must be valid JSON")}if(!e8(t))throw Error("Tool arguments must be a JSON object");return t}(t),a="string"==typeof t.argumentsJson&&t.argumentsJson.trim()?t.argumentsJson:tL(n)}catch(e){return ng("CLIENT_TOOL_INVALID_ARGUMENTS",tD(e),!1)}try{var i;nu(r.onTraceEvent,{event:"client_tool_call_started",request_id:t.requestId,trace_id:t.trace.trace_id,app_key:t.appKey,server_id:t.serverId,tool_call_id:t.toolCallId,tool_name:t.toolName,arguments:n,arguments_json:tL(n)});let s=await (()=>{var t,n;let a=null==(t=r.getRuntimeUrl)?void 0:t.call(r);if(!a)throw Error("Client Tool runtime is unavailable. Build the app with a Web Client Tool entry.");if(!e||e.runtimeUrl!==a){null==e||e.dispose();let t=(r.runtimeFactory??function(e,t){return new nc(e,t)})(a,null==(n=r.getRuntimeGlobalProps)?void 0:n.call(r));e=new nh(a,t,r.onTraceEvent),nu(r.onTraceEvent,{event:"client_tool_runtime_started",runtime_url:a})}return e})().invokeTool({toolId:t.toolName,input:a,context:{callbackId:t.toolCallId,conversationId:t.requestId,featureMap:void 0,msgId:t.replyMessageId,questionId:t.requestId},signal:t.signal}),o=function(e,t){var r,n;if(0===e.result)try{let n=function(e,t){if(!e8(e)||!Array.isArray(e.content))throw Error(`Client Tool "${t}" must return an MCP tool output object`);return e}(e.output,t.toolName),a=!0===n.isError?n:function(e,t){let r=na(t.manifest,t.toolName);if(!r||"string"!=typeof r.kind)throw Error(`Client Tool "${t.toolName}" manifest output is required`);if("execution_result"===r.kind)return e;if("entities"!==r.kind)throw Error(`Client Tool "${t.toolName}" has unsupported output kind "${r.kind}"`);if(!e8(e)||!Array.isArray(e.structuredContent))throw Error(`Client Tool "${t.toolName}" must return structuredContent as an array`);return ni(e,t.manifest,t.toolName)}(n,t);return r=ns(a,{businessErrorCode:"CLIENT_TOOL_BUSINESS_ERROR",protocol:nd,source:"client_tool"}),{...r,debug:{...r.debug,mcp_output:n}}}catch(e){return ng("CLIENT_TOOL_INVALID_RESULT",tD(e),!1)}let a=void 0===(n=e.reason)?"":e8(n)?"string"==typeof n.message?n.message:tL(n):tD(n);return 2===e.result?ng("CLIENT_TOOL_NOT_FOUND",`Client Tool not found: ${e.toolId}`,!1):1===e.result?ng("CLIENT_TOOL_FAILED",a||`Client Tool failed: ${e.toolId}`,!1):ng("CLIENT_TOOL_UNKNOWN_RESULT",`Client Tool returned unknown status: ${String(e.result)}`,!1)}(s,t);return nu(r.onTraceEvent,{event:"succeeded"===o.status?"client_tool_call_succeeded":"client_tool_call_failed",request_id:t.requestId,app_key:t.appKey,server_id:t.serverId,tool_call_id:t.toolCallId,tool_name:t.toolName,status:o.status,result:o.result,raw_mcp_result_json:o.raw_mcp_result_json,error:null==(i=o.error)?void 0:i.message}),o}catch(n){let e=tD(n);return nu(r.onTraceEvent,{event:"client_tool_call_failed",request_id:t.requestId,app_key:t.appKey,server_id:t.serverId,tool_call_id:t.toolCallId,tool_name:t.toolName,error:e}),ng("CLIENT_TOOL_CALL_FAILED",e,!0)}}).dispose=()=>{null==e||e.dispose(),e=void 0},t)}}({getRuntimeGlobalProps:l.getClientToolRuntimeGlobalProps,getRuntimeUrl:l.getClientToolRuntimeUrl,onTraceEvent:l.onTraceEvent}),c=u.toolExecutor,p=u.mcpServers,m=()=>{var e;return o??=Promise.resolve(d.mcpEndpoint||(null==(e=l.getMcpEndpoint)?void 0:e.call(l))).then(e=>{let t=uA(e);return s=t?function(e){let t=e4(e.endpoint);if(!t)return{};let r=function(e,t){if(null==t?void 0:t.trim())return t.trim();let r=new URL(e);return`${r.hostname}_${r.port||r.protocol.replace(":","")}${r.pathname}`.replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/^_+|_+$/g,"")||"local_mcp"}(t,e.serverId);return{mcpServers:async n=>{let a;try{sr(e.onTraceEvent,{event:"local_mcp_tools_load_started",app_key:n.appKey,mcp_endpoint:t,server_id:r},n),a=await sa(t,{...e,signal:n.signal});let i=await a.client.listTools(void 0,{signal:n.signal}),s=a.client.getServerVersion(),o={server_id:r,name:(null==s?void 0:s.name)||r,description:a.client.getInstructions()||"",tools:i.tools.map(sn).filter(e=>e.name)};return sr(e.onTraceEvent,{event:"local_mcp_tools_loaded",app_key:n.appKey,mcp_endpoint:t,server_id:o.server_id,server_version:s,tools:o.tools.map(e=>e.name)},n),[o]}catch(a){var i;return null==(i=n.signal)||i.throwIfAborted(),sr(e.onTraceEvent,{event:"local_mcp_tools_load_failed",app_key:n.appKey,mcp_endpoint:t,server_id:r,error:tD(a),request_will_continue:!0,tool_count:0,tools:[]},n),console.warn("[web-sdk-debugger] Failed to load MCP tools",a),[]}finally{a&&await si(a)}},toolExecutor:async r=>{var n;let a,i=r.arguments??tP(r.argumentsJson)??{},s=r.argumentsJson||tL(i),o=Date.now();try{sr(e.onTraceEvent,{event:"local_mcp_call_started",request_id:r.requestId,trace_id:r.trace.trace_id,app_key:r.appKey,server_id:r.serverId,tool_call_id:r.toolCallId,tool_name:r.toolName,arguments:i,arguments_json:s,mcp_endpoint:t}),a=await sa(t,{...e,signal:r.signal,headers:function(e,t){if(!e&&!t)return;let r=new Headers(e);for(let[e,n]of Object.entries(t??{}))r.set(e,n);return r}(e.headers,r.headers)}),null==(n=r.signal)||n.throwIfAborted();let l=await a.client.callTool({name:r.toolName,arguments:i,_meta:{request_id:r.requestId,trace_id:r.trace.trace_id,app_key:r.appKey,server_id:r.serverId,tool_call_id:r.toolCallId,tool_name:r.toolName,arguments_json:s}},{signal:r.signal}),d=!0===l.isError?l:ni(l,r.manifest,r.toolName),u=ns(d,{businessErrorCode:"LOCAL_MCP_BUSINESS_ERROR",protocol:"streamable_http",source:"local_mcp"});return u.debug={...u.debug,mcp_output:l},sr(e.onTraceEvent,{event:"local_mcp_call_succeeded",request_id:r.requestId,trace_id:r.trace.trace_id,app_key:r.appKey,server_id:r.serverId,tool_call_id:r.toolCallId,tool_name:r.toolName,status:u.status,result:u.result,raw_result_text:u.raw_result_text,raw_mcp_result:d,elapsed_ms:Date.now()-o,mcp_endpoint:t}),u}catch(a){if(r5(a))throw a;let n=tD(a);return sr(e.onTraceEvent,{event:"local_mcp_call_failed",request_id:r.requestId,trace_id:r.trace.trace_id,app_key:r.appKey,server_id:r.serverId,tool_call_id:r.toolCallId,tool_name:r.toolName,error:n,elapsed_ms:Date.now()-o,mcp_endpoint:t}),{status:"failed",result:{error:n},error:{code:"LOCAL_MCP_CALL_FAILED",message:n,retryable:!0,stage:"tool_execute"},raw_result_text:n}}finally{a&&await si(a)}}}}({endpoint:t,onTraceEvent:l.onTraceEvent}):void 0})},h=async e=>{let[t,r]=await Promise.all([m(),p(e)]);if(!t)return r;let n=t.mcpServers;return[...await n(e),...r]},g=async e=>{if(e.serverId===no)return c(e);let t=await m();if(!t){let e="Local MCP is not configured";return{status:"failed",result:{error:e},error:{code:"LOCAL_MCP_NOT_CONFIGURED",message:e,retryable:!1,stage:"tool_execute"},raw_result_text:e}}return t.toolExecutor(e)};return g.dispose=()=>{var e,t,r;null==(e=c.dispose)||e.call(c),null==s||null==(r=s.toolExecutor)||null==(t=r.dispose)||t.call(r)},{simulatorManifest:d.simulatorManifestUrl?(r=d.simulatorManifestUrl,n=l.onTraceEvent,async e=>{let t;uj(n,"manifest",r);try{if(!(t=await fetch(r,{signal:e,cache:"no-store",headers:{Accept:"application/yaml, text/yaml, text/x-yaml, application/json, text/plain"}})).ok)throw uO("manifest",r,t);let a=await t.text(),i=function(e){let t=(0,nn.qg)(e);if(!e8(t))throw Error("Simulator manifest must be a YAML object");return t}(a);return uL(n,"manifest",r,t,{bytes:a.length}),{...i,raw_manifest_yaml:a}}catch(e){throw uD(n,"manifest",r,e,t),console.warn("[web-sdk-debugger] Failed to load simulator manifest supplement",e),e}}):void 0,skills:d.simulatorSkillsIndexUrl?(a=d.simulatorSkillsIndexUrl,i=l.onTraceEvent,async e=>{let t;uj(i,"skill",a);try{var r;if(!(t=await fetch(a,{signal:e,cache:"no-store",headers:{Accept:"application/json"}})).ok)throw uO("skill",a,t);let n=await t.text();if(((null==(r=t.headers.get("content-type"))?void 0:r.toLowerCase())??"").includes("text/html")||/^<!doctype html\b|^<html[\s>]/i.test(n.trimStart()))throw Error(`Simulator skills index returned HTML instead of JSON (${a})`);let s=function(e){if(!e8(e)||!Array.isArray(e.skills))throw Error("Simulator skills index must contain a skills array");return e.skills.map((e,t)=>{var r;if(r=e,!e8(r)||"string"!=typeof r.relativePath||"string"!=typeof r.content)throw Error(`Simulator skills index contains an invalid entry at index ${t}`);return e}).sort((e,t)=>e.relativePath<t.relativePath?-1:+(e.relativePath>t.relativePath))}(JSON.parse(n));return uL(i,"skill",a,t,{bytes:n.length,skill_paths:s.map(e=>e.relativePath)}),s}catch(e){throw uD(i,"skill",a,e,t),console.warn("[web-sdk-debugger] Failed to load simulator skills",e),e}}):void 0,mcpServers:h,toolExecutor:g}})(n,{getClientToolRuntimeGlobalProps:()=>{var e;let t=null==(e=g.current)?void 0:e.getState().manifest;return t?td(t):void 0},getClientToolRuntimeUrl:()=>{var e;let t=null==(e=g.current)?void 0:e.getState();return t?function(e,t,r){var n,a,i,s,o,l;let d,u=(null==(i=t.applet)||null==(a=i.web)||null==(n=a.toolRuntimeEntry)?void 0:n.trim())||(null==(o=t.applet)||null==(s=o.toolRuntimeEntry)?void 0:s.trim());if(!u)return;let c=new URL(u,((d=new URL(String(e),(null==(l=globalThis.location)?void 0:l.href)||"http://localhost/")).pathname.endsWith("/base/manifest.json")?d.pathname=d.pathname.slice(0,-18):d.pathname=d.pathname.replace(/\/[^/]*$/,"/"),d.search="",d.hash="",d));return r&&c.searchParams.set("__doubao_resource_reload",r),c.toString()}(t.manifestUrl,t.manifest.raw,t.resourceUrlVersion):void 0},getMcpEndpoint:async()=>t.mcpProxyEndpoint,onTraceEvent:e=>{var t;return null==(t=g.current)?void 0:t.appendSimulatorTraceEvent(e)},simulatorManifestUrl:s,simulatorSkillsIndexUrl:l}),[n,s,l,t.mcpProxyEndpoint]),S=(0,rc.useMemo)(()=>{let e=h?{appKey:uU,appName:"调试示例智能服务",mcpServers:uF,simulatorFetch:function(e){let{getDebuggerState:t}=e;return async(e,r)=>{var n,a,i,s,o,l,d,u;let c,p,m,h,g,f,v,y,_=String(e);if(_.endsWith("/simulator/tool/report")){let e="string"==typeof(null==r?void 0:r.body)?JSON.parse(r.body):{};return new Response(JSON.stringify({code:0,message:"OK",request_id:e.request_id,tool_call_id:e.tool_call_id,trace:e.trace}),{headers:{"Content-Type":"application/json"},status:200,statusText:"OK"})}return _.endsWith("/simulator/chat")?(y=(n="string"!=typeof(null==r?void 0:r.body)?{}:JSON.parse(r.body),s=t(),p=((c=new URL(window.location.href).searchParams.get("simulatorMockWidget"))?uH(s,[c]):void 0)||uH(s,uB)||(null==s||null==(o=s.widgetSelection)?void 0:o.item.widgetId)||(null==(l=s)||null==(d=l.widgets.find(e=>{var t;return null==(t=e.web)?void 0:t.entry}))?void 0:d.widgetId)||(null==l||null==(u=l.widgets[0])?void 0:u.widgetId)||"weather-card",m=Date.now().toString(36),h={requestId:`req_mock_server_${m}`,replyMessageId:`msg_mock_reply_${m}`},g=(null==(a=n.message)?void 0:a.content)||"模拟请求",f=`call_mock_${m}`,v={applet_id:n.app_id||uU,widget_id:p,entity_id:"mock-entity-1",viewData:{source:"web-sdk-debugger-mock",keyword:g,widgetId:p},extra:{"doubao/outputTemplate":"mock.output.template"}},[uz(n,"ack",{ack:{request_id:h.requestId,message_id:h.replyMessageId,local_message_id:null==(i=n.message)?void 0:i.local_message_id}},h),uz(n,"tool_call",{tool_call:{tool_call_id:f,tool_name:u$,server_id:uq,app_key:n.app_id||uU,arguments_json:JSON.stringify({keyword:g}),status:"PENDING",timeout_ms:2e3}},h),uz(n,"tool_status",{tool_status:{tool_call_id:f,status:"RUNNING",progress:.6,message:"Mock tool running"}},h),uz(n,"text_delta",{text_delta:{block_id:"block_mock_text",op:"append",delta:`Mock 已收到:${g}`}},h),uz(n,"card_delta",{card_delta:{block_id:"block_mock_card",op:"append",card_id:`card_mock_${m}`,source_tool_call_id:f,source_entity_ids:["mock-entity-1"],is_final:!0,card:{card_id:`card_mock_${m}`,card_type:"mock_widget_card",title:"Mock 智能服务卡片",fallback_text:`使用 ${p} 渲染`,props_json:JSON.stringify(v)}}},h),uz(n,"debug",{debug_event:{category:"mock",title:"Mock Simulator",summary:"本地 mock SSE 已生成 text/card/tool 事件",data:{widget_id:p},redaction_level:"none"}},h),uz(n,"answer_finish",{answer_finish:{status:"completed",finish_reason:"stop",usage:{output_tokens:12}}},h),uz(n,"reply_finish",{reply_finish:{status:"completed",finish_reason:"stop",event_count:7}},h)]).map(uW).join(""),new Response(new ReadableStream({start(e){e.enqueue(new TextEncoder().encode(y)),e.close()}}),{headers:{"Content-Type":"text/event-stream"},status:200,statusText:"OK"})):new Response(JSON.stringify({ok:!1,error:"Unknown mock simulator endpoint"}),{status:404,statusText:"Not Found"})}}({getDebuggerState:()=>{var e;return(null==(e=g.current)?void 0:e.getState())??null}}),toolExecutor:uV}:{},t=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return new nP(e)}({manifestUrl:r,simulatorEndpoint:u,...w,...e});return g.current=t,t},[r,u,w,h]),[x,I]=(0,rc.useState)(()=>{let e,t,r;return t=(e=new URL(window.location.href)).searchParams.get("view"),r=e.searchParams.get("debugMode")||e.searchParams.get("mode"),"conversation"===t||"tool"===t||"card"===t||"page"===t?t:"conversation"===r||"tool"===r||"card"===r||"page"===r?r:"conversation"}),E=oQ((e,t)=>{uK(b.current,e)&&f.reportResult({commandId:e,...t}).catch(e=>console.error(e)).finally(()=>{_(t=>(null==t?void 0:t.commandId)===e?void 0:t)})}),C=oQ(e=>{if("cancel_chat_query"===e.type){lr(S,e.commandId),E(e.commandId,{ok:!1,error:{code:"CHAT_TIMEOUT",message:"Chat query was cancelled after the debugger control timeout"}});return}"execute_sandbox_tool_call"===e.type?S.executeSandboxToolCall(e.toolCall).then(t=>{E(e.commandId,{ok:!0,result:{reported:t.reported,request_id:t.requestId,tool_call_id:t.toolCallId}})}).catch(t=>{E(e.commandId,{error:{code:"TOOL_CALL_FAILED",message:t instanceof Error?t.message:String(t)},ok:!1})}):(_(e),("render_page"===e.type||"render_widget"===e.type||"submit_chat_query"===e.type)&&I("render_page"===e.type?"page":"render_widget"===e.type?"card":"conversation"))}),k=oQ(e=>{try{var t;null==(t=g.current)||t.navigateToPage(e.url)}catch{}I("page")}),N=oQ(()=>{let{manifest:e}=S.getState();return{appKey:e.appId,appName:e.name}});(0,rc.useEffect)(()=>{let e=f.subscribe(e=>{if("control"===e.type)C(e.data);else if("status"===e.type&&"connected"!==e.status){let e=lr(S);e&&uK(b.current,e),_(void 0)}});return f.start(),()=>{e(),f.stop()}},[f,C,S]),(0,rc.useEffect)(()=>(function(e){let t=document.modelContext;if(!t)return()=>{};let r=new AbortController,n=new URL("/__wsd_mcp",window.location.href);async function a(e){let t=await sa(n.href,{});try{return await e(t.client)}finally{await si(t)}}return n.searchParams.set("clientId",e),(async function(){let{tools:e}=await a(e=>e.listTools());for(let i of e){var n;r.signal.throwIfAborted(),await t.registerTool({name:i.name,description:i.description??"",inputSchema:i.inputSchema,annotations:{readOnlyHint:(null==(n=i.annotations)?void 0:n.readOnlyHint)===!0,untrustedContentHint:!0},execute:async function(e){let{signal:t}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return r.signal.throwIfAborted(),null==t||t.throwIfAborted(),a(async r=>{null==t||t.throwIfAborted();let n=await r.callTool({name:i.name,arguments:e},{signal:t,timeout:13e4}),a=JSON.stringify(n);if(n.isError)throw Error(a);return a})}},{signal:r.signal})}})().catch(e=>{r.signal.aborted||(r.abort(),console.warn("[web-sdk-debugger] Failed to register WebMCP tools",e))}),()=>r.abort()})(v),[v]),(0,rc.useEffect)(()=>{let e=!1;return S.loadManifest(r).then(()=>{if(!e){let e;return e=new URL(window.location.href),r===rf?e.searchParams.delete("manifest"):e.searchParams.set("manifest",r),window.history.replaceState(null,"",e),uY(S,w)}}).catch(()=>{}),()=>{e=!0,S.destroy(),g.current===S&&(g.current=null)}},[r,w,S]);let T=(0,rc.useMemo)(()=>({launchDir:c,simulatorManifestOriginalUrl:o,simulatorManifestProxyUrl:s,simulatorManifestUrl:s,simulatorSkillsIndexOriginalUrl:d,simulatorSkillsIndexProxyUrl:l,simulatorSkillsIndexUrl:l,webUrl:p,...t,mcpEndpoint:n||t.mcpProxyEndpoint,mcpOriginalEndpoint:a||t.mcpOriginalEndpoint,mcpProxyEndpoint:n||t.mcpProxyEndpoint}),[c,n,a,o,s,d,l,p,t]);return(0,i.jsx)(ru.M,{children:(0,i.jsx)("section",{className:"workspace",children:(0,i.jsx)("section",{className:"debug-workspace",children:(0,i.jsx)("section",{className:"debug-mode-panel",children:(0,i.jsx)(o0,{capability:T.realDeviceDebug,getAppIdentity:N,children:(0,i.jsx)(uR,{activeView:x,apiEnvironment:uJ,chromeDevToolsFrontendUrl:"/chrome-devtools/inspector.html",controlCommand:y,controlClientId:v,debugContext:T,onActiveViewChange:I,onControlResult:E,onNavigateToPage:k,showDebugTrace:m,connection:f,webSdkDebugger:S})})})})})})}function u1(e){let{serverDebugContext:t}=e;return window.location.pathname.startsWith("/chrome-devtools/")?(0,i.jsx)(uZ,{}):(0,i.jsx)(u0,{serverDebugContext:t})}async function u2(){let e=await uQ();e.webViewOrigin&&(em=t=>({messageTransport:"window",url:`${e.webViewOrigin}/__webview/bootstrap?${new URLSearchParams({url:t,parentOrigin:location.origin})}`}));let t=document.querySelector("#app");if(!t)throw Error("Cannot find #app");(0,tk.H)(t).render((0,i.jsx)(u1,{serverDebugContext:e}))}(async function(){if("serviceWorker"in navigator){let e=e=>(null==e?void 0:e.scriptURL)===new URL("/__webview/sw.js",location.origin).href,t=e(navigator.serviceWorker.controller),r=await navigator.serviceWorker.getRegistrations();if(await Promise.all(r.filter(t=>e(t.active)||e(t.waiting)||e(t.installing)).map(e=>e.unregister())),t)return void location.reload()}await u2()})().catch(u2)}},m={};function h(e){var t=m[e];if(void 0!==t)return t.exports;var r=m[e]={id:e,exports:{}};return p[e].call(r.exports,r,r.exports,h),r.exports}h.m=p,h.c=m,t=(e="function"==typeof Symbol)?Symbol("rspack queues"):"__rspack_queues",r=h.aE=e?Symbol("rspack exports"):"__webpack_exports__",n=e?Symbol("rspack error"):"__rspack_error",a=e?Symbol("rspack done"):"__rspack_done",i=h.zS=e?Symbol("rspack defer"):"__rspack_defer",h.zT=e=>{if(e.some(e=>{var t=m[e];return!t||!1===t[a]}))return{then:(t,r)=>Promise.all(e.map(h)).then(t,r)}},s=e=>{e&&e.d<1&&(e.d=1,e.forEach(e=>e.r--),e.forEach(e=>e.r--?e.r++:e()))},h.a=(e,o,l)=>{l&&((d=[]).d=-1);var d,u,c,p,m=new Set,g=e.exports,f=new Promise((e,t)=>{p=t,c=e});f[r]=g,f[t]=e=>{d&&e(d),m.forEach(e),f.catch(()=>{})},e.exports=f,o(e=>{u=e.map(e=>{if(null!==e&&"object"==typeof e){if(!e[t]&&e[i]){var a=h.zT(e[i]);if(!a)return e;var o=e;e={then(e,t){a.then(()=>e(o),t)}}}if(e[t])return e;if(e.then){var l=[];l.d=0,e.then(e=>{d[r]=e,s(l)},e=>{d[n]=e,s(l)});var d={};return d[i]=!1,d[t]=e=>e(l),d}}var u={};return u[t]=()=>{},u[r]=e,u});var a,o=()=>u.map(e=>{if(e[i])return e;if(e[n])throw e[n];return e[r]}),l=new Promise(e=>{(a=()=>e(o)).r=0;var r=e=>e!==d&&!m.has(e)&&(m.add(e),e&&!e.d&&(a.r++,e.push(a)));u.map(e=>e[i]||e[t](r))});return a.r?l:o()},e=>(e?p(f[n]=e):c(g),s(d),f[a]=!0)),d&&d.d<0&&(d.d=0)},h.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return h.d(t,{a:t}),t},h.d=(e,t,r)=>{var n=(t,r)=>{for(var n in t)h.o(t,n)&&!h.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,[r]:t[n]})};n(t,"get"),n(r,"value")},h.f={},h.e=(e,t)=>Promise.all(Object.keys(h.f).reduce((r,n)=>(h.f[n](e,r,t),r),[])),h.u=e=>"static/js/async/"+(({166:"xmarkdown-deps",350:"web-core-template-loader-thread",724:"web-elements",778:"legacy-wasm-js",894:"web-core-main-chunk",97:"web-core-worker-chunk"})[e]||e)+"."+({166:"3ea5672b2c",257:"4d55bd5ce8",350:"4a49f8a286",503:"cf61731bba",724:"43d1e29387",778:"bacc8b5564",894:"7fe9af852c",97:"c315fd6753"})[e]+".js",h.miniCssF=e=>""+e+".css",h.g=(()=>{if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}})(),h.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),o={},h.l=function(e,t,r,n,a){if(o[e])return void o[e].push(t);if(void 0!==r)for(var i,s,l=document.getElementsByTagName("script"),d=0;d<l.length;d++){var u=l[d];if(u.getAttribute("src")==e||u.getAttribute("data-rspack")=="@byted-doubao-apps/web-sdk-debugger-app:"+r){i=u;break}}i||(s=!0,(i=document.createElement("script")).timeout=120,h.nc&&i.setAttribute("nonce",h.nc),i.setAttribute("data-rspack","@byted-doubao-apps/web-sdk-debugger-app:"+r),a&&i.setAttribute("fetchpriority",a),i.src=e),o[e]=[t];var c=function(t,r){i.onerror=i.onload=null,clearTimeout(p);var n=o[e];if(delete o[e],i.parentNode&&i.parentNode.removeChild(i),n&&n.forEach(function(e){return e(r)}),t)return t(r)},p=setTimeout(c.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=c.bind(null,i.onerror),i.onload=c.bind(null,i.onload),s&&document.head.appendChild(i)},h.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},l=[],h.O=(e,t,r,n)=>{if(t){n=n||0;for(var a=l.length;a>0&&l[a-1][2]>n;a--)l[a]=l[a-1];l[a]=[t,r,n];return}for(var i=1/0,a=0;a<l.length;a++){for(var[t,r,n]=l[a],s=!0,o=0;o<t.length;o++)(!1&n||i>=n)&&Object.keys(h.O).every(e=>h.O[e](t[o]))?t.splice(o--,1):(s=!1,n<i&&(i=n));if(s){l.splice(a--,1);var d=r();void 0!==d&&(e=d)}}return e},h.p="/",h.j="410",h.b=document.baseURI||self.location.href,d={410:0},h.f.j=function(e,t,r){var n=h.o(d,e)?d[e]:void 0;if(0!==n)if(n)t.push(n[2]);else{var a=new Promise((t,r)=>n=d[e]=[t,r]);t.push(n[2]=a);var i=h.p+h.u(e),s=Error();h.l(i,function(t){if(h.o(d,e)&&(0!==(n=d[e])&&(d[e]=void 0),n)){var r=t&&("load"===t.type?"missing":t.type),a=t&&t.target&&t.target.src;s.message="Loading chunk "+e+" failed.\n("+r+": "+a+")",s.name="ChunkLoadError",s.type=r,s.request=a,n[1](s)}},"chunk-"+e,e,r)}},h.O.j=e=>0===d[e],u=(e,t)=>{var r,n,[a,i,s]=t,o=0;if(a.some(e=>0!==d[e])){for(r in i)h.o(i,r)&&(h.m[r]=i[r]);if(s)var l=s(h)}for(e&&e(t);o<a.length;o++)n=a[o],h.o(d,n)&&d[n]&&d[n][0](),d[n]=0;return h.O(l)},(c=globalThis.rspackChunk_byted_doubao_apps_web_sdk_debugger_app||=[]).forEach(u.bind(null,0)),c.push=u.bind(null,c.push.bind(c));var g=h.O(void 0,["493","783","682","670"],()=>h(51441));g=h.O(g)})();
|