@nnepoch/dtc-sdk 3.0.0
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/README.md +298 -0
- package/dist/browser/dtc-sdk-3.0.0.js +2 -0
- package/dist/cjs/index.cjs +38 -0
- package/dist/cjs/index.d.cts +5600 -0
- package/dist/esm/index.d.ts +5600 -0
- package/dist/esm/index.js +38 -0
- package/docs/api/api/classes/Animation.md +280 -0
- package/docs/api/api/classes/ApiRegistryError.md +60 -0
- package/docs/api/api/classes/Camera.md +601 -0
- package/docs/api/api/classes/Connect.md +257 -0
- package/docs/api/api/classes/Dlss.md +67 -0
- package/docs/api/api/classes/HighLighterEffect.md +173 -0
- package/docs/api/api/classes/Layer.md +444 -0
- package/docs/api/api/classes/Model.md +193 -0
- package/docs/api/api/classes/ModelPOI.md +279 -0
- package/docs/api/api/classes/ModelTransform.md +579 -0
- package/docs/api/api/classes/PathPatrol.md +337 -0
- package/docs/api/api/classes/Popup.md +323 -0
- package/docs/api/api/classes/Scene.md +272 -0
- package/docs/api/api/classes/Screen.md +157 -0
- package/docs/api/api/classes/TimeLine.md +274 -0
- package/docs/api/api/classes/UIPOI.md +318 -0
- package/docs/api/api/classes/WeatherSystem.md +581 -0
- package/docs/api/api/functions/createApiFacade.md +20 -0
- package/docs/api/api/index.md +45 -0
- package/docs/api/api/interfaces/ApiInstanceMap.md +107 -0
- package/docs/api/api/interfaces/ApiRegistryContext.md +47 -0
- package/docs/api/api/type-aliases/ApiFacade.md +7 -0
- package/docs/api/api/type-aliases/ApiModuleFactory.md +23 -0
- package/docs/api/api/type-aliases/ApiModuleKey.md +5 -0
- package/docs/api/api/type-aliases/ApiRegistry.md +7 -0
- package/docs/api/api/variables/API_MODULE_KEYS.md +5 -0
- package/docs/api/api/variables/PendingValidationSchemaMap.md +9 -0
- package/docs/api/api/variables/apiRegistry.md +7 -0
- package/docs/api/application/DTCEngine/classes/DTCEngine.md +738 -0
- package/docs/api/application/DTCEngine/index.md +11 -0
- package/docs/api/application/DTCEngine/interfaces/DTCEngineOptions.md +22 -0
- package/docs/api/index.md +7 -0
- package/docs/api/typedoc-sidebar.json +735 -0
- package/docs/api/types/enumerations/LayerEnum.md +21 -0
- package/docs/api/types/enumerations/ModelTransformType.md +251 -0
- package/docs/api/types/enumerations/VideoCodeType.md +37 -0
- package/docs/api/types/index.md +146 -0
- package/docs/api/types/interfaces/AnimationGetLengthRequest.md +29 -0
- package/docs/api/types/interfaces/AnimationPlayRequest.md +61 -0
- package/docs/api/types/interfaces/AnimationSetSpeedRequest.md +29 -0
- package/docs/api/types/interfaces/AnimationStartLoopRequest.md +53 -0
- package/docs/api/types/interfaces/AnimationStopLoopRequest.md +21 -0
- package/docs/api/types/interfaces/AnimationStopRequest.md +21 -0
- package/docs/api/types/interfaces/ApiRequestEnvelope.md +45 -0
- package/docs/api/types/interfaces/ApiResponseEnvelope.md +57 -0
- package/docs/api/types/interfaces/AuthErrorInfo.md +21 -0
- package/docs/api/types/interfaces/AuthSessionSnapshot.md +45 -0
- package/docs/api/types/interfaces/CameraFlyByPathRequest.md +37 -0
- package/docs/api/types/interfaces/CameraFlyToTargetRequest.md +29 -0
- package/docs/api/types/interfaces/CameraLookAtRequest.md +69 -0
- package/docs/api/types/interfaces/CameraObjFollowRequest.md +37 -0
- package/docs/api/types/interfaces/CameraSetFlySpeedRequest.md +13 -0
- package/docs/api/types/interfaces/CameraSetFovRequest.md +13 -0
- package/docs/api/types/interfaces/CameraSetPositionAndRotationRequest.md +21 -0
- package/docs/api/types/interfaces/CenterConnectResult.md +27 -0
- package/docs/api/types/interfaces/CenterEnvelope.md +33 -0
- package/docs/api/types/interfaces/CenterServiceInfo.md +33 -0
- package/docs/api/types/interfaces/CenterTokenAuthorizeResult.md +9 -0
- package/docs/api/types/interfaces/DlssSetEnableRequest.md +23 -0
- package/docs/api/types/interfaces/DlssSetQualityRequest.md +14 -0
- package/docs/api/types/interfaces/EngineConfig.md +127 -0
- package/docs/api/types/interfaces/EngineStatusInfo.md +59 -0
- package/docs/api/types/interfaces/FeatureToggleRequest.md +21 -0
- package/docs/api/types/interfaces/HighLighterEnableRequest.md +11 -0
- package/docs/api/types/interfaces/HighLighterRemoveHighLightModelRequest.md +21 -0
- package/docs/api/types/interfaces/HighLighterSetHighLightModelRequest.md +29 -0
- package/docs/api/types/interfaces/LayerAddRequest.md +61 -0
- package/docs/api/types/interfaces/LayerChildElementRequest.md +21 -0
- package/docs/api/types/interfaces/LayerModelAddRequest.md +75 -0
- package/docs/api/types/interfaces/LayerModelRemoveRequest.md +21 -0
- package/docs/api/types/interfaces/LayerPOIAddRequest.md +117 -0
- package/docs/api/types/interfaces/LayerSelectorRequest.md +21 -0
- package/docs/api/types/interfaces/LayerShowUIPopRequest.md +51 -0
- package/docs/api/types/interfaces/LayerSwitchModelRequest.md +29 -0
- package/docs/api/types/interfaces/ModelAddRequest.md +61 -0
- package/docs/api/types/interfaces/ModelBoundsRequest.md +21 -0
- package/docs/api/types/interfaces/ModelPOIAddRequest.md +53 -0
- package/docs/api/types/interfaces/ModelPOIDeleteByGroupRequest.md +13 -0
- package/docs/api/types/interfaces/ModelPOIDeleteByIdRequest.md +21 -0
- package/docs/api/types/interfaces/ModelPOIGetInfoRequest.md +21 -0
- package/docs/api/types/interfaces/ModelPOIUpdateRequest.md +53 -0
- package/docs/api/types/interfaces/ModelPOIVisibleByGroupRequest.md +21 -0
- package/docs/api/types/interfaces/ModelRemoveRequest.md +21 -0
- package/docs/api/types/interfaces/ModelSelectorRequest.md +21 -0
- package/docs/api/types/interfaces/ModelSetVisibleByTagsRequest.md +21 -0
- package/docs/api/types/interfaces/ModelSetVisibleRequest.md +29 -0
- package/docs/api/types/interfaces/ModelTransformNodeRequest.md +21 -0
- package/docs/api/types/interfaces/ModelTransformRestoreRequest.md +21 -0
- package/docs/api/types/interfaces/ModelTransformRotateByTargetRequest.md +85 -0
- package/docs/api/types/interfaces/ModelTransformRotateRequest.md +29 -0
- package/docs/api/types/interfaces/ModelTransformScaleRequest.md +37 -0
- package/docs/api/types/interfaces/ModelTransformStartMoveRequest.md +61 -0
- package/docs/api/types/interfaces/NetworkAdaptationActionResult.md +47 -0
- package/docs/api/types/interfaces/NetworkAdaptationActionStep.md +29 -0
- package/docs/api/types/interfaces/NetworkAdaptationState.md +41 -0
- package/docs/api/types/interfaces/NetworkDecisionTrace.md +53 -0
- package/docs/api/types/interfaces/NetworkDiagnosticsSnapshot.md +53 -0
- package/docs/api/types/interfaces/NetworkMetricsSnapshot.md +59 -0
- package/docs/api/types/interfaces/PathPatrolAddRequest.md +109 -0
- package/docs/api/types/interfaces/PathPatrolNodeRequest.md +21 -0
- package/docs/api/types/interfaces/PathPatrolSetTimeNodeRequest.md +37 -0
- package/docs/api/types/interfaces/PathPatrolUpdateRequest.md +53 -0
- package/docs/api/types/interfaces/PopupAddRequest.md +21 -0
- package/docs/api/types/interfaces/PopupDelayRequest.md +13 -0
- package/docs/api/types/interfaces/PopupItemRequest.md +61 -0
- package/docs/api/types/interfaces/PopupRemoveRequest.md +21 -0
- package/docs/api/types/interfaces/PopupShowDistanceRequest.md +13 -0
- package/docs/api/types/interfaces/PopupShowRequest.md +29 -0
- package/docs/api/types/interfaces/PopupSyncInfoRequest.md +37 -0
- package/docs/api/types/interfaces/QosEvent.md +65 -0
- package/docs/api/types/interfaces/QosReportingPayload.md +47 -0
- package/docs/api/types/interfaces/QosRuntimeContext.md +29 -0
- package/docs/api/types/interfaces/QosSessionContext.md +29 -0
- package/docs/api/types/interfaces/QosWarnErrorSummary.md +37 -0
- package/docs/api/types/interfaces/ResolvedEngineConfig.md +123 -0
- package/docs/api/types/interfaces/SceneListenCompassRequest.md +13 -0
- package/docs/api/types/interfaces/SceneSwitchRequest.md +13 -0
- package/docs/api/types/interfaces/ScreenSetSceneFPSRequest.md +14 -0
- package/docs/api/types/interfaces/ScreenSetSceneRenderBitrateRequest.md +15 -0
- package/docs/api/types/interfaces/ScreenSetScreenResolutionRequest.md +23 -0
- package/docs/api/types/interfaces/ScreenSetVideoDecodeRequest.md +13 -0
- package/docs/api/types/interfaces/SignallingAllocateResponse.md +27 -0
- package/docs/api/types/interfaces/StandardResponse.md +33 -0
- package/docs/api/types/interfaces/TimeSerialNode.md +21 -0
- package/docs/api/types/interfaces/TimelineNodeRequest.md +21 -0
- package/docs/api/types/interfaces/TimelinePlayRequest.md +53 -0
- package/docs/api/types/interfaces/TimelineSetSpeedRequest.md +37 -0
- package/docs/api/types/interfaces/TimelineStopRequest.md +45 -0
- package/docs/api/types/interfaces/UIPOIAddRequest.md +21 -0
- package/docs/api/types/interfaces/UIPOIDeleteByGroupRequest.md +13 -0
- package/docs/api/types/interfaces/UIPOIDeleteByIdRequest.md +21 -0
- package/docs/api/types/interfaces/UIPOIEnableOverlapRequest.md +13 -0
- package/docs/api/types/interfaces/UIPOIShowDistanceRequest.md +13 -0
- package/docs/api/types/interfaces/UIPOIUpdateRequest.md +21 -0
- package/docs/api/types/interfaces/UIPOIUpdateStateRequest.md +21 -0
- package/docs/api/types/interfaces/Vector3JsonInput.md +27 -0
- package/docs/api/types/interfaces/WeatherChangeSeasonRequest.md +21 -0
- package/docs/api/types/interfaces/WeatherOpenCameraFogRequest.md +69 -0
- package/docs/api/types/interfaces/WeatherSetAnimateTimeOfDayRequest.md +29 -0
- package/docs/api/types/interfaces/WeatherSetDayAndNightRequest.md +13 -0
- package/docs/api/types/interfaces/WeatherSetSceneTimeRequest.md +21 -0
- package/docs/api/types/interfaces/WeatherSetTimeSyncRequest.md +13 -0
- package/docs/api/types/interfaces/WeatherTypeRequest.md +27 -0
- package/docs/api/types/type-aliases/ApiCallback.md +21 -0
- package/docs/api/types/type-aliases/AuthWorkflowState.md +5 -0
- package/docs/api/types/type-aliases/DlssQuality.md +7 -0
- package/docs/api/types/type-aliases/EngineLogLevel.md +5 -0
- package/docs/api/types/type-aliases/EngineViewMode.md +5 -0
- package/docs/api/types/type-aliases/GetWeatherTypeRequest.md +7 -0
- package/docs/api/types/type-aliases/NetworkAdaptationActionType.md +7 -0
- package/docs/api/types/type-aliases/NetworkAdaptationLevel.md +7 -0
- package/docs/api/types/type-aliases/NetworkAdaptationMode.md +9 -0
- package/docs/api/types/type-aliases/QosEventName.md +9 -0
- package/docs/api/types/type-aliases/QosLevel.md +7 -0
- package/docs/api/types/type-aliases/QosStage.md +7 -0
- package/docs/api/types/type-aliases/QosStatus.md +7 -0
- package/docs/api/types/type-aliases/ScreenRenderBitratePreset.md +7 -0
- package/docs/api/types/type-aliases/Season.md +7 -0
- package/docs/api/types/type-aliases/Vector3Input.md +5 -0
- package/docs/api/types/variables/DlssQuality.md +57 -0
- package/docs/api/types/variables/QOS_EVENT_NAMES.md +7 -0
- package/docs/api/types/variables/ScreenRenderBitratePreset.md +39 -0
- package/docs/api/types/variables/ScreenRenderBitratePresetOptions.md +5 -0
- package/docs/api/types/variables/ScreenRenderBitratePresetValueMap.md +27 -0
- package/docs/api/types/variables/Season.md +33 -0
- package/package.json +86 -0
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import{EventEmitter as e,LogLevel as t,Logger as n}from"@epicgames-ps/lib-pixelstreamingcommon-ue5.6";import{z as r}from"zod";import i from"axios";import{Config as a,Flags as o,NumericParameters as s,OptionParameters as c,PixelStreaming as l}from"@epicgames-ps/lib-pixelstreamingfrontend-ue5.6";import{inflate as u}from"pako";var d=class extends Error{constructor(e,t,n){super(`Invalid payload for ${e}.${t}: ${n.map(e=>`${e.field}: ${e.reason}`).join(`; `)}`),this.moduleName=e,this.methodName=t,this.issues=n,this.name=`SDKValidationError`,this.code=`VALIDATION_ERROR`}toJSON(){return{name:this.name,code:this.code,message:this.message,module:this.moduleName,method:this.methodName,issues:this.issues}}};function f(e,t,n,r){let i=e.safeParse(t);if(i.success)return i.data;throw new d(n,r,i.error.issues.map(e=>({field:e.path.length>0?e.path.join(`.`):`<root>`,reason:e.message,code:e.code})))}function p(e){return e instanceof d?JSON.stringify(e.toJSON()):e instanceof Error?`${e.name}: ${e.message}`:String(e)}const m={debug(){},info(){},warn(){},error(){}},ee=[`silent`,`error`,`warn`,`info`,`debug`];function te(e){switch(e){case`silent`:return t.Disabled;case`error`:return t.Error;case`warn`:return t.Warning;case`info`:return t.Info;default:return t.Debug}}function ne(e){return typeof e==`string`&&ee.includes(e)}function re(e){if(e===void 0)return`info`;if(ne(e))return e;let t=typeof e==`string`?e:JSON.stringify(e);throw Error(`Invalid logger level: ${t}. Expected one of: ${ee.join(`, `)}.`)}function h(e){if(e===void 0)return``;try{let t=JSON.stringify(e);return t?` ${t}`:``}catch{return` ${String(e)}`}}var ie=class{constructor(e,t,n,r,i){this.driver=e,this.prefix=t,this.level=n,this.moduleName=r,this.reporter=i}shouldLog(e){let t={silent:0,error:1,warn:2,info:3,debug:4};return t[this.level]>=t[e]}debug(e,t){this.shouldLog(`debug`)&&this.driver.Debug(`${this.prefix} ${e}${h(t)}`.trim())}info(e,t){this.shouldLog(`info`)&&this.driver.Info(`${this.prefix} ${e}${h(t)}`.trim())}warn(e,t){this.reportWarnOrError(`warn`,e,t),this.shouldLog(`warn`)&&this.driver.Warning(`${this.prefix} ${e}${h(t)}`.trim())}error(e,t){this.reportWarnOrError(`error`,e,t),this.shouldLog(`error`)&&this.driver.Error(`${this.prefix} ${e}${h(t)}`.trim())}reportWarnOrError(e,t,n){this.reporter?.recordLogSignal({level:e,moduleName:this.moduleName,message:t,meta:n})}},ae=class{constructor(e,t=n,r){this.level=re(e),this.driver=t,this.driver.InitLogging(te(this.level),!1),this.reporter=r?.reporter??r?.qosMonitor}child(e){return new ie(this.driver,`[DTCEngine:${e}]`,this.level,e,this.reporter)}};const g={EngineIniting:`云渲染引擎初始化中...`,ServiceUrlInValid:`调度中心地址不正确,请检查中心地址!`,SerriceError:`调度中心连接失败,尝试重连中...`,SerriceUnAvaible:`没有服务资源,请检查服务是否启动!`,SerriceLoadingForWaiting:`服务资源启动中,请稍候!`,EngineWaiting:`云渲染服务坐席已满,当前排队人数:1人....`,EngineTockenChecking:`云引擎授权文件验证中...`,EngineTokenCheckFail:`云引擎授权许可无效,请联系管理员!`,EngineConnectioning:`云渲染引擎连接中...`,EngineConnectionSuccess:`云渲染引擎连接成功...`,EngineClose:`云渲染引擎连接断开,请检查服务状态!`,SourcePreparing:`资源准备中...`,TokenInValid:`许可未激活!`,TokenExpired:`许可授权已过期,实时渲染服务已停止!`,TokenWillExpired:`您的授权许可将于 YYYY-MM-DD 到期,请尽快续期!`};var oe=class{constructor(e){this.options=e,this.logger=e.logger??m}show(e,t,n=!0){if(console.log(`loading show`,e,t,n),this.options.emit({message:e,key:t,isFinish:!n}),!this.options.enabled)return;let r=this.getRoot();r&&(this.progressDiv||=this.createTipDiv(r,`engineProgressTips`),this.progressDiv.textContent=e,n||(this.clearAutoCloseTimer(),this.autoCloseTimer=setTimeout(()=>{this.removeProgressBar()},2e3)))}showTokenWillExpire(e,t=`TokenWillExpired`,n=!0){let r=this.formatTokenWillExpireMessage(e);if(this.options.emit({message:r,key:t,isFinish:!n}),!this.options.enabled)return;let i=this.getRoot();i&&(this.tokenWillExpireDiv||(this.tokenWillExpireDiv=this.createTipDiv(i,`TokenWillExpireTips`),this.tokenWillExpireDiv.style.top=`60px`),this.tokenWillExpireDiv.textContent=r)}dispose(){this.clearAutoCloseTimer(),this.removeProgressBar(),this.removeTokenWillExpireBar()}getRoot(){if(this.options.hostElement?.ownerDocument?.body)return this.options.hostElement.ownerDocument.body;if(typeof document<`u`&&document.body)return document.body;this.logger.debug(`skip loading progress ui render: document is unavailable`)}createTipDiv(e,t){let n=e.ownerDocument.createElement(`div`);return n.id=t,n.style.position=`fixed`,n.style.left=`50%`,n.style.top=`16px`,n.style.transform=`translateX(-50%)`,n.style.zIndex=`99999`,n.style.padding=`8px 14px`,n.style.borderRadius=`6px`,n.style.background=`rgba(0, 0, 0, 0.72)`,n.style.color=`#fff`,n.style.fontSize=`14px`,n.style.lineHeight=`1.4`,n.style.pointerEvents=`none`,n.style.maxWidth=`80vw`,n.style.textAlign=`center`,e.appendChild(n),n}removeProgressBar(){this.progressDiv&&=(this.progressDiv.remove(),void 0)}removeTokenWillExpireBar(){this.tokenWillExpireDiv&&=(this.tokenWillExpireDiv.remove(),void 0)}clearAutoCloseTimer(){this.autoCloseTimer&&=(clearTimeout(this.autoCloseTimer),void 0)}formatTokenWillExpireMessage(e){let t=e.trim();return t?t.includes(`到期`)?t:`您的授权许可将于 ${t}到期,请尽快续期!`:g.TokenWillExpired}};const se=`sdk3-agent-bridge/v1`;function ce(e){if(typeof WebSocket>`u`)throw Error(`WebSocket is not available in current runtime.`);return new WebSocket(e)}function le(e){return{ok:!0,data:e,ts:Date.now()}}function ue(e,t){return{ok:!1,error:{code:`PROTOCOL_ERROR`,message:e,details:t},ts:Date.now()}}function de(e){if(typeof e==`string`)try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return;let n=t;return n.protocolVersion!==`sdk3-agent-bridge/v1`||typeof n.type!=`string`||typeof n.callId!=`string`?void 0:n}catch{return}}var fe=class{constructor(e,t,n={}){this.runtime=e,this.options=t,this.reconnectAttempt=0,this.running=!1,this.startedAt=0,this.beforeUnloadHandler=()=>{this.stop(`pagehide`)},this.socketFactory=n.socketFactory??ce}start(){this.socket||(this.running=!0,this.openSocket(),typeof window<`u`&&(window.addEventListener(`beforeunload`,this.beforeUnloadHandler),window.addEventListener(`pagehide`,this.beforeUnloadHandler)))}stop(e=`stop`){this.running=!1,this.clearReconnect(),typeof window<`u`&&(window.removeEventListener(`beforeunload`,this.beforeUnloadHandler),window.removeEventListener(`pagehide`,this.beforeUnloadHandler)),this.clearHeartbeat(),this.runtime.dispose?.();let t=this.socket;t&&(t.readyState===1&&this.sendUnregister(e),this.clearSocketHandlers(t),t.close(1e3,e),this.socket=void 0)}openSocket(){this.startedAt=Date.now();let e=this.socketFactory(this.options.serverUrl??`ws://127.0.0.1:8787/sdk3-bridge`);this.socket=e,e.onopen=()=>{this.reconnectAttempt=0,this.sendRegister(),this.startHeartbeat()},e.onmessage=e=>{this.handleMessage(e.data)},e.onclose=()=>{this.clearSocketHandlers(e),this.clearHeartbeat(),this.socket===e&&(this.socket=void 0),this.scheduleReconnect()},e.onerror=()=>{this.clearHeartbeat()}}scheduleReconnect(){if(!this.running||this.reconnectTimer!==void 0||this.options.reconnect===!1)return;let e=this.getReconnectDelay();this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,!(!this.running||this.socket)&&this.openSocket()},e),this.reconnectAttempt+=1}getReconnectDelay(){let e=typeof this.options.reconnect==`object`?this.options.reconnect:void 0,t=Math.max(0,e?.initialDelayMs??1e3),n=Math.max(t,e?.maxDelayMs??15e3),r=Math.max(0,e?.jitterMs??500);return Math.min(n,t*2**this.reconnectAttempt)+Math.floor(Math.random()*(r+1))}clearReconnect(){this.reconnectTimer!==void 0&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0)}sendRegister(){let e={...this.runtime.getSnapshot(),heartbeatIntervalMs:this.getHeartbeatInterval(),capabilities:{catalog:!0,schema:!0,invoke:!0}};this.send({type:`register`,protocolVersion:se,bridgeId:e.bridgeId,ts:Date.now(),payload:e})}sendUnregister(e){let t={...this.runtime.getSnapshot(),reason:e};this.send({type:`unregister`,protocolVersion:se,bridgeId:t.bridgeId,ts:Date.now(),payload:t})}sendHeartbeat(){let e={...this.runtime.getSnapshot(),heartbeatIntervalMs:this.getHeartbeatInterval(),uptimeMs:Math.max(0,Date.now()-this.startedAt)};this.send({type:`heartbeat`,protocolVersion:se,bridgeId:e.bridgeId,ts:Date.now(),payload:e})}getHeartbeatInterval(){return Math.max(1e3,this.options.heartbeatIntervalMs??5e3)}startHeartbeat(){this.clearHeartbeat(),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeat()},this.getHeartbeatInterval())}clearHeartbeat(){this.heartbeatTimer!==void 0&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}async handleMessage(e){let t=de(e);if(t){if(t.type===`catalog`){let e=t.payload,n=e.kind===`modules`?le(this.runtime.listModules()):this.runtime.listMethods(e.moduleName??``);this.sendResult(t,`catalog`,n);return}if(t.type===`schema`){let e=t.payload;this.sendResult(t,`schema`,this.runtime.getMethodSchema(e.moduleName,e.methodName));return}if(t.type===`invoke`){this.sendResult(t,`invoke`,await this.runtime.invoke(t.payload));return}this.sendResult(t,`catalog`,ue(`Unsupported message type "${t.type}".`))}}sendResult(e,t,n){let r={requestType:t,result:n};this.send({type:`result`,protocolVersion:se,bridgeId:this.runtime.getSnapshot().bridgeId,callId:e.callId,ts:Date.now(),payload:r})}send(e){!this.socket||this.socket.readyState!==1||this.socket.send(JSON.stringify(e))}clearSocketHandlers(e){e.onopen=null,e.onmessage=null,e.onclose=null,e.onerror=null}};function pe(e,t){return t&&e.then(e=>{t(e)}).catch(e=>{t(e)}),e}var _=class{constructor(e,t,n){this.bridge=e,this.moduleName=t,this.logger=n?.logger??m}request(e,t,n,r){return pe(Promise.resolve().then(()=>{let n=r?f(r,t,this.moduleName,e):t;return r||this.logger.debug(`validation schema not configured`,{method:e}),this.logger.debug(`sending request`,{method:e}),this.bridge.sendRequest(this.moduleName,e,n)}).then(t=>(this.logger.info(`request success`,{method:e,code:t.code}),t)).catch(t=>{throw this.logger.warn(`request failed`,{method:e,error:p(t)}),t}),n)}requestStream(e,t,n,r){try{if(!this.bridge.sendStreamRequest)throw Error(`Current bridge does not support stream request`);let i=r?f(r,t,this.moduleName,e):t;return r||this.logger.debug(`validation schema not configured`,{method:e}),this.logger.debug(`sending stream request`,{method:e}),this.bridge.sendStreamRequest(this.moduleName,e,i,n)}catch(t){let r=t instanceof Error?t:Error(String(t));if(this.logger.warn(`stream request failed before send`,{method:e,error:p(r)}),n)try{n({type:`error`,requestId:``,error:r})}catch(t){this.logger.warn(`stream error callback failed`,{method:e,error:p(t)})}let i=Promise.reject(r);return Object.defineProperty(i,"requestId",{value:``,enumerable:!0}),i.cancel=()=>{},i}}};function me(e,t){let n=e*20037508.34/180,r=Math.log(Math.tan((90+t)*Math.PI/360))/(Math.PI/180);return r=r*20037508.34/180,{x:n,y:r}}function he(e,t){let n=e/20037508.34*180,r=t/20037508.34*180;return r=180/Math.PI*(2*Math.atan(Math.exp(r*Math.PI/180))-Math.PI/2),{x:n,y:r}}const v={EPSGType:{EPSG84:`4326`,EPSGWeb:`3857`,EPSGWorld:`0000`}};var y=class e{constructor(e=0,t=0,n=0,r=v.EPSGType.EPSG84){typeof e!=`number`&&(e=this.parseFloatDeal(e)),typeof t!=`number`&&(t=this.parseFloatDeal(t)),typeof n!=`number`&&(n=this.parseFloatDeal(n)),e!=e&&(e=0),t!=t&&(t=0),n!=n&&(n=0),this.x=e,this.y=t,this.z=n,this.ePSGType=r}parseFloatDeal(e){try{return parseFloat(e)}catch(e){return console.log(e),0}}set(e,t,n){return typeof e!=`number`&&(e=0),typeof t!=`number`&&(t=0),typeof n!=`number`&&(n=0),e!=e&&(e=0),t!=t&&(t=0),n!=n&&(n=0),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}clone(){return new e(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e,t){return t==null?(this.x+=e.x,this.y+=e.y,this.z+=e.z,this):this.addVectors(e,t)}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e,t){return t==null?(this.x-=e.x,this.y-=e.y,this.z-=e.z,this):this.subVectors(e,t)}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e,t){return t==null?(this.x*=e.x,this.y*=e.y,this.z*=e.z,this):this.multiplyVectors(e,t)}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this}clampScalar(t,n){let r=new e,i=new e;return r.set(t,t,t),i.set(n,n,n),this.clamp(r,i)}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(e,Math.min(t,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z),this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.subVectors(t,e).multiplyScalar(n).add(e)}cross(e,t){return t==null?this.crossVectors(this,e):this.crossVectors(e,t)}crossVectors(e,t){let n=e.x,r=e.y,i=e.z,a=t.x,o=t.y,s=t.z;return this.x=r*s-i*o,this.y=i*a-n*s,this.z=n*o-r*a,this}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}equals(e){return e.x==this.x&&e.y==this.y&&e.z==this.z}toString(){return JSON.stringify(this)}changeEPSGType(e){if(this.ePSGType!=e){if(e==v.EPSGType.EPSG84){let e=he(this.x,this.y);this.x=e.x,this.y=e.y}else if(e==v.EPSGType.EPSGWeb){let e=me(this.x,this.y);this.x=e.x,this.y=e.y}else console.log(`暂不支持[${this.ePSGType}]转换为${e}`);return this.ePSGType=e,this}}};const b={Off:0,Auto:1,DLAA:2,UltraQuality:3,Quality:4,Balanced:5,Performance:6,UltraPerformance:7},x={Auto:`auto`,Low:`low`,High:`high`,Super:`super`,Blue:`blue`},ge=[{label:`自动`,type:x.Auto,value:12e6},{label:`标清`,type:x.Low,value:4e6},{label:`高清`,type:x.High,value:8e6},{label:`超清`,type:x.Super,value:12e6},{label:`蓝光`,type:x.Blue,value:24e6}],_e={[x.Auto]:12e6,[x.Low]:4e6,[x.High]:8e6,[x.Super]:12e6,[x.Blue]:24e6};let ve=function(e){return e.VP8=`VP8`,e.VP9=`VP9`,e.AV1=`AV1`,e.H264=`H264`,e}({}),ye=function(e){return e.Model=`MODEL`,e.POI=`POI`,e}({});const S={Spring:0,Summer:1,Autumn:2,Winter:3};let be=function(e){return e[e.Linear=0]=`Linear`,e[e.EaseInQuad=1]=`EaseInQuad`,e[e.EaseOutQuad=2]=`EaseOutQuad`,e[e.EaseInOutQuad=3]=`EaseInOutQuad`,e[e.EaseOutInQuad=4]=`EaseOutInQuad`,e[e.EaseInCubic=5]=`EaseInCubic`,e[e.EaseOutCubic=6]=`EaseOutCubic`,e[e.EaseInOutCubic=7]=`EaseInOutCubic`,e[e.EaseOutInCubic=8]=`EaseOutInCubic`,e[e.EaseInQuart=9]=`EaseInQuart`,e[e.EaseOutQuart=10]=`EaseOutQuart`,e[e.EaseInOutQuart=11]=`EaseInOutQuart`,e[e.EaseOutInQuart=12]=`EaseOutInQuart`,e[e.EaseInQuint=13]=`EaseInQuint`,e[e.EaseOutQuint=14]=`EaseOutQuint`,e[e.EaseInOutQuint=15]=`EaseInOutQuint`,e[e.EaseOutInQuint=16]=`EaseOutInQuint`,e[e.EaseInSine=17]=`EaseInSine`,e[e.EaseOutSine=18]=`EaseOutSine`,e[e.EaseInOutSine=19]=`EaseInOutSine`,e[e.EaseOutInSine=20]=`EaseOutInSine`,e[e.EaseInExpo=21]=`EaseInExpo`,e[e.EaseOutExpo=22]=`EaseOutExpo`,e[e.EaseInOutExpo=23]=`EaseInOutExpo`,e[e.EaseOutInExpo=24]=`EaseOutInExpo`,e[e.EaseInCirc=25]=`EaseInCirc`,e[e.EaseOutCirc=26]=`EaseOutCirc`,e[e.EaseInOutCirc=27]=`EaseInOutCirc`,e[e.EaseOutInCirc=28]=`EaseOutInCirc`,e[e.EaseInElastic=29]=`EaseInElastic`,e[e.EaseOutElastic=30]=`EaseOutElastic`,e[e.EaseInOutElastic=31]=`EaseInOutElastic`,e[e.EaseOutInElastic=32]=`EaseOutInElastic`,e[e.EaseInBack=33]=`EaseInBack`,e[e.EaseOutBack=34]=`EaseOutBack`,e[e.EaseInOutBack=35]=`EaseInOutBack`,e[e.EaseOutInBack=36]=`EaseOutInBack`,e[e.EaseInBounce=37]=`EaseInBounce`,e[e.EaseOutBounce=38]=`EaseOutBounce`,e[e.EaseInOutBounce=39]=`EaseInOutBounce`,e[e.EaseOutInBounce=40]=`EaseOutInBounce`,e}({});const C=r.string().min(1),w=C.optional(),T=r.number().finite(),E=T.optional(),D=r.instanceof(y),xe=r.object({x:T,y:T,z:T,ePSGType:C}),O=r.union([D,xe]),Se=D.optional(),Ce=O.optional(),we=r.union([r.literal(S.Spring).describe(`春季`),r.literal(S.Summer).describe(`夏季`),r.literal(S.Autumn).describe(`秋季`),r.literal(S.Winter).describe(`冬季`)]).describe(`场景季节`),Te=r.union([r.literal(b.Off).describe(`关闭 DLSS`),r.literal(b.Auto).describe(`自动质量档位`),r.literal(b.DLAA).describe(`DLAA 2倍效果`),r.literal(b.UltraQuality).describe(`超高质量`),r.literal(b.Quality).describe(`高质量`),r.literal(b.Balanced).describe(`平衡`),r.literal(b.Performance).describe(`性能`),r.literal(b.UltraPerformance).describe(`超高性能`)]).describe(`DLSS 质量档位`),Ee=r.union([r.literal(x.Auto).describe(`自动`),r.literal(x.Low).describe(`标清`),r.literal(x.High).describe(`高清`),r.literal(x.Super).describe(`超清`),r.literal(x.Blue).describe(`蓝光`)]).describe(`渲染码率档位`),De=r.union([r.literal(`VP8`).describe(`VP8`),r.literal(`VP9`).describe(`VP9`),r.literal(`AV1`).describe(`AV1`),r.literal(`H264`).describe(`H264`)]).describe(`视频解码器类别`),Oe=r.union([r.literal(`MODEL`).describe(`模型图层`),r.literal(`POI`).describe(`POI 图层`)]).describe(`图层类别`),ke=r.union([C,r.array(C).min(1)]),k=r.undefined().optional(),Ae=r.object({parentId:r.string().optional(),id:w}),je=e=>e.refine(e=>!!(e.id||e.timelineId),{message:`id or timelineId is required`}),Me={connect:k,disconnect:k,reconnect:k,KickOtherConnect:k,KeepConnect:k,GetEngineServiceStatus:k},A={lookAt:r.object({parentId:r.string().optional(),id:ke,offSet:Ce,positionOffSetDistance:E,offSetX:E,distance:E,time:E,isRotate:r.boolean().optional(),isHighlight:r.boolean().optional(),showBack:r.boolean().optional()}),lookAtArray:r.object({parentId:w,ids:r.array(C).min(1),offSet:Ce,offSetX:E,distance:E,time:E,isRotate:r.boolean().optional(),isHighlight:r.boolean().optional()}),flyToTarget:r.object({point:Ce,target:Ce,time:E}),flyByPath:r.object({points:r.union([r.array(D),r.string()]).optional(),lookAts:r.union([r.array(D),r.string()]).optional(),nodes:r.string().optional(),time:E,smoothMode:r.union([r.literal(0),r.literal(1)]).optional()}),setFlySpeed:r.object({speed:T}),endFly:k,pauseFly:k,resumeFly:k,getCameraInfo:k,setCameraPositionAndRotation:r.object({point:D,rotation:D}),setCameraFov:r.object({fov:T}),startCameraObjFollow:r.object({parentId:r.string().optional(),id:C,offSet:O,smooth:T.optional().default(.85).refine(e=>e>=0&&e<=1,{message:`smooth must be in [0, 1]`,path:[`smooth`]})}),endCameraObjFollow:k,resetCameraFov:k,reset:k},j={getAllSceneName:k,switchSceneByName:r.object({sceneName:C}),getCurrentSceneName:k,listenMapCompass:r.object({enable:r.boolean()}),setFeatureToggle:r.object({key:C,enabled:r.boolean()}),getSceneMeta:k},Ne={setVisible:r.object({parentId:r.string().optional().default(``),id:ke,visible:r.boolean().optional()}),setVisibleResolved:r.object({parentId:r.string().optional(),ids:r.array(C).min(1),visible:r.boolean()}),setVisibleByTags:r.object({tags:ke,visible:r.boolean()}),add:r.object({parentId:r.string().optional().default(``),id:C,assetsPath:w,position:Se,angle:Se,scale:Se,description:r.string().optional()}),remove:r.object({parentId:r.string().optional().default(``),ids:r.array(C).min(1)}),getElementTree:r.object({parentId:r.string().optional().default(``),id:C}),getModelInfo:r.object({parentId:r.string().optional().default(``),id:C}),getModelBoundsInfo:r.object({parentId:r.string().optional().default(``),id:ke}),getModelBoundsInfoResolved:r.object({parentId:r.string().optional(),ids:r.array(C).min(1)})},M=r.object({parentId:r.string().optional(),id:C}),Pe=r.object({parentId:r.string().optional(),ids:r.array(C).min(1)}),Fe=M.extend({rotate:D}),N={startMoveByNodes:M.extend({nodes:r.array(O).min(1),speed:T.optional().default(1),linear:T.optional().default(1),isLookAtTarget:r.boolean().optional().default(!1),needDirection:r.boolean().optional().default(!0)}),pauseMove:M,resumeMove:M,endMove:M,restoreMove:Pe,rotate:Fe,endRotate:M,continuedRotate:Fe,rotateByTarget:M.extend({parentTargetId:w,targetID:C,point:D,axisX:T.optional().default(0),axisY:T.optional().default(0),axisZ:T.optional().default(0),angle:T.optional().default(0),isPersistence:r.boolean().optional().default(!1)}),restoreRotate:Pe,setScale:M.extend({scale:D,duration:T.optional().default(.5)}),endScale:M,restoreScale:Pe},Ie={enable:r.object({enable:r.boolean()}),setHighLightModel:r.object({parentId:r.string().optional().default(``),ids:r.array(C).min(1),showBack:r.boolean()}),removeHighLightModel:r.object({parentId:r.string().optional(),ids:r.array(C).min(1)}),clear:r.object({})},Le=r.object({parentId:w,id:w}),Re=e=>e.refine(e=>!!(e.id||e.parentId),{message:`id or parentId is required`}),P={addLayer:Re(Le.extend({layerName:r.string().optional(),show:r.boolean().optional(),poiEnabled:r.boolean().optional(),type:Oe.optional(),description:r.string().optional()})),addLayerResolved:r.object({parentId:r.string().optional(),id:C,layerName:r.string().optional(),show:r.boolean().optional().default(!0),poiEnabled:r.boolean().optional().default(!0),description:r.string().optional().default(``),isSystem:r.boolean().optional().default(!1)}),layerSelector:Re(Le),removeLayer:Re(Le),isLayerOrGroupExit:Re(Le),layerSelectorResolved:r.object({parentId:r.string().optional().default(``),id:C}),switchModelLayer:r.object({parentId:C,ids:r.array(C).min(1),toParentId:C}),showUIPop:r.object({parentId:r.string().optional(),id:C,visible:r.boolean().optional().default(!0),assetsPath:r.string().optional().default(``),offSet:O,scale:O}),addModel:r.object({parentId:C,id:C,assetsPath:w,position:O,rotation:O,scale:O,description:r.string().optional(),isSystem:r.boolean().optional(),tags:r.array(r.string()).optional()}),addPOI:r.object({parentId:r.string().optional(),id:C,assetsPath:C,position:O,targetParentId:r.string().optional(),targetId:r.string().optional(),rotation:O,scale:O,offSet:O,description:r.string().optional(),isSystem:r.boolean().optional(),text:r.string(),fontSize:r.number().optional(),tags:r.array(r.string()).optional()}),removeModel:r.object({parentId:C,ids:r.array(C).min(1)}),getLayerChildElement:r.object({parentId:r.string().optional().default(``),id:C})},F={closeCameraFog:k,getWeatherTypes:k,resetWeather:k,resetWeatherAndTime:k,openCameraFog:r.object({fogIntensity:E,fogStartColor:r.string().optional(),fogEndColor:r.string().optional(),fogStartDistance:E,fogEndDistance:E,directionalIntensity:E,directionalFallOff:E,directionalColor:r.string().optional()}).refine(e=>e.fogIntensity===void 0||e.fogIntensity>=0&&e.fogIntensity<=1,{message:`fogIntensity must be between 0 and 1`,path:[`fogIntensity`]}),setSceneTime:r.object({hour:T,timeDuration:E}).refine(e=>e.hour>=0&&e.hour<24,{message:`hour must be in [0, 24)`,path:[`hour`]}),changeWeatherType:r.object({type:T,timeDuration:E}),setAnimateTimeOfDay:r.object({isAnimate:r.boolean(),dayLength:E,nightLength:E}),changeSeason:r.object({season:we,duration:E.describe(`切换过渡时长,单位秒`)}),resetSeason:r.object({}),setTimeSync:r.object({syncSystemTime:r.boolean()}),resetSceneTime:r.object({}),setDayAndNight:r.object({dayType:C})},I={add:r.object({groupName:C,poiInfos:r.array(r.record(r.unknown())).min(1)}),deleteById:r.object({groupName:C,id:C}),deleteByGroup:r.object({groupName:C}),update:r.object({groupName:C,poiInfos:r.array(r.record(r.unknown())).min(1)}),updatePopStates:r.object({groupName:C,popStates:r.array(r.record(r.unknown())).min(1)}),enableOverlap:r.object({enable:r.boolean()}),showDistance:r.object({distance:T})},L={add:r.object({id:C,groupName:C,assetPath:C,targetParentId:w,targetId:w,visible:r.boolean().optional()}),deleteById:r.object({groupName:C,ids:r.array(C).min(1)}),deleteByGroup:r.object({groupName:C}),getPOIInfo:r.object({groupName:C,id:C}),update:r.object({id:C,groupName:C,assetPath:w,targetParentId:w,targetId:w,visible:r.boolean().optional()}),setVisibleByGroup:r.object({groupName:C,visible:r.boolean()})},ze=r.array(r.object({groupName:C,id:C,parentId:r.string().optional().default(``),position:Se})),R={addPop:ze,removePop:ze,removeAll:ze,show:ze,showAll:ze,setPopDelayFrame:r.object({time:T}),setPopShowDistance:r.object({distance:T})},z={startLoopAnimation:r.object({parentId:w,id:C,stateName:C,loopStartTime:E,loopEndTime:E,speed:E}).refine(e=>e.loopStartTime===void 0||e.loopStartTime>=0&&(e.loopEndTime===void 0||e.loopEndTime>e.loopStartTime),{message:`loopStartTime must be >= 0 and loopEndTime must be greater than loopStartTime`,path:[`loopStartTime`]}),stopLoopAnimation:r.object({parentId:w,id:C}),playAnimator:r.object({parentId:w,id:C,stateName:C,speed:E,startTime:E,endTime:E,isStop:r.boolean().optional()}),setAnimatorSpeed:r.object({parentId:w,id:C,speed:T}),getAnimationLength:r.object({parentId:w,id:C,stateName:C}),stopAnimator:r.object({parentId:w,id:C})},B={play:je(Ae.extend({initialTime:E,speed:E,keepLastFrame:r.boolean().optional()}).refine(e=>e.speed===void 0||e.speed<0||e.speed>=.1,{message:`speed must be negative or >= 0.1`,path:[`speed`]})),pause:je(Ae),resume:je(Ae),stop:je(Ae.extend({resetTime:E,isCameraToStart:r.boolean().optional()})),stopAll:r.object({}).optional(),setSpeed:je(Ae.extend({speed:T}).refine(e=>e.speed<0||e.speed>=.1,{message:`speed must be negative or >= 0.1`,path:[`speed`]}))},Be={setSceneRenderBitrate:r.object({bitrate:Ee.optional()}),setSceneRenderBitrateResolved:r.object({bitrate:T}).refine(e=>e.bitrate>=1e6,{message:`bitrate must be >= 1000000`,path:[`bitrate`]}),setSceneFPS:r.object({fps:T}).refine(e=>e.fps>=1&&e.fps<=300,{message:`fps must be in [1, 300]`,path:[`fps`]}),setVideoDecode:r.object({decode:De}),setScreenResolution:r.object({width:T,height:T}).refine(e=>e.width>0&&e.height>0,{message:`width and height must be > 0`,path:[`width`]})},Ve={setDlssEnable:r.object({enable:r.boolean(),quality:Te}),setDlss:r.object({enable:r.boolean(),quality:Te}),setDlssQuality:r.object({quality:Te})},He=r.object({node:O,time:r.string()}),Ue=r.object({parentId:r.string().optional().default(``),id:C}),V={add:r.object({parentId:r.string().optional().default(``),id:C,assetPath:r.string().optional().default(``),scale:O,showPath:r.boolean().optional().default(!0),passedColor:r.string().optional().default(`#ffffff`),lineColor:r.string().optional().default(`#00ff00`),lineWidth:T,duration:E,nodes:r.array(O).optional(),timeNodes:r.array(He).optional(),lineLayer:w,afterRender:r.boolean().optional().default(!1)}),update:r.object({parentId:r.string().optional().default(``),id:C,lineColor:r.string().optional(),lineWidth:E,passedColor:r.string().optional(),speed:E}).refine(e=>e.speed===void 0||e.speed>=0,{message:`speed must be >= 0`,path:[`speed`]}),setTimeNode:r.object({parentId:r.string().optional().default(``),id:C,timeStart:r.string().optional(),startNodeIndex:r.string().optional()}).refine(e=>e.timeStart!==void 0||e.startNodeIndex!==void 0,{message:`timeStart or startNodeIndex is required`,path:[`timeStart`]}).refine(e=>e.startNodeIndex===void 0||parseInt(e.startNodeIndex)>=0,{message:`startNodeIndex must be >= 0`,path:[`startNodeIndex`]}),node:Ue,pause:Ue,resume:Ue,stop:Ue,clear:r.object({}).optional()},We={},Ge={Connect:Me,Camera:A,Scene:j,Layer:P,Model:Ne,ModelTransform:N,HighlighterEffect:Ie,UIPOI:I,ModelPOI:L,Popup:R,Animation:z,TimeLine:B,Screen:Be,Dlss:Ve,WeatherSystem:F,PathPatrol:V};var Ke=class extends _{constructor(e,t){super(e,`Animation`,t)}startLoopAnimation(e,t){let n={...e,speed:e.speed??1};return this.request(`startLoopAnimation`,n,t,z.startLoopAnimation)}stopLoopAnimation(e,t){return this.request(`stopLoopAnimation`,e,t,z.stopLoopAnimation)}playAnimator(e,t){let n={...e,speed:e.speed??1,startTime:e.startTime??0,endTime:e.endTime??1,isStop:e.isStop??!1};return this.request(`playAnimator`,n,t,z.playAnimator)}setAnimatorSpeed(e,t){return this.request(`setAnimatorSpeed`,e,t,z.setAnimatorSpeed)}getAnimationLength(e,t){return this.request(`getAnimationLength`,e,t,z.getAnimationLength)}stopAnimator(e,t){return this.request(`stopAnimator`,e,t,z.stopAnimator)}},qe=class extends _{constructor(e,t){super(e,`CameraService`,t)}lookAt(e,t){let n={...e,time:e.time??3,distance:e.distance??20,isRotate:e.isRotate??!0,isHighlight:e.isHighlight??!0,offSet:e.offSet??new y(-50,100,100)};if(n.offSet&&(n.offSet.ePSGType=`0000`),Array.isArray(n.id)){let e={parentId:n.parentId,ids:n.id,offSet:n.offSet,offSetX:n.offSetX,distance:n.distance,time:n.time,isRotate:n.isRotate,isHighlight:n.isHighlight};return this.request(`LookAtArray`,e,t,A.lookAtArray)}return this.request(`LookAt`,n,t,A.lookAt)}flyToTarget(e,t){let n={...e,time:e.time??2};return this.request(`FlyToTarget`,n,t,A.flyToTarget)}flyByPath(e,t){let n=Array.isArray(e.points)?JSON.stringify(e.points):e.points,r=Array.isArray(e.lookAts)?JSON.stringify(e.lookAts):e.lookAts,i={...e,points:n,lookAts:r,nodes:JSON.stringify(e.points),time:e.time??4,smoothMode:e.smoothMode??0};return this.request(`flyByPath`,i,t,A.flyByPath)}setFlySpeed(e,t){return this.request(`setFlySpeed`,e,t,A.setFlySpeed)}endFly(e){return this.request(`endFly`,void 0,e,k)}pauseFly(e){return this.request(`pauseFly`,void 0,e,k)}resumeFly(e){return this.request(`resumeFly`,void 0,e,k)}getCameraInfo(e){return this.request(`GetCameraInfo`,void 0,e,k)}setCameraPositionAndRotation(e,t){return e.rotation&&(e.rotation.ePSGType=`0000`),this.request(`setCameraPositionAndRotation`,e,t,A.setCameraPositionAndRotation)}setCameraFov(e,t){return this.request(`setCameraFov`,e,t,A.setCameraFov)}resetCameraFov(e){return this.request(`resetCameraFov`,void 0,e,k)}reset(e){return this.request(`reset`,void 0,e,k)}startCameraObjFollow(e,t){e.offSet&&(e.offSet.ePSGType=`0000`);let n={...e,offSet:e.offSet?e.offSet:{x:-30,y:0,z:10}};return this.request(`StartCameraObjFollow`,n,t,A.startCameraObjFollow)}endCameraObjFollow(e){return this.request(`EndCameraObjFollow`,void 0,e,k)}},Je=class extends _{constructor(e,t,n){super(e,`Connect`,n),this.connectionLifecycle=t}connect(e){return pe(Promise.resolve().then(()=>(this.logger.warn(`connect called as compatibility API; SDK auto-connects after DTCEngine init`),this.connectionLifecycle.connect().then(()=>({requestId:``,success:!0,code:`CONNECT_OK`,message:`Connect requested (compatibility path)`,ts:Date.now()})))),e)}disconnect(e){return pe(Promise.resolve().then(()=>(this.logger.info(`disconnect requested`),Promise.resolve(this.connectionLifecycle.disconnect()).then(()=>({requestId:``,success:!0,code:`DISCONNECT_OK`,message:`Disconnected`,ts:Date.now()})))),e)}reconnect(e){return pe(Promise.resolve().then(()=>(this.logger.info(`reconnect requested`),this.connectionLifecycle.reconnect().then(()=>({requestId:``,success:!0,code:`RECONNECT_OK`,message:`Reconnect requested`,ts:Date.now()})))),e)}KickOtherConnect(e){return this.request(`KickOtherConnect`,void 0,e,k)}KeepConnect(e){return this.request(`KeepConnect`,void 0,e,k)}GetEngineServiceStatus(e){return this.request(`GetEngineServiceStatus`,void 0,e,k)}},Ye=class extends _{constructor(e,t){super(e,`DLSSService`,t)}setDlss(e={},t){let n={enable:e.enable??!1,quality:e.quality??b.Balanced};return this.request(`SetDlss`,n,t,Ve.setDlss)}},Xe=class extends _{constructor(e,t){super(e,`HighLighterService`,t)}enable(e,t){return this.request(`HighlightEnable`,e,t,Ie.enable)}setHighLightModel(e,t){return this.request(`AddHighLighterModel`,e,t,Ie.setHighLightModel)}removeHighLightModel(e,t){return this.request(`RemoveHighLightModel`,e,t,Ie.removeHighLightModel)}clear(e){return this.request(`Clear`,{},e,Ie.clear)}},Ze=class e{constructor(e=0,t=0){this.x=e,this.y=t}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}clone(){return new e(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e,t){return t==null?(this.x+=e.x,this.y+=e.y,this):this.addVectors(e,t)}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e,t){return t==null?(this.x-=e.x,this.y-=e.y,this):this.subVectors(e,t)}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}angle(){let e=Math.atan2(this.y,this.x);return e<0&&(e+=2*Math.PI),e}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y;return t*t+n*n}equals(e){return e.x==this.x&&e.y==this.y}toString(){return JSON.stringify(this)}},Qe=class e{constructor(e=0,t=0,n=0,r=0,i=v.EPSGType.EPSG84){this.x=e,this.y=t,this.z=n,this.v=r,this.EPSGType=i}set(e,t,n,r){return this.x=e,this.y=t,this.z=n,this.v=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}clone(){return new e(this.x,this.y,this.z,this.v)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.v=e.v,this}add(e,t){return t==null?(this.x+=e.x,this.y+=e.y,this.z+=e.z,this.v+=e.v,this):this.addVectors(e,t)}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.v+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.v=e.v+t.v,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.v+=e.v*t,this}sub(e,t){return t==null?(this.x-=e.x,this.y-=e.y,this.z-=e.z,this.v-=e.v,this):this.subVectors(e,t)}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.v-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.v=e.v-t.v,this}multiply(e,t){return t==null?(this.x*=e.x,this.y*=e.y,this.z*=e.z,this.v*=e.v,this):this.multiplyVectors(e,t)}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.v*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this.v=e.v*t.v,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.v/=e.v,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.v=Math.min(this.v,e.v),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.v=Math.max(this.v,e.v),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this.v=Math.max(e.v,Math.min(t.v,this.v)),this}clampScalar(t,n){let r=new e,i=new e;return r.set(t,t,t,t),i.set(n,n,n,n),this.clamp(r,i)}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(e,Math.min(t,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.v=Math.floor(this.v),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.v=Math.ceil(this.v),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.v=Math.round(this.v),this}roundToZero(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z),this.v=this.v<0?Math.ceil(this.v):Math.floor(this.v),this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.v*e.v}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.v*this.v}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.v*this.v)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.v)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.v+=(e.v-this.v)*t,this}lerpVectors(e,t,n){return this.subVectors(t,e).multiplyScalar(n).add(e)}cross(e,t){return t==null?this.crossVectors(this,e):this.crossVectors(e,t)}crossVectors(e,t){let n=e.x,r=e.y,i=e.z,a=t.x,o=t.y,s=t.z;return this.x=r*s-i*o,this.y=i*a-n*s,this.z=n*o-r*a,this}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,r=this.z-e.z,i=this.v-e.v;return t*t+n*n+r*r+i*i}equals(e){return e.x==this.x&&e.y==this.y&&e.z==this.z&&e.v==this.v}toString(){return JSON.stringify(this)}changeEPSGType(e){if(this.EPSGType!=e){if(e==v.EPSGType.EPSG84){let e=he(this.x,this.y);this.x=e.x,this.y=e.y}else if(e==v.EPSGType.EPSGWeb){let e=me(this.x,this.y);this.x=e.x,this.y=e.y}else console.log(`暂不支持[${this.EPSGType}]转换为${e}`);return this.EPSGType=e,this}}},$e=class{constructor(){this.Vector2=Ze,this.Vector3=y,this.Vector4=Qe}},et=class extends _{constructor(e,t){super(e,`LayerService`,t)}addLayer(e,t){let n={...e,show:e.show??!0,poiEnabled:e.poiEnabled??!0,isSystem:e.isSystem??!1};return this.request(`AddLayer`,n,t,P.addLayerResolved)}removeLayer(e,t){let n={...e};return this.request(`RemoveLayer`,n,t,P.layerSelectorResolved)}isLayerOrGroupExit(e,t){let n={...e};return this.request(`IsLayerOrGroupExit`,n,t,P.layerSelectorResolved)}switchModelLayer(e,t){return this.request(`SwitchLayer`,e,t,P.switchModelLayer)}showUIPop(e,t){let n={...e,id:e.id.trim(),visible:e.visible??!0,assetsPath:e.assetsPath??`/Game/Resources/POIS/BluePrints/BP_POI.uasset`,scale:e.scale??new y(1,1,1),offSet:e.offSet??new y(0,0,0)};return n.scale&&(n.scale.ePSGType=`0000`),n.offSet&&(n.offSet.ePSGType=`0000`),this.request(`ShowLayerUIPop`,n,t,P.showUIPop)}addModel(e,t){let n={...e,id:e.id.trim(),scale:e.scale??new y(1,1,1),rotation:e.rotation??new y(0,0,0)};return n.scale&&(n.scale.ePSGType=`0000`),n.rotation&&(n.rotation.ePSGType=`0000`),this.request(`AddModel`,n,t,P.addModel)}addPOI(e,t){let n={...e,id:e.id.trim(),scale:e.scale??new y(1,1,1),rotation:e.rotation??new y(0,0,0),fontSize:e.fontSize??16,isSystem:e.isSystem??!1,text:e.text??``,targetParentId:e.targetParentId??``,targetId:e.targetId??``,offSet:e.offSet??new y(0,0,0)};return n.scale&&(n.scale.ePSGType=`0000`),n.rotation&&(n.rotation.ePSGType=`0000`),n.offSet&&(n.offSet.ePSGType=`0000`),this.request(`AddPOI`,n,t,P.addPOI)}removeModel(e,t){return this.request(`RemoveModelByIds`,e,t,P.removeModel)}getLayerChildElement(e,t){return this.request(`GetLayerChildElements`,e,t,P.getLayerChildElement)}},tt=class extends _{constructor(e,t){super(e,`ModelService`,t)}toIdArray(e){return Array.isArray(e)?e:[e]}setVisible(e,t){let n={parentId:e.parentId,ids:this.toIdArray(e.id),visible:e.visible??!0};return this.request(`SetVisible`,n,t,Ne.setVisibleResolved)}setVisibleByTags(e,t){let n={tags:this.toIdArray(e.tags),visible:e.visible??!0};return this.request(`SetVisibleByTags`,n,t,Ne.setVisibleByTags)}getElementTree(e,t){return this.request(`GetElementTree`,e,t,Ne.getElementTree)}getModelInfo(e,t){return this.request(`GetModelInfo`,e,t,Ne.getModelInfo)}},nt=class extends _{constructor(e,t){super(e,`ModelPOI`,t)}add(e,t){let n={...e,visible:e.visible??!0};return this.request(`add`,n,t,L.add)}deleteById(e,t){return this.request(`deleteById`,e,t,L.deleteById)}deleteByGroup(e,t){return this.request(`deleteByGroup`,e,t,L.deleteByGroup)}getPOIInfo(e,t){return this.request(`getPOIInfo`,e,t,L.getPOIInfo)}update(e,t){let n={...e,visible:e.visible??!0};return this.request(`update`,n,t,L.update)}setVisibleByGroup(e,t){return this.request(`setVisibleByGroup`,e,t,L.setVisibleByGroup)}},rt=class extends _{constructor(e,t){super(e,`ModelTransformService`,t)}startMoveByNodes(e,t){return this.request(`StartMoveByNodes`,e,t,N.startMoveByNodes)}pauseMove(e,t){return this.request(`PauseMove`,e,t,N.pauseMove)}resumeMove(e,t){return this.request(`ResumeMove`,e,t,N.resumeMove)}endMove(e,t){return this.request(`EndMove`,e,t,N.endMove)}restoreMove(e,t){return this.request(`RestoreMove`,e,t,N.restoreMove)}rotate(e,t){return e.rotate.ePSGType=v.EPSGType.EPSGWorld,this.request(`StartRotate`,e,t,N.rotate)}endRotate(e,t){return this.request(`EndRotate`,e,t,N.endRotate)}continuedRotate(e,t){return e.rotate.ePSGType=v.EPSGType.EPSGWorld,this.request(`ContinuedRotate`,e,t,N.continuedRotate)}rotateByTarget(e,t){return this.request(`RotateByTarget`,e,t,N.rotateByTarget)}restoreRotate(e,t){return this.request(`RestoreRotate`,e,t,N.restoreRotate)}setScale(e,t){e.scale.ePSGType=v.EPSGType.EPSGWorld;let n={...e,id:e.id.trim()};return n.scale&&(n.scale.ePSGType=`0000`),this.request(`SetScale`,n,t,N.setScale)}endScale(e,t){return this.request(`EndScale`,e,t,N.endScale)}restoreScale(e,t){return this.request(`RestoreScale`,e,t,N.restoreScale)}},it=class extends _{constructor(e,t){super(e,`PathPatrolService`,t)}add(e,t){return e.scale&&(e.scale.ePSGType=v.EPSGType.EPSGWorld),this.requestStream(`AddPath`,e,t,V.add)}update(e,t){return this.request(`UpdatePath`,e,t,V.update)}setTimeNode(e,t){return this.request(`CuriserTimeSet`,e,t,V.setTimeNode)}clear(e){return this.request(`ClearPath`,void 0,e,V.clear)}pause(e,t){return this.request(`Pause`,e,t,V.node)}resume(e,t){return this.request(`Resume`,e,t,V.node)}stop(e,t){return this.request(`Stop`,e,t,V.node)}},at=class{static getUUID(e=11){let t=16,n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`.split(``),r=[],i;if(t||=n.length,e)for(i=0;i<e;i++)r[i]=n[0|Math.random()*t];else{let e;for(r[8]=r[13]=r[18]=r[23]=`-`,r[14]=`4`,i=0;i<36;i++)r[i]||(e=0|Math.random()*16,r[i]=n[i==19?e&3|8:e])}return`U`+r.join(``)}static warn(e,t=!1){console.log(`warn`,e,t);let n=document.createElement(`div`);return n.innerHTML=e,document.body.appendChild(n),n.setAttribute(`id`,`engineWarnTips`),n.style.cssText=`
|
|
2
|
+
pointer-events: none;
|
|
3
|
+
padding: 10px 40px;
|
|
4
|
+
letter-spacing: 1px;
|
|
5
|
+
font-size: 15px;
|
|
6
|
+
border-radius: 5px;
|
|
7
|
+
position: absolute;
|
|
8
|
+
top: -150px;
|
|
9
|
+
background: rgba(32, 52, 70, .6);
|
|
10
|
+
color: rgb(255, 255, 255);
|
|
11
|
+
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
|
|
12
|
+
z-index:999;
|
|
13
|
+
`,n.style.left=`calc(50vw - ${n.offsetWidth/2}px)`,n.style.left=`calc( - ${n.offsetWidth/2}px+50vw)`,n.style.transition=`top 250ms ease-out`,n.style.top=`200px`,t||window.setTimeout(()=>{document.body.removeChild(n)},3e3),n}static LoadingProgressDiv(e,t=!0){let n=document.createElement(`div`);return n.innerHTML=e,document.body.appendChild(n),n.setAttribute(`id`,`engineProgressTips`),n.style.cssText=`
|
|
14
|
+
pointer-events: none;
|
|
15
|
+
padding: 10px 40px;
|
|
16
|
+
letter-spacing: 1px;
|
|
17
|
+
font-size: 25px;
|
|
18
|
+
border-radius: 5px;
|
|
19
|
+
position: absolute;
|
|
20
|
+
top: -150px;
|
|
21
|
+
background: rgba(32, 52, 70, .6);
|
|
22
|
+
color: rgb(255, 255, 255);
|
|
23
|
+
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
|
|
24
|
+
z-index:999;
|
|
25
|
+
`,n.style.left=`calc(50vw - ${n.offsetWidth/2}px)`,n.style.left=`calc( - ${n.offsetWidth/2}px+50vw)`,n.style.transition=`top 250ms ease-out`,n.style.top=`500px`,t||window.setTimeout(()=>{document.body.removeChild(n)},2e3),n}static removeLoadingProgressDiv(){let e=document.getElementById(`engineProgressTips`);e&&document.body.removeChild(e)}static LoadingTokenWillExpireDiv(e,t=!0){let n=document.createElement(`div`);return n.innerHTML=e,document.body.appendChild(n),n.setAttribute(`id`,`TokenWillExpireTips`),n.style.cssText=`
|
|
26
|
+
pointer-events: none;
|
|
27
|
+
padding: 10px 40px;
|
|
28
|
+
letter-spacing: 1px;
|
|
29
|
+
font-size: 25px;
|
|
30
|
+
border-radius: 5px;
|
|
31
|
+
position: absolute;
|
|
32
|
+
top: -130px;
|
|
33
|
+
background: rgba(189, 77, 58, .6);
|
|
34
|
+
color: rgb(255, 255, 255);
|
|
35
|
+
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
|
|
36
|
+
z-index:999;
|
|
37
|
+
`,n.style.left=`calc(50vw - ${n.offsetWidth/2}px)`,n.style.left=`calc( - ${n.offsetWidth/2}px+50vw)`,n.style.transition=`top 250ms ease-out`,n.style.top=`440px`,t||window.setTimeout(()=>{document.body.removeChild(n)},15e3),n}static removeLoadingTokenWillExpireDiv(){let e=document.getElementById(`TokenWillExpireTips`);e&&document.body.removeChild(e)}static stopEvents(e){e.preventDefault&&e.preventDefault(),e.stopPropagation&&e.stopPropagation()}static degToRad(e){return e*Math.PI/180}static WGS84ToMercator(e,t){let n=e*20037508.34/180,r=Math.log(Math.tan((90+t)*Math.PI/360))/(Math.PI/180);return r=r*20037508.34/180,{x:n,y:r}}static MercatorToWGS84(e,t){let n=e/20037508.34*180,r=t/20037508.34*180;return r=180/Math.PI*(2*Math.atan(Math.exp(r*Math.PI/180))-Math.PI/2),{x:n,y:r}}static isPC(){let e=navigator.userAgent,t=[`Android`,`iPhone`,`SymbianOS`,`Windows Phone`,`iPad`,`iPod`],n=!0;for(let r=0;r<t.length;r++)if(e.indexOf(t[r])>0){n=!1;break}return n}static getTotalPage(e,t=50){let n=0,r=e/t;return n=e/t>parseInt(r+``)?parseInt(r+``)+1:parseInt(r+``),n}static{this.isEmpty=e=>e===null||e===``||e===void 0||e.length===0}static getValueOrDefault(e,t,n){return e[t]==null?e[t]=n:e[t]}static dynamicAddCrossAccess(){let e=document.head||document.getElementsByTagName(`head`)[0];function t(){let e=document.getElementsByTagName(`meta`);for(let t=0;t<e.length;t++)if(e[t].getAttribute(`http-equiv`)===`Access-Control-Allow-Origin`&&e[t].getAttribute(`content`)===`*`)return!0;return!1}if(!t()){let t=document.createElement(`meta`);t.setAttribute(`http-equiv`,`Access-Control-Allow-Origin`),t.setAttribute(`content`,`*`),e.appendChild(t)}}static GetAxios(e,t,n){i.defaults.headers.common[`content-Type`]=`application/json;charset=UTF-8`,i.get(e,n).then(function(e){t&&t(e)}).catch(function(e){e.response||(e.request?console.log(e.request):console.error(`Error`,e.message))})}static IsValidHexColor(e){return e=e.replace(/^#/,``),e.length!==3&&e.length!==6?!1:/^[0-9A-Fa-f]{3}$|^[0-9A-Fa-f]{6}$/.test(e)}static calculatePercentage(e,t){return(e/t*100).toFixed(2)}static getCurrentTimeFormatted(){let e=new Date;return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)} ${String(e.getHours()).padStart(2,`0`)}:${String(e.getMinutes()).padStart(2,`0`)}:${String(e.getSeconds()).padStart(2,`0`)}`}static CalTimeDifferToHHMMSS(e){Math.floor(e/864e5);let t=e%864e5,n=Math.floor(t/36e5).toString().padStart(2,`0`),r=t%36e5,i=Math.floor(r/6e4).toString().padStart(2,`0`),a=r%6e4;return`${n}:${i}:${Math.round(a/1e3).toString().padStart(2,`0`)}`}static isNumeric(e){return!isNaN(parseFloat(e))&&!isNaN(e)}},ot=class{constructor(e){this.pops={},this.def=`VEC_POP`,this.maxShowDistance=2e4,this.syncPopsHandler=e=>{this.SyncPops(e)},this.started=!1,this.dtcEngine=e,this.hostElement=e.getEngineConfig().dom,this.start()}start(){this.started||=(this.dtcEngine.on(`SyncPops`,this.syncPopsHandler),!0)}dispose(){this.started&&=(this.dtcEngine.off(`SyncPops`,this.syncPopsHandler),!1)}SyncPops(e){let t=JSON.parse(e.param??`[]`);Object.keys(this.pops).length!=0&&t.forEach(e=>{if(this.pops[e.groupName]&&this.pops[e.groupName][e.id]){let t=this.pops[e.groupName][e.id];t!=null&&(t.visible&&e.visible&&e.distance<this.maxShowDistance?t.showOnly(e.x,e.y,e.distance):t.disableOnly())}})}Set(e,t){e??=this.def,this.pops[e]||(this.pops[e]={}),t?.forEach(t=>{this.pops[e][t.id]||(this.pops[e][t.id]=t)})}RemovePop(e,t){e??=this.def,this.pops[e]&&(t==null?(Object.keys(this.pops[e]).map(t=>{if(this.pops[e]&&this.pops[e][t]){let n=this.pops[e][t];n&&n.dispose()}}),delete this.pops[e]):t.forEach(t=>{if(this.pops[e]&&this.pops[e][t]){let n=this.pops[e][t];n&&(n.dispose(),delete this.pops[e][t])}}))}RemoveAll(){Object.keys(this.pops).map(e=>{Object.keys(this.pops[e]).map(t=>{let n=this.pops[e][t];n&&n.dispose()}),delete this.pops[e]})}Switch(e,t,n){t??=this.def,this.pops[t]&&(n?n.forEach(n=>{let r=this.pops[t][n];r!=null&&(e?r.show():r.disable(),r.visible=e)}):Object.keys(this.pops[t]).forEach(n=>{let r=this.pops[t][n];r!=null&&(e?r.show():r.disable(),r.visible=e)}))}SwitchAll(e){Object.keys(this.pops).forEach(t=>{Object.keys(this.pops[t]).forEach(n=>{let r=this.pops[t][n];r!=null&&(e?r.show():r.disable())})})}SendNeedSyncPopsInfo(){let e=[];return Object.keys(this.pops).forEach(t=>{Object.keys(this.pops[t]).forEach(n=>{let r=this.pops[t][n];r.visible&&e.push({groupName:t,id:r.id,parentId:r.parentId,position:r.position})})}),e}},st=class{constructor(e,t,n,r,i,a,o=0,s=0){this.id=t,this.parentId=a,this.div=n,this.position=i,this.offSetX=o,this.offSetY=s,this.outDistance=!1,this.visible=r??!0,this.videoDom=e,this.div&&(this.div.style.left=`-9999px`,this.div.style.top=`-9999px`,this.videoDom.appendChild(this.div))}showOnly(e,t,n){let r=this.videoDom.getBoundingClientRect(),i=r.left,a=r.top,o=this.offSetY;this.div.style.left=e+this.offSetX+i+`px`,this.div.style.top=t+o+a+`px`,this.div.style.display=`block`,this.div.style.position=`absolute`}disableOnly(){this.div.style.left=`-9999px`,this.div.style.top=`-9999px`,this.div.style.display=`none`}show(e,t){this.visible=!0,this.showOnly(e,t)}disable(){this.visible=!1,this.disableOnly()}dispose(){this.videoDom.contains(this.div)&&this.videoDom.removeChild(this.div)}},ct=class extends _{constructor(e,t,n){super(e,`WebPopService`,n),this.popupManager=t}addPop(e,t){let n=(e.popInfo??[]).map(e=>{let t=at.getValueOrDefault(e,`offSetX`,0),n=at.getValueOrDefault(e,`offSetY`,0);return new st(this.popupManager.hostElement,e.id,e.div,e.visible,e.position,e.parentId,t,n)});return this.popupManager.Set(e.groupName,n),this.request(`SynPopsInfo`,this.popupManager.SendNeedSyncPopsInfo(),t,R.addPop)}removePop(e={},t){return this.popupManager.RemovePop(e.groupName,e.ids),this.request(`SynPopsInfo`,this.popupManager.SendNeedSyncPopsInfo(),t,R.removePop)}removeAll(e){return this.popupManager.RemoveAll(),this.request(`SynPopsInfo`,this.popupManager.SendNeedSyncPopsInfo(),e,R.removeAll)}show(e,t){let n=at.getValueOrDefault(e,`show`,!0);return this.popupManager.Switch(n,e.groupName,e.ids),this.request(`SynPopsInfo`,this.popupManager.SendNeedSyncPopsInfo(),t,R.show)}showAll(e=!0,t){return this.popupManager.SwitchAll(e),this.request(`SynPopsInfo`,this.popupManager.SendNeedSyncPopsInfo(),t,R.showAll)}setPopDelayFrame(e,t){return this.request(`SetPopDelayFrame`,e,t,R.setPopDelayFrame)}setPopShowDistance(e){if(e==null||typeof e!=`number`){console.log(`请检查传入参数,参见接口说明`);return}this.popupManager.maxShowDistance=e}},lt=class extends _{constructor(e,t){super(e,`WebScreenService`,t)}setSceneRenderBitrate(e={},t){let n=typeof e.bitrate==`number`?{bitrate:e.bitrate}:{bitrate:_e[f(Be.setSceneRenderBitrate,e,this.moduleName,`SetSceneRenderBitrate`).bitrate??x.High]};return this.request(`SetSceneRenderBitrate`,n,t,Be.setSceneRenderBitrateResolved)}setSceneFPS(e={},t){let n={fps:e.fps??150};return this.request(`SetSceneRenderFPS`,n,t,Be.setSceneFPS)}setScreenResolution(e={},t){let n={width:e.width??1920,height:e.height??1080};return this.request(`SetScreenResolution`,n,t,Be.setScreenResolution)}},ut=class extends _{constructor(e,t){super(e,`Scene`,t)}getAllSceneName(e){return this.request(`getAllSceneName`,void 0,e,j.getAllSceneName)}switchSceneByName(e,t){return this.request(`switchSceneByName`,e,t,j.switchSceneByName)}getCurrentSceneName(e){return this.request(`getCurrentSceneName`,void 0,e,j.getCurrentSceneName)}listenMapCompass(e,t){return this.request(`listenMapCompass`,e,t,j.listenMapCompass)}setFeatureToggle(e,t){return this.request(`setFeatureToggle`,e,t,j.setFeatureToggle)}getSceneMeta(e){return this.request(`getSceneMeta`,void 0,e,k)}},dt=class extends _{constructor(e,t){super(e,`TimeLineService`,t)}play(e,t){let n={...e,speed:e.speed??1,initialTime:e.initialTime??0,keepLastFrame:e.keepLastFrame??!1};return this.requestStream(`Play`,n,t,B.play)}pause(e,t){return this.request(`Pause`,e,t,B.pause)}resume(e,t){return this.request(`Resume`,e,t,B.resume)}stop(e,t){let n={...e,resetTime:e.resetTime??-1,isCameraToStart:e.isCameraToStart??!1};return this.request(`Stop`,n,t,B.stop)}stopAll(e){return this.request(`StopAll`,void 0,e,B.stopAll??k)}setSpeed(e,t){return this.request(`SetSpeed`,e,t,B.setSpeed)}},ft=class extends _{constructor(e,t){super(e,`UIPOI`,t)}add(e,t){return this.request(`add`,e,t,I.add)}deleteById(e,t){return this.request(`deleteById`,e,t,I.deleteById)}deleteByGroup(e,t){return this.request(`deleteByGroup`,e,t,I.deleteByGroup)}update(e,t){return this.request(`update`,e,t,I.update)}updatePopStates(e,t){return this.request(`updatePopStates`,e,t,I.updatePopStates)}enableOverlap(e,t){let n={...e,enable:e.enable??!0};return this.request(`enableOverlap`,n,t,I.enableOverlap)}showDistance(e,t){return this.request(`showDistance`,e,t,I.showDistance)}},pt=class extends _{constructor(e,t){super(e,`WeathersService`,t)}changeWeatherType(e,t){return this.request(`ChangeWeatherType`,e,t,F.changeWeatherType)}getWeatherTypes(e){return this.request(`GetWeatherTypes`,void 0,e,k)}resetWeather(e){return this.request(`ResetWeather`,void 0,e,k)}setSceneTime(e,t){let n={...e,timeDuration:e.timeDuration??5};return this.request(`SetCurrentSceneTime`,n,t,F.setSceneTime)}setTimeSync(e,t){let n={...e,syncSystemTime:e.syncSystemTime??!1};return this.request(`SetTimeSync`,n,t,F.setTimeSync)}resetSceneTime(e){return this.request(`ResetSceneTime`,{},e,F.resetSceneTime)}setAnimateTimeOfDay(e,t){let n={...e,isAnimate:e.isAnimate??!0,dayLength:e.dayLength??.5,nightLength:e.nightLength??.5};return this.request(`SetAnimateTimeOfDay`,n,t,F.setAnimateTimeOfDay)}resetWeatherAndTime(e){return this.request(`ResetWeatherAndTime`,void 0,e,k)}changeSeason(e,t){return this.request(`ChangeSeason`,e,t,F.changeSeason)}resetSeason(e){return this.request(`ResetSeason`,{},e,F.resetSeason)}setDayAndNight(e,t){return this.request(`setDayAndNight`,e,t,F.setDayAndNight)}openCameraFog(e,t){let n={...e,fogIntensity:e.fogIntensity??-1,fogStartDistance:e.fogStartDistance??-1,fogEndDistance:e.fogEndDistance??-1,directionalIntensity:e.directionalIntensity??-1,directionalFallOff:e.directionalFallOff??-1};return this.request(`openCameraFog`,n,t,F.openCameraFog)}closeCameraFog(e){return this.request(`closeCameraFog`,void 0,e,F.closeCameraFog??k)}};const mt={Connect:e=>new Je(e.bridge,e.connectionLifecycle,{logger:e.createLogger(`Connect`)}),Type:()=>new $e,Screen:e=>new lt(e.bridge,{logger:e.createLogger(`Screen`)}),Dlss:e=>new Ye(e.bridge,{logger:e.createLogger(`Dlss`)}),Camera:e=>new qe(e.bridge,{logger:e.createLogger(`Camera`)}),Scene:e=>new ut(e.bridge,{logger:e.createLogger(`Scene`)}),Layer:e=>new et(e.bridge,{logger:e.createLogger(`Layer`)}),Model:e=>new tt(e.bridge,{logger:e.createLogger(`Model`)}),UIPOI:e=>new ft(e.bridge,{logger:e.createLogger(`UIPOI`)}),ModelPOI:e=>new nt(e.bridge,{logger:e.createLogger(`ModelPOI`)}),ModelTransform:e=>new rt(e.bridge,{logger:e.createLogger(`ModelTransform`)}),PathPatrol:e=>new it(e.bridge,{logger:e.createLogger(`PathPatrol`)}),HighlighterEffect:e=>new Xe(e.bridge,{logger:e.createLogger(`HighlighterEffect`)}),Popup:e=>new ct(e.bridge,e.popupManager,{logger:e.createLogger(`Popup`)}),Animation:e=>new Ke(e.bridge,{logger:e.createLogger(`Animation`)}),TimeLine:e=>new dt(e.bridge,{logger:e.createLogger(`TimeLine`)}),WeatherSystem:e=>new pt(e.bridge,{logger:e.createLogger(`WeatherSystem`)})},H=Object.freeze(Object.keys(mt)),U=[`DTCEngine 已完成鉴权并建立 WebRTC 连接`],W=`Promise<ApiResponseEnvelope<unknown>>`,ht={Connect:{title:`连接控制`,description:`连接控制 API。`,capabilities:[`连接建立`,`连接断开`,`连接重连`,`会话接管`,`会话保活`,`服务状态查询`],methods:{connect:{description:"发起连接(兼容接口,SDK 实际已在 `new DTCEngine` 后自动连接)。",payloadType:``,returnType:W,sideEffects:[`connection`],preconditions:U,examples:[{}],riskLevel:`low`},disconnect:{description:`断开连接。`,payloadType:``,returnType:W,sideEffects:[`connection`],preconditions:U,examples:[{}],riskLevel:`low`},reconnect:{description:`重新连接。`,payloadType:``,returnType:W,sideEffects:[`connection`],preconditions:U,examples:[{}],riskLevel:`low`},KickOtherConnect:{description:`踢掉已存在会话并接管连接。`,payloadType:``,returnType:W,sideEffects:[`connection`],preconditions:U,examples:[{}],riskLevel:`low`},KeepConnect:{description:`保持当前连接会话。`,payloadType:``,returnType:W,sideEffects:[`connection`],preconditions:U,examples:[{}],riskLevel:`low`},GetEngineServiceStatus:{description:`获取引擎服务状态。`,payloadType:``,returnType:W,sideEffects:[`read`],preconditions:U,examples:[{}],riskLevel:`low`}}},Type:{title:`数学类型`,description:`SDK 数学类型构造器。`,capabilities:[`二维向量类型`,`三维向量类型`,`四维向量类型`,`坐标参数构造`],methods:{}},Screen:{title:`画面质量控制`,description:`屏幕与渲染质量控制 API。`,capabilities:[`渲染码率调整`,`场景帧率调整`,`屏幕分辨率调整`],methods:{setSceneRenderBitrate:{description:`设置场景渲染码率档位。`,payloadType:`ScreenSetSceneRenderBitrateRequest | { bitrate: number }`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{bitrate:`high`}],riskLevel:`low`},setSceneFPS:{description:`设置场景帧率。`,payloadType:`ScreenSetSceneFPSRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{fps:30}],riskLevel:`low`},setScreenResolution:{description:`设置渲染分辨率。`,payloadType:`ScreenSetScreenResolutionRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{width:1280,height:720}],riskLevel:`low`}}},Dlss:{title:`DLSS 画质控制`,description:`DLSS 画质控制 API。`,capabilities:[`DLSS 开关控制`,`DLSS 质量档位控制`],methods:{setDlss:{description:`同时设置 DLSS 开关和质量档位。`,payloadType:`DlssSetEnableRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{enable:!0,quality:`Balanced`}],riskLevel:`low`}}},Camera:{title:`相机控制`,description:`相机相关操作 API。`,capabilities:[`模型视角定位`,`批量目标定位`,`自由飞行`,`路径飞行`,`飞行控制`,`相机信息查询`,`相机姿态设置`,`视场角控制`,`相机重置`,`相机跟随控制`],methods:{lookAt:{description:`定位到指定模型对象或对象集合。`,payloadType:`CameraLookAtRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`test`,id:`Sphere`,time:2}],riskLevel:`low`},flyToTarget:{description:`相机飞向指定坐标点,并在飞行过程中看向目标点。`,payloadType:`CameraFlyToTargetRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{point:{x:120.1704,y:30.2472,z:148.1303,ePSGType:`0000`},target:{x:120.1691,y:30.2471,z:65.7,ePSGType:`0000`},time:2}],riskLevel:`low`},flyByPath:{description:`按多点路径执行相机飞行。`,payloadType:`CameraFlyByPathRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{points:[{x:0,y:0,z:100},{x:100,y:0,z:100}],lookAts:[{x:0,y:0,z:0},{x:100,y:0,z:0}],time:6,smoothMode:0}],riskLevel:`low`},setFlySpeed:{description:`设置相机飞行速度。`,payloadType:`CameraSetFlySpeedRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{speed:2}],riskLevel:`low`},endFly:{description:`终止当前飞行。`,payloadType:``,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{}],riskLevel:`low`},pauseFly:{description:`暂停当前飞行。`,payloadType:``,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{}],riskLevel:`low`},resumeFly:{description:`恢复当前飞行。`,payloadType:``,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{}],riskLevel:`low`},getCameraInfo:{description:`获取当前相机信息。`,payloadType:``,returnType:W,sideEffects:[`read`],preconditions:U,examples:[{}],riskLevel:`low`},setCameraPositionAndRotation:{description:`设置相机位置与旋转。`,payloadType:`CameraSetPositionAndRotationRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{point:{x:0,y:0,z:100,ePSGType:`0000`},rotation:{x:0,y:0,z:0,ePSGType:`0000`}}],riskLevel:`low`},setCameraFov:{description:`设置相机 FOV。`,payloadType:`CameraSetFovRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{fov:75}],riskLevel:`low`},resetCameraFov:{description:`重置相机 FOV。`,payloadType:``,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{}],riskLevel:`low`},reset:{description:`重置相机到默认状态。`,payloadType:``,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{}],riskLevel:`low`},startCameraObjFollow:{description:`相机跟随场景中运动的对象。`,payloadType:`CameraObjFollowRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{id:`myCar`,offSet:{x:0,y:3,z:5,ePSGType:`0000`},smooth:.85}],riskLevel:`low`},endCameraObjFollow:{description:`停止相机跟随。`,payloadType:``,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{}],riskLevel:`low`}}},Scene:{title:`场景管理`,description:`场景管理 API。`,capabilities:[`场景列表查询`,`场景切换`,`当前场景查询`,`地图罗盘监听`,`场景特性开关`,`场景元数据查询`],methods:{getAllSceneName:{description:`获取当前引擎服务支持的场景名称列表。`,payloadType:``,returnType:W,sideEffects:[`read`],preconditions:U,examples:[{}],riskLevel:`low`},switchSceneByName:{description:`按场景名称切换场景。`,payloadType:`SceneSwitchRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{sceneName:`TestScene`}],riskLevel:`low`},getCurrentSceneName:{description:`获取当前正在运行的场景名称。`,payloadType:``,returnType:W,sideEffects:[`read`],preconditions:U,examples:[{}],riskLevel:`low`},listenMapCompass:{description:`监听地图指北针角度变化。`,payloadType:`SceneListenCompassRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{enable:!0}],riskLevel:`low`},setFeatureToggle:{description:`设置场景特性开关。`,payloadType:`FeatureToggleRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{key:`minimap`,enabled:!0}],riskLevel:`low`},getSceneMeta:{description:`获取当前场景扩展元信息。`,payloadType:``,returnType:W,sideEffects:[`read`],preconditions:U,examples:[{}],riskLevel:`low`}}},Layer:{title:`图层管理`,description:`场景图层对象管理 API。`,capabilities:[`图层添加`,`图层删除`,`图层存在性查询`,`模型图层切换`,`图层气泡显隐`,`图层模型添加`,`图层模型删除`,`图层子对象查询`],methods:{addLayer:{description:`添加对象图层组。`,payloadType:`LayerAddRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`CameraGroup`,id:`CameraLayerModel`,layerName:`摄像机图层`,show:!0,poiEnabled:!0,type:`MODEL`}],riskLevel:`low`},removeLayer:{description:`删除对象图层组,并清空其下所有对象。`,payloadType:`LayerSelectorRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`CameraGroup`,id:`CameraLayerModel`}],riskLevel:`low`},isLayerOrGroupExit:{description:`判断图层或组对象是否存在。`,payloadType:`LayerSelectorRequest`,returnType:W,sideEffects:[`read`],preconditions:U,examples:[{id:`cameraGroup`}],riskLevel:`low`},switchModelLayer:{description:`切换模型的图层组。`,payloadType:`LayerSwitchModelRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`cameraLayer`,ids:[`camera01`,`camera02`],toParentId:`destLayer`}],riskLevel:`low`},showUIPop:{description:`显示或隐藏指定图层下的 UI Pop。`,payloadType:`LayerShowUIPopRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{id:`CameraLayer`,visible:!0}],riskLevel:`low`},addModel:{description:`在指定图层下添加模型资源。`,payloadType:`LayerModelAddRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`cameraLayer`,id:`camera01`,assetsPath:`Sphere`}],riskLevel:`low`},addPOI:{description:`在指定图层下添加模型资源。`,payloadType:`LayerPOIAddRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`cameraLayer`,id:`camera01`,assetsPath:`Sphere`}],riskLevel:`low`},removeModel:{description:`删除图层下指定模型资源。`,payloadType:`LayerModelRemoveRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`cameraLayer`,ids:[`camera01`,`camera02`]}],riskLevel:`low`},getLayerChildElement:{description:`获取图层下所有一级子对象。`,payloadType:`LayerChildElementRequest`,returnType:W,sideEffects:[`read`],preconditions:U,examples:[{id:`test`}],riskLevel:`low`}}},Model:{title:`模型管理`,description:`模型对象管理 API。`,capabilities:[`模型显隐控制`,`模型添加`,`模型删除`,`模型树查询`,`模型信息查询`,`模型包围盒查询`],methods:{setVisible:{description:`设置模型对象显隐状态。`,payloadType:`ModelSetVisibleRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`cameraGroup`,id:[`camera01`,`camera02`],visible:!1}],riskLevel:`low`},setVisibleByTags:{description:`按标签批量设置模型对象显隐状态。`,payloadType:`ModelSetVisibleByTagsRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{tags:[`camera`,`sensor`],visible:!1}],riskLevel:`low`},getElementTree:{description:`获取指定节点的一层子对象树。`,payloadType:`ModelSelectorRequest`,returnType:W,sideEffects:[`read`],preconditions:U,examples:[{parentId:`test`,id:`Root`}],riskLevel:`low`},getModelInfo:{description:`获取指定模型对象信息。`,payloadType:`ModelSelectorRequest`,returnType:W,sideEffects:[`read`],preconditions:U,examples:[{parentId:`test`,id:`Sphere`}],riskLevel:`low`}}},UIPOI:{title:`后端 UI 气泡`,description:`后端 UI 气泡(UIPOI)管理 API。`,capabilities:[`UI 气泡添加`,`UI 气泡删除`,`UI 气泡更新`,`弹窗状态更新`,`重叠控制`,`距离显示控制`],methods:{add:{description:`批量添加 UIPOI。`,payloadType:`UIPOIAddRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{groupName:`testGroup`,poiInfos:[{id:`camera01`,state:`normal`}]}],riskLevel:`low`},deleteById:{description:`删除指定组下的单个 UIPOI。`,payloadType:`UIPOIDeleteByIdRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{groupName:`testGroup`,id:`camera01`}],riskLevel:`low`},deleteByGroup:{description:`删除指定组下的全部 UIPOI。`,payloadType:`UIPOIDeleteByGroupRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{groupName:`myGroup`}],riskLevel:`low`},update:{description:`更新指定组 UIPOI 配置。`,payloadType:`UIPOIUpdateRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{groupName:`testGroup`,poiInfos:[{id:`camera01`,state:`alert`}]}],riskLevel:`low`},updatePopStates:{description:`批量更新 UIPOI 状态。`,payloadType:`UIPOIUpdateStateRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{groupName:`LCD80CunXianShiPingPop`,popStates:[{id:`1`,state:`normal`}]}],riskLevel:`low`},enableOverlap:{description:`开启或关闭 UIPOI 碰撞避让。`,payloadType:`UIPOIEnableOverlapRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{enable:!1}],riskLevel:`low`},showDistance:{description:`设置 UIPOI 可视距离。`,payloadType:`UIPOIShowDistanceRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{distance:800}],riskLevel:`low`}}},ModelPOI:{title:`模型气泡`,description:`模型气泡(ModelPOI)管理 API。`,capabilities:[`模型气泡添加`,`模型气泡删除`,`模型气泡查询`,`模型气泡更新`,`分组显隐控制`],methods:{add:{description:`添加模型气泡。`,payloadType:`ModelPOIAddRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{id:`123`,groupName:`cameraGroup`,assetPath:`dotPop`,targetId:`Camera01`}],riskLevel:`low`},deleteById:{description:`按编号批量删除模型气泡。`,payloadType:`ModelPOIDeleteByIdRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{groupName:`cameraGroup`,ids:[`Camera01`]}],riskLevel:`low`},deleteByGroup:{description:`删除指定组下全部模型气泡。`,payloadType:`ModelPOIDeleteByGroupRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{groupName:`myGroup`}],riskLevel:`low`},getPOIInfo:{description:`获取单个模型气泡信息。`,payloadType:`ModelPOIGetInfoRequest`,returnType:W,sideEffects:[`read`],preconditions:U,examples:[{groupName:`cameraGroup`,id:`Camera01`}],riskLevel:`low`},update:{description:`更新模型气泡信息。`,payloadType:`ModelPOIUpdateRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{id:`123`,groupName:`cameraGroup`,assetPath:`dotPop`,visible:!1}],riskLevel:`low`},setVisibleByGroup:{description:`设置指定组模型气泡显隐。`,payloadType:`ModelPOIVisibleByGroupRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{groupName:`myGroup`,visible:!0}],riskLevel:`low`}}},ModelTransform:{title:`模型变换`,description:`模型对象变换 API,涵盖旋转、缩放、移动操作。`,capabilities:[`模型轨迹移动`,`暂停/继续/结束移动`,`恢复位置`,`模型旋转`,`绕目标旋转`,`恢复旋转`,`模型缩放`,`停止缩放`,`恢复缩放`],methods:{startMoveByNodes:{description:`设置模型对象的移动轨迹。`,payloadType:`ModelTransformStartMoveRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`test`,id:`myRobot`,nodes:[{x:120.0001,y:30.0001,z:100.1},{x:122.0001,y:28.0001,z:110.1}],speed:3,linear:1,isLookAtTarget:!0}],riskLevel:`low`},pauseMove:{description:`暂停模型对象的移动。`,payloadType:`ModelTransformNodeRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`test`,id:`myRobot`}],riskLevel:`low`},resumeMove:{description:`继续模型对象的移动。`,payloadType:`ModelTransformNodeRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`test`,id:`Camera01`}],riskLevel:`low`},endMove:{description:`结束轨迹移动。`,payloadType:`ModelTransformNodeRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`test`,id:`Camera01`}],riskLevel:`low`},restoreMove:{description:`重置对象到原来的位置。`,payloadType:`ModelTransformRestoreRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{ids:[`Camera01`,`Camera02`]}],riskLevel:`low`},rotate:{description:`指定轴旋转模型角度到。`,payloadType:`ModelTransformRotateRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`test`,id:`myBus`,rotate:{x:30,y:180,z:120}}],riskLevel:`low`},endRotate:{description:`结束旋转。`,payloadType:`ModelTransformNodeRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`test`,id:`myBus`}],riskLevel:`low`},continuedRotate:{description:`持续不断的绕自身旋转。`,payloadType:`ModelTransformRotateRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`test`,id:`Camera01`,rotate:{x:30,y:180,z:120}}],riskLevel:`low`},rotateByTarget:{description:`围绕某个对象做旋转。`,payloadType:`ModelTransformRotateByTargetRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`test`,id:`Camera01`,targetID:`target`,point:{x:1,y:2,z:3},axisX:1,axisY:0,axisZ:0,angle:10,isPersistence:!0}],riskLevel:`low`},restoreRotate:{description:`重置恢复场景多个对象的旋转。`,payloadType:`ModelTransformRestoreRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{ids:[`Camera01`,`Camera02`]}],riskLevel:`low`},setScale:{description:`设置模型对象的缩放。`,payloadType:`ModelTransformScaleRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`test`,id:`Camera01`,scale:{x:.5,y:.5,z:.5},duration:3}],riskLevel:`low`},endScale:{description:`停止模型对象的缩放。`,payloadType:`ModelTransformNodeRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`test`,id:`Camera01`}],riskLevel:`low`},restoreScale:{description:`重置模型的缩放,恢复到开始状态。`,payloadType:`ModelTransformRestoreRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{ids:[`Camera01`,`Camera02`]}],riskLevel:`low`}}},PathPatrol:{title:`路径巡逻`,description:`路径巡逻 API,支持巡逻路线添加、样式修改、时间节点设置与巡逻控制。`,capabilities:[`添加巡逻路线`,`修改巡逻样式`,`设置巡逻时间节点`,`清除巡逻路径`,`暂停巡逻`,`继续巡逻`,`停止巡逻`],methods:{add:{description:`添加巡逻路线。`,payloadType:`PathPatrolAddRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`patrolLayer`,id:`patrolMan`,assetPath:`PatrolMan`,scale:{x:2,y:2,z:2},showPath:!0,passedColor:`#ff0013`,lineColor:`#0040ef`,lineWidth:2,nodes:[{x:114.79234244388735,y:34.8353249473732,z:67.76611328125},{x:114.78552975378634,y:34.84532722646887,z:67.76627349853516}],duration:10}],riskLevel:`low`},update:{description:`修改巡逻路径的样式。`,payloadType:`PathPatrolUpdateRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`patrolLayer`,id:`patrolMan`,lineColor:`#ff00ff`,lineWidth:3.5}],riskLevel:`low`},setTimeNode:{description:`设置巡逻开始的时间节点或是节点索引。`,payloadType:`PathPatrolSetTimeNodeRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`patrolLayer`,id:`patrolMan`,timeStart:`2025-09-10 00:05:00`}],riskLevel:`low`},clear:{description:`清除巡逻路径。`,payloadType:``,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{}],riskLevel:`low`},pause:{description:`暂停巡逻。`,payloadType:`PathPatrolNodeRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{id:`patrolMan`}],riskLevel:`low`},resume:{description:`继续巡逻。`,payloadType:`PathPatrolNodeRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{id:`patrolMan`}],riskLevel:`low`},stop:{description:`停止巡逻。`,payloadType:`PathPatrolNodeRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{id:`patrolMan`}],riskLevel:`low`}}},HighlighterEffect:{title:`高亮效果`,description:`高亮效果 API,控制场景中模型对象的高亮。`,capabilities:[`打开高亮`,`关闭高亮`,`模型高亮`,`移除模型高亮`,`清除全部高亮`],methods:{enable:{description:`打开高亮效果。`,payloadType:`HighLighterEnableRequest`,returnType:W,sideEffects:[`write`],preconditions:U,riskLevel:`low`},setHighLightModel:{description:`设置场景当中,指定模型对象 高亮效果`,payloadType:`HighLighterSetHighLightModelRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`test`,ids:[`Sphere`,`Sphere1`],showBack:!0}],riskLevel:`low`},removeHighLightModel:{description:`清除 指定模型对象的高亮效果`,payloadType:`HighLighterRemoveHighLightModelRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`test`,ids:[`Sphere`,`Sphere1`]}],riskLevel:`low`},clear:{description:`清除场景中模型的所有的高亮效果`,payloadType:``,returnType:W,sideEffects:[`write`],preconditions:U,riskLevel:`low`}}},Popup:{title:`前端 Popup`,description:`前端 Popup 管理 API。`,capabilities:[`Popup 添加`,`Popup 删除`,`Popup 清除`,`Popup 显隐控制`,`Popup 全部显隐控制`,`Popup 延迟帧控制`,`Popup 显示距离控制`],methods:{addPop:{description:`创建前端弹出气泡。`,payloadType:`PopupAddRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{groupName:`CameraPopGroup`,popInfo:[{id:`Camera1`,visible:!0}]}],riskLevel:`low`},removePop:{description:`删除前端气泡。`,payloadType:`PopupRemoveRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{groupName:`cameraLayer`,ids:[`camera01`]}],riskLevel:`low`},removeAll:{description:`清除所有前端气泡。`,payloadType:``,returnType:W,sideEffects:[`write`],preconditions:U,examples:[void 0],riskLevel:`low`},show:{description:`显示或隐藏气泡。`,payloadType:`PopupShowRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{groupName:`CameraPopGroup`,ids:[`Camera2`],show:!1}],riskLevel:`low`},showAll:{description:`显示或隐藏所有组下的所有气泡。`,payloadType:``,returnType:W,sideEffects:[`write`],preconditions:U,examples:[!0],riskLevel:`low`},setPopDelayFrame:{description:`设置前端气泡同步的延迟时间。`,payloadType:`PopupDelayRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{time:.3}],riskLevel:`low`},setPopShowDistance:{description:`设置前端页面气泡最远的显示距离(仅本地生效,不发送请求)。`,payloadType:``,returnType:W,sideEffects:[`write`],preconditions:U,examples:[2e3],riskLevel:`low`}}},Animation:{title:`模型动画`,description:`控制模型 Animator 和循环动画。`,capabilities:[`循环动画播放`,`循环动画停止`,`Animator 播放`,`Animator 停止`,`动画速度控制`,`动画长度查询`],methods:{startLoopAnimation:{description:`播放循环动画片段。`,payloadType:`AnimationStartLoopRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`AnimatorTest`,id:`rotateObj`,stateName:`door_open`,loopStartTime:0,loopEndTime:3,speed:1}],riskLevel:`low`},stopLoopAnimation:{description:`停止循环动画片段。`,payloadType:`AnimationStopLoopRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`AnimatorTest`,id:`rotateObj`}],riskLevel:`low`},playAnimator:{description:`播放 Animator 动画片段。`,payloadType:`AnimationPlayRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`AnimatorTest`,id:`rotateObj`,stateName:`door_open`,speed:1,startTime:0,endTime:1,isStop:!1}],riskLevel:`low`},setAnimatorSpeed:{description:`设置 Animator 动画播放速度。`,payloadType:`AnimationSetSpeedRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`AnimatorTest`,id:`rotateObj`,speed:1.5}],riskLevel:`low`},getAnimationLength:{description:`获取动画片段长度。`,payloadType:`AnimationGetLengthRequest`,returnType:W,sideEffects:[`read`],preconditions:U,examples:[{parentId:`AnimatorTest`,id:`rotateObj`,stateName:`door_open`}],riskLevel:`low`},stopAnimator:{description:`停止指定对象的 Animator 播放。`,payloadType:`AnimationStopRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{parentId:`AnimatorTest`,id:`rotateObj`}],riskLevel:`low`}}},TimeLine:{title:`时间线动画`,description:`TimeLine 动画控制 API。`,capabilities:[`时间线播放`,`时间线暂停`,`时间线恢复`,`时间线停止`,`全部时间线停止`,`播放速度控制`],methods:{play:{description:`播放指定 TimeLine 动画。`,payloadType:`TimelinePlayRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{id:`Path1`,speed:2}],riskLevel:`low`},pause:{description:`暂停指定 TimeLine 动画。`,payloadType:`TimelineNodeRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{id:`Path1`}],riskLevel:`low`},resume:{description:`继续播放指定 TimeLine 动画。`,payloadType:`TimelineNodeRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{id:`Path1`}],riskLevel:`low`},stop:{description:`停止指定 TimeLine 动画。`,payloadType:`TimelineStopRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{id:`Path1`,resetTime:-1,isCameraToStart:!1}],riskLevel:`low`},stopAll:{description:`停止全部 TimeLine 动画。`,payloadType:``,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{}],riskLevel:`low`},setSpeed:{description:`设置指定 TimeLine 的播放速度。`,payloadType:`TimelineSetSpeedRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{id:`Path1`,speed:1.2}],riskLevel:`low`}}},WeatherSystem:{title:`天气时间环境`,description:`天气与时间环境控制 API。`,capabilities:[`天气类型查询`,`天气切换`,`天气重置`,`天气时间重置`,`场景时间设置`,`时间同步控制`,`昼夜动画控制`,`昼夜模式设置`,`季节切换`,`季节重置`,`雾效开启`,`雾效关闭`],methods:{changeWeatherType:{description:`切换天气类型。`,payloadType:`WeatherTypeRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{type:0,timeDuration:60}],riskLevel:`low`},getWeatherTypes:{description:`得到所有天气类型`,payloadType:``,returnType:W,sideEffects:[`read`],preconditions:U,examples:[{}],riskLevel:`low`},resetWeather:{description:`重置天气`,payloadType:``,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{}],riskLevel:`low`},setSceneTime:{description:`设置场景时间(小时)。`,payloadType:`WeatherSetSceneTimeRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{hour:10.5,timeDuration:5}],riskLevel:`low`},setTimeSync:{description:`设置是否同步系统时间。`,payloadType:`WeatherSetTimeSyncRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{syncSystemTime:!0}],riskLevel:`low`},resetSceneTime:{description:`重置场景时间。`,payloadType:``,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{}],riskLevel:`low`},setAnimateTimeOfDay:{description:`设置是否模拟白天,黑夜轮换动画。`,payloadType:`WeatherSetAnimateTimeOfDayRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{isAnimate:!0,dayLength:.5,nightLength:.5}],riskLevel:`low`},resetWeatherAndTime:{description:`场景天气和时间重置`,payloadType:``,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{}],riskLevel:`low`},changeSeason:{description:`切换场景季节状态。`,payloadType:`WeatherChangeSeasonRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{season:1,duration:5}],riskLevel:`low`},resetSeason:{description:`重置场景季节状态。`,payloadType:``,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{}],riskLevel:`low`},setDayAndNight:{description:`在白天与夜晚模式之间切换。`,payloadType:`WeatherSetDayAndNightRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{dayType:`night`}],riskLevel:`low`},openCameraFog:{description:`开启并调整相机镜头雾效。`,payloadType:`WeatherOpenCameraFogRequest`,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{fogStartDistance:20,fogEndDistance:1500,fogIntensity:.5}],riskLevel:`low`},closeCameraFog:{description:`关闭相机镜头雾效。`,payloadType:``,returnType:W,sideEffects:[`write`],preconditions:U,examples:[{}],riskLevel:`low`}}}},gt=e=>e instanceof r.ZodEffects?gt(e._def.schema):e,_t=e=>{let t=gt(e);return t instanceof r.ZodOptional||t instanceof r.ZodDefault?{schema:gt(t._def.innerType),required:!1,description:t.description??``}:{schema:t,required:!0,description:t.description??``}},vt=e=>_t(e).schema instanceof r.ZodUndefined,yt=e=>{if(!(e instanceof r.ZodUnion))return;let t=e._def.options;if(!t.every(e=>e instanceof r.ZodLiteral))return;let n=t.map(e=>({value:e._def.value,...e.description?{description:e.description}:{}}));return{enumValues:n.map(e=>e.value),enumOptions:n}},bt=e=>{let t=yt(e);if(t)return{type:`enum`,...t};let n=`unknown`;return e instanceof r.ZodString?n=`string`:e instanceof r.ZodNumber?n=`number`:e instanceof r.ZodBoolean?n=`boolean`:e instanceof r.ZodObject?n=`object`:e instanceof r.ZodArray&&(n=`array`),{type:n}},xt=e=>{if(vt(e))return[];let t=_t(e).schema;return t instanceof r.ZodObject?Object.entries(t.shape).map(([e,t])=>{let{schema:n,required:r,description:i}=_t(t);return{name:e,required:r,description:i,...bt(n)}}):[]},St=[`write`],Ct=[`DTCEngine 已完成鉴权并建立 WebRTC 连接`],wt=(e,t,n)=>{let r=e[t],i=`${n.charAt(0).toLowerCase()}${n.slice(1)}`;return r?.[n]??r?.[i]},Tt=e=>e.apiModuleKeys.reduce((t,n)=>{let r=e.jsDocMetadata[n];return t[n]={moduleName:n,title:r.title,description:r.description,capabilities:r.capabilities,methods:Object.entries(r.methods).map(([t,r])=>{let i=[...r.sideEffects??St],a=[...r.preconditions??Ct],o=wt(e.schemaMap,n,t);if(!o)throw Error(`Missing validation schema for ${n}.${t}`);let s=vt(o)?`none`:`object`,c=s===`none`?[]:[...r.examples??[]],l=xt(o);return{moduleName:n,methodName:t,description:r.description,sideEffects:i,preconditions:a,riskLevel:r.riskLevel,schema:{payloadKind:s,fields:l,examples:c}}})},t},{});function Et(e){return{moduleName:e.moduleName,methodName:e.methodName,description:e.description,sideEffects:e.sideEffects,preconditions:e.preconditions}}const Dt=Tt({apiModuleKeys:H,schemaMap:Ge,jsDocMetadata:ht});function Ot(e){return e}function kt(e){return H.indexOf(e)>=0}function At(e){return e??`all`}function jt(e,t){let n=At(t);return n===`all`||n[e]!==void 0}function Mt(e,t,n){let r=At(n);if(r===`all`)return!0;let i=r[e];return i===!0||Array.isArray(i)&&i.indexOf(t)>=0}function Nt(e){return H.filter(t=>jt(t,e)).map(t=>{let n=Dt[t],r=Pt(t,e).length;return{moduleName:n.moduleName,title:n.title,description:n.description,capabilities:n.capabilities,methodCount:r}})}function Pt(e,t){return jt(e,t)?Dt[e].methods.filter(n=>Mt(e,n.methodName,t)).map(e=>Et(e)):[]}function Ft(e,t,n){if(Mt(e,t,n))return Dt[e].methods.find(e=>e.methodName===t)?.schema}function It(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`sdk3_${crypto.randomUUID()}`:`sdk3_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}function Lt(e){return{ok:!0,data:e,ts:Date.now()}}function G(e,t,n){return{ok:!1,error:{code:e,message:t,moduleName:n?.moduleName,methodName:n?.methodName,details:n?.details},ts:Date.now()}}function Rt(){return typeof document>`u`?void 0:document.title}function zt(){return typeof window>`u`?void 0:window.location.href}function Bt(e){return e.runtimeName??e.engineConfig?.sceneName??Rt()??e.engineConfig?.engineUuid}function Vt(e){if(e)return{sceneName:e.sceneName,engineUuid:e.engineUuid,mapType:e.mapType,operationType:e.operationType,viewMode:e.viewMode,centerIP:e.centerIP,signalingServer:e.signalingServer,codec:e.codec}}function Ht(e){return typeof e==`object`&&!!e}function Ut(e){return Ht(e)&&Object.keys(e).length===0}function Wt(e){return Ht(e)&&typeof e.ok==`boolean`&&typeof e.ts==`number`}function Gt(e){return new Promise(t=>{setTimeout(t,e)})}function Kt(e,t){let n=t?.fields.filter(e=>e.required)??[];if(n.length!==0)return Ht(e)?n.find(t=>e[t.name]===void 0):n[0]}function qt(e){return e instanceof d?e.toJSON():e instanceof Error?{name:e.name,message:e.message}:e}function Jt(e,t={}){let n=t.bridgeId??It(),r=At(t.expose),i=!1,a=()=>{i=!0},o=()=>{i=!1};e.on(e.Events.WebRtcConnected,a),e.on(e.Events.WebRtcDisconnected,o),e.on(e.Events.WebRtcFailed,o);function s(){return{bridgeId:n,connected:i,runtimeName:Bt(t),title:Rt(),pageUrl:zt(),sdkVersion:t.sdkVersion,metadata:t.metadata,engine:Vt(t.engineConfig)}}function c(e){return kt(e)?jt(e,r)?e:G(`API_NOT_EXPOSED`,`API module "${e}" is not exposed by agentBridge.expose.`,{moduleName:e}):G(`API_NOT_FOUND`,`API module "${e}" does not exist.`,{moduleName:e})}function l(t,n){if(!Mt(t,n,r))return G(`API_NOT_EXPOSED`,`API method "${t}.${n}" is not exposed.`,{moduleName:t,methodName:n});let i=e[t];return!Ht(i)||typeof i[n]!=`function`?G(`API_NOT_FOUND`,`API method "${t}.${n}" does not exist.`,{moduleName:t,methodName:n}):i}return{getSnapshot:s,dispose(){e.off(e.Events.WebRtcConnected,a),e.off(e.Events.WebRtcDisconnected,o),e.off(e.Events.WebRtcFailed,o)},listModules(){return Nt(r)},listMethods(e){let t=c(e);return typeof t==`string`?Lt(Pt(t,r)):t},getMethodSchema(e,t){let n=c(e);if(typeof n!=`string`)return n;if(!Mt(n,t,r))return G(`API_NOT_EXPOSED`,`API method "${n}.${t}" is not exposed.`,{moduleName:n,methodName:t});let i=Ft(n,t,r);return i?Lt(i):G(`METHOD_SCHEMA_NOT_FOUND`,`Schema for "${n}.${t}" is not available.`,{moduleName:n,methodName:t})},async invoke(e){let n=c(e.moduleName);if(typeof n!=`string`)return n;let i=l(n,e.methodName);if(Wt(i))return i;let a=Ft(n,e.methodName,r);if(!a)return G(`METHOD_SCHEMA_NOT_FOUND`,`Schema for "${n}.${e.methodName}" is not available.`,{moduleName:n,methodName:e.methodName});let o=s();if(!o.connected)return G(`SDK_NOT_READY`,`DTCEngine is not connected yet.`,{moduleName:n,methodName:e.methodName,details:o});if(a.payloadKind===`none`&&e.payload!==void 0&&!Ut(e.payload))return G(`INVALID_PAYLOAD`,`API method "${n}.${e.methodName}" does not accept payload.`,{moduleName:n,methodName:e.methodName,details:e.payload});let u=Kt(e.payload,a);if(u)return G(`INVALID_PAYLOAD`,`Missing required payload field "${u.name}".`,{moduleName:n,methodName:e.methodName,details:{field:u.name}});let f=i[e.methodName];if(typeof f!=`function`)return G(`API_NOT_FOUND`,`API method "${n}.${e.methodName}" does not exist.`,{moduleName:n,methodName:e.methodName});if(t.mockInvoke===!0)return await Gt(100),Lt({success:!0,code:`MOCK_OK`,message:`mock invoke success`,data:null});try{return Lt(a.payloadKind===`none`||e.payload===void 0?await f.call(i):await f.call(i,e.payload))}catch(t){return t instanceof d?G(`INVALID_PAYLOAD`,t.message,{moduleName:n,methodName:e.methodName,details:t.toJSON()}):G(`API_EXECUTION_FAILED`,`API method "${n}.${e.methodName}" failed.`,{moduleName:n,methodName:e.methodName,details:qt(t)})}}}}function Yt(){return typeof globalThis<`u`&&typeof globalThis.location?.href==`string`?globalThis.location?.href??``:``}function Xt(){return typeof globalThis<`u`&&typeof globalThis.navigator?.userAgent==`string`?globalThis.navigator?.userAgent??``:``}const Zt=r.string().min(1),Qt=[`bs`,`cs`],$t=r.custom(e=>typeof e==`object`&&!!e,`dom must be a valid HTMLDivElement`),en={centerHeartbeatIntervalMs:5e3,centerHeartbeatTimeoutMs:5e4},K={runMode:`RunMode/`,centerIP:`CenterIP/`,privateKey:`PrivateKey/`,showProgressBar:`showProgressBar/`},tn=r.object({centerIP:Zt.optional(),signalingServer:Zt.optional(),sceneName:Zt.optional(),token:Zt.optional(),dom:$t.optional(),showProgressBar:r.boolean().optional().default(!0),codec:r.string().optional().default(`H264`),viewMode:r.enum(Qt).optional().default(`bs`),turnServer:r.string().optional(),turnUser:r.string().optional(),turnPwd:r.string().optional(),privateKey:r.string().optional(),engineUuid:r.string().optional(),mapType:r.string().optional().default(`web`),operationType:r.string().optional().default(`viewer`),freeCheckInterval:r.number().int().min(0).optional().default(0),initialSettings:r.record(r.unknown()).optional().default({}),logger:r.enum([`silent`,`error`,`warn`,`info`,`debug`]).optional().default(`info`),centerHeartbeatIntervalMs:r.never().optional(),centerHeartbeatTimeoutMs:r.never().optional()}).strict().superRefine((e,t)=>{!e.centerIP&&!e.signalingServer&&t.addIssue({code:r.ZodIssueCode.custom,path:[`centerIP`],message:`one of centerIP, signalingServer is required`}),e.sceneName||t.addIssue({code:r.ZodIssueCode.custom,path:[`sceneName`],message:`sceneName is required`}),e.token||t.addIssue({code:r.ZodIssueCode.custom,path:[`token`],message:`token is required`}),e.dom||t.addIssue({code:r.ZodIssueCode.custom,path:[`dom`],message:`dom is required`})});function nn(e){let t={};return e.split(` `).forEach(e=>{if(e.startsWith(K.runMode)){t.viewMode=e.slice(K.runMode.length);return}if(e.startsWith(K.centerIP)){t.centerIP=e.slice(K.centerIP.length);return}if(e.startsWith(K.privateKey)){t.privateKey=e.slice(K.privateKey.length);return}if(e.startsWith(K.showProgressBar)){let n=e.slice(K.showProgressBar.length);n===`true`?t.showProgressBar=!0:n===`false`&&(t.showProgressBar=!1)}}),t}function rn(e){let t=Xt()||void 0;if(!t)return e;let n=nn(t);return Object.keys(n).length===0?e:{...e,...n}}function an(e){let t=rn(e),n=tn.safeParse(t);if(!n.success)throw new d(`Core`,`DTCEngine.constructor`,n.error.issues.map(e=>({field:e.path.length>0?e.path.join(`.`):`<root>`,reason:e.message,code:e.code})));let r=n.data;return{centerIP:r.centerIP??``,signalingServer:r.signalingServer,sceneName:r.sceneName??``,token:r.token??``,dom:r.dom,showProgressBar:r.showProgressBar,codec:r.codec,viewMode:r.viewMode,turnServer:r.turnServer,turnUser:r.turnUser,turnPwd:r.turnPwd,privateKey:r.privateKey??``,engineUuid:r.engineUuid,mapType:r.mapType,operationType:r.operationType,freeCheckInterval:r.freeCheckInterval,initialSettings:r.initialSettings,logger:r.logger,centerHeartbeatIntervalMs:en.centerHeartbeatIntervalMs,centerHeartbeatTimeoutMs:en.centerHeartbeatTimeoutMs}}const on=[`token`,`privatekey`,`authorization`,`cookie`,`set-cookie`],sn={enabled:!1,endpoint:``,apiKey:``,app:{name:`@nnepoch/dtc-sdk`,version:`0.1.0`,environment:`production`},batching:{enabled:!0,itemLimit:20,sendTimeoutMs:3e4},retry:{maxAttempts:2},failure:{disableAfterConsecutiveFailures:5,warningIntervalMs:3e4},redactKeys:on},cn=r.object({enabled:r.boolean().default(!1),endpoint:r.string().optional(),apiKey:r.string().optional(),app:r.object({name:r.string().min(1).default(`@nnepoch/dtc-sdk`),version:r.string().min(1).default(`0.1.0`),environment:r.string().min(1).default(`production`)}).default({name:`@nnepoch/dtc-sdk`,version:`0.1.0`,environment:`production`}),batching:r.object({enabled:r.boolean().default(!0),itemLimit:r.number().int().min(1).default(20),sendTimeoutMs:r.number().int().min(200).default(3e3)}).default({enabled:!0,itemLimit:20,sendTimeoutMs:3e3}),retry:r.object({maxAttempts:r.number().int().min(1).max(5).default(2)}).default({maxAttempts:2}),failure:r.object({disableAfterConsecutiveFailures:r.number().int().min(1).default(5),warningIntervalMs:r.number().int().min(1e3).default(3e4)}).default({disableAfterConsecutiveFailures:5,warningIntervalMs:3e4}),redactKeys:r.array(r.string().min(1)).default(on)}).superRefine((e,t)=>{let n=typeof e.endpoint==`string`?e.endpoint.trim():``,i=n.length>0;if(e.enabled&&!i){t.addIssue({code:r.ZodIssueCode.custom,path:[`endpoint`],message:`qos reporting enabled requires endpoint`});return}e.enabled&&i&&!r.string().url().safeParse(n).success&&t.addIssue({code:r.ZodIssueCode.custom,path:[`endpoint`],message:`qos reporting endpoint must be a valid url`})});function ln(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function un(e,t){let n={...e};return Object.entries(t).forEach(([e,t])=>{if(t!==void 0){if(ln(t)&&ln(n[e])){n[e]=un(n[e],t);return}n[e]=t}}),n}function dn(){let e=ln(globalThis.__ENGINE3_INTERNAL_QOS_REPORTING__)?{...globalThis.__ENGINE3_INTERNAL_QOS_REPORTING__}:{};typeof e.endpoint==`string`&&e.endpoint.trim().length===0&&delete e.endpoint,typeof e.apiKey==`string`&&e.apiKey.trim().length===0&&delete e.apiKey;let t=un(sn,e);return cn.parse(t)}function fn(e,t){let n=e.toLowerCase();return t.some(e=>n.includes(e.toLowerCase()))}function pn(e){if(typeof e==`string`)return e;if(e===void 0)return`undefined`;if(e===null)return`null`;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function mn(e,t){let n=new WeakSet,r=(e,i)=>{if(i&&fn(i,t.redactKeys))return`[REDACTED]`;if(e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(typeof e==`bigint`)return e.toString();if(e===void 0)return`undefined`;if(typeof e==`function`||typeof e==`symbol`)return String(e);if(e instanceof Date)return e.toISOString();if(e instanceof Error)return{name:e.name,message:e.message,stack:e.stack};if(Array.isArray(e))return e.map(e=>r(e));if(typeof e==`object`&&e){if(n.has(e))return`[CIRCULAR]`;n.add(e);let t=Object.entries(e),i={};return t.forEach(([e,t])=>{i[e]=r(t,e)}),i}return pn(e)};return r(e)}function hn(e){let t=e.toLowerCase();return t.includes(`auth`)?`auth`:t.includes(`center`)?`center`:t.includes(`sessionadapter`)||t.includes(`webrtc`)||t.includes(`pixelstreaming`)?`webrtc`:t.includes(`enginestatus`)||t.includes(`stream`)?`media`:t.includes(`requestbridge`)||t.includes(`camera`)||t.includes(`scene`)||t.includes(`model`)||t.includes(`poi`)||t.includes(`weather`)||t.includes(`timeline`)||t.includes(`popup`)||t.includes(`animation`)?`ue_api`:`session`}function q(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function gn(e){return e.trim().replace(/\s+/g,`_`).slice(0,64)}function _n(e){if(!ln(e))return;let t=q(e.code)??q(e.errorCode)??q(e.status);if(t)return gn(t);let n=e.error;if(ln(n)){let e=q(n.code)??q(n.errorCode)??q(n.status);if(e)return gn(e)}}var vn=class{constructor(e,t){this.config=e,this.deps=t}async send(e){let t=typeof AbortController<`u`?new AbortController:void 0,n=t?setTimeout(()=>{t.abort()},this.config.batching.sendTimeoutMs):void 0;try{let n=await this.deps.fetchImpl(this.config.endpoint??``,{method:`POST`,headers:{"Content-Type":`application/json`,...this.config.apiKey?{"x-api-key":this.config.apiKey}:{}},body:JSON.stringify(e),signal:t?.signal});if(!n.ok)throw Error(`qos reporting request failed: ${n.status}`)}finally{n&&clearTimeout(n)}}};function yn(){return typeof fetch==`function`}var bn=class{constructor(e,t,n,r,i={}){if(this.config=e,this.session=t,this.runtime=n,this.onWarning=r,this.queue=[],this.flushing=!1,this.consecutiveFailures=0,this.lastWarningAt=0,this.disabledByFailure=!1,this.warnCount=0,this.errorCount=0,this.errorByStage={},this.errorCodeCounts=new Map,this.now=i.now??Date.now,this.setTimeoutImpl=i.setTimeoutImpl??setTimeout,this.clearTimeoutImpl=i.clearTimeoutImpl??clearTimeout,!e.enabled){this.enabled=!1,this.transport=void 0;return}if(this.enabled=!0,i.createTransport){this.transport=i.createTransport(e);return}if(!yn()){this.transport=void 0,this.warnLimited(`qos reporting skipped: fetch unavailable`);return}this.transport=new vn(e,{fetchImpl:fetch})}startSession(e){this.resetWarnErrorSummary(),this.recordEvent({eventName:`session_start`,stage:`session`,status:`start`,attrs:e})}endSession(e){this.recordEvent({eventName:`session_end`,stage:`session`,status:`end`,attrs:e,metrics:{summary:this.getWarnErrorSummary()}}),this.flush()}recordEvent(e){if(!this.enabled||!this.transport||this.disabledByFailure)return;let t=e.attrs?mn(e.attrs,this.config):void 0,n=e.metrics?mn(e.metrics,this.config):void 0;if(this.queue.push({eventName:e.eventName,stage:e.stage,status:e.status,ts:e.ts??this.now(),level:e.level??(e.status===`failed`?`error`:`info`),durationMs:e.durationMs,errorCode:e.errorCode,errorMessage:e.errorMessage,attrs:t,metrics:n}),!this.config.batching.enabled||this.queue.length>=this.config.batching.itemLimit){this.flush();return}this.flushTimer||=this.setTimeoutImpl(()=>{this.flushTimer=void 0,this.flush()},this.config.batching.sendTimeoutMs)}recordLogSignal(e){if(e.level===`warn`){this.warnCount+=1;return}this.errorCount+=1;let t=hn(e.moduleName);this.errorByStage[t]=(this.errorByStage[t]??0)+1;let n=_n(e.meta)??`UNKNOWN`;this.errorCodeCounts.set(n,(this.errorCodeCounts.get(n)??0)+1)}getWarnErrorSummary(){let e=Array.from(this.errorCodeCounts.entries()).sort((e,t)=>t[1]-e[1]).map(([e,t])=>({code:e,count:t}));return{logWarnCount:this.warnCount,logErrorCount:this.errorCount,logErrorByStage:{...this.errorByStage},logErrorTopCodes:e}}async flush(){if(this.flushing||this.queue.length===0||!this.transport||this.disabledByFailure)return;this.flushing=!0,this.flushTimer&&=(this.clearTimeoutImpl(this.flushTimer),void 0);let e=this.config.batching.enabled?this.config.batching.itemLimit:this.queue.length,t=this.queue.splice(0,e),n={schemaVersion:`1.0.0`,source:`enginesdk3`,sdkVersion:this.config.app.version,sentAt:this.now(),session:this.session,context:this.runtime,events:t};try{await this.sendWithRetry(n),this.consecutiveFailures=0}catch(e){this.onFailure(e,`send qos payload failed`)}finally{this.flushing=!1,this.queue.length>0&&!this.disabledByFailure&&this.flush()}}async sendWithRetry(e){let t=Math.max(1,this.config.retry.maxAttempts),n;for(let r=1;r<=t;r+=1)try{await this.transport?.send(e);return}catch(e){n=e}throw n instanceof Error?n:Error(String(n))}onFailure(e,t){this.consecutiveFailures+=1,this.warnLimited(t,{consecutiveFailures:this.consecutiveFailures,error:e instanceof Error?`${e.name}: ${e.message}`:String(e)}),this.consecutiveFailures>=this.config.failure.disableAfterConsecutiveFailures&&(this.disabledByFailure=!0,this.warnLimited(`qos reporting disabled after repeated failures`))}warnLimited(e,t){let n=this.now();n-this.lastWarningAt<this.config.failure.warningIntervalMs||(this.lastWarningAt=n,this.onWarning(e,t))}resetWarnErrorSummary(){this.warnCount=0,this.errorCount=0,this.errorByStage={},this.errorCodeCounts.clear()}},xn=class{constructor(){this.listeners=new Map,this.debugMode=!1}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),this.debugMode&&console.log(`[EventBus] Subscribed to "${String(e)}"`)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e)),this.debugMode&&console.log(`[EventBus] Unsubscribed from "${String(e)}"`)}emit(e,t){let n=this.listeners.get(e);this.debugMode&&console.log(`[EventBus] Emitting "${String(e)}"`,t),!(!n||n.size===0)&&n.forEach(n=>{try{n(t)}catch(t){console.error(`[EventBus] Error in handler for "${String(e)}":`,t)}})}once(e,t){let n=r=>{this.off(e,n),t(r)};this.on(e,n)}removeAllListeners(e){e===void 0?(this.listeners.clear(),this.debugMode&&console.log(`[EventBus] Removed all listeners`)):(this.listeners.delete(e),this.debugMode&&console.log(`[EventBus] Removed all listeners for "${String(e)}"`))}listenerCount(e){return this.listeners.get(e)?.size??0}eventNames(){return Array.from(this.listeners.keys())}setDebugMode(e){this.debugMode=e}};const Sn=[`webRtcConnected`,`webRtcDisconnected`,`webRtcConnecting`,`webRtcFailed`,`statsReceived`,`subscribeFailed`,`streamerAssigned`];var Cn=class{constructor(){this.mode=`bs`,this.forwardEvents=[...Sn,`streamLoading`]}applyInitialSettings(e){return{[o.KeyboardInput]:!0,[o.MouseInput]:!0,[o.TouchInput]:!0,[o.GamepadInput]:!0,[o.XRControllerInput]:!0,[o.HoveringMouseMode]:!0,[o.AutoPlayVideo]:!0,[o.MatchViewportResolution]:!0,[o.StartVideoMuted]:!0,[s.MaxReconnectAttempts]:0,...e}}onBeforeConnect(e){e.info(`session connect preparing for bs mode`)}onAfterConnect(e){e.info(`session connect triggered for bs mode`)}},wn=class{constructor(){this.mode=`cs`,this.forwardEvents=Sn}applyInitialSettings(e){return{[o.KeyboardInput]:!0,[o.MouseInput]:!1,[o.TouchInput]:!1,[o.GamepadInput]:!1,[o.XRControllerInput]:!1,[o.HoveringMouseMode]:!0,[o.AutoPlayVideo]:!0,[o.MatchViewportResolution]:!0,[o.StartVideoMuted]:!0,[s.MaxReconnectAttempts]:0,...e}}onBeforeConnect(e){e.info(`session connect preparing for cs mode`)}onAfterConnect(e){e.info(`session connect triggered for cs mode`)}};function Tn(e){return e===`cs`?new wn:new Cn}var En=class{constructor(e,t,n=m){this.logger=n,this.streamerAssignedListeners=new Set,this.modeStrategy=Tn(e.viewMode);let r=this.modeStrategy.applyInitialSettings(e.initialSettings??{});this.psConfig=new a({initialSettings:{...r}}),t?.classList?.add(`fixed-size`),t&&getComputedStyle(t).position===`static`&&(t.style.position=`relative`),this.stream=new l(this.psConfig,t?{videoElementParent:t}:void 0),this.setupStreamerAssignedListener(),this.logger.info(`session initialized`,{hasVideoParent:!!t,viewMode:this.modeStrategy.mode})}connect(){this.modeStrategy.onBeforeConnect(this.logger),this.logger.info(`connect`),this.stream.connect(),this.modeStrategy.onAfterConnect(this.logger)}reconnect(){this.logger.info(`reconnect`),this.stream.reconnect()}disconnect(){this.logger.info(`disconnect`),this.stream.disconnect()}setSignallingUrlBuilder(e){this.logger.info(`setSignallingUrlBuilder configured`),this.stream.setSignallingUrlBuilder(e)}emitUIInteraction(e){let t=this.stream.emitUIInteraction(e);return t?this.logger.debug(`emitUIInteraction sent`):this.logger.warn(`emitUIInteraction failed`),t}emitCommand(e){let t=this.stream.emitCommand(e);return t?this.logger.debug(`emitCommand sent`):this.logger.warn(`emitCommand failed`),t}addResponseEventListener(e,t){this.logger.debug(`addResponseEventListener`,{name:e}),this.stream.addResponseEventListener(e,t)}removeResponseEventListener(e){this.logger.debug(`removeResponseEventListener`,{name:e}),this.stream.removeResponseEventListener(e)}addEventListener(e,t){if(this.logger.debug(`addEventListener`,{event:e}),e===`streamerAssigned`){this.streamerAssignedListeners.add(t);return}this.stream.addEventListener(e,t)}removeEventListener(e,t){if(this.logger.debug(`removeEventListener`,{event:e}),e===`streamerAssigned`){this.streamerAssignedListeners.delete(t);return}this.stream.removeEventListener(e,t)}getForwardEvents(){return this.modeStrategy.forwardEvents}getViewMode(){return this.modeStrategy.mode}isReconnecting(){return this.stream.isReconnecting()}setupStreamerAssignedListener(){try{let e=this.stream.webRtcController?.protocol;if(!e||typeof e.addListener!=`function`){this.logger.warn(`webRtcController.protocol not available, streamerAssigned listener not registered`);return}e.addListener(`streamerAssigned`,e=>{if(this.logger.info(`streamerAssigned received`,{streamerId:e.streamerId}),e.streamerId)try{this.psConfig.setOptionSettingValue(c.StreamerId,e.streamerId),this.logger.info(`StreamerId configured`,{streamerId:e.streamerId})}catch(t){this.logger.error(`Failed to set StreamerId`,{streamerId:e.streamerId,error:t instanceof Error?t.message:String(t)})}else this.logger.warn(`streamerAssigned received without streamerId`,{msg:e});this.streamerAssignedListeners.forEach(t=>{try{t(e)}catch(e){this.logger.error(`streamerAssigned listener error`,{error:e instanceof Error?e.message:String(e)})}})}),this.logger.debug(`streamerAssigned listener registered`)}catch(e){this.logger.error(`Failed to setup streamerAssigned listener`,{error:e instanceof Error?e.message:String(e)})}}};const J={SignallingBootstrapFailed:`SIGNALLING_BOOTSTRAP_FAILED`,CenterUnavailable:`CENTER_UNAVAILABLE`,CenterProtocolInvalid:`CENTER_PROTOCOL_INVALID`,ConnectResultFailed:`CONNECT_RESULT_FAILED`,ServiceAllocationFailed:`SERVICE_ALLOCATION_FAILED`,ResourceWaiting:`RESOURCE_WAITING`,AuthorizeFailed:`AUTHORIZE_FAILED`,TokenInvalid:`TOKEN_INVALID`,TokenExpired:`TOKEN_EXPIRED`,SignallingUrlMissing:`SIGNALLING_URL_MISSING`,HeartbeatTimeout:`HEARTBEAT_TIMEOUT`,CenterDisconnected:`CENTER_DISCONNECTED`};var Y=class extends Error{constructor(e,t,n,r){super(t),this.code=e,this.retryable=n,this.details=r,this.name=`SDKAuthError`}toErrorInfo(){return{code:this.code,message:this.message,retryable:this.retryable}}};function Dn(e){return e instanceof Y?e:e instanceof Error?new Y(J.CenterUnavailable,e.message,!0,{cause:e.message}):new Y(J.CenterUnavailable,String(e),!0)}var On=class{constructor(t,n=m,r){this.config=t,this.logger=n,this.authEvents=r,this.textEncoder=new TextEncoder,this.connectId=``,this.events=new e,this.manualClose=!1}on(e,t){this.events.on(e,t)}off(e,t){this.events.off(e,t)}isConnected(){return this.socket?.readyState===WebSocket.OPEN}getConnectId(){return this.connectId}async connect(){if(this.isConnected())return;this.disposeSocket(),this.connectId=this.generateConnectId();let e=this.buildCenterWsUrl(this.connectId),t=this.defaultWebSocketFactory;return this.logger.info(`center connecting`,{wsUrl:e}),this.manualClose=!1,this.closeReasonError=void 0,new Promise((n,r)=>{try{let i=t(e);this.socket=i,i.onopen=()=>{this.startHeartbeatLoops(),this.sendHeartbeat(),this.logger.info(`center connected`),i.binaryType=`arraybuffer`,n()},i.onmessage=e=>{this.handleIncomingData(e.data)},i.onerror=()=>{},i.onclose=()=>{this.stopHeartbeatLoops(),this.socket=void 0;let e=this.closeReasonError??new Y(J.CenterDisconnected,`Center websocket disconnected`,!0);this.manualClose||(this.events.emit(`disconnected`,e),r(e)),this.closeReasonError=void 0}}catch(e){this.authEvents.emit(`progress`,{kind:`loading`,message:g.ServiceUrlInValid,key:`ServiceUrlInValid`,isClose:!0}),r(new Y(J.CenterUnavailable,`Failed to create center websocket: ${e instanceof Error?e.message:String(e)}`,!0,{cause:e instanceof Error?e.message:String(e)}))}})}disconnect(){this.manualClose=!0,this.closeReasonError=void 0,this.disposeSocket()}sendApiData(e,t,n){if(!this.socket||this.socket.readyState!==WebSocket.OPEN)throw new Y(J.CenterDisconnected,`Center websocket is not connected`,!0);let r={projectKey:this.config.sceneName,cls:`WebAPI`,method:e,param:t,fn:n},i=JSON.stringify(r),a=this.textEncoder.encode(i),o=new Uint8Array(a.length+1);o.set(a),this.socket.send(o.buffer),e!==`Heart`&&this.logger.debug(`center send`,{method:e,callbackName:n})}defaultWebSocketFactory(e){if(typeof WebSocket>`u`)throw Error(`WebSocket is not available in current runtime.`);return new WebSocket(e)}startHeartbeatLoops(){this.stopHeartbeatLoops(),this.heartbeatTimer=setInterval(()=>{try{this.isConnected()&&this.sendHeartbeat()}catch(e){this.logger.warn(`send heartbeat failed`,{error:e instanceof Error?e.message:String(e)})}},this.config.centerHeartbeatIntervalMs)}sendHeartbeat(){this.sendApiData(`Heart`),this.armHeartbeatTimeout()}stopHeartbeatLoops(){this.heartbeatTimer&&=(clearInterval(this.heartbeatTimer),void 0),this.clearHeartbeatTimeout()}armHeartbeatTimeout(){this.heartbeatTimeoutTimer||=setTimeout(()=>{this.heartbeatTimeoutTimer=void 0;let e=new Y(J.HeartbeatTimeout,`Center heartbeat timed out after ${this.config.centerHeartbeatTimeoutMs}ms`,!0);this.closeReasonError=e,this.events.emit(`heartbeatTimeout`,e),this.socket?.close()},this.config.centerHeartbeatTimeoutMs)}clearHeartbeatTimeout(){this.heartbeatTimeoutTimer&&=(clearTimeout(this.heartbeatTimeoutTimer),void 0)}disposeSocket(){this.stopHeartbeatLoops(),this.socket&&=(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,this.socket.close(),void 0)}async handleIncomingData(e){this.clearHeartbeatTimeout();let t=await this.decodeToBytes(e);if(!t)return;let n;try{n=u(t,{to:`string`})}catch{this.logger.warn(`center message inflate failed`);return}if(!n)return;let r;try{r=JSON.parse(n)}catch{this.logger.warn(`center message parse failed`);return}if(!r.fn){this.logger.warn(`center message missing fn`);return}r.fn!==`Heart`&&this.events.emit(`message`,r)}async decodeToBytes(e){if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(typeof Blob<`u`&&e instanceof Blob){let t=await e.arrayBuffer();return new Uint8Array(t)}return typeof e==`string`?this.textEncoder.encode(e):(this.logger.warn(`unsupported center message format`),null)}buildCenterWsUrl(e){return`${this.config.centerIP.replace(/^https:/i,`wss:`).replace(/^http:/i,`ws:`).replace(/\/+$/,``)}/${[this.config.mapType,e,this.config.sceneName,this.config.token,this.config.operationType].map(e=>encodeURIComponent(e)).join(`/`)}`}generateConnectId(){return`w_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}};function kn(e,t,n){let r=e.endsWith(`/`)?e:`${e}/`,i=new URL(`api/v1/allocate`,r);return i.searchParams.set(`token`,t),i.searchParams.set(`proj`,n),i.toString()}function An(e){if(typeof e.signalingAddress==`string`&&e.signalingAddress.trim().length>0)return e.signalingAddress.trim();if(typeof e.signallingAddress==`string`&&e.signallingAddress.trim().length>0)return e.signallingAddress.trim()}async function jn(e,t=m){if(typeof fetch!=`function`)throw new Y(J.SignallingBootstrapFailed,`Fetch API is not available for signalling allocation`,!1);let n=kn(e.signalingServer,e.token,e.proj);try{let e=await fetch(n,{method:`GET`});if(!e.ok)throw new Y(J.SignallingBootstrapFailed,`Signalling allocate request failed with status ${e.status}`,!0,{endpoint:n,status:e.status});let r;try{r=await e.json()}catch(e){throw new Y(J.SignallingBootstrapFailed,`Signalling allocate response is not valid JSON`,!1,{endpoint:n,cause:e instanceof Error?e.message:String(e)})}let i=An(r);if(!i)throw new Y(J.SignallingUrlMissing,`Signalling allocate response missing signalingAddress`,!1,r);return t.info(`signalling allocate resolved url`,{endpoint:n}),i}catch(e){throw e instanceof Y?e:new Y(J.SignallingBootstrapFailed,e instanceof Error?e.message:`Signalling allocate request failed`,!0,{endpoint:n,cause:e})}}var Mn=class{constructor(t,n,r=m){this.config=t,this.session=n,this.logger=r,this.events=new e,this.handleWebRtcDisconnected=()=>{this.recoverFromWebRtcDisconnection()},this.nextOperationId=0,this.phase=`idle`,this.stopRequested=!1,this.reconnecting=!1,this.snapshot={state:`idle`,reconnecting:!1,updatedAt:Date.now()},this.centerClient=new On(t,r,this.events),this.centerClient.on(`heartbeatTimeout`,e=>{this.logger.warn(`center heartbeat timeout`,{message:e.message}),this.handleCenterInterruption(e)}),this.centerClient.on(`disconnected`,e=>{this.logger.warn(`center disconnected`,{message:e.message}),this.handleCenterInterruption(e)}),this.centerClient.on(`message`,e=>{this.handleCenterMessage(e)}),this.session.addEventListener(`webRtcDisconnected`,this.handleWebRtcDisconnected)}on(e,t){this.events.on(e,t)}off(e,t){this.events.off(e,t)}getSnapshot(){return{...this.snapshot,reconnecting:this.reconnecting||this.session.isReconnecting()}}start(){return this.runningFlow?this.runningFlow.promise:this.startFlow({route:this.shouldUseDirectSignallingBootstrap()?`direct`:`center`,reconnecting:!1,disconnectSession:!1,resolveOnStop:!0})}reconnect(){return this.startFlow({route:this.shouldUseDirectSignallingBootstrap()?`direct`:`center`,reconnecting:!0,disconnectSession:!0,resolveOnStop:!0})}reconnectSignalling(){let e=this.signallingAllocationSource;return e?this.startFlow({route:`signalling`,reconnecting:!0,disconnectSession:!0,resolveOnStop:!1,signallingSource:e}):this.reconnect()}startFlow(e){if(this.runningFlow)return e.reconnecting&&(this.reconnecting=!0),e.disconnectSession&&this.session.disconnect(),this.runningFlow.promise;e.disconnectSession&&this.session.disconnect(),this.stopRequested=!1,this.reconnecting=e.reconnecting;let t=this.advanceOperation(),n=this.createRunningFlow(t,e.resolveOnStop);return this.runningFlow=n,this.phase=e.route===`signalling`?`settling`:`starting`,n.promise=this.decorateRunningFlow(n),(e.route===`center`||e.route===`direct`)&&this.prepareAuthBootstrap(t),this.runFlowRoute(e,t),n.promise}runFlowRoute(e,t){switch(e.route){case`center`:this.runCenterFlow(t);return;case`direct`:this.runDirectFlow(t);return;case`signalling`:this.runSignallingFlow(e.signallingSource,t);return}}prepareAuthBootstrap(e){this.centerClient.disconnect(),this.clearRunningContext(),this.pendingCenterInterruption=void 0,this.updateSnapshot(`centerConnecting`,{lastError:void 0,signallingUrl:void 0,engineToken:void 0,webToken:void 0}),this.isCurrentOperation(e)}runCenterFlow(e){this.runAuthFlowOnce(e)}runDirectFlow(e){this.startDirectSignallingBootstrap(e).catch(t=>{this.rejectActiveFlow(t,e)})}runSignallingFlow(e,t){if(!e){this.rejectActiveFlow(new Y(J.SignallingBootstrapFailed,`Signalling bootstrap source is missing`,!1),t);return}this.signallingAllocationSource=e,this.resolveAndConnectSignalling(e,t).catch(e=>{this.rejectActiveFlow(e,t)})}disconnect(){let e=this.runningFlow;this.advanceOperation(),this.runningFlow=void 0,this.reconnecting=!1,this.stopRequested=!0,this.pendingCenterInterruption=void 0,this.phase=`idle`;let t=new Y(J.CenterDisconnected,`Auth workflow disconnected by user`,!0);e&&(e.stopRequested=!0,e.reject?.(t),e.resolve=void 0,e.reject=void 0),this.centerClient.disconnect(),this.session.disconnect(),this.updateSnapshot(`idle`,{webToken:void 0,engineToken:void 0,signallingUrl:void 0,lastError:void 0}),e&&(e.stopSnapshot=this.getSnapshot())}disconnectAndWait(){let e=this.runningFlow?.promise;return this.disconnect(),e?e.then(()=>void 0,()=>void 0):Promise.resolve()}runAuthFlowOnce(e){this.isCurrentOperation(e)&&this.centerClient.connect().then(()=>{this.isCurrentOperation(e)&&(this.updateSnapshot(`centerConnected`),this.expectMessage(`ConnectResult`))}).catch(t=>{this.rejectActiveFlow(t,e)})}shouldUseDirectSignallingBootstrap(){return!!this.config.signalingServer}async startDirectSignallingBootstrap(e){if(!this.isCurrentOperation(e))return;this.setPhase(`settling`,e);let t=this.resolveDirectSignallingAllocationSource();this.signallingAllocationSource=t,await this.resolveAndConnectSignalling(t,e)}resolveDirectSignallingAllocationSource(){if(this.config.signalingServer)return{signalingServer:this.config.signalingServer,token:this.config.token,proj:this.config.sceneName};throw new Y(J.SignallingBootstrapFailed,`No signalling bootstrap source configured`,!1)}handleCenterMessage(e){switch(e.fn){case`ConnectResult`:this.emitCenterEvent(`ConnectResult`,e),this.handleConnectResult(e);return;case`EngineServiceInit`:this.emitCenterEvent(`EngineServiceInit`,e),this.handleEngineServiceInit(e);return;case`TokenAuthorize`:this.emitCenterEvent(`TokenAuthorize`,e),this.handleTokenAuthorize(e);return;case`CenterCloseMessage`:this.emitCenterEvent(`CenterCloseMessage`,e),this.handleCenterCloseMessage(e);return;case`EngineSocketClose`:this.emitCenterEvent(`EngineSocketClose`,e),this.handleEngineSocketClose(e);return;case`TokenWillExpired`:this.emitCenterEvent(`TokenWillExpired`,e),this.handleTokenWillExpired(e);return;case`Offer`:case`Answer`:case`IceCandidate`:this.logger.debug(`center message ignored by current change scope`,{fn:e.fn});return;default:this.logger.debug(`unhandled center message`,{fn:e.fn})}}handleConnectResult(e){if(this.isExpecting(`ConnectResult`))try{if(e.success===!1){this.logger.warn(`connect result failed`,{status:e.status??``,message:e.message??``});return}let t=this.parseValues(e),n=t.webToken;if(!n)throw new Y(J.ConnectResultFailed,`ConnectResult missing webToken`,!0,e);this.connectResult=t,this.emitCenterEvent(`Connect`,e),this.emitLoadingProgress(g.EngineIniting,`EngineIniting`),this.updateSnapshot(`serviceAllocating`,{webToken:n}),this.centerClient.sendApiData(`GetServiceInfo`,this.config.privateKey||void 0),this.expectMessage(`EngineServiceInit`)}catch(e){this.rejectActiveFlow(e)}}handleEngineServiceInit(e){if(this.isExpecting(`EngineServiceInit`))try{if(e.success===!1){let t=e.message??``;this.emitWaitingProgress(t),this.config.viewMode!==`cs`&&this.emitCenterEvent(`EngineServiceInitWait`,e),this.updateSnapshot(`waiting`);return}let t=this.parseValues(e),n=t.token;if(!n)throw new Y(J.ServiceAllocationFailed,`EngineServiceInit missing engine token`,!0,e);this.serviceInfo=t,this.emitLoadingProgress(g.EngineTockenChecking,`EngineTockenChecking`),this.updateSnapshot(`authorizing`,{engineToken:n});let r=JSON.stringify({engineToken:n,webUuid:this.centerClient.getConnectId(),webToken:this.snapshot.webToken});this.centerClient.sendApiData(`AuthorizeToken`,r,`TokenAuthorize`),this.expectMessage(`TokenAuthorize`)}catch(e){this.rejectActiveFlow(e)}}handleTokenAuthorize(e){if(!this.isExpecting(`TokenAuthorize`))return;if(e.success===!1){this.logger.warn(`token authorize failed, wait center close message`,{status:e.status??``,message:e.message??``});return}let t=this.runningFlow?.operationId;t!==void 0&&this.handleTokenAuthorizeSuccess(e,t).catch(e=>{this.rejectActiveFlow(e,t)})}async handleTokenAuthorizeSuccess(e,t){if(!this.isCurrentOperation(t))return;this.setPhase(`settling`,t);let n=(this.tryParseValues(e)??{}).signalingServer?.trim();if(!n)throw new Y(J.SignallingUrlMissing,`TokenAuthorize missing signalingServer`,!1,e);let r=this.snapshot.engineToken;if(!r)throw new Y(J.ServiceAllocationFailed,`Engine token is missing before signaling allocation`,!1,e);let i={signalingServer:n,token:r,proj:this.config.sceneName};this.signallingAllocationSource=i,await this.resolveAndConnectSignalling(i,t)}async resolveAndConnectSignalling(e,t){let n=await jn(e,this.logger);if(!this.isCurrentOperation(t)){this.logger.debug(`ignore stale signalling allocation result`,{operationId:t});return}this.connectWithSignallingUrl(n,t)}connectWithSignallingUrl(e,t){if(!this.isCurrentOperation(t)){this.logger.debug(`ignore stale signalling connect result`,{operationId:t});return}if(!e)throw new Y(J.SignallingUrlMissing,`Signalling url is missing before connect`,!1);this.session.setSignallingUrlBuilder(()=>{let e=this.snapshot.signallingUrl;if(!e)throw new Y(J.SignallingUrlMissing,`Signalling url not ready before connect`,!1);return e}),this.emitLoadingProgress(g.EngineConnectioning,`EngineConnectioning`),this.updateSnapshot(`webrtcConnecting`,{signallingUrl:e}),this.session.connect(),this.setPhase(`connected`,t),this.updateSnapshot(`connected`),this.completeRunningFlow(this.getSnapshot(),t)}handleCenterCloseMessage(e){let t=e.message??`CenterCloseMessage received`;if(e.status===`TokenInValid`){this.emitLoadingProgress(g.TokenInValid,`TokenInValid`);let n=new Y(J.TokenInvalid,t,!1,e);this.rejectActiveFlow(n)||this.publishFailure(n),this.centerClient.disconnect();return}if(e.status===`TokenExpired`){this.emitLoadingProgress(g.TokenExpired,`TokenExpired`);let n=new Y(J.TokenExpired,t,!1,e);this.rejectActiveFlow(n)||this.publishFailure(n),this.centerClient.disconnect();return}this.emitLoadingProgress(g.EngineTokenCheckFail,`EngineTokenCheckFail`);let n=new Y(J.AuthorizeFailed,t,!1,e);this.rejectActiveFlow(n)||this.publishFailure(n)}handleEngineSocketClose(e){let t=this.snapshot.engineToken,n=this.extractEngineSocketCloseToken(e.values);if(!t||!n||t!==n){this.logger.debug(`ignore EngineSocketClose for non-current session`,{currentToken:t,closedToken:n});return}let r=new Y(J.CenterDisconnected,e.message??`Engine socket closed`,!0,e);this.emitLoadingProgress(g.EngineClose,`EngineClose`),this.handleCenterInterruption(r)}handleTokenWillExpired(e){this.logger.warn(`token will expire soon`,{message:e.message??``}),this.emitTokenWillExpireProgress(e.message??``)}expectMessage(e){this.expectedCenterFn=e}isExpecting(e){return this.expectedCenterFn===e&&this.hasActiveRunningFlow()}advanceOperation(){return this.nextOperationId+=1,this.nextOperationId}isCurrentOperation(e){return this.runningFlow?.operationId===e}setPhase(e,t){return this.isCurrentOperation(t)?(this.phase=e,!0):!1}createRunningFlow(e,t=!1){let n=()=>void 0,r=()=>void 0;return{operationId:e,promise:new Promise((e,t)=>{n=e,r=t}),resolve:n,reject:r,stopRequested:!1,resolveOnStop:t}}decorateRunningFlow(e){return e.promise.then(t=>e.stopRequested?e.stopSnapshot??this.getSnapshot():(this.reconnecting=!1,this.events.emit(`connected`,t),t)).catch(t=>{if(e.stopRequested){if(e.resolveOnStop)return e.stopSnapshot??this.getSnapshot();throw Dn(t)}let n=Dn(t);throw this.isCurrentOperation(e.operationId)&&(this.updateSnapshot(`failed`,{lastError:n.toErrorInfo()}),this.events.emit(`failed`,this.getSnapshot())),n}).finally(()=>{if(!this.isCurrentOperation(e.operationId))return;let t=e.stopRequested||this.stopRequested;this.setPhase(this.snapshot.state===`connected`?`connected`:`idle`,e.operationId),this.runningFlow=void 0,this.reconnecting=!1,this.stopRequested=!1,this.flushPendingCenterInterruption(t,e.operationId)})}completeRunningFlow(e,t){if(!this.isCurrentOperation(t)){this.logger.debug(`ignore stale auth flow completion`,{operationId:t});return}let n=this.runningFlow;this.clearRunningContext(t),n?.resolve?.(e),n&&(n.resolve=void 0,n.reject=void 0)}rejectActiveFlow(e,t){let n=Dn(e),r=this.runningFlow;if(!r||t!==void 0&&r.operationId!==t)return this.logger.debug(`ignore stale auth flow failure`,{operationId:t,currentOperationId:r?.operationId,code:n.code,message:n.message}),!1;let i=r.reject;return i?(this.clearRunningContext(r.operationId),r.resolve=void 0,r.reject=void 0,i(n),!0):(this.logger.debug(`ignore auth flow failure without active deferred`,{operationId:r.operationId,code:n.code,message:n.message}),!1)}publishFailure(e){this.updateSnapshot(`failed`,{lastError:e.toErrorInfo()}),this.events.emit(`failed`,this.getSnapshot())}hasActiveRunningFlow(){return!!this.runningFlow?.reject}clearRunningContext(e){e!==void 0&&!this.isCurrentOperation(e)||(this.expectedCenterFn=void 0,this.connectResult=void 0,this.serviceInfo=void 0)}isWaitingMessage(e){return[`坐席已满`,`服务已满`,`排队`,`没有服务资源`,`资源`].some(t=>e.includes(t))}parseValues(e){if(!e.values)return{};try{return JSON.parse(e.values)}catch(t){throw new Y(J.CenterProtocolInvalid,`Invalid center values json for ${e.fn}`,!1,{envelope:e,cause:t instanceof Error?t.message:String(t)})}}tryParseValues(e){if(e.values)try{return JSON.parse(e.values)}catch(t){this.logger.warn(`center values parse failed, fallback to empty payload`,{fn:e.fn,cause:t instanceof Error?t.message:String(t)});return}}extractEngineSocketCloseToken(e){if(!e)return;let t=e.trim();if(t){try{let e=JSON.parse(t);if(typeof e==`string`)return e;if(e&&typeof e.token==`string`&&e.token.trim().length>0)return e.token}catch{}return t}}handleCenterInterruption(e){let t=this.decideCenterInterruption();switch(t.kind){case`ignore`:return;case`reject`:this.rejectActiveFlow(e,t.operationId);return;case`defer`:this.deferCenterInterruption(e,t.operationId);return;case`recover`:this.recoverFromCenterInterruption(e);return}}decideCenterInterruption(){if(this.isTerminalSnapshot())return{kind:`ignore`};let e=this.runningFlow;return e?this.phase===`settling`?{kind:`defer`,operationId:e.operationId}:this.hasActiveRunningFlow()?{kind:`reject`,operationId:e.operationId}:{kind:`defer`,operationId:e.operationId}:{kind:`recover`}}isTerminalSnapshot(){return this.isTerminalSnapshotState(this.snapshot.state)}deferCenterInterruption(e,t){if(this.isCurrentOperation(t)){if(this.pendingCenterInterruption){this.logger.debug(`center interruption already deferred during flow settlement`,{currentCode:this.pendingCenterInterruption.error.code,incomingCode:e.code});return}this.pendingCenterInterruption={operationId:t,error:e},this.logger.debug(`defer center interruption until current flow settles`,{operationId:t,code:e.code,message:e.message})}}flushPendingCenterInterruption(e,t){let n=this.pendingCenterInterruption;if(!(!n||n.operationId!==t)){if(this.pendingCenterInterruption=void 0,e||this.snapshot.state===`idle`||this.snapshot.state===`failed`||this.runningFlow){this.logger.debug(`drop deferred center interruption`,{skip:e,state:this.snapshot.state,code:n.error.code,operationId:t});return}this.recoverFromCenterInterruption(n.error)}}recoverFromWebRtcDisconnection(){let e=this.snapshot.state;if(this.shouldIgnoreWebRtcDisconnection(e)){this.logger.debug(`ignore WebRTC disconnection for current workflow state`,{stopRequested:this.stopRequested,reconnecting:this.reconnecting,hasRunningPromise:!!this.runningFlow,state:e});return}this.logger.warn(`WebRTC disconnected, reconnect signalling`,{state:e}),this.reconnectSignalling().catch(e=>{let t=Dn(e);this.publishFailure(t)})}shouldIgnoreWebRtcDisconnection(e){return this.stopRequested||this.reconnecting||!!this.runningFlow||this.isTerminalSnapshotState(e)}isTerminalSnapshotState(e){return e===`idle`||e===`failed`}recoverFromCenterInterruption(e){this.logger.warn(`center interruption detected, start reconnect`,{state:this.snapshot.state,code:e.code,message:e.message}),this.emitCenterEvent(`UnConnect`,{code:e.code,message:e.message}),this.emitLoadingProgress(g.SerriceError,`SerriceError`),this.reconnect().catch(e=>{let t=Dn(e);this.publishFailure(t)})}updateSnapshot(e,t){this.snapshot={...this.snapshot,...t,state:e,reconnecting:this.reconnecting||this.session.isReconnecting(),updatedAt:Date.now()},this.events.emit(`stateChanged`,this.getSnapshot())}emitLoadingProgress(e,t,n=!0){this.events.emit(`progress`,{kind:`loading`,message:e,key:t,isClose:n})}emitTokenWillExpireProgress(e,t=!0){this.events.emit(`progress`,{kind:`tokenWillExpire`,message:e,key:`TokenWillExpired`,isClose:t})}emitCenterEvent(e,t){this.events.emit(`centerEvent`,{eventName:e,payload:t})}emitWaitingProgress(e){if(this.config.viewMode!==`cs`){if(e.includes(`云渲染服务坐席已满`)||e.includes(`坐席已满`)||e.includes(`当前服务已满`)){this.emitLoadingProgress(e,`EngineWaiting`);return}e.includes(`没有服务资源`)&&this.emitLoadingProgress(g.SerriceUnAvaible,`SerriceUnAvaible`)}}};function Nn(e){return typeof e==`object`&&!!e}var Pn=class{constructor(e,t=m,n={}){this.session=e,this.logger=t,this.hooks=n,this.pending=new Map,this.listenerName=`enginesdk3_response_listener`,this.disconnectEvents=[`webRtcDisconnected`,`webRtcFailed`],this.onResponse=this.handleResponse.bind(this),this.onSessionDisconnected=()=>{this.cleanupPendingOnDisconnect()},this.logger.debug(`register response listener`,{listenerName:this.listenerName}),this.session.addResponseEventListener(this.listenerName,this.onResponse),this.disconnectEvents.forEach(e=>{this.session.addEventListener(e,this.onSessionDisconnected)})}sendRequest(e,t,n){let{requestId:r,envelope:i}=this.createRequestEnvelope(e,t,n),a,o,s=new Promise((e,t)=>{a=e,o=t}),c={mode:`single`,module:e,method:t,sentAt:Date.now(),resolve:a,reject:o};this.pending.set(r,c);let l=this.sendPendingRequest(r,i,c);return l&&this.settlePendingFailure(r,c,l),s}sendStreamRequest(e,t,n,r){let{requestId:i,envelope:a}=this.createRequestEnvelope(e,t,n),o=r??(()=>void 0),s,c,l=new Promise((e,t)=>{s=e,c=t});Object.defineProperty(l,"requestId",{value:i,enumerable:!0}),l.cancel=e=>{this.cancelStreamRequest(i,e)};let u={mode:`stream`,module:e,method:t,sentAt:Date.now(),callback:o,isDone:e=>this.defaultStreamDonePredicate(e),resolve:s,reject:e=>c(e)};this.pending.set(i,u);let d=this.sendPendingRequest(i,a,u);return d&&this.settlePendingFailure(i,u,d,{notifyStream:!0}),l}sendPendingRequest(e,t,n){if(this.logger.debug(`emit ${n.mode} request`,{requestId:e,module:n.module,method:n.method}),!this.session.emitUIInteraction(t)){let t=Error(`Failed to send ${n.mode} request: ${n.module}.${n.method}`);return this.logger.error(`emit request failed`,{requestId:e,module:n.module,method:n.method}),t}this.hooks.onRequestSent?.({requestId:e,module:n.module,method:n.method})}settlePendingFailure(e,t,n,r={}){this.pending.get(e)===t&&(this.pending.delete(e),t.mode===`stream`&&r.notifyStream&&this.emitStreamCallback(t,{type:`error`,requestId:e,response:r.response,error:n}),t.reject(n))}handleResponse(e){let t;try{t=JSON.parse(e)}catch(e){this.logger.warn(`response parse failed`,{error:p(e)});return}let n=t.requestId??t.uuid;if(!n){this.logger.warn(`response missing requestId`);return}t.requestId=n,t.param!==void 0&&t.params===void 0&&(t.params=t.param);let r=this.pending.get(n);if(!r){this.logger.debug(`response ignored, no pending request`,{requestId:n});return}if(r.mode===`single`){this.pending.delete(n),this.resolveSingleResponse(t,r);return}this.resolveStreamResponse(t,r)}createRequestEnvelope(e,t,n){let r=`r_${Date.now()}_${Math.random().toString(16).slice(2,10)}`;return{requestId:r,envelope:{AssemblyName:`EngineApi`,fn:r,ClassName:e,FunctionName:t,Value:JSON.stringify(n),ts:Date.now()}}}defaultStreamDonePredicate(e){if(typeof e.code==`string`){let t=e.code.trim().toUpperCase();if(t===`DONE`||t===`STREAM_DONE`)return!0}return!!this.hasDoneFlag(e)}hasDoneFlag(e){return[e,e.data].some(e=>Nn(e)?e.done===!0||e.isEnd===!0:!1)}resolveSingleResponse(e,t){if(e.success||!e.success&&e.errorMsg!=null){this.emitResponseReceivedHook(e,t),this.logger.info(`response success`,{requestId:e.requestId,code:e.code}),t.resolve(e);return}this.logger.warn(`response failed`,{requestId:e.requestId,code:``,message:e.errorMsg}),t.reject(Error(` ${e.errorMsg}`))}resolveStreamResponse(e,t){if(!e.success){let n=Error(` ${e.errorMsg??e.message}`);this.logger.warn(`stream response failed`,{requestId:e.requestId,code:e.code,message:e.errorMsg??e.message}),this.settlePendingFailure(e.requestId,t,n,{response:e,notifyStream:!0});return}if(this.emitResponseReceivedHook(e,t),t.isDone(e)){this.pending.delete(e.requestId);let n=this.emitStreamCallback(t,this.createStreamResponseEvent(`done`,e));if(n){t.reject(n);return}this.logger.info(`stream request done`,{requestId:e.requestId,code:e.code}),t.resolve(e);return}let n=this.emitStreamCallback(t,this.createStreamResponseEvent(`data`,e));n&&this.settlePendingFailure(e.requestId,t,n)}createStreamResponseEvent(e,t){return{...t,type:e,requestId:t.requestId,response:t,data:t.data,params:t.params,param:t.params??t.param,errorMsg:t.errorMsg}}emitResponseReceivedHook(e,t){this.hooks.onResponseReceived?.({requestId:e.requestId,module:t.module,method:t.method,durationMs:Math.max(0,Date.now()-t.sentAt),code:e.code})}emitStreamCallback(e,t){try{e.callback(t);return}catch(e){let n=e instanceof Error?e:Error(String(e));return this.logger.warn(`stream callback failed`,{requestId:t.requestId,type:t.type,error:n.message}),n}}cancelStreamRequest(e,t){let n=this.pending.get(e);if(!n||n.mode!==`stream`)return;this.pending.delete(e);let r=t?.trim()||`Stream request cancelled by client`,i=Error(r);this.logger.info(`stream request cancelled`,{requestId:e,module:n.module,method:n.method}),this.emitStreamCallback(n,{type:`cancel`,requestId:e,error:i}),n.reject(i)}cleanupPendingOnDisconnect(){if(this.pending.size===0)return;let e=Error(`Session disconnected before request completed`);this.pending.forEach((t,n)=>{t.mode===`single`||this.emitStreamCallback(t,{type:`error`,requestId:n,error:e}),t.reject(e),this.logger.warn(`pending request cleared on disconnect`,{requestId:n,mode:t.mode})}),this.pending.clear()}};function Fn(e){return typeof e==`object`&&!!e}function X(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function In(e){if(!Fn(e))return;let t=e.data;if(!Fn(t))return;let n=t.aggregatedStats;if(Fn(n))return n}function Ln(e,t,n){if(e===void 0||t===void 0)return{packetLossRate:void 0,next:n};let r={packetsLost:e,packetsReceived:t};if(!n)return{packetLossRate:void 0,next:r};let i=e-n.packetsLost,a=t-n.packetsReceived;if(i<0||a<0)return{packetLossRate:void 0,next:r};let o=i+a;if(o<=0)return{packetLossRate:void 0,next:r};let s=i/o;return{packetLossRate:Math.max(0,Math.min(1,s)),next:r}}function Rn(e){let t=e.getActiveCandidatePair;if(typeof t!=`function`)return;let n=t.call(e);if(!Fn(n))return;let r=X(n.currentRoundTripTime);return r===void 0?void 0:r*1e3}function zn(e,t){let n=In(e);if(!n)return;let r=Fn(n.inboundVideoStats)?n.inboundVideoStats:{},i=X(r.bitrate),a=Ln(X(r.packetsLost),X(r.packetsReceived),t);return{aggregatedStats:n,inboundVideoStats:r,metrics:{fps:X(r.framesPerSecond),bitrateKbps:i===void 0?void 0:i/1e3,packetLossRate:a.packetLossRate,jitterMs:(()=>{let e=X(r.jitter);return e===void 0?void 0:e*1e3})(),rttMs:Rn(n),frameWidth:X(r.frameWidth),frameHeight:X(r.frameHeight)},packetCounters:a.next}}function Bn(){return{CameraHeight:`-`,FPS:`-`,Width:`-`,Height:`-`,runTime:`-`,bytePerSecond:`-`,lostPacketsRate:`-`,delayTime:`-`,Codec:`-`}}function Vn(e){if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e)}function Hn(e){if(e<=0||!Number.isFinite(e))return`00:00:00`;let t=Math.floor(e/1e3);return[Math.floor(t/3600),Math.floor(t%3600/60),t%60].map(e=>String(e).padStart(2,`0`)).join(`:`)}var Un=class{constructor(e,t,n=m,r){this.session=e,this.onStatus=t,this.logger=n,this.onSample=r,this.connected=!1,this.status=Bn(),this.onWebRtcConnected=()=>{this.connected=!0,this.firstStatsTimestampMs=void 0,this.lastStatsTimestamp=void 0,this.packetCounters=void 0,this.logger.info(`engine status collector started`)},this.onWebRtcDisconnected=()=>{this.pause(`webRtcDisconnected`)},this.onWebRtcFailed=()=>{this.pause(`webRtcFailed`)},this.onWebRtcConnecting=()=>{this.pause(`webRtcConnecting`)},this.onStatsReceived=e=>{if(!this.connected)return;let t=zn(e,this.packetCounters);t&&(this.packetCounters=t.packetCounters,this.status=this.patchByStats(this.status,t),this.onSample?.(this.extractMediaSample(t)),this.emit())},this.session.addEventListener(`webRtcConnected`,this.onWebRtcConnected),this.session.addEventListener(`webRtcDisconnected`,this.onWebRtcDisconnected),this.session.addEventListener(`webRtcFailed`,this.onWebRtcFailed),this.session.addEventListener(`webRtcConnecting`,this.onWebRtcConnecting),this.session.addEventListener(`statsReceived`,this.onStatsReceived)}stop(){this.pause(`manualStop`)}dispose(){this.stop(),this.session.removeEventListener(`webRtcConnected`,this.onWebRtcConnected),this.session.removeEventListener(`webRtcDisconnected`,this.onWebRtcDisconnected),this.session.removeEventListener(`webRtcFailed`,this.onWebRtcFailed),this.session.removeEventListener(`webRtcConnecting`,this.onWebRtcConnecting),this.session.removeEventListener(`statsReceived`,this.onStatsReceived)}pause(e){this.connected&&(this.connected=!1,this.lastStatsTimestamp=void 0,this.packetCounters=void 0,this.logger.info(`engine status collector paused`,{reason:e}))}patchByStats(e,t){let n=t.aggregatedStats,r=t.inboundVideoStats,i={...e},a=t.metrics.frameWidth;a!==void 0&&(i.Width=String(a));let o=t.metrics.frameHeight;o!==void 0&&(i.Height=String(o));let s=t.metrics.fps;s!==void 0&&(i.FPS=String(s));let c=t.metrics.bitrateKbps;c!==void 0&&(i.bytePerSecond=`${Math.round(c)} kb/s`),i.lostPacketsRate=t.metrics.packetLossRate===void 0?`-`:`${(t.metrics.packetLossRate*100).toFixed(2)}%`;let l=X(r.timestamp);if(l!==void 0){if(this.lastStatsTimestamp!==void 0){let e=l-this.lastStatsTimestamp;i.delayTime=`${Math.max(0,1e3-e).toFixed(2)} ms`}this.lastStatsTimestamp=l}this.firstStatsTimestampMs===void 0&&(this.firstStatsTimestampMs=Date.now()),i.runTime=Vn(n.sessionStats?.runTime)??Hn(Date.now()-this.firstStatsTimestampMs);let u=Vn(r.codecId),d=u?this.getCodecMimeType(n,u):void 0;return d&&(i.Codec=d),i}extractMediaSample(e){return{...e.metrics,bitrateKbps:e.metrics.bitrateKbps===void 0?void 0:Math.round(e.metrics.bitrateKbps)}}getCodecMimeType(e,t){let n=e.codecs;if(!n)return;let r;(n instanceof Map||typeof n.get==`function`)&&(r=n.get(t));let i=r?.mimeType;return typeof i==`string`&&i.length>0?i:void 0}emit(){this.onStatus({...this.status})}};const Wn=[`Normal`,`Mild`,`Moderate`,`Severe`];function Gn(e){return Wn.indexOf(e)}function Kn(e,t){return Gn(e)>=Gn(t)?e:t}function qn(e,t){let n=Gn(t);return e.filter(e=>Gn(e)>=n).length}function Jn(e){return e===`Severe`?`Moderate`:e===`Moderate`?`Mild`:`Normal`}function Yn(e){return e===void 0?`Normal`:e>=.1?`Severe`:e>=.06?`Moderate`:e>=.03?`Mild`:`Normal`}function Xn(e){return e===void 0?`Normal`:e>=240?`Severe`:e>=180?`Moderate`:e>=120?`Mild`:`Normal`}function Zn(e){return e===void 0?`Normal`:e>=80?`Severe`:e>=50?`Moderate`:e>=25?`Mild`:`Normal`}function Qn(e){return e===void 0?`Normal`:e<=12?`Severe`:e<=20?`Moderate`:e<=28?`Mild`:`Normal`}function $n(e){let t=Yn(e.packetLossRate),n=Kn(Xn(e.rttMs),Zn(e.jitterMs)),r=[t,n,Qn(e.fps)],i=[t,n];return r.some(e=>e===`Severe`)?`Severe`:qn(r,`Moderate`)>=2||qn(i,`Moderate`)>=1&&qn(r,`Mild`)>=2?`Moderate`:qn(r,`Mild`)>=2||qn(i,`Moderate`)>=1?`Mild`:`Normal`}function Z(e,t,n,r,i=e){return{measuredLevel:t,outcome:n,reason:r,degradeStreak:i.degradeStreak,recoverStreak:i.recoverStreak}}const er=[{evaluate(e,t){if(!(e.connected&&e.metrics.connected))return Z(e,t,`hold`,`session not connected, skip adaptation`)}},{evaluate(e,t){if(e.actionInFlight)return Z(e,t,`hold`,`action in flight`)}},{evaluate(e,t){if(!(e.now>=e.cooldownUntil))return Z(e,t,`skip_cooldown`,`cooldown until ${e.cooldownUntil}`)}},{evaluate(e,t){if(Gn(t)<=Gn(e.stableLevel))return;let n=e.degradeStreak+1,r=t===`Severe`?1:2;return n<r?Z(e,t,`skip_hysteresis`,`degrade streak ${n}/${r}`,{degradeStreak:n,recoverStreak:0}):{measuredLevel:t,outcome:`downgrade`,targetLevel:t,reason:`measured ${t}`,degradeStreak:0,recoverStreak:0}}},{evaluate(e,t){if(t!==`Normal`||e.stableLevel===`Normal`)return;let n=e.recoverStreak+1;if(n<4)return Z(e,t,`skip_hysteresis`,`recover streak ${n}/4`,{degradeStreak:0,recoverStreak:n});let r=Jn(e.stableLevel);return{measuredLevel:t,outcome:`recover`,targetLevel:r,reason:`recover to ${r}`,degradeStreak:0,recoverStreak:0}}},{evaluate(e,t){return Z(e,t,`hold`,`no transition`,{degradeStreak:0,recoverStreak:t===`Normal`?e.recoverStreak:0})}}];function tr(e){let t=$n(e.metrics);for(let n of er){let r=n.evaluate(e,t);if(r)return r}return Z(e,t,`hold`,`no transition`)}const nr={Normal:{bitrate:12e6,fps:60,width:1920,height:1080},Mild:{bitrate:8e6,fps:45,width:1600,height:900},Moderate:{bitrate:4e6,fps:30,width:1280,height:720},Severe:{bitrate:2e6,fps:20,width:960,height:540}};function Q(e){let t=e.filter(e=>typeof e==`number`&&Number.isFinite(e));if(t.length!==0)return t.reduce((e,t)=>e+t,0)/t.length}var rr=class{constructor(e){this.metricsWindow=[],this.traces=[],this.connected=!1,this.mode=`auto`,this.currentLevel=`Normal`,this.stableLevel=`Normal`,this.diagnosticsVisible=!1,this.degradeStreak=0,this.recoverStreak=0,this.cooldownUntil=0,this.actionInFlight=!1,this.lastAppliedProfileKey=``,this.transitionGeneration=0,this.onStatsReceived=e=>{this.handleStatsReceived(e)},this.onWebRtcConnected=()=>{this.connected=!0,this.metricsWindow.length=0,this.degradeStreak=0,this.recoverStreak=0,this.cooldownUntil=0,this.actionInFlight=!1,this.packetCounters=void 0,this.lastMetrics=void 0,this.currentLevel=`Normal`,this.stableLevel=`Normal`,this.lastAppliedProfileKey=``,this.transitionGeneration+=1,this.logger.info(`network adaptation received webRtcConnected`),this.pushTrace({outcome:`hold`,reason:`webrtc connected, resume adaptation`}),this.emitDiagnosticsSnapshot()},this.onWebRtcConnecting=()=>{this.handleConnectionInterrupted(`webRtcConnecting`)},this.onWebRtcDisconnected=()=>{this.handleConnectionInterrupted(`webRtcDisconnected`)},this.onWebRtcFailed=()=>{this.handleConnectionInterrupted(`webRtcFailed`)},this.session=e.session,this.screen=e.screen,this.logger=e.logger??m,this.onStateChange=e.onStateChange,this.onAction=e.onAction,this.onDiagnostics=e.onDiagnostics}start(){this.session.addEventListener(`statsReceived`,this.onStatsReceived),this.session.addEventListener(`webRtcConnected`,this.onWebRtcConnected),this.session.addEventListener(`webRtcConnecting`,this.onWebRtcConnecting),this.session.addEventListener(`webRtcDisconnected`,this.onWebRtcDisconnected),this.session.addEventListener(`webRtcFailed`,this.onWebRtcFailed)}dispose(){this.session.removeEventListener(`statsReceived`,this.onStatsReceived),this.session.removeEventListener(`webRtcConnected`,this.onWebRtcConnected),this.session.removeEventListener(`webRtcConnecting`,this.onWebRtcConnecting),this.session.removeEventListener(`webRtcDisconnected`,this.onWebRtcDisconnected),this.session.removeEventListener(`webRtcFailed`,this.onWebRtcFailed)}setMode(e){this.mode!==e&&(this.mode=e,this.pushTrace({outcome:`manual`,reason:`mode switched to ${e}`}),this.emitDiagnosticsSnapshot(),e===`auto`&&this.lastMetrics&&this.evaluateAutoStrategy(this.lastMetrics))}setManualLevel(e){this.setMode(`manual`),this.transitionToLevel(e,`manual`,`manual override to ${e}`,!0)}setDiagnosticsVisible(e){this.diagnosticsVisible=e,this.emitDiagnosticsSnapshot()}getDiagnosticsSnapshot(){return{ts:Date.now(),visible:this.diagnosticsVisible,mode:this.mode,currentLevel:this.currentLevel,connected:this.connected,lastMetrics:this.lastMetrics,lastAction:this.lastAction,traces:[...this.traces]}}handleStatsReceived(e){let t=zn(e,this.packetCounters);if(!t)return;this.packetCounters=t.packetCounters;let n={ts:Date.now(),connected:this.connected,...t.metrics};this.lastMetrics=this.pushMetrics(n),this.emitDiagnosticsSnapshot(),this.mode!==`manual`&&this.evaluateAutoStrategy(this.lastMetrics)}handleConnectionInterrupted(e){this.connected=!1,this.logger.warn(`network adaptation connection interrupted`,{source:e}),this.metricsWindow.length=0,this.recoverStreak=0,this.degradeStreak=0,this.cooldownUntil=0,this.actionInFlight=!1,this.packetCounters=void 0,this.transitionGeneration+=1,this.pushTrace({outcome:`hold`,reason:`${e}; session disconnected, pause adaptation`}),this.emitDiagnosticsSnapshot()}pushMetrics(e){return this.metricsWindow.push(e),this.metricsWindow.length>5&&this.metricsWindow.shift(),{ts:e.ts,connected:e.connected,fps:Q(this.metricsWindow.map(e=>e.fps)),bitrateKbps:Q(this.metricsWindow.map(e=>e.bitrateKbps)),packetLossRate:Q(this.metricsWindow.map(e=>e.packetLossRate)),jitterMs:Q(this.metricsWindow.map(e=>e.jitterMs)),rttMs:Q(this.metricsWindow.map(e=>e.rttMs)),frameWidth:Q(this.metricsWindow.map(e=>e.frameWidth)),frameHeight:Q(this.metricsWindow.map(e=>e.frameHeight))}}evaluateAutoStrategy(e){let t=tr({connected:this.connected,metrics:e,currentLevel:this.currentLevel,stableLevel:this.stableLevel,mode:this.mode,actionInFlight:this.actionInFlight,cooldownUntil:this.cooldownUntil,now:Date.now(),degradeStreak:this.degradeStreak,recoverStreak:this.recoverStreak});this.applyStrategyDecision(t,e)}applyStrategyDecision(e,t){if(this.degradeStreak=e.degradeStreak,this.recoverStreak=e.recoverStreak,e.outcome===`downgrade`||e.outcome===`recover`){this.transitionToLevel(e.targetLevel??e.measuredLevel,e.outcome,e.reason,!1,t);return}this.pushTrace({measuredLevel:e.measuredLevel,currentLevel:this.currentLevel,mode:this.mode,metrics:t,outcome:e.outcome,reason:e.reason})}transitionToLevel(e,t,n,r,i=this.lastMetrics){if(console.log(`transitionToLevel`,e,t,n,r,i),!r&&e===this.stableLevel){this.pushTrace({measuredLevel:$n(i??{ts:Date.now(),connected:!1}),currentLevel:this.currentLevel,mode:this.mode,metrics:i,outcome:`hold`,reason:`target level equals current level`});return}let a=this.transitionGeneration;this.actionInFlight=!0,this.runTransition(e,t,n,a,i).finally(()=>{a===this.transitionGeneration&&(this.actionInFlight=!1)})}async runTransition(e,t,n,r,i=this.lastMetrics){if(r!==this.transitionGeneration){this.logger.info(`network adaptation transition ignored before start`,{targetLevel:e,reason:n});return}let a=this.currentLevel,o=this.stableLevel,s=$n(i??{ts:Date.now(),connected:!1});t===`recover`&&this.currentLevel!==`Recovering`&&(this.currentLevel=`Recovering`,this.onStateChange?.({from:a,to:`Recovering`,mode:this.mode,reason:`enter recovering before ${e}`,ts:Date.now(),metrics:i}));let c=await this.applyLevelProfile(e,n);if(r!==this.transitionGeneration){this.logger.info(`network adaptation transition discarded after action (stale generation)`,{targetLevel:e,reason:n}),this.pushTrace({measuredLevel:s,currentLevel:this.currentLevel,mode:this.mode,targetLevel:e,metrics:i,outcome:`hold`,reason:`${n}; stale transition discarded`}),this.emitDiagnosticsSnapshot();return}if(this.lastAction=c,this.onAction?.(c),!c.success){this.logger.warn(`network adaptation transition not committed due to action failure`,{targetLevel:e,reason:n});let t=this.currentLevel;this.currentLevel=o,t!==this.currentLevel&&this.onStateChange?.({from:t,to:this.currentLevel,mode:this.mode,reason:`${n}; action failed rollback`,ts:Date.now(),metrics:i}),this.pushTrace({measuredLevel:s,currentLevel:t,mode:this.mode,targetLevel:e,metrics:i,outcome:`hold`,reason:`${n}; action failed, keep ${o}`}),this.emitDiagnosticsSnapshot();return}let l=this.currentLevel;this.stableLevel=e,this.currentLevel=e,this.cooldownUntil=Date.now()+6e3,this.onStateChange?.({from:l,to:e,mode:this.mode,reason:n,ts:Date.now(),metrics:i}),this.pushTrace({measuredLevel:s,currentLevel:l,mode:this.mode,targetLevel:e,metrics:i,outcome:t,reason:n}),this.emitDiagnosticsSnapshot()}async applyLevelProfile(e,t){let n=nr[e],r=`${n.bitrate}-${n.fps}-${n.width}x${n.height}`;if(r===this.lastAppliedProfileKey)return{level:e,mode:this.mode,success:!0,skipped:!0,reason:`${t}; profile already applied`,ts:Date.now(),steps:[]};let i=[];i.push(await this.runActionStep(`SetSceneRenderBitrate`,{bitrate:n.bitrate})),i.push(await this.runActionStep(`SetSceneFPS`,{fps:n.fps})),i.push(await this.runActionStep(`SetScreenResolution`,{width:n.width,height:n.height}));let a=i.every(e=>e.success);return a&&(this.lastAppliedProfileKey=r),{level:e,mode:this.mode,success:a,skipped:!1,reason:t,ts:Date.now(),steps:i}}async runActionStep(e,t){try{return this.logger.info(`network adaptation action success`,{type:e,payload:t}),{type:e,payload:t,success:!0}}catch(n){let r=n instanceof Error?n.message:String(n);return this.logger.warn(`network adaptation action failed`,{type:e,payload:t,error:r}),{type:e,payload:t,success:!1,error:r}}}pushTrace(e){let t={ts:Date.now(),mode:e.mode??this.mode,currentLevel:e.currentLevel??this.currentLevel,measuredLevel:e.measuredLevel??$n(this.lastMetrics??{ts:Date.now(),connected:this.connected}),targetLevel:e.targetLevel,outcome:e.outcome,reason:e.reason,metrics:e.metrics};this.traces.unshift(t),this.traces.length>30&&(this.traces.length=30),this.emitDiagnosticsSnapshot()}emitDiagnosticsSnapshot(){this.onDiagnostics?.(this.getDiagnosticsSnapshot())}},ir=class{constructor(e){this.visible=!1,this.onKeyDown=e=>{e.ctrlKey&&e.altKey&&e.code===`KeyD`&&(e.preventDefault(),this.toggle())},this.options=e,this.logger=e.logger??m,typeof window<`u`&&window.addEventListener(`keydown`,this.onKeyDown)}dispose(){typeof window<`u`&&window.removeEventListener(`keydown`,this.onKeyDown),this.root?.remove(),this.root=void 0}update(e){this.snapshot=e,this.visible&&(this.ensureRoot(),this.render())}setVisible(e){this.visible!==e&&(this.visible=e,this.ensureRoot(),this.root&&(this.root.style.display=e?`block`:`none`),e&&this.render(),this.options.onVisibilityChange?.(e))}toggle(){this.setVisible(!this.visible)}ensureRoot(){if(this.root||typeof document>`u`||!document.body)return;let e=document.createElement(`div`);e.id=`enginesdk3-network-diagnostics-panel`,e.style.position=`fixed`,e.style.right=`16px`,e.style.bottom=`16px`,e.style.zIndex=`2147483647`,e.style.width=`360px`,e.style.maxWidth=`calc(100vw - 32px)`,e.style.maxHeight=`70vh`,e.style.overflow=`auto`,e.style.padding=`12px`,e.style.borderRadius=`8px`,e.style.boxShadow=`0 6px 24px rgba(0, 0, 0, 0.35)`,e.style.background=`rgba(12, 17, 24, 0.94)`,e.style.color=`#e8f0ff`,e.style.fontFamily=`Menlo, Consolas, Monaco, monospace`,e.style.fontSize=`12px`,e.style.lineHeight=`1.4`,e.style.display=this.visible?`block`:`none`;let t=document.createElement(`div`);t.style.display=`flex`,t.style.justifyContent=`space-between`,t.style.alignItems=`center`,t.style.marginBottom=`8px`;let n=document.createElement(`strong`);n.textContent=`Network Diagnostics`,t.appendChild(n),this.levelLabel=document.createElement(`span`),this.levelLabel.style.color=`#7ee787`,this.levelLabel.textContent=`Normal`,t.appendChild(this.levelLabel),e.appendChild(t);let r=document.createElement(`div`);r.style.display=`flex`,r.style.alignItems=`center`,r.style.gap=`8px`,r.style.marginBottom=`8px`;let i=document.createElement(`span`);i.textContent=`Mode`,r.appendChild(i),this.modeSelect=document.createElement(`select`),this.modeSelect.style.flex=`1`,this.modeSelect.innerHTML=`<option value="auto">Auto</option><option value="manual">Manual</option>`,this.modeSelect.onchange=()=>{let e=this.modeSelect?.value===`manual`?`manual`:`auto`;this.options.onModeChange(e)},r.appendChild(this.modeSelect),e.appendChild(r);let a=document.createElement(`div`);a.style.display=`flex`,a.style.alignItems=`center`,a.style.gap=`8px`,a.style.marginBottom=`8px`;let o=document.createElement(`span`);o.textContent=`Manual Level`,a.appendChild(o),this.levelSelect=document.createElement(`select`),this.levelSelect.style.flex=`1`,this.levelSelect.innerHTML=[`<option value="Normal">Normal</option>`,`<option value="Mild">Mild</option>`,`<option value="Moderate">Moderate</option>`,`<option value="Severe">Severe</option>`].join(``),this.levelSelect.onchange=()=>{let e=this.levelSelect?.value??`Normal`;this.options.onManualLevelChange(e)},a.appendChild(this.levelSelect),e.appendChild(a),this.metricsPre=document.createElement(`pre`),this.metricsPre.style.margin=`0 0 8px 0`,this.metricsPre.style.padding=`8px`,this.metricsPre.style.background=`rgba(255, 255, 255, 0.06)`,this.metricsPre.style.borderRadius=`6px`,this.metricsPre.style.whiteSpace=`pre-wrap`,this.metricsPre.style.wordBreak=`break-word`,e.appendChild(this.metricsPre);let s=document.createElement(`div`);s.style.marginBottom=`6px`,s.textContent=`Recent Decisions`,e.appendChild(s),this.traceList=document.createElement(`div`),this.traceList.style.display=`flex`,this.traceList.style.flexDirection=`column`,this.traceList.style.gap=`4px`,e.appendChild(this.traceList),document.body.appendChild(e),this.root=e,this.logger.info(`network diagnostics panel ready`)}render(){!this.root||!this.snapshot||(this.levelLabel&&(this.levelLabel.textContent=this.snapshot.currentLevel,this.levelLabel.style.color=this.snapshot.currentLevel===`Severe`?`#ff7b72`:`#7ee787`),this.modeSelect&&(this.modeSelect.value=this.snapshot.mode),this.levelSelect&&(this.levelSelect.disabled=this.snapshot.mode!==`manual`),this.metricsPre&&(this.metricsPre.textContent=this.buildMetricsText(this.snapshot)),this.traceList&&(this.traceList.innerHTML=``,this.snapshot.traces.slice(0,10).forEach(e=>{let t=document.createElement(`div`);t.style.padding=`6px`,t.style.borderRadius=`6px`,t.style.background=`rgba(255, 255, 255, 0.04)`,t.textContent=`${new Date(e.ts).toLocaleTimeString()} | ${e.outcome} | ${e.reason}`,this.traceList?.appendChild(t)})))}buildMetricsText(e){let t=e.lastMetrics;if(!t)return`No metrics yet`;let n=t.packetLossRate===void 0?`-`:`${(t.packetLossRate*100).toFixed(2)}%`;return[`connected: ${e.connected}`,`mode: ${e.mode}`,`level: ${e.currentLevel}`,`fps: ${t.fps?.toFixed(2)??`-`}`,`bitrate(kbps): ${t.bitrateKbps?.toFixed(2)??`-`}`,`packetLoss: ${n}`,`rtt(ms): ${t.rttMs?.toFixed(2)??`-`}`,`jitter(ms): ${t.jitterMs?.toFixed(2)??`-`}`,`resolution: ${t.frameWidth??`-`}x${t.frameHeight??`-`}`,`lastAction: ${e.lastAction?`${e.lastAction.level} (${e.lastAction.success?`ok`:`fail`})`:`-`}`].join(`
|
|
38
|
+
`)}},ar=class{constructor(e){this.disconnected=!1,this.hasEverConnected=!1,this.authWorkflow=e.authWorkflow,this.logger=e.logger}async connect(){if(this.disconnected)throw Error(`Cannot connect after disconnect. Use restart() instead.`);this.logger.info(`Starting connection flow`);try{let e=await this.authWorkflow.start();return this.logger.info(`Connection established`,{engineToken:e.engineToken?.substring(0,16)+`...`}),e}catch(e){throw this.logger.error(`Connection failed`,{error:e}),e}}async disconnect(){return this.disconnected?(this.logger.info(`Already disconnected, skipping`),this.disconnectPromise||Promise.resolve()):(this.logger.info(`Disconnecting...`),this.disconnected=!0,this.disconnectPromise=(async()=>{try{await this.authWorkflow.disconnectAndWait(),this.logger.info(`Disconnected successfully`)}catch(e){throw this.logger.error(`Error during disconnect`,{error:e}),e}})(),this.disconnectPromise)}async prepareConnectAfterDisconnect(){this.disconnectPromise&&await this.disconnectPromise,this.disconnected=!1,this.disconnectPromise=void 0,this.hasEverConnected=!1}async restart(){return this.logger.info(`Restarting connection...`),await this.disconnect(),await this.prepareConnectAfterDisconnect(),this.connect()}getStatus(){return{disconnected:this.disconnected,hasEverConnected:this.hasEverConnected}}hasConnectedBefore(){return this.hasEverConnected}markConnected(){this.hasEverConnected=!0}},$=class extends Error{constructor(e,t,n,r){super(t),this.code=e,this.moduleName=n,this.dependencyName=r,this.name=`ApiRegistryError`}};function or(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function sr(e,t){return or(e)&&typeof e[t]==`function`}function cr(e){if(!or(e))throw new $(`CONTEXT_INVALID`,`API registry context must be an object`);let t=[[`bridge`,e.bridge,`sendRequest`],[`authWorkflow`,e.authWorkflow,`getSnapshot`],[`connectionLifecycle`,e.connectionLifecycle,`connect`],[`createLogger`,e.createLogger,void 0]];for(let[e,n,r]of t)if(!(r?sr(n,r):typeof n==`function`||n!=null))throw new $(`CONTEXT_INVALID`,`API registry context dependency '${e}'${r?` with ${r}()`:``} is required`,void 0,e)}function lr(e){if(!or(e))throw new $(`REGISTRY_INVALID`,`API registry must be a non-null object`);let t=Object.keys(e).find(e=>!H.includes(e));if(t)throw new $(`REGISTRY_UNKNOWN_MODULE`,`API registry contains unknown module '${t}'`,t);let n=H.find(t=>!(t in e));if(n)throw new $(`REGISTRY_INCOMPLETE`,`API registry is missing module '${n}'`,n);for(let t of H)if(typeof e[t]!=`function`)throw new $(`FACTORY_INVALID`,`API registry factory for '${t}' must be a function`,t)}function ur(e,t,n,r){let i;try{i=t[r](n)}catch(e){throw new $(`FACTORY_FAILED`,`API registry factory for '${r}' failed: ${e instanceof Error?e.message:String(e)}`,r,void 0)}if(i==null)throw new $(`FACTORY_EMPTY_RESULT`,`API registry factory for '${r}' returned ${i===null?`null`:`undefined`}`,r);e[r]=i}function dr(e,t=mt){if(cr(e),lr(t),typeof t.Popup==`function`&&(e.popupManager===null||e.popupManager===void 0))throw new $(`CONTEXT_INVALID`,`API registry context dependency 'popupManager' is required by the Popup module`,`Popup`,`popupManager`);let n={};return H.forEach(r=>{ur(n,t,e,r)}),n}var fr=class{bind(e){this.lifecycle=e}connect(){return this.getLifecycle().connect()}disconnect(){return this.getLifecycle().disconnect()}reconnect(){return this.getLifecycle().reconnect()}getLifecycle(){if(!this.lifecycle)throw Error(`Connection lifecycle is not bound`);return this.lifecycle}};function pr(e){return`${e}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}var mr=class{withConfig(e){return this.userConfig=e,this}withOptions(e){return this.videoElementParent=e?.videoElementParent,this}build(){if(!this.userConfig)throw Error(`Config must be set via withConfig() before calling build()`);let e=an(this.userConfig),t=pr(`sess`),r=pr(`trace`),i=dn(),a=new bn(i,{sessionId:t,traceId:r,runMode:e.viewMode,viewMode:e.viewMode},{appId:e.sceneName,env:i.app.environment,pageUrl:Yt(),userAgent:Xt()},(e,t)=>{let r=t?` ${JSON.stringify(t)}`:``;n.Warning(`[DTCEngine:QoS] ${e}${r}`.trim())}),o=new ae(e.logger,n,{reporter:a}),s=new xn,c=o.child(`Core`);c.info(`engine init`,{logLevel:o.level,qosReportingEnabled:i.enabled}),a.startSession({engineUuid:e.engineUuid??``});let l=new En(e,e.dom||this.videoElementParent,o.child(`SessionAdapter`)),u=new Mn(e,l,o.child(`AuthWorkflow`)),d=new Pn(l,o.child(`RequestBridge`),{onRequestSent:({requestId:e,module:t,method:n})=>{a.recordEvent({eventName:`ue_request_sent`,stage:`ue_api`,status:`start`,attrs:{requestId:e,apiName:`${t}.${n}`,module:t,method:n}})},onResponseReceived:({requestId:e,module:t,method:n,durationMs:r,code:i})=>{a.recordEvent({eventName:`ue_response_received`,stage:`ue_api`,status:`success`,durationMs:r,attrs:{requestId:e,apiName:`${t}.${n}`,module:t,method:n},metrics:{ueApiRttMs:r,code:i}})}}),f=new ar({authWorkflow:u,logger:o.child(`ConnectionManager`)}),p=new fr,m=new oe({enabled:e.showProgressBar,hostElement:e.dom,emit:e=>{s.emit(`LoadingProgress`,e)},logger:o.child(`LoadingProgress`)}),ee=new Un(l,e=>{s.emit(`EngineStatus`,e)},o.child(`EngineStatus`),e=>{a.recordEvent({eventName:`media_stats_sample`,stage:`media`,status:`update`,metrics:e})}),te=new ot({getEngineConfig:()=>e,on:(e,t)=>s.on(e,t),off:(e,t)=>s.off(e,t)}),ne=dr({bridge:d,authWorkflow:u,connectionLifecycle:p,createLogger:e=>o.child(e),popupManager:te}),re={},h=new rr({session:l,screen:ne.Screen,logger:o.child(`NetworkAdaptation`),onStateChange:e=>{c.info(`network level changed`,e),s.emit(`networkLevelChanged`,e)},onAction:e=>{(e.success?c.info.bind(c):c.warn.bind(c))(`network adaptation action executed`,e),s.emit(`networkActionExecuted`,e)},onDiagnostics:e=>{s.emit(`networkDiagnosticsUpdated`,e),re.current?.update(e)}}),ie=new ir({logger:o.child(`NetworkDiagnosticsPanel`),onModeChange:e=>{c.info(`network mode changed`,{mode:e}),s.emit(`networkModeChanged`,{mode:e}),h.setMode(e)},onManualLevelChange:e=>{c.info(`network manual level set`,{level:e}),h.setManualLevel(e)},onVisibilityChange:e=>{c.info(`network diagnostics visibility changed`,{visible:e}),h.setDiagnosticsVisible(e),s.emit(`networkDiagnosticsVisibilityChanged`,{visible:e})}});return re.current=ie,{config:e,qosMonitor:a,loggerManager:o,eventBus:s,session:l,authWorkflow:u,bridge:d,connectionManager:f,connectionLifecycle:p,loadingProgress:m,engineStatus:ee,networkAdaptation:h,networkDiagnosticsPanel:ie,popupManager:te,apiFacade:ne,sessionId:t,traceId:r}}};const hr={centerConnecting:`authConnecting`,waiting:`authWaiting`,authorizing:`authAuthorizing`,connected:`authConnected`,failed:`authFailed`};var gr=class{constructor(e,t){this.Events={WebRtcConnected:`webRtcConnected`,WebOnConnect:`webRtcConnected`,MapLoaded:`OnApiDataChannelStarted`,WebRtcDisconnected:`webRtcDisconnected`,WebOnDisconnect:`webRtcDisconnected`,DataChannelDisconnet:`webRtcDisconnected`,WebRtcConnecting:`webRtcConnecting`,WebRtcFailed:`webRtcFailed`,StatsReceived:`statsReceived`,EngineStatus:`EngineStatus`,StreamLoading:`streamLoading`,LoadingProgress:`LoadingProgress`,CenterConnected:`Connect`,CenterDisconnected:`UnConnect`,ConnectResult:`ConnectResult`,CenterCloseMessage:`CenterCloseMessage`,TokenAuthorize:`TokenAuthorize`,EngineServiceInit:`EngineServiceInit`,EngineServiceInitWait:`EngineServiceInitWait`,EngineSocketClose:`EngineSocketClose`,TokenWillExpired:`TokenWillExpired`,AuthStateChanged:`authStateChanged`,AuthConnecting:`authConnecting`,AuthWaiting:`authWaiting`,AuthAuthorizing:`authAuthorizing`,AuthConnected:`authConnected`,AuthFailed:`authFailed`,SessionModeReady:`sessionModeReady`,SessionModeFailed:`sessionModeFailed`,SceneConfig:`SceneConfig`,ModelClick:`ModelClick`,CameraHeight:`CameraHeight`,LeftClick:`MouseLeftButtonClick`,LeftDoubleClick:`MouseLeftButtonDoubleClick`,LeftLongPressed:`MouseLeftButtonLongPressed`,RightClick:`MouseRightButtonClick`,RightDoubleClick:`MouseRightButtonDoubleClick`,RightLongPressed:`MouseRightButtonLongPressed`,ModelTrigger:`ModelTrigger`,SyncPops:`SyncPops`,NetworkLevelChanged:`networkLevelChanged`,NetworkActionExecuted:`networkActionExecuted`,NetworkModeChanged:`networkModeChanged`,NetworkDiagnosticsVisibilityChanged:`networkDiagnosticsVisibilityChanged`,NetworkDiagnosticsUpdated:`networkDiagnosticsUpdated`},this.Enums={DlssQuality:b,LayerEnum:ye,ModelTransformType:be,ScreenRenderBitratePreset:x,Season:S,VideoCodeType:ve},this.uePushResponseListenerName=`enginesdk3_ue_push_listener`,this.uePushResponseHandler=this.handleUePushResponse.bind(this);let n=new mr().withConfig(e).withOptions({videoElementParent:t?.videoElementParent}).build();this.resolvedConfig=n.config,this.agentBridgeOptions=t?.agentBridge,this.eventBus=n.eventBus,this.qosMonitor=n.qosMonitor,this.session=n.session,this.authWorkflow=n.authWorkflow,this.connectionManager=n.connectionManager,this.loadingProgressController=n.loadingProgress,this.engineStatusCollector=n.engineStatus,this.networkAdaptation=n.networkAdaptation,this.networkDiagnosticsPanel=n.networkDiagnosticsPanel,this.popupManager=n.popupManager,n.connectionLifecycle.bind({connect:this.connect.bind(this),disconnect:()=>this.disconnectAndWait(),reconnect:this.restart.bind(this)});let r=n.loggerManager.child(`Core`),i=this.resolvedConfig;this.uePushEventNames=new Set([this.Events.MapLoaded,this.Events.ModelClick,this.Events.CameraHeight,this.Events.LeftClick,this.Events.LeftDoubleClick,this.Events.LeftLongPressed,this.Events.RightClick,this.Events.RightDoubleClick,this.Events.RightLongPressed,this.Events.SceneConfig,this.Events.ModelTrigger,this.Events.SyncPops]),this.session.addResponseEventListener(this.uePushResponseListenerName,this.uePushResponseHandler),i.viewMode===`cs`?this.loadingProgressController.show(g.SourcePreparing,`SourcePreparing`):this.loadingProgressController.show(g.EngineIniting,`EngineIniting`),this.mountApiFacade(n.apiFacade),this.networkAdaptation.start(),this.networkDiagnosticsPanel.update(this.networkAdaptation.getDiagnosticsSnapshot()),this.initializeOptionalRuntimeExtensions(),this.setupEventListeners(r),this.bootstrapPromise=this.startAuthFlowWithQos().catch(e=>(r.error(`auto auth bootstrap failed`,{error:p(e)}),this.authWorkflow.getSnapshot()))}setupEventListeners(e){this.session.getForwardEvents().forEach(t=>{this.session.addEventListener(t,n=>{t===`webRtcConnected`&&(this.connectionManager.markConnected(),this.loadingProgressController.show(g.EngineConnectionSuccess,`EngineConnectionSuccess`,!1)),(t===`webRtcDisconnected`||t===`subscribeFailed`)&&this.loadingProgressController.show(g.EngineClose,`EngineClose`,!0),t===`streamerAssigned`&&(this.connectionManager.hasConnectedBefore()?(this.loadingProgressController.show(g.EngineConnectionSuccess,`EngineConnectionSuccess`,!1),e.info(`streamerAssigned during reconnect, showing success progress`)):e.info(`streamerAssigned during initial connect, skip progress (will show on webRtcConnected)`)),this.handleSessionForwardEventForQos(t),e.debug(`forward event`,{eventName:t}),this.eventBus.emit(t,n)})}),this.authWorkflow.on(`stateChanged`,t=>{this.handleAuthStateForQos(t.state),e.debug(`auth state changed`,{state:t.state}),this.eventBus.emit(this.Events.AuthStateChanged,t);let n=hr[t.state];n&&this.eventBus.emit(n,t)}),this.authWorkflow.on(`progress`,e=>{this.handleProgressNotice(e)}),this.authWorkflow.on(`centerEvent`,({eventName:e,payload:t})=>{this.handleCenterEventForQos(e),this.eventBus.emit(e,t)}),this.authWorkflow.on(`failed`,t=>{let n=this.durationFrom(this.authStartedAt);this.authStartedAt=void 0,this.qosMonitor.recordEvent({eventName:`auth_failed`,stage:`auth`,status:`failed`,durationMs:n,errorCode:t.lastError?.code,errorMessage:t.lastError?.message}),e.error(`auth workflow failed`,{error:t.lastError?JSON.stringify(t.lastError):`unknown`}),this.eventBus.emit(this.Events.SessionModeFailed,{mode:this.session.getViewMode(),snapshot:t})}),this.authWorkflow.on(`connected`,e=>{let t=this.durationFrom(this.authStartedAt);this.authStartedAt=void 0,this.qosMonitor.recordEvent({eventName:`auth_success`,stage:`auth`,status:`success`,durationMs:t}),this.eventBus.emit(this.Events.SessionModeReady,{mode:this.session.getViewMode(),snapshot:e})})}on(e,t){this.eventBus.on(e,t)}off(e,t){this.eventBus.off(e,t)}whenReady(){return this.bootstrapPromise}setNetworkAdaptationMode(e){this.handleNetworkModeChange(e)}setNetworkManualLevel(e){this.handleNetworkModeChange(`manual`),this.networkAdaptation.setManualLevel(e)}getNetworkDiagnosticsSnapshot(){return this.latestNetworkDiagnostics??this.networkAdaptation.getDiagnosticsSnapshot()}async disconnectAndWait(){this.connectionManager.getStatus().disconnected||(this.qosMonitor.endSession({reason:`disconnect`}),this.stopRuntimeForLifecycle({disconnectAuth:!1,removeListener:!0}),await this.connectionManager.disconnect())}disconnect(){this.disconnectAndWait()}async connect(){return this.connectionManager.getStatus().disconnected?(await this.connectionManager.prepareConnectAfterDisconnect(),this.session.addResponseEventListener(this.uePushResponseListenerName,this.uePushResponseHandler),this.initializeOptionalRuntimeExtensions(),this.qosMonitor.startSession({reason:`connect`}),this.startAuthFlowWithQos()):this.authWorkflow.getSnapshot()}async restart(){return this.qosMonitor.endSession({reason:`restart`}),this.stopRuntimeForLifecycle({disconnectAuth:!1,stopAgentBridge:!1,removeListener:!0}),this.session.addResponseEventListener(this.uePushResponseListenerName,this.uePushResponseHandler),this.initializeOptionalRuntimeExtensions(),this.qosMonitor.startSession({reason:`restart`}),this.authStartedAt=Date.now(),this.centerConnectStartedAt=void 0,this.webrtcConnectStartedAt=void 0,this.qosMonitor.recordEvent({eventName:`auth_start`,stage:`auth`,status:`start`}),this.connectionManager.restart()}startAuthFlowWithQos(){return this.authStartedAt=Date.now(),this.centerConnectStartedAt=void 0,this.webrtcConnectStartedAt=void 0,this.qosMonitor.recordEvent({eventName:`auth_start`,stage:`auth`,status:`start`}),this.connectionManager.connect()}handleSessionForwardEventForQos(e){if(e===`webRtcConnecting`){this.webrtcConnectStartedAt===void 0&&(this.webrtcConnectStartedAt=Date.now(),this.qosMonitor.recordEvent({eventName:`webrtc_connect_start`,stage:`webrtc`,status:`start`}));return}if(e===`webRtcConnected`){let e=this.durationFrom(this.webrtcConnectStartedAt);this.webrtcConnectStartedAt=void 0,this.qosMonitor.recordEvent({eventName:`webrtc_connected`,stage:`webrtc`,status:`success`,durationMs:e}),this.qosMonitor.recordEvent({eventName:`first_frame_rendered`,stage:`media`,status:`success`,durationMs:e});return}(e===`webRtcDisconnected`||e===`webRtcFailed`)&&(this.webrtcConnectStartedAt=void 0,this.qosMonitor.recordEvent({eventName:`webrtc_disconnected`,stage:`webrtc`,status:`failed`,attrs:{reason:e}}))}handleAuthStateForQos(e){if(e===`centerConnecting`){this.centerConnectStartedAt=Date.now(),this.qosMonitor.recordEvent({eventName:`center_connect_start`,stage:`center`,status:`start`});return}if(e===`centerConnected`){let e=this.durationFrom(this.centerConnectStartedAt);this.centerConnectStartedAt=void 0,this.qosMonitor.recordEvent({eventName:`center_connected`,stage:`center`,status:`success`,durationMs:e});return}e===`webrtcConnecting`&&this.webrtcConnectStartedAt===void 0&&(this.webrtcConnectStartedAt=Date.now(),this.qosMonitor.recordEvent({eventName:`webrtc_connect_start`,stage:`webrtc`,status:`start`}))}handleCenterEventForQos(e){if(this.qosMonitor.recordEvent({eventName:`center_message_received`,stage:`center`,status:`update`,attrs:{fn:e}}),e===this.Events.CenterDisconnected){this.qosMonitor.recordEvent({eventName:`center_disconnected`,stage:`center`,status:`failed`,attrs:{reason:e}});return}if(e===this.Events.CenterConnected&&this.centerConnectStartedAt!==void 0){let e=this.durationFrom(this.centerConnectStartedAt);this.centerConnectStartedAt=void 0,this.qosMonitor.recordEvent({eventName:`center_connected`,stage:`center`,status:`success`,durationMs:e})}}durationFrom(e){if(e===void 0)return;let t=Date.now()-e;return Number.isFinite(t)&&t>=0?t:void 0}handleProgressNotice(e){if(e.kind===`tokenWillExpire`){this.loadingProgressController.showTokenWillExpire(e.message,e.key,e.isClose);return}this.loadingProgressController.show(e.message,e.key,e.isClose)}handleNetworkModeChange(e){this.networkAdaptation.setMode(e);let t={mode:e,ts:Date.now(),diagnostics:this.networkAdaptation.getDiagnosticsSnapshot()};this.eventBus.emit(this.Events.NetworkModeChanged,t)}mountApiFacade(e){let t=this;Object.keys(e).forEach(n=>{this.setApiModule(t,e,n)})}setApiModule(e,t,n){e[n]=t[n]}initializeOptionalRuntimeExtensions(){if(this.agentBridge||!this.agentBridgeOptions?.enabled)return;let e={...this.agentBridgeOptions,serverUrl:this.agentBridgeOptions.serverUrl??`ws://127.0.0.1:8787/sdk3-bridge`},t=Jt(this,{runtimeName:e.runtimeName,expose:e.expose,metadata:e.metadata,engineConfig:this.resolvedConfig,getAuthSnapshot:()=>this.authWorkflow.getSnapshot(),mockInvoke:e.mockInvoke});this.agentBridge=new fe(t,e),this.agentBridge.start()}stopRuntimeForLifecycle(e){e?.stopAgentBridge!==!1&&(this.agentBridge?.stop(`disconnect`),this.agentBridge=void 0),e?.removeListener!==!1&&this.session.removeResponseEventListener(this.uePushResponseListenerName),this.engineStatusCollector.stop(),e?.disconnectAuth!==!1&&this.authWorkflow.disconnect(),this.loadingProgressController.dispose(),this.qosMonitor.flush()}handleUePushResponse(e){let t=e,n;try{if(t=JSON.parse(e),typeof t==`object`&&t){let e=t,r=e.uuid??e.fn;typeof r==`string`&&r.length>0&&(n=r)}}catch{}!n&&this.uePushEventNames.has(e)&&(n=e),!(!n||!this.uePushEventNames.has(n))&&this.eventBus.emit(n,t)}getEngineConfig(){return this.resolvedConfig}};export{Dt as AGENT_BRIDGE_API_METADATA,H as API_MODULE_KEYS,fe as AgentRuntimeBridge,Ke as Animation,$ as ApiRegistryError,qe as Camera,Je as Connect,gr as DTCEngine,Ye as Dlss,b as DlssQuality,Xe as HighLighterEffect,et as Layer,ye as LayerEnum,tt as Model,nt as ModelPOI,rt as ModelTransform,be as ModelTransformType,it as PathPatrol,We as PendingValidationSchemaMap,ct as Popup,d as SDKValidationError,ut as Scene,lt as Screen,x as ScreenRenderBitratePreset,ge as ScreenRenderBitratePresetOptions,S as Season,dt as TimeLine,ft as UIPOI,ve as VideoCodeType,pt as WeatherSystem,mt as apiRegistry,Ot as createAgentBridgeMetadata,dr as createApiFacade,Jt as createBridgeRuntime,Ft as getAgentBridgeMethodSchema,Mt as isAgentBridgeMethodExposed,jt as isAgentBridgeModuleExposed,kt as isAgentBridgeModuleName,Pt as listAgentBridgeMethods,Nt as listAgentBridgeModules,At as resolveAgentBridgeExposeConfig};
|