@doubao-dev/cli 0.0.19 → 0.0.20
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/2514.js +8 -8
- package/dist/2932.js +1 -1
- package/dist/318.js +1 -1
- package/dist/3494.js +284 -0
- package/dist/{1122.js.LICENSE.txt → 3494.js.LICENSE.txt} +6 -0
- package/dist/4931.js +1 -1
- package/dist/7410.js +1 -1
- package/dist/{1664.js → 8713.js} +3 -3
- package/dist/@byted-doubao-apps/create.js +1 -1
- 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/README.md +0 -2
- package/dist/@byted-doubao-apps/template-empty/package.json +3 -3
- package/dist/@byted-doubao-apps/template-starter/README.md +1 -1
- 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/@lynx-js/web-core-canary.js +2 -13
- package/dist/@lynx-js/web-core-canary~1.js +2 -0
- package/dist/app.js +1 -1
- package/dist/assets/web-sdk-debugger/chrome-devtools/entrypoints/devtools_app/devtools_app.js +9 -7
- package/dist/assets/web-sdk-debugger/chrome-devtools/panels/wsd-debug/WsdDebug.js +9 -7
- package/dist/assets/web-sdk-debugger/chrome-devtools/panels/wsd-debug/WsdDebugMeta.js +79 -77
- package/dist/assets/web-sdk-debugger/index.html +1 -1
- package/dist/assets/web-sdk-debugger/static/css/index.9952f4197c.css +1 -0
- package/dist/assets/web-sdk-debugger/static/js/{741.ece428827e.js → 48.8c158322ee.js} +60 -67
- package/dist/assets/web-sdk-debugger/static/js/48.8c158322ee.js.LICENSE.txt +5 -0
- package/dist/assets/web-sdk-debugger/static/js/async/257.4d55bd5ce8.js +1 -0
- package/dist/assets/web-sdk-debugger/static/js/async/{web-core-template-loader-thread.f9f3ef68b1.js → web-core-template-loader-thread.20d5b2a451.js} +2 -2
- package/dist/assets/web-sdk-debugger/static/js/async/{web-core-worker-chunk.002a4f7b9d.js → web-core-worker-chunk.71b9323071.js} +1 -1
- package/dist/assets/web-sdk-debugger/static/js/index.e5bc5f1bbd.js +26 -0
- package/dist/assets/web-sdk-debugger/static/js/{lib-polyfill.8cf763c414.js → lib-polyfill.4f00df8f2a.js} +1 -1
- 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/auth.js +1 -1
- package/dist/browser.js +1 -1
- package/dist/csstree.esm.js +12 -0
- package/dist/dbx-demo.js +1 -1
- package/dist/dbx.js +1 -1
- package/dist/demo-server.js +1 -1
- package/dist/dev-config.js +1 -1
- package/dist/dev-service-client.js +6 -6
- package/dist/dev-shell.js +1 -1
- package/dist/dev.js +7 -7
- package/dist/eval.js +1 -1
- package/dist/gen-explore.js +1 -1
- package/dist/gen-trajectory.js +1 -1
- package/dist/get.js +1 -1
- package/dist/init.js +2 -2
- package/dist/ink.js +1 -1
- package/dist/json-file.js +1 -1
- package/dist/login.js +1 -1
- package/dist/main.js +1 -1
- package/dist/manifest-mcp-config.js +1 -1
- package/dist/ora.js +1 -1
- package/dist/portal.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 +1 -1
- package/dist/sandbox.js +1 -1
- package/dist/sdk.js +67 -133
- package/dist/sdk~1.js +67 -133
- package/dist/server.js +1 -1
- package/dist/shared.js +1 -1
- package/dist/simulator-client.js +1 -1
- package/dist/skill.js +1 -1
- package/dist/skills~1.js +1 -1
- package/dist/static/assets/web-view-proxy-page-client.js +1 -0
- package/dist/static/assets/web-view-proxy-service-worker.js +1 -0
- package/dist/status.js +1 -1
- package/dist/status~1.js +1 -1
- package/dist/stop.js +1 -1
- package/dist/update.js +1 -1
- package/dist/upgrade.js +1 -1
- package/dist/upload.js +1 -1
- package/dist/validate.js +1 -1
- package/dist/workspace.js +1 -1
- package/dist/yaml.js +1 -1
- package/package.json +2 -2
- package/skills/doubao-agentic-service-development/references/dev-debug.md +6 -6
- package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/01-/345/237/272/347/241/200.md +105 -25
- package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/02-/347/263/273/347/273/237.md +118 -6
- package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/06-/344/272/244/344/272/222.md +18 -8
- package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/quick-reference.md +3 -3
- package/skills/doubao-agentic-service-development/references/frontend/examples/page-widget-basics.md +2 -3
- package/skills/doubao-agentic-service-development/references/frontend/guides/component-development.md +2 -1
- package/skills/doubao-agentic-service-development/references/frontend/guides/debugger-mcp.md +7 -1
- package/skills/doubao-agentic-service-development/references/frontend/rules/dos-and-donts.md +4 -7
- package/skills/doubao-agentic-service-development/references/frontend-dev.md +0 -1
- package/skills/doubao-agentic-service-development/references/manifest-guide.md +5 -4
- package/skills/doubao-agentic-service-development/references/mcp-protocol.md +4 -3
- package/dist/1122.js +0 -277
- package/dist/assets/web-sdk-debugger/static/css/index.fe34ed7927.css +0 -1
- package/dist/assets/web-sdk-debugger/static/js/index.da81c37197.js +0 -26
- package/dist/push-page.js +0 -1
- package/dist/push-widget.js +0 -1
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
(()=>{"use strict";var e,t,r,n,a,i,s,o,l,d,u,c,p={14061(e,t,r){let n,a;r(15254);var i=r(63159);function s(e){return"object"==typeof e&&null!==e}function o(e){return s(e.web)&&"string"==typeof e.web.entry}function l(e){return"widgetId"in e?e.widgetId:e.id}function d(e){let t=new Map;for(let r of e)for(let e of function(e){let t=[l(e)];return"path"in e&&"string"==typeof e.path&&t.push(e.path),t.filter(Boolean)}(r))t.has(e)||t.set(e,r);return t}r(52205),r(40768),r(76235),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(14104),r(42949),r(18723);class u{raw;appEntry;pageEntries;pageEntryMap;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(o),this.pageEntryMap=d(this.pageEntries),this.widgetEntries=e.widgets.filter(o),this.widgetEntryMap=d(this.widgetEntries)}get appId(){return"string"==typeof this.raw.appId?this.raw.appId:void 0}get name(){return this.raw.applet.name}get iconSrc(){let e=this.raw.applet.icons;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"])}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?this.pageEntryMap.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 c(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(!s(a))throw Error("Invalid Web manifest: expected a JSON object");return new u(a)}function p(e,t,r){var n;let a="item"in t?t.item:t,i="web"in a&&s(a.web)&&"string"==typeof a.web.entry?function(e){if(s(e.web)&&"string"==typeof e.web.entry)return e.web.entry;throw Error(`No Web entry configured for manifest entry: ${l(e)}`)}(a):a.entry,o=new URL(e,r??(null==(n=globalThis.location)?void 0:n.href)??"http://localhost/");return o.pathname.endsWith("/web/manifest.json")?o.pathname=o.pathname.slice(0,-17):o.pathname.endsWith("/base/manifest.json")?o.pathname=o.pathname.slice(0,-18):o.pathname=o.pathname.replace(/\/[^/]*$/,"/"),o.search="",o.hash="",new URL(i,o).toString()}function m(){var e;return(null==(e=globalThis.location)?void 0:e.href)??"http://localhost/"}function h(e){return new URL(e,m()).toString()}class g{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=h(await this.getManifestUrl(e)),n=this.packages.get(r);if(n&&!t.forceReload)return n;let a=c(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(h(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:function(e,t){if(!t)return e;let r=new URL(e,m());return r.searchParams.set("__doubao_resource_reload",t),r.toString()}(p(r.manifestUrl,n),this.resourceUrlVersion)}}}let f=new g,v={mode:"inline"};class y extends Error{errNo;errMsg;constructor(e,t,r=e){super(e),this.errNo=t,this.errMsg=r,Object.setPrototypeOf(this,new.target.prototype),this.name="BridgeAPIError"}}function _(e){return s(e)&&"call"===e.type&&"string"==typeof e.name&&"number"==typeof e.callbackId}function b(e,t){return{type:"callback",callbackId:e.callbackId,params:{code:1,data:t}}}function w(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 S(e){return e instanceof Error?e.message:String(e)}function x(e,t){return t instanceof y?w(e,t.message,t.errNo,t.errMsg):w(e,S(t))}function I(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!_(e))return;let n=t[e.name];if(!n)return w(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=>x(e,t));return t??w(e,`API ${e.name} is not implemented in Doubao Web SDK`)}catch(t){return x(e,t)}}function E(){return null==n?void 0:n.getPackageInfo()}function C(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(67548),r(70954),r(98803),r(79162),r(15385),r(39342),r(69152),r(61955),r(82689),r(84847),r(16285),r(20602),r(33307),r(94341),r(7270),r(44997),r(50364),r(79780),r(80372),r(72498),r(37928),r(25597),r(92321);class k{registry=new Map;eventSources=new Map;eventSourceCleanups=new Map;eventSourceRetainCounts=new Map;eventControllers=new Set;handlers={};constructor(e){e&&this.registerMany(e)}register(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!r.override&&this.registry.has(e))throw Error(`Bridge API handler ${e} is already registered`);let 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)}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 N(this,e)}fork(){let e=new k(this.getRegistrations());return e.registerEventSources(this.getEventSources()),e}getRegistrations(){return Object.fromEntries(this.registry)}getEventSources(){return Object.fromEntries(this.eventSources)}attachEventController(e){return this.eventControllers.add(e),()=>{this.eventControllers.delete(e)}}retainEventSource(e){let t=this.eventSourceRetainCounts.get(e)??0;if(this.eventSourceRetainCounts.set(e,t+1),t>0)return;let r=this.eventSources.get(e);r&&this.startEventSource(e,r)}releaseEventSource(e){let t=this.eventSourceRetainCounts.get(e)??0;if(t<=1){this.eventSourceRetainCounts.delete(e),this.stopEventSource(e);return}this.eventSourceRetainCounts.set(e,t-1)}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 N{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 T=new k;function M(){return(navigator.language||"zh-CN").replace("-","_")}function R(){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 A(){return"u"<typeof DoubaoAppsSDKVersion?void 0:DoubaoAppsSDKVersion}function P(){return navigator.userAgentData}function j(){var e;let t=null==(e=P())?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 L(){var e,t;let r=null==(e=P())?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 D(){var e;let t=navigator.userAgent??"",r=navigator.platform??"",n=(null==(e=P())?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 O(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:E();return{appId:(null==e?void 0:e.appId)??"",name:(null==e?void 0:e.name)??"",iconSrc:null==e?void 0:e.iconSrc}}function U(){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 q(){return D().platform}function $(){var e,t,r,n,a;let i=navigator.userAgent??"",s=q();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 B(){return{isConnected:!0,networkType:"unknown",hasSystemProxy:!1,weakNet:!1}}function F(){let e,t=D(),r=navigator.platform||q();return{abi:r,deviceAbi:r,benchmarkLevel:-1,brand:t.brand,model:function(){let e=navigator.userAgent??"",t=q();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?D().brand:"mac"===t||"windows"===t||"linux"===t?navigator.platform||D().brand:j()}(),system:function(){let e=q(),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=L(),n=j();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 W(){let e=F(),t=U(),r=t.windowWidth>t.windowHeight;return{os:e.platform,osVersion:$(),deviceBrand:e.brand,deviceModel:e.model,deviceType:e.model,channel:"debug",screenOrientation:+!!r,isLandscape:+!!r,abi:e.abi}}function H(){let e=U(),t=F();return{...e,brand:t.brand,model:t.model,language:M(),version:L(),system:t.system,platform:t.platform,SDKVersion:A(),theme:R(),benchmarkLevel:-1,enableDebug:!0,deviceOrientation:e.windowWidth>e.windowHeight?"landscape":"portrait",abi:t.abi}}function z(){let e=U();return{bluetoothEnabled:!1,locationEnabled:!0,wifiEnabled:B().isConnected,deviceOrientation:e.windowWidth>e.windowHeight?"landscape":"portrait"}}function V(){let e=B();return{networkType:e.networkType,signalStrength:e.signalStrength,hasSystemProxy:e.hasSystemProxy??!1,weakNet:e.weakNet??!1}}function G(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:E();return{SDKVersion:A(),enableDebug:!0,host:{appId:O(e).appId},language:M(),version:L(),theme:R()}}function J(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:E();return{miniProgram:{appId:O(e).appId,envVersion:"develop",version:(null==e?void 0:e.versionName)??""}}}function K(e){return null==e?void 0:e.packageInfo}function X(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 Q(e,t){let r=t instanceof Error?t.message:String(t);return`${e} failed: ${r}`}async function Z(e){let t=X("setClipboardData","writeText");try{await t.writeText(e)}catch(e){throw Error(Q("setClipboardData",e))}}async function Y(){let e=X("getClipboardData","readText");try{let t=await e.readText();if("string"==typeof t)return t}catch(e){throw Error(Q("getClipboardData",e))}throw Error("getClipboardData failed: clipboard did not return text")}function ee(){return{pages:(null==n?void 0:n.getCurrentPages())??[]}}T.handlers,r(46455);let et="doubao-web-sdk:storage:";function er(e){return`${et}${e}`}function en(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 ea(e){if(ei(e)>1048576)throw Error("data size must be less than or equal to 1048576 bytes")}function ei(e){return new TextEncoder().encode(e).byteLength}function es(e){return Object.values(e).reduce((e,t)=>e+ei(t),0)}function eo(e){if(e>0xa00000)throw new y("total storage size exceeded",1600002)}function el(e){let t={};for(let r=0;r<e.length;r+=1){let n=e.key(r);(null==n?void 0:n.startsWith(et))&&(t[n.slice(et.length)]=e.getItem(n)??"")}return t}function ed(e,t){if(!s(e))return;let r=e[t];return"string"==typeof r&&r.length>0?r:void 0}function eu(e){if(!s(e)||!s(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 ec(e){let t=eu(e),r=(null==t?void 0:t.appId)??ed(e,"appName")??"unknown-app",n=ed(e,"userId")??ed(e,"userID")??"anonymous";return`${encodeURIComponent(r)}:${encodeURIComponent(n)}`}function ep(){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 em(e){return`doubao-web-sdk:file-system:${encodeURIComponent(e)}`}function eh(e,t){var r;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:ec(e);return{fileSystemNamespace:n,fileSystemSnapshot:function(e){let t=localStorage.getItem(em(e));if(!t)return ep();try{let e=JSON.parse(t);if(s(e)&&s(e.entries))return e}catch{}return ep()}(n),apiResults:(r=eu(e),(t??T).getSyncResults({apiRegistry:t,globalProps:e,packageInfo:r})),storageSnapshot:el(localStorage),supportedAPIs:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:T;return e.getSupportedNames({apiRegistry:e})}(t)}}r(21301);let eg={"doubao.getClipboardData":async e=>b(e,{data:await Y()}),"doubao.setClipboardData":async e=>{let{data:t}=function(e){if(!s(e)||"string"!=typeof e.data)throw Error("data must be a string");return{data:e.data}}(e.params);return await Z(t),b(e,{})},"applet.subscribeEvent":(e,t)=>{let r=s(e.params)&&"string"==typeof e.params.eventName?e.params.eventName:"";if(r){var n;null==t||null==(n=t.events)||n.subscribe(r)}return b(e,{})},"applet.unsubscribeEvent":(e,t)=>{let r=s(e.params)&&"string"==typeof e.params.eventName?e.params.eventName:"";if(r){var n;null==t||null==(n=t.events)||n.unsubscribe(r)}return b(e,{})},"doubao.getCurrentPages":{handler:e=>b(e,ee()),syncResult:ee},"doubao.navigateTo":e=>{var t;return(t=e.params,null==n||n.navigateTo(t),n)?b(e,{}):w(e,"No active Runtime to navigate")},"doubao.redirectTo":e=>{var t;return(t=e.params,null==n||n.redirectTo(t),n)?b(e,{}):w(e,"No active Runtime to redirect")},"doubao.reLaunch":e=>{var t;return(t=e.params,null==n||n.reLaunch(t),n)?b(e,{}):w(e,"No active Runtime to relaunch")},"doubao.navigateBack":e=>{var t;return(t=e.params??{},null==n||n.navigateBack(t),n)?b(e,{}):w(e,"No active Runtime to navigate back")},"doubao.exitApp":e=>(null==n||n.exitApp(),n)?b(e,{}):w(e,"No active Runtime to exit app"),"doubao.close":e=>{var t;return(t=e.params??{},null==n||n.close(t),n)?b(e,{}):w(e,"No active Runtime to close page")},"doubao.setStorage":e=>{var t;let r,n,{key:a,data:i}=e.params,s=(t=el(localStorage),r=en(a),ea(i),n=Object.prototype.hasOwnProperty.call(t,r)?t[r]:void 0,eo(es(t)-(void 0===n?0:ei(n))+ei(i)),r);return localStorage.setItem(er(s),i),b(e,{})},"doubao.getStorage":e=>{let{key:t}=e.params;return b(e,{data:el(localStorage)[en(t)]})},"doubao.removeStorage":e=>{let{key:t}=e.params,r=en(t);return localStorage.removeItem(er(r)),b(e,{})},"doubao.clearStorage":e=>{for(let e of Object.keys(el(localStorage)))localStorage.removeItem(er(e));return b(e,{})},"doubao.getStorageInfo":e=>{var t;return b(e,{keys:Object.keys(t=el(localStorage)),currentSize:Math.ceil(es(t)/1024),limitSize:10240})},"doubao.__webSyncBridgePersist":(e,t)=>{var r,n,a;let i=s(r=e.params)&&s(r.storageSnapshot)?r.storageSnapshot:void 0,o=s(n=e.params)&&"string"==typeof n.fileSystemNamespace?n.fileSystemNamespace:void 0,l=null==t?void 0:t.fileSystemNamespace,d=s(a=e.params)&&s(a.fileSystemSnapshot)?a.fileSystemSnapshot:void 0;return i&&function(e){let t=[];for(let[t,r]of Object.entries(e))en(t),ea(r);eo(es(e));for(let e=0;e<localStorage.length;e+=1){let r=localStorage.key(e);(null==r?void 0:r.startsWith(et))&&t.push(r)}for(let e of t)localStorage.removeItem(e);for(let[t,r]of Object.entries(e))localStorage.setItem(er(t),r)}(i),l&&o===l&&d&&localStorage.setItem(em(l),JSON.stringify(d)),b(e,{})},"doubao.authorize":{handler:e=>b(e,{}),syncResult:{}},"doubao.canIUse":{handler:(e,t)=>{let{schema:r}=e.params;return b(e,{result:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:T;return t.canIUse(e,{apiRegistry:t})}(r,null==t?void 0:t.apiRegistry)})}},"doubao.getAccountInfo":{handler:e=>b(e,J()),syncResult:e=>J(K(e))},"doubao.getPackageInfo":{handler:e=>b(e,O()),syncResult:e=>O(K(e))},"doubao.getAppBaseInfo":{handler:e=>b(e,G()),syncResult:e=>G(K(e))},"doubao.getMenuButtonBoundingClientRect":{handler:(e,t)=>b(e,C(null==t?void 0:t.globalProps)),syncResult:e=>C(null==e?void 0:e.globalProps)},"doubao.getSystemInfo":{handler:e=>b(e,H()),syncResult:H},"doubao.getSystemSetting":{handler:e=>b(e,z()),syncResult:z},"doubao.getWindowInfo":{handler:e=>b(e,U()),syncResult:U},"doubao.getDeviceInfo":{handler:e=>b(e,F()),syncResult:F},"doubao.getNetworkType":{handler:e=>b(e,V()),syncResult:V}};function ef(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.apiRegistry??T;return(r,n,a)=>{if(("AppletJSModule"!==a||"log"!==r)&&"AppletBridgeModule"===a&&"postMessage"===r)return I(n,t.handlers,{...e,apiRegistry:t})}}function ev(e){if(!e.resourceUrl)throw Error("Container.render requires a resourceUrl");return e.resourceUrl}function ey(e){return e.containerType??"PAGE"}function e_(e){return"WIDGET"===e?"content":"fill"}function eb(){return"0.0.42-rc.10"}function ew(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}T.registerMany(eg,{override:!0}),T.registerEventSources({onThemeChange:e=>{let t=matchMedia("(prefers-color-scheme: dark)"),r=()=>e({appTheme:matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"});return t.addEventListener("change",r),()=>t.removeEventListener("change",r)}},{override:!0});class eS{container;options;sandboxUrl;targetOrigin;bridgeEvents=null;connected=!1;failed=!1;handshakeTimer=null;loadCount=0;port=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=r.href,this.targetOrigin=r.origin}get element(){return this.view}render(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"));let r=ey(e),n=new URL(ev(e),document.baseURI).href,a=e.initData??{},i={...W(),...e.globalProps??{}},s=eh(i,this.options.apiRegistry,this.options.fileSystemNamespace);this.renderMessage={type:"render",resourceUrl:n,containerType:r,initData:a,globalProps:i,syncBridgeData:s};let o=document.createElement("iframe");o.className=this.options.className??"doubao-web-container-view",o.dataset.containerType=r,o.dataset.webSizing=e_(r),o.referrerPolicy="no-referrer",o.title="Doubao app content",o.sandbox.add("allow-scripts","allow-same-origin"),o.setAttribute("allow","picture-in-picture 'none'"),o.src=this.sandboxUrl,o.style.display="APP"===r||"TOOL"===r?"none":"block",o.style.border="0",o.style.width="100%",o.style.height="WIDGET"===r?"0px":"100%",o.addEventListener("load",()=>this.handleLoad()),this.view=o,this.container.replaceChildren(o);let l=this.options.apiRegistry??T;return this.bridgeEvents=l.createEventController((e,t)=>this.postOrFail({type:"global-event",name:e,params:t})),o}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.renderMessage=null,this.connected=!1,this.failed=!1,this.loadCount=0,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})}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,ew(e)),e}handleLoad(){if(this.failed||!this.view)return;if(this.loadCount+=1,this.loadCount>1)return void this.fail(Error("iframe navigated after the sandbox runtime loaded"));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:eb()};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||a.sdkVersion!==eb()?void this.fail(Error("iframe sandbox protocol or SDK 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||"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=ef({apiRegistry:this.options.apiRegistry??T,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});try{var n,a;t=await ((null==(n=(a=this.options).nativeModulesCallHandler)?void 0:n.call(a,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:S(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]:ew(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}}r(84552);var ex=r(51238);r(74678),r(55910),r(76691),r(72919);let eI="embed-webview",eE="__channel_ack__",eC=new WeakMap,ek=e=>({url:e});function eN(e){if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}}function eT(e){return"string"==typeof e?e:JSON.stringify(e??{})}let eM=globalThis.HTMLElement??class{};"object"!=typeof customElements||customElements.get(eI)||customElements.define(eI,class e extends eM{static observedAttributes=["src"];#e=null;#t=null;#r=!1;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}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=s(e)?e.data:void 0;this.#s({type:"event",name:"message",params:{data:t},timestamp:Date.now()})}eval(e){let t=s(e)&&"string"==typeof e.func?e.func:"";if(t)try{var r;null==(r=this.#o())||r.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.#l),t.addEventListener("error",this.#d),e.replaceChildren(t),this.#e=t,window.addEventListener("message",this.#u),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=ek(r);(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}#o(){try{var e;let t=(null==(e=this.#e)?void 0:e.contentWindow)??null;return null==t||t.document,t}catch{return null}}#l=()=>{this.#c(),this.#p(),this.#m(),this.#h("load",{url:this.getAttribute("src")??""})};#d=()=>{this.#h("error",{errorMsg:`Failed to load ${this.getAttribute("src")??""}`,errorCode:-1})};#u=e=>{if(!this.#e||e.source!==this.#e.contentWindow||e.data===eE)return;let t=eN(e.data);this.#g(t)||this.#f(eT(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!==eE&&this.#g(eN(e.data))},this.#t=r.port1,t.postMessage("__channel_init__","*",[r.port2])}#p(){let e=this.#o();e&&!e.AppletBridgeModule&&(e.AppletBridgeModule={postMessage:e=>(this.#g(eN(e)),Promise.resolve({})),postMessageSync:e=>{let t=eN(e);return _(t)?w(t,"Sync AppletBridgeModule APIs are not supported in Doubao Web SDK web-view"):void 0}})}#m(){let e=this.#o();e&&this.#f(JSON.stringify({type:"__doubao_web_view_set_title__",title:e.document.title||""}))}#g(e){if(s(e)&&"event"===e.type)return"__bridge_ready__"===e.name;if(!_(e))return!1;if("doubao.postMessage"===e.name){let t=s(e.params)?e.params.data:void 0;return this.#f(eT(t)),this.#s(b(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=eC.get(t);if(e)return e}let e=t.parentNode;t=e instanceof ShadowRoot?e.host:e}}(this);if(!t)return void this.#s(w(e,`API ${e.name} is not available in this web-view host`));let r=await t(e);this.#s(r??w(e,`API ${e.name} is not implemented in Doubao Web SDK`))}#s(e){var t;let r=JSON.stringify(e);if(this.#t)return void this.#t.postMessage(r);let n=this.#o();null==n||null==(t=n.onWebViewMessage)||t.call(n,r)}#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}))}});let eR="AppletBridgeModule",eA="postMessage";function eP(e,t,r){t===eA&&(null==r?void 0:r.type)==="callback"&&"callbackId"in r&&"function"==typeof e.sendGlobalEvent&&e.sendGlobalEvent("__APPLET_BRIDGE__",[r])}function ej(e,t,r){"function"==typeof e.sendGlobalEvent&&e.sendGlobalEvent("__APPLET_BRIDGE__",[{type:"event",name:t,params:r,timestamp:Date.now()}])}class eL{container;className;options;syncBridgeData;bridgeEvents=null;view=null;constructor(e,t){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.syncBridgeData=t}get element(){return this.view}render(e){var t,r,n,a,i,s,o;let l,d,u,c;this.clear();let p=document.createElement("lynx-view"),m=ey(e),h=e_(m);p.className=this.className,p.dataset.containerType=m,p.dataset.webSizing=h,p.style.display="APP"===m||"TOOL"===m?"none":"block",p.style.width="100%",p.style.height="content"===h?"auto":"100%","content"===h&&p.setAttribute("height","auto"),p.url=ev(e),p.initData=e.initData??{};let g={...W(),...e.globalProps??{}},f=this.syncBridgeData??eh(g,this.options.apiRegistry,this.options.fileSystemNamespace);l=new URL("./__doubao_web_sdk_native_modules/",(null==(t=globalThis.document)?void 0:t.baseURI)??(null==(r=globalThis.location)?void 0:r.href)??"http://localhost/").href,p.nativeModulesMap={AppletBridgeModule:(n=new URL("applet-bridge-module.js",l).href,(u=new URLSearchParams((d=new URL(n)).hash.slice(1))).set("__doubao_sync_bridge",JSON.stringify({...f,fileSystemSnapshot:ep()})),d.hash=u.toString(),d.href),AppletJSModule:new URL("applet-js-module.js",l).href},(0,ex.B)(p),p.globalProps={...g,__DOUBAO_WEB_SDK_SYNC_BRIDGE__:f};let v=this.options.apiRegistry??T;return this.bridgeEvents=v.createEventController((e,t)=>ej(p,e,t)),a=this.options,i=this.bridgeEvents,s=f.fileSystemNamespace,c=ef({apiRegistry:a.apiRegistry,emitEvent:(e,t)=>i.emit(e,t),events:i,fileSystemNamespace:s,globalProps:g}),p.onNativeModulesCall=async(e,t,r)=>{var n,i,s,o;let l=r===eR&&e===eA&&"callback"===(s=t).type&&"callbackId"in s;if(r===eR&&e===eA&&"event"===(o=t).type&&"__bridge_ready__"===o.name&&(null==(n=a.onReady)||n.call(a)),l&&"TOOL"!==m)return eP(p,e,t),t;try{let n=await (null==(i=a.nativeModulesCallHandler)?void 0:i.call(a,e,t,r,{containerType:m,element:p}));if(l){if(void 0!==n)return n;return eP(p,e,t),t}let s=void 0===n?await c(e,t,r):n;return eP(p,e,s),s}catch(n){let r=_(t)?w(t,S(n)):void 0;return eP(p,e,r),r}},o=e=>I(e,v.handlers,{apiRegistry:v,globalProps:g}),eC.set(p,o),p.transformVW=!0,p.transformVH="content"!==h,p.transformREM=!0,p.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=p,this.container.replaceChildren(p),p}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]:{},r=this.view;r&&ej(r,e,t)}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)}}class eD{options;adapter=null;constructor(e){if(!e.container)throw Error("Container requires a container element");this.options=e}get element(){var e;return(null==(e=this.adapter)?void 0:e.element)??null}render(e){var t;null==(t=this.adapter)||t.clear();let r=v;this.adapter="iframe"===r.mode?new eS(this.options,r.url):new eL(this.options);try{return this.adapter.render(e)}catch(e){throw this.adapter.clear(),this.adapter=null,e}}clear(){var e;null==(e=this.adapter)||e.clear(),this.adapter=null}sendEvent(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};null==(t=this.adapter)||t.sendEvent(e,r)}sendGlobalEvent(e,t){var r;null==(r=this.adapter)||r.sendGlobalEvent(e,t)}reload(){var e;null==(e=this.adapter)||e.reload()}}let eO=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2
|
+
<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"/>
|
|
3
|
+
</svg>`,eU=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
4
|
+
<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"/>
|
|
5
|
+
</svg>`,eq="doubao-apps-page",e$={body:`${eq}__body`,capsule:`${eq}__capsule`,capsuleAction:`${eq}__capsule-action`,capsuleCloseIcon:`${eq}__capsule-close-icon`,capsuleMoreIcon:`${eq}__capsule-more-icon`,root:eq};class eB{host;options;container=null;root=null;constructor(e){if(!e.container)throw Error("Page requires a container element");this.host=e.container,this.options=e}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=e$.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=e$.body,n.append(a,this.createCapsule()),this.host.replaceChildren(n),this.root=n,this.container=new eD({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),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(e$.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(e$.capsuleMoreIcon,"More",eO,"doubao:page-capsule-more")}createCapsuleCloseIcon(){return this.createCapsuleAction(e$.capsuleCloseIcon,"Close app",eU,"doubao:page-capsule-close")}createCapsule(){let e=document.createElement("div");return e.className=e$.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 eF=/\{\{\s*([^{}\s]+)\s*\}\}/g;function eW(e){return"string"==typeof e?e:JSON.stringify(e)}function eH(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(eF),e=>e[1])),a=(r=e.url,r.replace(eF,(e,r)=>{if(!Object.prototype.hasOwnProperty.call(t,r))return e;let n=eW(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=eW(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(eF))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 ez(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`${eG(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))?`${eG(a,e)}://${e}`:e}function eV(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=String(e??"").trim();if(!r)return;let n=ez(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 eG(e,t){return"function"==typeof e?e(t):e}function eJ(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}var eK=r(70851);let eX="doubao-apps-widget",eQ={body:`${eX}__body`,header:`${eX}__header`,icon:`${eX}__icon`,root:eX,title:`${eX}__title`};class eZ{container;options;root=null;body=null;title=null;icon=null;runtimeContainer=null;renderToken=0;constructor(e){if(!e.container)throw Error("Widget requires a container element");this.container=e.container,this.options=e}get element(){var e;return(null==(e=this.runtimeContainer)?void 0:e.element)??null}async render(){this.clear();let e=this.renderToken,t=await f.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,eK.$)(eQ.root,this.options.className);let r=document.createElement("div");r.className=eQ.body;let n=null;if(2!==e.titleType){(n=document.createElement("header")).className=eQ.header,n.hidden="iframe"===v.mode;let e=document.createElement("img");e.alt="",e.className=eQ.icon,e.height=16,e.width=16;let r=document.createElement("div");r.className=eQ.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=new eD({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))}}r(84086),r(37891);let eY="onDestroy",e0="onShow";function e1(e){return e.path||e.id}function e2(e,t){e.style.display=t?"block":"none"}function e3(e,t){let r=function(e){let{pageId:t,viewData:r}=function(e){if(!e.trim())throw Error("route url must be a non-empty string");let[t,r=""]=e.trim().split("?");if(!t)throw Error("route url must include a page path");let n={};return new URLSearchParams(r).forEach((e,t)=>{n[t]=e}),{pageId:t,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 e4(e,t){return e&&"object"==typeof e?{packageInfo:t,...e}:{packageInfo:t}}function e5(e){return{appId:e.appId,name:e.name,iconSrc:e.iconSrc,versionName:e.versionName}}function e8(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e4(t,e5(e))}function e6(e){if(s(e))return{...e};if("string"!=typeof e)return{};try{let t=JSON.parse(e);return s(t)?t:{}}catch{return{}}}class e7{container;className;apiRegistry;nativeModulesCallHandler;onError;appGlobalProps;appInitData;runtimeHost;configuredFileSystemNamespace;cleanupBridgeController;cleanupEmptyState;emptyState;manifest;manifestUrl;pageCapsule;fileSystemNamespace;appRuntime=null;stack=[];pendingPageRoutes=[];nextPageIndex=0;constructor(e){if(!e.container)throw Error("Runtime requires a container element");if(this.container=e.container,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.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 t,r;this.container.append(this.emptyState);const e=null==(r=this.runtimeHost)||null==(t=r.mountRuntimeEmptyState)?void 0:t.call(r,this.emptyState);this.cleanupEmptyState="function"==typeof e?e:()=>{}}else this.cleanupEmptyState=()=>{};this.updateEmptyState(),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)})}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,t,r;let n,a,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},o=this.resolvePageEntry(i),l=p(this.manifestUrl,o),d=i.pageCapsule??this.pageCapsule,u=`page-${++this.nextPageIndex}`,c=(e=i,t=u,r=o,n=s(e.globalProps)?e6(e.globalProps.__VIEW_CONTEXT__):{},{...s(e.initData)?e6(e.initData.viewContext):{},...n,viewId:t,pageName:r.id,pageUrl:e1(r)}),m=((a=document.createElement("div")).className="doubao-runtime-page",a.style.display="block",a.style.width="100%",a.style.height="100%",a),h=null,g=new eB({apiRegistry:this.apiRegistry,className:this.className,container:m,fileSystemNamespace:this.fileSystemNamespace,nativeModulesCallHandler:this.nativeModulesCallHandler,onError:this.onError,onReady:()=>{h&&this.stack.includes(h)&&(h.isReady=!0,this.flushPageLifecycleEvents(h))}});void 0!==i.pageCapsule&&(this.pageCapsule=i.pageCapsule),this.ensureAppRuntime(),this.container.append(m),this.pendingPageRoutes.push(e1(o));try{let e,t,r=g.render({resourceUrl:l,initData:s(i.initData)?{...i.initData,viewContext:c}:{viewContext:c},globalProps:(e=null==d?void 0:d.statusBarHeight,t="number"==typeof e&&Number.isFinite(e)?{statusBarHeight:e}:{},s(i.globalProps)?{...i.globalProps,...t,__VIEW_CONTEXT__:c}:{...t,__VIEW_CONTEXT__:c}),pageCapsule:d}),n=this.getCurrentStackItem();return n&&(this.sendPageLifecycleEvent(n,"onHide"),e2(n.frame,!1)),h={id:u,pageId:o.id,route:e1(o),resourceUrl:l,entry:o,element:r,frame:m,isReady:!1,pendingLifecycleEvents:[],page:g},m.addEventListener("doubao:page-capsule-close",e=>{e.stopPropagation(),this.exitBridgeApp()}),this.stack.push(h),this.updateEmptyState(),this.sendPageLifecycleEvent(h,e0),this.sendAppLifecycleEvent("onPageOpened",{viewId:h.id}),this.toStackEntry(h)}catch(e){throw g.clear(),m.remove(),this.updateEmptyState(),e}finally{this.pendingPageRoutes.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()}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,eY),e.page.clear(),e.frame.remove();let n=this.getCurrentStackItem();return t&&n&&(e2(n.frame,!0),this.sendPageLifecycleEvent(n,e0)),this.updateEmptyState(),r}ensureAppRuntime(){let e;if(this.appRuntime||!this.manifest.appRuntimeEntry)return;let t=p(this.manifestUrl,this.manifest.appRuntimeEntry),r=((e=document.createElement("div")).className="doubao-runtime-app",e.hidden=!0,e.style.display="none",e),n=new eD({apiRegistry:this.apiRegistry,className:this.className,container:r,fileSystemNamespace:this.fileSystemNamespace,nativeModulesCallHandler:this.nativeModulesCallHandler,onError:this.onError,onReady:()=>{var e;(null==(e=this.appRuntime)?void 0:e.container)===n&&(this.appRuntime.isReady=!0,this.flushAppLifecycleEvents())}});this.container.append(r),this.appRuntime={container:n,frame:r,isReady:!1,pendingLifecycleEvents:[]};try{n.render({resourceUrl:t,containerType:"APP",initData:this.appInitData??{},globalProps:e8(this.manifest,this.appGlobalProps)}),this.sendAppLifecycleEvent("onForeground")}catch(e){throw this.appRuntime=null,n.clear(),r.remove(),e}}clearAppRuntime(){let e=this.appRuntime;(null==e?void 0:e.isReady)&&(this.sendAppLifecycleEvent("onBackground"),this.sendAppLifecycleEvent(eY)),null==e||e.container.clear(),null==e||e.frame.remove(),this.appRuntime=null}sendAppLifecycleEvent(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=this.appRuntime;if(r){if(!r.isReady)return void r.pendingLifecycleEvents.push({name:e,params:t});r.container.sendEvent(e,t)}}flushAppLifecycleEvents(){let e=this.appRuntime;if(null==e?void 0:e.isReady)for(let t of e.pendingLifecycleEvents.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 e3(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=>({route:e.route})),...this.pendingPageRoutes.map(e=>({route:e}))]}getPackageInfo(){return e5(this.manifest)}resolveFileSystemNamespace(){return this.configuredFileSystemNamespace?this.configuredFileSystemNamespace:ec(e4(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}}}var e9=r(75541),te=r(64865),tt=r(11855);function tr(e){let t=new Uint8Array(e),r="";for(let e=0;e<t.length;e+=32768)r+=String.fromCharCode(...t.subarray(e,e+32768));return btoa(r)}r(20303),r(99166),r(6106),r(22742),r(37553),r(62148),r(89055),r(12205),r(65850),r(65135),r(5876),r(94359),r(28016),r(38641),r(82247),r(11839),r(56109),r(63589),r(32037),r(31178);let tn="/__wsd_control_results";function ta(e){return"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=9999}function ti(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0}async function ts(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tn,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:fetch,n=await r(t,{body:JSON.stringify(e),headers:{"Content-Type":"application/json"},method:"POST"});if(!n.ok)throw Error(`Failed to report debugger control result: ${n.status}`)}let to="/__web_artifacts/base/manifest.json",tl="/app_developer";function td(e){return!e.debugHidden}function tu(e){return eJ(e)?eJ(e.viewData)?e:{...e,viewData:e}:{viewData:{}}}function tc(e){return"object"==typeof e&&null!==e}function tp(e){if("string"==typeof e&&e.trim())try{return JSON.parse(e)}catch{return}}function tm(e){if(eJ(e))return e;let t=tp(e);return eJ(t)?t:void 0}function th(e){if("string"==typeof e)return e;try{return JSON.stringify(e??{})}catch{return"{}"}}function tg(e){return e instanceof Error?e.message:String(e)}function tf(e,t){let r=e[t];return"string"==typeof r?r:""}function tv(e,t){let r=e[t];return"number"==typeof r&&Number.isFinite(r)?r:void 0}function ty(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 t_(e){let[t,...r]=e.trim().split(":"),n=t.replace(/_/g," ").trim().split(/\s+/).filter(Boolean).map(tb).join(" ");return 0===r.length?n||e:`${n}: ${r.join(":").trim()}`}function tb(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)}`}function tw(e,t){let r=t.trim();r&&!e.includes(r)&&e.push(r)}function tS(e){let t=[];return!function e(t,r,n){if(!(!tc(t)||n.has(t))){if(n.add(t),Array.isArray(t))return void t.forEach(t=>e(t,r,n));if(eJ(t))for(let[a,i]of Object.entries(t))"response_headers"===a.toLowerCase()&&function(e,t){if(eJ(e)){for(let[r,n]of Object.entries(e))if("x-tt-logid"===r.toLowerCase()&&"string"==typeof n)return void tw(t,n)}}(i,r),"log_ids"===a.toLowerCase()&&function(e,t){if("string"==typeof e)return tw(t,e);if(Array.isArray(e))for(let r of e)"string"==typeof r&&tw(t,r)}(i,r),e(i,r,n)}}(e,t,new WeakSet),t}function tx(e){let t=ez(String(e??tl).trim(),{addProtocolToBareHost:!0,allowRootRelative:!0,defaultProtocol:tI}).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 tI(e){return/^(localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|\[::1\])(?::|\/|$)/i.test(e)?"http":"https"}function tE(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 tC(e,t){return`${tx(e)}${"chat"===t?"/api/simulator/chat":"/api/simulator/tool/report"}`}r(12021),r(20789),r(62839),r(66876),r(78872),r(60972);var tk=r(75585);let tN=["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 tT(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,tk.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=eJ(c)?{...e.event&&!c.event?{event:e.event}:{},...c}:{event:e.event||"message",data:c},{eventType:m,payload:h}=function(e){var t;for(let t of tN){let r=e[t];if(eJ(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=eJ(h)?h:{},f=tv(p,"sequence")??(t.fallbackSeq+=1),v=e.id||tf(p,"id")||`evt_${f.toString().padStart(4,"0")}`,y=function(e,t,r){let n=tf(e,"request_id")||("ack"===r?tf(t,"request_id"):"");if("ack"===r&&!n)throw Error("Invalid simulator SSE ACK: missing request_id");return n||tf(e,"id")}(p,g,m),_=tf(p,"reply_message_id")||tf(g,"message_id")||t.replyMessageId;return{event_id:v,event_type:m,seq:f,request_id:y,query_message_id:tf(p,"query_message_id")||tf(g,"query_message_id"),reply_message_id:_,created_at_ms:tv(p,"timestamp_ms")??Date.now(),received_at_ms:Date.now(),trace:(d=eJ(p.trace)?p.trace:{},{trace_id:"string"==typeof(u=t.trace??{}).trace_id?u.trace_id:"string"==typeof d.trace_id?d.trace_id:tE("trace"),span_id:"string"==typeof d.span_id?d.span_id:tE("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:{...eJ(u.baggage)?u.baggage:{},...eJ(d.baggage)?d.baggage:{}}}),payload:(n=g,0===(o=Array.isArray(s=eJ(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 tM="x-tt-logid";class tR extends Error{responseDebug;constructor(e,t){super(e),this.responseDebug=t,this.name="SimulatorHttpError"}}function tA(e){return e.headers.get(tM)||void 0}function tP(e){let t={},r=tA(e);return r&&(t[tM]=r),t}function tj(e){return eJ(e.trace)?e.trace:{}}async function tL(e,t){let r=tA(t),n=tP(t),a=await t.text().catch(()=>""),i={status:t.status,status_text:t.statusText,...Object.keys(n).length>0?{response_headers:n}:{},...r?{log_ids:[r]}:{},...a?{response_text:a}:{}};return new tR(`${e}: ${t.status} ${t.statusText}`,i)}function tD(e){return e instanceof tR?e.responseDebug:void 0}function tO(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},a=arguments.length>4?arguments[4]:void 0,i=tj(e),s=Date.now();return{event_id:tE("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:tE("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??(eJ(i.baggage)?i.baggage:{})},payload:{event:t,category:"api",elapsed_ms:Date.now()-r,...n}}}async function tU(e){let t,{endpoint:r,fetcher:n,onEvent:a,request:i,signal:s}=e,o=Date.now(),l=tC(r,"chat");a(tO(i,"simulator_chat_fetch_started",o,{endpoint:"chat",phase:"request",request:i,request_json:th(i),url:l}));let d=setTimeout(()=>{a(tO(i,"simulator_chat_fetch_waiting_for_headers",o,{endpoint:"chat",phase:"wait",url:l,wait_ms:5e3}))},5e3);try{t=await (n??fetch)(l,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(i),signal:s})}catch(e){throw clearTimeout(d),a(tO(i,"simulator_chat_fetch_failed",o,{endpoint:"chat",phase:"error",url:l,error:tg(e)})),e}clearTimeout(d);let u=tA(t),c=tP(t),p=tj(i),m={...eJ(p.baggage)?p.baggage:{}};if(u&&(m[tM]=u,m.log_ids=[u]),a(tO(i,"simulator_chat_headers_received",o,{event:"simulator_chat_response_meta",endpoint:"chat",phase:"response",status:t.status,status_text:t.statusText,...u?{log_ids:[u]}:{},...Object.keys(c).length>0?{response_headers:c}:{}},m)),!t.ok){let e=await tL("Simulator query failed",t);throw a(tO(i,"simulator_chat_fetch_failed",o,{endpoint:"chat",phase:"error",error:e.message,...e.responseDebug},m)),e}if(!t.body)throw Error("Simulator query response has no SSE body");let h=0,g=!1,f=setTimeout(()=>{g||a(tO(i,"simulator_chat_sse_waiting_for_first_event",o,{endpoint:"chat",wait_ms:5e3},m))},5e3);try{await tT(t.body,e=>{h+=1,g||(g=!0,clearTimeout(f)),a(e)},{trace:{...p,baggage:m}})}catch(e){throw clearTimeout(f),a(tO(i,"simulator_chat_sse_read_failed",o,{endpoint:"chat",phase:"error",event_count:h,error:tg(e)},m)),e}clearTimeout(f)}async function tq(e){let{endpoint:t,fetcher:r,result:n,signal:a}=e,i=await (r??fetch)(tC(t,"tool-report"),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(n),signal:a});if(!i.ok)throw await tL("Simulator tool result failed",i);let s=await t$(i),o=tA(i);return{...s,...o?{response_headers:{...eJ(s.response_headers)?s.response_headers:{},[tM]:o},log_ids:[o]}:{}}}async function t$(e){let t=await e.text().catch(()=>"");if(!t.trim())return{};try{let e=JSON.parse(t);return eJ(e)?e:{response_body:e}}catch{return{response_text:t}}}let tB={label:"Request",tone:"request"},tF={label:"Response",tone:"response"},tW={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:tB,title:"Chat"},simulator_chat_fetch_waiting_for_headers:{title:"Chat Waiting"},simulator_chat_response_meta:{badge:tF,title:"Chat"},simulator_chat_fetch_failed:{badge:tF,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:tB,debugOnly:!0,title:"MCP Load"},local_mcp_tools_loaded:{badge:tF,debugOnly:!0,title:"MCP Load"},local_mcp_tools_load_failed:{badge:tF,title:"MCP Load Failed"},local_mcp_missing:{title:"MCP Missing"},local_mcp_call_started:{badge:tB,title:e=>`MCP Tool${e}`},local_mcp_call_succeeded:{badge:tF,title:e=>`MCP Tool${e}`},local_mcp_call_failed:{badge:tF,title:e=>`MCP Tool Failed${e}`},tool_result_report_started:{badge:tB,title:e=>`Report Tool Result${e}`},tool_result_report_response_received:{badge:tF,title:e=>`Report Tool Result${e}`},tool_result_report_failed:{badge:tF,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:tF,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:tB,debugOnly:!0,title:"Manifest Load"},simulator_manifest_loaded:{badge:tF,debugOnly:!0,title:"Manifest Load"},simulator_manifest_load_failed:{badge:tF,title:"Manifest Load Failed"},simulator_manifest_fetch_started:{badge:tB,debugOnly:!0,title:"Manifest Fetch"},simulator_manifest_fetch_succeeded:{badge:tF,debugOnly:!0,title:"Manifest Fetch"},simulator_manifest_fetch_failed:{badge:tF,title:"Manifest Fetch Failed"},simulator_manifest_missing:{title:"Manifest Missing"},simulator_skill_load_started:{badge:tB,debugOnly:!0,title:"Skill Load"},simulator_skill_loaded:{badge:tF,debugOnly:!0,title:"Skill Load"},simulator_skill_empty:{badge:tF,debugOnly:!0,title:"Skill Empty"},simulator_skill_load_failed:{badge:tF,title:"Skill Load Failed"},simulator_skill_fetch_started:{badge:tB,debugOnly:!0,title:"Skill Fetch"},simulator_skill_fetch_succeeded:{badge:tF,debugOnly:!0,title:"Skill Fetch"},simulator_skill_fetch_failed:{badge:tF,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 tH(e){try{return JSON.stringify(e??{})}catch{return""}}function tz(e){if(!eJ(e))return;let t=tV(e);return{category:t.category,...t.debugOnly?{debugOnly:!0}:{},detail:t.detail,...t.transportBadge?{leftBadges:[t.transportBadge]}:{},phase:t.phase,title:t.title}}function tV(e){var t,r;let n="string"==typeof e.event?e.event:"",a=tW[n],i=e.detail??e.data??e,s="string"==typeof e.title&&e.title?t_(e.title):function(e,t){var r;let n=null==(r=tW[e])?void 0:r.title;if("function"==typeof n){let e,r,a;return n((e="string"==typeof t.tool_name&&t.tool_name?t.tool_name:"",r="string"==typeof t.tool_call_id&&t.tool_call_id?t.tool_call_id:"",(a=e||r)?`: ${a}`:""))}return n||(e?t_(e):"Agent Trace Event")}(n,e),o="string"==typeof e.category&&e.category?ty(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="string"==typeof e.phase&&e.phase?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 tG(e){return e.blocks.some(e=>"card"===e.type&&"permission_apply"===e.card.card_type)}function tJ(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(tG);if(-1===r)return;let n=e[r];if(tG(n))for(let t=r-1;t>=0;t--){let r=e[t];if("user"===r.role&&r.text.trim())return{messageIds:[r.messageId,n.messageId],query:r.text.trim()}}}(r,t.grantingMessageId);return a?"streaming"===n?{status:"streaming"}:(e.removeSimulatorMessages(a.messageIds),{completion:t.noLogin?e.sendSimulatorQuery(a.query,{noLogin:!0}):e.sendSimulatorQuery(a.query),status:"started",target:a}):{status:"not_found"}}function tK(e){if(!eJ(e))return;let t=tf(e,"grantingName");if(t){var r;return{grantingName:t,permissionStatus:tf(e,"permissionStatus")||"pending",priorityLevel:"number"==typeof e.priorityLevel?e.priorityLevel:0,relatedData:tm(r=e.relatedData)??(eJ(r)?r:{}),required:!1!==e.required}}}function tX(e){let t=tm(e);if(!t)return;let r=Array.isArray(t.grantingList)?t.grantingList.map(tK).filter(e=>!!e):[];if(0!==r.length)return{cardStatus:tf(t,"cardStatus")||"unexpired",doubaoAppletIcon:tf(t,"doubaoAppletIcon"),doubaoAppletKey:tf(t,"doubaoAppletKey"),doubaoAppletName:tf(t,"doubaoAppletName")||"智能服务",doubaoAppletVersion:tf(t,"doubaoAppletVersion"),grantingList:r,raw:t}}function tQ(e){var t;switch(null==(t=e.grantingList[0])?void 0:t.grantingName){case"permission":return"权限申请";case"privacy":return"隐私协议提示";default:return"登录授权"}}r(66249);let tZ="miniapp_packet_10066";function tY(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,...n&&!e.requestId?{requestId:n}:{},...a&&!e.traceId?{traceId:a}:{}}:e):e:[...e,{messageId:t,...n?{requestId:n}:{},...a?{traceId:a}:{},role:"assistant",contentType:"mixed",text:"",blocks:[],status:"streaming",createdAtMs:r}]}function t0(e,t,r){return e.map(e=>e.messageId===t?r(e):e)}function t1(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 t2(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 t3(e){return"debug"===e.event_type?e.payload.data??e.payload:e.payload}function t4(e){let t=tf(e.payload,"tool_name")||tf(e.payload,"tool_call_id"),r=tf(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 t_(tf(e.payload,"title")||"Agent Trace");case"heartbeat":return"Heartbeat";default:return t_(e.event_type)}}function t5(e){let t=tf(e.payload,"category");if(t)return ty(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 t8(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 t6(e){return"u">typeof DOMException&&e instanceof DOMException?"AbortError"===e.name:e instanceof Error&&"AbortError"===e.name}function t7(e,t){if(eJ(e)&&"code"in e&&"message"in e)return e;let r=eJ(e)&&eJ(e.responseDebug)?e.responseDebug:void 0,n=tm(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||tg(e),retryable:!1,stage:t,...r?{details:{response:r,...n?{response_body:n}:{}}}:{}}}function t9(e,t){let r=eJ(e)?e:void 0,n=eJ(t)?t:void 0;if(r||n)return{...r,...n}}function re(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 rt(e,t,r){var n;let a=function(e){let t=eJ(e.card)?e.card:{},r=eJ(t.state)?t.state:{},n=tf(e,"card_id"),a=tf(r,"widget_id");if("update_state"!==tf(e,"op")||"miniapp_history_refresh"!==tf(t,"card_type")||"fixed_style"!==tf(r,"refresh_to")||!n||!a)return;let i=tf(r,"url")||tf(r,"schema");return{cardId:n,state:r,widgetData:{...i?{url:i}:{},...tf(r,"title")?{title:tf(r,"title")}:{},...tf(r,"detailText")?{detailText:tf(r,"detailText")}:{}},widgetId:a}}(t);if(a){let t=t2(e.messages,a.cardId,e=>{let t=eJ(e.state)?e.state:{};if("fixed"!==tf(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(!eJ(t)||t.card_type!==tZ)return;let r="string"==typeof e.card_id&&e.card_id||"string"==typeof t.card_id&&t.card_id,n="string"==typeof t.props_json?tm(t.props_json):void 0,a=eJ(null==n?void 0:n._meta)?n._meta:void 0,i=eJ(t.render_data)?t.render_data:void 0,s=eJ(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=tm(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(!eJ(t)||!0!==t.IsFinish||2!==t.MessageType||1005!==t.ContentType||"string"!=typeof t.Content)continue;let n=tm(t.Content);if((null==n?void 0:n.command_type)==="require_location"&&eJ(n.require_location))return{cardId:r,..."string"==typeof s.app_key&&s.app_key?{appKey:s.app_key}:{},..."string"==typeof e.source_tool_call_id&&e.source_tool_call_id?{sourceToolCallId:e.source_tool_call_id}:{},..."string"==typeof s.tool_name&&s.tool_name?{toolName:s.tool_name}:{}}}}((null==r?void 0:r.payload)??{});if(i)return{state:e,locationDirective:{...i,requestId:null==r?void 0:r.request_id,...(null==r?void 0:r.query_message_id)?{queryMessageId:r.query_message_id}:{},...(null==r?void 0:r.reply_message_id)??e.activeReplyMessageId?{replyMessageId:(null==r?void 0:r.reply_message_id)??e.activeReplyMessageId}:{}}};let s=(null==r?void 0:r.reply_message_id)??e.activeReplyMessageId,o=function(e){let t,r=e.card;if(!eJ(r))return{};let n=tm(r.props_json)??{},a=function(e){let t,r;if(e.card_type!==tZ)return;let n=tm(e.props_json)||tm(e.render_data_json)||(eJ(e.render_data)?tm(e.render_data.content_for_display):void 0)||{};return tf(n,"permission_data")||((r=(Array.isArray(null==(t=eJ(n.structuredContent)?n.structuredContent:void 0)?void 0:t.entity_list)?t.entity_list:[]).find(e=>eJ(e)&&(Array.isArray(e.grantingList)||eJ(e._meta)&&!0===e._meta.is_permission)))&&eJ(r)?JSON.stringify(r):void 0)}(r),i=tX(a),s=eJ(n.extra)?n.extra:{},o=Object.keys(n).length>0?(t=tm(n.widget_data))?{viewData:t}:eJ(n.viewData)?{viewData:n.viewData}:{viewData:n}:void 0,l={...eJ(r.source)?r.source:{},..."string"==typeof e.source_tool_call_id?{tool_call_id:e.source_tool_call_id}:{},...Array.isArray(e.source_entity_ids)?{entity_ids:e.source_entity_ids}:{}};return{...{..."string"==typeof e.card_id?{card_id:e.card_id}:{},..."string"==typeof e.widget_id?{widget_id:e.widget_id}:{},..."string"==typeof e.card_type?{card_type:e.card_type}:{},..."string"==typeof e.app_id?{app_id:e.app_id}:{}},...r,..."string"==typeof n.widget_id?{widget_id:n.widget_id}:{},..."string"==typeof n.applet_id?{app_id:n.applet_id}:{},..."string"==typeof n.entity_id?{entity_id:n.entity_id}:{},...Object.keys(l).length>0?{source:l}:{},...i?{card_type:"permission_apply",fallback_text:r.fallback_text||"需要授权后继续",render_data:{grantingData:i,permissionData:a},title:r.title||tQ(i)}:o?{render_data:o}:{},debug:{...eJ(r.debug)?r.debug:{},..."string"==typeof r.props_json?{props_json:r.props_json}:{},..."string"==typeof s["doubao/outputTemplate"]?{output_template:s["doubao/outputTemplate"]}:{}}}}(t),l=tf(t,"block_id")||o.card_id||(n=`card_${(null==r?void 0:r.seq)??0}`,o.card_id||o.title||n),d=tf(t,"op")||"append";if("append"!==d&&"replace"!==d)return{state:e};if(o.card_id){let t=t2(e.messages,o.card_id,e=>{let t,n,a;return r?o:(t=t9(e.state,o.state),n=t9(e.source,o.source),a=t9(e.debug,o.debug),{...e,...o,...t?{state:t}:{},...n?{source:n}:{},...a?{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=tY(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:t0(u,s,e=>({...e,contentType:"mixed",blocks:t1(e.blocks,l,o,d)}))}}}function rr(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 rn(e,t,r){return{...e,toolCalls:e.toolCalls.map(e=>e.toolCallId===t?{...e,...r}:e)}}function ra(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)}var ri=r(33680);function rs(e,t,r){let n,a;if(!eJ(e)||!Array.isArray(e.structuredContent))return e;let i=(n=eJ(t)&&eJ(t.tools)?t.tools:{},a=eJ(n[r])?n[r]:{},eJ(a.output)?a.output:void 0);if(!i||"entities"!==i.kind)return e;if(!e.structuredContent.every(eJ))throw Error(`Tool "${r}" structuredContent items must be objects`);return{...e,structuredContent:{entities:e.structuredContent.map(e=>({...e,entity_type:r}))}}}function ro(e,t){let r;if(!eJ(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=th(e),i=e.content.filter(eJ).map(e=>"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n")||void 0,s=!0===e.isError;return{status:s?"failed":"succeeded",result:n,...s?{error:{code:t.businessErrorCode,message:eJ(n)&&"string"==typeof n.message?n.message:i||a,retryable:!1,stage:"tool_execute",details:eJ(n)?n:{structuredContent:n}}}:{},raw_result_text:a,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 rl="client_tool",rd="__bridge_ready__",ru="lynxview";function rc(e,t){null==e||e({category:"mcp",source:"client_tool",...t})}class rp{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 eD({className:"doubao-client-tool-runtime-view",container:this.host,nativeModulesCallHandler:this.handleNativeModulesCall,onError:e=>this.emitError(e),onReady:()=>this.emitMessage({type:"event",name:rd})}),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&&eJ(t)&&rh(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 rm(e){return Object.assign(Error(e),{name:"AbortError"})}function rh(e){return"callback"===e.type&&"number"==typeof e.callbackId}class rg{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(rm("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(rm("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(rm("Client Tool call aborted"));let o=()=>{null==s||s.removeEventListener("abort",l)},l=()=>{this.pendingCallbacks.delete(n),i(rm("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=eJ(r="string"==typeof e.data?tp(e.data):e.data)?r:void 0;if(!n)return;if("event"===n.type&&n.name===rd){this.ready=!0,null==(t=this.resolveReady)||t.call(this),rc(this.onTraceEvent,{event:"client_tool_runtime_ready",runtime_url:this.runtimeUrl});return}if(!rh(n))return;let a=this.pendingCallbacks.get(n.callbackId);if(a){this.pendingCallbacks.delete(n.callbackId);try{a.resolve(function(e){let t=eJ(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 rf(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:ru}}}let rv="simulator_web_tester";function ry(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=tm(null==(t=e.debug)?void 0:t.props_json),i=r_(e.card_id),s=r_(null==a?void 0:a.applet_id)||r_(e.app_id),o=r_(null==a?void 0:a.entity_id)||r_(e.entity_id);if(i&&s)return{card_id:i,app_key:s,...o?{business_entity_ids:[o]}:{},lifecycle_state:(null==(r=e.state)?void 0:r.lifecycle_state)==="fixed"||(null==(n=e.state)?void 0:n.lifecycle_state)===2?2:1,..."string"==typeof e.refresh_key?{refresh_key:e.refresh_key}:{}}}(e.card);r&&t.set(r.card_id,r)}return[...t.values()]}function r_(e){return"string"==typeof e?e.trim():""}function rb(e){return["succeeded","failed","timeout","cancelled","rejected"].includes(e)}function rw(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,...n?{details:n}:{}}}async function rS(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=rw("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,...h?{signal:h}:{}}))];if(void 0!==c&&m){let e=rw("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 rx(e){return e?String(e):to}function rI(e,t,r){return r?{type:e,message:t,error:r}:{type:e,message:t}}let rE={simulator_manifest_load_failed:"Manifest",simulator_skill_load_failed:"Skill",local_mcp_tools_load_failed:"MCP",simulator_chat_fetch_failed:"对话接口"};function rC(e,t){return e?{kind:"pages",item:e,...t?{routeUrl:t}:{}}:null}function rk(e,t){if(!t)return null;try{return rC(e3({url:t},e).entry,t)}catch{return null}}function rN(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):th(r).slice(0,1e3))||e.status}function rT(e,t){return"string"==typeof e.app_key&&e.app_key||"string"==typeof e.appKey&&e.appKey||"string"==typeof e.appId&&e.appId||"string"==typeof e.packageName&&e.packageName||t}function rM(e,t){let r=eJ(e.applet)?e.applet:{};return"string"==typeof e.name&&e.name||"string"==typeof e.appName&&e.appName||"string"==typeof e.app_name&&e.app_name||"string"==typeof r.name&&r.name||t}function rR(e,t){if(!eJ(t))return e;let r=eJ(e.applet)?e.applet:{},n=eJ(t.applet)?t.applet:{},a=Array.isArray(r.tools)?r.tools:[],i=Array.isArray(n.tools)?n.tools:[],s=new Map,o="string"==typeof t.name&&t.name||"string"==typeof t.appName&&t.appName||"string"==typeof t.app_name&&t.app_name||"string"==typeof n.name&&n.name||"";if(i.length>0)for(let e of[...a,...i])eJ(e)&&"string"==typeof e.id&&e.id&&s.set(e.id,e);return{...e,..."number"==typeof t.manifest_version||"string"==typeof t.manifest_version?{manifest_version:t.manifest_version}:{},..."string"==typeof t.app_key?{app_key:t.app_key}:{},..."string"==typeof t.name?{name:t.name}:{},..."string"==typeof t.appName?{appName:t.appName}:{},..."string"==typeof t.app_name?{app_name:t.app_name}:{},...eJ(t.mcp_server)?{mcp_server:t.mcp_server}:{},...eJ(t.tools)?{tools:t.tools}:{},...eJ(t.entities)?{entities:t.entities}:{},...eJ(t.tool_card_binding)?{tool_card_binding:t.tool_card_binding}:{},..."string"==typeof t.raw_manifest_yaml?{raw_manifest_yaml:t.raw_manifest_yaml}:{},applet:{...r,...o?{name:o}:{},...i.length>0?{tools:[...s.values()]}:{}}}}class rA{fetcher;simulatorFetcher;historyMaxTurns;simulatorAppKey;simulatorAppName;simulatorSkill;simulatorManifest;simulatorMaxStep;simulatorMcpServers;simulatorMcpServerProvider;simulatorToolExecutor;listeners=new Set;activeSimulatorRun=null;lastResolvedSimulatorMcpServers=[];receivedSimulatorLocationDirectiveCardIds=new Set;resourceUrlVersion;hasSimulatorManifestStateValue=!1;simulatorManifestStateValue;simulatorManifestStatePromise;simulatorRunSeq=0;destroyed=!1;state;constructor(e={}){const t=rx(e.manifestUrl);this.fetcher=e.fetcher,this.simulatorFetcher=e.simulatorFetch,this.historyMaxTurns=e.historyMaxTurns??6,this.simulatorAppKey=e.appKey,this.simulatorAppName=e.appName,this.simulatorSkill=e.skill,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 u({manifestVersion:"3.0",packageName:"",appId:"",versionCode:"",applet:{appletId:"",appRuntimeEntry:"",digest:"",pages:[]},widgets:[]}),pages:[],widgets:[],pageSelection:null,widgetSelection:null,simulator:function(e){return{endpoint:tx(e),messages:[],streamStatus:"idle",toolCalls:[],traceEvents:[]}}(e.simulatorEndpoint),status:rI("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 u(rR(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=rx(e??this.state.manifestUrl);this.setState({...this.state,manifestUrl:r,resourceUrlVersion:this.resourceUrlVersion,status:rI("loading",`Loading manifest ${r}`)});try{let e,t,u,p,m,h=await c(r,{fetcher:this.fetcher}),g=await this.mergeSimulatorManifestForState(h),y=g.pages,_=g.widgets,b=rk(g,null==(s=this.state.pageSelection)?void 0:s.routeUrl)??(n=g,a=y,i=this.state.pageSelection,e=a.filter(td),t=null==i?void 0:i.item.path,u=function(e,t){if(null==t?void 0:t.trim())try{return e.getPageEntry(t)}catch{return}}(n,n.raw.applet.appletEntry),rC((t?e.find(e=>e.path===t):void 0)??(u&&td(u)?u:void 0)??e.find(e=>{var t;let r=null==(t=e.path)?void 0:t.replace(/^\/+|\/+$/g,"");return"index"===e.id||"pages/index"===r||"pages/index/index"===r})??e[0])),w=(o=this.state.widgetSelection,p=_.filter(td),(l=((m=null==o?void 0:o.item.widgetId)?p.find(e=>e.widgetId===m):void 0)??p[0])?{kind:"widgets",item:l}:null),S;var n,a,i,s,o,l,d={isolation:S?{mode:"iframe",url:S}:{mode:"inline"},resolveManifestUrl:()=>r,resourceUrlVersion:this.resourceUrlVersion};if(d.isolation){if("inline"!==d.isolation.mode&&"iframe"!==d.isolation.mode)throw Error("Runtime isolation mode must be inline or iframe");v=d.isolation}return f.configure(d),this.setState({...this.state,manifestUrl:r,manifest:g,pages:y,widgets:_,resourceUrlVersion:this.resourceUrlVersion,pageSelection:b,widgetSelection:w,status:rI("ready",b||w?`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:rI("error",`Load failed: ${e.message}`,e)}),e}}navigateToPage(e){this.assertActive();try{let t=rk(this.state.manifest,e);if(!t)throw Error(`Unknown pages route: ${e}`);this.setState({...this.state,pageSelection:t,status:rI("ready",`Navigated page ${t.item.path}`)})}catch(t){let e=t instanceof Error?t:Error(String(t));throw this.setState({...this.state,status:rI("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:rI("error",t.message,t)}),t}this.setState({...this.state,widgetSelection:{kind:"widgets",item:t},status:rI("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=tE("reload");this.resourceUrlVersion=t,this.clearSimulatorManifestStateValue(),f.clearPackageCache(e);let r=await this.loadManifest(e);return 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();if(!r)return;this.cancelSimulatorQuery();let n=tE("local_msg"),a=tE("idem"),i=tE("trace"),s=Date.now(),o=this.state.simulator,l=this.state.manifest.raw,d={messageId:n,localMessageId:n,traceId:i,role:"user",contentType:"text",text:r,blocks:[{blockId:tE("block_text"),type:"text",text:r}],status:"completed",createdAtMs:s},u=this.createSimulatorRun(i);this.activeSimulatorRun=u,this.setState({...this.state,simulator:{...o,activeRequestId:void 0,activeReplyMessageId:void 0,error:void 0,locationDirective:void 0,messages:[...o.messages,d],streamStatus:"streaming"}}),this.appendSimulatorDebugEvent({event:"simulator_query_prepare_started",trace_id:i,previous_active_request_id:o.activeRequestId,previous_stream_status:o.streamStatus,history_message_count:o.messages.length,query_preview:r.slice(0,80)});try{var c,p,m,h;let e,d,g,f,v,y,_,b,w,S=await this.resolveSimulatorManifestForQuery(i,t,l),x=rT(S,this.state.manifest.appId),I=rM(S,this.state.manifest.name);if(!this.isSimulatorRunCurrent(u))return;let E=await this.resolveSimulatorSkillForQuery(i,t);if(!this.isSimulatorRunCurrent(u))return;let C={trace:{trace_id:i,component:"web_sdk_debugger",stage:"query_prepare",sampled:!0},appKey:t.appKey||this.simulatorAppKey||x||void 0,appName:t.appName||this.simulatorAppName||I||void 0,manifest:S},k=this.simulatorMcpServerProvider?await this.simulatorMcpServerProvider(C):this.simulatorMcpServers;if(this.lastResolvedSimulatorMcpServers=k,!this.isSimulatorRunCurrent(u))return;this.appendSimulatorDebugEvent({event:"simulator_query_mcp_resolved",trace_id:i,elapsed_ms:Date.now()-s,mcp_server_count:k.length,mcp_servers:k.map(e=>({server_id:e.server_id,tool_count:e.tools.length,tools:e.tools.map(e=>e.name)}))});let N=(p=(c={historyMaxTurns:this.historyMaxTurns,idempotencyKey:a,localMessageId:n,manifestAppId:this.state.manifest.appId,manifestAppName:I,messages:o.messages,toolCalls:o.toolCalls,options:t,queryText:r,simulatorAppKey:this.simulatorAppKey,simulatorAppName:this.simulatorAppName,simulatorSkill:E,simulatorManifest:S,simulatorMaxStep:this.simulatorMaxStep,simulatorMcpServers:k,traceId:i}).messages,m=c.toolCalls,h=c.historyMaxTurns,e=p.slice(-Math.max(0,2*h)).map(e=>{var t,r,n;let a,i,s,o=(t=e,(a=m.filter(e=>e.replyMessageId===t.messageId&&rb(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?a:(t.toolCalls??[]).filter(e=>rb(e.status))),l=(r=e,(i=m.filter(e=>e.replyMessageId===r.messageId&&rb(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,...r?{result_summary:r}:{},...void 0===e.structuredResultSummary?{}:{structured_summary:e.structuredResultSummary},...void 0===e.isMiniApp?{}:{is_mini_app:e.isMiniApp}}})).length>0?i:r.toolResults??[]);return{role:"assistant"===e.role?"ASSISTANT":"USER",content:(s=(n=e).text?n.text:n.blocks.filter(e=>"text"===e.type).map(e=>e.text).join(""))||e.blocks.filter(e=>"card"===e.type).map(e=>{var t;return(t=e.card).fallback_text||t.title||t.card_type||t.card_id||"卡片"}).join("\n"),...o.length>0?{tool_calls:o.map(e=>({tool_call_id:e.tool_call_id,tool_name:e.tool_name,arguments:e.arguments_summary,status:e.status}))}:{},...l.length>0?{tool_results:l.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}))}:{}}}),d=ry(c.messages),g=c.simulatorManifest||c.options.manifest||{},f="string"==typeof g.app_key?g.app_key:"",v=c.options.appKey||c.simulatorAppKey||f||c.manifestAppId||"web-sdk-debugger",y=c.options.appName||c.simulatorAppName||c.manifestAppName||v,_=(c.options.skill||c.simulatorSkill||"").trim(),b=c.options.mcpServers??c.simulatorMcpServers,w=function(e,t){let r="string"==typeof e.raw_manifest_yaml?e.raw_manifest_yaml:"",n=t.find(e=>e.server_id===rl&&e.tools.length>0);if(!n||!eJ(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,ri.qg)(e);if(!eJ(t))throw Error("Client Tool raw_manifest_yaml must contain a YAML object");return t}(r);return null!=a.mcp_server?r:(0,ri.As)({...a,mcp_server:{end_point:n.server_id,description:n.description||n.name}})}(g,b),{app_id:v,scene:"miniapp_simulator_web_tester",history_messages:e,card_snapshots:d,message:{role:"USER",content:c.queryText,local_message_id:c.localMessageId},trace:{trace_id:c.traceId,component:rv,stage:"query",sampled:!0},client:{platform:"web",locale:"zh-CN",timezone:function(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"Asia/Shanghai"}}()},ext:{web_tester:"true",stateless_context:"client_history",skill_source:_?"local_file":"none",...c.options.followUpContent?{applet_follow_up_data:th(c.options.followUpContent)}:{},...c.options.noLogin?{no_login:"true"}:{}},max_step:c.options.maxStep??c.simulatorMaxStep??20,protocol_version:"v2",idempotency_key:c.idempotencyKey,mini_apps:[{app_key:v,app_name:y,..._?{skill:_}:{},manifest:{app_key:v,app_name:y,raw_manifest_yaml:w},mcp_servers:b.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:th(e.input_schema_json)}))}))}],web_capabilities:{supports_debug_event:!0}});if(await tU({endpoint:this.state.simulator.endpoint,fetcher:this.simulatorFetcher,request:N,signal:u.streamAbortController.signal,onEvent:e=>this.handleSimulatorEvent(e,u)}),!this.isSimulatorRunCurrent(u))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:i,elapsed_ms:Date.now()-s,stream_status:this.state.simulator.streamStatus,active_request_id:this.state.simulator.activeRequestId})}catch(n){if(t6(n))return void this.appendSimulatorDebugEvent({event:"simulator_query_aborted",trace_id:i,elapsed_ms:Date.now()-s,stream_status:this.state.simulator.streamStatus});if(!this.isSimulatorRunCurrent(u))return;let e=t7(n,"query_stream"),t=this.getSimulatorQueryFailureDiagnosis(i,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:i,elapsed_ms:Date.now()-s,error:r}),this.setState({...this.state,simulator:{...this.state.simulator,activeRequestId:void 0,error:r,streamStatus:"error"}}),n}finally{this.finishSimulatorStream(u)}}removeSimulatorMessages(e){this.assertActive();let t=new Set(e.filter(Boolean));0!==t.size&&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}))}applySimulatorCardDelta(e){this.assertActive(),this.updateSimulatorState(t=>rt(t,eJ(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",...e?{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){let t;if(this.assertActive(),!this.simulatorToolExecutor)throw Error("No local simulator tool executor is configured");let r=e.toolName.trim();if(!r)throw Error("toolName must be a non-empty string");let n=tE("req_tool"),a=tE("reply_tool"),i=tE("tool_call"),s=tE("trace"),o={trace_id:s,component:"web_sdk_debugger",stage:"direct_tool_call",sampled:!0},l=Date.now(),d=await this.resolveDirectToolCallServerId(r,e.serverId,o),u={requestId:n,replyMessageId:a,toolCallId:i,toolName:r,serverId:d,appKey:this.simulatorAppKey||rT(this.state.manifest.raw,this.state.manifest.appId)||void 0,arguments:e.params,argumentsJson:e.params?tH(e.params):void 0,status:"running",createdAtMs:l,updatedAtMs:l,trace:o,timeoutMs:e.timeoutMs};this.updateSimulatorState(e=>({...e,toolCalls:[...e.toolCalls,u]})),this.appendSimulatorDebugEvent({event:"direct_tool_call_started",request_id:n,trace_id:s,tool_call_id:i,tool_name:r,server_id:d,arguments:e.params,arguments_json:u.argumentsJson});let c=Date.now();try{t=await rS({executor:this.simulatorToolExecutor,input:this.createToolExecutorInput(u),record:u})}catch(r){let e=t7(r,"tool_execute");t={status:"TOOL_EXEC_TIMEOUT"===e.code?"timeout":"TOOL_EXEC_CANCELLED"===e.code||t6(r)?"cancelled":"failed",error:e}}return this.updateToolCall(i,{status:t.status,updatedAtMs:Date.now(),error:t.error,resultSummary:rN(t),structuredResultSummary:t.result,isMiniApp:t.miniapp&&"boolean"==typeof t.miniapp.is_mini_app?t.miniapp.is_mini_app:void 0}),this.appendSimulatorDebugEvent({event:"direct_tool_call_completed",request_id:n,trace_id:s,tool_call_id:i,tool_name:r,server_id:d,status:t.status,elapsed_ms:Date.now()-c,result:t.result,error:t.error,raw_result_text:t.raw_result_text}),t}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,i=(a=e.raw_mcp_result_json)||e.raw_result_text||th(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),...e.appKey?{app_key:e.appKey}:{},result:{tool_call_id:e.toolCallId,content:a||i,structured_json:th(n)},raw_result_text:i,raw_mcp_result_json:a||"",miniapp:e.miniapp,timing:e.timing,trace:{trace_id:e.trace.trace_id,component:rv,stage:"tool_report",sampled:e.trace.sampled??!0},ext:{reported_by:rv}});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,report_request_json:tH(o),endpoint:this.state.simulator.endpoint});try{r=await tq({endpoint:this.state.simulator.endpoint,fetcher:this.simulatorFetcher,result:o,signal:t})}catch(r){let t=tD(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:tg(r),...t?{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=tS(e)[0];return rw("TOOL_RESULT_REJECTED",i?`${a} (x-tt-logid: ${i})`:a,"tool_result_submit",{gateway_response:e,...n?{gateway_code:t}:{},...r?{gateway_accepted:!1}:{},...i?{"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,...l?{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(!eJ(t))return{status:"invalid_widget_data",message:"widgetData must be a JSON object"};let r=t2(this.state.simulator.messages,e.widgetInstanceId,r=>({...r,...e.widgetId?{widget_id:e.widgetId}:{},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=rw("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=t7(a,"tool_result_submit");throw this.appendSimulatorDebugEvent({event:"tool_result_submit_failed",trace_id:r.trace.trace_id,tool_call_id:e,summary:tg(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)?p(this.state.manifestUrl,e):null}destroy(){var e,t;this.destroyed||(this.cancelSimulatorQuery(),null==(t=this.simulatorToolExecutor)||null==(e=t.dispose)||e.call(t),this.destroyed=!0,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){for(let t of(e.cancelled=!0,e.streamAbortController.abort(),e.toolAbortControllers))t.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){let r="tool_call"===e.event_type;if(!this.isSimulatorRunCurrent(t)){r&&this.appendSimulatorDebugEvent({event:"tool_call_event_skipped",request_id:e.request_id,trace_id:e.trace.trace_id,tool_call_id:tf(e.payload,"tool_call_id"),tool_name:tf(e.payload,"tool_name"),reason:"stale_or_cancelled_run",summary:"Tool call event arrived after its simulator run was cancelled and was not executed"});return}let n=this.state.simulator.activeRequestId;if(n&&e.request_id!==n&&"ack"!==e.event_type&&"debug"!==e.event_type){if(!r&&"tool_status"!==e.event_type)return;this.appendSimulatorDebugEvent({event:"tool_call_request_id_mismatch",request_id:e.request_id,active_request_id:n,trace_id:e.trace.trace_id,tool_call_id:tf(e.payload,"tool_call_id"),tool_name:tf(e.payload,"tool_name"),event_type:e.event_type,summary:"Tool call event request_id differs from the acknowledged request_id"})}let{state:a,toolCall:i,cardRefresh:s,locationDirective:o}=function(e,t,r){var n,a,i,s,o,l,d,u,c,p,m,h,g,f;let v,y,_,b,w,S,x,I,E,C,k,N,T={...e,activeReplyMessageId:t.reply_message_id??e.activeReplyMessageId},M=!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)?T:re(T,(N=t.received_at_ms??Date.now(),{display:"debug"===(n=t).event_type?tz(n.payload)??{category:"debug",detail:t3(n),phase:"event",title:"Debug"}:{category:t5(n),detail:t3(n),phase:t8(n.event_type),title:t4(n)},id:t.event_id,timestamp:N,payload:(a=t,i=N,v=t5(a),y=t8(a.event_type),_={event:a.event_type,category:v,phase:y,received_at_ms:i,server_timestamp_ms:a.created_at_ms,title:t4(a),detail:t3(a),trace:a.trace},"debug"===a.event_type?{..._,event:tf(a.payload,"event")||"debug",title:t_(tf(a.payload,"title")||tf(a.payload,"event")||"Debug Event"),summary:tf(a.payload,"summary"),elapsed_ms:tv(a.payload,"elapsed_ms"),redaction_level:tf(a.payload,"redaction_level")}:"heartbeat"===a.event_type?{..._,server_time_ms:tv(a.payload,"server_time_ms"),message:tf(a.payload,"message")}:"answer_finish"===a.event_type?{..._,status:tf(a.payload,"status"),finish_reason:tf(a.payload,"finish_reason"),usage:a.payload.usage}:{..._,...a.payload})}));switch(t.event_type){case"ack":return{state:(s=M,b=tf((o=t).payload,"local_message_id"),w=tf(o.payload,"query_message_id"),S=tf(o.payload,"message_id"),x=b&&w?s.messages.map(e=>e.localMessageId===b?{...e,messageId:w}:e):s.messages,{...s,activeRequestId:o.request_id,...S?{activeReplyMessageId:S}:{},messages:x})};case"message_start":return{state:(l=M,I=tf((d=t).payload,"message_id")||d.reply_message_id||tE("reply"),{...l,activeReplyMessageId:I,messages:tY(l.messages,I,d.created_at_ms,d.request_id,d.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=tf(t.payload,"block_id")||`block_text_${t.seq}`,a=tf(t.payload,"delta"),i=tf(t.payload,"op")||"append";if("append"!==i&&"replace"!==i)return e;let s=tY(e.messages,r,t.created_at_ms,t.request_id,t.trace.trace_id);return{...e,messages:t0(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)}))}}(M,t)};case"card_delta":return rt(M,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(!eJ(e))return;let t=eJ(e.content)?e.content:e,r=eJ(t.permission_apply_block)?t.permission_apply_block:eJ(t.permissionApplyBlock)?t.permissionApplyBlock:void 0;return r?tf(r,"permission_data")||tf(r,"permissionData"):""}(n),i=tX(a);if(!i)continue;let s=eJ(n)&&tf(n,"block_id")||eJ(n)&&tf(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:tQ(i)},op:tf(e,"op")||"append"}}}(t.payload,t);if(!n||"append"!==n.op&&"replace"!==n.op)return e;let a=tY(e.messages,r,t.created_at_ms,t.request_id,t.trace.trace_id);return{...e,messages:t0(a,r,e=>({...e,contentType:"mixed",blocks:t1(e.blocks,n.blockId,n.card,n.op)}))}}(M,t)};case"tool_call":return function(e,t,r){let n,a=tf(t.payload,"tool_call_id"),i=tf(t.payload,"tool_name"),s=tf(t.payload,"server_id"),o=tf(t.payload,"arguments_json"),l=t.reply_message_id??e.activeReplyMessageId??tE("reply");if(!a||!i)return{state:re(e,{id:tE("trace"),timestamp:Date.now(),payload:{event:"tool_call_ignored",request_id:t.request_id,trace_id:t.trace.trace_id,tool_call_id:a,tool_name:i,reason:a?"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 d=("boolean"==typeof(n=t.payload.requires_user_approval)?n:void 0)??!1,u=d?"pending_approval":r.hasToolExecutor?"running":"pending",c={requestId:t.request_id,...void 0===r.runId?{}:{runId:r.runId},replyMessageId:l,toolCallId:a,toolName:i,serverId:s,appKey:tf(t.payload,"app_key")||void 0,arguments:eJ(t.payload.arguments)?t.payload.arguments:tm(o),argumentsJson:o||void 0,mcpHeaders:function(e){if(!eJ(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:u,createdAtMs:t.created_at_ms,updatedAtMs:t.created_at_ms,trace:t.trace,requiresUserApproval:d,timeoutMs:tv(t.payload,"timeout_ms"),deadlineMs:tv(t.payload,"deadline_ms")},p=t0(tY(e.messages,l,t.created_at_ms,t.request_id,t.trace.trace_id),l,e=>({...e,toolCalls:ra(e.toolCalls??[],c)})),m={...e,messages:p,toolCalls:[...e.toolCalls.filter(e=>e.toolCallId!==a),c]};return r.hasToolExecutor?{state:m,toolCall:c}:{state:re(m,{id:tE("trace"),timestamp:Date.now(),payload:{event:"tool_executor_missing",request_id:c.requestId,trace_id:c.trace.trace_id,tool_call_id:a,tool_name:i,summary:"No local simulator tool executor is configured"}})}}(M,t,r);case"tool_status":return{state:function(e,t){let r=tf(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""}}(tf(t.payload,"status"));if(!r||!n)return e;let a=tv(t.payload,"progress"),i=tf(t.payload,"message"),s=t.payload.error?t7(t.payload.error,"tool_execute"):void 0,o=rn(e,r,{status:n,updatedAtMs:t.created_at_ms,...void 0===a?{}:{progress:a},...i?{message:i}:{},...s?{error:s}:{}}),l=o.toolCalls.find(e=>e.toolCallId===r);return l?{...o,messages:t0(o.messages,l.replyMessageId,e=>({...e,toolCalls:ra(e.toolCalls??[],l)}))}:o}(M,t)};case"trace_event":case"debug":default:return{state:M};case"heartbeat":return{state:(u=M,c=t,{...u,lastHeartbeatMs:tv(c.payload,"server_time_ms")??c.created_at_ms})};case"answer_finish":return{state:(p=M,m=t,{...p,answerFinish:{messageId:m.reply_message_id,status:tf(m.payload,"status"),finishReason:tf(m.payload,"finish_reason"),usage:eJ(m.payload.usage)?m.payload.usage:void 0,createdAtMs:m.created_at_ms,trace:m.trace,payload:m.payload}})};case"message_finish":return{state:function(e,t){let r=tf(t.payload,"message_id")||t.reply_message_id;if(!r)return e;let n=tf(t.payload,"status")||"completed";return{...e,messages:t0(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)}))}}(M,t)};case"reply_finish":return{state:(h=M,C="completed"===(E=tf(t.payload,"status")||"completed")||"finished"===E?"completed":"cancelled"===E?"cancelled":"error",{...h,activeRequestId:void 0,activeReplyMessageId:void 0,messages:rr(h.messages,C),streamStatus:C})};case"stream_error":return{state:(g=M,k=t7((f=t).payload.error??f.payload,tf(f.payload,"stage")||"stream"),{...g,activeRequestId:void 0,error:k,messages:rr(g.messages,"error"),streamStatus:"error"})}}}(this.state.simulator,e,{hasToolExecutor:!!this.simulatorToolExecutor,runId:t.id}),l=o&&!this.receivedSimulatorLocationDirectiveCardIds.has(o.cardId)?o:void 0;if(l&&this.receivedSimulatorLocationDirectiveCardIds.add(l.cardId),this.updateSimulatorState(()=>l?{...a,locationDirective:l}:a),l?this.appendSimulatorDebugEvent({category:"card",event:"simulator_location_directive_received",card_id:l.cardId,request_id:l.requestId,source_tool_call_id:l.sourceToolCallId,tool_name:l.toolName,trace_id:e.trace.trace_id}):o&&this.appendSimulatorDebugEvent({category:"card",event:"simulator_location_directive_loop_prevented",card_id:o.cardId,reason:"duplicate_card_id",request_id:o.requestId,tool_name:o.toolName,trace_id:e.trace.trace_id}),(null==s?void 0:s.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:s.cardId}),i){let e=this.withFallbackToolCallServerId(i);e.requiresUserApproval?t.pendingApprovalToolCallIds.add(e.toolCallId):this.executeSimulatorToolCall(e,t)}}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 executeSimulatorToolCall(e,t){let r;if(!this.simulatorToolExecutor)return;let n=this.simulatorToolExecutor;if(t&&!this.isSimulatorRunCurrent(t))return;let a=Date.now(),i=this.createToolExecutorInput(e),s=t?new AbortController:void 0;t&&s&&t.toolAbortControllers.add(s);try{r=await rS({executor:n,input:i,record:e,signal:null==s?void 0:s.signal})}catch(t){let e=t7(t,"tool_execute");r={status:"TOOL_EXEC_TIMEOUT"===e.code?"timeout":"TOOL_EXEC_CANCELLED"===e.code||t6(t)?"cancelled":"failed",error:e}}try{if(t&&!this.isSimulatorRunCurrent(t))return void this.appendSimulatorDebugEvent({event:"tool_result_submit_skipped",request_id:e.requestId,trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,tool_name:e.toolName,reason:"stale_or_cancelled_run"});if(await this.submitExecutedToolResult(i,r,a,null==s?void 0:s.signal),t&&!this.isSimulatorRunCurrent(t))return;this.updateToolCall(e.toolCallId,{status:r.status,updatedAtMs:Date.now(),error:r.error,resultSummary:rN(r),structuredResultSummary:r.result,isMiniApp:r.miniapp&&"boolean"==typeof r.miniapp.is_mini_app?r.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=t7(n,"tool_result_submit");this.appendSimulatorDebugEvent({event:"tool_result_submit_failed",trace_id:e.trace.trace_id,tool_call_id:e.toolCallId,summary:tg(n),error:r}),this.updateToolCall(e.toolCallId,{status:"failed",updatedAtMs:Date.now(),error:r}),this.failActiveSimulatorStream(r)}finally{t&&s&&(t.toolAbortControllers.delete(s),this.releaseSimulatorRun(t))}}createToolExecutorInput(e){let t={trace_id:e.trace.trace_id,span_id:tE("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||rT(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){let n=Date.now(),a=void 0!==t.manifest,i=a?"query_option":void 0===this.simulatorManifest?"loaded_manifest":"debugger_option";this.appendSimulatorDebugEvent({event:"simulator_manifest_load_started",trace_id:e,source:i});try{let s=a?{found:!1,value:void 0}:this.takeSimulatorManifestStateValue(),o=a?t.manifest:s.found?s.value:"function"==typeof this.simulatorManifest?await this.simulatorManifest():this.simulatorManifest,l=o?rR(r,o):r;return this.appendSimulatorDebugEvent({event:"simulator_manifest_loaded",trace_id:e,elapsed_ms:Date.now()-n,source:i,manifest:l}),l}catch(t){return this.appendSimulatorDebugEvent({event:"simulator_manifest_load_failed",trace_id:e,elapsed_ms:Date.now()-n,error:tg(t),source:i}),r}}async resolveSimulatorSkillForQuery(e,t){let r=Date.now(),n=void 0===t.skill?"debugger_option":"query_option";this.appendSimulatorDebugEvent({event:"simulator_skill_load_started",trace_id:e,source:n});try{let a=t.skill??("function"==typeof this.simulatorSkill?await this.simulatorSkill():this.simulatorSkill)??"";return this.appendSimulatorDebugEvent({event:a.trim()?"simulator_skill_loaded":"simulator_skill_empty",trace_id:e,elapsed_ms:Date.now()-r,skill_length:a.length,source:n}),a}catch(t){return this.appendSimulatorDebugEvent({event:"simulator_skill_load_failed",trace_id:e,elapsed_ms:Date.now()-r,error:tg(t),source:n}),""}}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||rT(i,this.state.manifest.appId)||void 0,o=this.simulatorAppName||rM(i,this.state.manifest.name)||void 0,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=rw("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 submitExecutedToolResult(e,t,r,n){let a=Date.now();await this.submitToolResult({...e,...t,timing:{started_at_ms:r,ended_at_ms:a,duration_ms:a-r,attempt:1}},n)}updateToolCall(e,t){this.updateSimulatorState(r=>rn(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=eJ(t.payload)?t.payload:{},a=rE["string"==typeof n.event?n.event:""];a&&function(e){let t=eJ(e.trace)?e.trace:{},r=e.trace_id??t.trace_id;return"string"==typeof r?r:""}(n)===e&&"Failed to fetch"===("string"==typeof n.error?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=tD(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"===tg(t)?{code:"SIMULATOR_ENDPOINT_UNREACHABLE",confidence:"unknown",summary:"无法连接模拟器接口",suggestion:"可能是接口服务未启动、端口不可达、浏览器网络异常或 CORS 被拦截。"}:void 0}appendSimulatorDebugEvent(e){let t=tS(e),r={display:tz(e),id:tE("trace"),timestamp:Date.now(),payload:function(e,t){if(!eJ(e))return e;let r=tV(e);return{...e,category:r.category,detail:r.detail,phase:r.phase,title:r.title,...t.length>0?{log_ids:t}:{}}}(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 rP="iphone-13",rj=[{key:rP,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}}],rL=[{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}],rD={key:"mobile-393",label:"393px",width:393,density:3};function rO(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 rj.find(t=>t.key===e)??rj.find(e=>e.key===rP)??rj[0]}function rU(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:rj["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}}function rq(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:rD,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}}function r$(e,t){try{let e=t.trim()?JSON.parse(t):{};if(eJ(e))return e;throw Error("expected a JSON object")}catch(t){throw Error(`${e}: ${t.message}`)}}function rB(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:"重新打开当前页面"})]})}function rF(e,t){let r=(0,e9.H)(e);return r.render((0,i.jsx)(rB,{onReopen:t})),()=>r.unmount()}function rW(e){return e??document.body}async function rH(e,t){var r;let n,a=rW(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(rW(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 rz=[],rV=new Map,rG=!1;function rJ(e){for(let t of e)URL.revokeObjectURL(t),rV.delete(t)}function rK(){for(let e of rz.splice(0))rJ(e)}function rX(e){var t;let r=rV.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 rQ(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 rZ(e){if("string"!=typeof e.src||!e.src)throw Error("src must be a non-empty string");let t=await rQ(e.src);return{width:t.naturalWidth||t.width,height:t.naturalHeight||t.height,orientation:"up",path:e.src,type:rX(e.src)}}async function rY(e){if("string"!=typeof e.src||!e.src)throw Error("src must be a non-empty string");let t=await rQ(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 r0={enableHighAccuracy:!0,maximumAge:0,timeout:1e4};function r1(){return{browserAuthorization:"unknown",message:"未配置",tone:"muted",userAuthorization:"unknown"}}function r2(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 r3{browserAuthorization="unknown";browserLocation;browserWatchId;locationListeners=new Set;manualLocation;pendingBrowserRequest;revision=0;snapshot=r1();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]:r0;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]:r0;return this.getConfiguredLocation()??this.locateWithBrowser(e)}async requestBrowserLocation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:r0;return this.manualLocation=void 0,this.locateWithBrowser(e)}setManualLocation(e){r2(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]:r0,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 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=r1(),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(r2({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 r4=new r3,r5=new Map,r8={"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 r6(e,t){return`${e||"unknown-app"}:${t}`}function r7(e){return r8[e]??{description:"需要获得你的授权后才能继续使用此功能。",title:`申请获取你的${e.replace(/^scope\./,"")||"相关"}权限`}}async function r9(e){var t;let{appId:r,appIcon:n,appName:a,presenter:i,scope:s,skipDialogIfDenied:o=!1}=e,l=r||"unknown-app",d=r5.get(r6(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,...r7(s)});return t=u?"granted":"denied",r5.set(r6(l,s),t),u}function ne(){throw Error("Simulator UI presenter is unavailable")}function nt(){return{chooseLocation:async()=>ne(),hideLoading:ne,hideToast:ne,showActionSheet:async()=>ne(),showBottomSheet:async()=>ne(),showLoading:ne,showModal:async()=>ne(),showToast:ne}}function nr(){a&&window.removeEventListener("beforeunload",a),a=void 0}function nn(e,t){return w(e,"user_unauthorized"===t.status?"user permission denied":t.message)}async function na(e){let t=await r9({appId:e.appId,appIcon:e.appIcon,appName:e.appName,presenter:e.showSimulatorPermission,scope:"scope.userLocation",skipDialogIfDenied:!0});return r4.updateUserAuthorization(t),t}function ni(e){let t={};return e.forEach((e,r)=>{t[r]=e}),t}function ns(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:ni(r),method:t,url:"string"==typeof e.url?e.url:""}}async function no(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ns(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:ni(r.headers),data:a}}let nl=new Set,nd=new WeakSet,nu=0;function nc(){return navigator.connection}function np(){var e;let t,r=nc(),n=null==r?void 0:r.effectiveType;return{isConnected:!1!==navigator.onLine,networkType:(t=null==(e=nc())?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 nm(){return{timestamp:performance.now()/1e3,wallTime:Date.now()/1e3}}function nh(e){for(let t of nl)try{t(e)}catch(e){console.error("Failed to record doubao.request in Chrome DevTools",e)}}function ng(){let e=np();return{networkType:e.networkType,signalStrength:e.signalStrength,hasSystemProxy:e.hasSystemProxy??!1,weakNet:e.weakNet??!1}}function nf(e,t){let r=null==e?void 0:e[t];return"string"==typeof r?r.trim():""}async function nv(e,t,r){let n=await r9({appId:e.appId,appIcon:e.appIcon,appName:e.appName,presenter:e.showSimulatorPermission,scope:t,skipDialogIfDenied:r});return r4.isLocationScope(t)&&r4.updateUserAuthorization(n),n}let ny="app_id_missing",n_="cashier_unavailable",nb="create_order_failed",nw="developer_order_exists",nS="login_credential_invalid",nx="login_credential_missing",nI="login_authorization_failed",nE="login_authorization_unsupported",nC="login_state_invalid",nk="login_session_unavailable",nN="payment_amount_invalid",nT="payment_authorization_invalid",nM="payment_cancelled",nR="payment_data_invalid",nA="payment_data_missing",nP="payment_data_unavailable",nj="payment_data_unavailable_with_sign",nL="payment_data_unsupported",nD="payment_failed",nO="payment_method_unavailable",nU="payment_order_invalid",nq="payment_parameter_missing",n$="payment_params_invalid",nB="payment_params_unavailable",nF="payment_sign_params_invalid",nW="payment_sign_params_unavailable",nH="payment_incomplete",nz="privacy_state_unavailable",nV="privacy_authorization_failed",nG="pre_order_failed",nJ="phone_authorization_failed",nK="request_format_invalid",nX="request_params_invalid",nQ="sandbox_resource_not_found",nZ="sandbox_service_unavailable",nY="sandbox_session_expired",n0="sandbox_session_forbidden",n1="sign_order_failed",n2="sign_order_already_exists",n3="sign_order_not_found",n4="sign_order_params_invalid",n5="sign_order_status_invalid",n8="sign_order_create_failed",n6="sign_page_params_invalid",n7="sign_page_unavailable",n9="sign_page_data_unavailable",ae="请求暂时无法完成,请稍后重试;如持续失败,请提供 log_id";class at extends Error{code;details;constructor(e,t={}){super(an(e,t)),this.code=e,this.details=t,this.name="SandboxError"}}class ar extends Error{remoteCode;options;constructor(e,t,r={}){super(t),this.remoteCode=e,this.options=r,this.name="SandboxRemoteError"}}function an(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};switch(e){case ny:return"当前未配置应用 ID,请先完成应用配置。";case n_:return"无法打开模拟器收银台,请刷新模拟器后重试。";case nb:return"暂时无法创建订单,请检查签名参数后稍后重试;如持续失败,请提供 log_id";case nw:return"开发者订单号已存在,请查询原订单";case nS:return"登录失败:登录凭证已过期或已使用,请重新发起登录。";case nx:return"登录失败:成功登录回调未携带业务登录凭证,请检查登录实现。";case"login_failed":return"登录失败:无法完成模拟器登录,请检查模拟器会话后重试。";case"login_info_unavailable":return"登录信息暂时不可用,请稍后重试;如持续失败,请提供 log_id";case nI:return"暂时无法完成登录授权,请重新发起授权";case nE:return"当前 Sandbox 无法完成该授权请求,请检查授权方式和会话配置";case"login_permission_denied":return"登录失败:开发者账号没有该应用的调试权限,请检查应用归属和账号状态。";case nC:return"用户登录状态已失效,请重新登录";case nk:return"登录失败:模拟器会话不可用,请登录开发者账号后重新打开模拟器。";case"payment_already_paid":return"订单已完成支付,请勿重复提交。";case nN:return"支付金额无效,请使用最小货币单位的整数,并由业务服务端生成金额。";case nT:return"支付授权校验失败,请确认 data 和 dbAuthorization 使用同一个 dev.key 生成,并且模拟器配置了匹配的 dev.csr。";case nM:return"已取消支付。";case nR:return"支付数据格式无效,请检查业务服务端生成的 pay_data。";case nA:{let e=t.field?({id:"支付方式 ID",name:"支付方式名称",pay_order_no:"支付订单号",pay_status:"支付状态",trade_no:"交易号"})[t.field]||t.field:"必要字段";return`支付数据缺少${e},请检查业务服务端生成的 pay_data。`}case nP:return"无法打开收银台:模拟器未返回支付数据,请检查订单状态和预下单响应。";case nj:return"无法打开支付签约收银台:模拟器未返回支付数据,请检查签约参数和订单状态。";case nL:return"当前支付数据不支持模拟器收银台,请检查模拟器支付配置。";case nD:return ae;case"payment_login_required":return"支付需要先登录,请完成模拟器登录并绑定支付账户后重试。";case nO:return"支付数据中没有可用的支付方式,请检查模拟器支付配置。";case"payment_order_expired":return"支付订单已过期,请重新创建订单后重试。";case nU:return"订单不存在或不属于当前应用";case nq:{let e=t.key||"该参数";return`缺少支付参数,请提供${({data:"业务服务端生成的 data",dbAuthorization:"业务服务端生成的 dbAuthorization",orderId:"requestOrder 返回的 orderId",signData:"业务服务端生成的 signData",signDbAuthorization:"业务服务端生成的 signDbAuthorization"})[e]||e}。`}case n$:return"请求参数不正确,请检查订单信息和金额";case nB:return"暂时无法获取支付参数,请检查订单号后重试;如持续失败,请提供 log_id";case nF:return"请求参数不正确,请检查订单号和签约信息";case nW:return"暂时无法获取支付参数,请稍后重试;如持续失败,请提供 log_id";case nH:return"模拟支付未完成,请检查支付方式和订单状态后重试;如持续失败,请提供 log_id";case nz:return"暂时无法读取或保存授权状态,请稍后重试";case nJ:return"手机号授权失败:无法获取手机号授权凭证,请重试或使用其他登录方式。";case nV:return"隐私授权失败:请刷新模拟器后重试。";case nG:return"预下单失败:模拟器未返回订单 ID,请检查业务服务端预下单响应。";case nK:return"请求格式不正确,请检查后重试";case nX:return"请求参数不正确,请检查必填字段和字段格式";case nQ:return"未找到沙箱会话或相关资源,请重新创建后重试";case nZ:return"沙箱服务暂时不可用,请稍后重试;如持续失败,请提供 log_id";case nY:return"沙箱会话已过期,请重新启动调试会话";case n0:return"当前沙箱会话无权访问该应用,请检查应用和会话是否匹配";case n1:return"创建签约订单失败:模拟器未返回签约订单 ID,请检查签约参数。";case n2:return"开发者签约单号已存在,请查询原签约单";case n3:return"签约单不存在或不属于当前应用";case n4:return"签约单参数无效,请检查单号、应用和有效期";case n5:return"当前签约单状态不允许继续签约";case n8:return"暂时无法创建签约单,请检查签名参数后重试;如持续失败,请提供 log_id";case n6:return"签约单参数无效,请检查单号、应用和有效期";case n7:return"暂时无法获取签约页,请稍后重试;如持续失败,请提供 log_id";case n9:return"打开签约页面失败:模拟器未返回签约数据,请检查签约订单状态。";default:return ae}}function aa(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}}function ai(e,t){if(400===t)return nK;switch(e){case 400:return nX;case 401:return nY;case 403:return n0;case 404:return nQ;case 500:return nZ;default:return}}function as(e,t,r){switch(e){case 500:return"payment"===r?nH:nZ;case 4201:return nT;case 0x1dcd6501:if(t===nG)return n$;if(t===nj)return nF;if(t===n1)return n4;if(t===n9)return n6;return n$;case 0x1dcdb322:return nw;case 5e8:if(t===nG)return nb;if(t===nj)return nW;if(t===n1)return n8;if(t===n9)return n7;return nB;case 0x1dcdb325:return t===n9?n3:nU;case 0x1dcdb327:return n2;case 0x1dcdb328:return n5;default:return void 0===e||0===e?t:nD}}function ao(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if("code"===r.errorField){let t=ai(e,r.httpStatus);if(t)return t}if("data.error_code"===r.errorField&&40001===e)return nE;if("err_code"===r.errorField){if(401===e)return nX;if(402===e)return nC;if(501===e)return nz}switch(e){case -1:return nk;case 1001:return"phone"===t?nJ:nS;case 4001:return nS;case 2001:return nV;case 502:return nI;case 402:return nC;case 501:return nz;case 400:return nX;default:return nZ}}function al(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ae;if(e instanceof at)return an(e.code,e.details);if(e instanceof ar){let t="code"===e.options.errorField?ai(e.remoteCode,e.options.httpStatus):void 0;return an("payment"===e.options.operation?as(e.remoteCode,nD,e.options.operation):t||as(e.remoteCode,nD))}return t}function ad(e,t){return e instanceof at?e:new at(e instanceof ar?ao(e.remoteCode,t,e.options):nZ)}function au(e,t){let r=aa(e.err_code);if(void 0!==r&&0!==r)throw new at(ao(r,t,{errorField:"err_code"}))}function ac(e){return!e||"object"!=typeof e||Array.isArray(e)?{}:{code:aa(e.code),logId:"string"==typeof e.log_id?e.log_id:void 0}}function ap(e,t){let{code:r,logId:n}=ac(e);if(void 0!==r&&0!==r)throw new ar(r,`Sandbox 请求失败,错误码为 ${String(r)}。`,{errorField:"code",httpStatus:t,logId:n})}let am="web-sdk-debugger",ah=[{id:"douyin",name:"抖音支付"}];async function ag(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}=ac(r);if(!t.ok)throw new ar(n,`Sandbox 代理请求失败,HTTP 状态码为 ${t.status}。`,{errorField:"code",httpStatus:t.status,logId:a});return ap(r,t.status),r}let af=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};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)}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)}}({baseURL:"",request:ag});function av(e,t){if(!e.data)throw Error(e.message||`${t} returned empty data`);return e.data}async function ay(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return av(await af.PullSandboxNotices(e),"PullSandboxNotices")}async function a_(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return av(await af.PullSandboxTasks(e),"PullSandboxTasks")}async function ab(e){return av(await af.RemoveSandboxTaskFromUser({task_id:e}),"RemoveSandboxTaskFromUser").removed_task}async function aw(e,t){return ag({data:{event_id:e,data:t},method:"POST",url:"/app_developer/api/sandbox/bridge/events/report"})}async function aS(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 af.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)}`)}function ax(e){var t;let r=(null==(t=e.getAppId)?void 0:t.call(e))||e.appId;if(!r)throw new at(ny);return r}function aI(e,t){if(!e||"object"!=typeof e)return"";let r=e[t];return"string"==typeof r?r:""}function aE(e,t){let r=aI(e,t).trim();if(!r)throw new at(nq,{key:t});return r}function aC(e,t){let r=e[t];if("string"!=typeof r||!r.trim())throw new at(nA,{field:t});return r.trim()}function ak(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],a=arguments.length>4?arguments[4]:void 0,i=aa(t.err_code),s=i??(a instanceof ar?a.remoteCode:void 0)??-1,o=t.log_id??(a instanceof ar?a.options.logId:void 0),l=a?al(a,an(r)):an(as(i,r)),d={...n?{code:s}:{},errNo:String(s),errMsg:l,...o?{errLogId:o}:{}};return{type:"callback",callbackId:e.callbackId,params:{code:0,data:d,errNo:s,errMsg:l,msg:l}}}async function aN(e,t){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];try{return await t()}catch(t){return ak(e,{},nD,r,t)}}async function aT(e,t){let r=function(e){let t;try{t=JSON.parse(e)}catch{throw new at(nR)}if(!t||"object"!=typeof t||Array.isArray(t))throw new at(nR);let r=t;if("sandbox_cashier"!==r.type)throw new at(nL);let n="string"==typeof r.total_amount?r.total_amount.trim():"";if(!n||!/^\d+$/.test(n))throw new at(nN);return{paymentTypes:function(e){if(!Array.isArray(e)||0===e.length)throw new at(nO);let t=e.map(e=>{if(!e||"object"!=typeof e||Array.isArray(e))throw new at(nR);return{id:aC(e,"id"),name:aC(e,"name")}});if(new Set(t.map(e=>{let{id:t}=e;return t})).size!==t.length)throw new at(nR);return t}(r.pay_types??ah),payOrderNo:aC(r,"pay_order_no"),payStatus:aC(r,"pay_status"),totalAmount:n,tradeNo:aC(r,"trade_no"),type:"sandbox_cashier"}}(e);if(!t.showSandboxCashier)throw new at(n_);if(!await t.showSandboxCashier(r,async e=>{if(!r.paymentTypes.some(t=>{let{id:r}=t;return r===e}))throw new at(nO);try{await af.SandboxPay({trade_no:r.tradeNo,pay_type:e})}catch(e){if(e instanceof ar&&"code"===e.options.errorField&&500===e.remoteCode)throw new ar(e.remoteCode,e.message,{...e.options,operation:"payment"});throw e}}))throw new at(nM)}async function aM(e,t){let r,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"user_info",a=t?"phone":"login";try{r=await af.SandboxIssueLoginCode({aid:"482431",client_key:ax(e),scope:n,source:"jsb",...t?{exchange_type:t}:{}})}catch(e){throw ad(e,a)}var i,s,o=aa(null==(i=r.data)?void 0:i.error_code);let l=aa(o);if(void 0!==l&&0!==l)throw new at(ao(l,a,{errorField:"data.error_code"}));let d=null==(s=r.data)?void 0:s.code;if(!d)throw new at(nZ);return d}async function aR(e){try{let t=void 0!==e.locationInfo,r=await af.UpdateSandboxBusinessInfo({...e.csrPem||t?{csr_pem:e.csrPem??""}:{},...t?{location_info:e.locationInfo}:{},phone_num:e.phoneNum,sandbox_session_id:""});return ap(r),r}catch(t){let e=Error(t.message);throw e.logId=t instanceof ar?t.options.logId:t&&"object"==typeof t&&"logId"in t&&"string"==typeof t.logId?t.logId:void 0,e}}async function aA(e){return aR(e)}async function aP(e){return aR({csrPem:"",locationInfo:e,phoneNum:""})}async function aj(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}r(45249);let aL=["aztec","codabar","code_39","code_93","code_128","data_matrix","ean_8","ean_13","itf","pdf417","qr_code","upc_a","upc_e"],aD={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 aO(e){let t=e.getSupportedFormats;return"function"==typeof t?new Set(await t()):null}function aU(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,aL.includes(r)?"pdf417"===r?"PDF_417":r.toUpperCase():"QR_CODE")}}async function aq(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 a$(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 aB(e,t){e.srcObject=t,await a$(e,()=>e.readyState>=HTMLMediaElement.HAVE_METADATA,["loadedmetadata"],3e3,"Camera stream started, but video metadata was not loaded"),await e.play(),await a$(e,()=>e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA,["loadeddata","canplay","playing"],3e3,"Camera stream started, but no video frame was rendered")}async function aF(e,t){var r;let n,a=globalThis.BarcodeDetector;if(!a)throw Error("BarcodeDetector is not supported in this browser");let i=await aO(a),s=[...new Set((null==(r=e.scanType)?void 0:r.length)?e.scanType.flatMap(e=>aD[e]):aL)].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(aU(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("正在识别图片..."),aq(o,e).then(e=>{let t=e[0];t?i(()=>r(aU(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,aB(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}}let aW="doubao-web-sdk-debugger-vibration-style",aH="doubao-web-sdk-debugger-screen-vibrating",az={heavy:4,light:1,medium:2},aV=0,aG=null;function aJ(e){e.classList.remove(aH),e.style.removeProperty("--doubao-web-sdk-debugger-vibrate-distance"),e.style.removeProperty("--doubao-web-sdk-debugger-vibrate-duration")}function aK(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(aW))return;let e=document.createElement("style");e.id=aW,e.textContent=`
|
|
6
|
+
@keyframes doubao-web-sdk-debugger-screen-vibrate {
|
|
7
|
+
0%, 100% { transform: translate3d(0, 0, 0); }
|
|
8
|
+
12.5% { transform: translate3d(calc(var(--doubao-web-sdk-debugger-vibrate-distance) * -1), 0, 0); }
|
|
9
|
+
25% { transform: translate3d(var(--doubao-web-sdk-debugger-vibrate-distance), 0, 0); }
|
|
10
|
+
37.5% { transform: translate3d(0, calc(var(--doubao-web-sdk-debugger-vibrate-distance) * -1), 0); }
|
|
11
|
+
50% { transform: translate3d(0, var(--doubao-web-sdk-debugger-vibrate-distance), 0); }
|
|
12
|
+
62.5% { transform: translate3d(var(--doubao-web-sdk-debugger-vibrate-distance), var(--doubao-web-sdk-debugger-vibrate-distance), 0); }
|
|
13
|
+
75% { transform: translate3d(calc(var(--doubao-web-sdk-debugger-vibrate-distance) * -1), calc(var(--doubao-web-sdk-debugger-vibrate-distance) * -1), 0); }
|
|
14
|
+
87.5% { transform: translate3d(var(--doubao-web-sdk-debugger-vibrate-distance), 0, 0); }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
.${aH} {
|
|
18
|
+
animation: doubao-web-sdk-debugger-screen-vibrate var(--doubao-web-sdk-debugger-vibrate-duration) linear;
|
|
19
|
+
}
|
|
20
|
+
`,document.head.append(e)})(),window.clearTimeout(aV),n=r||(document.body??document.documentElement),aG&&aG!==n&&aJ(aG),aG=n,aJ(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(aH),aV=window.setTimeout(()=>{aJ(n),aG===n&&(aG=null)},e+50)}}let aX="socketStatusChanged",aQ="socketDataReceived",aZ=1,aY=new Map;function a0(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 a1(){return{...F(),platform:"devtools_web"}}function a2(){var e,t;let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=(null==(e=r.baseAPIRegistry)?void 0:e.fork())??new k(eg);return n.registerMany(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.uiPresenter??nt(),r=e.scanCodePresenter;return{"doubao.request":function(e){if(nd.has(e))return e;let t=(t,r)=>{let n=`wsd-request-${++nu}`,a=t.params??{},i=function(e){try{return ns(e)}catch{return}}(a);nh({phase:"request",request:i??{headers:{},method:"string"==typeof a.method?a.method.toUpperCase():"GET",url:"string"==typeof a.url?a.url:""},requestId:n,...nm()});let s=e=>nh({errorText:e,phase:"failure",requestId:n,...nm()}),o=e=>((null==e?void 0:e.params.code)===1?nh({phase:"response",requestId:n,response:e.params.data,...nm()}):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 nd.add(t),t}(e.requestHandler??(async(e,t,r)=>b(e,await no(e.params,r)))),"doubao.getDeviceInfo":{handler:e=>b(e,a1()),syncResult:a1},"doubao.getNetworkType":{handler:e=>b(e,ng()),syncResult:ng},"doubao.scanCode":async e=>{if(!r)throw Error("Simulator scan-code presenter is unavailable");return b(e,await aF(e.params,r))},"doubao.vibrateLong":async t=>(await void aK(400,3,e.vibrationContainer),b(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;aK(15,az[r],t)}(t.params,e.vibrationContainer),b(t,{})),...(!rG&&"u">typeof window&&(window.addEventListener("pagehide",rK),rG=!0),{"doubao.chooseImage":async e=>{var t;let r,n,a,i,s;return b(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():rX(e.name);return r&&rV.set(t,r),{path:t,size:e.size,type:e.type,originalFileObj:e}})}catch(e){rJ(o),t(e);return}for(rz.push(o);rz.length>20;)rJ(rz.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=>b(e,await rZ(e.params)),"doubao.compressImage":async e=>b(e,await rY(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(),b(e,{})}}),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.chooseLocation??nt().chooseLocation;return{"doubao.getLocation":async t=>{var r;await na(e);let n=await r4.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?b(t,{latitude:(r=n.location).latitude,longitude:r.longitude,timestamp:new Date(r.timestamp).toISOString(),speed:r.speed,accuracy:r.accuracy}):nn(t,n)},"doubao.chooseLocation":async r=>await na(e)?b(r,await t(r.params)):w(r,"user permission denied"),"doubao.openLocation":async t=>{if(!await na(e))return w(t,"user permission denied");var r=t.params;if("number"!=typeof r.latitude||"number"!=typeof r.longitude)throw Error("latitude and longitude must be numbers");let n=new URL("https://www.google.com/maps/search/");return n.searchParams.set("api","1"),n.searchParams.set("query",`${r.latitude},${r.longitude}`),window.open(n.toString(),"_blank","noopener,noreferrer"),b(t,{})},"doubao.startLocationUpdate":async t=>{await na(e);let r=await r4.startLocationUpdates();return"success"===r.status?b(t,{}):nn(t,r)},"doubao.stopLocationUpdate":e=>(r4.stopLocationUpdates(),b(e,{}))}}({...e,chooseLocation:t.chooseLocation}),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.presenter??nt();return{"applet.showToast":e=>(t.showToast(e.params),b(e,{})),"doubao.hideToast":e=>(t.hideToast(),b(e,{})),"doubao.showLoading":e=>(t.showLoading(),b(e,{})),"doubao.hideLoading":e=>(t.hideLoading(),b(e,{})),"doubao.showModal":async e=>b(e,await t.showModal(e.params)),"doubao.showActionSheet":async e=>b(e,await t.showActionSheet(e.params)),"doubao.showBottomSheet":async e=>b(e,await t.showBottomSheet(e.params)),"doubao.enableAlertBeforeUnload":e=>{var t;let r;return t=e.params,nr(),r="string"==typeof t.message?t.message:"",a=e=>(e.preventDefault(),e.returnValue=r,r),window.addEventListener("beforeunload",a),b(e,{})},"doubao.disableAlertBeforeUnload":e=>(nr(),b(e,{})),"doubao.hideKeyboard":e=>(document.activeElement.blur(),b(e,{}))}}({presenter:t}),...{"doubao.connectSocket":(e,t)=>b(e,function(e,t){if("string"!=typeof e.url||!e.url)throw Error("url must be a non-empty string");let r=aZ++,n=new WebSocket(e.url,e.protocols);return n.binaryType="arraybuffer",aY.set(r,n),n.addEventListener("open",()=>{a0(t,aX,{socketTaskId:r,status:"connected",header:{},protocolType:n.protocol})}),n.addEventListener("message",e=>{!function(e,t,r){if("string"==typeof r)return a0(e,aQ,{socketTaskId:t,data:r,dataType:"string"});if(r instanceof ArrayBuffer){let n;a0(e,aQ,{socketTaskId:t,data:(n="",new Uint8Array(r).forEach(e=>{n+=String.fromCharCode(e)}),btoa(n)),dataType:"base64"})}}(t,r,e.data)}),n.addEventListener("close",e=>{aY.delete(r),a0(t,aX,{socketTaskId:r,status:"closed",code:e.code,reason:e.reason,protocolType:n.protocol})}),n.addEventListener("error",()=>{aY.delete(r),a0(t,aX,{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?aY.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?function(e){let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)r[e]=t.charCodeAt(e);return r.buffer}(t.data):t.data}),b(e,{})},"doubao.closeSocket":e=>{var t=e.params;let r=t.socketTaskId,n="number"==typeof r?aY.get(r):void 0;if(!n)throw Error(`socket not found: ${r}`);return n.close(t.code,t.reason),b(e,{})}},...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{"doubao.requestOrder":t=>aN(t,async()=>{let r=await af.SandboxRequestOrder({app_key:ax(e),data:aE(t.params,"data"),db_authorization:aE(t.params,"dbAuthorization")});return r.err_code||!r.order_id?ak(t,r,nG):b(t,{orderId:r.order_id,logId:r.log_id||""})}),"doubao.getOrderPayment":t=>aN(t,async()=>{let r=aE(t.params,"orderId"),n=await af.SandboxGetOrderPayment({app_key:ax(e),aweme_bind_status:!0,order_id:r,platform_signed_pt_code:aI(t.params,"platformSignedPtCode").trim()||void 0});return n.err_code||!n.pay_data?ak(t,n,nP):(await aT(n.pay_data,e),b(t,{orderId:r,logId:n.log_id||""}))}),"doubao.getOrderPaymentWithSign":t=>aN(t,async()=>{let r=aE(t.params,"orderId"),n=await af.SandboxGetOrderPaymentWithSign({app_key:ax(e),aweme_bind_status:!0,order_id:r,sign_data:aE(t.params,"signData"),sign_db_authorization:aE(t.params,"signDbAuthorization")});return n.err_code||!n.pay_data?ak(t,n,nj):(await aT(n.pay_data,e),b(t,{orderId:r,logId:n.log_id||""}))}),"doubao.getPlatformSignInfo":e=>b(e,{signInfo:""}),"doubao.createSignOrder":t=>aN(t,async()=>{let r=await af.SandboxCreateSignOrder({app_key:ax(e),data:aE(t.params,"data"),db_authorization:aE(t.params,"dbAuthorization")});return r.err_code||!r.auth_order_id?ak(t,r,n1):b(t,{authOrderId:r.auth_order_id,logId:r.log_id||""})}),"doubao.sign":t=>aN(t,async()=>{let r=await af.SandboxGetSignPageData({app_key:ax(e),auth_order_id:aE(t.params,"orderId"),aweme_bind_status:!0});return r.err_code||!r.data?ak(t,r,n9,!0):b(t,{})},!0),"doubao.login":async t=>b(t,{code:await aM(e)}),"doubao.loginWithDoubaoWidget":e=>b(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})),b(t,{});let l=aI(o,"code");if(!l)throw new at(nx);try{s=await af.SandboxApiExchangeCode({app_key:ax(e),code:l,version_tag:am})}catch(e){throw ad(e,"login")}return au(s,"login"),null==(r=e.onPrivacyLoginCardClose)||r.call(e,"login"),await (null==(n=e.onGrantingCompleted)?void 0:n.call(e,"login")),b(t,{})},"doubao.getPrivacySetting":async t=>{var r;let n;try{n=await af.SandboxApiCheckPrivacyOrLoginStatus({app_key:ax(e),check_type:1,version_tag:am})}catch(e){throw ad(e,"privacy")}return au(n,"privacy"),b(t,{needAuthorization:(null==(r=n.data)?void 0:r.PrivacyAgreed)===!1})},"applet.agreePrivacyAuthorization":async t=>{var r,n;let a;try{a=await af.SandboxApiAcceptPrivacy({app_key:ax(e)})}catch(e){throw ad(e,"privacy")}return au(a,"privacy"),null==(r=e.onPrivacyLoginCardClose)||r.call(e,"privacy"),await (null==(n=e.onGrantingCompleted)?void 0:n.call(e,"privacy")),b(t,{result:!0})},"applet.getPhoneNumber":async t=>b(t,{code:await aM(e,"profile","user_info,mobile"),message:"success"}),"applet.openLoginPage":t=>{let r=aI(t.params,"url");if(r){var n;null==(n=e.onCustomLoginNavigate)||n.call(e,r)}return b(t,{})},"applet.closePrivacyLoginCard":t=>{var r;return null==(r=e.onPrivacyLoginCardClose)||r.call(e,aI(t.params,"type")),b(t,{})},"applet.reportAppLog":e=>b(e,{}),"applet.open":e=>{let t=aI(e.params,"schema");return t&&window.open(t,"_blank","noopener,noreferrer"),b(e,{})},"doubao.__debuggerUpdateSandboxBusinessInfo":async e=>{let t=e.params,r=aI(t,"csrPem"),n=aI(t,"locationInfo");return b(e,await aR({...r?{csrPem:r}:{},...n?{locationInfo:n}:{},phoneNum:aI(t,"phoneNum")}))},...e.onCustomLoginNavigate?{"doubao.navigateTo":t=>{let r=aI(t.params,"url");if(r){var n;null==(n=e.onCustomLoginNavigate)||n.call(e,r)}return b(t,{})}}:{}}}(e),...function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{"doubao.authorize":async t=>{let r=nf(t.params,"scope");return r?await nv(e,r,!1)?b(t,{}):w(t,"user permission denied"):w(t,"scope is required")},"doubao.operateRecorder":async t=>"start"!==nf(t.params,"operationType")||await nv(e,"scope.record",!1)?b(t,{}):w(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(!eJ(e))throw Error("content items must be objects");if("text"===e.type){if("string"!=typeof e.text||!e.text.trim())throw Error("text content must be a non-empty string");r=!0;continue}if("api/call"===e.type){if(!r)throw Error("api/call content must follow text content");if(!eJ(e.data)||"string"!=typeof e.data.name||!e.data.name.trim()||!eJ(e.data.arguments))throw Error("api/call content must include a name and arguments object");continue}if("responseHint"===e.type){if(!eJ(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,prompt:t.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}}(t.params)),b(t,{})},"doubao.multiMediaBroadcast":async t=>b(t,await rH(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(np())),addEventListener("offline",r),()=>{removeEventListener("online",r),removeEventListener("offline",r)}}},...{"doubao.onLocationChange":e=>r4.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=>r4.subscribeLocation(t=>{"success"!==t.status&&e("user_unauthorized"===t.status?{errMsg:"user permission denied"}:{errCode:t.code,errMsg:t.message})})},...{[aX]:()=>void 0,[aQ]:()=>void 0}},{override:!0}),n}function a3(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{apiRegistry:e.apiRegistry??a2(e),runtimeHost:e.runtimeHost??{mountRuntimeEmptyState:rF},scanCodePresenter:e.scanCodePresenter,uiPresenter:e.uiPresenter}}var a4=r(17228);function a5(e,t,r){null==e||e({category:"mcp",source:"local_mcp",...(null==r?void 0:r.trace)?{trace_id:r.trace.trace_id,trace:r.trace}:{},...t})}function a8(e){return{name:e.name,description:e.description||"",input_schema_json:th(e.inputSchema??{type:"object",additionalProperties:!0})}}async function a6(e,t){let r=new a4.Kj({name:"web-sdk-debugger",version:"0.0.1"},{versionNegotiation:{mode:"auto"}}),n=new a4.jS(new URL(e),{fetch:t.fetcher,requestInit:t.headers?{headers:t.headers}:void 0});try{await r.connect(n)}catch(e){throw await n.close().catch(()=>void 0),await r.close().catch(()=>void 0),e}return{client:r,transport:n}}async function a7(e){await e.transport.close().catch(()=>void 0),await e.client.close().catch(()=>void 0)}let a9="wsd:runtime-console",ie=new WeakMap;function it(e,t){if(!e.dispatchEvent(new CustomEvent(a9,{cancelable:!0,detail:t})))return;let r=ie.get(e)??[];r.push(t),ie.set(e,r)}let ir=["log","info","warn","error","debug"];function ia(){return{entries:[],nextEntryId:0}}function ii(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 is(e){return"number"==typeof e&&Number.isFinite(e)?Math.max(e-1,0):0}function io(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 il(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(is(Number(s))-d,0),columnNumber:void 0===o?0:"number"==typeof(r=Number(o))&&Number.isFinite(r)?Math.max(r-1,0):0}}function id(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=il(r,t);return n?{functionName:e,scriptId:"",...n}:null}let i=il(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|hookConsole|console\.(?:log|info|warn|error|debug)/.test(e.functionName))),i=a.length>0?a:n;return i.length>0?{callFrames:i}:void 0}function iu(e){let t=null==e?void 0:e.callFrames[0];return t?{url:t.url,lineNumber:t.lineNumber,columnNumber:t.columnNumber}:void 0}function ic(e){return e?{callFrames:[{functionName:"",scriptId:"",...e}]}:void 0}function ip(e){return e?`[${e}] `:""}class im{target;store;listeners=new Set;constructor(e,t=ia()){this.target=e,this.store=t,this.target.addEventListener("error",this.handleRuntimeError),this.target.addEventListener(a9,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=ii(n);return this.addEntry("eval","iframe"===t?"iframe":"eval",a),{ok:!0,value:a}}catch(t){let e=ii(t);return this.addEntry("error","eval",e),{ok:!1,value:e}}}destroy(){this.target.removeEventListener("error",this.handleRuntimeError),this.target.removeEventListener(a9,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?io(e.currentTarget):void 0,i=iu(a=id(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:is(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??ic(i)}}:{message:ii(r??t??e),metadata:{location:i,stackTrace:a??ic(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=ie.get(e)??[],ie.delete(e),t))this.addRuntimeConsoleEntry(r)}addRuntimeConsoleEntry(e){var t;let r=e.stackTrace??id(e.stack,{dropFirstFrame:!0,fallbackSourceUrl:io(this.target)}),n=e.location??iu(r),a="string"==typeof e.message?e.message:(e.args??[]).map(ii).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,ir.includes(t)?t:"log"),"runtime",`${ip(s)}${a}`,{args:function(e,t){if(!e||!t)return e;let r=ip(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??ic(n)})}notify(){for(let e of this.listeners)e()}}let ih=new Set(["IFRAME","LINK","SCRIPT","STYLE","TEMPLATE"]),ig=new Set(["data-wsd-node-id"]),iv=new Set(["part","lynx-default-overflow-visible"]),iy=new Set(["style","data-wsd-node-id"]);function i_(e){return e.nodeType===Node.ELEMENT_NODE&&!ih.has(e.tagName)}function ib(e){var t;return e.nodeType===Node.TEXT_NODE&&!!(null==(t=e.textContent)?void 0:t.trim())}function iw(e){return e.nodeType===Node.DOCUMENT_FRAGMENT_NODE?"#shadow-root":e.nodeType===Node.TEXT_NODE?"#text":e.tagName.toLowerCase()}function iS(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 ix(e){return Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0")}function iI(e){let t=e.trim(),r=Number.parseFloat(t);return Number.isFinite(r)&&0===r?"0":t}function iE(e){let t=Number.parseFloat(e);return Number.isFinite(t)?t:0}function iC(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 ik(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 iN(e){return!e.hasAttribute("disabled")&&"true"!==e.getAttribute("aria-disabled")&&(!!(e.isContentEditable||e instanceof HTMLAnchorElement&&e.hasAttribute("href"))||e.tabIndex>=0)}function iT(e){return Array.from(e.attributes).filter(e=>!ig.has(e.name)).map(e=>({name:e.name,value:e.value}))}function iM(e){let t=document.createElement("template");return t.innerHTML=e,t.content}function iR(e){return ig.has(e)||iv.has(e)}function iA(e){return"DIV"===e.tagName&&"page"===e.getAttribute("part")}function iP(e,t){return ig.has(t)||iA(e)&&iR(t)}function ij(e,t){for(let r of t)iP(e,r.name)||e.setAttribute(r.name,r.value)}function iL(e){return iT(e).filter(t=>!iP(e,t.name))}function iD(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 iO(e){return Array.from(e.childNodes).filter(e=>i_(e)||ib(e))}function iU(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 iq(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement??null;for(;t;){if(ih.has(t.tagName))return!0;t=t.parentElement}return!1}class i${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?iT(n):[]}(t),a=null==r?void 0:r.trim();return this.editElementAttributes(e,e=>{a&&!iP(e,a)&&e.removeAttribute(a),ij(e,n)})}setAttributeValue(e,t,r){let n=t.trim();return n?this.editElementAttributes(e,e=>{if(iP(e,n))return!1;e.setAttribute(n,r)}):[]}removeAttribute(e,t){let r=t.trim();return r?this.editElementAttributes(e,e=>{if(iP(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(iA(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=iO(r).map(e=>this.getNodeId(e)),n=iM(t);return r.replaceChildren(...Array.from(n.childNodes)),[this.getChildListMutation(r,e,this.getInsertedNodeMutations(r,null,iO(r)))]}if(r instanceof Element&&iA(r)){let n=iL(r),a=iO(r).map(e=>this.getNodeId(e));!function(e,t){let r=iM(t),n=r.firstElementChild;if(!n)return e.replaceChildren(...Array.from(r.childNodes));for(let t of Array.from(e.attributes))iR(t.name)||e.removeAttribute(t.name);ij(e,iT(n)),e.replaceChildren(...Array.from(n.childNodes))}(r,t);let i=this.getInsertedNodeMutations(r,null,iO(r));return[...iD(e,n,iL(r)),this.getChildListMutation(r,a,i)]}let n=r.parentNode;if(!n)return[];let a=this.getPreviousInspectableSiblingId(r),i=iM(t),s=iO(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=>{let i;for(let s of(i_(a)&&(i=a.getBoundingClientRect()).width>0&&i.height>0&&e>=i.left&&e<=i.right&&t>=i.top&&t<=i.bottom&&(r=a),Array.from(a.childNodes)))i_(s)&&n(s)})(a),r),o=i?iU(i,e,t):iU(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&&!i_(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(!_||!_.isConnected)return null;let b=_.getBoundingClientRect(),w=t.getBoundingClientRect(),S=t.offsetWidth?w.width/t.offsetWidth:1,x=t.offsetHeight?w.height/t.offsetHeight:1,I=b.width/S,E=b.height/x,C=getComputedStyle(_),k=C.backgroundColor.trim(),N=(r=C.paddingTop,n=C.paddingRight,(a=[r,n,C.paddingBottom,C.paddingLeft].map(iI)).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:(b.left-w.left)/S,top:(b.top-w.top)/x,width:I,height:E,nodeName:iw(_),selector:(i=_.id.trim(),{tagName:iw(_),...i?{id:i}:{},classNames:Array.from(_.classList).filter(Boolean)}),boxModel:(s=iE(C.borderTopWidth),o=iE(C.borderRightWidth),l=iE(C.borderBottomWidth),d=iE(C.borderLeftWidth),u=iE(C.paddingTop),c=iE(C.paddingRight),p=iE(C.paddingBottom),m=d+iE(C.paddingLeft),{content:{left:m,top:h=s+u,width:Math.max(0,I-m-o-c),height:Math.max(0,E-h-l-p)}}),dimensions:`${iS(I)} \xd7 ${iS(E)}`,styles:[...k?[{name:"Background",value:(f=(g=k.trim()).match(/^rgb\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*\)$/i),v=g.match(/^rgba\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d?(?:\.\d+)?)\s*\)$/i),(y=f??(v&&1===Number(v[4])?v:null))?`#${ix(Math.round(Number(y[1])))}${ix(Math.round(Number(y[2])))}${ix(Math.round(Number(y[3])))}`:g),swatch:k}]:[],...N?[{name:"Padding",value:N}]:[]],accessibility:{name:iC(_),role:ik(_),keyboardFocusable:iN(_)}}}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=iL(r);return!1===t(r)?[]:iD(e,n,iL(r))})}getPreviousInspectableSiblingId(e){let t=e.parentNode;if(!t)return null;let r=iO(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:iO(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:iw(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:iw(e),attributes:e instanceof Element?iT(e):[],children:iO(e).map(e=>this.serializeNode(e)),...n?{accessibility:{name:iC(n),role:ik(n),keyboardFocusable:iN(n)}}:{}}}observe(){let e=this.target.shadowRoot??this.target;this.mutationObserver=new MutationObserver(e=>{e.some(e=>(function(e){if(iq(e.target))return!1;if("attributes"===e.type)return e.target instanceof Element&&i_(e.target)&&!iy.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!iq(t)&&(!!(i_(t)||ib(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 iB="data-wsd-node-id";function iF(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 iW(e){return"u">typeof CSSStyleRule&&e instanceof CSSStyleRule}function iH(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 iz(e){return`${e.name}: ${e.value}${e.priority?` !${e.priority}`:""};`}function iV(e){return e.map(e=>({...e}))}function iG(e){return`inline:${e}`}function iJ(e){return`rule:${e}`}class iK{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=iG(e);this.rememberStyleTextDeclaration(s,iF(i.style),t,r,n,a),iH(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&&iH(r.style,e.name,e.value,e.priority);this.styleTextSnapshots.set(iG(e),iV(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=iJ(t);if(this.rememberStyleTextDeclaration(o,s?iF(s.style):[],r,n,a,i),!i){if(s)try{iH(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{iH(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(iJ(t),iV(r)),!n)return void this.setOverrideDeclarations(e,a);try{for(let e of(n.style.cssText="",a))iH(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(iz).join(" ")} }`;try{let e=i.cssRules.length;i.insertRule(s,e);let t=i.cssRules[e];if(t&&iW(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(iB,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(iB,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(iB);this.overriddenElements.clear(),this.rules.clear()}getInlineStyle(e,t,r){return{id:"inline",selectorText:"element.style",editable:!0,declarations:this.getStyleTextSnapshot(iG(e))??iF(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(iW(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(iJ(n))??iF(e.style)}}getStyleTextSnapshot(e){let t=this.styleTextSnapshots.get(e);return t?iV(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)??iV(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`[${iB}="${t}"] {
|
|
21
|
+
${n}
|
|
22
|
+
}`});this.getOverrideStyleElement().textContent=t.join("\n\n")}}class iX{listeners=new Set;elementInspector;styleInspector;consoleRecorder;selectedNodeId=null;consoleUnsubscribe=null;constructor(e,t={}){this.elementInspector=new i$(e,()=>this.notify({type:"document"})),this.styleInspector=new iK(e,this.elementInspector),this.consoleRecorder=new im(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 iQ(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}}function iZ(e){return"object"==typeof e&&null!==e||"function"==typeof e}function iY(e){return Array.isArray(e)?"array":void 0}function i0(e){return Array.isArray(e)?`Array(${e.length})`:i1(e)}function i1(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 i2(e,t){return{name:e,type:i3(t),subtype:iZ(t)?iY(t):void 0,value:iZ(t)?i0(t):String(t)}}function i3(e){return null===e?"object":typeof e}function i4(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:i3(e),unserializableValue:r,description:r};if("symbol"==typeof e)return{type:"symbol",description:String(e)};if(iZ(e)){let r;return{type:"function"==typeof e?"function":"object",subtype:"function"==typeof e?void 0:iY(e),className:"function"==typeof e?"Function":i1(e),description:"function"==typeof e?e.toString():i0(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:iY(e),description:i0(e),overflow:r.length>5,properties:r.slice(0,5).map(t=>{try{let r=Object.getOwnPropertyDescriptor(e,t);return i2(t,r&&"value"in r?r.value:void 0)}catch{return i2(t,void 0)}})})}}return{type:i3(e),value:e,description:String(e)}}function i5(e,t){return(e.args??[e.message]).map(e=>i4(e,t))}function i8(e,t){return{startLine:0,startColumn:e,endLine:0,endColumn:t}}function i6(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=i8(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:i8(0,Math.max(0,n.trim().length)),shorthandEntries:[],cssProperties:a}}function i7(e){let t=e.indexOf(":");return t<0?{kind:e,id:""}:{kind:e.slice(0,t),id:e.slice(t+1)}}function i9(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(...se(r.slice(i,t.index),!0)),n.push(...se(t[1],!1)),i=t.index+t[0].length;return n.push(...se(r.slice(i),!0)),n}function se(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}let st=new Map([["x-view","view"],["x-text","text"]]);function sr(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 sn(e){return sr(e)?e.attributes.filter(e=>"part"!==e.name&&"lynx-default-overflow-visible"!==e.name):e.attributes}function sa(e){return sn(e).flatMap(e=>[e.name,e.value])}function si(e){return sr(e)?"page":st.get(e.name)??e.name}function ss(e,t){var r;return(null==(r=e.attributes.find(e=>e.name===t))?void 0:r.value)||void 0}function so(e,t){return e.type===t.type&&e.name===t.name&&(t.id?ss(e,"id")===t.id:!t.className||ss(e,"class")===t.className)}function sl(e,t){let r=Number(e);return Number.isFinite(r)?r<0?1/0:r:t}function sd(e){return e===1/0?e:Math.max(0,e-1)}function su(e){if("text"===e.type)return e.textContent??"";if("document"===e.type)return sc(e);let t=sn(e).map(e=>` ${e.name}="${e.value}"`).join(""),r=e.children.map(e=>su(e)).join(""),n=si(e);return`<${n}${t}>${r}</${n}>`}function sc(e){return e.children.map(e=>su(e)).join("")}function sp(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 sm="__wsd_document__";function sh(e){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation()}let sg="wsd-main-frame";function sf(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function sv(e){var t;let r;if(e instanceof ArrayBuffer)return{base64Encoded:!0,body:tr(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 sy(e){throw Object.assign(Error(e),{code:-32602})}function s_(e,t,r){return e??sy(null===e?r:t)}class sb{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,nl.add(r),()=>nl.delete(r)),this.enabledSessions.set(this.getSessionKey(t),{maxPostDataSize:sf(null==e?void 0:e.maxPostDataSize,65536),maxTotalBufferSize:sf(null==e?void 0:e.maxTotalBufferSize,262144e3)}),this.refreshBufferLimit(),{}}disable(e){let t=this.getSessionKey(e);for(let[e,r]of(this.enabledSessions.delete(t),this.requests))r.sessions.delete(t),0===r.sessions.size&&this.deleteRequest(e,r);if(0===this.enabledSessions.size){var r;null==(r=this.unsubscribe)||r.call(this),this.unsubscribe=void 0,this.clearRequests()}else this.refreshBufferLimit();return{}}getRequestPostData(e,t){let r=s_(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=s_(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:sv(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:sg,initiator:{type:"script"},loaderId:sg,redirectHasExtraInfo:!1,request:{...i,hasPostData:!!n,headers:e.request.headers,initialPriority:"High",isSameSite:!0,method:e.request.method,mixedContentType:"none",...a?{postData:n.body}:{},referrerPolicy:"no-referrer"},requestId:e.requestId,timestamp:e.timestamp,type:"XHR",wallTime:e.wallTime}},this.getSessionId(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=sv(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:sg,hasExtraInfo:!1,loaderId:sg,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,this.getSessionId(r))}getRequest(e,t){let r="string"!=typeof(null==e?void 0:e.requestId)||0===e.requestId.length?sy("requestId must be a non-empty string"):e.requestId,n=this.requests.get(r);return(null==n?void 0:n.sessions.has(this.getSessionKey(t)))?n:sy(`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}getSessionKey(e){return e??""}getSessionId(e){return e||void 0}}class sw{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(sm),n=sd(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=sd(t),i=t>0?e.children.map(e=>this.toCdpNode(e,a,n)):void 0,s="text"===e.type,o="document"===e.type,l=si(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?sa(e):void 0,children:i};return this.cdpNodes.set(n,d),d}}function sS(e){return e.map(e=>({...e}))}function sx(e){return"attributes"===e.type||"characterData"===e.type}class sI{adapter;consoleAdapter=null;appAdapter=null;appTarget=null;target;listeners=new Set;options;nodeStore=new sw;network;consoleStore=ia();appConsoleStore=ia();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 sb((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 iX(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 iX(e,{consoleStore:this.options.preserveConsoleOnTargetChange?this.consoleStore:void 0})}createAppTargetAdapter(e){return new iX(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),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.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(this.getSessionKey(e.sessionId)),this.emitRuntimeExecutionContext(e.sessionId),this.emitNewConsoleEntriesForSession(e.sessionId),this.getAppAdapter(),this.emitNewConsoleEntriesForSession(e.sessionId,"app"),{};case"Runtime.disable":return this.runtimeEnabledSessions.delete(this.getSessionKey(e.sessionId)),this.knownConsoleEntryIdsBySession.delete(this.getSessionKey(e.sessionId)),{};case"Debugger.enable":return this.debuggerEnabledSessions.add(this.getSessionKey(e.sessionId)),this.getAppAdapter(),this.emitNewConsoleEntries("app"),this.emitSourceScripts(e.sessionId),{debuggerId:"wsd-debugger"};case"Debugger.disable":return this.debuggerEnabledSessions.delete(this.getSessionKey(e.sessionId)),this.parsedScriptIdsBySession.delete(this.getSessionKey(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.adapter.getDocument(),n=sl(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=sl(null==e?void 0:e.depth,1),i=this.adapter.getDocument(),s=n===sm?null:this.findInspectorNode(n),o=n===sm?i?[this.nodeStore.toCdpNode(i,sd(a),r)]:[]:(null==s?void 0:s.children.map(e=>this.nodeStore.toCdpNode(e,sd(a),r)))??[];return this.emit({method:"DOM.setChildNodes",params:{parentId:r,nodes:o}},t),{}}pushNodesByBackendIdsToFrontend(e,t){let r=this.adapter.getDocument();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=sp(e,t);if(!n)return!1;let a=this.nodeStore.getCdpNodeId(sm);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=sp(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.adapter.getDocument(),r=t?sp(t,e):null;if(r){let e=r.map(e=>({type:e.type,name:e.name,className:ss(e,"class"),id:ss(e,"id")}));return this.selectedNodeSignaturePath=e,e}return null}findInspectorNodeBySignaturePath(e,t){if(!(null==t?void 0:t.length)||!so(e,t[0]))return null;let r=e;for(let e of t.slice(1)){let t=r.children.find(t=>so(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.adapter.getDocument();return{node:r===sm&&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?sa(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.adapter.getDocument();return{outerHTML:t===sm&&n?su(n):r?su(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(sx),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?sc(e):su(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:i6(`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?i6(`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=i9(String(e.text??"")),{id:a,kind:i}=i7(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=i9(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:i6("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}=i7(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(!iZ(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=i4(n.value,t),a.writable=n.writable),a})}catch{return[]}}(t,this.remoteObjectStore),internalProperties:function(e,t){if(!iZ(e))return[];let r=Object.getPrototypeOf(e);return r?[{name:"[[Prototype]]",value:i4(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)){let t=this.getSessionId(e);this.emit({method:"Runtime.executionContextsCleared"},t),this.emitRuntimeExecutionContext(t),this.emitNewConsoleEntriesForSession(t,"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&&(sh(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=>{sh(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.adapter.getDocument();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();return i&&s?(this.options.onHighlightChange(this.adapter.getNodeHighlight(i,s)),{cdpNodeId:this.nodeStore.getCdpNodeId(i),inspectorNodeId:i}):(this.options.onHighlightChange(null),null)}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:sS(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}=i7(e.styleSheetId);this.isApplyingStyleEdit=!0;try{"inline"===r?this.adapter.setInlineDeclarations(t,sS(e.previousDeclarations)):"rule"===r&&this.adapter.setRuleDeclarations(e.nodeId,t,sS(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}}}findInspectorNode(e){let t=this.adapter.getDocument();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}=i7(e),s=t.map(e=>({name:e.name,value:e.value,priority:e.priority,active:e.active}));if("inline"===i)return i6(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 i6(e,(null==r?void 0:r.declarations)??s)}return i6(e,s)}getDeclarationsForStyleSheet(e){var t,r;let{id:n,kind:a}=i7(e);if("inline"===a)return sS((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 sS((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:i8(0,e.length)}],text:e}}toCdpRulePayload(e){let t=`rule:${e.id}`,r=i6(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:i5(e,this.remoteObjectStore)};return e.location&&(r.url=e.location.url,r.lineNumber=e.location.lineNumber,r.columnNumber=e.location.columnNumber),r}getSessionKey(e){return e??""}getSessionId(e){return e||void 0}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 iQ(e);t===this.sourceLoadId&&(r&&this.sourceScriptsById.set(this.getScriptId(r.url),r),this.emitSourceScriptsForEnabledSessions())}emitSourceScriptsForEnabledSessions(){for(let e of this.debuggerEnabledSessions)this.emitSourceScripts(this.getSessionId(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.getSessionKey(t),i=this.getScriptId(e),s=this.getParsedScriptIds(a);if(!this.debuggerEnabledSessions.has(a)||s.has(i))return;s.add(i);let o=(null==r?void 0:r.content.split("\n"))??[""];this.emit({method:"Debugger.scriptParsed",params:{scriptId:i,url:r?"":e,startLine:0,startColumn:0,endLine:r?o.length-1:1,endColumn:r?(null==(n=o.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(this.getSessionId(t),e)}emitNewConsoleEntriesForSession(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"current",r=this.getSessionKey(e);if(!this.runtimeEnabledSessions.has(r))return;let n="app"===t?this.appConsoleStore.entries:this.getConsoleAdapter().getConsoleEntries(),a=this.getKnownConsoleEntryIds(r,t);for(let t of n){var i;if(a.has(t.id)||(a.add(t.id),"host"===t.source))continue;let r=this.toCdpStackTrace(t.stackTrace),n={type:"warn"===(i=t.level)?"warning":"eval"===i?"log":i,args:i5(t,this.remoteObjectStore),executionContextId:1,timestamp:t.timestamp};r&&(n.stackTrace=r),this.emit({method:"Runtime.consoleAPICalled",params:n},e)}}emitSelectedStyleInvalidated(){let e=this.adapter.getSelectedNodeId(),t=e?this.nodeStore.getExistingCdpNodeId(e):void 0;t&&this.emit({method:"DOM.inlineStyleInvalidated",params:{nodeIds:[t]}})}}let sE="AppletJSModule",sC=["log","info","warn","error","debug"];function sk(e,t,r){if("log"!==e)return null;let n=tc(t)&&("string"==typeof t.message||Array.isArray(t.args))?{level:sC.includes(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?r===sE?n:null:r!==sE?null:{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)}}class sN{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):it(this.current,e)}flush(){if(this.current)for(let e of this.runtimeConsoleEvents.splice(0))it(this.current,e)}}let sT=new Set(["doubao.navigateTo","doubao.redirectTo","doubao.reLaunch","doubao.navigateBack","doubao.exitApp","doubao.close"]);function sM(e){return"string"==typeof e&&e.trim()?e.trim().replace(/^\/+/,""):void 0}function sR(e){return sM(null==e?void 0:e.path)??sM(null==e?void 0:e.id)}class sA{container;fileSystemNamespace;nativeModulesCallHandler;webSdkDebugger;onExitApp;onError;apiEnvironment;previewTarget=new sN;appPreviewTarget=new sN;pagePathsByTarget=new WeakMap;targetObserver=null;runtime=null;runtimeManifestUrl=null;lastRenderOptions=null;isRuntimeTargetChanging=!1;deferredPagePath;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??a3(),"u">typeof MutationObserver&&(this.targetObserver=new MutationObserver(this.handleRuntimeContainerMutation),this.targetObserver.observe(this.container,{childList:!0}))}render(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=this.webSdkDebugger.getState(),n=!t.entry&&(null==(e=r.pageSelection)?void 0:e.routeUrl)?e3({url:r.pageSelection.routeUrl},r.manifest):void 0,a=(null==n?void 0:n.entry)??function(e,t){if(t.entry)return t.entry;if(!e.pageSelection)throw Error("No page selected");return e.pageSelection.item}(r,t),i=t.device??rj["0"],s=(null==n?void 0:n.initData)??t.initData??{},o=n?rU(i,{...t.globalProps,...n.globalProps}):t.globalProps??rU(i),l=this.getRuntime(r),d=sR(a);this.lastRenderOptions=t,this.isRuntimeTargetChanging=!0,this.deferredPagePath=d;try{let e=l.replacePage({entry:a,initData:s,globalProps:o,pageCapsule:t.pageCapsule??{statusBarHeight:i.statusBarHeight}});return this.bindPageTarget(e.element,d??sR(e.entry)),this.previewTarget.set(e.element),e.element}catch(e){throw this.syncCurrentRuntimeTarget(),e}finally{this.isRuntimeTargetChanging=!1,this.deferredPagePath=void 0,this.previewTarget.flush()}}getCurrentTarget(){return this.previewTarget.current}getCurrentAppTarget(){return this.appPreviewTarget.current}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)}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"))}}reload(){var e;null==(e=this.runtime)||e.reload(),this.previewTarget.notify()}clear(){var e;null==(e=this.runtime)||e.clear(),this.deferredPagePath=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,runtimeHost:{...this.apiEnvironment.runtimeHost,mountRuntimeEmptyState:e=>rF(e,()=>this.reopenCurrentPage())}};return this.runtime=new e7(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;let i=function(e,t,r){if("AppletBridgeModule"===r&&"postMessage"===e&&"object"==typeof t&&null!==t&&"call"===t.type&&"string"==typeof t.name&&sT.has(t.name))return t.name}(e,t,r);i&&(this.deferredPagePath=this.getNavigationPagePath(t),this.scheduleRuntimeTargetSync("doubao.exitApp"===i?this.onExitApp:void 0));let s=sk(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){var t;this.isRuntimeTargetChanging=!0,t=()=>{this.syncCurrentRuntimeTarget(),this.isRuntimeTargetChanging=!1,this.deferredPagePath=void 0,this.previewTarget.flush(),null==e||e()},"function"==typeof queueMicrotask?queueMicrotask(t):Promise.resolve().then(t)}syncCurrentRuntimeTarget(){var e;let t=(null==(e=this.runtime)?void 0:e.currentPage)??null,r=(null==t?void 0:t.element)??null;(r&&this.bindPageTarget(r,this.getCurrentPagePath()),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){e&&t&&this.pagePathsByTarget.set(e,t)}getNavigationPagePath(e){var t;if("object"!=typeof e||null===e)return;let r=null==(t=e.params)?void 0:t.url;if("string"==typeof r)try{return sR(e3({url:r},this.webSdkDebugger.getState().manifest).entry)}catch{return sM(r.split("?")[0])}}getCurrentPagePath(){var e;let t=null==(e=this.runtime)?void 0:e.currentPage;return sR(null==t?void 0:t.entry)??sM(null==t?void 0:t.route)??sM(null==t?void 0:t.pageId)}getRuntimeConsolePagePath(e){var t,r;if((null==e?void 0:e.containerType)!=="PAGE")return;let n=this.pagePathsByTarget.get(e.element)??this.deferredPagePath??this.getCurrentPagePath();return this.bindPageTarget(null==(r=this.runtime)||null==(t=r.currentPage)?void 0:t.element,n),n}}class sP{container;fileSystemNamespace;nativeModulesCallHandler;webSdkDebugger;onError;apiEnvironment;previewTarget=new sN;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??a3()}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??rD,a=tu(e.initData??{}),i=e.globalProps??rq(n);this.clear(),this.widget=new eZ({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)=>{var n;let a=sk(e,t,r);return a?void this.previewTarget.dispatch(a):null==(n=this.nativeModulesCallHandler)?void 0:n.call(this,e,t,r)}}var sj=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 sL(e){let t=(0,tt.useRef)(e);t.current=e;let r=(0,tt.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 sD={revision:0,phase:"idle",canCancel:!1,canRetry:!1},sO=(0,tt.createContext)({});function sU(e){let{capability:t,children:r,getAppIdentity:n}=e;return(0,i.jsx)(sO.Provider,{value:{capability:t,getAppIdentity:n},children:r})}async function sq(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 s$(){var e,t,r,n,a,s,o;let{capability:l,getAppIdentity:d}=(0,tt.useContext)(sO),[u,c]=(0,tt.useState)(!1),[p,m]=(0,tt.useState)(sD),[h,g]=(0,tt.useState)(),[f,v]=(0,tt.useState)("modern"),[y,_]=(0,tt.useState)(),b=(0,tt.useId)(),w=(0,tt.useRef)(!1),S=(0,tt.useRef)(sD),x=(0,tt.useRef)(null),I=sL(e=>{e.revision<S.current.revision||(S.current=e,m(e))}),E=sL(async(e,t)=>{if(!l)throw Error("真机调试能力不可用");return sq(await fetch(e,{cache:"no-store",...t,headers:{Accept:"application/json","X-DBX-Real-Device-Token":l.accessToken,...(null==t?void 0:t.headers)??{}}}))}),C=sL(async()=>{if(l)try{let e=await E(l.stateEndpoint);I(e),g(void 0)}catch(e){g(e instanceof Error?e.message:String(e))}}),k=sL(async()=>{if(l){g(void 0);try{let e=await E(l.startEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"});if(!w.current&&e.operationId&&e.canCancel&&"web"===e.owner)return void await E(l.cancelEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({operationId:e.operationId})}).catch(()=>void 0);I(e)}catch(e){g(e instanceof Error?e.message:String(e))}}}),N=sL(async()=>{let e=S.current;if(l&&e.operationId&&e.canCancel&&"web"===e.owner)try{let t=await E(l.cancelEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({operationId:e.operationId})});I(t)}catch{}}),T=sL(()=>{w.current=!1,c(!1),N()});if((0,tt.useEffect)(()=>{if(!u||!l)return;C();let e=window.setInterval(()=>void C(),l.pollIntervalMs);return()=>window.clearInterval(e)},[l,u,C]),(0,tt.useEffect)(()=>{if(!u)return;let e=e=>{var t;(null==(t=x.current)?void 0:t.contains(e.target))||T()},t=e=>{"Escape"===e.key&&T()};return window.addEventListener("pointerdown",e),window.addEventListener("keydown",t),()=>{window.removeEventListener("pointerdown",e),window.removeEventListener("keydown",t)}},[T,u]),(0,tt.useEffect)(()=>{p.qr&&"modern"===f&&!p.qr.modernAvailable&&p.qr.legacyAvailable&&v("legacy")},[f,p.qr]),(0,tt.useEffect)(()=>{let e=!1,t=u&&!!l&&!!p.operationId&&"connected"===p.phase&&"qr"===p.connectionMode;if(!u||!l||!p.operationId||"waiting_for_scan"!==p.phase||!p.qr||("modern"===f?!p.qr.modernAvailable:!p.qr.legacyAvailable)){t||_(void 0);return}_(void 0),g(void 0);let r=new URL(l.qrEndpoint,window.location.origin);return r.searchParams.set("operationId",p.operationId),r.searchParams.set("kind",f),fetch(r,{cache:"no-store",headers:{"X-DBX-Real-Device-Token":l.accessToken}}).then(e=>{if(!e.ok)throw Error("二维码暂不可用");return e.blob()}).then(t=>{e||_(URL.createObjectURL(t))}).catch(t=>{e||g(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[l,u,f,p.connectionMode,p.operationId,p.phase,null==(e=p.qr)?void 0:e.legacyAvailable,null==(t=p.qr)?void 0:t.modernAvailable,null==(r=p.qr)?void 0:r.revision]),(0,tt.useEffect)(()=>{if(y)return()=>URL.revokeObjectURL(y)},[y]),!l)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"准备开始真机调试"}}(p),R=null==(n=p.progress)?void 0:n.percentage,A="number"==typeof R&&"downloading"===p.phase,P="waiting_for_scan"===p.phase&&!!p.qr,j=!!y&&(P||"connected"===p.phase&&"qr"===p.connectionMode),L="failed"===p.phase||"timed_out"===p.phase||!!h,D=L?"二维码暂不可用":"connected"===p.phase?"连接成功请勿重复扫码。":"准备完成后可扫码",O=null==d?void 0:d(),U=[null==O||null==(a=O.appName)?void 0:a.trim(),null==O||null==(s=O.appKey)?void 0:s.trim()].filter(Boolean).join(" · ");return(0,i.jsxs)("div",{className:"wsd-real-device-wrapper",ref:x,children:[(0,i.jsx)("button",{"aria-expanded":u,"aria-haspopup":"dialog","aria-label":"真机调试","aria-pressed":u,"aria-describedby":b,className:(0,eK.$)("wsd-device-toolbar-icon",u&&"is-active"),onClick:()=>{u?T():(v("modern"),w.current=!0,c(!0),k())},type:"button",children:(0,i.jsx)(sj,{"aria-hidden":"true"})}),(0,i.jsx)("span",{className:"wsd-real-device-tooltip",id:b,role:"tooltip",children:"真机调试"}),u?(0,i.jsxs)("dialog",{"aria-label":"真机调试",className:"wsd-real-device-popover",open:!0,children:[(0,i.jsxs)("header",{className:"wsd-real-device-header",children:[(0,i.jsx)("h2",{children:"真机调试"}),(0,i.jsx)("p",{children:"使用已登录的客户端扫码,创建新的真机调试对话"})]}),(0,i.jsx)("div",{className:(0,eK.$)("wsd-real-device-qr",!j&&"is-locked"),children:j&&y?(0,i.jsx)("img",{alt:"modern"===f?"新版客户端真机调试二维码":"旧版客户端真机调试二维码",src:y}):(0,i.jsxs)("div",{className:"wsd-real-device-placeholder",children:[(0,i.jsx)("span",{"aria-hidden":"true",children:L?"!":"⌁"}),(0,i.jsx)("strong",{children:D})]})}),P&&(null==(o=p.qr)?void 0:o.modernAvailable)&&p.qr.legacyAvailable?(0,i.jsx)("button",{className:"wsd-real-device-client-switch",onClick:()=>v(e=>"modern"===e?"legacy":"modern"),type:"button",children:"modern"===f?"旧版客户端":"返回新版客户端"}):null,A?(0,i.jsx)("div",{className:"wsd-real-device-progress","aria-label":`下载进度 ${Math.round(R)}%`,children:(0,i.jsx)("span",{style:{width:`${Math.max(0,Math.min(100,R))}%`}})}):null,(0,i.jsxs)("div",{className:"wsd-real-device-details",children:[U?(0,i.jsx)("div",{"aria-label":"小程序信息",className:"wsd-real-device-app-identity",title:U,children:U}):null,"waiting_for_scan"!==p.phase?(0,i.jsxs)("div",{className:(0,eK.$)("wsd-real-device-status",L&&"is-error","connected"===p.phase&&"is-success"),children:[["preparing","downloading","installing_tool","reusing_client","waiting_for_scan","waiting_for_install","launching_tool"].includes(p.phase)&&!A?(0,i.jsx)("span",{className:"wsd-real-device-spinner","aria-hidden":"true"}):null,(0,i.jsxs)("div",{children:[(0,i.jsx)("strong",{children:h||M}),"connected"===p.phase?(0,i.jsx)("small",{children:"扫码成功"}):null,"existing_client"===p.connectionMode?(0,i.jsx)("small",{children:"已复用当前连接,无需扫码"}):null]})]}):null]}),(p.canRetry||h)&&L?(0,i.jsx)("button",{className:"wsd-real-device-retry",onClick:()=>void k(),type:"button",children:"重新尝试"}):null]}):null]})}let sB=(0,tt.createContext)(null);function sF(e){let t=function(e){let t=(0,tt.useContext)(sB),r=e??t;if(!r)throw Error("WebSdkDebuggerProvider is missing");return r}(e),r=(0,tt.useCallback)(e=>t.subscribe(e),[t]),n=(0,tt.useCallback)(()=>t.getState(),[t]);return(0,tt.useSyncExternalStore)(r,n,n)}function sW(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 sH(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 sz(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,tt.useRef)(null),[f,v]=(0,tt.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=sL(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=sL(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,eK.$)("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)(sW,{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)(sH,{focusable:o.accessibility.keyboardFocusable})})]})]})]}):null]})]}):null,l]})})})}function sV(e){let t,r,n,{cashier:a,onCancel:s,onConfirm:o}=e,[l,d]=(0,tt.useState)(!1),[u,c]=(0,tt.useState)(""),[p,m]=(0,tt.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(al(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 sG(){let[e,t]=(0,tt.useState)(),r=(0,tt.useRef)(null),n=(0,tt.useRef)(null),a=(0,tt.useRef)(!1),i=sL((e,a)=>r.current?Promise.reject(Error("Sandbox cashier is already open")):new Promise(i=>{r.current=i,n.current=a,t(e)})),s=sL(e=>{let a=r.current;a&&(r.current=null,n.current=null,t(void 0),a(e))}),o=sL(()=>{a.current||s(!1)}),l=sL(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,tt.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 sJ=new WeakMap;async function sK(e,t,r){sJ.set(e,t);try{await e.sendSimulatorQuery(r)}finally{sJ.get(e)===t&&sJ.delete(e)}}function sX(e,t){let r=sJ.get(e);if(r&&(!t||r===t))return sJ.delete(e),e.cancelSimulatorQuery(),r}var sQ=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 sZ(){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 sY(e){let{className:t,fallback:r,src:n}=e,[a,s]=(0,tt.useState)(!1);return(0,tt.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 s0(e){let t=Number(e);if(!Number.isFinite(t))return;let r=new Date(t);return Number.isFinite(r.getTime())?r:void 0}function s1(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)(sZ,{}),(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)(sQ,{"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=s0(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=s0(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)(sY,{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 s2=new Set([1,2,3]);function s3(e){return e.filter(e=>1!==e.display_status&&s2.has(e.status))}function s4(e){let{onAction:t,onClose:r,onRemove:n,removingTaskIds:a,tasks:s}=e,o=s3(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,tt.useEffect)(()=>{let e=e=>{"Escape"===e.key&&r()};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[r]),(0,tt.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,eK.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)(sY,{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 s5={hasUnreadNotices:!1,hasUnreadTasks:!1,markServiceNoticesRead:()=>void 0,markTasksRead:()=>void 0,notices:[],removeTask:async()=>void 0,removingTaskIds:new Set,status:"unavailable",tasks:[]},s8=(0,tt.createContext)(s5);function s6(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 s7(e){if(eJ(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 s9(e){if(eJ(e)&&("card_delta"===e.type||"get_simulator_card_snapshots"===e.type)&&eJ(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 oe(e){let{children:t,enabled:r,eventsEndpoint:n,onMessage:a,webSdkDebugger:s}=e,[o,l]=(0,tt.useState)([]),[d,u]=(0,tt.useState)([]),[c,p]=(0,tt.useState)(!1),[m,h]=(0,tt.useState)(!1),[g,f]=(0,tt.useState)(r&&n?"loading":"unavailable"),[v,y]=(0,tt.useState)(new Set),_=(0,tt.useRef)(new Map),b=(0,tt.useRef)(new Map),w=(0,tt.useRef)(new Map),S=(0,tt.useRef)(new Map),x=(0,tt.useRef)({notice:void 0,task:void 0}),I=(0,tt.useRef)({}),E=(0,tt.useRef)(new Set),C=(0,tt.useRef)(0),k=(0,tt.useRef)(a);k.current=a;let N=sL(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(E.current.has(t))return;E.current.add(t);let r=(()=>{try{if(!s)throw Error("Web SDK debugger is unavailable");return{card_snapshots:ry(s.getState().simulator.messages)}}catch{return{error:{code:"SNAPSHOT_COLLECTION_FAILED",message:"failed to collect simulator state"}}}})();await aw(t,r)}),T=sL(()=>{l([..._.current.values()].sort((e,t)=>Number(e.created_at_ms)-Number(t.created_at_ms)))}),M=sL(()=>{u([...b.current.values()].sort((e,t)=>Number(t.updated_at_ms)-Number(e.updated_at_ms)))}),R=sL(e=>{let t=!1;for(let r of e.notices??[]){let e=w.current.get(r.notice_id);(void 0===e||s6(r.revision,e)>0)&&(w.current.set(r.notice_id,r.revision),_.current.set(r.notice_id,r),t=!0)}for(let t of e.removed_notices??[]){let e=w.current.get(t.resource_id);(void 0===e||s6(t.revision,e)>=0)&&(w.current.set(t.resource_id,t.revision),_.current.delete(t.resource_id))}t&&p(!0),T()}),A=sL(e=>{let t=S.current.get(e.resource_id);(void 0===t||s6(e.revision,t)>=0)&&(S.current.set(e.resource_id,e.revision),b.current.delete(e.resource_id),M())}),P=sL(e=>{let t=!1;for(let r of e.tasks??[]){let e=S.current.get(r.task_id);void 0!==e&&0>=s6(r.revision,e)||(S.current.set(r.task_id,r.revision),t=!0,1===r.display_status?b.current.delete(r.task_id):b.current.set(r.task_id,r))}for(let r of e.removed_tasks??[]){let e=S.current.get(r.resource_id);(void 0===e||s6(r.revision,e)>=0)&&(S.current.set(r.resource_id,r.revision),b.current.delete(r.resource_id),t=!0)}t&&h(!0),M()}),j=sL(async(e,t)=>{let r=!1;do{let n=x.current[e],a="notice"===e?await ay({cursor:n,limit:100}):await a_({cursor:n,limit:100});if(C.current!==t)return;if("notice"===e?R(a):P(a),a.has_more&&!a.next_cursor)throw Error(`Sandbox ${e} pull returned has_more without next_cursor`);a.next_cursor&&(x.current[e]=a.next_cursor),r=a.has_more}while(r)}),L=sL((e,t)=>{let r=I.current[e];if(r)return r;let n=j(e,t).finally(()=>{I.current[e]===n&&delete I.current[e]});return I.current[e]=n,n}),D=sL(async(e,t)=>{if(C.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=w.current.get(e.resourceId);(void 0===t||s6(e.revision,t)>=0)&&(w.current.set(e.resourceId,e.revision),_.current.delete(e.resourceId),T())}else A(t);return}if("notice"===e.resource){let r=await ay({notice_ids:[e.resourceId]});C.current===t&&R(r)}else{let r=await a_({task_ids:[e.resourceId]});C.current===t&&P(r)}}}),O=sL(()=>{_.current.clear(),b.current.clear(),w.current.clear(),S.current.clear(),x.current={notice:void 0,task:void 0},I.current={},p(!1),h(!1),l([]),u([])});(0,tt.useEffect)(()=>{let e,t,a;if(!r||!n){C.current+=1,O(),f("unavailable");return}let i=!1,s=++C.current,o=!1,l=0,d=0,u=0,c=-1,p=!1;O(),f("loading");let m=e=>{var t;if(i)return;let r=e instanceof Error?e.message:String(e);f("error"),null==(t=k.current)||t.call(k,`Sandbox 资源同步失败:${r}`,!0)},h=e=>!!function(e){if(!(e instanceof ar))return!1;let t=e.remoteCode??e.options.httpStatus;return -1===t||401===t||403===t||404===t}(e)&&(p||(p=!0,m(e)),!0),g=()=>p?Promise.resolve():Promise.all([L("notice",s),L("task",s)]);g().then(()=>{i||p||C.current!==s||(o=!0,f("reconnecting"===a?"reconnecting":"connected"))}).catch(e=>{h(e)||m(e)});let v=async()=>{t=new AbortController;try{let e=await fetch(n,{cache:"no-store",headers:{Accept:"application/json"},signal:t.signal});if(!e.ok)throw Error(`资源事件接口请求失败(HTTP ${e.status})`);let m=function(e){if(eJ(e)&&["connected","connecting","reconnecting"].includes(String(e.connectionStatus))&&"number"==typeof e.generation&&"number"==typeof e.updatedAtMs)return{connectionStatus:e.connectionStatus,events:Array.isArray(e.events)?e.events.map(s7).filter(e=>!!e):[],generation:e.generation,simulatorEvents:Array.isArray(e.simulatorEvents)?e.simulatorEvents.map(s9).filter(e=>!!e):[],updatedAtMs:e.updatedAtMs}}(await e.json());if(!m)throw Error("资源事件接口返回格式错误");if(i)return;let h=m.connectionStatus!==a;if(a=m.connectionStatus,m.updatedAtMs!==c){c=m.updatedAtMs;let e=!1;for(let t of(0===u?u=m.generation:m.generation!==u&&(u=m.generation,l=0,d=0,E.current.clear(),p=!1,s=++C.current,o=!1,O(),f("loading"),e=!0),m.simulatorEvents.filter(e=>e.sequence>d).sort((e,t)=>e.sequence-t.sequence)))try{await N(t)}catch(t){var r;let e=t instanceof Error?t.message:String(t);null==(r=k.current)||r.call(k,`Sandbox 模拟器事件处理失败:${e}`,!0)}finally{d=Math.max(d,t.sequence)}if(e&&(await g(),o=!0),p)return;let t=m.events.filter(e=>e.sequence>l).sort((e,t)=>e.sequence-t.sequence);for(let e of(l>0&&t[0]&&t[0].sequence>l+1&&await g(),t))await D(e,s),l=Math.max(l,e.sequence)}if(p)return;"reconnecting"===m.connectionStatus&&h?(f("reconnecting"),await g()):o&&"connected"===m.connectionStatus&&f("connected")}catch(e){i||(null==t?void 0:t.signal.aborted)||h(e)||f("reconnecting")}finally{i||(e=window.setTimeout(v,800))}};return v(),()=>{i=!0,C.current+=1,null==t||t.abort(),void 0!==e&&window.clearTimeout(e)}},[r,n,N,L,D,O]);let U=sL(async e=>{y(t=>new Set(t).add(e));try{let t=await ab(e);A(t)}finally{y(t=>{let r=new Set(t);return r.delete(e),r})}}),q=sL(()=>{p(!1)}),$=sL(()=>{h(!1)}),B=(0,tt.useMemo)(()=>({hasUnreadNotices:c,hasUnreadTasks:m,markServiceNoticesRead:q,markTasksRead:$,notices:o,removeTask:U,removingTaskIds:v,status:g,tasks:d}),[c,m,q,$,o,U,v,g,d]);return(0,i.jsx)(s8.Provider,{value:B,children:t})}var ot=r(64031),or=r(88460);let on={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 oa(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)(ot.oz,{components:on,remarkPlugins:[or.A],children:t})})}function oi(e,t,r){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:eJ(e.source)?e.source.tool_call_id:void 0,render_data:e.render_data}}function os(e){let{apiEnvironment:t,appId:r,card:n,inspectableTargetKey:a,reloadKey:s,nativeModulesCallHandler:o,onInspectableTargetChange:l,onTraceEvent:d,onUpdateWidget:u,requestId:c,runtimeConsoleTarget:p,traceId:m,viewport:h,widgets:g}=e,f=(0,tt.useRef)(null),v=n.widget_id,y=h??rD,_=!!v&&((null==g?void 0:g.some(e=>e.widgetId===v))??!1),[S,x]=(0,tt.useState)(),[I,E]=(0,tt.useState)(0),[C,k]=(0,tt.useState)({status:"idle"}),N=S??y.width,T={height:`${I||Math.round(1.35*N)}px`},M=(0,tt.useMemo)(()=>{if(!u)return null==t?void 0:t.apiRegistry;let e=(null==t?void 0:t.apiRegistry.fork())??a2();return e.register("doubao.updateWidget",{handler:e=>{let t=function(e){if(eJ(e)&&"string"==typeof e.widgetInstanceId&&"string"==typeof e.widgetData&&(void 0===e.widgetId||"string"==typeof e.widgetId))return{widgetInstanceId:e.widgetInstanceId,widgetData:e.widgetData,..."string"==typeof e.widgetId?{widgetId:e.widgetId}:{}}}(e.params);if(!t)return w(e,"Invalid doubao.updateWidget parameters");let r=u(t);return"updated"===r.status?b(e,{}):w(e,r.message)}},{override:!0}),e},[null==t?void 0:t.apiRegistry,u]),R=(0,tt.useMemo)(()=>(e,t,r,n)=>{let a=sk(e,t,r);return a?void it(p??n.element,a):null==o?void 0:o(e,t,r,n)},[o,p]);return(0,tt.useEffect)(()=>{let e=f.current;if(!e)return;let t=()=>{let t=e.clientWidth;(t>0||"u"<typeof ResizeObserver)&&x(t||y.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()}},[y.width]),(0,tt.useEffect)(()=>{let e,i,s=f.current;if(!s||void 0===S)return;if(s.replaceChildren(),E(0),a&&(null==l||l(a,null)),!v){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,...oi(n,c,m)});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,...oi(n,c,m)});return}if(!_){let e=`Manifest 中找不到 widget_id: ${v}`;k({status:"skipped",message:e}),null==d||d({category:"card",event:"simulator_card_render_skipped",reason:"widget_not_found",summary:e,...oi(n,c,m)});return}let o=!1,u=null,p=rq({...y,width:S},n.card_id?{__VIEW_CONTEXT__:{widgetInstanceId:n.card_id}}:{}),h=()=>{o||E(Math.ceil(s.scrollHeight||s.getBoundingClientRect().height))},g=()=>{"u"<typeof window?h():(void 0!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(h))},b=Date.now();k({status:"rendering"});try{u=new eZ({appId:r,apiRegistry:M,container:s,globalProps:p,initData:tu(n.render_data),nativeModulesCallHandler:R,onError:e=>{null==d||d({category:"card",event:"simulator_card_runtime_error",elapsed_ms:Date.now()-b,summary:e.message,...oi(n,c,m)})},runtimeHost:null==t?void 0:t.runtimeHost,widgetId:v})}catch(t){let e=tg(t);k({status:"error",message:e}),null==d||d({category:"card",event:"simulator_card_render_failed",elapsed_ms:Date.now()-b,summary:e,...oi(n,c,m)});return}return u.render().then(e=>{o||(k({status:"rendered"}),a&&(null==l||l(a,e,S)),g(),"u">typeof ResizeObserver&&(i=new ResizeObserver(g)).observe(s),null==d||d({category:"card",event:"simulator_card_rendered",elapsed_ms:Date.now()-b,...oi(n,c,m)}))}).catch(e=>{if(o)return;let t=tg(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()-b,summary:t,...oi(n,c,m)})}),()=>{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,M,r,n,R,a,l,d,s,y,S,_,v]),(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:f})}),"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 oo="mcp-privacy-login-card",ol="__doubao_apps__expired-widget";function od(e){return e.title||e.fallback_text||e.card_type||e.card_id||"卡片"}function ou(e,t){return(null==e?void 0:e.some(e=>e.widgetId===t))?e:[...e??[],{widgetId:t}]}function oc(e,t){return`${e.messageId}:${t.blockId}:${t.card.card_id||t.blockId}`}function op(e){var t,r;let{apiEnvironment:n,appId:a,block:s,cardReloadKey:o,message:l,nativeModulesCallHandler:d,onInspectableCardTargetChange:u,grantingItemIndex:c,onGrantingCardOpen:p,onGrantingPermissionDecision:m,onGrantingCardSkip:h,onTraceEvent:g,onUpdateWidget:f,runtimeConsoleTarget:v,widgetViewport:y,widgets:_}=e,b=(0,tt.useMemo)(()=>"card"===s.type&&s.card.widget_id===ol?ou(_,ol):_,[s,_]);if((0,tt.useEffect)(()=>{var e;"card"!==s.type||s.card.widget_id||null==g||g({category:"card",event:"simulator_card_render_skipped",reason:"missing_widget_id",summary:"缺少 widget_id,已展示 fallback",...(e=s.card,{request_id:l.requestId,trace_id:l.traceId,card_id:e.card_id,widget_id:e.widget_id,card_type:e.card_type})})},[s,l.requestId,l.traceId,g]),"text"===s.type)return(0,i.jsx)(oa,{text:s.text});if("card"===(t=s).type&&"permission_apply"===t.card.card_type){let e=oc(l,s),t=(null==(r=og(s.card,c))?void 0:r.itemIndex)??0;return(0,i.jsx)(oy,{card:s.card,grantingItemIndex:t,onLogin:()=>null==p?void 0:p(s.card,e,t),onPermissionDecision:r=>null==m?void 0:m(s.card,e,t,r),onSkip:r=>null==h?void 0:h(r,s.card,e,t),onTraceEvent:g})}return s.card.widget_id?(0,i.jsx)("article",{className:"wsd-widget-chat-card has-runtime",children:(0,i.jsx)(os,{apiEnvironment:n,appId:a,card:s.card,inspectableTargetKey:oc(l,s),reloadKey:o,nativeModulesCallHandler:d,onInspectableTargetChange:u,onTraceEvent:g,onUpdateWidget:f,requestId:l.requestId,runtimeConsoleTarget:v,traceId:l.traceId,viewport:y,widgets:b})}):(0,i.jsxs)("article",{className:"wsd-widget-chat-card",children:[(0,i.jsx)("span",{className:"wsd-widget-chat-card-kicker",children:s.card.card_type||"卡片"}),(0,i.jsx)("strong",{children:od(s.card)}),s.card.fallback_text&&s.card.fallback_text!==od(s.card)?(0,i.jsx)("span",{className:"wsd-widget-chat-card-summary",children:s.card.fallback_text}):null]})}function om(e){var t;let r=null==(t=e.render_data)?void 0:t.grantingData;return eJ(r)&&Array.isArray(r.grantingList)?r:void 0}function oh(e){return"pending"===e.permissionStatus||"revoked"===e.permissionStatus}function og(e,t){let r=om(e),n=(null==r?void 0:r.grantingList.findIndex(oh))??-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 of(e){return"string"==typeof e?e:""}function ov(e){let{appIcon:t}=e,[r,n]=(0,tt.useState)(!1);return((0,tt.useEffect)(()=>{n(!1)},[t]),!t||r)?null:(0,i.jsx)("img",{alt:"",className:"wsd-widget-granting-prompt-logo",onError:()=>n(!0),src:t})}function oy(e){var t,r,n;let{card:a,grantingItemIndex:s,onLogin:o,onPermissionDecision:l,onSkip:d,onTraceEvent:u}=e,c=(0,tt.useMemo)(()=>og(a,s),[a,s]),p=null==c?void 0:c.grantingData,m=null==c?void 0:c.item,h=(null==p?void 0:p.doubaoAppletName)||"智能服务",g=(null==m?void 0:m.grantingName)==="permission",f=of(null==m||null==(t=m.relatedData)?void 0:t.scopeName),v=(0,tt.useMemo)(()=>r7(f),[f]),[y,_]=(0,tt.useState)(),[b,w]=(0,tt.useState)(),S=r4.isLocationScope(f),x=void 0!==b,I=S&&"granted"===b,E=g&&(null==p?void 0:p.cardStatus)==="expired",C=g&&!y&&(!x||S)&&!E&&((null==m?void 0:m.permissionStatus)==="pending"||(null==m?void 0:m.permissionStatus)==="revoked"),k=g?v.title:`在豆包内使用 ${h}`,N=g?"granted"===y?`已允许${h}获取`:"refused"===y?`已拒绝${h}获取`:E?"已过期,暂无法操作":of(null==m||null==(r=m.relatedData)?void 0:r.scopeDescription)||v.description:of(null==m||null==(n=m.relatedData)?void 0:n.bizLoginDescription)||((null==m?void 0:m.grantingName)==="privacy"?"需同意后才可以继续使用":"需登录后才可以继续使用");async function T(e){if(!x){w(e?"granted":"refused"),null==u||u({category:"card",event:"simulator_granting_prompt_permission_click",granted:e,scope:f});try{let t=await (null==l?void 0:l(e));!1!==t&&_(e?"granted":"refused")}finally{w(void 0)}}}return(0,tt.useEffect)(()=>{_(void 0),w(void 0)},[a.card_id,null==p?void 0:p.cardStatus,s,null==m?void 0:m.permissionStatus,f]),(0,i.jsxs)("article",{className:(0,eK.$)("wsd-widget-granting-prompt-card",g&&"is-permission"),children:[(0,i.jsxs)("header",{className:"wsd-widget-granting-prompt-brand",children:[(0,i.jsx)(ov,{appIcon:null==p?void 0:p.doubaoAppletIcon}),(0,i.jsx)("span",{children:h})]}),(0,i.jsx)("strong",{className:"wsd-widget-granting-prompt-title",children:k}),(0,i.jsx)("p",{className:"wsd-widget-granting-prompt-description",children:N}),g?C?(0,i.jsxs)("footer",{className:"wsd-widget-granting-prompt-actions",children:[(0,i.jsx)("button",{className:"wsd-widget-granting-prompt-secondary",disabled:x,onClick:()=>void T(!1),type:"button",children:"拒绝"}),(0,i.jsxs)("button",{"aria-busy":I,className:"wsd-widget-granting-prompt-primary",disabled:x,onClick:()=>void T(!0),type:"button",children:[I?(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==u||u({category:"card",event:"simulator_granting_prompt_skip_click",granting_name:null==m?void 0:m.grantingName}),null==d||d((null==m?void 0:m.grantingName)==="privacy"?"privacy":"login")},type:"button",children:"暂不登录"}),(0,i.jsx)("button",{className:"wsd-widget-granting-prompt-primary",onClick:function(){null==u||u({category:"card",event:"simulator_granting_prompt_login_click",granting_name:null==m?void 0:m.grantingName}),null==o||o()},type:"button",children:"登录"})]})]})}function o_(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,tt.useMemo)(()=>ou(c,oo),[c]),m=(0,tt.useMemo)(()=>(function(e,t){let r,n,a,i,s,o,l,d;return{...e,card_id:`${e.card_id||"permission_apply"}:${oo}`,card_type:"permission_apply",render_data:{...eJ(e.render_data)?e.render_data:{},viewData:(n=null==(r=og(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=of(i.mobileMask),d=o?of(i.bizPrivacyContent)||`${s} 需要你同意隐私政策后继续。`:of(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:of(i.termsOfServiceURL)||void 0},{text:"和"},{text:"隐私政策",url:of(i.privacyURL)||void 0}]},warningToast:"请先阅读并同意协议"})},widget_id:oo}})(n,a),[n,a]),h=(0,tt.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)(os,{apiEnvironment:t,appId:r,card:m,inspectableTargetKey:s,nativeModulesCallHandler:o,onInspectableTargetChange:l,onTraceEvent:d,runtimeConsoleTarget:u,viewport:h,widgets:p})})}function ob(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=>"text"===e.type&&e.text.trim()),x=s.traceId,I=!!(x&&m),E=!!(x&&x===f);return(0,i.jsxs)("article",{"aria-pressed":I?E:void 0,className:(0,eK.$)("wsd-widget-chat-message",_?"is-assistant":"is-user",S&&"has-text",w&&"has-card",I&&"is-trace-selectable",E&&"is-trace-selected"),onClick:e=>{!x||!m||ow(e.target)||m(x)},onKeyDown:e=>{!x||!m||ow(e.target)||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),m(x))},role:I?"button":void 0,tabIndex:I?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)(op,{apiEnvironment:t,appId:r,block:e,cardReloadKey:n,grantingItemIndex:"card"===e.type?null==a?void 0:a[oc(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 ow(e){return e instanceof Element&&!!e.closest("button,a,input,textarea,select,.wsd-widget-chat-card")}let oS="mcp-login-page";function ox(e){return e.split(":")[0]||""}function oI(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,tt.useState)(""),[N,T]=(0,tt.useState)(!1),[M,R]=(0,tt.useState)(!1),A=(0,tt.useContext)(s8),P=(0,tt.useMemo)(()=>s3(A.tasks).length>0,[A.tasks]),j=(0,tt.useRef)(null),L=(0,tt.useRef)(b.messages.length),D=(0,tt.useRef)(!0),[O,U]=(0,tt.useState)(),[q,$]=(0,tt.useState)({}),B=(0,tt.useRef)(new Set),F=(0,tt.useRef)(),W=(0,tt.useRef)(new Set),H=(0,tt.useRef)(new Set),z=(0,tt.useRef)(new Set),V="streaming"===b.streamStatus,G=!!C.trim()&&!V,J=((r=null==O?void 0:O.card)?null==(n=om(r))?void 0:n.doubaoAppletKey:void 0)||void 0,K=s||J,X=sL(e=>{(U(void 0),m)?m({url:e}):I.navigateToPage(e)}),Q=sL(()=>{var e;null==a||null==(e=a.uiPresenter)||e.showToast({duration:3e3,icon:"warn",message:"请先在 DevTools Sandbox 面板配置位置",type:"warning"}),null==g||g()}),Z=sL(e=>I.updateSimulatorWidget(e)),Y=sL((e,t)=>{let r=tJ(I,{grantingMessageId:(null==t?void 0:t.grantingMessageId)??(O?ox(O.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}U(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)})}),ee=sL(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})}),et=sL(async(e,t)=>{ee("simulator_location_directive_started",e);try{let r=await r4.requestLocationForHostDirective();if("success"!==r.status){Q(),ee("simulator_location_directive_unavailable",e,{failure_type:r.code?`browser_geolocation_${r.code}`:"browser_geolocation_unavailable",location_status:r.status});return}try{let e=r4.createBusinessLocationInfo(r.location);await aP(JSON.stringify(e))}catch(t){ee("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(ee("simulator_location_directive_reported",e),"completed"!==I.getState().simulator.streamStatus){ee("simulator_location_directive_unavailable",e,{failure_type:"simulator_stream_not_completed"}),null==E||E("当前仍在生成中,暂不重发定位后的消息",!0);return}z.current.add(t.query),I.removeSimulatorMessages(t.messageIds),ee("simulator_location_directive_resend_started",e),null==h||h();try{await I.sendSimulatorQuery(t.query)}catch(e){null==E||E(e.message,!0)}}finally{H.current.delete(t.query)}});(0,tt.useEffect)(()=>{let e=b.locationDirective;if(!e||"completed"!==b.streamStatus||W.current.has(e.cardId))return;W.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());if(null==n?void 0:n.text.trim())return{messageIds:[n.messageId,...-1===r?[]:[e[r].messageId]],query:n.text.trim()}}(b.messages,e);if(!t)return void ee("simulator_location_directive_unavailable",e,{failure_type:"original_query_not_found"});if(H.current.has(t.query)||z.current.has(t.query)){ee("simulator_location_directive_loop_prevented",e),null==E||E("位置已上报但平台仍要求定位,请检查 Sandbox 位置状态",!0);return}H.current.add(t.query),et(e,t)},[et,E,b.locationDirective,b.messages,b.streamStatus,ee]);let er=sL((e,t,r,n)=>{var a;let i=og(e,r);if(!i){null==E||E("索权卡缺少有效的授权项",!0);return}let s=`${t}:${r}`;if(B.current.has(s))return;B.current.add(s);let o=function(e,t){let r=om(e);if(!r)return;let n=r.grantingList.findIndex((e,r)=>r>t&&oh(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 Y(l,{grantingMessageId:ox(t),noLogin:!0});if(void 0!==o){$(e=>({...e,[t]:o})),U(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=og(e,o))?void 0:a.item.grantingName});return}Y(l,{grantingMessageId:ox(t)})}),en=sL((e,t,r)=>{var n,a;let i;(null==(i=null==(n=og(e,r))?void 0:n.item)?void 0:i.grantingName)==="privacy"||of(null==i||null==(a=i.relatedData)?void 0:a.mobileMask).trim()?U({card:e,itemIndex:r,key:t}):(null==f||f({category:"card",event:"simulator_granting_custom_login_navigate",reason:"missing_mobile_mask",url:oS}),X(oS))}),ea=sL(async(e,t,r,n)=>{var a,i,s;let o,l=function(e,t){var r;let n=og(e,t),a=null==n?void 0:n.grantingData,i=null==n?void 0:n.item,s=of(null==a?void 0:a.doubaoAppletKey).trim(),o=of(null==i||null==(r=i.relatedData)?void 0:r.scopeName).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(r4.isLocationScope(l.scope)&&(r4.updateUserAuthorization(n),n)){let e=await r4.requestLocation();if("success"!==e.status)return"browser_unauthorized"===e.status&&Q(),null==f||f({category:"card",event:"simulator_granting_location_unavailable",location_status:e.status,scope:l.scope}),!1;o=r4.createBusinessLocationInfo(e.location)}try{await aS({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 aP(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",r5.set(r6(a,i),s),null==f||f({category:"card",event:"simulator_granting_permission_reported",applet_id:l.appId,granted:n,scope:l.scope}),er(e,t,r,n),!0}),ei=sL((e,t,r,n)=>{er(t,r,n,!1)}),es=(0,tt.useMemo)(()=>{var e,t;if(!O)return;let r=(e=O.key,t=O.itemIndex,`${e}:${t}`);return a3({appId:K,baseAPIRegistry:null==a?void 0:a.apiRegistry,onGrantingCompleted:(e,t)=>er(O.card,O.key,O.itemIndex,!(null==t?void 0:t.noLogin)),onCustomLoginNavigate:X,onPrivacyLoginCardClose:()=>{Promise.resolve().then(()=>{B.current.has(r)||er(O.card,O.key,O.itemIndex,!1)})},runtimeHost:null==a?void 0:a.runtimeHost,scanCodePresenter:null==a?void 0:a.scanCodePresenter,uiPresenter:null==a?void 0:a.uiPresenter})},[O,a,K,er,X]),eo=sL((e,t,r)=>{null==p||p(e,t,r),null==u||u(t)}),el=sL(e=>{R(!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")}}),ed=sL(()=>{R(!1)}),eu=sL(async e=>{try{await A.removeTask(e)}catch(e){null==E||E(e.message,!0)}});(0,tt.useEffect)(()=>{let e=j.current,t=L.current,r=b.messages.at(-1),n=b.messages.length>t&&(null==r?void 0:r.role)==="user";L.current=b.messages.length,e&&(D.current||n)&&(e.scrollTop=e.scrollHeight,D.current=!0)},[null==(t=b.error)?void 0:t.message,b.messages,b.streamStatus]);let ec=sL(async(e,t)=>{z.current.delete(e),null==h||h(),await (t?sK(I,t,e):I.sendSimulatorQuery(e))});return((0,tt.useEffect)(()=>{if((null==l?void 0:l.type)!=="submit_chat_query"||F.current===l.commandId)return;F.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;ec(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,ec,I]),(0,tt.useEffect)(()=>{N&&A.hasUnreadNotices&&A.markServiceNoticesRead()},[A.hasUnreadNotices,A.markServiceNoticesRead,N]),N)?(0,i.jsx)(s1,{notices:A.notices,onAction:el,onBack:()=>T(!1),status:A.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)(sZ,{}),(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":A.hasUnreadNotices?"打开菜单,有更新":"打开菜单",className:(0,eK.$)("wsd-doubao-icon-button",A.hasUnreadNotices&&"has-badge"),onClick:()=>T(!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,eK.$)("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;D.current=t.scrollHeight-t.scrollTop-t.clientHeight<=24},ref:j,children:[b.messages.length>0?b.messages.map(e=>(0,i.jsx)(ob,{apiEnvironment:a,appId:s,cardReloadKey:o,grantingItemIndexes:q,message:e,nativeModulesCallHandler:d,onGrantingCardOpen:en,onGrantingPermissionDecision:ea,onGrantingCardSkip:ei,onInspectableCardTargetChange:p,onTraceEvent:f,onTraceSelect:v,onUpdateWidget:Z,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:"wsd-widget-chat-composer",onSubmit:function(e){e.preventDefault();let t=C.trim();t&&!V&&(k(""),ec(t).catch(e=>{null==E||E(e.message,!0)}))},children:[(0,i.jsx)("input",{"aria-label":"输入消息",className:"wsd-widget-chat-input",disabled:V,onChange:e=>k(e.currentTarget.value),placeholder:"发消息...",type:"text",value:C}),(0,i.jsx)("button",{"aria-label":V?"取消生成":"发送消息",className:"wsd-widget-chat-send",disabled:!V&&!G,onClick:function(){V&&I.cancelSimulatorQuery()},type:V?"button":"submit",children:V?(0,i.jsx)("span",{"aria-hidden":"true",className:"wsd-doubao-cancel-icon"}):(0,i.jsx)("span",{"aria-hidden":"true",className:"wsd-doubao-send-icon"})})]})}),P&&!M?(0,i.jsx)("button",{"aria-label":"展开进行中的任务",className:"wsd-sandbox-task-collapsed-entry",onClick:()=>{A.markTasksRead(),R(!0)},type:"button",children:(0,i.jsx)("span",{"aria-hidden":"true"})}):null,O?(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)(o_,{apiEnvironment:es,appId:K,card:O.card,grantingItemIndex:O.itemIndex,inspectableTargetKey:O.key,nativeModulesCallHandler:d,onInspectableTargetChange:eo,onTraceEvent:f,runtimeConsoleTarget:y,widgets:x})})]}):null,M?(0,i.jsx)(s4,{onAction:el,onClose:ed,onRemove:eu,removingTaskIds:A.removingTaskIds,tasks:A.tasks}):null]})}function oE(e){let{appIcon:t}=e,[r,n]=(0,tt.useState)(!1);return((0,tt.useEffect)(()=>{n(!1)},[t]),!t||r)?null:(0,i.jsx)("img",{alt:"",className:"wsd-simulator-permission-app-icon",onError:()=>n(!0),src:t})}function oC(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)(oE,{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 ok(){let[e,t]=(0,tt.useState)(),r=(0,tt.useRef)(null),n=sL(e=>r.current?Promise.reject(Error("Simulator permission prompt is already open")):new Promise(n=>{r.current=n,t(e)})),a=sL(e=>{let n=r.current;n&&(r.current=null,t(void 0),n(e))}),i=sL(()=>a(!0)),s=sL(()=>a(!1));return(0,tt.useEffect)(()=>()=>{let e=r.current;r.current=null,null==e||e(!1)},[]),{allowPermission:i,permission:e,rejectPermission:s,showPermission:n}}var oN=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"})}),oT=r(35668),oM=r(27860),oR=r(26661),oA=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 oP=[{key:"conversation",label:"对话"},{key:"tool",label:"工具"},{key:"card",label:"卡片"},{key:"page",label:"全页"}],oj=[{label:"iOS",devices:rj.filter(e=>e.key.startsWith("iphone"))},{label:"Android",devices:rj.filter(e=>e.key.startsWith("pixel")||e.key.startsWith("galaxy"))},{label:"平板",devices:rj.filter(e=>e.key.startsWith("ipad"))}];function oL(e){let{activeView:t,children:r,onActiveViewChange:n,onDeviceChange:a,selectedDeviceKey:s}=e,[o,l]=(0,tt.useState)(!1),[d,u]=(0,tt.useState)(),c=rO(s??rP),[p,m]=(0,tt.useState)(()=>String(c.width)),[h,g]=(0,tt.useState)(()=>String(c.height)),f=(0,tt.useRef)(null),v=(null==s?void 0:s.startsWith("custom-"))===!0&&c.key===s,y=(e,t)=>{let r=`custom-${e}x${t}`;rO(r).key===r&&(null==a||a(r))};return(0,tt.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,eK.$)("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)(oA,{"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,eK.$)("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)(oT.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:oj.map(e=>(0,i.jsx)(oM.g,{showDivider:e!==oj.at(-1),title:e.label,children:e.devices.map(e=>(0,i.jsx)(oR.Y,{title:e.label,children:e.label},e.key))},e.label))})]}):null,(0,i.jsx)("button",{"aria-label":"设置","aria-pressed":"settings"===d,className:(0,eK.$)("wsd-device-toolbar-icon","settings"===d&&"is-active"),onClick:()=>{u("settings"),l(!1)},type:"button",children:(0,i.jsx)(sQ,{"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:oP.map(e=>(0,i.jsx)("span",{"aria-selected":t===e.key,className:(0,eK.$)("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)(s$,{}),r]})]})}function oD(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,tt.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,tt.useEffect)(()=>{var e;null==(e=n.onChromeDevToolsPanelChange)||e.call(n,l)},[l,n.onChromeDevToolsPanelChange]),(0,i.jsxs)("div",{className:(0,eK.$)("wsd-widget-preview-column","card"===n.activeView&&"is-card-debug"),children:[(0,i.jsx)(oL,{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)(oN,{"aria-hidden":"true"})}):null}),r]})}function oO(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return{type:"callback",callbackId:e.callbackId,params:{code:1,data:t}}}let oU=["agreeMain","agreeSub","reject"],oq={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"},o$={error:"error",success:"success",warning:"warn"};function oB(e){return Array.isArray(e.itemList)?e.itemList:[]}function oF(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 oW(e){let{content:t}=e,r=(0,tt.useMemo)(()=>oF(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):(0,i.jsx)("a",{href:t.href,rel:"noreferrer",target:"_blank",children:s},a)})}(r)})}function oH(e){let{id:t,params:r,onSubmit:n}=e,[a,s]=(0,tt.useState)(String(r.latitude??0)),[o,l]=(0,tt.useState)(String(r.longitude??0)),[d,u]=(0,tt.useState)(""),[c,p]=(0,tt.useState)(""),[m,h]=(0,tt.useState)("");return(0,i.jsxs)("form",{"aria-label":"选择位置",className:"wsd-simulator-overlay-dialog wsd-simulator-location-form",onClick:e=>e.stopPropagation(),onSubmit:function(e){e.preventDefault();let r=Number(a),i=Number(o);Number.isFinite(r)&&Number.isFinite(i)?n(t,{address:c.trim()||void 0,latitude:r,longitude:i,name:d.trim()||void 0}):h("纬度和经度必须是有效数字")},children:[(0,i.jsx)("h2",{children:"选择位置"}),(0,i.jsxs)("label",{children:[(0,i.jsx)("span",{children:"纬度"}),(0,i.jsx)("input",{onChange:e=>s(e.currentTarget.value),value:a})]}),(0,i.jsxs)("label",{children:[(0,i.jsx)("span",{children:"经度"}),(0,i.jsx)("input",{onChange:e=>l(e.currentTarget.value),value:o})]}),(0,i.jsxs)("label",{children:[(0,i.jsx)("span",{children:"名称(可选)"}),(0,i.jsx)("input",{onChange:e=>u(e.currentTarget.value),value:d})]}),(0,i.jsxs)("label",{children:[(0,i.jsx)("span",{children:"地址(可选)"}),(0,i.jsx)("input",{onChange:e=>p(e.currentTarget.value),value:c})]}),m?(0,i.jsx)("p",{className:"wsd-simulator-location-error",role:"alert",children:m}):null,(0,i.jsx)("footer",{className:"wsd-simulator-overlay-actions",children:(0,i.jsx)("button",{className:"wsd-simulator-overlay-button is-primary",type:"submit",children:"确定"})})]})}function oz(e){let{scanner:t}=e,r=(0,tt.useRef)(null),n=(0,tt.useRef)(null);return(0,tt.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 oV(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 oG(e){var t;let{interaction:r,onActionSheetSelect:n,onBottomSheetSelect:a,onDismiss:s,onLocationSubmit:o,onModalResult:l}=e,d=()=>s(r);if("location"===r.kind)return(0,i.jsx)(oV,{onDismiss:d,children:(0,i.jsx)(oH,{id:r.id,onSubmit:o,params:r.params},r.id)});if("modal"===r.kind){let{params:e}=r,t=!1!==e.showCancel;return(0,i.jsx)(oV,{className:"is-modal",exiting:r.exiting,onDismiss:d,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:()=>l(r.id,"cancel"),type:"button",children:e.cancelText||"cancel"}):null,(0,i.jsx)("button",{className:"wsd-simulator-modal-button is-confirm",onClick:()=>l(r.id,"confirm"),type:"button",children:e.confirmText||"confirm"})]})]})})}if("actionSheet"===r.kind){let e=oB(r.params);return(0,i.jsx)(oV,{onDismiss:d,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 u=Array.isArray((t=r.params).buttons)?t.buttons:[];return(0,i.jsx)(oV,{onDismiss:d,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)(oW,{content:r.params.content}):null,(0,i.jsx)("div",{className:"wsd-simulator-overlay-actions",children:u.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 oJ(e){let{interaction:t,loading:r,onActionSheetSelect:n,onBottomSheetSelect:a,onDismiss:s,onLocationSubmit:o,onModalResult:l,scanner:d,toast:u}=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,u?(0,i.jsxs)("output",{"aria-live":"polite",className:`wsd-simulator-toast is-${u.type}${u.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||o$[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:oq[t]})}):null}(u),(0,i.jsx)("span",{className:"wsd-simulator-toast-message",children:u.message})]},u.id):null,d?(0,i.jsx)(oz,{scanner:d}):null,t?(0,i.jsx)(oG,{interaction:t,onActionSheetSelect:n,onBottomSheetSelect:a,onDismiss:s,onLocationSubmit:o,onModalResult:l}):null]})}function oK(){let[e,t]=(0,tt.useState)(null),[r,n]=(0,tt.useState)(!1),[a,s]=(0,tt.useState)(null),o=(0,tt.useRef)(null),l=(0,tt.useRef)(),d=(0,tt.useRef)(0),u=(0,tt.useRef)(0),c=(0,tt.useRef)(0),p=(0,tt.useRef)(null),[m,h]=(0,tt.useState)(null),g=(0,tt.useRef)(null),f=(0,tt.useRef)(),v=(0,tt.useRef)(),y=sL((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))}),_=sL(()=>{let e=o.current;e&&("modal"===e.kind?y(e.id,{action:"cancel"}):"bottomSheet"===e.kind?y(e.id,{action:"cancel",source:"unknown"}):"actionSheet"===e.kind?y(e.id,void 0,Error("action sheet selection was cancelled")):y(e.id,void 0,Error("chooseLocation was cancelled")))}),b=sL((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=sL(()=>{v.current&&(clearTimeout(v.current),v.current=void 0),f.current&&(clearTimeout(f.current),f.current=void 0)}),S=sL(e=>{var t;(null==(t=g.current)?void 0:t.id)===e&&(g.current=null,f.current=void 0,s(null))}),x=sL(()=>{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=sL(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=sL(e=>{var t;(null==(t=p.current)?void 0:t.id)===e&&(p.current=null,h(null))}),C=sL((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=sL(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=sL(e=>new Promise((t,r)=>{b("modal",e,t,r)})),T=sL(e=>new Promise((t,r)=>{b("location",e,t,r)})),M=sL(e=>new Promise((t,r)=>{0===oB(e).length?r(Error("itemList must contain at least one item")):b("actionSheet",e,t,r)})),R=sL(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(!oF(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=oU.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)})),A=sL((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))}),P=sL((e,t)=>{let r=o.current;r&&r.id===e&&A(e,{action:t})}),j=sL((e,t)=>{let r=o.current;r&&r.id===e&&"actionSheet"===r.kind&&y(e,{tapIndex:t})}),L=sL((e,t)=>{let r=o.current;r&&r.id===e&&"bottomSheet"===r.kind&&y(e,{action:"buttonClick",role:t})}),D=sL((e,t)=>{let r=o.current;r&&r.id===e&&"location"===r.kind&&y(e,t)}),O=sL(e=>{let t=o.current;if(t&&t.id===e.id)if("modal"===e.kind){if(!1===e.params.tapMaskToDismiss)return;A(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"actionSheet"===e.kind?y(e.id,void 0,Error("action sheet selection was cancelled")):y(e.id,void 0,Error("chooseLocation was cancelled"))});(0,tt.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 U=(0,tt.useMemo)(()=>({chooseLocation:T,hideLoading:()=>n(!1),hideToast:x,showActionSheet:M,showBottomSheet:R,showLoading:()=>n(!0),showModal:N,showToast:I}),[T,x,M,R,N,I]);return{overlay:(0,i.jsx)(oJ,{interaction:e,loading:r,onActionSheetSelect:j,onBottomSheetSelect:L,onDismiss:O,onLocationSubmit:D,onModalResult:P,scanner:m,toast:a}),presenter:U,scanCodePresenter:k}}function oX(e){return"string"==typeof e&&e.trim()?e.trim():""}function oQ(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function oZ(e){return"boolean"!=typeof(null==e?void 0:e.sandboxPhoneNumberUploaded)?void 0:!1===e.sandboxCsrRequired?e.sandboxPhoneNumberUploaded:"boolean"==typeof e.sandboxCsrUploaded?e.sandboxCsrUploaded&&e.sandboxPhoneNumberUploaded:void 0}function oY(e,t){return eJ(e)?e[t]:void 0}function o0(e,t){let r=oY(e,t);return eJ(r)?r:void 0}function o1(e,t){let r=oY(e,t);return Array.isArray(r)?r:[]}function o2(e){let t=oY(e,"raw");return eJ(t)?t:eJ(e)?e:{}}function o3(e){return o0(o2(e),"applet")}function o4(e){return null==e?void 0:e.replace(/^\/+|\/+$/g,"")}function o5(e){return eJ(e.payload)?e.payload:void 0}function o8(e,t){for(let r=e.length-1;r>=0;r-=1){let n=o5(e[r]);if((null==n?void 0:n.event)===t)return n}}function o6(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 o7(e,t,r){let n=function(){for(var r=arguments.length,n=Array(r),a=0;a<r;a++)n[a]=arguments[a];return n.map(r=>o8(e,`simulator_${t}_${r}`)).find(Boolean)},a=n("missing"),i=n("fetch_started","load_started"),s=n("fetch_failed","load_failed"),o=n("fetch_succeeded","loaded"),l=n("empty");return o?{bytes:oQ(o.bytes)??oQ(o.skill_length),detail:oX(o.url)||r,label:"已加载",tone:"success"}:l?{detail:r||"未配置",label:"空内容",tone:"muted"}:a||!r?{detail:r,label:"未配置",tone:"muted"}:s?{detail:oX(s.error)||oX(s.url)||r,label:"加载失败",tone:"error"}:i?{detail:oX(i.url)||r,label:"加载中",tone:"pending"}:{detail:r,label:"检查中",tone:"pending"}}function o9(e){return"string"==typeof e?e.trim():eJ(e)?oX(e.name)||oX(e.id):""}function le(){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 lt(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 le("src",/\.(tsx|ts|jsx|js)$/.test(e)?e:`${e}.tsx`)}return!r||r.startsWith("__")?"":le("src",t,r,"index.tsx")}function lr(e){var t,r;let n,a,i,s,o,l,d,u,c,p,m,h,g,{context:f,events:v,manifest:y,pages:_=[],widgets:b}=e,w=(null==f?void 0:f.launchDir)||"",S=(null==f?void 0:f.mcpEndpoint)||(null==f?void 0:f.mcpProxyEndpoint)||"",x=(null==f?void 0:f.mcpOriginalEndpoint)||oX(null==(a=o0(o2(y),"mcp_server"))?void 0:a.end_point)||oX(null==a?void 0:a.endpoint)||oX(null==a?void 0:a.url)||oX(null==a?void 0:a.mcp_endpoint),I=(null==f?void 0:f.mcpProxyEndpoint)||(null==f?void 0:f.mcpEndpoint)||"",E=(null==f?void 0:f.simulatorManifestOriginalUrl)||"",C=(null==f?void 0:f.simulatorManifestProxyUrl)||(null==f?void 0:f.simulatorManifestUrl)||"",k=(null==f?void 0:f.simulatorManifestRelativePath)||"",N=(null==f?void 0:f.simulatorBusinessTemplatesOriginalUrl)||"",T=(null==f?void 0:f.simulatorBusinessTemplatesRelativePath)||"",M=(null==f?void 0:f.simulatorManifestUrl)||(null==f?void 0:f.simulatorManifestProxyUrl)||"",R=(null==f?void 0:f.simulatorSkillOriginalUrl)||"",A=(null==f?void 0:f.simulatorSkillProxyUrl)||(null==f?void 0:f.simulatorSkillUrl)||"",P=(null==f?void 0:f.simulatorSkillRelativePath)||"",j=(null==f?void 0:f.simulatorSkillUrl)||(null==f?void 0:f.simulatorSkillProxyUrl)||"",L=o6(M,E,"/__simulator_manifest/manifest.yaml"),D=o6(j,R,"/__simulator_skill/skill.md"),O=o6(S,(null==f?void 0:f.mcpOriginalEndpoint)||"","/__mcp_proxy"),U=function(e){let t=new Set;for(let r of e){let e=o5(r);if(e){for(let r of o1(e,"tools")){let e=o9(r);e&&t.add(e)}for(let r of o1(e,"mcp_servers"))for(let e of o1(r,"tools")){let r=o9(e);r&&t.add(r)}}}return[...t]}(v),q=function(e){let t=new Map,r=function(e,r){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",a=eJ(r)?oX(r.widget_id)||oX(r.widgetId)||oX(r.widget):oX(r),i=eJ(r)&&(oX(r.entity_type)||oX(r.entityType)||oX(r.entity))||n;e&&a&&t.set(`${e}:${a}:${i}`,{entityType:i,toolName:e,widgetId:a})},n=o2(e),a=oY(n,"tool_card_binding");if(eJ(a))for(let[e,t]of Object.entries(a))r(e,t);let i=oY(n,"entities");for(let[e,t]of eJ(i)?Object.entries(i):[]){if(!eJ(t))continue;let n=oX(t.entity_type)||oX(t.entityType)||e,a=oY(t,"tool_card_binding");if(eJ(a))for(let[e,t]of Object.entries(a))r(e,t,n)}return[...t.values()]}(y),$={manifest:o7(v,"manifest",L),mcp:(i=o8(v,"local_mcp_missing"),s=o8(v,"local_mcp_tools_load_started"),o=o8(v,"local_mcp_tools_load_failed"),l=o8(v,"local_mcp_tools_loaded"),d=o8(v,"client_tools_resolved"),u=o8(v,"client_tools_empty"),l?{detail:oX(l.mcp_endpoint)||O,label:"已连接",tone:"success"}:d?{detail:`${oQ(d.tool_count)??0} tools`,label:"客户端工具",tone:"success"}:u?{detail:"manifest.yaml 未声明 tools",label:"无客户端工具",tone:"muted"}:i||!O?{detail:O,label:"未配置",tone:"muted"}:o?{detail:oX(o.error)||oX(o.mcp_endpoint)||O,label:"连接失败",tone:"error"}:s?{detail:oX(s.mcp_endpoint)||O,label:"连接中",tone:"pending"}:{detail:O,label:"检查中",tone:"pending"}),skill:o7(v,"skill",D)},B=!!L||"success"===$.manifest.tone,F=!!D||"success"===$.skill.tone,W=!!O||"success"===$.mcp.tone,H={businessTemplates:N?{detail:T||N,label:"已加载",tone:"success"}:{detail:"",label:"未配置",tone:"muted"},manifest:{...$.manifest,detail:k||$.manifest.detail},mcp:$.mcp,skill:{...$.skill,detail:P||$.skill.detail}};return{appId:(c=o2(y),p=o3(y),oX(oY(y,"appId"))||oX(c.appId)||oX(c.app_key)||oX(null==p?void 0:p.appletId)),appName:(m=o2(y),h=o3(y),oX(oY(y,"name"))||oX(m.name)||oX(m.app_name)||oX(null==h?void 0:h.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}(w,(null==f?void 0:f.homeDir)||"")},mcpTools:U,pages:(t=y,g=(null==(n=function(e,t){let r=o4(t);if(r)return e.find(e=>e.id===t||o4(e.path)===r)}(r=_,oX(oY(o3(t),"appletEntry")))??r.find(e=>{let t=o4(e.path);return"index"===e.id||"pages/index"===t||"pages/index/index"===t})??r[0])?void 0:n.path)||"",_.map(e=>{var t,r;return{entry:lt(w,"pages",(null==(t=o4(e.path))?void 0:t.replace(/^pages\//,"").replace(/\/index$/,""))??"",oX(e.entry)),isHome:!!g&&e.path===g,name:oX(oY(e,"name"))||oX(oY(e,"title")),pageId:e.id,path:oX(e.path)||oX(null==(r=e.web)?void 0:r.entry)||oX(e.entry)}})),resources:H,sources:{manifest:{original:B?E:"",proxy:B?C||M:""},mcp:{original:W?x:"",proxy:W?I:""},skill:{original:F?R:"",proxy:F?A||j:""}},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(td).map(e=>({boundTools:n.get(e.widgetId)??[],entry:lt(r,"widgets",e.widgetId,oX(e.entry)),name:oX(e.name),widgetId:e.widgetId}))}(b,q,w)}}function ln(e,t,r){return!!(e&&t&&t!==r&&e.sourceTarget===t)}function la(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}}),...t?{currentTarget:t}:{}}}function li(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":si(e),attributes:"element"===e.type?sn(e).map(e=>{var t;return{name:e.name,value:(t=e.value,t.length<=500?t:(i(),`${t.slice(0,499)}…`))}}):[],children:t,...e.accessibility?{accessibility:e.accessibility}:{},...e.textContent?{text:e.textContent}:{}}};return{root:e?s(e):null,...t?{selectedUid:t}:{},nodeCount:n,truncated:a,...r?{sourceTarget:r}:{},updatedAtMs:Date.now()}}let ls={message:"未上传",tone:"muted"},lo={message:"已上传",tone:"success"},ll=ls,ld=new Set;function lu(e){return ld.add(e),()=>ld.delete(e)}function lc(){return ll}function lp(e){for(let t of(ll=e,ld))t()}function lm(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ls.message;lp({message:e,tone:"muted",updatedAtMs:Date.now()})}function lh(e){let t=(0,tt.useSyncExternalStore)(lu,lc,lc);return(0,tt.useEffect)(()=>{void 0!==e&&lp(e?lo:ls)},[e]),t}let lg={message:"可用",tone:"success"},lf={message:"不可用",tone:"error"},lv=lg,ly=new Set;function l_(e){return ly.add(e),()=>ly.delete(e)}function lb(){return lv}function lw(e){for(let t of(lv=e,ly))t()}function lS(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0],t=(0,tt.useSyncExternalStore)(l_,lb,lb);return(0,tt.useEffect)(()=>{lw(e?lg:lf)},[e]),t}function lx(e){var t,r,n;let a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("locate-sandbox-location"===e.kind)return r4.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{r4.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);r4.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?(lw({message:"正在重建",tone:"pending",updatedAtMs:Date.now()}),aj({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?lp({message:"已上传",tone:"success",updatedAtMs:Date.now()}):lm(),lw({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}`;lm(),lw({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&&(lp({message:"正在上传...",tone:"pending",updatedAtMs:Date.now()}),aA({csrPem:e.csrPem,phoneNum:e.phoneNum}).then(()=>{var e,t;lp({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:"";lp({errorMessage:(e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message?e.message:"")||void 0,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)}let lI=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"]),lE={query:0,"tool-call":10,"tool-result":20,"agent-processing":25,card:30,"agent-response":40,error:50};function lC(e,t){return{category:"api",detail:{query:t},key:"query",phase:"request",payload:{event:"query",query:t},source:e,sources:[e],title:"Query"}}function lk(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=lA(lR(e.source));return lN(lA(lR(t.source)))>lN(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:lO(a.detail,i.detail),phase:"error"===t.phase?t.phase:a.phase,payload:lO(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 lN(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 lT(e){let t=lF([...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=l$(a.sources.flatMap(tS)),_=l$(a.sources.map(e=>lU(lR(e).request_id))),w=void 0===(b=(l=a,d=s,u=o,c=lq(l.payload.elapsed_ms)??lq(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?lq(f.payload.elapsed_ms)??lq(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:{...1===_.length?{request_id:_[0]}:{},..._.length>1?{request_ids:_}:{},...a.payload,trace_id:i.id,...i.status?{run_status:i.status}:{},...void 0===b?{elapsed_ms:void 0}:{elapsed_ms:b},...y.length>0?{log_ids:y}:{}}}})}function lM(e,t){let r=lB(lR(t)),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 lR(e){return eJ(e.payload)?e.payload:{}}function lA(e){return lU(e.event)}function lP(e,t){return lj(e)||[lB(e)||t.id,lU(e.tool_name)||"unknown-tool"].filter(Boolean).join(":")}function lj(e){return lU(e.tool_call_id)}function lL(e){let t=lU(e.tool_name)||lj(e);return t?`: ${t}`:""}function lD(e){let t={};for(let[r,n]of Object.entries(e))null!=n&&""!==n&&(t[r]=n);return t}function lO(e,t){return{...t,...e,...Object.fromEntries(Object.entries(t).filter(t=>{let[r,n]=t;return void 0===e[r]&&void 0!==n}))}}function lU(e){return"string"==typeof e&&e.trim()?e.trim():""}function lq(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function l$(e){return[...new Set(e.filter(e=>!!e))]}function lB(e){let t=eJ(e.trace)?e.trace:{};return lU(e.trace_id)||lU(t.trace_id)}function lF(e){return[...e].sort((e,t)=>e.source.timestamp-t.source.timestamp||(e.source.order??0)-(t.source.order??0)||lE[e.key.split(":")[0]]-lE[t.key.split(":")[0]]||e.key.localeCompare(t.key))}function lW(e,t){return e.startedAt-t.startedAt||e.order-t.order||e.id.localeCompare(t.id)}function lH(e,t){return e.timestamp-t.timestamp||(e.order??0)-(t.order??0)||e.id.localeCompare(t.id)}function lz(e){let t=new WeakSet;try{return JSON.stringify(e,(e,r)=>{if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if("function"==typeof r)return`[Function ${r.name||"anonymous"}]`;if(tc(r)){if(t.has(r))return"[Circular]";t.add(r)}return r},2)}catch{var r=e;if("string"==typeof r){let e=r.trim();if(!e)return"";try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}if(void 0===r)return"";try{return JSON.stringify(r,null,2)}catch{return String(r)}}}function lV(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:lG(e,t),debug_snapshot:lG(e,{...t,debug:!0,includeRuntimeRoot:!1})}}function lG(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,eJ(t)&&!r&&eJ(t.runtime_snapshot)?{...t,runtime_snapshot:lK(t.runtime_snapshot,!1)}:t):function(e,t){var r;if(!eJ(e))return e;let n=eJ(e.simulator)?e.simulator:{},a=Array.isArray(n.messages)?n.messages.filter(e=>lX(e,t.traceId)):void 0,i=Array.isArray(n.tool_calls)?n.tool_calls.filter(e=>lX(e,t.traceId)):void 0,s=lK(e.runtime_snapshot,!1!==t.includeRuntimeRoot);return{...l2(e,["exported_at","client_id","command_id","context","render_targets"]),...eJ(s)?{runtime_snapshot:s}:{},...eJ(e.simulator)?{simulator:{...l2(n,["stream_status","active_request_id","active_reply_message_id"]),...n.error?{error:l1(n.error)}:{},...n.selected_card?{selected_card:l0(n.selected_card)}:{},...n.answer_finish?{answer_finish:eJ(r=n.answer_finish)?l2(r,["messageId","status","finishReason","usage","createdAtMs"]):r}:{},...a?{messages:a.map(lQ)}:{},...i?{tool_calls:i.map(lY)}:{},...Array.isArray(n.trace_events)?{trace_events:lJ(n.trace_events,{debug:t.debug,messages:a,traceId:t.traceId})}:{}}}:{},...Array.isArray(e.widget_runtime_trace_events)?{widget_runtime_trace_events:lJ(e.widget_runtime_trace_events,{debug:t.debug,traceId:t.traceId})}:{},...Array.isArray(e.page_runtime_trace_events)?{page_runtime_trace_events:lJ(e.page_runtime_trace_events,{debug:t.debug,traceId:t.traceId})}:{},...eJ(e.runtime_console)?{runtime_console:e.runtime_console}:{}}}(e,n),i=tS(e);return i.length>0&&eJ(a)?{...a,log_ids:i}:a}function lJ(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=>lB(lR(e))===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(lH))!function(e,t){var r,n;let a=lR(t),i=lA(a);if("tool_result_report_started"===i){let r=lM(e,t);if(!r)return;lk(r,function(e){let t=lR(e),r=lD({tool_call_id:lj(t),tool_name:t.tool_name});return{category:"agent",detail:r,key:`agent-processing:${lP(t,e)}`,phase:"request",payload:{event:"agent_processing",...r},source:e,sources:[e],title:`Agent Processing${lL(t)}`}}(t));return}if(!((r=i).startsWith("tool_result_report_")||"tool_result_ack"===r)){if("simulator_chat_fetch_started"===i){let r=function(e){let t=eJ(e.request)?e.request:{},r=eJ(t.message)?t.message:{};return lU(e.query)||lU(t.query)||lU(r.content)}(a);if(!r)return;let n=lM(e,t);if(!n)return;lk(n,lC(t,r));return}if("tool_call"===i||"local_mcp_call_started"===i){let r=lM(e,t);if(!r)return;lk(r,function(e){let t=lR(e),r=lD({tool_call_id:lj(t),tool_name:t.tool_name,arguments:t.arguments,arguments_json:t.arguments_json});return{category:"agent",detail:r,key:`tool-call:${lP(t,e)}`,phase:"request",payload:{event:"tool_call",...r},source:e,sources:[e],title:`Tool Call${lL(t)}`}}(t));return}if("local_mcp_call_succeeded"===i||"local_mcp_call_failed"===i){let r=lM(e,t);if(!r)return;lk(r,function(e){let t=lR(e),r="local_mcp_call_failed"===lA(t),n=lD({tool_call_id:lj(t),tool_name:t.tool_name,status:t.status,result:t.result,structured_result:t.structured_result,structured_result_json:t.structured_result_json,raw_result_text:t.raw_result_text,raw_mcp_result:t.raw_mcp_result,raw_mcp_result_json:t.raw_mcp_result_json,elapsed_ms:t.elapsed_ms,error:t.error});return{category:"mcp",detail:n,key:`tool-result:${lP(t,e)}`,phase:r?"error":"response",payload:{event:r?"tool_result_failed":"tool_result",...n},source:e,sources:[e],title:`${r?"Tool Result Failed":"Tool Result"}${lL(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=lM(e,t);if(!r)return;lk(r,function(e){var t,r;let n=lR(e),a=lA(n),i="error"in n||a.endsWith("_failed")||a.endsWith("_error"),s=lD({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,lU(t.card_id)||lU(t.source_tool_call_id)||[lB(t)||r.id,lU(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=lU(e.phase),n=e.status;return lI.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=lM(e,t);if(!r)return;lk(r,function(e){var t,r;let n=lR(e),a=eJ(n.detail)?n.detail:{},i=n.event_count??a.event_count,s=lD({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"===lA(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:lA(n)||"trace_error",...s},source:e,sources:[e],title:(null==(r=e.display)?void 0:r.title)||lU(n.title)||"Trace Error"}}(t))}}}(r,t);for(let e of t)!function(e,t){var r,n,a,i;let s=(r=t,{id:`trace-message-${r.messageId}`,timestamp:r.createdAtMs,payload:lD({message_id:r.messageId,request_id:r.requestId,trace_id:r.traceId})}),o=lM(e,s);o&&("assistant"===t.role&&t.status&&(n=o,a=t.status,i=t.createdAtMs,void 0!==n.statusUpdatedAt&&i<n.statusUpdatedAt||(n.status=a,n.statusUpdatedAt=i)),"user"===t.role&&t.text.trim()&&!o.steps.has("query")&&lk(o,lC(s,t.text)),"assistant"===t.role&&t.text.trim()&&lk(o,function(e,t){let r=lF([...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:"number"==typeof(null==r?void 0:r.source.order)?r.source.order+.1:null==r?void 0:r.source.order,timestamp:n,payload:lD({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"}}(o,t)))}(r,e);return r}(e,t.messages);return(t.traceId?a.runs.filter(e=>e.id===t.traceId):a.runs).sort(lW).flatMap(lT)}(e,t)}function lK(e,t){if(!eJ(e)||t)return e;let{root:r,...n}=e;return n}function lX(e,t){if(!t)return!0;if(!eJ(e))return!1;let r=eJ(e.trace)?e.trace:{};return e.traceId===t||r.trace_id===t}function lQ(e){return eJ(e)?{...l2(e,["messageId","localMessageId","requestId","traceId","role","contentType","status","createdAtMs"]),..."string"==typeof e.text?{text:l3(e.text)}:{},...Array.isArray(e.blocks)?{blocks:e.blocks.map(lZ)}:{},...Array.isArray(e.toolCalls)?{toolCalls:e.toolCalls}:{},...Array.isArray(e.toolResults)?{toolResults:e.toolResults}:{}}:e}function lZ(e){return eJ(e)?"card"===e.type?{...l2(e,["blockId","type"]),card:l0(e.card)}:{...l2(e,["blockId","type"]),..."string"==typeof e.text?{text:l3(e.text)}:{}}:e}function lY(e){return eJ(e)?{...l2(e,["requestId","runId","replyMessageId","toolCallId","toolName","serverId","appKey","status","createdAtMs","updatedAtMs","requiresUserApproval","timeoutMs","deadlineMs","progress","message","resultSummary","structuredResultSummary","isMiniApp"]),...void 0===e.arguments?{}:{arguments:e.arguments},...void 0===e.arguments&&e.argumentsJson?{argumentsJson:e.argumentsJson}:{},...e.error?{error:l1(e.error)}:{}}:e}function l0(e){return eJ(e)?l2(e,["reply_message_id","block_id","card_id","widget_id","card_type","app_id","entity_id","title","fallback_text"]):e}function l1(e){return eJ(e)?l2(e,["code","message","user_message","retryable","stage","details","name","stack"]):e}function l2(e,t){let r={};for(let n of t)void 0!==e[n]&&(r[n]=e[n]);return r}function l3(e){return e.length>1e3?`${e.slice(0,1e3)}...`:e}function l4(e){let[t,r]=(0,tt.useState)(),n=(0,tt.useRef)(),a=(0,tt.useRef)(),i=sL((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=sL((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 l5="u"<typeof window?tt.useEffect:tt.useLayoutEffect;function l8(e,t){let[r,n]=(0,tt.useState)(rP),[a,i]=(0,tt.useState)("fit"),s=(0,tt.useRef)(),o=(0,tt.useMemo)(()=>rO(r),[r]),l=rL.find(e=>e.key===a)??rL.find(e=>"fit"===e.key)??rL[0],d="fit"===l.key,{fitScale:u,setRuntimeShellRef:c}=function(e){let{deviceHeight:t,deviceWidth:r,enabled:n}=e,[a,i]=(0,tt.useState)(.88),s=(0,tt.useRef)(null),o=(0,tt.useRef)(null),l=(0,tt.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,tt.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 l5(()=>{n&&l()},[n,l]),l5(()=>()=>{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,tt.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}}let l6={logs:[],updatedAtMs:0};function l7(e){if(eJ(e)&&"string"==typeof e.id&&eJ(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:eJ(e.response)?e.response:void 0,sandboxSessionId:"string"==typeof e.sandboxSessionId?e.sandboxSessionId:"",status:e.status,timestamp:e.timestamp,updatedAtMs:e.updatedAtMs}}function l9(e){return eJ(e)?{logs:Array.isArray(e.logs)?e.logs.map(l7).filter(e=>!!e):[],updatedAtMs:"number"==typeof e.updatedAtMs?e.updatedAtMs:0}:l6}function de(e){let[t,r]=(0,tt.useState)(l6),n=(0,tt.useRef)(0),a=sL(async()=>{if(!e)throw Error("服务端日志接口不可用");let t=++n.current,a=await fetch(e,{headers:{Accept:"application/json"},method:"DELETE"});if(!a.ok)throw Error(`清空服务端日志失败(HTTP ${a.status})`);let i=l9(await a.json());t===n.current&&r(i)});return(0,tt.useEffect)(()=>{let t,a;if(!e)return void r(l6);let i=!1,s=async()=>{a=new AbortController;let o=n.current;try{let t=await fetch(e,{cache:"no-store",headers:{Accept:"application/json"},signal:a.signal});if(t.ok&&!i&&o===n.current){let e=l9(await t.json());r(t=>t.updatedAtMs===e.updatedAtMs?t:e)}}catch{}i||(t=window.setTimeout(s,1e3))};return s(),()=>{i=!0,null==a||a.abort(),void 0!==t&&window.clearTimeout(t)}},[e]),{clearLogs:a,logs:t.logs}}function dt(){return(0,tt.useSyncExternalStore)(r4.subscribe,r4.getSnapshot,r4.getSnapshot)}function dr(e,t,r){var n;let a=(0,tt.useRef)(),i=!!(e&&r&&((null==(n=a.current)?void 0:n.endpoint)!==e||a.current.snapshot!==r)),s=(0,tt.useMemo)(()=>e?lz(lV(t,{includeRuntimeRoot:i})):void 0,[e,i,t]);(0,tt.useEffect)(()=>{if(!e||!s)return;let t=window.setTimeout(()=>{e&&"u">typeof fetch&&fetch(e,{body:s,headers:{"Content-Type":"application/json"},method:"POST"}).catch(()=>{}),i&&r&&(a.current={endpoint:e,snapshot:r})},500);return()=>window.clearTimeout(t)},[e,i,r,s])}let dn={appEntries:[],entries:[],updatedAtMs:0};function da(e,t){var r;return!t||e.traceId===t||(null==(r=e.trace)?void 0:r.trace_id)===t}function di(e,t){var r;let{chromeDevToolsFrontendUrl:n,controlCommand:a,controlClientId:i,debugContext:s,onChromeDevToolsPanelChange:o,onActiveViewChange:l,onControlResult:d,onMessage:u,onNavigateToPage:c,apiEnvironment:p,showDebugTrace:m,traceSnapshotEndpoint:h,webSdkDebugger:g}=e,f=sF(g),v=(0,tt.useMemo)(()=>f.widgets.filter(td),[f.widgets]),y=(0,tt.useRef)(null),w=(0,tt.useRef)(null),S=(0,tt.useRef)(null),x=(0,tt.useRef)(null),I=(0,tt.useRef)(null);!I.current&&"u">typeof document&&(I.current=document.createElement("div"));let[E,C]=(0,tt.useState)(0),k=sL(()=>w.current),[N,T]=(0,tt.useState)(null),[M,R]=(0,tt.useState)(!1),[A,P]=(0,tt.useState)(0),[j,L]=(0,tt.useState)(!1),[D,O]=(0,tt.useState)([]),[U,q]=(0,tt.useState)(dn),[$,B]=(0,tt.useState)(null),[F,W]=(0,tt.useState)(null),[H,z]=(0,tt.useState)(null),[V,G]=(0,tt.useState)(),[J,K]=(0,tt.useState)(0),[X,Q]=(0,tt.useState)(0),[Z,Y]=(0,tt.useState)(0),ee=sG(),et=oK(),er=ok(),en=(null==s?void 0:s.sandboxSessionAvailable)!==!1,ea=oZ(s),[ei,es]=(0,tt.useState)(!0!==ea),eo=lh(ea),el=dt(),ed=lS(en),{clearLogs:eu,logs:ec}=de(null==s?void 0:s.sandboxBridgeLogsEndpoint),ep=(0,tt.useRef)(null),em=(0,tt.useMemo)(()=>x.current,[E]),{accept:eh,pending:eg,pendingRef:ef,report:ev}=l4(d),ey=(0,tt.useRef)(),e_=(0,tt.useRef)(new Map),eb=(0,tt.useRef)(new Map),ew=(0,tt.useRef)(0),{runtimeScaleMode:eS,runtimeStyle:ex,selectedDevice:eI,selectedDeviceKey:eE,setRuntimeShellRef:eC,setSelectedDeviceKey:ek}=l8(a,d),eN=(0,tt.useRef)(eE),eT=(null==(r=f.widgetSelection)?void 0:r.item.widgetId)??"",eM=(0,tt.useRef)(eT),eR=f.simulator,eA=(0,tt.useRef)(eR.toolCalls),eP=!!f.widgetSelection&&"streaming"!==eR.streamStatus&&!j,ej=(0,tt.useMemo)(()=>({...rD,density:eI.density,label:eI.label,width:Math.max(1,eI.width-38)}),[eI.density,eI.label,eI.width]);(0,tt.useEffect)(()=>{eA.current=eR.toolCalls},[eR.toolCalls]);let eL=sL(e=>{let t=function(e,t){var r;if(!eJ(e))return e;let n="string"==typeof e.source_tool_call_id?e.source_tool_call_id:void 0,a=n?t.find(e=>e.toolCallId===n):void 0;if(!a)return e;let i=eJ(e.trace)?e.trace:{},s="string"==typeof e.trace_id||"string"==typeof i.trace_id;return{...e,...e.request_id?{}:{request_id:a.requestId},...s||!(null==(r=a.trace)?void 0:r.trace_id)?{}:{trace_id:a.trace.trace_id}}}(e,eA.current),r=++ew.current,n={display:tz(t),id:`trace-${r}`,order:r,payload:t,timestamp:Date.now()};O(e=>[...e,n].slice(-200))}),eD=sL(()=>{O([])}),eO=(0,tt.useMemo)(()=>[...eR.traceEvents.map((e,t)=>({event:e,sortOrder:e.order??t})),...D.map((e,t)=>({event:e,sortOrder:e.order??eR.traceEvents.length+t}))].sort((e,t)=>e.event.timestamp-t.event.timestamp||e.sortOrder-t.sortOrder||e.event.id.localeCompare(t.event.id)).map(e=>{let{event:t}=e;return t}),[D,eR.traceEvents]),eU=(0,tt.useMemo)(()=>({...s,manifestUrl:f.manifestUrl,simulatorEndpoint:eR.endpoint}),[s,eR.endpoint,f.manifestUrl]),eq=(0,tt.useMemo)(()=>lr({context:eU,events:eO,manifest:f.manifest,pages:f.pages,widgets:f.widgets}),[eO,eU,f.manifest,f.pages,f.widgets]),e$=eq.appId||f.manifest.appId,eB=eq.appName||f.manifest.name,eF=(0,tt.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,tt.useMemo)(()=>la(eq,"card"===t&&f.widgetSelection?eF:null==H?void 0:H.targetInfo),[t,H,eF,eq.pages,eq.widgets,f.widgetSelection]),eH=!!(eg&&ln($,em,eg.previousTarget)&&"card"===t&&eT===eg.command.widgetId),ez=(0,tt.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,tt.useMemo)(()=>({exported_at:new Date().toISOString(),client_id:i,...eH?{command_id:null==eg?void 0:eg.command.commandId}:{},context:{launch_dir:eU.launchDir,manifest_url:f.manifestUrl,app_id:e$,app_name:f.manifest.name,mcp_endpoint:eU.mcpEndpoint,mcp_original_endpoint:eq.sources.mcp.original,mcp_proxy_endpoint:eq.sources.mcp.proxy,simulator_manifest_original_url:eq.sources.manifest.original,simulator_manifest_proxy_url:eq.sources.manifest.proxy,simulator_manifest_url:eU.simulatorManifestUrl,simulator_skill_original_url:eq.sources.skill.original,simulator_skill_proxy_url:eq.sources.skill.proxy,simulator_skill_url:eU.simulatorSkillUrl,widget_id:eT,simulator_endpoint:eR.endpoint,web_url:eU.webUrl},render_targets:eW,runtime_snapshot:ez,simulator:{stream_status:eR.streamStatus,active_request_id:eR.activeRequestId,active_reply_message_id:eR.activeReplyMessageId,error:eR.error,answer_finish:eR.answerFinish,messages:eR.messages,tool_calls:eR.toolCalls,trace_events:eR.traceEvents},runtime_console:{app:{entries: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.simulatorSkillUrl,eU.webUrl,U,eT,eR,e$,i,eH,null==eg?void 0:eg.command.commandId,eW,f.manifest.name,f.manifestUrl,ez]),eG=sL(e=>{g.approveSimulatorToolCall(e).catch(e=>{null==u||u(e.message,!0)})}),eK=sL(e=>{g.rejectSimulatorToolCall(e).catch(e=>{null==u||u(e.message,!0)})}),eX=sL(e=>{"clear-trace-filter"===e.kind?G(void 0):lx(e,{onClearLogs:eu,onMessage:u,onRecreated:()=>es(!0),onUpdated:()=>es(!1)})||("approve-tool-call"===e.kind||"reject-tool-call"===e.kind)&&("approve-tool-call"===e.kind?eG:eK)(e.toolCallId)}),eQ=sL(e=>{G(t=>t===e?void 0:e)}),eZ=sL(()=>{K(e=>Math.max(e,X)+1)});(0,tt.useEffect)(()=>{"success"===eo.tone&&es(!1)},[eo.tone]),(0,tt.useEffect)(()=>{void 0!==ea&&es(!ea)},[ea]);let eY=sL(()=>{Q(e=>Math.max(e,J)+1)}),e0=sL(()=>{Q(e=>Math.max(e,J)+1),Y(e=>e+1)}),e1=sL(e=>{e.stopPropagation(),es(!1)}),e2=Math.max(J,X);(0,tt.useEffect)(()=>{V&&!eR.messages.some(e=>da(e,V))&&G(void 0)},[V,eR.messages]);let e3=(0,tt.useMemo)(()=>m?eO:eO.filter(e=>{var t;return!(null==(t=e.display)?void 0:t.debugOnly)}),[eO,m]),e4="conversation"===t?F:em,e5=sL(e=>{W(e)}),e8=()=>{for(let e of eR.messages.slice().reverse())for(let t of e.blocks.slice().reverse()){if("card"!==t.type)continue;let r=eb.current.get(oc(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=sL((e,t,r)=>{if(t){let n=eR.messages.slice().reverse().flatMap(t=>{let r=t.blocks.find(r=>"card"===r.type&&oc(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},...(null==n?void 0:n.card.app_id)?{appId:n.card.app_id}:{},...(null==n?void 0:n.card.widget_id)?{widgetId:n.card.widget_id}:{},...(null==n?void 0:n.card.card_id)?{cardId:n.card.card_id}:{},...(null==n?void 0:n.message.requestId)?{requestId:n.message.requestId}:{}}};eb.current.set(e,a),z(e8());return}let n=eb.current.get(e);eb.current.delete(e),z(e=>n&&(null==e?void 0:e.target)===n.target?e8():e)}),e7=sL((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,tt.useMemo)(()=>lJ(e3,{debug:m,messages:eR.messages,traceId:V}),[V,m,eR.messages,e3]),te=(0,tt.useMemo)(()=>V?eR.toolCalls.filter(e=>da(e,V)):eR.toolCalls,[V,eR.toolCalls]),tr=(0,tt.useMemo)(()=>lG(eV,{debug:m,traceId:V}),[V,m,eV]),tn=(0,tt.useMemo)(()=>lz(tr),[tr]),ta=(0,tt.useMemo)(()=>({debugData:eq,events:e9,logSnapshot:tr,logSnapshotText:tn,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:ec,businessInfoStatus:eo,location:el,locationFocusRequestId:Z,sessionStatus:ed},showDebugTrace:m,traceFilterId:V??"",traceSurface:"conversation",toolCalls:te,updatedAtMs:Date.now()}),[eq,te,e9,tr,tn,ec,en,eo,el,Z,ed,null==s?void 0:s.sandboxCsrRequired,V,m]);dr(h,eV,$),(0,tt.useEffect)(()=>{if((null==a?void 0:a.type)==="render_widget"&&eh(a,em))try{g.selectWidget(a.widgetId)}catch(e){ev(a.commandId,{ok:!1,error:{code:"TARGET_NOT_FOUND",message:e.message}})}},[eh,a,ev,g,em]),(0,tt.useEffect)(()=>{eg&&eH&&ev(eg.command.commandId,{ok:!0,target:eF,snapshot:lV(eV)})},[eF,eH,eg,ev,eV]);let ti=(0,tt.useMemo)(()=>{let e=(e,t,r)=>{var n;if("AppletBridgeModule"===r&&("postMessage"===e||"postMessageSync"===e)&&eJ(n=t)&&"call"===n.type&&"string"==typeof n.name&&"number"==typeof n.callbackId){if("mind.getAgentTraceSwitch"===t.name)return oO(t,{value:!0});if("mind.reportAgentTraceEvent"===t.name)return eL(t.params??{}),oO(t)}};return(t,r,n,a)=>"AppletBridgeModule"===n&&"postMessage"===t&&_(r)&&"doubao.navigateTo"===r.name&&eJ(r.params)&&"string"==typeof r.params.url?(null==c||c({url:r.params.url}),null==u||u(`卡片 navigateTo: ${r.params.url}`),b(r,{})):e(t,r,n,a)},[eL,u,c]),ts=(0,tt.useCallback)(e=>a3({appId:e$,appIcon:f.manifest.iconSrc,appName:eB,baseAPIRegistry:null==p?void 0:p.apiRegistry,onCustomLoginNavigate:e=>null==c?void 0:c({url:e}),sendFollowUpMessage:e=>{let{content:t,prompt:r}=e;return g.sendSimulatorQuery(r,{followUpContent:t})},multiMediaBroadcastContainer:e??void 0,runtimeHost:null==p?void 0:p.runtimeHost,scanCodePresenter:et.scanCodePresenter,showSandboxCashier:ee.showCashier,uiPresenter:et.presenter,showSimulatorPermission:er.showPermission,vibrationContainer:S.current??void 0}),[p,e$,eB,c,ee.showCashier,et.scanCodePresenter,et.presenter,er.showPermission,f.manifest.iconSrc,g]),to=(0,tt.useMemo)(()=>ts(),[ts]),tl=sL(e=>{x.current!==e&&(x.current=e,C(e=>e+1)),T(null)});(0,tt.useEffect)(()=>{let e=y.current;if(!e)return;let t=ts(e),r=new sP({container:e,fileSystemNamespace:null==s?void 0:s.fileSystemNamespace,nativeModulesCallHandler:ti,webSdkDebugger:g,onError:e=>{null==u||u(`Widget runtime error ${eT}: ${e.message}`,!0)},apiEnvironment:t});ep.current=r;let n=r.subscribeTarget(tl);return tl(r.getCurrentTarget()),()=>{n(),r.destroy(),ep.current=null,tl(null)}},[t,ts,null==s?void 0:s.fileSystemNamespace,ti,u,eT,tl,g]);let tu=sL(async function(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=ep.current,n=t.widgetId??(null==(e=f.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),console.log(`Rendering widget ${n} with initData:`,a),eD();try{return await r.render({widgetId:n,...a?{initData:a}:{},viewport:{...rD,density:eI.density,label:eI.label,width:Math.max(1,eI.width-38)}}),eN.current=eE,R(!0),null==u||u(`Rendered widget ${n}`),!0}catch(t){R(!1),null==u||u(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,tt.useEffect)(()=>{let e=ef.current;e&&"card"===t&&ep.current&&ey.current!==e.command.commandId&&(ey.current=e.command.commandId,tu({widgetId:e.command.widgetId,initData:e.command.structuredContent}))},[t,eg,tu]),(0,tt.useEffect)(()=>{var e,t;let r=eM.current;if((eM.current=eT,r!==eT)&&(null==(e=ef.current)?void 0:e.command.widgetId)!==eT){if(f.widgetSelection)return void tu();eD(),R(!1),null==(t=ep.current)||t.clear()}},[eD,tu,eT,f.widgetSelection]),(0,tt.useEffect)(()=>{!ef.current&&M&&eN.current!==eE&&tu()},[M,tu,eE]);let tc=sL(async()=>{if(!eP)return!1;L(!0);try{if(await g.reloadResources(),P(e=>e+1),M&&!await tu())return!1;return null==u||u("已刷新卡片资源"),!0}catch(e){return null==u||u(e.message,!0),!1}finally{L(!1)}});return{activeView:t,appendAgentTraceEvent:eL,canReloadResources:eP,cardReloadKey:A,chromeDevToolsFrontendUrl:n,controlCommand:a,conversationAPIEnvironment:to,conversationConsoleTarget:I.current,conversationControlTarget:H,conversationWidgetViewport:ej,currentDebugAppId:e$,currentDebugAppName:eB,debugState:ta,devtoolsTarget:e4,devToolsPanelId:X===e2&&e2>0?"wsd-sandbox":J>0?"wsd-trace":void 0,getRuntimeFrame:k,handleDebugAction:eX,handleGrantingSheetTargetChange:e5,handleInspectableCardTargetChange:e6,handleQuerySubmit:eZ,handleSandboxLoginHintClick:eY,handleSandboxLoginHintClose:e1,handleSandboxLocationConfigOpen:e0,handleTraceMessageSelect:eQ,hasRenderedPreview:M,highlightRect:N,latestDevToolsPanelRequestId:e2,nativeModulesCallHandler:ti,onActiveViewChange:l,onChromeDevToolsPanelChange:o,onControlResult:d,onMessage:u,onNavigateToPage:c,reloadResources:tc,renderSelectedWidget:tu,resolveConversationInspectTarget:e7,runtimeFrameRef:w,runtimeFrameScaleBoxRef:S,runtimeScaleMode:eS,runtimeStyle:ex,runtimeSnapshotTarget:"conversation"===t?(null==H?void 0:H.targetInfo)??eF:eF,runtimeTargetRef:y,sandboxCashier:ee,simulatorUI:et,simulatorPermissionPrompt:er,selectedDeviceKey:eE,selectedTraceId:V,selectedWidgetId:eT,setHighlightRect:T,setRuntimeConsoleSnapshot:q,setRuntimeDomSnapshot:B,setSelectedDeviceKey:ek,setRuntimeShellRef:eC,sandboxLoginAvailable:en,showSandboxLoginHint:ei,simulatorState:eR,state:f,visibleWidgets:v,webSdkDebugger:g}}function ds(e){let t=di(e,"conversation");return(0,i.jsx)(oD,{runtime:t,children:(0,i.jsx)(sz,{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)(oI,{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)(sV,{cashier:t.sandboxCashier.cashier,onCancel:t.sandboxCashier.cancelCashier,onConfirm:t.sandboxCashier.confirmCashier}):null,t.simulatorPermissionPrompt.permission?(0,i.jsx)(oC,{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 dl=r(18017),dd=r(29912),du=r(80405);async function dc(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 dp(){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 dc(e,"Scene ",t);if(!eJ(r)||!Array.isArray(r.scenes)||!Array.isArray(r.errors))throw Error("Scene 发现接口返回了无效数据");let n=r.scenes.flatMap(e=>eJ(e)&&"string"==typeof e.name&&eJ(e.content)?[{content:e.content,name:e.name}]:[]);return{errors:r.errors.flatMap(e=>eJ(e)&&"string"==typeof e.name&&"string"==typeof e.message?[{name:e.name,message:e.message}]:[]),scenes:n}}let dm={appEntries:[],entries:[],updatedAtMs:0},dh="scene:";function dg(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)(dl.I,{closeDelay:0,content:r,delay:300,placement:"right",children:o}):o}function df(){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 dv(e){var t,r,n,a;let{activeView:s,chromeDevToolsFrontendUrl:o,controlCommand:l,controlClientId:d,debugContext:u,onChromeDevToolsPanelChange:c,onActiveViewChange:p,onControlResult:m,onMessage:h,apiEnvironment:g,showDebugTrace:f,traceSnapshotEndpoint:v,webSdkDebugger:y}=e,_=sF(y),b=(0,tt.useMemo)(()=>_.pages.filter(td),[_.pages]),[w,S]=(0,tt.useState)({errors:[],scenes:[]}),[x,I]=(0,tt.useState)(""),[E,C]=(0,tt.useState)(null),[k,N]=(0,tt.useState)(null),[T,M]=(0,tt.useState)(null),[R,A]=(0,tt.useState)(null),[P,j]=(0,tt.useState)(null),[L,D]=(0,tt.useState)(0),[O,U]=(0,tt.useState)(null),[q,$]=(0,tt.useState)(dm),B=sG(),F=oK(),W=(null==u?void 0:u.sandboxSessionAvailable)!==!1,H=lh(oZ(u)),z=dt(),V=lS(W),{clearLogs:G,logs:J}=de(null==u?void 0:u.sandboxBridgeLogsEndpoint),[K,X]=(0,tt.useState)(null),Q=ok(),Z=(0,tt.useRef)(null),{accept:Y,pending:ee,pendingRef:et,report:er}=l4(m),{runtimeScaleMode:en,runtimeStyle:ea,selectedDevice:ei,selectedDeviceKey:es,setRuntimeShellRef:eo,setSelectedDeviceKey:el}=l8(l,m),ed=(null==(t=_.pageSelection)?void 0:t.item.id)??"",eu=_.pageSelection?_.pageSelection.item.path:"",ec=(0,tt.useMemo)(()=>w.scenes.flatMap(e=>{let t=eH(e.content);if("page"!==t.type||t.unresolvedVariables.length>0)return[];try{return e3({url:t.url},_.manifest),[{key:`${dh}${e.name}`,label:t.url,type:"scene",url:t.url}]}catch{return[]}}),[w.scenes,_.manifest]),ep=(0,tt.useMemo)(()=>[...b.map(e=>({key:e.path,url:e.path})),...ec],[ec,b]),em=(null==(r=ec.find(e=>{var t;return e.key===x&&e.url===(null==(t=_.pageSelection)?void 0:t.routeUrl)}))?void 0:r.key)??"",eh=(0,tt.useMemo)(()=>({...u,manifestUrl:_.manifestUrl,simulatorEndpoint:_.simulator.endpoint}),[u,_.manifestUrl,_.simulator.endpoint]),eg=(0,tt.useMemo)(()=>lr({context:eh,events:_.simulator.traceEvents,manifest:_.manifest,pages:_.pages,widgets:_.widgets}),[eh,_.manifest,_.pages,_.simulator.traceEvents,_.widgets]),ef=eg.appId||_.manifest.appId,ev=eg.appName||_.manifest.name,ey=(0,tt.useMemo)(()=>{var e;return{type:"page",appId:ef,appName:ev,pageId:ed,pagePath:eu,url:(null==(e=_.pageSelection)?void 0:e.routeUrl)??eu,viewport:{key:ei.key,label:ei.label,width:ei.width,height:ei.height,density:ei.density}}},[ef,ev,ei,ed,eu,null==(n=_.pageSelection)?void 0:n.routeUrl]),e_=(0,tt.useMemo)(()=>la(eg,_.pageSelection?ey:void 0),[ey,eg.pages,eg.widgets,_.pageSelection]),eb=!!(ee&&ln(K,R,ee.previousTarget)&&(null==(a=_.pageSelection)?void 0:a.routeUrl)===ee.command.url),ew=(0,tt.useMemo)(()=>(null==K?void 0:K.sourceTarget)===R?{target:ey,root:K.root,nodeCount:K.nodeCount,selectedUid:K.selectedUid,truncated:K.truncated,updatedAtMs:K.updatedAtMs}:void 0,[ey,R,K]),eS=(0,tt.useMemo)(()=>({exported_at:new Date().toISOString(),client_id:d,...eb?{command_id:null==ee?void 0:ee.command.commandId}:{},context:{launch_dir:eh.launchDir,manifest_url:_.manifestUrl,app_id:ef,app_name:eg.appName||_.manifest.name,mcp_endpoint:eh.mcpEndpoint,mcp_original_endpoint:eg.sources.mcp.original,mcp_proxy_endpoint:eg.sources.mcp.proxy,page_id:ed,page_path:eu,simulator_endpoint:_.simulator.endpoint,simulator_manifest_original_url:eg.sources.manifest.original,simulator_manifest_proxy_url:eg.sources.manifest.proxy,simulator_manifest_url:eh.simulatorManifestUrl,simulator_skill_original_url:eg.sources.skill.original,simulator_skill_proxy_url:eg.sources.skill.proxy,simulator_skill_url:eh.simulatorSkillUrl,web_url:eh.webUrl},render_targets:e_,runtime_snapshot:ew,page_runtime_trace_events:[],runtime_console:{app:{entries:q.appEntries,updated_at_ms:q.updatedAtMs},page:{entries:q.entries,updated_at_ms:q.updatedAtMs}},simulator:{stream_status:_.simulator.streamStatus,trace_events:_.simulator.traceEvents,tool_calls:_.simulator.toolCalls}}),[eg.appId,eg.appName,eg.sources.manifest.original,eg.sources.manifest.proxy,eg.sources.mcp.original,eg.sources.mcp.proxy,eg.sources.skill.original,eg.sources.skill.proxy,eh.launchDir,eh.mcpEndpoint,eh.simulatorManifestUrl,eh.simulatorSkillUrl,eh.webUrl,q,ed,eu,ef,d,eb,null==ee?void 0:ee.command.commandId,e_,_.manifest.name,_.manifestUrl,_.simulator.endpoint,_.simulator.streamStatus,_.simulator.toolCalls,_.simulator.traceEvents,ew]),ex=(0,tt.useMemo)(()=>f?_.simulator.traceEvents:_.simulator.traceEvents.filter(e=>{var t;return!(null==(t=e.display)?void 0:t.debugOnly)}),[f,_.simulator.traceEvents]),eI=(0,tt.useMemo)(()=>lJ(ex,{debug:f,messages:_.simulator.messages}),[f,_.simulator.messages,ex]),eE=(0,tt.useMemo)(()=>lG(eS,{debug:f}),[f,eS]),eC=(0,tt.useMemo)(()=>lz(eE),[eE]);(0,tt.useEffect)(()=>{let e=!0;return dp(null==u?void 0:u.debugScenesEndpoint).then(t=>{if(e)for(let e of(S(t),t.errors))null==h||h(`${e.name}: ${e.message}`,!0)}).catch(t=>{e&&(S({errors:[],scenes:[]}),null==h||h(t.message,!0))}),()=>{e=!1}},[null==u?void 0:u.debugScenesEndpoint,h]);let ek=sL(e=>{var t,r;let n=(null==(t=Z.current)?void 0:t.getCurrentTarget())??(null==(r=Z.current)?void 0:r.getCurrentAppTarget()),a=`[Debug Scene] ${e}`;n?it(n,{level:"error",message:a,pagePath:eu||void 0}):console.error(a)}),eN=sL(e=>{let t=ep.find(t=>t.key===e);t&&(t.key.startsWith(dh)?I(t.key):I(""),y.navigateToPage(t.url))}),eT=sL(e=>{lx(e,{onClearLogs:G,onMessage:h})}),eM=(0,tt.useMemo)(()=>({debugData:eg,events:eI,logSnapshot:eE,logSnapshotText:eC,sandbox:{available:W,csrRequired:(null==u?void 0:u.sandboxCsrRequired)!==!1,input:{csrPem:(null==u?void 0:u.sandboxCsrPem)??"",phoneNum:(null==u?void 0:u.sandboxPhoneNum)??""},logs:J,businessInfoStatus:H,location:z,sessionStatus:V},showDebugTrace:f,traceSurface:"page",toolCalls:_.simulator.toolCalls,updatedAtMs:Date.now()}),[eg,eI,eE,eC,J,H,z,W,V,null==u?void 0:u.sandboxCsrRequired,f,_.simulator.toolCalls]);dr(v,eS,K),(0,tt.useEffect)(()=>{if((null==l?void 0:l.type)==="render_page"&&Y(l,R))try{I(""),y.navigateToPage(l.url)}catch(e){er(l.commandId,{ok:!1,error:{code:"TARGET_NOT_FOUND",message:e.message}})}},[Y,l,R,er,y]),(0,tt.useEffect)(()=>{ee&&eb&&er(ee.command.commandId,{ok:!0,target:ey,snapshot:lV(eS)})},[ey,eb,ee,er,eS]);let eR=sL((e,t)=>{let r=tJ(y,{noLogin:null==t?void 0:t.noLogin});if("not_found"===r.status){null==h||h("未找到需要重发的原始消息",!0);return}if("streaming"===r.status){null==h||h("当前仍在生成中,暂不重发授权后的消息",!0);return}y.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==h||h(e.message,!0)})}),eA=sL((e,t)=>{eR(e,t),"login"===e&&(null==p||p("conversation"))}),eP=(0,tt.useMemo)(()=>a3({appId:ef,appIcon:_.manifest.iconSrc,appName:ev,baseAPIRegistry:null==g?void 0:g.apiRegistry,onGrantingCompleted:eA,sendFollowUpMessage:e=>{let{content:t,prompt:r}=e;return y.sendSimulatorQuery(r,{followUpContent:t})},multiMediaBroadcastContainer:E??void 0,runtimeHost:null==g?void 0:g.runtimeHost,scanCodePresenter:F.scanCodePresenter,showSandboxCashier:B.showCashier,uiPresenter:F.presenter,showSimulatorPermission:Q.showPermission,vibrationContainer:T??void 0}),[g,eA,ef,ev,T,E,B.showCashier,F.scanCodePresenter,F.presenter,Q.showPermission,_.manifest.iconSrc,y]);(0,tt.useEffect)(()=>{if(!E)return;let e=new sA({container:E,fileSystemNamespace:null==u?void 0:u.fileSystemNamespace,webSdkDebugger:y,onExitApp:()=>null==p?void 0:p("conversation"),onError:e=>{null==h||h(`Page runtime error: ${e.message}`,!0)},apiEnvironment:eP});Z.current=e;let t=e.subscribeTarget(t=>{A(t),D(e.getPageStackSize()),U(null)}),r=e.subscribeAppTarget(e=>{j(e)});return A(e.getCurrentTarget()),j(e.getCurrentAppTarget()),D(e.getPageStackSize()),()=>{t(),r(),e.destroy(),Z.current=null,A(null),j(null),D(0),U(null)}},[null==u?void 0:u.fileSystemNamespace,p,h,eP,E,y]),(0,tt.useEffect)(()=>{let e=Z.current;if(!e||!_.pageSelection){null==e||e.clear();return}try{e.render({device:ei})}catch(r){let e=r.message;em?ek(e):null==h||h(e,!0);let t=et.current;t&&er(t.command.commandId,{ok:!1,error:{code:"RENDER_FAILED",message:r.message}})}},[h,ek,er,E,ei,ed,em,_.pageSelection]);let ej=(0,tt.useMemo)(()=>({appTarget:P,controlCommand:l,controlTarget:_.pageSelection?R:null,debugState:eM,frontendUrl:o,onConsoleSnapshotChange:$,onControlResult:m,onDebugAction:eT,onHighlightChange:U,onRuntimeSnapshotChange:X,preserveConsoleOnTargetChange:!0,runtimeSnapshotTarget:ey,runtimeFrame:k,target:_.pageSelection?R:null}),[P,o,l,ey,eM,eT,m,R,k,_.pageSelection]);return(0,tt.useEffect)(()=>{null==c||c(ej)},[ej,c]),(0,i.jsxs)("div",{className:"wsd-page-preview-column",children:[(0,i.jsx)(oL,{activeView:s??"page",onActiveViewChange:p,onDeviceChange:el,selectedDeviceKey:es,children:(0,i.jsx)("button",{"aria-label":"Reload",className:"wsd-icon-button",disabled:!_.pageSelection,onClick:()=>{var e;return null==(e=Z.current)?void 0:e.reload()},title:"Reload",type:"button",children:(0,i.jsx)(oN,{"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:L<2,onClick:()=>{var e;return null==(e=Z.current)?void 0:e.closeCurrentPage()},title:"返回",type:"button",children:(0,i.jsx)(df,{})})}),(0,i.jsx)("div",{className:"wsd-page-route-select-wrapper",children:(0,i.jsx)(dd.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===b.length&&0===ec.length,listboxProps:{itemClasses:{base:"wsd-page-path-option",selectedIcon:"wsd-page-path-selected-icon"}},onChange:e=>eN(e.target.value),placeholder:eu||"No page",popoverProps:{offset:0},renderValue:e=>{var t;return(0,i.jsx)(dg,{value:String((null==(t=e[0])?void 0:t.textValue)??eu)})},selectedKeys:em?[em]:eu?[eu]:[],size:"sm",children:ep.map(e=>(0,i.jsx)(du.y,{textValue:e.url,children:(0,i.jsx)(dg,{showTooltip:!0,value:e.url})},e.key))})})]}),_.pageSelection?(0,i.jsx)(sz,{highlightRect:O,overlay:(0,i.jsxs)(i.Fragment,{children:[F.overlay,B.cashier?(0,i.jsx)(sV,{cashier:B.cashier,onCancel:B.cancelCashier,onConfirm:B.confirmCashier}):null,Q.permission?(0,i.jsx)(oC,{onAllow:Q.allowPermission,onReject:Q.rejectPermission,permission:Q.permission}):null]}),runtimeFrameRef:N,runtimeFrameScaleBoxRef:M,runtimeScaleMode:en,runtimeShellRef:eo,runtimeStyle:ea,runtimeTargetRef:C}):(0,i.jsx)("div",{className:"wsd-page-empty",children:"No page"})]})}async function dy(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 d_(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(r$("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:()=>{dy(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 db(e){let{id:t,name:r,onChange:n,onError:a,type:s,value:o}=e,[l,d]=(0,tt.useState)(JSON.stringify(o??("array"===s?[]:{}),null,2));function u(e,t){try{let t=JSON.parse(e);if(!("array"===s?Array.isArray(t):eJ(t)))throw Error(`expected a JSON ${s}`);n(t)}catch(e){t&&a(`${r}: ${e.message}`)}}return(0,i.jsx)("textarea",{"aria-label":`参数 ${r}`,className:"wsd-tool-complex-input",id:t,onBlur:()=>u(l,!0),onChange:e=>{let t=e.currentTarget.value;d(t),u(t,!1)},spellCheck:!1,value:l})}function dw(e){let{onChange:t,onError:r,schema:n,value:a}=e,s=(0,tt.useId)(),o=eJ(n.properties)?n.properties:{},l=new Set(Array.isArray(n.required)?n.required.filter(e=>"string"==typeof e):[]);function d(e,r){let n={...a};void 0===r?delete n[e]:n[e]=r,t(n)}return 0===Object.keys(o).length?(0,i.jsx)("div",{className:"wsd-tool-empty-input",children:"无需输入参数"}):(0,i.jsx)("div",{className:"wsd-tool-input-form",children:Object.entries(o).map(e=>{let[t,n]=e,o=eJ(n)?n:{},u="string"==typeof o.type?o.type:"string",c="string"==typeof o.description?o.description:"",p=Array.isArray(o.enum)?o.enum:void 0,m=a[t],h=`${s}-${t}`;return(0,i.jsxs)("label",{className:"wsd-tool-form-field",htmlFor:h,children:[(0,i.jsxs)("span",{className:"wsd-tool-form-field-title",children:[(0,i.jsx)("strong",{children:t}),l.has(t)?(0,i.jsx)("em",{children:"必填"}):null,(0,i.jsx)("small",{children:`${u}${p?" · enum":""}`})]}),c?(0,i.jsx)("span",{className:"wsd-tool-form-field-description",children:c}):null,p?(0,i.jsxs)("select",{"aria-label":`参数 ${t}`,id:h,onChange:e=>d(t,e.currentTarget.value?JSON.parse(e.currentTarget.value):void 0),value:void 0===m?"":JSON.stringify(m),children:[(0,i.jsx)("option",{value:"",children:"请选择"}),p.map(e=>(0,i.jsx)("option",{value:JSON.stringify(e),children:String(e)},JSON.stringify(e)))]}):"boolean"===u?(0,i.jsxs)("select",{"aria-label":`参数 ${t}`,id:h,onChange:e=>d(t,""===e.currentTarget.value?void 0:"true"===e.currentTarget.value),value:"boolean"==typeof m?String(m):"",children:[(0,i.jsx)("option",{value:"",children:"请选择"}),(0,i.jsx)("option",{value:"true",children:"true"}),(0,i.jsx)("option",{value:"false",children:"false"})]}):"array"===u||"object"===u?(0,i.jsx)(db,{id:h,name:t,onChange:e=>d(t,e),onError:r,type:u,value:m}):(0,i.jsx)("input",{"aria-label":`参数 ${t}`,id:h,onChange:e=>{d(t,function(e,t){if(e)return"number"===t||"integer"===t?Number(e):e}(e.currentTarget.value,u))},step:"integer"===u?1:"any",type:"number"===u||"integer"===u?"number":"text",value:"string"==typeof m||"number"==typeof m?m:""})]},t)})})}let dS=0;function dx(){return{callError:"",inputError:"",inputMode:"form",inputParams:{},inputText:"{}",isRunning:!1,selectedOutputIndex:0,selectedToolName:""}}function dI(e){var t;let r=null==e||null==(t=e.debug)?void 0:t.mcp_output,n=eJ(r)?[r]:[],a=!1,i=n.flatMap(e=>{if(Array.isArray(e.structuredContent)){a=!0;let t=e.structuredContent.filter(eJ);return t.length>0?t.map(t=>({...e,structuredContent:t})):[e]}if(!eJ(e.structuredContent)||!Array.isArray(e.structuredContent.entities))return[e];a=!0;let t=e.structuredContent.entities.filter(eJ);return t.length>0?t.map(t=>({...e,structuredContent:t})):[e]});return{collectionType:a?"entity":void 0,outputs:i}}function dE(e){return Array.isArray(null==e?void 0:e.content)?e.content.filter(eJ).map(e=>"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"):""}function dC(e){var t;let{onSessionChange:r,onUseWidgetOutput:n,session:a,...s}=e,o=di(s,"card"),l=null==(t=s.debugContext)?void 0:t.toolsConfigUrl,d=sL(e=>{var t;null==(t=s.onMessage)||t.call(s,e,!0)}),[u,c]=(0,tt.useState)({}),p=(0,tt.useMemo)(()=>{var e;return e=o.state.manifest.raw,eJ(e)&&eJ(e.tools)?Object.entries(e.tools).flatMap(t=>{let[r,n]=t;if(!eJ(n))return[];let a=u[r]??function e(t){return Array.isArray(t)?t.map(e):eJ(t)?Object.fromEntries(Object.entries(t).map(t=>{let[r,n]=t;return[r,"type"===r&&"int"===n?"integer":"type"===r&&"float"===n?"number":e(n)]})):t}(n.input_schema);return eJ(a)?[{description:"string"==typeof n.description?n.description:"",inputSchema:a,name:r,widgetId:function(e,t){for(let r of eJ(e.entities)?Object.values(e.entities):[]){if(!eJ(r)||!eJ(r.tool_card_binding))continue;let e=r.tool_card_binding[t];if("string"==typeof e&&e.trim())return e.trim()}}(e,r)}]:[]}):[]},[o.state.manifest,u]),{callError:m,copiedResultSection:h,inputError:g,inputMode:f,inputParams:v,inputText:y,isRunning:_,result:b,selectedOutputIndex:w,selectedToolName:S}=a,x=p.find(e=>e.name===S)??p[0],I=null==x?void 0:x.widgetId,E=dI(b),C=E.outputs,k=C[w]??C[0],N=eJ(null==k?void 0:k.structuredContent)?k.structuredContent:void 0,T=eJ(null==k?void 0:k._meta)?k._meta:void 0,M=dE(k);async function R(){let e;if(!x)return;try{e=r$("调用参数",y)}catch(e){r(t=>({...t,inputError:e.message}));return}let t=dS+=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:x.name});r(e=>{let r;return e.activeInvocationId===t?{...e,result:n,selectedOutputIndex:(r=dI(n).outputs.findIndex(e=>eJ(e.structuredContent)))<0?0:r}:e})}catch(e){r(r=>r.activeInvocationId===t?{...r,callError:e.message}:r)}finally{r(e=>e.activeInvocationId===t?{...e,activeInvocationId:void 0,isRunning:!1}:e)}}async function A(e,t){await dy("meta"===e?"META JSON":"STRUCTUREDCONTENT JSON",JSON.stringify(t,null,2),o.onMessage)&&r(t=>({...t,copiedResultSection:e}))}return(0,tt.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(eJ(e)&&Array.isArray(e.tools)?Object.fromEntries(e.tools.flatMap(e=>eJ(e)&&"string"==typeof e.name&&eJ(e.inputSchema)?[[e.name,e.inputSchema]]:[])):{})}).catch(t=>{e.signal.aborted||d(t.message)}),()=>e.abort()},[d,l]),(0,tt.useEffect)(()=>{x&&x.name!==S&&r(e=>({...e,selectedToolName:x.name}))},[r,x,S]),(0,i.jsx)(oD,{runtime:o,showReloadButton:!1,toolbarView:"tool",children:(0,i.jsx)("div",{className:"wsd-tool-debug",children:x?(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({...dx(),selectedToolName:t})},value:x.name,children:p.map(e=>(0,i.jsx)("option",{value:e.name,children:e.name},e.name))})]}),(0,i.jsx)("h2",{children:x.name}),x.description?(0,i.jsx)("p",{children:x.description}):null,(0,i.jsxs)("div",{className:"wsd-tool-input-heading",children:[(0,i.jsx)("span",{children:"输入参数 · INPUTSCHEMA"}),(0,i.jsx)("button",{className:"wsd-button wsd-button-ghost",onClick:function(){if("form"===f)return void r(e=>({...e,inputMode:"text"}));try{let e=r$("调用参数",y);r(t=>({...t,inputError:"",inputMode:"form",inputParams:e,inputText:JSON.stringify(e,null,2)}))}catch(e){r(t=>({...t,inputError:e.message}))}},type:"button",children:"form"===f?"文本模式":"表单模式"})]}),"form"===f?(0,i.jsx)(dw,{onChange:function(e){r(t=>({...t,inputError:"",inputParams:e,inputText:JSON.stringify(e,null,2)}))},onError:e=>r(t=>({...t,inputError:e})),schema:x.inputSchema,value:v},x.name):(0,i.jsx)(d_,{label:"调用参数",minHeight:160,onChange:e=>{r(t=>({...t,inputError:"",inputText:e}))},onMessage:o.onMessage,value:y}),g?(0,i.jsx)("span",{className:"wsd-tool-input-error",children:g}):null,(0,i.jsx)("button",{className:"wsd-button wsd-button-primary wsd-tool-run-button",disabled:_,onClick:()=>void R(),type:"button",children:_?"运行中…":"▶ 运行"})]}),b||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==b?void 0:b.status)==="succeeded"?"is-success":"is-error",children:(null==b?void 0:b.status)==="succeeded"?"运行成功":"运行失败"})]}),E.collectionType&&C.length>0?(0,i.jsxs)("label",{className:"wsd-tool-select-control wsd-tool-output-select-control",children:[(0,i.jsx)("span",{children:"entity"===E.collectionType?"Entity 元素":"数组元素"}),(0,i.jsx)("select",{"aria-label":"entity"===E.collectionType?"Entity 元素":"数组元素",onChange:e=>{let t=Number(e.currentTarget.value);r(e=>({...e,copiedResultSection:void 0,selectedOutputIndex:t}))},value:w,children:C.map((e,t)=>{let r,n,a;return(0,i.jsx)("option",{value:t,children:(n=[null==(r=eJ(e.structuredContent)?e.structuredContent:void 0)?void 0:r.name,null==r?void 0:r.title].find(e=>"string"==typeof e&&e.trim()),a=dE(e).split("\n")[0],`${t+1}. ${n||a||"空结果"}`)},t)})})]}):null,m||(null==b?void 0:b.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==b?void 0:b.error,null,2)})]}):null,M?(0,i.jsxs)("div",{className:"wsd-tool-result-block",children:[(0,i.jsx)("span",{children:"CONTENT"}),(0,i.jsx)("p",{children:M})]}):null,N?(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 A("structuredContent",N),type:"button",children:"structuredContent"===h?"已复制":"复制 JSON"})]}),(0,i.jsx)("pre",{children:JSON.stringify(N,null,2)})]}):null,T?(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 A("meta",T),type:"button",children:"meta"===h?"已复制":"复制 JSON"})]}),(0,i.jsx)("pre",{children:JSON.stringify(T,null,2)})]}):null,(null==b?void 0:b.status)==="succeeded"&&I&&N?(0,i.jsxs)("button",{className:"wsd-button wsd-button-primary wsd-tool-use-widget-output",onClick:()=>n({viewData:N,widgetId:I}),type:"button",children:["填入 ",I," 卡片预览"]}):null]}):null]}):(0,i.jsx)("div",{className:"wsd-page-empty",children:"No tool"})})})}var dk=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"})}),dN=r(48986),dT=r(80704),dM=r(51290),dR=r(36091);let dA=dM.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)"}}),dP=[(0,dN.Pq)(),(0,dT.pJ)(),(0,dT.bu)((0,dN.cp)()),dM.Lz.lineWrapping,dA];function dj(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)(dR.Ay,{basicSetup:{autocompletion:!0,bracketMatching:!0,closeBrackets:!0,foldGutter:!0,highlightActiveLine:!0,highlightActiveLineGutter:!0,lineNumbers:!0,searchKeymap:!0},extensions:dP,minHeight:`${r}px`,onChange:n,value:a})})}function dL(e){return eJ(e)?Object.fromEntries(Object.entries(e).flatMap(e=>{let[t,r]=e;return eJ(r)?[[t,r]]:[]})):{}}async function dD(){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(!eJ(n)||!eJ(n.templatesByEntry)&&!eJ(n.templatesByWidget))throw Error("Widget viewData 模板接口返回了无效数据");return{templatesByEntry:dL(n.templatesByEntry),templatesByWidget:dL(n.templatesByWidget)}}let dO="输入数据(structuredContent)",dU={};function dq(e){var t,r,n;let{initDataDraft:a,...s}=e,o=di(s,"card"),[l,d]=(0,tt.useState)("{}"),[u,c]=(0,tt.useState)([]),[p,m]=(0,tt.useState)({templatesByEntry:{},templatesByWidget:{}}),h=(0,tt.useRef)(!1),g=(0,tt.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]??dU,y=(0,tt.useMemo)(()=>u.flatMap(e=>{let t=eH(e.content);return"widget"===t.type&&t.id===o.selectedWidgetId?[{...t,sceneName:e.name}]:[]}),[u,o.selectedWidgetId]);(0,tt.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,tt.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,tt.useEffect)(()=>{var e;let t=!0;return dp(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 _=sL(async function(){var e,t;let r=arguments.length>0&&void 0!==arguments[0]&&arguments[0];try{let t=await dD(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,tt.useEffect)(()=>{_()},[null==(n=s.debugContext)?void 0:n.widgetViewDataTemplatesEndpoint,_]);let b=sL(e=>{h.current=!0,d(e)}),w=sL(async()=>{let e=await o.reloadResources();return e&&await _(!0),e});function S(){try{let e=r$(dO,l);o.renderSelectedWidget({initData:{viewData:e}})}catch(t){var e;null==(e=o.onMessage)||e.call(o,t.message,!0)}}return(0,tt.useEffect)(()=>{a&&(h.current=!0,d(JSON.stringify(a,null,2)))},[a]),(0,i.jsx)(oD,{runtime:{...o,reloadResources:w},children:o.state.widgetSelection?(0,i.jsx)(sz,{highlightRect:o.highlightRect,overlay:(0,i.jsxs)("section",{"aria-label":"卡片调试",className:(0,eK.$)("wsd-widget-card-debug",{"has-rendered-preview":o.hasRenderedPreview}),children:[(0,i.jsx)(sZ,{}),(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)(dk,{"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)(d_,{JsonEditorComponent:dj,label:dO,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,eK.$)({"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)(sV,{cashier:o.sandboxCashier.cashier,onCancel:o.sandboxCashier.cancelCashier,onConfirm:o.sandboxCashier.confirmCashier}):null,o.simulatorPermissionPrompt.permission?(0,i.jsx)(oC,{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 d$=r(85624);function dB(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 dF(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||!dB(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||!dB(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 dW="wsd-cdp-adapter",dH={jpeg:"image/jpeg",png:"image/png",webp:"image/webp"};function dz(e,t){return{ok:!1,error:{code:e,message:t}}}async function dV(e,t,r,n){if("take_snapshot"===e.type){if(!t||!r||!n)return dz("TARGET_NOT_FOUND","No Page or Widget target is currently rendered");let e=t.getInspectorSnapshot(),a=li(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 dz("TARGET_NOT_FOUND","No Page or Widget target is currently rendered");if("scroll_to"===e.type){if(e.uid&&!t.getElement(e.uid))return dz("ELEMENT_NOT_FOUND",`Element uid ${e.uid} was not found`);let n=await dF(e,t,r);return n?{ok:!0,result:n}:dz("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}}:dz("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}}:dz("ELEMENT_NOT_FOUND",`Element uid ${e.uid} was not found`)}let a=e.uid?t.getElement(e.uid):r;if(!a)return dz("ELEMENT_NOT_FOUND",`Element uid ${e.uid} was not found`);let i=dH[e.format],s=a.getBoundingClientRect(),o=a.offsetWidth||s.width,l=a.offsetHeight||s.height;try{let t=await (0,d$.TC)(a,{height:l,scale:3,type:i,width:o,...void 0!==e.quality&&"png"!==e.format?{quality:e.quality/100}:{},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 dz("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),...e.uid?{uid:e.uid}:{}}}}catch(e){return dz("SCREENSHOT_FAILED",e instanceof Error?e.message:String(e))}}function dG(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,tt.useRef)(null),S=(0,tt.useRef)(n),x=(0,tt.useRef)(h??null),I=(0,tt.useRef)(y??null),E=(0,tt.useRef)(b),C=(0,tt.useRef)({consoleTarget:_,getRuntimeFrame:m,onConsoleSnapshotChange:o,onDebugAction:s,onHighlightChange:d,onRuntimeSnapshotChange:u,preserveConsoleOnTargetChange:c,resolveTargetAtPoint:p}),k=(0,tt.useRef)(),N=(0,tt.useRef)(null),T=(0,tt.useRef)(null),M=(0,tt.useRef)(null),R=(0,tt.useRef)(null),A=(0,tt.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,tt.useCallback)(e=>{var t,r;A&&(null==(r=w.current)||null==(t=r.contentWindow)||t.postMessage({source:dW,type:"wsd-show-panel",panelId:e},A.origin))},[A]),L=sL(()=>{var e,t;let r=S.current;r&&A&&(null==(t=w.current)||null==(e=t.contentWindow)||e.postMessage({source:dW,type:"wsd-debug-state",state:r},A.origin))});return((0,tt.useEffect)(()=>{x.current=h??null},[h]),(0,tt.useEffect)(()=>{var e;I.current=y??null,null==(e=T.current)||e.call(T)},[y]),(0,tt.useEffect)(()=>{S.current=n,L();let e=[100,500,1e3].map(e=>window.setTimeout(L,e));return()=>e.forEach(e=>window.clearTimeout(e))},[n,L,P]),(0,tt.useEffect)(()=>{if(!f||!v)return;j(f);let e=[100,500].map(e=>window.setTimeout(()=>j(f),e));return()=>e.forEach(e=>window.clearTimeout(e))},[j,f,v]),(0,tt.useEffect)(()=>{C.current.onHighlightChange(null);let e=null==A?void 0:A.origin;R.current??=document.createElement("div");let t=new sI(E.current??R.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,li(s.root,s.selectedUid,i))},s=t=>{var r,n;e&&(null==(n=w.current)||null==(r=n.contentWindow)||r.postMessage({source:dW,...t},e))},o=t=>{var r,n;e&&(null==(n=w.current)||null==(r=n.contentWindow)||r.postMessage({source:dW,type:"cdp-raw-message",message:JSON.stringify(t)},e))};T.current=a,M.current=i;let l=t.subscribe(e=>{s(e),o(e),("WSD.consoleUpdated"===e.method||"WSD.appConsoleUpdated"===e.method)&&a(),("DOM.documentUpdated"===e.method||"DOM.inlineStyleInvalidated"===e.method||"Overlay.inspectNodeRequested"===e.method)&&i()}),d={method:"DOM.documentUpdated"};s(d),o(d),a(),i();let u=r=>{var n,a,i,l,d,u,c,p,m,h,g,f,v;if(!e||r.source!==(null==(n=w.current)?void 0:n.contentWindow)||r.origin!==e)return;let y=r.data;if((null==y?void 0:y.source)==="wsd-chrome-devtools-frontend"){if("ready"===y.type||"wsd-debug-ready"===y.type)return void L();if("wsd-debug-action"===y.type){let e=y.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==(l=(d=C.current).onDebugAction)||l.call(d,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==(u=(c=C.current).onDebugAction)||u.call(c,e);return}if((null==e?void 0:e.kind)==="update-sandbox-business-info"&&"string"==typeof e.phoneNum&&"string"==typeof e.csrPem){null==(p=(m=C.current).onDebugAction)||p.call(m,e);return}if((null==e?void 0:e.kind)==="recreate-sandbox-session"&&"string"==typeof e.phoneNum&&"string"==typeof e.csrPem){null==(h=(g=C.current).onDebugAction)||h.call(g,e);return}e&&("approve-tool-call"===e.kind||"reject-tool-call"===e.kind)&&"string"==typeof e.toolCallId&&(null==(f=(v=C.current).onDebugAction)||f.call(v,e));return}if("wsd-preact-devtools-message"===y.type)return void t.sendPreactDevtoolsMessage(y.payload);if("wsd-preact-highlight"===y.type){let e=y.uniqueId;t.highlightLynxNode("number"==typeof e?e:null);return}if("cdp-raw-message"===y.type&&"string"==typeof y.message){let e;try{e=JSON.parse(y.message)}catch{return}o(t.dispatch(e));return}"cdp-request"===y.type&&y.id&&s(t.dispatch({id:y.id,method:y.method??"",params:y.params,sessionId:y.sessionId}))}},c=e=>{let t=e.detail;if((null==t?void 0:t.type)==="PreactDevtools"&&"string"==typeof t.data)try{s({type:"wsd-preact-devtools-message",payload:JSON.parse(t.data)})}catch{}};return e&&(window.addEventListener("message",u),document.addEventListener("devtoolMessage",c)),()=>{window.removeEventListener("message",u),document.removeEventListener("devtoolMessage",c),l(),T.current===a&&(T.current=null),M.current===i&&(M.current=null),N.current===t&&(N.current=null),t.destroy(),C.current.onHighlightChange(null)}},[L,A]),(0,tt.useEffect)(()=>{var e,t,r,n;E.current=b,R.current??=document.createElement("div"),null==(e=N.current)||e.setConsoleTarget(_),null==(t=N.current)||t.setTarget(b??R.current),null==(r=T.current)||r.call(T),null==(n=M.current)||n.call(M)},[_,b]),(0,tt.useEffect)(()=>{if(!t||"render_page"===t.type||"render_widget"===t.type||"set_viewport"===t.type||"submit_chat_query"===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,dz("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 dV(t,N.current,e,g)}catch(e){r=dz("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:()=>{L(),f&&j(f)},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 dJ(e,t,r){return Math.min(Math.max(e,t),r)}function dK(e,t,r,n){if(!t)return dJ(e,r,n);let a=t.getBoundingClientRect().width;if(!a)return dJ(e,r,n);let i=Math.min(n,Math.max(r,a-8-340));return dJ(e,r,i)}function dX(e){var t,r;let{activeView:n="conversation",className:a,onActiveViewChange:s,...o}=e,[l,d]=(0,tt.useState)(dx),[u,c]=(0,tt.useState)(),[p,m]=(0,tt.useState)({onHighlightChange:()=>void 0,target:null}),h=sL(e=>{m(e)}),{isResizing:g,panelStyle:f,separatorProps:v}=function(){let{defaultWidth:e=520,minWidth:t=420,maxWidth:r=640}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},[n,a]=(0,tt.useState)(e),[i,s]=(0,tt.useState)(!1),o=(0,tt.useRef)(null),l=(0,tt.useMemo)(()=>({"--wsd-preview-column-width":`${n}px`}),[n]),d=sL((e,n)=>{if(!n)return;let i=n.getBoundingClientRect();i.width&&a(dK(e-i.left,n,t,r))});(0,tt.useEffect)(()=>()=>{var e;null==(e=o.current)||e.call(o)},[]);let u=sL(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=sL(e=>{let n=e.currentTarget.parentElement;if("ArrowLeft"===e.key){e.preventDefault(),a(e=>dK(e-24,n,t,r));return}if("ArrowRight"===e.key){e.preventDefault(),a(e=>dK(e+24,n,t,r));return}if("Home"===e.key){e.preventDefault(),a(dK(t,n,t,r));return}"End"===e.key&&(e.preventDefault(),a(dK(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}),y={...o,onChromeDevToolsPanelChange:h},_="page"===n?(0,i.jsx)(dv,{...y,activeView:n,onActiveViewChange:s}):"tool"===n?(0,i.jsx)(dC,{...y,onActiveViewChange:s,onSessionChange:d,onUseWidgetOutput:e=>{let{viewData:t,widgetId:r}=e;o.webSdkDebugger.selectWidget(r),c(t),null==s||s("card")},session:l}):"card"===n?(0,i.jsx)(dq,{...y,initDataDraft:u,onActiveViewChange:s}):(0,i.jsx)(ds,{...y,onActiveViewChange:s});return(0,i.jsxs)("section",{className:(0,eK.$)("page"===n?"wsd-page-panel":"wsd-widget-panel",g&&"is-resizing",a),style:f,children:[(0,i.jsx)(oe,{enabled:!!((null==(t=o.debugContext)?void 0:t.sandboxResourceEventsEndpoint)&&!1!==o.debugContext.sandboxSessionAvailable),eventsEndpoint:null==(r=o.debugContext)?void 0:r.sandboxResourceEventsEndpoint,onMessage:o.onMessage,webSdkDebugger:o.webSdkDebugger,children:_}),(0,i.jsx)("div",{className:"wsd-runtime-splitter",...v}),(0,i.jsx)(dG,{...p})]})}function dQ(e,t){null==e||e({category:"string"==typeof t.event&&(t.event.startsWith("simulator_manifest_")||t.event.startsWith("simulator_skill_")||t.event.startsWith("simulator_resources_"))?"resource":"mcp",source:"local_mcp",...t})}function dZ(e){return eV(e,{allowRootRelative:!0,baseUrl:window.location.href})}function dY(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,...Object.keys(t).length>0?{response_headers:t}:{}}}function d0(e,t,r){dQ(e,{event:`simulator_${t}_fetch_started`,phase:"request",url:r})}function d1(e,t,r,n){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};dQ(e,{event:`simulator_${t}_fetch_succeeded`,phase:"response",url:r,...dY(n),...a})}function d2(e,t,r,n,a){dQ(e,{event:`simulator_${t}_fetch_failed`,phase:"error",url:r,...a?dY(a):{},error:n instanceof Error?n.message:String(n)})}function d3(e,t,r){return Error(`Simulator ${e} failed: ${r.status} ${r.statusText} (${t})`)}let d4="web-sdk-debugger-demo",d5="mock_local_mcp",d8="mock_lookup",d6=["template-transport-card","template-price-action-card","template-ticket-order-card","weather-card","flight-card","api-demo-card","summary-card","configured-widget-id"],d7=[{server_id:d5,name:"Mock Local MCP",description:"Web SDK Debugger 本地模拟 MCP server",tools:[{name:d8,description:"返回用于本地调试的智能服务结构化结果",input_schema_json:JSON.stringify({type:"object",properties:{keyword:{type:"string"}},required:["keyword"]})}]}];function d9(e,t){return`id: evt_mock_${t.toString().padStart(4,"0")}
|
|
23
|
+
event: ${e.event}
|
|
24
|
+
data: ${JSON.stringify(e)}
|
|
25
|
+
|
|
26
|
+
`}function ue(e,t){return t.find(t=>null==e?void 0:e.widgets.some(e=>e.widgetId===t))}function ut(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 ur=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}}},un=tx(tl),ua=a3({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:tr(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?b(e,{statusCode:s.statusCode,header:s.header,data:function(e){let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)r[e]=t.charCodeAt(e);return r.buffer}(s.data)}):b(e,s)}});function ui(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 us(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 uo(){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"}});if(!r.ok)return{};return!(t=await r.json())||"object"!=typeof t||Array.isArray(t)?{}:t}catch{return{}}}async function ul(e,t){let r=t.skill,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 ud(){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 uu(){let e=(0,tt.useMemo)(()=>new URL(window.location.href).searchParams.get("manifest")||to,[]),t=(0,tt.useMemo)(()=>us("mcp","",void 0),[]),r=(0,tt.useMemo)(()=>{let e;return(e=new URL(window.location.href)).searchParams.get("mcpOriginal")||e.searchParams.get("mcpEndpoint")||""},[]),n=(0,tt.useMemo)(()=>us("simulatorManifest","/__simulator_manifest/manifest.yaml",void 0),[]),a=(0,tt.useMemo)(()=>new URL(window.location.href).searchParams.get("simulatorManifestOriginal")||"",[]),s=(0,tt.useMemo)(()=>us("simulatorSkill","/__simulator_skill/skill.md",void 0),[]),o=(0,tt.useMemo)(()=>new URL(window.location.href).searchParams.get("simulatorSkillOriginal")||"",[]),l=(0,tt.useMemo)(()=>tx(new URL(window.location.href).searchParams.get("simulator")||un),[]),d=(0,tt.useMemo)(()=>{let e;return(e=new URL(window.location.href)).searchParams.get("launchDir")||e.searchParams.get("projectPath")||e.searchParams.get("cwd")||""},[]),u=(0,tt.useMemo)(()=>`${window.location.origin}${window.location.pathname}`,[]),c=(0,tt.useMemo)(()=>{let e;return null!==(e=new URL(window.location.href).searchParams.get("DEBUG"))&&"0"!==e&&"false"!==e.toLowerCase()},[]),p=(0,tt.useMemo)(()=>"1"===new URL(window.location.href).searchParams.get("simulatorMock")||"true"===String((void 0)??"").toLowerCase(),[]),[m,h]=(0,tt.useState)({}),g=(0,tt.useMemo)(()=>crypto.randomUUID(),[]),[f,v]=(0,tt.useState)(),y=(0,tt.useRef)(new Set),_=(0,tt.useRef)(null),b=(0,tt.useMemo)(()=>(function(e){var t,r,n,a,i,s;let o,l=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},d={mcpEndpoint:dZ((t={mcpEndpoint:e,simulatorManifestUrl:l.simulatorManifestUrl,simulatorSkillUrl:l.simulatorSkillUrl}).mcpEndpoint),simulatorManifestUrl:dZ(t.simulatorManifestUrl),simulatorSkillUrl:dZ(t.simulatorSkillUrl)},u=function(){let e,t,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{mcpServers:async e=>{var t;let n=Object.entries(eJ(t=e.manifest??{})&&eJ(t.tools)?Object.fromEntries(Object.entries(t.tools).filter(e=>{let[,t]=e;return eJ(t)&&!0===t.is_client_tool})):{}).map(e=>{let[t,r]=e;if(!eJ(r))throw Error(`Client Tool "${t}" definition must be an object`);if("string"!=typeof r.description||!r.description.trim())throw Error(`Client Tool "${t}" requires description`);if(!eJ(r.input_schema))throw Error(`Client Tool "${t}" requires input_schema`);return{name:t,description:r.description,input_schema_json:function e(t){if(Array.isArray(t))return t.map(e);if(!eJ(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===n.length?(rc(r.onTraceEvent,{event:"client_tools_empty",app_key:e.appKey,server_id:rl,tool_count:0,tools:[]}),[]):(rc(r.onTraceEvent,{event:"client_tools_resolved",app_key:e.appKey,server_id:rl,tool_count:n.length,tools:n.map(e=>e.name)}),[{server_id:rl,name:"Client Tool",description:"Client Tool runtime for simulator debugging",tools:n}])},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(!eJ(t))throw Error("Tool arguments must be a JSON object");return t}(t),a="string"==typeof t.argumentsJson&&t.argumentsJson.trim()?t.argumentsJson:th(n)}catch(e){return rf("CLIENT_TOOL_INVALID_ARGUMENTS",tg(e),!1)}try{rc(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:th(n)});let i=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 rp(e,t)})(a,null==(n=r.getRuntimeGlobalProps)?void 0:n.call(r));e=new rg(a,t,r.onTraceEvent),rc(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}),s=function(e,t){var r,n;if(0===e.result)try{let n=function(e,t){if(!eJ(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){var r,n;let a,i,s=(r=t.manifest,n=t.toolName,a=eJ(r)&&eJ(r.tools)?r.tools:{},i=eJ(a[n])?a[n]:{},eJ(i.output)?i.output:void 0);if(!s||"string"!=typeof s.kind)throw Error(`Client Tool "${t.toolName}" manifest output is required`);if("execution_result"===s.kind)return e;if("entities"!==s.kind)throw Error(`Client Tool "${t.toolName}" has unsupported output kind "${s.kind}"`);if(!eJ(e)||!Array.isArray(e.structuredContent))throw Error(`Client Tool "${t.toolName}" must return structuredContent as an array`);return rs(e,t.manifest,t.toolName)}(n,t);return r=ro(a,{businessErrorCode:"CLIENT_TOOL_BUSINESS_ERROR",protocol:ru,source:"client_tool"}),{...r,debug:{...r.debug,mcp_output:n}}}catch(e){return rf("CLIENT_TOOL_INVALID_RESULT",tg(e),!1)}let a=void 0===(n=e.reason)?"":eJ(n)?"string"==typeof n.message?n.message:th(n):tg(n);return 2===e.result?rf("CLIENT_TOOL_NOT_FOUND",`Client Tool not found: ${e.toolId}`,!1):1===e.result?rf("CLIENT_TOOL_FAILED",a||`Client Tool failed: ${e.toolId}`,!1):rf("CLIENT_TOOL_UNKNOWN_RESULT",`Client Tool returned unknown status: ${String(e.result)}`,!1)}(i,t);return rc(r.onTraceEvent,{event:"succeeded"===s.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:s.status,result:s.result,raw_mcp_result_json:s.raw_mcp_result_json,...s.error?{error:s.error.message}:{}}),s}catch(n){let e=tg(n);return rc(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}),rf("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=d.mcpEndpoint?function(e){let t=eV(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{a5(e.onTraceEvent,{event:"local_mcp_tools_load_started",app_key:n.appKey,mcp_endpoint:t,server_id:r},n),a=await a6(t,e);let i=await a.client.listTools(),s=a.client.getServerVersion(),o={server_id:r,name:(null==s?void 0:s.name)||r,description:a.client.getInstructions()||"",tools:i.tools.map(a8).filter(e=>e.name)};return a5(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){return a5(e.onTraceEvent,{event:"local_mcp_tools_load_failed",app_key:n.appKey,mcp_endpoint:t,server_id:r,error:tg(a),request_will_continue:!0,tool_count:0,tools:[]},n),console.warn("[web-sdk-debugger] Failed to load MCP tools",a),[]}finally{a&&await a7(a)}},toolExecutor:async r=>{var n,a;let i,s=r.arguments??tp(r.argumentsJson)??{},o=r.argumentsJson||th(s),l=Date.now();try{if(a5(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:s,arguments_json:o,mcp_endpoint:t}),i=await a6(t,{...e,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)?void 0:n.aborted)throw a="MCP tool call aborted","u">typeof DOMException?new DOMException(a,"AbortError"):Object.assign(Error(a),{name:"AbortError"});let d=await i.client.callTool({name:r.toolName,arguments:s,_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:o}},r.signal?{signal:r.signal}:void 0),u=!0===d.isError?d:rs(d,r.manifest,r.toolName),c=ro(u,{businessErrorCode:"LOCAL_MCP_BUSINESS_ERROR",protocol:"streamable_http",source:"local_mcp"});c.debug={...c.debug,mcp_output:d};let p=tp(c.raw_mcp_result_json);return a5(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:c.status,result:c.result,structured_result_json:th(c.result),raw_result_text:c.raw_result_text,raw_mcp_result_json:c.raw_mcp_result_json,...void 0===p?{}:{raw_mcp_result:p},elapsed_ms:Date.now()-l,mcp_endpoint:t}),c}catch(a){if(t6(a))throw a;let n=tg(a);return a5(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()-l,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{i&&await a7(i)}}}}({endpoint:d.mcpEndpoint,onTraceEvent:l.onTraceEvent}):void 0,p=c?async e=>{let t=c.mcpServers,r=u.mcpServers;return[...await t(e),...await r(e)]}:u.mcpServers,m=u.toolExecutor,h=c?(r=c.toolExecutor,(o=e=>(e.serverId===rl?m:r)(e)).dispose=()=>{var e,t;null==(e=m.dispose)||e.call(m),null==(t=r.dispose)||t.call(r)},o):m;return{...d.simulatorManifestUrl?{simulatorManifest:(n=d.simulatorManifestUrl,a=l.onTraceEvent,async()=>{let e;d0(a,"manifest",n);try{if(!(e=await fetch(n,{cache:"no-store",headers:{Accept:"application/yaml, text/yaml, text/x-yaml, application/json, text/plain"}})).ok)throw d3("manifest",n,e);let t=await e.text(),r=function(e){let t=(0,ri.qg)(e);if(!eJ(t))throw Error("Simulator manifest must be a YAML object");return t}(t);return d1(a,"manifest",n,e,{bytes:t.length}),{...r,raw_manifest_yaml:t}}catch(t){throw d2(a,"manifest",n,t,e),console.warn("[web-sdk-debugger] Failed to load simulator manifest supplement",t),t}})}:{},...d.simulatorSkillUrl?{skill:(i=d.simulatorSkillUrl,s=l.onTraceEvent,async()=>{let e;d0(s,"skill",i);try{var t;if(!(e=await fetch(i,{cache:"no-store",headers:{Accept:"text/markdown, text/plain"}})).ok)throw d3("skill",i,e);let r=(await e.text()).trim();if(((null==(t=e.headers.get("content-type"))?void 0:t.toLowerCase())??"").includes("text/html")||/^<!doctype html\b|^<html[\s>]/i.test(r.trimStart()))throw Error(`Simulator skill returned HTML instead of markdown (${i})`);return d1(s,"skill",i,e,{bytes:r.length}),r}catch(t){throw d2(s,"skill",i,t,e),console.warn("[web-sdk-debugger] Failed to load simulator skill",t),t}})}:{},mcpServers:p,toolExecutor:h}})(t,{getClientToolRuntimeGlobalProps:()=>{var e;let t=null==(e=_.current)?void 0:e.getState().manifest;return t?e8(t):void 0},getClientToolRuntimeUrl:()=>{var e;let t=null==(e=_.current)?void 0:e.getState();return t?function(e,t,r){var n;let a;if(!eJ(t))return;let i=eJ(t.applet)?t.applet:{},s=eJ(i.web)?i.web:{},o="string"==typeof s.toolRuntimeEntry?s.toolRuntimeEntry.trim():"string"==typeof i.toolRuntimeEntry?i.toolRuntimeEntry.trim():"";if(!o)return;let l=new URL(o,((a=new URL(String(e),(null==(n=globalThis.location)?void 0:n.href)||"http://localhost/")).pathname.endsWith("/base/manifest.json")?a.pathname=a.pathname.slice(0,-18):a.pathname=a.pathname.replace(/\/[^/]*$/,"/"),a.search="",a.hash="",a));return r&&l.searchParams.set("__doubao_resource_reload",r),l.toString()}(t.manifestUrl,t.manifest.raw,t.resourceUrlVersion):void 0},onTraceEvent:e=>{var t;return null==(t=_.current)?void 0:t.appendSimulatorTraceEvent(e)},simulatorManifestUrl:n,simulatorSkillUrl:s}),[t,n,s]),w=(0,tt.useMemo)(()=>{let t=p?{appKey:d4,appName:"调试示例智能服务",mcpServers:d7,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"))?ue(s,[c]):void 0)||ue(s,d6)||(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||d4,widget_id:p,entity_id:"mock-entity-1",viewData:{source:"web-sdk-debugger-mock",keyword:g,widgetId:p},extra:{"doubao/outputTemplate":"mock.output.template"}},[ut(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),ut(n,"tool_call",{tool_call:{tool_call_id:f,tool_name:d8,server_id:d5,app_key:n.app_id||d4,arguments_json:JSON.stringify({keyword:g}),status:"PENDING",timeout_ms:2e3}},h),ut(n,"tool_status",{tool_status:{tool_call_id:f,status:"RUNNING",progress:.6,message:"Mock tool running"}},h),ut(n,"text_delta",{text_delta:{block_id:"block_mock_text",op:"append",delta:`Mock 已收到:${g}`}},h),ut(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),ut(n,"debug",{debug_event:{category:"mock",title:"Mock Simulator",summary:"本地 mock SSE 已生成 text/card/tool 事件",data:{widget_id:p},redaction_level:"none"}},h),ut(n,"answer_finish",{answer_finish:{status:"completed",finish_reason:"stop",usage:{output_tokens:12}}},h),ut(n,"reply_finish",{reply_finish:{status:"completed",finish_reason:"stop",event_count:7}},h)]).map(d9).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=_.current)?void 0:e.getState())??null}}),toolExecutor:ur}:{},r=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return new rA(e)}({manifestUrl:e,simulatorEndpoint:l,...b,...t});return _.current=r,r},[e,l,b,p]),[S,x]=(0,tt.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"}),I=sL((e,t)=>{ui(y.current,e)&&ts({clientId:g,commandId:e,...t},tn).catch(e=>console.error(e)).finally(()=>{v(t=>(null==t?void 0:t.commandId)===e?void 0:t)})}),E=sL(e=>{if("cancel_chat_query"===e.type){sX(w,e.commandId),I(e.commandId,{ok:!1,error:{code:"CHAT_TIMEOUT",message:"Chat query was cancelled after the debugger control timeout"}});return}v(e),("render_page"===e.type||"render_widget"===e.type||"submit_chat_query"===e.type)&&x("render_page"===e.type?"page":"render_widget"===e.type?"card":"conversation")}),C=sL(e=>{try{var t;null==(t=_.current)||t.navigateToPage(e.url)}catch{}x("page")}),k=sL(()=>{let{manifest:e}=w.getState();return{appKey:e.appId,appName:e.name}});(0,tt.useEffect)(()=>(function(e){let{clientId:t,endpoint:r="/__wsd_control_events",onCommand:n,onDisconnect:a}=e;if("u"<typeof EventSource)return()=>void 0;let i=new URL(r,window.location.href);i.searchParams.set("clientId",t);let s=new EventSource(i.toString());return s.onmessage=e=>{let t;try{t=JSON.parse(e.data)}catch{return}let r=function(e){if(!eJ(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&&eJ(e.structuredContent))return{commandId:e.commandId,type:e.type,widgetId:e.widgetId,structuredContent:e.structuredContent};if("set_viewport"===e.type&&ta(e.width)&&ta(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("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,...e.properties?{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,..."string"==typeof e.uid?{uid:e.uid}:{},..."number"==typeof r?{quality:r}:{}}}return"scroll_to"===e.type?(void 0===e.uid||"string"==typeof e.uid&&e.uid.trim())&&(void 0===e.x||ti(e.x))&&(void 0===e.y||ti(e.y))?{commandId:e.commandId,type:e.type,..."string"==typeof e.uid?{uid:e.uid}:{},..."number"==typeof e.x?{x:e.x}:{},..."number"==typeof e.y?{y:e.y}:{}}:null:null}(t);r&&n(r)},s.onerror=()=>null==a?void 0:a(),()=>s.close()})({clientId:g,onCommand:E,onDisconnect:()=>{let e=sX(w);e&&(ui(y.current,e),v(t=>(null==t?void 0:t.commandId)===e?void 0:t))}}),[g,E,w]),(0,tt.useEffect)(()=>{let t=!1;return w.loadManifest(e).then(()=>{if(!t){let t;return t=new URL(window.location.href),e===to?t.searchParams.delete("manifest"):t.searchParams.set("manifest",e),window.history.replaceState(null,"",t),ul(w,b)}}).catch(()=>{}),()=>{t=!0,w.destroy(),_.current===w&&(_.current=null)}},[e,b,w]),(0,tt.useEffect)(()=>{let e=!1;return uo().then(t=>{e||h(t)}),()=>{e=!0}},[]);let N=(0,tt.useMemo)(()=>({launchDir:d,mcpEndpoint:t,mcpOriginalEndpoint:r,mcpProxyEndpoint:t,simulatorManifestOriginalUrl:a,simulatorManifestProxyUrl:n,simulatorManifestUrl:n,simulatorSkillOriginalUrl:o,simulatorSkillProxyUrl:s,simulatorSkillUrl:s,webUrl:u,...m}),[d,t,r,a,n,o,s,u,m]);return(0,i.jsx)(te.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)(sU,{capability:N.realDeviceDebug,getAppIdentity:k,children:(0,i.jsx)(dX,{activeView:S,apiEnvironment:ua,chromeDevToolsFrontendUrl:"/chrome-devtools/inspector.html",controlCommand:f,controlClientId:g,debugContext:N,onActiveViewChange:x,onControlResult:I,onNavigateToPage:C,showDebugTrace:c,traceSnapshotEndpoint:"/__agent_trace",webSdkDebugger:w})})})})})})}function uc(){return window.location.pathname.startsWith("/chrome-devtools/")?(0,i.jsx)(ud,{}):(0,i.jsx)(uu,{})}ek=e=>({url:`/__webview/page?url=${encodeURIComponent(e)}`});let up=document.querySelector("#app");function um(){if(!up)throw Error("Cannot find #app");(0,e9.H)(up).render((0,i.jsx)(uc,{}))}("serviceWorker"in navigator?navigator.serviceWorker.register("/__webview/sw.js",{scope:"/"}).then(()=>navigator.serviceWorker.ready):Promise.resolve()).then(um,um)}},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:"576bbf433d",257:"4d55bd5ce8",350:"20d5b2a451",503:"cf61731bba",724:"a0014ddd5b",778:"cc9aea9d55",894:"bc96e803db",97:"71b9323071"})[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","922","48"],()=>h(14061));g=h.O(g)})();
|