@vibexnpm/talkx 2.3.1 → 2.5.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.
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TalkFlowSDK={})}(this,function(e){"use strict";class t{constructor(){this._events=new Map}on(e,t){return this._events.has(e)||this._events.set(e,new Set),this._events.get(e).add(t),()=>this.off(e,t)}once(e,t){const s=(...i)=>{this.off(e,s),t.apply(this,i)};return s._originalListener=t,this.on(e,s)}off(e,t){const s=this._events.get(e);if(s){for(const e of s)if(e===t||e._originalListener===t){s.delete(e);break}0===s.size&&this._events.delete(e)}}emit(e,t){const s=this._events.get(e);s&&s.forEach(s=>{try{s(t)}catch(t){console.error(`Error in event listener for '${e}':`,t)}})}removeAllListeners(e){e?this._events.delete(e):this._events.clear()}listenerCount(e){const t=this._events.get(e);return t?t.size:0}eventNames(){return Array.from(this._events.keys())}}const s={DISCONNECTED:"disconnected",CONNECTING:"connecting",CONNECTED:"connected",RECONNECTING:"reconnecting",ERROR:"error"},i={CONNECTION_FAILED:"CONNECTION_FAILED",CONNECTION_LOST:"CONNECTION_LOST",CONNECTION_TIMEOUT:"CONNECTION_TIMEOUT",JWT_INVALID:"JWT_INVALID",JWT_EXPIRED:"JWT_EXPIRED",JWT_PARSE_FAILED:"JWT_PARSE_FAILED",UNAUTHORIZED:"UNAUTHORIZED",API_ERROR:"API_ERROR",API_TIMEOUT:"API_TIMEOUT",CHAT_ROOM_NOT_FOUND:"CHAT_ROOM_NOT_FOUND",CHAT_MESSAGE_FAILED:"CHAT_MESSAGE_FAILED",CHAT_SUBSCRIPTION_FAILED:"CHAT_SUBSCRIPTION_FAILED",MEDIA_ACCESS_DENIED:"MEDIA_ACCESS_DENIED",SCREEN_SHARE_DENIED:"SCREEN_SHARE_DENIED",PEER_CONNECTION_FAILED:"PEER_CONNECTION_FAILED",ICE_CONNECTION_FAILED:"ICE_CONNECTION_FAILED",SIGNALING_FAILED:"SIGNALING_FAILED",DEVICE_SWITCH_FAILED:"DEVICE_SWITCH_FAILED",ENUMERATE_DEVICES_FAILED:"ENUMERATE_DEVICES_FAILED",CALL_ROOM_NOT_FOUND:"CALL_ROOM_NOT_FOUND",INVALID_STATE:"INVALID_STATE",UNKNOWN_ERROR:"UNKNOWN_ERROR"},n={CALL_OFFER:"call_offer",CALL_ANSWER:"call_answer",ICE_CANDIDATE:"ice_candidate",JOIN_ROOM:"join_room",LEAVE_ROOM:"leave_room",PEER_JOINED:"peer_joined",PEER_LEFT:"peer_left",VIDEO_STATE_CHANGED:"video_state_changed",AUDIO_STATE_CHANGED:"audio_state_changed",SCREEN_SHARE_STARTED:"screen_share_started",SCREEN_SHARE_ENDED:"screen_share_ended",CALL_REQUEST:"call_request",CALL_ACCEPT:"call_accept",CALL_REJECT:"call_reject",CALL_CANCEL:"call_cancel",CALL_END:"call_end",CALL_INVITATION:"call_invitation",CALL_BUSY:"call_busy"},r={DIRECT:"DIRECT",GROUP:"GROUP",PRIVATE_GROUP:"PRIVATE_GROUP",TEAM:"TEAM"},o={MESSAGE_RECEIVED:"MESSAGE_RECEIVED",MESSAGE_DELETED:"MESSAGE_DELETED",MESSAGE_UPDATED:"MESSAGE_UPDATED",ROOM_CREATED:"ROOM_CREATED",ROOM_JOINED:"ROOM_JOINED",ROOM_LEFT:"ROOM_LEFT",ROOM_UPDATED:"ROOM_UPDATED",ROOM_KICKED:"ROOM_KICKED",ROOM_BANNED:"ROOM_BANNED",MESSAGE_RETENTION_CLEANUP:"MESSAGE_RETENTION_CLEANUP"},a={SOCKJS_ENDPOINT:"/ws-chat",NATIVE_ENDPOINT:"/ws-chat-native",APP_PREFIX:"/app",TOPIC_PREFIX:"/topic",QUEUE_PREFIX:"/queue",USER_PREFIX:"/user",getChatDestination:e=>`/topic/chat/${e}`,getChatReadDestination:e=>`/topic/chat/${e}/read`,getChatTypingDestination:e=>`/topic/chat/${e}/typing`,ROOM_LIST_USER_DESTINATION:"/user/queue/rooms",getWebRTCDestination:e=>`/topic/webrtc/${e}`,getWebRTCUserDestination:()=>"/user/queue/webrtc",CHAT_SEND:"/app/chat/send",CHAT_READ:"/app/chat/read",CHAT_TYPING:"/app/chat/typing",WEBRTC_SIGNAL:"/app/webrtc/signal"},c={DEVELOPMENT:"development",STAGING:"staging",PRODUCTION:"production"},l={[c.DEVELOPMENT]:{serverUrl:"https://dev-chat.apiorbit.net",wsEndpoint:"/ws-chat"},[c.STAGING]:{serverUrl:"https://stg-api.talk-x.app",wsEndpoint:"/ws-chat"},[c.PRODUCTION]:{serverUrl:"https://prod-api.talk-x.app",wsEndpoint:"/ws-chat"}},h={environment:c.PRODUCTION,reconnectDelay:5e3,maxReconnectAttempts:10,heartbeatIncoming:1e4,heartbeatOutgoing:1e4,apiTimeout:3e4,iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],logLevel:2};function d(e){return(l[e]||l[c.PRODUCTION]).serverUrl}const u={DEBUG:0,INFO:1,WARN:2,ERROR:3,NONE:4};class p{constructor(e=u.WARN,t="TalkFlow"){this.level=e,this.prefix=t}setLevel(e){this.level=e}setPrefix(e){this.prefix=e}_format(e,...t){return[`[${(new Date).toISOString()}] [${e}] [${this.prefix}]`,...t]}debug(...e){this.level<=u.DEBUG&&console.debug(...this._format("DEBUG",...e))}info(...e){this.level<=u.INFO&&console.info(...this._format("INFO",...e))}warn(...e){this.level<=u.WARN&&console.warn(...this._format("WARN",...e))}error(...e){this.level<=u.ERROR&&console.error(...this._format("ERROR",...e))}}class g{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.apiKey=e.apiKey,this.projectId=e.projectId,this.jwtToken=e.jwtToken,this.timeout=e.timeout||h.apiTimeout,this.logger=new p(e.logLevel,"ApiClient")}setJwtToken(e){this.jwtToken=e}_getHeaders(){const e={"Content-Type":"application/json","X-API-KEY":this.apiKey,"X-PROJECT-ID":this.projectId};return this.jwtToken&&(e.Authorization=this.jwtToken.startsWith("Bearer ")?this.jwtToken:`Bearer ${this.jwtToken}`),e}async request(e,t,s={}){const{body:n,params:r}=s;let o=`${this.baseUrl}${t}`;if(r){const e=new URLSearchParams;Object.entries(r).forEach(([t,s])=>{null!=s&&e.append(t,s)});const t=e.toString();t&&(o+=`?${t}`)}const a=new AbortController,c=setTimeout(()=>a.abort(),this.timeout);let l;try{this.logger.debug(`${e} ${o}`,n?{body:n}:""),l=await fetch(o,{method:e,headers:this._getHeaders(),body:n?JSON.stringify(n):void 0,signal:a.signal})}catch(t){if(clearTimeout(c),"AbortError"===t.name){const e=new Error("Request timeout");throw e.code=i.API_TIMEOUT,e}throw this.logger.error(`API Error: ${e} ${o}`,t),t}clearTimeout(c);const h=l.headers.get("content-type");let d;if(d=h&&h.includes("application/json")?await l.json():await l.text(),!l.ok){const t=new Error(d?.message||`HTTP ${l.status}`);throw t.code=i.API_ERROR,t.status=l.status,t.response=d,this.logger.error(`API Error: ${e} ${o}`,t),t}return this.logger.debug(`Response ${l.status}:`,d),d}get(e,t){return this.request("GET",e,{params:t})}post(e,t,s){return this.request("POST",e,{body:t,params:s})}put(e,t){return this.request("PUT",e,{body:t})}patch(e,t){return this.request("PATCH",e,{body:t})}delete(e,t){return this.request("DELETE",e,{params:t})}upload(e,t,s={}){const{fieldName:n="file",onProgress:r,signal:o,timeout:a=6e5}=s;return new Promise((s,c)=>{const l=`${this.baseUrl}${e}`,h=new XMLHttpRequest,d=new FormData;d.append(n,t),h.open("POST",l),h.timeout=a,h.setRequestHeader("X-API-KEY",this.apiKey),h.setRequestHeader("X-PROJECT-ID",this.projectId),this.jwtToken&&h.setRequestHeader("Authorization",this.jwtToken.startsWith("Bearer ")?this.jwtToken:`Bearer ${this.jwtToken}`),"function"==typeof r&&(h.upload.onprogress=e=>{e.lengthComputable&&r({loaded:e.loaded,total:e.total,percent:Math.round(e.loaded/e.total*100)})});const u=()=>h.abort();if(o){if(o.aborted)return void c(new Error("Upload cancelled"));o.addEventListener("abort",u)}const p=()=>{o&&o.removeEventListener("abort",u)};h.onload=()=>{p();let e=h.responseText;if((h.getResponseHeader("content-type")||"").includes("application/json"))try{e=JSON.parse(h.responseText)}catch{}if(h.status>=200&&h.status<300)this.logger.debug(`Upload ${h.status}:`,e),s(e);else{const t=new Error(e?.message||`HTTP ${h.status}`);t.code=i.API_ERROR,t.status=h.status,t.response=e,this.logger.error(`Upload Error: POST ${l}`,t),c(t)}},h.onerror=()=>{p();const e=new Error("Network error during upload");e.code=i.API_ERROR,this.logger.error(`Upload Network Error: POST ${l}`,e),c(e)},h.ontimeout=()=>{p();const e=new Error("Upload timeout");e.code=i.API_TIMEOUT,this.logger.error(`Upload Timeout: POST ${l}`,e),c(e)},h.onabort=()=>{p(),c(new Error("Upload cancelled"))},this.logger.debug(`POST ${l} (multipart, ${t.size} bytes)`),h.send(d)})}}function m(e){return e&&"string"==typeof e?e.replace(/^Bearer\s+/i,""):""}function f(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const s=t.length%4;s&&(t+="=".repeat(4-s));const i=atob(t),n=Uint8Array.from(i,e=>e.charCodeAt(0));return(new TextDecoder).decode(n)}function b(e,t={}){const{bufferSeconds:s=30,validateExpiry:n=!0}=t;if(!e||"string"!=typeof e){const e=new Error("JWT token is required");throw e.code=i.JWT_INVALID,e}const r=m(e).split(".");if(3!==r.length){const e=new Error("Invalid JWT format: expected 3 parts separated by dots");throw e.code=i.JWT_INVALID,e}let o;try{o=JSON.parse(f(r[1]))}catch(e){const t=new Error("Invalid JWT: failed to decode payload");throw t.code=i.JWT_PARSE_FAILED,t.originalError=e,t}if(n&&o.exp){const e=1e3*o.exp,t=1e3*s,n=Date.now();if(e<n+t){const t=new Error(e<n?"JWT token expired":`JWT token expires within ${s} seconds`);throw t.code=i.JWT_EXPIRED,t.expiredAt=new Date(e).toISOString(),t}}if(o.iat){const e=6e4;if(1e3*o.iat>Date.now()+e){const e=new Error("JWT token issued in the future");throw e.code=i.JWT_INVALID,e}}const a=o.userId||o.sub||o.user_id;if(!a){const e=new Error("Cannot extract userId from JWT: missing userId, sub, or user_id claim");throw e.code=i.JWT_INVALID,e}return{userId:a,payload:o}}function _(e){try{const t=m(e).split(".");if(3!==t.length)return null;const s=JSON.parse(f(t[1]));return s.userId||s.sub||s.user_id||null}catch(e){return console.error("Failed to extract userId from JWT:",e),null}}function y(e,t=0){try{const s=m(e).split(".");if(3!==s.length)return!0;const i=JSON.parse(f(s[1]));if(!i.exp)return!1;const n=1e3*i.exp,r=1e3*t;return n<Date.now()+r}catch(e){return console.error("Failed to check JWT expiration:",e),!0}}const E="\n",v="\0";class S{get body(){return!this._body&&this.isBinaryBody&&(this._body=(new TextDecoder).decode(this._binaryBody)),this._body||""}get binaryBody(){return this._binaryBody||this.isBinaryBody||(this._binaryBody=(new TextEncoder).encode(this._body)),this._binaryBody}constructor(e){const{command:t,headers:s,body:i,binaryBody:n,escapeHeaderValues:r,skipContentLengthHeader:o}=e;this.command=t,this.headers=Object.assign({},s||{}),n?(this._binaryBody=n,this.isBinaryBody=!0):(this._body=i||"",this.isBinaryBody=!1),this.escapeHeaderValues=r||!1,this.skipContentLengthHeader=o||!1}static fromRawFrame(e,t){const s={},i=e=>e.replace(/^\s+|\s+$/g,"");for(const n of e.headers.reverse()){n.indexOf(":");const r=i(n[0]);let o=i(n[1]);t&&"CONNECT"!==e.command&&"CONNECTED"!==e.command&&(o=S.hdrValueUnEscape(o)),s[r]=o}return new S({command:e.command,headers:s,binaryBody:e.binaryBody,escapeHeaderValues:t})}toString(){return this.serializeCmdAndHeaders()}serialize(){const e=this.serializeCmdAndHeaders();return this.isBinaryBody?S.toUnit8Array(e,this._binaryBody).buffer:e+this._body+v}serializeCmdAndHeaders(){const e=[this.command];this.skipContentLengthHeader&&delete this.headers["content-length"];for(const t of Object.keys(this.headers||{})){const s=this.headers[t];this.escapeHeaderValues&&"CONNECT"!==this.command&&"CONNECTED"!==this.command?e.push(`${t}:${S.hdrValueEscape(`${s}`)}`):e.push(`${t}:${s}`)}return(this.isBinaryBody||!this.isBodyEmpty()&&!this.skipContentLengthHeader)&&e.push(`content-length:${this.bodyLength()}`),e.join(E)+E+E}isBodyEmpty(){return 0===this.bodyLength()}bodyLength(){const e=this.binaryBody;return e?e.length:0}static sizeOfUTF8(e){return e?(new TextEncoder).encode(e).length:0}static toUnit8Array(e,t){const s=(new TextEncoder).encode(e),i=new Uint8Array([0]),n=new Uint8Array(s.length+t.length+i.length);return n.set(s),n.set(t,s.length),n.set(i,s.length+t.length),n}static marshall(e){return new S(e).serialize()}static hdrValueEscape(e){return e.replace(/\\/g,"\\\\").replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/:/g,"\\c")}static hdrValueUnEscape(e){return e.replace(/\\r/g,"\r").replace(/\\n/g,"\n").replace(/\\c/g,":").replace(/\\\\/g,"\\")}}class w{constructor(e,t){this.onFrame=e,this.onIncomingPing=t,this._encoder=new TextEncoder,this._decoder=new TextDecoder,this._token=[],this._initState()}parseChunk(e,t=!1){let s;if(s="string"==typeof e?this._encoder.encode(e):new Uint8Array(e),t&&0!==s[s.length-1]){const e=new Uint8Array(s.length+1);e.set(s,0),e[s.length]=0,s=e}for(let e=0;e<s.length;e++){const t=s[e];this._onByte(t)}}_collectFrame(e){0!==e&&13!==e&&(10!==e?(this._onByte=this._collectCommand,this._reinjectByte(e)):this.onIncomingPing())}_collectCommand(e){if(13!==e)return 10===e?(this._results.command=this._consumeTokenAsUTF8(),void(this._onByte=this._collectHeaders)):void this._consumeByte(e)}_collectHeaders(e){13!==e&&(10!==e?(this._onByte=this._collectHeaderKey,this._reinjectByte(e)):this._setupCollectBody())}_reinjectByte(e){this._onByte(e)}_collectHeaderKey(e){if(58===e)return this._headerKey=this._consumeTokenAsUTF8(),void(this._onByte=this._collectHeaderValue);this._consumeByte(e)}_collectHeaderValue(e){if(13!==e)return 10===e?(this._results.headers.push([this._headerKey,this._consumeTokenAsUTF8()]),this._headerKey=void 0,void(this._onByte=this._collectHeaders)):void this._consumeByte(e)}_setupCollectBody(){const e=this._results.headers.filter(e=>"content-length"===e[0])[0];e?(this._bodyBytesRemaining=parseInt(e[1],10),this._onByte=this._collectBodyFixedSize):this._onByte=this._collectBodyNullTerminated}_collectBodyNullTerminated(e){0!==e?this._consumeByte(e):this._retrievedBody()}_collectBodyFixedSize(e){0!==this._bodyBytesRemaining--?this._consumeByte(e):this._retrievedBody()}_retrievedBody(){this._results.binaryBody=this._consumeTokenAsRaw();try{this.onFrame(this._results)}catch(e){console.log("Ignoring an exception thrown by a frame handler. Original exception: ",e)}this._initState()}_consumeByte(e){this._token.push(e)}_consumeTokenAsUTF8(){return this._decoder.decode(this._consumeTokenAsRaw())}_consumeTokenAsRaw(){const e=new Uint8Array(this._token);return this._token=[],e}_initState(){this._results={command:void 0,headers:[],binaryBody:void 0},this._token=[],this._headerKey=void 0,this._onByte=this._collectFrame}}var I,T,C,R;!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.OPEN=1]="OPEN",e[e.CLOSING=2]="CLOSING",e[e.CLOSED=3]="CLOSED"}(I||(I={})),function(e){e[e.ACTIVE=0]="ACTIVE",e[e.DEACTIVATING=1]="DEACTIVATING",e[e.INACTIVE=2]="INACTIVE"}(T||(T={})),function(e){e[e.LINEAR=0]="LINEAR",e[e.EXPONENTIAL=1]="EXPONENTIAL"}(C||(C={})),function(e){e.Interval="interval",e.Worker="worker"}(R||(R={}));class A{constructor(e,t=R.Interval,s){this._interval=e,this._strategy=t,this._debug=s,this._workerScript=`\n var startTime = Date.now();\n setInterval(function() {\n self.postMessage(Date.now() - startTime);\n }, ${this._interval});\n `}start(e){this.stop(),this.shouldUseWorker()?this.runWorker(e):this.runInterval(e)}stop(){this.disposeWorker(),this.disposeInterval()}shouldUseWorker(){return"undefined"!=typeof Worker&&this._strategy===R.Worker}runWorker(e){this._debug("Using runWorker for outgoing pings"),this._worker||(this._worker=new Worker(URL.createObjectURL(new Blob([this._workerScript],{type:"text/javascript"}))),this._worker.onmessage=t=>e(t.data))}runInterval(e){if(this._debug("Using runInterval for outgoing pings"),!this._timer){const t=Date.now();this._timer=setInterval(()=>{e(Date.now()-t)},this._interval)}}disposeWorker(){this._worker&&(this._worker.terminate(),delete this._worker,this._debug("Outgoing ping disposeWorker"))}disposeInterval(){this._timer&&(clearInterval(this._timer),delete this._timer,this._debug("Outgoing ping disposeInterval"))}}class O{constructor(e){this.versions=e}supportedVersions(){return this.versions.join(",")}protocolVersions(){return this.versions.map(e=>`v${e.replace(".","")}.stomp`)}}O.V1_0="1.0",O.V1_1="1.1",O.V1_2="1.2",O.default=new O([O.V1_2,O.V1_1,O.V1_0]);class k{get connectedVersion(){return this._connectedVersion}get connected(){return this._connected}constructor(e,t,s){this._client=e,this._webSocket=t,this._connected=!1,this._serverFrameHandlers={CONNECTED:e=>{this.debug(`connected to server ${e.headers.server}`),this._connected=!0,this._connectedVersion=e.headers.version,this._connectedVersion===O.V1_2&&(this._escapeHeaderValues=!0),this._setupHeartbeat(e.headers),this.onConnect(e)},MESSAGE:e=>{const t=e.headers.subscription,s=this._subscriptions[t]||this.onUnhandledMessage,i=e,n=this,r=this._connectedVersion===O.V1_2?i.headers.ack:i.headers["message-id"];i.ack=(e={})=>n.ack(r,t,e),i.nack=(e={})=>n.nack(r,t,e),s(i)},RECEIPT:e=>{const t=this._receiptWatchers[e.headers["receipt-id"]];t?(t(e),delete this._receiptWatchers[e.headers["receipt-id"]]):this.onUnhandledReceipt(e)},ERROR:e=>{this.onStompError(e)}},this._counter=0,this._subscriptions={},this._receiptWatchers={},this._partialData="",this._escapeHeaderValues=!1,this._lastServerActivityTS=Date.now(),this.debug=s.debug,this.stompVersions=s.stompVersions,this.connectHeaders=s.connectHeaders,this.disconnectHeaders=s.disconnectHeaders,this.heartbeatIncoming=s.heartbeatIncoming,this.heartbeatToleranceMultiplier=s.heartbeatGracePeriods,this.heartbeatOutgoing=s.heartbeatOutgoing,this.splitLargeFrames=s.splitLargeFrames,this.maxWebSocketChunkSize=s.maxWebSocketChunkSize,this.forceBinaryWSFrames=s.forceBinaryWSFrames,this.logRawCommunication=s.logRawCommunication,this.appendMissingNULLonIncoming=s.appendMissingNULLonIncoming,this.discardWebsocketOnCommFailure=s.discardWebsocketOnCommFailure,this.onConnect=s.onConnect,this.onDisconnect=s.onDisconnect,this.onStompError=s.onStompError,this.onWebSocketClose=s.onWebSocketClose,this.onWebSocketError=s.onWebSocketError,this.onUnhandledMessage=s.onUnhandledMessage,this.onUnhandledReceipt=s.onUnhandledReceipt,this.onUnhandledFrame=s.onUnhandledFrame,this.onHeartbeatReceived=s.onHeartbeatReceived,this.onHeartbeatLost=s.onHeartbeatLost}start(){const e=new w(e=>{const t=S.fromRawFrame(e,this._escapeHeaderValues);this.logRawCommunication||this.debug(`<<< ${t}`);(this._serverFrameHandlers[t.command]||this.onUnhandledFrame)(t)},()=>{this.debug("<<< PONG"),this.onHeartbeatReceived()});this._webSocket.onmessage=t=>{if(this.debug("Received data"),this._lastServerActivityTS=Date.now(),this.logRawCommunication){const e=t.data instanceof ArrayBuffer?(new TextDecoder).decode(t.data):t.data;this.debug(`<<< ${e}`)}e.parseChunk(t.data,this.appendMissingNULLonIncoming)},this._webSocket.onclose=e=>{this.debug(`Connection closed to ${this._webSocket.url}`),this._cleanUp(),this.onWebSocketClose(e)},this._webSocket.onerror=e=>{this.onWebSocketError(e)},this._webSocket.onopen=()=>{const e=Object.assign({},this.connectHeaders);this.debug("Web Socket Opened..."),e["accept-version"]=this.stompVersions.supportedVersions(),e["heart-beat"]=[this.heartbeatOutgoing,this.heartbeatIncoming].join(","),this._transmit({command:"CONNECT",headers:e})}}_setupHeartbeat(e){if(e.version!==O.V1_1&&e.version!==O.V1_2)return;if(!e["heart-beat"])return;const[t,s]=e["heart-beat"].split(",").map(e=>parseInt(e,10));if(0!==this.heartbeatOutgoing&&0!==s){const e=Math.max(this.heartbeatOutgoing,s);this.debug(`send PING every ${e}ms`),this._pinger=new A(e,this._client.heartbeatStrategy,this.debug),this._pinger.start(()=>{this._webSocket.readyState===I.OPEN&&(this._webSocket.send(E),this.debug(">>> PING"))})}if(0!==this.heartbeatIncoming&&0!==t){const e=Math.max(this.heartbeatIncoming,t);this.debug(`check PONG every ${e}ms`),this._ponger=setInterval(()=>{const t=Date.now()-this._lastServerActivityTS;t>e*this.heartbeatToleranceMultiplier&&(this.debug(`did not receive server activity for the last ${t}ms`),this.onHeartbeatLost(),this._closeOrDiscardWebsocket())},e)}}_closeOrDiscardWebsocket(){this.discardWebsocketOnCommFailure?(this.debug("Discarding websocket, the underlying socket may linger for a while"),this.discardWebsocket()):(this.debug("Issuing close on the websocket"),this._closeWebsocket())}forceDisconnect(){this._webSocket&&(this._webSocket.readyState!==I.CONNECTING&&this._webSocket.readyState!==I.OPEN||this._closeOrDiscardWebsocket())}_closeWebsocket(){this._webSocket.onmessage=()=>{},this._webSocket.close()}discardWebsocket(){var e,t;"function"!=typeof this._webSocket.terminate&&(e=this._webSocket,t=e=>this.debug(e),e.terminate=function(){const s=()=>{};this.onerror=s,this.onmessage=s,this.onopen=s;const i=new Date,n=Math.random().toString().substring(2,8),r=this.onclose;this.onclose=e=>{const s=(new Date).getTime()-i.getTime();t(`Discarded socket (#${n}) closed after ${s}ms, with code/reason: ${e.code}/${e.reason}`)},this.close(),r?.call(e,{code:4001,reason:`Quick discarding socket (#${n}) without waiting for the shutdown sequence.`,wasClean:!1})}),this._webSocket.terminate()}_transmit(e){const{command:t,headers:s,body:i,binaryBody:n,skipContentLengthHeader:r}=e,o=new S({command:t,headers:s,body:i,binaryBody:n,escapeHeaderValues:this._escapeHeaderValues,skipContentLengthHeader:r});let a=o.serialize();if(this.logRawCommunication?this.debug(`>>> ${a}`):this.debug(`>>> ${o}`),this.forceBinaryWSFrames&&"string"==typeof a&&(a=(new TextEncoder).encode(a)),"string"==typeof a&&this.splitLargeFrames){let e=a;for(;e.length>0;){const t=e.substring(0,this.maxWebSocketChunkSize);e=e.substring(this.maxWebSocketChunkSize),this._webSocket.send(t),this.debug(`chunk sent = ${t.length}, remaining = ${e.length}`)}}else this._webSocket.send(a)}dispose(){if(this.connected)try{const e=Object.assign({},this.disconnectHeaders);e.receipt||(e.receipt="close-"+this._counter++),this.watchForReceipt(e.receipt,e=>{this._closeWebsocket(),this._cleanUp(),this.onDisconnect(e)}),this._transmit({command:"DISCONNECT",headers:e})}catch(e){this.debug(`Ignoring error during disconnect ${e}`)}else this._webSocket.readyState!==I.CONNECTING&&this._webSocket.readyState!==I.OPEN||this._closeWebsocket()}_cleanUp(){this._connected=!1,this._pinger&&(this._pinger.stop(),this._pinger=void 0),this._ponger&&(clearInterval(this._ponger),this._ponger=void 0)}publish(e){const{destination:t,headers:s,body:i,binaryBody:n,skipContentLengthHeader:r}=e,o=Object.assign({destination:t},s);this._transmit({command:"SEND",headers:o,body:i,binaryBody:n,skipContentLengthHeader:r})}watchForReceipt(e,t){this._receiptWatchers[e]=t}subscribe(e,t,s={}){(s=Object.assign({},s)).id||(s.id="sub-"+this._counter++),s.destination=e,this._subscriptions[s.id]=t,this._transmit({command:"SUBSCRIBE",headers:s});const i=this;return{id:s.id,unsubscribe:e=>i.unsubscribe(s.id,e)}}unsubscribe(e,t={}){t=Object.assign({},t),delete this._subscriptions[e],t.id=e,this._transmit({command:"UNSUBSCRIBE",headers:t})}begin(e){const t=e||"tx-"+this._counter++;this._transmit({command:"BEGIN",headers:{transaction:t}});const s=this;return{id:t,commit(){s.commit(t)},abort(){s.abort(t)}}}commit(e){this._transmit({command:"COMMIT",headers:{transaction:e}})}abort(e){this._transmit({command:"ABORT",headers:{transaction:e}})}ack(e,t,s={}){s=Object.assign({},s),this._connectedVersion===O.V1_2?s.id=e:s["message-id"]=e,s.subscription=t,this._transmit({command:"ACK",headers:s})}nack(e,t,s={}){return s=Object.assign({},s),this._connectedVersion===O.V1_2?s.id=e:s["message-id"]=e,s.subscription=t,this._transmit({command:"NACK",headers:s})}}class N{get webSocket(){return this._stompHandler?._webSocket}get disconnectHeaders(){return this._disconnectHeaders}set disconnectHeaders(e){this._disconnectHeaders=e,this._stompHandler&&(this._stompHandler.disconnectHeaders=this._disconnectHeaders)}get connected(){return!!this._stompHandler&&this._stompHandler.connected}get connectedVersion(){return this._stompHandler?this._stompHandler.connectedVersion:void 0}get active(){return this.state===T.ACTIVE}_changeState(e){this.state=e,this.onChangeState(e)}constructor(e={}){this.stompVersions=O.default,this.connectionTimeout=0,this.reconnectDelay=5e3,this._nextReconnectDelay=0,this.maxReconnectDelay=9e5,this.reconnectTimeMode=C.LINEAR,this.heartbeatIncoming=1e4,this.heartbeatToleranceMultiplier=2,this.heartbeatOutgoing=1e4,this.heartbeatStrategy=R.Interval,this.splitLargeFrames=!1,this.maxWebSocketChunkSize=8192,this.forceBinaryWSFrames=!1,this.appendMissingNULLonIncoming=!1,this.discardWebsocketOnCommFailure=!1,this.state=T.INACTIVE;const t=()=>{};this.debug=t,this.beforeConnect=t,this.onConnect=t,this.onDisconnect=t,this.onUnhandledMessage=t,this.onUnhandledReceipt=t,this.onUnhandledFrame=t,this.onHeartbeatReceived=t,this.onHeartbeatLost=t,this.onStompError=t,this.onWebSocketClose=t,this.onWebSocketError=t,this.logRawCommunication=!1,this.onChangeState=t,this.connectHeaders={},this._disconnectHeaders={},this.configure(e)}configure(e){Object.assign(this,e),this.maxReconnectDelay>0&&this.maxReconnectDelay<this.reconnectDelay&&(this.debug(`Warning: maxReconnectDelay (${this.maxReconnectDelay}ms) is less than reconnectDelay (${this.reconnectDelay}ms). Using reconnectDelay as the maxReconnectDelay delay.`),this.maxReconnectDelay=this.reconnectDelay)}activate(){const e=()=>{this.active?this.debug("Already ACTIVE, ignoring request to activate"):(this._changeState(T.ACTIVE),this._nextReconnectDelay=this.reconnectDelay,this._connect())};this.state===T.DEACTIVATING?(this.debug("Waiting for deactivation to finish before activating"),this.deactivate().then(()=>{e()})):e()}async _connect(){if(await this.beforeConnect(this),this._stompHandler)return void this.debug("There is already a stompHandler, skipping the call to connect");if(!this.active)return void this.debug("Client has been marked inactive, will not attempt to connect");this.connectionTimeout>0&&(this._connectionWatcher&&clearTimeout(this._connectionWatcher),this._connectionWatcher=setTimeout(()=>{this.connected||(this.debug(`Connection not established in ${this.connectionTimeout}ms, closing socket`),this.forceDisconnect())},this.connectionTimeout)),this.debug("Opening Web Socket...");const e=this._createWebSocket();this._stompHandler=new k(this,e,{debug:this.debug,stompVersions:this.stompVersions,connectHeaders:this.connectHeaders,disconnectHeaders:this._disconnectHeaders,heartbeatIncoming:this.heartbeatIncoming,heartbeatGracePeriods:this.heartbeatToleranceMultiplier,heartbeatOutgoing:this.heartbeatOutgoing,heartbeatStrategy:this.heartbeatStrategy,splitLargeFrames:this.splitLargeFrames,maxWebSocketChunkSize:this.maxWebSocketChunkSize,forceBinaryWSFrames:this.forceBinaryWSFrames,logRawCommunication:this.logRawCommunication,appendMissingNULLonIncoming:this.appendMissingNULLonIncoming,discardWebsocketOnCommFailure:this.discardWebsocketOnCommFailure,onConnect:e=>{if(this._connectionWatcher&&(clearTimeout(this._connectionWatcher),this._connectionWatcher=void 0),this._nextReconnectDelay=this.reconnectDelay,!this.active)return this.debug("STOMP got connected while deactivate was issued, will disconnect now"),void this._disposeStompHandler();this.onConnect(e)},onDisconnect:e=>{this.onDisconnect(e)},onStompError:e=>{this.onStompError(e)},onWebSocketClose:e=>{this._stompHandler=void 0,this.state===T.DEACTIVATING&&this._changeState(T.INACTIVE),this.onWebSocketClose(e),this.active&&this._schedule_reconnect()},onWebSocketError:e=>{this.onWebSocketError(e)},onUnhandledMessage:e=>{this.onUnhandledMessage(e)},onUnhandledReceipt:e=>{this.onUnhandledReceipt(e)},onUnhandledFrame:e=>{this.onUnhandledFrame(e)},onHeartbeatReceived:()=>{this.onHeartbeatReceived()},onHeartbeatLost:()=>{this.onHeartbeatLost()}}),this._stompHandler.start()}_createWebSocket(){let e;if(this.webSocketFactory)e=this.webSocketFactory();else{if(!this.brokerURL)throw new Error("Either brokerURL or webSocketFactory must be provided");e=new WebSocket(this.brokerURL,this.stompVersions.protocolVersions())}return e.binaryType="arraybuffer",e}_schedule_reconnect(){this._nextReconnectDelay>0&&(this.debug(`STOMP: scheduling reconnection in ${this._nextReconnectDelay}ms`),this._reconnector=setTimeout(()=>{this.reconnectTimeMode===C.EXPONENTIAL&&(this._nextReconnectDelay=2*this._nextReconnectDelay,0!==this.maxReconnectDelay&&(this._nextReconnectDelay=Math.min(this._nextReconnectDelay,this.maxReconnectDelay))),this._connect()},this._nextReconnectDelay))}async deactivate(e={}){const t=e.force||!1,s=this.active;let i;if(this.state===T.INACTIVE)return this.debug("Already INACTIVE, nothing more to do"),Promise.resolve();if(this._changeState(T.DEACTIVATING),this._nextReconnectDelay=0,this._reconnector&&(clearTimeout(this._reconnector),this._reconnector=void 0),!this._stompHandler||this.webSocket.readyState===I.CLOSED)return this._changeState(T.INACTIVE),Promise.resolve();{const e=this._stompHandler.onWebSocketClose;i=new Promise((t,s)=>{this._stompHandler.onWebSocketClose=s=>{e(s),t()}})}return t?this._stompHandler?.discardWebsocket():s&&this._disposeStompHandler(),i}forceDisconnect(){this._stompHandler&&this._stompHandler.forceDisconnect()}_disposeStompHandler(){this._stompHandler&&this._stompHandler.dispose()}publish(e){this._checkConnection(),this._stompHandler.publish(e)}_checkConnection(){if(!this.connected)throw new TypeError("There is no underlying STOMP connection")}watchForReceipt(e,t){this._checkConnection(),this._stompHandler.watchForReceipt(e,t)}subscribe(e,t,s={}){return this._checkConnection(),this._stompHandler.subscribe(e,t,s)}unsubscribe(e,t={}){this._checkConnection(),this._stompHandler.unsubscribe(e,t)}begin(e){return this._checkConnection(),this._stompHandler.begin(e)}commit(e){this._checkConnection(),this._stompHandler.commit(e)}abort(e){this._checkConnection(),this._stompHandler.abort(e)}ack(e,t,s={}){this._checkConnection(),this._stompHandler.ack(e,t,s)}nack(e,t,s={}){this._checkConnection(),this._stompHandler.nack(e,t,s)}}var M="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function L(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var D,P,x,U,W,F,j={exports:{}},$={};function H(){if(x)return P;x=1;var e=(D||(D=1,M.crypto&&M.crypto.getRandomValues?$.randomBytes=function(e){var t=new Uint8Array(e);return M.crypto.getRandomValues(t),t}:$.randomBytes=function(e){for(var t=new Array(e),s=0;s<e;s++)t[s]=Math.floor(256*Math.random());return t}),$),t="abcdefghijklmnopqrstuvwxyz012345";return P={string:function(s){for(var i=e.randomBytes(s),n=[],r=0;r<s;r++)n.push(t.substr(i[r]%32,1));return n.join("")},number:function(e){return Math.floor(Math.random()*e)},numberString:function(e){var t=(""+(e-1)).length;return(new Array(t+1).join("0")+this.number(e)).slice(-t)}}}function B(){return U||(U=1,function(e){var t=H(),s={},i=!1,n=M.chrome&&M.chrome.app&&M.chrome.app.runtime;e.exports={attachEvent:function(e,t){void 0!==M.addEventListener?M.addEventListener(e,t,!1):M.document&&M.attachEvent&&(M.document.attachEvent("on"+e,t),M.attachEvent("on"+e,t))},detachEvent:function(e,t){void 0!==M.addEventListener?M.removeEventListener(e,t,!1):M.document&&M.detachEvent&&(M.document.detachEvent("on"+e,t),M.detachEvent("on"+e,t))},unloadAdd:function(e){if(n)return null;var r=t.string(8);return s[r]=e,i&&setTimeout(this.triggerUnloadCallbacks,0),r},unloadDel:function(e){e in s&&delete s[e]},triggerUnloadCallbacks:function(){for(var e in s)s[e](),delete s[e]}};n||e.exports.attachEvent("unload",function(){i||(i=!0,e.exports.triggerUnloadCallbacks())})}(j)),j.exports}var V,G,J,z,K,q={};function X(){if(J)return G;J=1;var e=F?W:(F=1,W=function(e,t){if(t=t.split(":")[0],!(e=+e))return!1;switch(t){case"http":case"ws":return 80!==e;case"https":case"wss":return 443!==e;case"ftp":return 21!==e;case"gopher":return 70!==e;case"file":return!1}return 0!==e}),t=function(){if(V)return q;V=1;var e=Object.prototype.hasOwnProperty;function t(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(e){return null}}function s(e){try{return encodeURIComponent(e)}catch(e){return null}}return q.stringify=function(t,i){i=i||"";var n,r,o=[];for(r in"string"!=typeof i&&(i="?"),t)if(e.call(t,r)){if((n=t[r])||null!=n&&!isNaN(n)||(n=""),r=s(r),n=s(n),null===r||null===n)continue;o.push(r+"="+n)}return o.length?i+o.join("&"):""},q.parse=function(e){for(var s,i=/([^=?#&]+)=?([^&]*)/g,n={};s=i.exec(e);){var r=t(s[1]),o=t(s[2]);null===r||null===o||r in n||(n[r]=o)}return n},q}(),s=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/,i=/[\n\r\t]/g,n=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,r=/:\d+$/,o=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,a=/^[a-zA-Z]:/;function c(e){return(e||"").toString().replace(s,"")}var l=[["#","hash"],["?","query"],function(e,t){return u(t.protocol)?e.replace(/\\/g,"/"):e},["/","pathname"],["@","auth",1],[NaN,"host",void 0,1,1],[/:(\d*)$/,"port",void 0,1],[NaN,"hostname",void 0,1,1]],h={hash:1,query:1};function d(e){var t,s=("undefined"!=typeof window?window:void 0!==M?M:"undefined"!=typeof self?self:{}).location||{},i={},r=typeof(e=e||s);if("blob:"===e.protocol)i=new g(unescape(e.pathname),{});else if("string"===r)for(t in i=new g(e,{}),h)delete i[t];else if("object"===r){for(t in e)t in h||(i[t]=e[t]);void 0===i.slashes&&(i.slashes=n.test(e.href))}return i}function u(e){return"file:"===e||"ftp:"===e||"http:"===e||"https:"===e||"ws:"===e||"wss:"===e}function p(e,t){e=(e=c(e)).replace(i,""),t=t||{};var s,n=o.exec(e),r=n[1]?n[1].toLowerCase():"",a=!!n[2],l=!!n[3],h=0;return a?l?(s=n[2]+n[3]+n[4],h=n[2].length+n[3].length):(s=n[2]+n[4],h=n[2].length):l?(s=n[3]+n[4],h=n[3].length):s=n[4],"file:"===r?h>=2&&(s=s.slice(2)):u(r)?s=n[4]:r?a&&(s=s.slice(2)):h>=2&&u(t.protocol)&&(s=n[4]),{protocol:r,slashes:a||u(r),slashesCount:h,rest:s}}function g(s,n,r){if(s=(s=c(s)).replace(i,""),!(this instanceof g))return new g(s,n,r);var o,h,m,f,b,_,y=l.slice(),E=typeof n,v=this,S=0;for("object"!==E&&"string"!==E&&(r=n,n=null),r&&"function"!=typeof r&&(r=t.parse),o=!(h=p(s||"",n=d(n))).protocol&&!h.slashes,v.slashes=h.slashes||o&&n.slashes,v.protocol=h.protocol||n.protocol||"",s=h.rest,("file:"===h.protocol&&(2!==h.slashesCount||a.test(s))||!h.slashes&&(h.protocol||h.slashesCount<2||!u(v.protocol)))&&(y[3]=[/(.*)/,"pathname"]);S<y.length;S++)"function"!=typeof(f=y[S])?(m=f[0],_=f[1],m!=m?v[_]=s:"string"==typeof m?~(b="@"===m?s.lastIndexOf(m):s.indexOf(m))&&("number"==typeof f[2]?(v[_]=s.slice(0,b),s=s.slice(b+f[2])):(v[_]=s.slice(b),s=s.slice(0,b))):(b=m.exec(s))&&(v[_]=b[1],s=s.slice(0,b.index)),v[_]=v[_]||o&&f[3]&&n[_]||"",f[4]&&(v[_]=v[_].toLowerCase())):s=f(s,v);r&&(v.query=r(v.query)),o&&n.slashes&&"/"!==v.pathname.charAt(0)&&(""!==v.pathname||""!==n.pathname)&&(v.pathname=function(e,t){if(""===e)return t;for(var s=(t||"/").split("/").slice(0,-1).concat(e.split("/")),i=s.length,n=s[i-1],r=!1,o=0;i--;)"."===s[i]?s.splice(i,1):".."===s[i]?(s.splice(i,1),o++):o&&(0===i&&(r=!0),s.splice(i,1),o--);return r&&s.unshift(""),"."!==n&&".."!==n||s.push(""),s.join("/")}(v.pathname,n.pathname)),"/"!==v.pathname.charAt(0)&&u(v.protocol)&&(v.pathname="/"+v.pathname),e(v.port,v.protocol)||(v.host=v.hostname,v.port=""),v.username=v.password="",v.auth&&(~(b=v.auth.indexOf(":"))?(v.username=v.auth.slice(0,b),v.username=encodeURIComponent(decodeURIComponent(v.username)),v.password=v.auth.slice(b+1),v.password=encodeURIComponent(decodeURIComponent(v.password))):v.username=encodeURIComponent(decodeURIComponent(v.auth)),v.auth=v.password?v.username+":"+v.password:v.username),v.origin="file:"!==v.protocol&&u(v.protocol)&&v.host?v.protocol+"//"+v.host:"null",v.href=v.toString()}return g.prototype={set:function(s,i,n){var o=this;switch(s){case"query":"string"==typeof i&&i.length&&(i=(n||t.parse)(i)),o[s]=i;break;case"port":o[s]=i,e(i,o.protocol)?i&&(o.host=o.hostname+":"+i):(o.host=o.hostname,o[s]="");break;case"hostname":o[s]=i,o.port&&(i+=":"+o.port),o.host=i;break;case"host":o[s]=i,r.test(i)?(i=i.split(":"),o.port=i.pop(),o.hostname=i.join(":")):(o.hostname=i,o.port="");break;case"protocol":o.protocol=i.toLowerCase(),o.slashes=!n;break;case"pathname":case"hash":if(i){var a="pathname"===s?"/":"#";o[s]=i.charAt(0)!==a?a+i:i}else o[s]=i;break;case"username":case"password":o[s]=encodeURIComponent(i);break;case"auth":var c=i.indexOf(":");~c?(o.username=i.slice(0,c),o.username=encodeURIComponent(decodeURIComponent(o.username)),o.password=i.slice(c+1),o.password=encodeURIComponent(decodeURIComponent(o.password))):o.username=encodeURIComponent(decodeURIComponent(i))}for(var h=0;h<l.length;h++){var d=l[h];d[4]&&(o[d[1]]=o[d[1]].toLowerCase())}return o.auth=o.password?o.username+":"+o.password:o.username,o.origin="file:"!==o.protocol&&u(o.protocol)&&o.host?o.protocol+"//"+o.host:"null",o.href=o.toString(),o},toString:function(e){e&&"function"==typeof e||(e=t.stringify);var s,i=this,n=i.host,o=i.protocol;o&&":"!==o.charAt(o.length-1)&&(o+=":");var a=o+(i.protocol&&i.slashes||u(i.protocol)?"//":"");return i.username?(a+=i.username,i.password&&(a+=":"+i.password),a+="@"):i.password?(a+=":"+i.password,a+="@"):"file:"!==i.protocol&&u(i.protocol)&&!n&&"/"!==i.pathname&&(a+="@"),(":"===n[n.length-1]||r.test(i.hostname)&&!i.port)&&(n+=":"),a+=n+i.pathname,(s="object"==typeof i.query?e(i.query):i.query)&&(a+="?"!==s.charAt(0)?"?"+s:s),i.hash&&(a+=i.hash),a}},g.extractProtocol=p,g.location=d,g.trimLeft=c,g.qs=t,G=g}function Y(){if(K)return z;K=1;var e=X();return z={getOrigin:function(t){if(!t)return null;var s=new e(t);if("file:"===s.protocol)return null;var i=s.port;return i||(i="https:"===s.protocol?"443":"80"),s.protocol+"//"+s.hostname+":"+i},isOriginEqual:function(e,t){return this.getOrigin(e)===this.getOrigin(t)},isSchemeEqual:function(e,t){return e.split(":")[0]===t.split(":")[0]},addPath:function(e,t){var s=e.split("?");return s[0]+t+(s[1]?"?"+s[1]:"")},addQuery:function(e,t){return e+(-1===e.indexOf("?")?"?"+t:"&"+t)},isLoopbackAddr:function(e){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(e)||/^\[::1\]$/.test(e)}}}var Q,Z={exports:{}};function ee(){return Q||(Q=1,"function"==typeof Object.create?Z.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:Z.exports=function(e,t){if(t){e.super_=t;var s=function(){};s.prototype=t.prototype,e.prototype=new s,e.prototype.constructor=e}}),Z.exports}var te,se,ie,ne={};function re(){if(se)return te;function e(){this._listeners={}}return se=1,e.prototype.addEventListener=function(e,t){e in this._listeners||(this._listeners[e]=[]);var s=this._listeners[e];-1===s.indexOf(t)&&(s=s.concat([t])),this._listeners[e]=s},e.prototype.removeEventListener=function(e,t){var s=this._listeners[e];if(s){var i=s.indexOf(t);-1===i||(s.length>1?this._listeners[e]=s.slice(0,i).concat(s.slice(i+1)):delete this._listeners[e])}},e.prototype.dispatchEvent=function(){var e=arguments[0],t=e.type,s=1===arguments.length?[e]:Array.apply(null,arguments);if(this["on"+t]&&this["on"+t].apply(this,s),t in this._listeners)for(var i=this._listeners[t],n=0;n<i.length;n++)i[n].apply(this,s)},te=e}function oe(){if(ie)return ne;ie=1;var e=ee(),t=re();function s(){t.call(this)}return e(s,t),s.prototype.removeAllListeners=function(e){e?delete this._listeners[e]:this._listeners={}},s.prototype.once=function(e,t){var s=this,i=!1;this.on(e,function n(){s.removeListener(e,n),i||(i=!0,t.apply(this,arguments))})},s.prototype.emit=function(){var e=arguments[0],t=this._listeners[e];if(t){for(var s=arguments.length,i=new Array(s-1),n=1;n<s;n++)i[n-1]=arguments[n];for(var r=0;r<t.length;r++)t[r].apply(this,i)}},s.prototype.on=s.prototype.addListener=t.prototype.addEventListener,s.prototype.removeListener=t.prototype.removeEventListener,ne.EventEmitter=s,ne}var ae,ce,le,he,de,ue,pe,ge,me,fe,be,_e,ye,Ee,ve,Se,we,Ie,Te,Ce,Re,Ae,Oe,ke,Ne,Me,Le,De,Pe,xe,Ue,We,Fe,je,$e,He={exports:{}};function Be(){if(le)return ce;le=1;var e=B(),t=Y(),s=ee(),i=oe().EventEmitter,n=function(){if(ae)return He.exports;ae=1;var e=M.WebSocket||M.MozWebSocket;return He.exports=e?function(t){return new e(t)}:void 0,He.exports}();function r(s,o,a){if(!r.enabled())throw new Error("Transport created when disabled");i.call(this);var c=this,l=t.addPath(s,"/websocket");l="https"===l.slice(0,5)?"wss"+l.slice(5):"ws"+l.slice(4),this.url=l,this.ws=new n(this.url,[],a),this.ws.onmessage=function(e){e.data,c.emit("message",e.data)},this.unloadRef=e.unloadAdd(function(){c.ws.close()}),this.ws.onclose=function(e){e.code,e.reason,c.emit("close",e.code,e.reason),c._cleanup()},this.ws.onerror=function(e){c.emit("close",1006,"WebSocket connection broken"),c._cleanup()}}return s(r,i),r.prototype.send=function(e){var t="["+e+"]";this.ws.send(t)},r.prototype.close=function(){var e=this.ws;this._cleanup(),e&&e.close()},r.prototype._cleanup=function(){var t=this.ws;t&&(t.onmessage=t.onclose=t.onerror=null),e.unloadDel(this.unloadRef),this.unloadRef=this.ws=null,this.removeAllListeners()},r.enabled=function(){return!!n},r.transportName="websocket",r.roundTrips=2,ce=r}function Ve(){if(me)return ge;me=1;var e=ee(),t=Y(),s=function(){if(de)return he;de=1;var e=ee(),t=oe().EventEmitter;function s(e,s){t.call(this),this.sendBuffer=[],this.sender=s,this.url=e}return e(s,t),s.prototype.send=function(e){this.sendBuffer.push(e),this.sendStop||this.sendSchedule()},s.prototype.sendScheduleWait=function(){var e,t=this;this.sendStop=function(){t.sendStop=null,clearTimeout(e)},e=setTimeout(function(){t.sendStop=null,t.sendSchedule()},25)},s.prototype.sendSchedule=function(){this.sendBuffer.length;var e=this;if(this.sendBuffer.length>0){var t="["+this.sendBuffer.join(",")+"]";this.sendStop=this.sender(this.url,t,function(t){e.sendStop=null,t?(e.emit("close",t.code||1006,"Sending error: "+t),e.close()):e.sendScheduleWait()}),this.sendBuffer=[]}},s.prototype._cleanup=function(){this.removeAllListeners()},s.prototype.close=function(){this._cleanup(),this.sendStop&&(this.sendStop(),this.sendStop=null)},he=s}(),i=function(){if(pe)return ue;pe=1;var e=ee(),t=oe().EventEmitter;function s(e,s,i){t.call(this),this.Receiver=e,this.receiveUrl=s,this.AjaxObject=i,this._scheduleReceiver()}return e(s,t),s.prototype._scheduleReceiver=function(){var e=this,t=this.poll=new this.Receiver(this.receiveUrl,this.AjaxObject);t.on("message",function(t){e.emit("message",t)}),t.once("close",function(s,i){e.pollIsClosing,e.poll=t=null,e.pollIsClosing||("network"===i?e._scheduleReceiver():(e.emit("close",s||1006,i),e.removeAllListeners()))})},s.prototype.abort=function(){this.removeAllListeners(),this.pollIsClosing=!0,this.poll&&this.poll.abort()},ue=s}();function n(e,n,r,o,a){var c=t.addPath(e,n),l=this;s.call(this,e,r),this.poll=new i(o,c,a),this.poll.on("message",function(e){l.emit("message",e)}),this.poll.once("close",function(e,t){l.poll=null,l.emit("close",e,t),l.close()})}return e(n,s),n.prototype.close=function(){s.prototype.close.call(this),this.removeAllListeners(),this.poll&&(this.poll.abort(),this.poll=null)},ge=n}function Ge(){if(be)return fe;be=1;var e=ee(),t=Y(),s=Ve();function i(e,i,n,r){s.call(this,e,i,function(e){return function(s,i,n){var r={};"string"==typeof i&&(r.headers={"Content-type":"text/plain"});var o=t.addPath(s,"/xhr_send"),a=new e("POST",o,i,r);return a.once("finish",function(e){if(a=null,200!==e&&204!==e)return n(new Error("http status "+e));n()}),function(){a.close(),a=null;var e=new Error("Aborted");e.code=1e3,n(e)}}}(r),n,r)}return e(i,s),fe=i}function Je(){if(ye)return _e;ye=1;var e=ee(),t=oe().EventEmitter;function s(e,s){t.call(this);var i=this;this.bufferPosition=0,this.xo=new s("POST",e,null),this.xo.on("chunk",this._chunkHandler.bind(this)),this.xo.once("finish",function(e,t){i._chunkHandler(e,t),i.xo=null;var s=200===e?"network":"permanent";i.emit("close",null,s),i._cleanup()})}return e(s,t),s.prototype._chunkHandler=function(e,t){if(200===e&&t)for(var s=-1;;this.bufferPosition+=s+1){var i=t.slice(this.bufferPosition);if(-1===(s=i.indexOf("\n")))break;var n=i.slice(0,s);n&&this.emit("message",n)}},s.prototype._cleanup=function(){this.removeAllListeners()},s.prototype.abort=function(){this.xo&&(this.xo.close(),this.emit("close",null,"user"),this.xo=null),this._cleanup()},_e=s}function ze(){if(ve)return Ee;ve=1;var e=oe().EventEmitter,t=ee(),s=B(),i=Y(),n=M.XMLHttpRequest;function r(t,s,i,n){var r=this;e.call(this),setTimeout(function(){r._start(t,s,i,n)},0)}t(r,e),r.prototype._start=function(e,t,o,a){var c=this;try{this.xhr=new n}catch(e){}if(!this.xhr)return this.emit("finish",0,"no xhr support"),void this._cleanup();t=i.addQuery(t,"t="+ +new Date),this.unloadRef=s.unloadAdd(function(){c._cleanup(!0)});try{this.xhr.open(e,t,!0),this.timeout&&"timeout"in this.xhr&&(this.xhr.timeout=this.timeout,this.xhr.ontimeout=function(){c.emit("finish",0,""),c._cleanup(!1)})}catch(e){return this.emit("finish",0,""),void this._cleanup(!1)}if(a&&a.noCredentials||!r.supportsCORS||(this.xhr.withCredentials=!0),a&&a.headers)for(var l in a.headers)this.xhr.setRequestHeader(l,a.headers[l]);this.xhr.onreadystatechange=function(){if(c.xhr){var e,t,s=c.xhr;switch(s.readyState,s.readyState){case 3:try{t=s.status,e=s.responseText}catch(e){}1223===t&&(t=204),200===t&&e&&e.length>0&&c.emit("chunk",t,e);break;case 4:1223===(t=s.status)&&(t=204),12005!==t&&12029!==t||(t=0),s.responseText,c.emit("finish",t,s.responseText),c._cleanup(!1)}}};try{c.xhr.send(o)}catch(e){c.emit("finish",0,""),c._cleanup(!1)}},r.prototype._cleanup=function(e){if(this.xhr){if(this.removeAllListeners(),s.unloadDel(this.unloadRef),this.xhr.onreadystatechange=function(){},this.xhr.ontimeout&&(this.xhr.ontimeout=null),e)try{this.xhr.abort()}catch(e){}this.unloadRef=this.xhr=null}},r.prototype.close=function(){this._cleanup(!0)},r.enabled=!!n;var o=["Active"].concat("Object").join("X");!r.enabled&&o in M&&(n=function(){try{return new M[o]("Microsoft.XMLHTTP")}catch(e){return null}},r.enabled=!!new n);var a=!1;try{a="withCredentials"in new n}catch(e){}return r.supportsCORS=a,Ee=r}function Ke(){if(we)return Se;we=1;var e=ee(),t=ze();function s(e,s,i,n){t.call(this,e,s,i,n)}return e(s,t),s.enabled=t.enabled&&t.supportsCORS,Se=s}function qe(){if(Te)return Ie;Te=1;var e=ee(),t=ze();function s(e,s,i){t.call(this,e,s,i,{noCredentials:!0})}return e(s,t),s.enabled=t.enabled,Ie=s}function Xe(){return Re?Ce:(Re=1,Ce={isOpera:function(){return M.navigator&&/opera/i.test(M.navigator.userAgent)},isKonqueror:function(){return M.navigator&&/konqueror/i.test(M.navigator.userAgent)},hasDomain:function(){if(!M.document)return!0;try{return!!M.document.domain}catch(e){return!1}}})}function Ye(){if(Oe)return Ae;Oe=1;var e=ee(),t=Ge(),s=Je(),i=Ke(),n=qe(),r=Xe();function o(e){if(!n.enabled&&!i.enabled)throw new Error("Transport created when disabled");t.call(this,e,"/xhr_streaming",s,i)}return e(o,t),o.enabled=function(e){return!e.nullOrigin&&(!r.isOpera()&&i.enabled)},o.transportName="xhr-streaming",o.roundTrips=2,o.needBody=!!M.document,Ae=o}function Qe(){if(Ne)return ke;Ne=1;var e=oe().EventEmitter,t=ee(),s=B(),i=Xe(),n=Y();function r(t,s,i){var n=this;e.call(this),setTimeout(function(){n._start(t,s,i)},0)}return t(r,e),r.prototype._start=function(e,t,i){var r=this,o=new M.XDomainRequest;t=n.addQuery(t,"t="+ +new Date),o.onerror=function(){r._error()},o.ontimeout=function(){r._error()},o.onprogress=function(){o.responseText,r.emit("chunk",200,o.responseText)},o.onload=function(){r.emit("finish",200,o.responseText),r._cleanup(!1)},this.xdr=o,this.unloadRef=s.unloadAdd(function(){r._cleanup(!0)});try{this.xdr.open(e,t),this.timeout&&(this.xdr.timeout=this.timeout),this.xdr.send(i)}catch(e){this._error()}},r.prototype._error=function(){this.emit("finish",0,""),this._cleanup(!1)},r.prototype._cleanup=function(e){if(this.xdr){if(this.removeAllListeners(),s.unloadDel(this.unloadRef),this.xdr.ontimeout=this.xdr.onerror=this.xdr.onprogress=this.xdr.onload=null,e)try{this.xdr.abort()}catch(e){}this.unloadRef=this.xdr=null}},r.prototype.close=function(){this._cleanup(!0)},r.enabled=!(!M.XDomainRequest||!i.hasDomain()),ke=r}function Ze(){if(Le)return Me;Le=1;var e=ee(),t=Ge(),s=Je(),i=Qe();function n(e){if(!i.enabled)throw new Error("Transport created when disabled");t.call(this,e,"/xhr_streaming",s,i)}return e(n,t),n.enabled=function(e){return!e.cookie_needed&&!e.nullOrigin&&(i.enabled&&e.sameScheme)},n.transportName="xdr-streaming",n.roundTrips=2,Me=n}function et(){return Pe?De:(Pe=1,De=M.EventSource)}function tt(){if(Fe)return We;Fe=1;var e=ee(),t=Ge(),s=function(){if(Ue)return xe;Ue=1;var e=ee(),t=oe().EventEmitter,s=et();function i(e){t.call(this);var i=this,n=this.es=new s(e);n.onmessage=function(e){e.data,i.emit("message",decodeURI(e.data))},n.onerror=function(e){n.readyState;var t=2!==n.readyState?"network":"permanent";i._cleanup(),i._close(t)}}return e(i,t),i.prototype.abort=function(){this._cleanup(),this._close("user")},i.prototype._cleanup=function(){var e=this.es;e&&(e.onmessage=e.onerror=null,e.close(),this.es=null)},i.prototype._close=function(e){var t=this;setTimeout(function(){t.emit("close",null,e),t.removeAllListeners()},200)},xe=i}(),i=Ke(),n=et();function r(e){if(!r.enabled())throw new Error("Transport created when disabled");t.call(this,e,"/eventsource",s,i)}return e(r,t),r.enabled=function(){return!!n},r.transportName="eventsource",r.roundTrips=2,We=r}function st(){return $e?je:($e=1,je="1.6.1")}var it,nt,rt,ot,at,ct,lt,ht,dt,ut,pt,gt,mt,ft,bt,_t,yt,Et,vt,St,wt,It,Tt,Ct={exports:{}};function Rt(){return it||(it=1,function(e){var t=B(),s=Xe();e.exports={WPrefix:"_jp",currentWindowId:null,polluteGlobalNamespace:function(){e.exports.WPrefix in M||(M[e.exports.WPrefix]={})},postMessage:function(t,s){M.parent!==M&&M.parent.postMessage(JSON.stringify({windowId:e.exports.currentWindowId,type:t,data:s||""}),"*")},createIframe:function(e,s){var i,n,r=M.document.createElement("iframe"),o=function(){clearTimeout(i);try{r.onload=null}catch(e){}r.onerror=null},a=function(){r&&(o(),setTimeout(function(){r&&r.parentNode.removeChild(r),r=null},0),t.unloadDel(n))},c=function(e){r&&(a(),s(e))};return r.src=e,r.style.display="none",r.style.position="absolute",r.onerror=function(){c("onerror")},r.onload=function(){clearTimeout(i),i=setTimeout(function(){c("onload timeout")},2e3)},M.document.body.appendChild(r),i=setTimeout(function(){c("timeout")},15e3),n=t.unloadAdd(a),{post:function(e,t){setTimeout(function(){try{r&&r.contentWindow&&r.contentWindow.postMessage(e,t)}catch(e){}},0)},cleanup:a,loaded:o}},createHtmlfile:function(s,i){var n,r,o,a=["Active"].concat("Object").join("X"),c=new M[a]("htmlfile"),l=function(){clearTimeout(n),o.onerror=null},h=function(){c&&(l(),t.unloadDel(r),o.parentNode.removeChild(o),o=c=null,CollectGarbage())},d=function(e){c&&(h(),i(e))};c.open(),c.write('<html><script>document.domain="'+M.document.domain+'";<\/script></html>'),c.close(),c.parentWindow[e.exports.WPrefix]=M[e.exports.WPrefix];var u=c.createElement("div");return c.body.appendChild(u),o=c.createElement("iframe"),u.appendChild(o),o.src=s,o.onerror=function(){d("onerror")},n=setTimeout(function(){d("timeout")},15e3),r=t.unloadAdd(h),{post:function(e,t){try{setTimeout(function(){o&&o.contentWindow&&o.contentWindow.postMessage(e,t)},0)}catch(e){}},cleanup:h,loaded:l}}},e.exports.iframeEnabled=!1,M.document&&(e.exports.iframeEnabled=("function"==typeof M.postMessage||"object"==typeof M.postMessage)&&!s.isKonqueror())}(Ct)),Ct.exports}function At(){if(rt)return nt;rt=1;var e=ee(),t=oe().EventEmitter,s=st(),i=Y(),n=Rt(),r=B(),o=H();function a(e,s,c){if(!a.enabled())throw new Error("Transport created when disabled");t.call(this);var l=this;this.origin=i.getOrigin(c),this.baseUrl=c,this.transUrl=s,this.transport=e,this.windowId=o.string(8);var h=i.addPath(c,"/iframe.html")+"#"+this.windowId;this.iframeObj=n.createIframe(h,function(e){l.emit("close",1006,"Unable to load an iframe ("+e+")"),l.close()}),this.onmessageCallback=this._message.bind(this),r.attachEvent("message",this.onmessageCallback)}return e(a,t),a.prototype.close=function(){if(this.removeAllListeners(),this.iframeObj){r.detachEvent("message",this.onmessageCallback);try{this.postMessage("c")}catch(e){}this.iframeObj.cleanup(),this.iframeObj=null,this.onmessageCallback=this.iframeObj=null}},a.prototype._message=function(e){if(e.data,!i.isOriginEqual(e.origin,this.origin))return e.origin,void this.origin;var t;try{t=JSON.parse(e.data)}catch(t){return void e.data}if(t.windowId!==this.windowId)return t.windowId,void this.windowId;switch(t.type){case"s":this.iframeObj.loaded(),this.postMessage("s",JSON.stringify([s,this.transport,this.transUrl,this.baseUrl]));break;case"t":this.emit("message",t.data);break;case"c":var n;try{n=JSON.parse(t.data)}catch(e){return void t.data}this.emit("close",n[0],n[1]),this.close()}},a.prototype.postMessage=function(e,t){this.iframeObj.post(JSON.stringify({windowId:this.windowId,type:e,data:t||""}),this.origin)},a.prototype.send=function(e){this.postMessage("m",e)},a.enabled=function(){return n.iframeEnabled},a.transportName="iframe",a.roundTrips=2,nt=a}function Ot(){return at||(at=1,ot={isObject:function(e){var t=typeof e;return"function"===t||"object"===t&&!!e},extend:function(e){if(!this.isObject(e))return e;for(var t,s,i=1,n=arguments.length;i<n;i++)for(s in t=arguments[i])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e}}),ot}function kt(){if(lt)return ct;lt=1;var e=ee(),t=At(),s=Ot();return ct=function(i){function n(e,s){t.call(this,i.transportName,e,s)}return e(n,t),n.enabled=function(e,n){if(!M.document)return!1;var r=s.extend({},n);return r.sameOrigin=!0,i.enabled(r)&&t.enabled()},n.transportName="iframe-"+i.transportName,n.needBody=!0,n.roundTrips=t.roundTrips+i.roundTrips-1,n.facadeTransport=i,n},ct}function Nt(){if(pt)return ut;pt=1;var e=ee(),t=function(){if(dt)return ht;dt=1;var e=ee(),t=Rt(),s=Y(),i=oe().EventEmitter,n=H();function r(e){i.call(this);var o=this;t.polluteGlobalNamespace(),this.id="a"+n.string(6),e=s.addQuery(e,"c="+decodeURIComponent(t.WPrefix+"."+this.id)),r.htmlfileEnabled;var a=r.htmlfileEnabled?t.createHtmlfile:t.createIframe;M[t.WPrefix][this.id]={start:function(){o.iframeObj.loaded()},message:function(e){o.emit("message",e)},stop:function(){o._cleanup(),o._close("network")}},this.iframeObj=a(e,function(){o._cleanup(),o._close("permanent")})}e(r,i),r.prototype.abort=function(){this._cleanup(),this._close("user")},r.prototype._cleanup=function(){this.iframeObj&&(this.iframeObj.cleanup(),this.iframeObj=null),delete M[t.WPrefix][this.id]},r.prototype._close=function(e){this.emit("close",null,e),this.removeAllListeners()},r.htmlfileEnabled=!1;var o=["Active"].concat("Object").join("X");if(o in M)try{r.htmlfileEnabled=!!new M[o]("htmlfile")}catch(e){}return r.enabled=r.htmlfileEnabled||t.iframeEnabled,ht=r}(),s=qe(),i=Ge();function n(e){if(!t.enabled)throw new Error("Transport created when disabled");i.call(this,e,"/htmlfile",t,s)}return e(n,i),n.enabled=function(e){return t.enabled&&e.sameOrigin},n.transportName="htmlfile",n.roundTrips=2,ut=n}function Mt(){if(mt)return gt;mt=1;var e=ee(),t=Ge(),s=Je(),i=Ke(),n=qe();function r(e){if(!n.enabled&&!i.enabled)throw new Error("Transport created when disabled");t.call(this,e,"/xhr",s,i)}return e(r,t),r.enabled=function(e){return!e.nullOrigin&&(!(!n.enabled||!e.sameOrigin)||i.enabled)},r.transportName="xhr-polling",r.roundTrips=2,gt=r}function Lt(){if(bt)return ft;bt=1;var e=ee(),t=Ge(),s=Ze(),i=Je(),n=Qe();function r(e){if(!n.enabled)throw new Error("Transport created when disabled");t.call(this,e,"/xhr",i,n)}return e(r,t),r.enabled=s.enabled,r.transportName="xdr-polling",r.roundTrips=2,ft=r}function Dt(){if(vt)return Et;vt=1;var e,t,s=H(),i=Y();return Et=function(n,r,o){e||((e=M.document.createElement("form")).style.display="none",e.style.position="absolute",e.method="POST",e.enctype="application/x-www-form-urlencoded",e.acceptCharset="UTF-8",(t=M.document.createElement("textarea")).name="d",e.appendChild(t),M.document.body.appendChild(e));var a="a"+s.string(8);e.target=a,e.action=i.addQuery(i.addPath(n,"/jsonp_send"),"i="+a);var c=function(e){try{return M.document.createElement('<iframe name="'+e+'">')}catch(s){var t=M.document.createElement("iframe");return t.name=e,t}}(a);c.id=a,c.style.display="none",e.appendChild(c);try{t.value=r}catch(e){}e.submit();var l=function(e){c.onerror&&(c.onreadystatechange=c.onerror=c.onload=null,setTimeout(function(){c.parentNode.removeChild(c),c=null},500),t.value="",o(e))};return c.onerror=function(){l()},c.onload=function(){l()},c.onreadystatechange=function(e){c.readyState,"complete"===c.readyState&&l()},function(){l(new Error("Aborted"))}},Et}function Pt(){if(wt)return St;wt=1;var e=ee(),t=Ve(),s=function(){if(yt)return _t;yt=1;var e=Rt(),t=H(),s=Xe(),i=Y(),n=ee(),r=oe().EventEmitter;function o(s){var n=this;r.call(this),e.polluteGlobalNamespace(),this.id="a"+t.string(6);var a=i.addQuery(s,"c="+encodeURIComponent(e.WPrefix+"."+this.id));M[e.WPrefix][this.id]=this._callback.bind(this),this._createScript(a),this.timeoutId=setTimeout(function(){n._abort(new Error("JSONP script loaded abnormally (timeout)"))},o.timeout)}return n(o,r),o.prototype.abort=function(){if(M[e.WPrefix][this.id]){var t=new Error("JSONP user aborted read");t.code=1e3,this._abort(t)}},o.timeout=35e3,o.scriptErrorTimeout=1e3,o.prototype._callback=function(e){this._cleanup(),this.aborting||(e&&this.emit("message",e),this.emit("close",null,"network"),this.removeAllListeners())},o.prototype._abort=function(e){this._cleanup(),this.aborting=!0,this.emit("close",e.code,e.message),this.removeAllListeners()},o.prototype._cleanup=function(){if(clearTimeout(this.timeoutId),this.script2&&(this.script2.parentNode.removeChild(this.script2),this.script2=null),this.script){var t=this.script;t.parentNode.removeChild(t),t.onreadystatechange=t.onerror=t.onload=t.onclick=null,this.script=null}delete M[e.WPrefix][this.id]},o.prototype._scriptError=function(){var e=this;this.errorTimer||(this.errorTimer=setTimeout(function(){e.loadedOkay||e._abort(new Error("JSONP script loaded abnormally (onerror)"))},o.scriptErrorTimeout))},o.prototype._createScript=function(e){var i,n=this,r=this.script=M.document.createElement("script");if(r.id="a"+t.string(8),r.src=e,r.type="text/javascript",r.charset="UTF-8",r.onerror=this._scriptError.bind(this),r.onload=function(){n._abort(new Error("JSONP script loaded abnormally (onload)"))},r.onreadystatechange=function(){if(r.readyState,/loaded|closed/.test(r.readyState)){if(r&&r.htmlFor&&r.onclick){n.loadedOkay=!0;try{r.onclick()}catch(e){}}r&&n._abort(new Error("JSONP script loaded abnormally (onreadystatechange)"))}},void 0===r.async&&M.document.attachEvent)if(s.isOpera())(i=this.script2=M.document.createElement("script")).text="try{var a = document.getElementById('"+r.id+"'); if(a)a.onerror();}catch(x){};",r.async=i.async=!1;else{try{r.htmlFor=r.id,r.event="onclick"}catch(e){}r.async=!0}void 0!==r.async&&(r.async=!0);var o=M.document.getElementsByTagName("head")[0];o.insertBefore(r,o.firstChild),i&&o.insertBefore(i,o.firstChild)},_t=o}(),i=Dt();function n(e){if(!n.enabled())throw new Error("Transport created when disabled");t.call(this,e,"/jsonp",i,s)}return e(n,t),n.enabled=function(){return!!M.document},n.transportName="jsonp-polling",n.roundTrips=1,n.needBody=!0,St=n}function xt(){return Tt?It:(Tt=1,It=[Be(),Ye(),Ze(),tt(),kt()(tt()),Nt(),kt()(Nt()),Mt(),Lt(),kt()(Mt()),Pt()])}var Ut,Wt,Ft,jt,$t,Ht,Bt,Vt,Gt,Jt,zt,Kt,qt,Xt,Yt,Qt,Zt,es,ts,ss,is,ns,rs,os,as,cs,ls,hs,ds,us,ps,gs,ms,fs={};function bs(){if(Ut)return fs;Ut=1;var e,t=Array.prototype,s=Object.prototype,i=Function.prototype,n=String.prototype,r=t.slice,o=s.toString,a=function(e){return"[object Function]"===s.toString.call(e)},c=function(e){return"[object String]"===o.call(e)},l=Object.defineProperty&&function(){try{return Object.defineProperty({},"x",{}),!0}catch(e){return!1}}();e=l?function(e,t,s,i){!i&&t in e||Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:!0,value:s})}:function(e,t,s,i){!i&&t in e||(e[t]=s)};var h=function(t,i,n){for(var r in i)s.hasOwnProperty.call(i,r)&&e(t,r,i[r],n)},d=function(e){if(null==e)throw new TypeError("can't convert "+e+" to object");return Object(e)};function u(){}h(i,{bind:function(e){var t=this;if(!a(t))throw new TypeError("Function.prototype.bind called on incompatible "+t);for(var s=r.call(arguments,1),i=Math.max(0,t.length-s.length),n=[],o=0;o<i;o++)n.push("$"+o);var c=Function("binder","return function ("+n.join(",")+"){ return binder.apply(this, arguments); }")(function(){if(this instanceof c){var i=t.apply(this,s.concat(r.call(arguments)));return Object(i)===i?i:this}return t.apply(e,s.concat(r.call(arguments)))});return t.prototype&&(u.prototype=t.prototype,c.prototype=new u,u.prototype=null),c}}),h(Array,{isArray:function(e){return"[object Array]"===o.call(e)}});var p,g,m,f=Object("a"),b="a"!==f[0]||!(0 in f);h(t,{forEach:function(e){var t=d(this),s=b&&c(this)?this.split(""):t,i=arguments[1],n=-1,r=s.length>>>0;if(!a(e))throw new TypeError;for(;++n<r;)n in s&&e.call(i,s[n],n,t)}},(p=t.forEach,g=!0,m=!0,p&&(p.call("foo",function(e,t,s){"object"!=typeof s&&(g=!1)}),p.call([1],function(){m="string"==typeof this},"x")),!(p&&g&&m)));var _=Array.prototype.indexOf&&-1!==[0,1].indexOf(1,2);h(t,{indexOf:function(e){var t=b&&c(this)?this.split(""):d(this),s=t.length>>>0;if(!s)return-1;var i,n=0;for(arguments.length>1&&((i=+arguments[1])!=i?i=0:0!==i&&i!==1/0&&i!==-1/0&&(i=(i>0||-1)*Math.floor(Math.abs(i))),n=i),n=n>=0?n:Math.max(0,s+n);n<s;n++)if(n in t&&t[n]===e)return n;return-1}},_);var y,E=n.split;2!=="ab".split(/(?:ab)*/).length||4!==".".split(/(.?)(.?)/).length||"t"==="tesst".split(/(s)*/)[1]||4!=="test".split(/(?:)/,-1).length||"".split(/.?/).length||".".split(/()()/).length>1?(y=void 0===/()??/.exec("")[1],n.split=function(e,s){var i=this;if(void 0===e&&0===s)return[];if("[object RegExp]"!==o.call(e))return E.call(this,e,s);var n,r,a,c,l=[],h=(e.ignoreCase?"i":"")+(e.multiline?"m":"")+(e.extended?"x":"")+(e.sticky?"y":""),d=0;for(e=new RegExp(e.source,h+"g"),i+="",y||(n=new RegExp("^"+e.source+"$(?!\\s)",h)),s=void 0===s?-1>>>0:s>>>0;(r=e.exec(i))&&!((a=r.index+r[0].length)>d&&(l.push(i.slice(d,r.index)),!y&&r.length>1&&r[0].replace(n,function(){for(var e=1;e<arguments.length-2;e++)void 0===arguments[e]&&(r[e]=void 0)}),r.length>1&&r.index<i.length&&t.push.apply(l,r.slice(1)),c=r[0].length,d=a,l.length>=s));)e.lastIndex===r.index&&e.lastIndex++;return d===i.length?!c&&e.test("")||l.push(""):l.push(i.slice(d)),l.length>s?l.slice(0,s):l}):"0".split(void 0,0).length&&(n.split=function(e,t){return void 0===e&&0===t?[]:E.call(this,e,t)});var v=n.substr,S="".substr&&"b"!=="0b".substr(-1);return h(n,{substr:function(e,t){return v.call(this,e<0&&(e=this.length+e)<0?0:e,t)}},S),fs}function _s(){if(Ft)return Wt;Ft=1;var e,t=/[\x00-\x1f\ud800-\udfff\ufffe\uffff\u0300-\u0333\u033d-\u0346\u034a-\u034c\u0350-\u0352\u0357-\u0358\u035c-\u0362\u0374\u037e\u0387\u0591-\u05af\u05c4\u0610-\u0617\u0653-\u0654\u0657-\u065b\u065d-\u065e\u06df-\u06e2\u06eb-\u06ec\u0730\u0732-\u0733\u0735-\u0736\u073a\u073d\u073f-\u0741\u0743\u0745\u0747\u07eb-\u07f1\u0951\u0958-\u095f\u09dc-\u09dd\u09df\u0a33\u0a36\u0a59-\u0a5b\u0a5e\u0b5c-\u0b5d\u0e38-\u0e39\u0f43\u0f4d\u0f52\u0f57\u0f5c\u0f69\u0f72-\u0f76\u0f78\u0f80-\u0f83\u0f93\u0f9d\u0fa2\u0fa7\u0fac\u0fb9\u1939-\u193a\u1a17\u1b6b\u1cda-\u1cdb\u1dc0-\u1dcf\u1dfc\u1dfe\u1f71\u1f73\u1f75\u1f77\u1f79\u1f7b\u1f7d\u1fbb\u1fbe\u1fc9\u1fcb\u1fd3\u1fdb\u1fe3\u1feb\u1fee-\u1fef\u1ff9\u1ffb\u1ffd\u2000-\u2001\u20d0-\u20d1\u20d4-\u20d7\u20e7-\u20e9\u2126\u212a-\u212b\u2329-\u232a\u2adc\u302b-\u302c\uaab2-\uaab3\uf900-\ufa0d\ufa10\ufa12\ufa15-\ufa1e\ufa20\ufa22\ufa25-\ufa26\ufa2a-\ufa2d\ufa30-\ufa6d\ufa70-\ufad9\ufb1d\ufb1f\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufb4e\ufff0-\uffff]/g;return Wt={quote:function(s){var i=JSON.stringify(s);return t.lastIndex=0,t.test(i)?(e||(e=function(e){var t,s={},i=[];for(t=0;t<65536;t++)i.push(String.fromCharCode(t));return e.lastIndex=0,i.join("").replace(e,function(e){return s[e]="\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4),""}),e.lastIndex=0,s}(t)),i.replace(t,function(t){return e[t]})):i}}}function ys(){if($t)return jt;$t=1;return jt=function(e){return{filterToEnabled:function(t,s){var i={main:[],facade:[]};return t?"string"==typeof t&&(t=[t]):t=[],e.forEach(function(e){e&&("websocket"===e.transportName&&!1===s.websocket||(t.length&&-1===t.indexOf(e.transportName)?e.transportName:e.enabled(s)?(e.transportName,i.main.push(e),e.facadeTransport&&i.facade.push(e.facadeTransport)):e.transportName))}),i}}}}function Es(){if(Bt)return Ht;Bt=1;var e={};return["log","debug","warn"].forEach(function(t){var s;try{s=M.console&&M.console[t]&&M.console[t].apply}catch(e){}e[t]=s?function(){return M.console[t].apply(M.console,arguments)}:"log"===t?function(){}:e.log}),Ht=e}function vs(){if(Gt)return Vt;function e(e){this.type=e}return Gt=1,e.prototype.initEvent=function(e,t,s){return this.type=e,this.bubbles=t,this.cancelable=s,this.timeStamp=+new Date,this},e.prototype.stopPropagation=function(){},e.prototype.preventDefault=function(){},e.CAPTURING_PHASE=1,e.AT_TARGET=2,e.BUBBLING_PHASE=3,Vt=e}function Ss(){return zt?Jt:(zt=1,Jt=M.location||{origin:"http://localhost:80",protocol:"http:",host:"localhost",port:80,href:"http://localhost/",hash:""})}function ws(){if(ts)return es;ts=1;var e=oe().EventEmitter,t=ee(),s=Ot();function i(t,i){e.call(this);var n=this,r=+new Date;this.xo=new i("GET",t),this.xo.once("finish",function(e,t){var i,o;if(200===e){if(o=+new Date-r,t)try{i=JSON.parse(t)}catch(e){}s.isObject(i)||(i={})}n.emit("finish",i,o),n.removeAllListeners()})}return t(i,e),i.prototype.close=function(){this.removeAllListeners(),this.xo.close()},es=i}function Is(){if(is)return ss;is=1;var e=ee(),t=oe().EventEmitter,s=qe(),i=ws();function n(e){var n=this;t.call(this),this.ir=new i(e,s),this.ir.once("finish",function(e,t){n.ir=null,n.emit("message",JSON.stringify([e,t]))})}return e(n,t),n.transportName="iframe-info-receiver",n.prototype.close=function(){this.ir&&(this.ir.close(),this.ir=null),this.removeAllListeners()},ss=n}function Ts(){if(as)return os;as=1;var e=oe().EventEmitter,t=ee(),s=Y(),i=Qe(),n=Ke(),r=qe(),o=function(){if(Zt)return Qt;Zt=1;var e=oe().EventEmitter;function t(){var s=this;e.call(this),this.to=setTimeout(function(){s.emit("finish",200,"{}")},t.timeout)}return ee()(t,e),t.prototype.close=function(){clearTimeout(this.to)},t.timeout=2e3,Qt=t}(),a=function(){if(rs)return ns;rs=1;var e=oe().EventEmitter,t=ee(),s=B(),i=At(),n=Is();function r(t,r){var o=this;e.call(this);var a=function(){var e=o.ifr=new i(n.transportName,r,t);e.once("message",function(e){if(e){var t;try{t=JSON.parse(e)}catch(e){return o.emit("finish"),void o.close()}var s=t[0],i=t[1];o.emit("finish",s,i)}o.close()}),e.once("close",function(){o.emit("finish"),o.close()})};M.document.body?a():s.attachEvent("load",a)}return t(r,e),r.enabled=function(){return i.enabled()},r.prototype.close=function(){this.ifr&&this.ifr.close(),this.removeAllListeners(),this.ifr=null},ns=r}(),c=ws();function l(t,s){var i=this;e.call(this),setTimeout(function(){i.doXhr(t,s)},0)}return t(l,e),l._getReceiver=function(e,t,s){return s.sameOrigin?new c(t,r):n.enabled?new c(t,n):i.enabled&&s.sameScheme?new c(t,i):a.enabled()?new a(e,t):new c(t,o)},l.prototype.doXhr=function(e,t){var i=this,n=s.addPath(e,"/info");this.xo=l._getReceiver(e,n,t),this.timeoutRef=setTimeout(function(){i._cleanup(!1),i.emit("finish")},l.timeout),this.xo.once("finish",function(e,t){i._cleanup(!0),i.emit("finish",e,t)})},l.prototype._cleanup=function(e){clearTimeout(this.timeoutRef),this.timeoutRef=null,!e&&this.xo&&this.xo.close(),this.xo=null},l.prototype.close=function(){this.removeAllListeners(),this._cleanup(!1)},l.timeout=8e3,os=l}function Cs(){if(ds)return hs;ds=1;var e=Y(),t=B(),s=function(){if(ls)return cs;ls=1;var e=Rt();function t(e){this._transport=e,e.on("message",this._transportMessage.bind(this)),e.on("close",this._transportClose.bind(this))}return t.prototype._transportClose=function(t,s){e.postMessage("c",JSON.stringify([t,s]))},t.prototype._transportMessage=function(t){e.postMessage("t",t)},t.prototype._send=function(e){this._transport.send(e)},t.prototype._close=function(){this._transport.close(),this._transport.removeAllListeners()},cs=t}(),i=Is(),n=Rt(),r=Ss();return hs=function(o,a){var c,l={};a.forEach(function(e){e.facadeTransport&&(l[e.facadeTransport.transportName]=e.facadeTransport)}),l[i.transportName]=i,o.bootstrap_iframe=function(){var i;n.currentWindowId=r.hash.slice(1);t.attachEvent("message",function(t){if(t.source===parent&&(void 0===c&&(c=t.origin),t.origin===c)){var a;try{a=JSON.parse(t.data)}catch(e){return void t.data}if(a.windowId===n.currentWindowId)switch(a.type){case"s":var h;try{h=JSON.parse(a.data)}catch(e){a.data;break}var d=h[0],u=h[1],p=h[2],g=h[3];if(d!==o.version)throw new Error('Incompatible SockJS! Main site uses: "'+d+'", the iframe: "'+o.version+'".');if(!e.isOriginEqual(p,r.href)||!e.isOriginEqual(g,r.href))throw new Error("Can't connect to different domain from within an iframe. ("+r.href+", "+p+", "+g+")");i=new s(new l[u](p,g));break;case"m":i._send(a.data);break;case"c":i&&i._close(),i=null}}}),n.postMessage("s")}},hs}function Rs(){if(ps)return us;ps=1,bs();var e,t=X(),s=ee(),i=H(),n=_s(),r=Y(),o=B(),a=ys(),c=Ot(),l=Xe(),h=Es(),d=vs(),u=re(),p=Ss(),g=function(){if(qt)return Kt;qt=1;var e=ee(),t=vs();function s(){t.call(this),this.initEvent("close",!1,!1),this.wasClean=!1,this.code=0,this.reason=""}return e(s,t),Kt=s}(),m=function(){if(Yt)return Xt;Yt=1;var e=ee(),t=vs();function s(e){t.call(this),this.initEvent("message",!1,!1),this.data=e}return e(s,t),Xt=s}(),f=Ts(),b=function(){};function _(e,s,n){if(!(this instanceof _))return new _(e,s,n);if(arguments.length<1)throw new TypeError("Failed to construct 'SockJS: 1 argument required, but only 0 present");u.call(this),this.readyState=_.CONNECTING,this.extensions="",this.protocol="",(n=n||{}).protocols_whitelist&&h.warn("'protocols_whitelist' is DEPRECATED. Use 'transports' instead."),this._transportsWhitelist=n.transports,this._transportOptions=n.transportOptions||{},this._timeout=n.timeout||0;var o=n.sessionId||8;if("function"==typeof o)this._generateSessionId=o;else{if("number"!=typeof o)throw new TypeError("If sessionId is used in the options, it needs to be a number or a function.");this._generateSessionId=function(){return i.string(o)}}this._server=n.server||i.numberString(1e3);var a=new t(e);if(!a.host||!a.protocol)throw new SyntaxError("The URL '"+e+"' is invalid");if(a.hash)throw new SyntaxError("The URL must not contain a fragment");if("http:"!==a.protocol&&"https:"!==a.protocol)throw new SyntaxError("The URL's scheme must be either 'http:' or 'https:'. '"+a.protocol+"' is not allowed.");var c="https:"===a.protocol;if("https:"===p.protocol&&!c&&!r.isLoopbackAddr(a.hostname))throw new Error("SecurityError: An insecure SockJS connection may not be initiated from a page loaded over HTTPS");s?Array.isArray(s)||(s=[s]):s=[];var d=s.sort();d.forEach(function(e,t){if(!e)throw new SyntaxError("The protocols entry '"+e+"' is invalid.");if(t<d.length-1&&e===d[t+1])throw new SyntaxError("The protocols entry '"+e+"' is duplicated.")});var g=r.getOrigin(p.href);this._origin=g?g.toLowerCase():null,a.set("pathname",a.pathname.replace(/\/+$/,"")),this.url=a.href,this.url,this._urlInfo={nullOrigin:!l.hasDomain(),sameOrigin:r.isOriginEqual(this.url,p.href),sameScheme:r.isSchemeEqual(this.url,p.href)},this._ir=new f(this.url,this._urlInfo),this._ir.once("finish",this._receiveInfo.bind(this))}function y(e){return 1e3===e||e>=3e3&&e<=4999}return s(_,u),_.prototype.close=function(e,t){if(e&&!y(e))throw new Error("InvalidAccessError: Invalid code");if(t&&t.length>123)throw new SyntaxError("reason argument has an invalid length");if(this.readyState!==_.CLOSING&&this.readyState!==_.CLOSED){this._close(e||1e3,t||"Normal closure",!0)}},_.prototype.send=function(e){if("string"!=typeof e&&(e=""+e),this.readyState===_.CONNECTING)throw new Error("InvalidStateError: The connection has not been established yet");this.readyState===_.OPEN&&this._transport.send(n.quote(e))},_.version=st(),_.CONNECTING=0,_.OPEN=1,_.CLOSING=2,_.CLOSED=3,_.prototype._receiveInfo=function(t,s){if(this._ir=null,t){this._rto=this.countRTO(s),this._transUrl=t.base_url?t.base_url:this.url,t=c.extend(t,this._urlInfo);var i=e.filterToEnabled(this._transportsWhitelist,t);this._transports=i.main,this._transports.length,this._connect()}else this._close(1002,"Cannot connect to server")},_.prototype._connect=function(){for(var e=this._transports.shift();e;e=this._transports.shift()){if(b(e.transportName),e.needBody&&(!M.document.body||void 0!==M.document.readyState&&"complete"!==M.document.readyState&&"interactive"!==M.document.readyState))return this._transports.unshift(e),void o.attachEvent("load",this._connect.bind(this));var t=Math.max(this._timeout,this._rto*e.roundTrips||5e3);this._transportTimeoutId=setTimeout(this._transportTimeout.bind(this),t);var s=r.addPath(this._transUrl,"/"+this._server+"/"+this._generateSessionId()),i=this._transportOptions[e.transportName],n=new e(s,this._transUrl,i);return n.on("message",this._transportMessage.bind(this)),n.once("close",this._transportClose.bind(this)),n.transportName=e.transportName,void(this._transport=n)}this._close(2e3,"All transports failed",!1)},_.prototype._transportTimeout=function(){this.readyState===_.CONNECTING&&(this._transport&&this._transport.close(),this._transportClose(2007,"Transport timed out"))},_.prototype._transportMessage=function(e){var t,s=this,i=e.slice(0,1),n=e.slice(1);switch(i){case"o":return void this._open();case"h":return this.dispatchEvent(new d("heartbeat")),void this.transport}if(n)try{t=JSON.parse(n)}catch(e){}if(void 0!==t)switch(i){case"a":Array.isArray(t)&&t.forEach(function(e){s.transport,s.dispatchEvent(new m(e))});break;case"m":this.transport,this.dispatchEvent(new m(t));break;case"c":Array.isArray(t)&&2===t.length&&this._close(t[0],t[1],!0)}},_.prototype._transportClose=function(e,t){this.transport,this._transport&&(this._transport.removeAllListeners(),this._transport=null,this.transport=null),y(e)||2e3===e||this.readyState!==_.CONNECTING?this._close(e,t):this._connect()},_.prototype._open=function(){this._transport&&this._transport.transportName,this.readyState,this.readyState===_.CONNECTING?(this._transportTimeoutId&&(clearTimeout(this._transportTimeoutId),this._transportTimeoutId=null),this.readyState=_.OPEN,this.transport=this._transport.transportName,this.dispatchEvent(new d("open")),this.transport):this._close(1006,"Server lost session")},_.prototype._close=function(e,t,s){this.transport,this.readyState;var i=!1;if(this._ir&&(i=!0,this._ir.close(),this._ir=null),this._transport&&(this._transport.close(),this._transport=null,this.transport=null),this.readyState===_.CLOSED)throw new Error("InvalidStateError: SockJS has already been closed");this.readyState=_.CLOSING,setTimeout(function(){this.readyState=_.CLOSED,i&&this.dispatchEvent(new d("error"));var n=new g("close");n.wasClean=s||!1,n.code=e||1e3,n.reason=t,this.dispatchEvent(n),this.onmessage=this.onclose=this.onerror=null}.bind(this),0)},_.prototype.countRTO=function(e){return e>100?4*e:300+e},us=function(t){return e=a(t),Cs()(_,t),_}}var As=function(){if(ms)return gs;ms=1;var e=xt();return gs=Rs()(e),"_sockjs_onload"in M&&setTimeout(M._sockjs_onload,1),gs}(),Os=L(As);const ks=()=>"undefined"!=typeof window&&window.StompJs&&window.StompJs.Client?window.StompJs.Client:N,Ns=()=>"undefined"!=typeof window&&window.SockJS?window.SockJS:Os;class Ms extends t{constructor(e){super(),this.serverUrl=e.serverUrl.replace(/\/$/,""),this.jwtToken=e.jwtToken,this.apiKey=e.apiKey,this.projectId=e.projectId,this.useSockJS=!1!==e.useSockJS,this.reconnectDelay=e.reconnectDelay||h.reconnectDelay,this.maxReconnectAttempts=e.maxReconnectAttempts||h.maxReconnectAttempts,this.heartbeatIncoming=e.heartbeatIncoming||h.heartbeatIncoming,this.heartbeatOutgoing=e.heartbeatOutgoing||h.heartbeatOutgoing,this.logger=new p(e.logLevel||u.WARN,"ConnectionManager"),this.state=s.DISCONNECTED,this.stompClient=null,this.reconnectAttempts=0,this.subscriptions=new Map,this.pendingSubscriptions=[],this.userId=null}_setState(e){const t=this.state;this.state=e,this.emit("stateChange",{state:e,prevState:t}),this.logger.info(`State changed: ${t} -> ${e}`)}_getWebSocketUrl(){const e=this.useSockJS?a.SOCKJS_ENDPOINT:a.NATIVE_ENDPOINT;return`${this.serverUrl}${e}`}_createStompClient(){const e=this._getWebSocketUrl(),t={connectHeaders:{Authorization:this.jwtToken.startsWith("Bearer ")?this.jwtToken:`Bearer ${this.jwtToken}`,"X-API-KEY":this.apiKey,"X-PROJECT-ID":this.projectId},heartbeatIncoming:this.heartbeatIncoming,heartbeatOutgoing:this.heartbeatOutgoing,reconnectDelay:this.reconnectDelay,debug:e=>{this.logger.level<=u.DEBUG&&this.logger.debug("STOMP:",e)},onConnect:e=>this._onConnect(e),onDisconnect:e=>this._onDisconnect(e),onStompError:e=>this._onStompError(e),onWebSocketClose:e=>this._onWebSocketClose(e),onWebSocketError:e=>this._onWebSocketError(e)};if(this.useSockJS){const s=Ns();t.webSocketFactory=()=>new s(e)}else{const e=this.serverUrl.startsWith("https")?"wss":"ws",s=this.serverUrl.replace(/^https?:\/\//,"");t.brokerURL=`${e}://${s}${a.NATIVE_ENDPOINT}`}return new(ks())(t)}async connect(){if(this.state!==s.CONNECTED){if(this.state!==s.CONNECTING)return this._setState(s.CONNECTING),this.reconnectAttempts=0,new Promise((e,t)=>{this._connectResolve=e,this._connectReject=t;try{this.stompClient=this._createStompClient(),this.stompClient.activate()}catch(e){this._setState(s.ERROR),this._drainPendingSubscriptions("Connection activation failed"),t(e)}});this.logger.warn("Connection in progress")}else this.logger.warn("Already connected")}_onConnect(e){this._setState(s.CONNECTED),this.reconnectAttempts=0,this.logger.info("Connected to server",e),this._restoreSubscriptions(),this._processPendingSubscriptions(),this.emit("connected",{frame:e}),this._connectResolve&&(this._connectResolve(),this._connectResolve=null,this._connectReject=null)}_onDisconnect(e){this.logger.info("Disconnected from server",e),this._setState(s.DISCONNECTED),this.emit("disconnected",{frame:e})}_onStompError(e){this.logger.error("STOMP error:",e),this._setState(s.ERROR);const t={type:i.CONNECTION_FAILED,message:e.headers?.message||"STOMP error",frame:e};this._drainPendingSubscriptions(`STOMP error: ${t.message}`),this.emit("error",t),this._connectReject&&(this._connectReject(new Error(t.message)),this._connectResolve=null,this._connectReject=null)}_onWebSocketClose(e){this.logger.warn("WebSocket closed:",e),this.state!==s.DISCONNECTED&&this._handleReconnect()}_onWebSocketError(e){this.logger.error("WebSocket error:",e),this._connectReject&&(this._drainPendingSubscriptions("WebSocket connection failed"),this._connectReject(new Error("WebSocket connection failed")),this._connectResolve=null,this._connectReject=null)}_handleReconnect(){if(this.reconnectAttempts++,this.reconnectAttempts>this.maxReconnectAttempts){if(this.stompClient){try{this.stompClient.deactivate()}catch(e){this.logger.warn("Error deactivating stomp client on max reconnect:",e)}this.stompClient=null}return this._drainPendingSubscriptions("Max reconnection attempts exceeded"),this._setState(s.ERROR),void this.emit("error",{type:i.CONNECTION_LOST,message:"Max reconnection attempts exceeded"})}this._setState(s.RECONNECTING),this.emit("reconnecting",{attempt:this.reconnectAttempts}),this.logger.info(`Reconnecting... attempt ${this.reconnectAttempts}`)}_restoreSubscriptions(){if(0===this.subscriptions.size)return;this.logger.info(`Restoring ${this.subscriptions.size} subscriptions after reconnect`);const e=new Map(this.subscriptions);this.subscriptions.clear(),e.forEach(({callback:e,headers:t},s)=>{this._subscribeInternal(s,e,t),this.logger.debug(`Restored subscription: ${s}`)})}_processPendingSubscriptions(){for(;this.pendingSubscriptions.length>0;){const{destination:e,callback:t,headers:s,resolve:i}=this.pendingSubscriptions.shift(),n=this._subscribeInternal(e,t,s);i&&i(n)}}_subscribeInternal(e,t,s={}){const i=this.stompClient.subscribe(e,e=>{try{const s=JSON.parse(e.body);t(s,e)}catch(s){this.logger.error("Failed to parse message:",s),t(e.body,e)}},s);return this.subscriptions.set(e,{subscription:i,callback:t,headers:s}),this.logger.debug(`Subscribed to: ${e}`),i}subscribe(e,t,i={}){return this.subscriptions.has(e)&&this.unsubscribe(e),this.state!==s.CONNECTED?new Promise((s,n)=>{this.pendingSubscriptions.push({destination:e,callback:t,headers:i,resolve:s,reject:n}),this.logger.debug(`Queued subscription for: ${e}`)}):Promise.resolve(this._subscribeInternal(e,t,i))}unsubscribe(e){const t=this.subscriptions.get(e);t&&(t.subscription.unsubscribe(),this.subscriptions.delete(e),this.logger.debug(`Unsubscribed from: ${e}`))}unsubscribeAll(){this.subscriptions.forEach(({subscription:e},t)=>{e.unsubscribe(),this.logger.debug(`Unsubscribed from: ${t}`)}),this.subscriptions.clear()}send(e,t,i={}){return this.state!==s.CONNECTED?(this.logger.warn("Cannot send message: not connected"),!1):(this.stompClient.publish({destination:e,body:JSON.stringify(t),headers:i}),this.logger.debug(`Sent to ${e}:`,t),!0)}updateToken(e){this.jwtToken=e,this.stompClient&&(this.stompClient.connectHeaders={...this.stompClient.connectHeaders,Authorization:e.startsWith("Bearer ")?e:`Bearer ${e}`})}async disconnect(){this._drainPendingSubscriptions("Disconnected before subscription completed"),this.stompClient&&(this.unsubscribeAll(),await this.stompClient.deactivate(),this.stompClient=null),this._setState(s.DISCONNECTED),this.logger.info("Disconnected")}_drainPendingSubscriptions(e){if(0===this.pendingSubscriptions.length)return;const t=this.pendingSubscriptions;this.pendingSubscriptions=[],t.forEach(({destination:t,reject:s})=>{s&&s(new Error(`${e}: ${t}`))}),this.logger.debug(`Drained ${t.length} pending subscriptions: ${e}`)}isConnected(){return this.state===s.CONNECTED}getState(){return this.state}setLogLevel(e){this.logger.setLevel(e)}async destroy(){await this.disconnect(),this.removeAllListeners(),this.logger.info("ConnectionManager destroyed")}}class Ls extends t{constructor(e){super(),this.connectionManager=e.connectionManager,this.apiClient=e.apiClient,this.userId=e.userId,this.logger=new p(e.logLevel||u.WARN,"ChatClient"),this.subscribedRooms=new Map,this.roomListSubscribed=!1,this._activeRoomId=null,this._typingTimers=new Map,this._assistantTypingTimers=new Map,this._assistantTypingTimeoutMs=3e4,this._assistantTypingUserId="__assistant__",this._assistantTypingUserName="AI",this._seenChatMessageIdsByRoom=new Map,this._seenRoomListMessageIdsByRoom=new Map,this._maxSeenPerRoom=200}_shouldDedupMessage(e,t,s){if(!t||!s)return!1;let i=e.get(t);if(i||(i=new Map,e.set(t,i)),i.has(s))return!0;if(i.set(s,!0),i.size>this._maxSeenPerRoom){const e=i.keys().next().value;i.delete(e)}return!1}async getRooms(e={}){const{size:t=50,lastId:s,lastSortValue:i,type:n}=e;return this.apiClient.get("/api/v1/rooms/my",{size:t,lastId:s,lastSortValue:i,type:n})}async getRoom(e){return this.apiClient.get(`/api/v1/rooms/${e}`)}async enterRoom(e){const t=this.subscribedRooms.has(e);t||await this.subscribeRoom(e),this.setActiveRoom(e);try{return await this.getRoom(e)}catch(s){throw this.getActiveRoom()===e&&this.clearActiveRoom(),t||this.unsubscribeRoom(e),s}}async getRoomInfo(e){return this.apiClient.get(`/api/v1/rooms/${e}/info`)}async setMyRoomLanguage(e,t){return this.apiClient.put(`/api/v1/rooms/${e}/my-language`,{language:t})}async createOneToOneRoom(e){return this.apiClient.post(`/api/v1/rooms/direct/${e}`)}async createGroupRoom(e){const t=e.roomType||r.GROUP;if(t===r.PRIVATE_GROUP){if(!e.password||e.password.length<4)throw new Error("PRIVATE_GROUP requires a password of at least 4 characters")}else if(t===r.GROUP){if(e.password)throw new Error("Public GROUP rooms cannot have a password")}else if(t===r.TEAM&&e.password)throw new Error("TEAM rooms cannot have a password (invite-only)");return this.apiClient.post("/api/v1/rooms/group",{roomName:e.roomName,description:e.description,invitedUserIds:e.invitedUserIds,roomType:t,password:e.password,messageRetentionHours:e.messageRetentionHours,invitedAssistantPersonaIds:e.invitedAssistantPersonaIds,assistantMode:e.assistantMode,roomAiType:e.roomAiType,engagementIntensity:e.engagementIntensity})}async getAssistants(){const e=await this.apiClient.get("/api/v1/assistants");return this._unwrapSuccessResponse(e)}async getRoomAiMeta(){const e=await this.apiClient.get("/api/v1/rooms/ai-meta");return this._unwrapSuccessResponse(e)}async rateAssistantMessage(e,t,s,i){if(!Number.isInteger(s)||s<1||s>5)throw new Error("rating must be an integer between 1 and 5");await this.apiClient.post(`/api/v1/chat-messages/${e}/messages/${t}/rating`,{rating:s,comment:i})}async summarizeWithAssistant(e,t={}){const{personaId:s,format:i,messageCount:n}=t;if(!s)throw new Error("summarizeWithAssistant requires options.personaId");const r=await this.apiClient.post(`/api/v1/rooms/${e}/assistant/tools/summarize`,{personaId:s,format:i,messageCount:n});return this._unwrapSuccessResponse(r)}async translateWithAssistant(e,t={}){const{personaId:s,targetLang:i,sourceMessageId:n}=t;if(!s)throw new Error("translateWithAssistant requires options.personaId");if(!n)throw new Error("translateWithAssistant requires options.sourceMessageId");const r=await this.apiClient.post(`/api/v1/rooms/${e}/assistant/tools/translate`,{personaId:s,targetLang:i,sourceMessageId:n});return this._unwrapSuccessResponse(r)}async getRoomPmPrompt(e){const t=await this.apiClient.get(`/api/v1/rooms/${e}/pm-prompt`);return this._unwrapSuccessResponse(t)}async upsertRoomPmPrompt(e,t){if("string"!=typeof t||!t.trim())throw new Error("upsertRoomPmPrompt requires non-blank content");if(t.length>2e3)throw new Error("upsertRoomPmPrompt content exceeds 2000 characters");const s=await this.apiClient.put(`/api/v1/rooms/${e}/pm-prompt`,{content:t});return this._unwrapSuccessResponse(s)}async activateRoomPmPrompt(e){const t=await this.apiClient.patch(`/api/v1/rooms/${e}/pm-prompt/activate`);return this._unwrapSuccessResponse(t)}async deactivateRoomPmPrompt(e){const t=await this.apiClient.patch(`/api/v1/rooms/${e}/pm-prompt/deactivate`);return this._unwrapSuccessResponse(t)}async getRoomPmPromptVersions(e){const t=await this.apiClient.get(`/api/v1/rooms/${e}/pm-prompt/versions`);return this._unwrapSuccessResponse(t)}async activateRoomPmPromptVersion(e,t){if(!Number.isInteger(t)||t<1)throw new Error("activateRoomPmPromptVersion requires a positive integer version");const s=await this.apiClient.post(`/api/v1/rooms/${e}/pm-prompt/versions/${t}/activate`);return this._unwrapSuccessResponse(s)}async previewRoomPmPrompt(e){const t=await this.apiClient.get(`/api/v1/rooms/${e}/pm-prompt/preview`);return this._unwrapSuccessResponse(t)}async joinGroupRoom(e,t){const s=t?{password:t}:void 0;return this.apiClient.post(`/api/v1/rooms/group/${e}/join`,s)}async leaveRoom(e){const t=await this.apiClient.post(`/api/v1/rooms/${e}/leave`);return this.unsubscribeRoom(e),t}async updateGroupRoom(e,t){return this.apiClient.put(`/api/v1/rooms/group/${e}`,t)}async inviteToGroupRoom(e,t){const s=Array.isArray(t)?{userIds:t}:{userIds:t?.userIds,assistantPersonaIds:t?.assistantPersonaIds};return this.apiClient.post(`/api/v1/rooms/group/${e}/invite`,s)}async kickMember(e,t){return this.apiClient.delete(`/api/v1/rooms/${e}/members/${t}`)}async banMember(e,t){return this.apiClient.post(`/api/v1/rooms/${e}/banned-members`,{userId:t})}async unbanMember(e,t){return this.apiClient.delete(`/api/v1/rooms/${e}/banned-members/${t}`)}async getBannedMembers(e){const t=await this.apiClient.get(`/api/v1/rooms/${e}/banned-members`);return t&&"object"==typeof t&&"data"in t?t.data:t}async pinMessage(e,t){return this.apiClient.post(`/api/v1/rooms/group/${e}/pin/${t}`)}async unpinMessage(e){return this.apiClient.post(`/api/v1/rooms/group/${e}/unpin`)}async toggleReaction(e,t,s){return this.apiClient.post(`/api/v1/chat-messages/${e}/messages/${t}/reaction`,{emoji:s})}async getAvailableGroupRooms(e={}){const{size:t=50,lastId:s,lastSortValue:i}=e;return this.apiClient.get("/api/v1/rooms/groups/available",{size:t,lastId:s,lastSortValue:i})}async getAllGroupRooms(e={}){const{size:t=50,lastId:s,lastSortValue:i}=e;return this.apiClient.get("/api/v1/rooms/groups/all",{size:t,lastId:s,lastSortValue:i})}async getMessages(e,t={}){const{size:s=50,lastId:i,lastSortValue:n}=t,r=await this.apiClient.get(`/api/v1/chat-messages/${e}/list`,{size:s,lastId:i,lastSortValue:n}),o=this._unwrapSuccessResponse(r);return o&&Array.isArray(o.content)&&o.content.forEach(e=>this._normalizeMessageTimestamps(e)),r}async fetchLinkPreview(e){const t="string"==typeof e?e.trim():"";if(!t)throw new Error("url is required");const s=await this.apiClient.post("/api/v1/link-preview",{url:t});return this._unwrapSuccessResponse(s)}async sendMessage(e,t){const s=this._generateMessageId();return this._sendMessageWithId(e,s,t)}sendMessageOptimistic(e,t){const s=this._generateMessageId(),i=this._predictMessageIdsFromData(s,t),n=this._sendMessageWithId(e,s,t).then(e=>this._attachOptimisticMetadata(i,e));return{baseMessageId:s,messageIds:i,promise:n}}async _sendMessageWithId(e,t,s){this.stopTyping(e);const i=await this.apiClient.post(`/api/v1/chat-messages/${e}/send`,{messageId:t,message:s.message,fileInfos:s.fileInfos,separateFiles:!1!==s.separateFiles,replyToMessageId:s.replyToMessageId}),n=this._unwrapSuccessResponse(i);return n&&Array.isArray(n.messages)&&n.messages.forEach(e=>this._normalizeMessageTimestamps(e)),n}async sendTextMessage(e,t){return this.sendMessage(e,{message:t})}sendTextMessageOptimistic(e,t){return this.sendMessageOptimistic(e,{message:t})}async uploadFile(e,t,s={}){if(!e)throw new Error("roomId is required");if(!t)throw new Error("file is required");const i=await this.apiClient.upload(`/api/v1/files/${e}/upload`,t,{onProgress:s.onProgress,signal:s.signal});return this._unwrapSuccessResponse(i)}async sendFileMessage(e,t,s={}){const i=this._normalizeFileArray(t),n=await this._uploadFiles(e,i,s),r=this._applyFileMetadata(n,s.metadata);return this.sendMessage(e,{message:s.message,fileInfos:r,separateFiles:s.separateFiles,replyToMessageId:s.replyToMessageId})}sendFileMessageOptimistic(e,t,s={}){const i=this._normalizeFileArray(t),n=this._generateMessageId(),r=this._predictMessageIds(n,this._predictGroupCount(i,!1!==s.separateFiles),this._hasTextMessage(s.message)),o=(async()=>{const t=await this._uploadFiles(e,i,s),o=this._applyFileMetadata(t,s.metadata),a=await this._sendMessageWithId(e,n,{message:s.message,fileInfos:o,separateFiles:s.separateFiles,replyToMessageId:s.replyToMessageId});return this._attachOptimisticMetadata(r,a)})();return{baseMessageId:n,messageIds:r,promise:o}}_normalizeFileArray(e){const t=Array.isArray(e)?e:[e];if(0===t.length)throw new Error("At least one file is required");if(t.length>20)throw new Error("A maximum of 20 files can be sent in one message");return t}async _uploadFiles(e,t,s={}){return Promise.all(t.map((t,i)=>this.uploadFile(e,t,{signal:s.signal,onProgress:s.onUploadProgress?e=>s.onUploadProgress({...e,fileIndex:i}):void 0})))}_applyFileMetadata(e,t){return null==t?e:e.map((e,s)=>{const i=Array.isArray(t)?t[s]:t;return null==i?e:{...e,metadata:i}})}async sendReply(e,t,s){return this.sendMessage(e,{message:t,replyToMessageId:s})}sendReplyOptimistic(e,t,s){return this.sendMessageOptimistic(e,{message:t,replyToMessageId:s})}async deleteMessage(e,t,s="ALL"){return this.apiClient.post(`/api/v1/chat-messages/${e}/messages/${t}/delete`,{deleteType:s})}async editMessage(e,t,s){return this.apiClient.put(`/api/v1/chat-messages/${e}/messages/${t}`,{message:s})}_hasTextMessage(e){return"string"==typeof e&&e.trim().length>0}_classifyFileType(e){const t=(e||"").toLowerCase();return t.startsWith("image/")?"IMAGE":t.startsWith("video/")?"VIDEO":t.startsWith("audio/")?"AUDIO":t.includes("pdf")||t.includes("document")?"DOCUMENT":"FILE"}_predictGroupCount(e,t){if(!e||0===e.length)return 0;if(t)return e.length;const s=new Set;for(const t of e){const e=t&&(t.type||t.fileType)||"";s.add(this._classifyFileType(e))}return s.size}_predictMessageIds(e,t,s){const i=(s?1:0)+t;if(0===i)return[];if(1===i)return[e];const n=[];s&&n.push(e);for(let s=0;s<t;s++)n.push(`${e}#${s}`);return n}_predictMessageIdsFromData(e,t){const s=t&&t.fileInfos||[],i=!t||!1!==t.separateFiles,n=this._predictGroupCount(s,i),r=this._hasTextMessage(t&&t.message);return this._predictMessageIds(e,n,r)}_attachOptimisticMetadata(e,t){const s=t&&Array.isArray(t.messages)?t.messages.map(e=>e&&e.messageId||null):[],i=s.length===e.length&&e.every((e,t)=>e===s[t]);return i||this.logger.warn("Optimistic messageId prediction mismatch — server may have changed grouping rules. Use result.optimistic.actualMessageIds to reconcile.",{predicted:e,actual:s}),{...t,optimistic:{predictedMessageIds:e,actualMessageIds:s,predictionMatched:i}}}_generateMessageId(){return"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}_unwrapSuccessResponse(e){return e&&"object"==typeof e&&Object.prototype.hasOwnProperty.call(e,"data")?e.data:e}_normalizeMessageTimestamps(e){return e&&"object"==typeof e?(e.sentAt=this._toEpochMillis(e.sentAt),e.editedAt=this._toEpochMillis(e.editedAt),e.replyTo&&"object"==typeof e.replyTo&&(e.replyTo.sentAt=this._toEpochMillis(e.replyTo.sentAt)),e):e}_toEpochMillis(e){if("string"!=typeof e)return e;const t=Date.parse(e);return Number.isNaN(t)?e:t}async subscribeRoom(e){if(this.subscribedRooms.has(e))return void this.logger.warn(`Already subscribed to room: ${e}`);const t=a.getChatDestination(e);await this.connectionManager.subscribe(t,t=>{this._handleChatMessage(e,t)});const s=a.getChatReadDestination(e);await this.connectionManager.subscribe(s,t=>{this._handleReadEvent(e,t)});const i=a.getChatTypingDestination(e);await this.connectionManager.subscribe(i,t=>{this._handleTypingEvent(e,t)});const n=t=>{t.roomId===e&&this.emit("memberJoined",{roomId:e,members:t.members||[],participantCount:t.activeParticipantCount,timestamp:t.timestamp})},r=t=>{t.roomId===e&&this.emit("memberLeft",{roomId:e,members:t.members||[],participantCount:t.activeParticipantCount,timestamp:t.timestamp})};this.on("roomListJoined",n),this.on("roomListLeft",r),this.subscribedRooms.set(e,{chatDestination:t,readDestination:s,typingDestination:i,memberJoinedHandler:n,memberLeftHandler:r,subscribedAt:new Date}),this.logger.info(`Subscribed to room: ${e}`),this.emit("roomSubscribed",{roomId:e})}unsubscribeRoom(e){const t=this.subscribedRooms.get(e);t?(this.connectionManager.unsubscribe(t.chatDestination),this.connectionManager.unsubscribe(t.readDestination),t.typingDestination&&this.connectionManager.unsubscribe(t.typingDestination),t.memberJoinedHandler&&this.off("roomListJoined",t.memberJoinedHandler),t.memberLeftHandler&&this.off("roomListLeft",t.memberLeftHandler),this._clearTypingTimer(e),this._clearAssistantTypingTimer(e),this._activeRoomId===e&&(this._activeRoomId=null),this.subscribedRooms.delete(e),this._seenChatMessageIdsByRoom.delete(e),this._seenRoomListMessageIdsByRoom.delete(e),this.logger.info(`Unsubscribed from room: ${e}`),this.emit("roomUnsubscribed",{roomId:e})):this.logger.warn(`Not subscribed to room: ${e}`)}unsubscribeAllRooms(){this.subscribedRooms.forEach((e,t)=>{this.unsubscribeRoom(t)})}setActiveRoom(e){this._activeRoomId=e,this.logger.debug(`Active room set: ${e}`)}clearActiveRoom(){this.logger.debug(`Active room cleared (was: ${this._activeRoomId})`),this._activeRoomId=null}getActiveRoom(){return this._activeRoomId}async subscribeRoomList(){if(this.roomListSubscribed)return void this.logger.warn("Already subscribed to room list");const e=a.ROOM_LIST_USER_DESTINATION;await this.connectionManager.subscribe(e,e=>{this._handleRoomListEvent(e)}),this.roomListSubscribed=!0,this.logger.info("Subscribed to room list"),this.emit("roomListSubscribed",{})}unsubscribeRoomList(){this.roomListSubscribed?(this.connectionManager.unsubscribe(a.ROOM_LIST_USER_DESTINATION),this.roomListSubscribed=!1,this.logger.info("Unsubscribed from room list"),this.emit("roomListUnsubscribed",{})):this.logger.warn("Not subscribed to room list")}isRoomListSubscribed(){return this.roomListSubscribed}markAsRead(e,t){return this.connectionManager.isConnected()?this.connectionManager.send(a.CHAT_READ,{roomId:e,messageId:t}):(this.logger.warn("Cannot mark as read: not connected"),!1)}_handleChatMessage(e,t){if(this.logger.debug(`Message received in room ${e} (${t.eventType}):`,t),"MESSAGE_CREATED"===t.eventType&&this._shouldDedupMessage(this._seenChatMessageIdsByRoom,e,t.messageId))this.logger.debug(`Duplicate MESSAGE_CREATED suppressed: room=${e}, messageId=${t.messageId}`);else switch("MESSAGE_UPDATED"===t.eventType&&(void 0===t.translations&&(t.translations=null),void 0===t.sourceLang&&(t.sourceLang=null),void 0===t.translationsOf&&(t.translationsOf=null)),this.emit("message",{roomId:e,message:t}),t.eventType){case"MESSAGE_CREATED":"ASSISTANT"===t.senderType&&(this._clearAssistantTypingTimer(e),this.emit("typing",{roomId:e,userId:this._assistantTypingUserId,userName:this._assistantTypingUserName,typing:!1,senderType:"ASSISTANT"})),t.userId!==this.userId&&(this.emit("newMessage",{roomId:e,message:t}),this._activeRoomId===e&&t.messageId&&this.markAsRead(e,t.messageId));break;case"MESSAGE_UPDATED":this.emit("messageUpdated",{roomId:e,message:t});break;case"MESSAGE_DELETED":this.emit("messageDeleted",{roomId:e,message:t});break;case"REACTION_CHANGED":this.emit("reactionChanged",{roomId:e,message:t});break;case"LINK_PREVIEW_ATTACHED":this.emit("linkPreviewAttached",{roomId:e,message:t});break;case"MESSAGE_TRANSLATED":this.emit("messageTranslated",{roomId:e,message:t});break;default:this.logger.warn(`Unknown eventType "${t.eventType}" — falling back to legacy behavior`),t.userId!==this.userId&&(this.emit("newMessage",{roomId:e,message:t}),this._activeRoomId===e&&t.messageId&&this.markAsRead(e,t.messageId))}}_handleRoomListEvent(e){if(this.logger.debug("Room list event:",e),e.eventType===o.MESSAGE_RECEIVED&&e.messageId&&this._shouldDedupMessage(this._seenRoomListMessageIdsByRoom,e.roomId,e.messageId))this.logger.debug(`Duplicate roomList MESSAGE_RECEIVED suppressed: room=${e.roomId}, messageId=${e.messageId}`);else switch(this.emit("roomListUpdate",e),e.eventType){case o.MESSAGE_RECEIVED:this.emit("roomListMessage",e);break;case o.MESSAGE_DELETED:this.emit("roomListMessageDeleted",e);break;case o.MESSAGE_UPDATED:this.emit("roomListMessageUpdated",e);break;case o.ROOM_CREATED:this.emit("roomListCreated",e);break;case o.ROOM_JOINED:this.emit("roomListJoined",e);break;case o.ROOM_LEFT:this.emit("roomListLeft",e),e.actorId===this.userId&&this.emit("roomListSelfLeft",e);break;case o.ROOM_KICKED:this.emit("roomListKicked",e),this._isSelfInMembers(e)&&this.emit("roomListSelfKicked",e);break;case o.ROOM_BANNED:this.emit("roomListBanned",e),this._isSelfInMembers(e)&&this.emit("roomListSelfBanned",e);break;case o.ROOM_UPDATED:this.emit("roomListRoomUpdated",e);break;case o.MESSAGE_RETENTION_CLEANUP:this.emit("retentionCleanup",{roomId:e.roomId,cutoffTime:e.cutoffTime});break;default:this.logger.warn("Unknown room list event type:",e.eventType)}}_handleReadEvent(e,t){this.logger.debug(`Read event in room ${e}:`,t);const s=t.roomId||e;t.events&&Array.isArray(t.events)?t.events.forEach(e=>{this.emit("messageRead",{roomId:s,messageId:e.messageId,userId:t.userId,remainingUnreadCount:e.remainingUnreadCount})}):this.emit("messageRead",{roomId:s,messageId:t.messageId,userId:t.userId,remainingUnreadCount:t.remainingUnreadCount})}startTyping(e){if(!this.connectionManager.isConnected())return;const t=this._typingTimers.get(e);t?clearTimeout(t):this.connectionManager.send(a.CHAT_TYPING,{roomId:e,typing:!0});const s=setTimeout(()=>{this.stopTyping(e)},3e3);this._typingTimers.set(e,s)}stopTyping(e){this._clearTypingTimer(e),this.connectionManager.isConnected()&&this.connectionManager.send(a.CHAT_TYPING,{roomId:e,typing:!1})}_isSelfInMembers(e){return Array.isArray(e.members)&&e.members.some(e=>e&&e.userId===this.userId)}_handleTypingEvent(e,t){"ASSISTANT"!==t.senderType&&t.userId===this.userId||("ASSISTANT"===t.senderType&&!0===t.typing&&this._startAssistantTypingTimer(e),this.emit("typing",{roomId:e,userId:t.userId,userName:t.userName,typing:t.typing,senderType:t.senderType||"USER"}))}_startAssistantTypingTimer(e){this._clearAssistantTypingTimer(e);const t=setTimeout(()=>{this._assistantTypingTimers.delete(e),this.emit("typing",{roomId:e,userId:this._assistantTypingUserId,userName:this._assistantTypingUserName,typing:!1,senderType:"ASSISTANT"}),this.logger.debug(`Assistant typing auto-cleared (timeout): room=${e}`)},this._assistantTypingTimeoutMs);this._assistantTypingTimers.set(e,t)}_clearAssistantTypingTimer(e){const t=this._assistantTypingTimers.get(e);t&&(clearTimeout(t),this._assistantTypingTimers.delete(e))}_clearTypingTimer(e){const t=this._typingTimers.get(e);t&&(clearTimeout(t),this._typingTimers.delete(e))}getSubscribedRooms(){return Array.from(this.subscribedRooms.keys())}isSubscribed(e){return this.subscribedRooms.has(e)}setLogLevel(e){this.logger.setLevel(e)}destroy(){this.unsubscribeAllRooms(),this.roomListSubscribed&&this.unsubscribeRoomList(),this._typingTimers.forEach(e=>clearTimeout(e)),this._typingTimers.clear(),this._assistantTypingTimers.forEach(e=>clearTimeout(e)),this._assistantTypingTimers.clear(),this._seenChatMessageIdsByRoom.clear(),this._seenRoomListMessageIdsByRoom.clear(),this.removeAllListeners(),this.logger.info("ChatClient destroyed")}}class Ds extends t{constructor(e={}){super(),this.localStream=null,this.screenStream=null,this.videoEnabled=!0,this.audioEnabled=!0,this.logger=new p(e.logLevel||u.WARN,"MediaStreamManager"),this._deviceChangeHandler=null}async getUserMedia(e={video:!0,audio:!0}){try{return this.localStream=await navigator.mediaDevices.getUserMedia(e),this.videoEnabled=!1!==e.video,this.audioEnabled=!1!==e.audio,this.emit("streamStarted",{stream:this.localStream}),this.logger.info("User media stream started"),this.localStream}catch(e){throw this.logger.error("Failed to get user media:",e),this.emit("error",{type:i.MEDIA_ACCESS_DENIED,message:this._getMediaErrorMessage(e),error:e}),e}}_getMediaErrorMessage(e){switch(e.name){case"NotAllowedError":return"Camera/Microphone permission denied";case"NotFoundError":return"Camera/Microphone not found";case"NotReadableError":return"Camera/Microphone is already in use";case"OverconstrainedError":return"Camera/Microphone constraints cannot be satisfied";case"AbortError":return"Media access aborted";default:return e.message||"Unknown media error"}}async getDisplayMedia(e={video:!0,audio:!1}){try{return this.screenStream=await navigator.mediaDevices.getDisplayMedia(e),this.screenStream.getVideoTracks()[0].onended=()=>{this.emit("screenShareEnded",{}),this.screenStream=null},this.emit("screenShareStarted",{stream:this.screenStream}),this.logger.info("Screen share stream started"),this.screenStream}catch(e){throw this.logger.error("Failed to get display media:",e),this.emit("error",{type:i.SCREEN_SHARE_DENIED,message:"NotAllowedError"===e.name?"Screen share permission denied":e.message,error:e}),e}}toggleVideo(){if(!this.localStream)return this.logger.warn("No local stream available"),this.videoEnabled;const e=this.localStream.getVideoTracks();return 0===e.length?(this.logger.warn("No video track available"),this.videoEnabled):(this.videoEnabled=!this.videoEnabled,e.forEach(e=>{e.enabled=this.videoEnabled}),this.emit("videoToggled",{enabled:this.videoEnabled}),this.logger.debug(`Video toggled: ${this.videoEnabled}`),this.videoEnabled)}toggleAudio(){if(!this.localStream)return this.logger.warn("No local stream available"),this.audioEnabled;const e=this.localStream.getAudioTracks();return 0===e.length?(this.logger.warn("No audio track available"),this.audioEnabled):(this.audioEnabled=!this.audioEnabled,e.forEach(e=>{e.enabled=this.audioEnabled}),this.emit("audioToggled",{enabled:this.audioEnabled}),this.logger.debug(`Audio toggled: ${this.audioEnabled}`),this.audioEnabled)}setVideoEnabled(e){if(!this.localStream)return void this.logger.warn("No local stream available");this.localStream.getVideoTracks().forEach(t=>{t.enabled=e}),this.videoEnabled=e,this.emit("videoToggled",{enabled:e})}setAudioEnabled(e){if(!this.localStream)return void this.logger.warn("No local stream available");this.localStream.getAudioTracks().forEach(t=>{t.enabled=e}),this.audioEnabled=e,this.emit("audioToggled",{enabled:e})}getLocalStream(){return this.localStream}getScreenStream(){return this.screenStream}isVideoEnabled(){return this.videoEnabled}isAudioEnabled(){return this.audioEnabled}stopAll(){this.localStream&&(this.localStream.getTracks().forEach(e=>e.stop()),this.localStream=null,this.emit("streamStopped",{}),this.logger.info("All media tracks stopped")),this.screenStream&&(this.screenStream.getTracks().forEach(e=>e.stop()),this.screenStream=null)}replaceTrack(e,t){this.localStream?(this.localStream.removeTrack(e),this.localStream.addTrack(t),e.stop(),this.emit("trackReplaced",{oldTrack:e,newTrack:t}),this.logger.debug(`Track replaced: ${e.kind}`)):this.logger.warn("No local stream available")}getTrack(e){if(!this.localStream)return null;const t="video"===e?this.localStream.getVideoTracks():this.localStream.getAudioTracks();return t.length>0?t[0]:null}async getDevices(){try{const e=await navigator.mediaDevices.enumerateDevices();return{videoInputs:e.filter(e=>"videoinput"===e.kind),audioInputs:e.filter(e=>"audioinput"===e.kind),audioOutputs:e.filter(e=>"audiooutput"===e.kind)}}catch(e){throw this.logger.error("Failed to enumerate devices:",e),this.emit("error",{type:i.ENUMERATE_DEVICES_FAILED,message:e.message,error:e}),e}}async switchDevice(e,t){if(!this.localStream)throw new Error("No local stream available");try{const s="video"===t?{video:{deviceId:{exact:e}},audio:!1}:{video:!1,audio:{deviceId:{exact:e}}},i=(await navigator.mediaDevices.getUserMedia(s)).getTracks()[0],n="video"===t?this.localStream.getVideoTracks()[0]:this.localStream.getAudioTracks()[0];return n&&(this.replaceTrack(n,i),this.emit("deviceSwitched",{kind:t,deviceId:e,newTrack:i}),this.logger.info(`${t} device switched to ${e}`)),i}catch(e){throw this.logger.error(`Failed to switch ${t} device:`,e),this.emit("error",{type:i.DEVICE_SWITCH_FAILED,message:e.message,error:e}),e}}startDeviceChangeDetection(){this._deviceChangeHandler||(this._deviceChangeHandler=async()=>{try{const e=await this.getDevices();this.emit("deviceChange",e),this.logger.debug("Device change detected")}catch(e){this.logger.warn("Failed to get devices on change:",e)}},navigator.mediaDevices.addEventListener("devicechange",this._deviceChangeHandler),this.logger.debug("Device change detection started"))}stopDeviceChangeDetection(){this._deviceChangeHandler&&(navigator.mediaDevices.removeEventListener("devicechange",this._deviceChangeHandler),this._deviceChangeHandler=null,this.logger.debug("Device change detection stopped"))}getStreamInfo(){return this.localStream?{hasStream:!0,videoEnabled:this.videoEnabled,audioEnabled:this.audioEnabled,tracks:this.localStream.getTracks().map(e=>({kind:e.kind,id:e.id,label:e.label,enabled:e.enabled,readyState:e.readyState,muted:e.muted}))}:{hasStream:!1,videoEnabled:this.videoEnabled,audioEnabled:this.audioEnabled,tracks:[]}}async applyVideoConstraints(e){if(!this.localStream)throw new Error("No local stream available");const t=this.localStream.getVideoTracks()[0];if(!t)throw new Error("No video track available");try{await t.applyConstraints(e),this.emit("videoConstraintsApplied",{constraints:e}),this.logger.info("Video constraints applied:",e)}catch(e){throw this.logger.error("Failed to apply video constraints:",e),e}}getVideoSettings(){if(!this.localStream)return null;const e=this.localStream.getVideoTracks()[0];return e?e.getSettings():null}getAudioSettings(){if(!this.localStream)return null;const e=this.localStream.getAudioTracks()[0];return e?e.getSettings():null}setLogLevel(e){this.logger.setLevel(e)}destroy(){this.stopAll(),this.stopDeviceChangeDetection(),this.removeAllListeners(),this.logger.info("MediaStreamManager destroyed")}}class Ps extends t{constructor(e={}){super(),this.iceServers=e.iceServers||h.iceServers,this.logger=new p(e.logLevel||u.WARN,"PeerConnectionManager"),this.peers=new Map,this.localStream=null}setLocalStream(e){this.localStream=e,this.peers.forEach(e=>{this._addTracksToConnection(e.connection)})}setIceServers(e){this.iceServers=e}createPeerConnection(e,t=!1,s={}){if(this.peers.has(e))return this.logger.warn(`Peer connection already exists: ${e}`),this.peers.get(e).connection;const i={iceServers:this.iceServers,iceCandidatePoolSize:10},n=new RTCPeerConnection(i),r={connection:n,polite:t,makingOffer:!1,ignoreOffer:!1,isSettingRemoteAnswerPending:!1,skipAutoNegotiation:s.skipAutoNegotiation||!1};return this.peers.set(e,r),this._setupConnectionHandlers(e,n,r),this.localStream&&this._addTracksToConnection(n),this.logger.info(`Peer connection created: ${e} (polite: ${t}, skipAutoNegotiation: ${r.skipAutoNegotiation})`),n}_setupConnectionHandlers(e,t,s){t.onicecandidate=t=>{t.candidate&&this.emit("iceCandidate",{peerId:e,candidate:t.candidate})},t.oniceconnectionstatechange=()=>{this.logger.debug(`ICE connection state (${e}): ${t.iceConnectionState}`),this.emit("iceConnectionStateChange",{peerId:e,state:t.iceConnectionState}),"failed"===t.iceConnectionState&&this.emit("error",{type:i.ICE_CONNECTION_FAILED,peerId:e,message:"ICE connection failed"})},t.onconnectionstatechange=()=>{this.logger.debug(`Connection state (${e}): ${t.connectionState}`),this.emit("connectionStateChange",{peerId:e,state:t.connectionState}),"connected"===t.connectionState?this.emit("peerConnected",{peerId:e}):"disconnected"!==t.connectionState&&"failed"!==t.connectionState||this.emit("peerDisconnected",{peerId:e})},t.onnegotiationneeded=async()=>{if(s.skipAutoNegotiation)this.logger.debug(`Skipping auto negotiation for ${e} (manual offer will be sent)`);else try{s.makingOffer=!0,await t.setLocalDescription(),this.emit("negotiationNeeded",{peerId:e,description:t.localDescription})}catch(t){this.logger.error(`Negotiation error (${e}):`,t)}finally{s.makingOffer=!1}},t.ontrack=t=>{this.logger.info(`Remote track received from ${e}:`,t.track.kind),this.emit("remoteTrack",{peerId:e,track:t.track,streams:t.streams})},t.ondatachannel=t=>{this.logger.info(`Data channel received from ${e}`),this.emit("dataChannel",{peerId:e,channel:t.channel})}}_addTracksToConnection(e){if(!this.localStream)return;const t=e.getSenders();this.localStream.getTracks().forEach(s=>{t.find(e=>e.track&&e.track.kind===s.kind)||e.addTrack(s,this.localStream)})}async createOffer(e){const t=this.peers.get(e);if(!t)throw new Error(`Peer not found: ${e}`);try{const s=await t.connection.createOffer();return await t.connection.setLocalDescription(s),this.logger.debug(`Offer created for ${e}`),t.connection.localDescription}catch(t){throw this.logger.error(`Failed to create offer for ${e}:`,t),t}}async createAnswer(e){const t=this.peers.get(e);if(!t)throw new Error(`Peer not found: ${e}`);try{const s=await t.connection.createAnswer();return await t.connection.setLocalDescription(s),this.logger.debug(`Answer created for ${e}`),t.connection.localDescription}catch(t){throw this.logger.error(`Failed to create answer for ${e}:`,t),t}}async handleRemoteDescription(e,t){const s=this.peers.get(e);if(!s)throw new Error(`Peer not found: ${e}`);const{connection:i,polite:n,makingOffer:r}=s,o="offer"===t.type&&(r||"stable"!==i.signalingState);if(s.ignoreOffer=!n&&o,s.ignoreOffer)this.logger.debug(`Ignoring offer collision from ${e} (I am impolite)`);else try{if(o&&n&&(this.logger.debug(`Offer collision detected, rolling back local offer for ${e} (I am polite)`),await i.setLocalDescription({type:"rollback"})),s.isSettingRemoteAnswerPending="answer"===t.type,await i.setRemoteDescription(t),s.isSettingRemoteAnswerPending=!1,this.logger.debug(`Remote ${t.type} set for ${e}`),"offer"===t.type){const t=await this.createAnswer(e);this.emit("answerCreated",{peerId:e,answer:t})}}catch(t){throw this.logger.error(`Failed to set remote description for ${e}:`,t),t}}async addIceCandidate(e,t){const s=this.peers.get(e);if(!s)return this.logger.warn(`Peer not found for ICE candidate: ${e}`),!1;if(!s.connection.remoteDescription)return this.logger.debug(`Remote description not set yet for ${e}, ICE candidate queued`),!1;try{return await s.connection.addIceCandidate(t),this.logger.debug(`ICE candidate added for ${e}`),!0}catch(t){return s.ignoreOffer||this.logger.error(`Failed to add ICE candidate for ${e}:`,t),!1}}getPeerConnection(e){const t=this.peers.get(e);return t?t.connection:null}getPeerIds(){return Array.from(this.peers.keys())}closePeerConnection(e){const t=this.peers.get(e);t&&(t.connection.close(),this.peers.delete(e),this.emit("peerClosed",{peerId:e}),this.logger.info(`Peer connection closed: ${e}`))}closeAllPeerConnections(){this.peers.forEach((e,t)=>{e.connection.close(),this.logger.debug(`Peer connection closed: ${t}`)}),this.peers.clear(),this.emit("allPeersClosed",{})}async replaceTrack(e,t){const s=[];this.peers.forEach((i,n)=>{const r=i.connection.getSenders().find(t=>t.track&&t.track.kind===e.kind);r&&s.push(r.replaceTrack(t).then(()=>this.logger.debug(`Track replaced for ${n}`)).catch(e=>this.logger.error(`Failed to replace track for ${n}:`,e)))}),await Promise.all(s)}async getStats(e){const t=this.peers.get(e);return t?t.connection.getStats():null}getConnectionSummary(){const e={};return this.peers.forEach((t,s)=>{e[s]={connectionState:t.connection.connectionState,iceConnectionState:t.connection.iceConnectionState,signalingState:t.connection.signalingState,polite:t.polite}}),e}setLogLevel(e){this.logger.setLevel(e)}destroy(){this.closeAllPeerConnections(),this.localStream=null,this.removeAllListeners(),this.logger.info("PeerConnectionManager destroyed")}}class xs extends t{constructor(e){super(),this.connectionManager=e.connectionManager,this.apiClient=e.apiClient,this.userId=e.userId,this.logLevel=e.logLevel||u.WARN,this.logger=new p(this.logLevel,"WebRTCClient"),this.mediaManager=new Ds({logLevel:this.logLevel}),this.peerManager=new Ps({iceServers:e.iceServers||h.iceServers,logLevel:this.logLevel}),this.currentRoom=null,this.isGroupCall=!1,this.participants=new Map,this._iceServersFetched=!1,this._waitingForCallAccept=!1,this._pendingCallTarget=null,this._pendingIceCandidates=new Map,this._setupEventHandlers()}async initializeIceServers(){if(!this._iceServersFetched)try{const e=await this.getTurnCredentials();e&&e.iceServers&&(this.peerManager.setIceServers(e.iceServers),this._iceServersFetched=!0,this.logger.info("ICE servers fetched successfully"))}catch(e){this.logger.warn("Failed to fetch TURN credentials, using fallback ICE servers:",e.message),this._setFallbackIceServers()}}_setFallbackIceServers(){this.peerManager.setIceServers([{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}])}_setupEventHandlers(){this.mediaManager.on("streamStarted",e=>this.emit("localStreamStarted",e)),this.mediaManager.on("streamStopped",e=>this.emit("localStreamStopped",e)),this.mediaManager.on("videoToggled",()=>this._sendMediaState()),this.mediaManager.on("audioToggled",()=>this._sendMediaState()),this.mediaManager.on("screenShareStarted",e=>this.emit("screenShareStarted",e)),this.mediaManager.on("screenShareEnded",e=>this.emit("screenShareEnded",e)),this.mediaManager.on("error",e=>this.emit("error",e)),this.peerManager.on("remoteTrack",e=>this.emit("remoteTrack",e)),this.peerManager.on("peerConnected",e=>this.emit("peerConnected",e)),this.peerManager.on("peerDisconnected",e=>this.emit("peerDisconnected",e)),this.peerManager.on("peerClosed",e=>this.emit("peerClosed",e)),this.peerManager.on("error",e=>this.emit("error",e)),this.peerManager.on("iceCandidate",({peerId:e,candidate:t})=>{this._sendSignal({type:n.ICE_CANDIDATE,receiverId:e,data:{candidate:t}})}),this.peerManager.on("negotiationNeeded",({peerId:e,description:t})=>{this._sendSignal({type:n.CALL_OFFER,receiverId:e,data:{sdp:t}})}),this.peerManager.on("answerCreated",({peerId:e,answer:t})=>{this._sendSignal({type:n.CALL_ANSWER,receiverId:e,data:{sdp:t}})})}async getTurnCredentials(){return(await this.apiClient.get("/api/v1/webrtc/turn-credentials")).data}async createCallRoom(e){return this.apiClient.post("/api/v1/webrtc/rooms",e)}async getCallRoom(e){return this.apiClient.get(`/api/v1/webrtc/rooms/${e}`)}async joinCallRoomApi(e){return this.apiClient.post(`/api/v1/webrtc/rooms/${e}/join`)}async leaveCallRoomApi(e){return this.apiClient.delete(`/api/v1/webrtc/rooms/${e}/leave`)}async enableIncomingCalls(){this._incomingCallsEnabled?this.logger.debug("Incoming calls already enabled"):(await this._subscribeToDirectSignaling(),this._incomingCallsEnabled=!0,this.logger.info("Incoming calls enabled - now listening for call invitations"))}disableIncomingCalls(){if(!this._incomingCallsEnabled)return;const e=a.getWebRTCUserDestination();this.connectionManager.unsubscribe(e),this._incomingCallsEnabled=!1,this.logger.info("Incoming calls disabled")}isIncomingCallsEnabled(){return this._incomingCallsEnabled||!1}async startCall(e){const{roomId:t,isGroup:s=!1,mediaConstraints:r={video:!0,audio:!0}}=e;try{await this.initializeIceServers();const e=await this.mediaManager.getUserMedia(r);return this.peerManager.setLocalStream(e),this.currentRoom=t,this.isGroupCall=s,await this._subscribeToSignaling(t,s),this._sendSignal({type:n.JOIN_ROOM,roomId:t}),this.logger.info(`Call started in room: ${t}`),this.emit("callStarted",{roomId:t,isGroup:s,localStream:e}),e}catch(e){throw this.logger.error("Failed to start call:",e),this.emit("error",{type:i.PEER_CONNECTION_FAILED,message:e.message,error:e}),e}}async callUser(e,t={video:!0,audio:!0}){try{await this.initializeIceServers();const s=await this.mediaManager.getUserMedia(t);this.peerManager.setLocalStream(s),await this._subscribeToDirectSignaling(),this._waitingForCallAccept=!0,this._pendingCallTarget=e,this._sendSignal({type:n.CALL_REQUEST,receiverId:e}),this.currentRoom=null,this.isGroupCall=!1,this.emit("callRequested",{targetUserId:e,localStream:s})}catch(e){throw this.logger.error("Failed to call user:",e),this._waitingForCallAccept=!1,this._pendingCallTarget=null,e}}async acceptCall(e,t={video:!0,audio:!0}){try{await this.initializeIceServers();const s=await this.mediaManager.getUserMedia(t);this.peerManager.setLocalStream(s),this.peerManager.createPeerConnection(e,!0,{skipAutoNegotiation:!0}),this._sendSignal({type:n.CALL_ACCEPT,receiverId:e}),this.emit("callAccepted",{callerId:e})}catch(e){throw this.logger.error("Failed to accept call:",e),e}}rejectCall(e){this._sendSignal({type:n.CALL_REJECT,receiverId:e}),this.emit("callRejected",{callerId:e})}cancelCall(){this._waitingForCallAccept&&this._pendingCallTarget&&(this._sendSignal({type:n.CALL_CANCEL,receiverId:this._pendingCallTarget}),this.emit("callCancelled",{targetUserId:this._pendingCallTarget}),this._waitingForCallAccept=!1,this._pendingCallTarget=null,this.mediaManager.stopAll())}endCall(){this._waitingForCallAccept&&this._pendingCallTarget&&this._sendSignal({type:n.CALL_CANCEL,receiverId:this._pendingCallTarget}),this._waitingForCallAccept=!1,this._pendingCallTarget=null,this.currentRoom&&(this._sendSignal({type:n.LEAVE_ROOM,roomId:this.currentRoom}),this._unsubscribeFromSignaling()),this.peerManager.getPeerIds().forEach(e=>{this._sendSignal({type:n.CALL_END,receiverId:e})}),this.peerManager.closeAllPeerConnections(),this.mediaManager.stopAll(),this.participants.clear(),this._pendingIceCandidates.clear();const e=this.currentRoom;this.currentRoom=null,this.isGroupCall=!1,this.emit("callEnded",{roomId:e}),this.logger.info("Call ended")}toggleVideo(){return this.mediaManager.toggleVideo()}toggleAudio(){return this.mediaManager.toggleAudio()}async startScreenShare(){const e=await this.mediaManager.getDisplayMedia(),t=e.getVideoTracks()[0],s=this.mediaManager.getTrack("video");return s&&t&&await this.peerManager.replaceTrack(s,t),t.onended=async()=>{const e=this.mediaManager.getTrack("video");e&&await this.peerManager.replaceTrack(t,e),this.emit("screenShareEnded",{})},e}stopScreenShare(){const e=this.mediaManager.getScreenStream();e&&e.getTracks().forEach(e=>e.stop())}getLocalStream(){return this.mediaManager.getLocalStream()}async getDevices(){return this.mediaManager.getDevices()}async switchDevice(e,t){const s=this.mediaManager.getTrack(t),i=await this.mediaManager.switchDevice(e,t);return s&&await this.peerManager.replaceTrack(s,i),i}setVideoEnabled(e){this.mediaManager.setVideoEnabled(e),this._sendMediaState()}setAudioEnabled(e){this.mediaManager.setAudioEnabled(e),this._sendMediaState()}startDeviceChangeDetection(){this.mediaManager.startDeviceChangeDetection(),this.mediaManager.on("deviceChange",e=>{this.emit("deviceChange",e)})}stopDeviceChangeDetection(){this.mediaManager.stopDeviceChangeDetection()}async applyVideoConstraints(e){return this.mediaManager.applyVideoConstraints(e)}getVideoSettings(){return this.mediaManager.getVideoSettings()}getAudioSettings(){return this.mediaManager.getAudioSettings()}async _subscribeToSignaling(e,t){if(t){const t=a.getWebRTCDestination(e);await this.connectionManager.subscribe(t,e=>{this._handleSignal(e)})}await this._subscribeToDirectSignaling()}async _subscribeToDirectSignaling(){const e=a.getWebRTCUserDestination();await this.connectionManager.subscribe(e,e=>{this._handleSignal(e)})}_unsubscribeFromSignaling(){if(this.currentRoom&&this.isGroupCall){const e=a.getWebRTCDestination(this.currentRoom);this.connectionManager.unsubscribe(e)}if(!this._incomingCallsEnabled){const e=a.getWebRTCUserDestination();this.connectionManager.unsubscribe(e)}}_sendSignal(e){const t={type:e.type,roomId:e.roomId||this.currentRoom,receiverId:e.receiverId,data:e.data};this.connectionManager.send(a.WEBRTC_SIGNAL,t),this.logger.debug("Signal sent:",t)}_sendMediaState(){if(!this.currentRoom&&0===this.peerManager.getPeerIds().length)return;const e={videoEnabled:this.mediaManager.isVideoEnabled(),audioEnabled:this.mediaManager.isAudioEnabled()};this._sendSignal({type:n.VIDEO_STATE_CHANGED,data:e}),this.emit("mediaStateChanged",e)}async _handleSignal(e){const{type:t,senderId:s,data:i}=e;if(s!==this.userId)switch(this.logger.debug(`Signal received: ${t} from ${s}`),t){case n.JOIN_ROOM:case n.PEER_JOINED:await this._handleUserJoined(s);break;case n.LEAVE_ROOM:case n.PEER_LEFT:this._handleUserLeft(s);break;case n.CALL_OFFER:await this._handleOffer(s,i.sdp);break;case n.CALL_ANSWER:await this._handleAnswer(s,i.sdp);break;case n.ICE_CANDIDATE:await this._handleIceCandidate(s,i.candidate);break;case n.VIDEO_STATE_CHANGED:case n.AUDIO_STATE_CHANGED:this._handleMediaState(s,i);break;case n.CALL_REQUEST:this.isInCall()||this._waitingForCallAccept?(this._sendSignal({type:n.CALL_BUSY,receiverId:s}),this.emit("incomingCallWhileBusy",{callerId:s})):this.emit("incomingCall",{callerId:s});break;case n.CALL_BUSY:this._waitingForCallAccept=!1,this._pendingCallTarget=null,this.mediaManager.stopAll(),this.emit("callBusy",{userId:s});break;case n.CALL_INVITATION:this.emit("callInvitation",{callRoomId:i?.callRoomId||e.roomId,title:i?.title,hostUserId:i?.hostUserId||s,maxParticipants:i?.maxParticipants,createdAt:i?.createdAt});break;case n.CALL_ACCEPT:await this._handleCallAccepted(s);break;case n.CALL_REJECT:this._waitingForCallAccept=!1,this._pendingCallTarget=null,this.mediaManager.stopAll(),this.emit("callRejected",{userId:s});break;case n.CALL_CANCEL:this._waitingForCallAccept=!1,this._pendingCallTarget=null,this.emit("callCancelled",{userId:s});break;case n.CALL_END:this._handleCallEnded(s);break;default:this.logger.warn(`Unknown signal type: ${t}`)}}async _handleUserJoined(e){this.participants.set(e,{joinedAt:new Date});const t=this.userId<e;this.peerManager.createPeerConnection(e,t),this.emit("userJoined",{userId:e}),this.logger.info(`User joined: ${e} (I am ${t?"polite":"impolite"})`)}_handleUserLeft(e){this.participants.delete(e),this.peerManager.closePeerConnection(e),this.emit("userLeft",{userId:e}),this.logger.info(`User left: ${e}`)}async _handleOffer(e,t){if(!this.peerManager.getPeerConnection(e)){const t=this.userId<e;this.peerManager.createPeerConnection(e,t,{skipAutoNegotiation:!0})}await this.peerManager.handleRemoteDescription(e,t),await this._processPendingIceCandidates(e)}async _handleAnswer(e,t){await this.peerManager.handleRemoteDescription(e,t),await this._processPendingIceCandidates(e)}async _handleIceCandidate(e,t){if(!this.peerManager.getPeerConnection(e))return void this._queueIceCandidate(e,t);await this.peerManager.addIceCandidate(e,new RTCIceCandidate(t))||this._queueIceCandidate(e,t)}_queueIceCandidate(e,t){this._pendingIceCandidates.has(e)||this._pendingIceCandidates.set(e,[]),this._pendingIceCandidates.get(e).push(t),this.logger.debug(`ICE candidate queued for ${e}`)}async _processPendingIceCandidates(e){const t=this._pendingIceCandidates.get(e);if(t&&0!==t.length){this.logger.debug(`Processing ${t.length} pending ICE candidates for ${e}`);for(const s of t)await this.peerManager.addIceCandidate(e,new RTCIceCandidate(s));this._pendingIceCandidates.delete(e)}}_handleMediaState(e,t){this.emit("participantMediaState",{userId:e,videoEnabled:t.videoEnabled,audioEnabled:t.audioEnabled})}async _handleCallAccepted(e){this._waitingForCallAccept=!1,this._pendingCallTarget=null,this.peerManager.createPeerConnection(e,!1,{skipAutoNegotiation:!0});const t=await this.peerManager.createOffer(e);this._sendSignal({type:n.CALL_OFFER,receiverId:e,data:{sdp:t}}),this.emit("callAccepted",{userId:e})}_handleCallEnded(e){this.peerManager.closePeerConnection(e),this.participants.delete(e),this.emit("participantLeft",{userId:e}),0===this.peerManager.getPeerIds().length&&this.endCall()}isInCall(){return null!==this.currentRoom||this.peerManager.getPeerIds().length>0}getCurrentRoom(){return this.currentRoom}getParticipants(){return Array.from(this.participants.keys())}getConnectionSummary(){return this.peerManager.getConnectionSummary()}async getStats(e){return this.peerManager.getStats(e)}getMediaState(){return{videoEnabled:this.mediaManager.isVideoEnabled(),audioEnabled:this.mediaManager.isAudioEnabled(),streamInfo:this.mediaManager.getStreamInfo()}}setLogLevel(e){this.logger.setLevel(e),this.mediaManager.setLogLevel(e),this.peerManager.setLogLevel(e)}destroy(){this.endCall(),this.mediaManager.destroy(),this.peerManager.destroy(),this.removeAllListeners(),this.logger.info("WebRTCClient destroyed")}}const Us=Object.freeze({UNSUPPORTED_BROWSER:"UNSUPPORTED_BROWSER",FIREBASE_NOT_INSTALLED:"FIREBASE_NOT_INSTALLED",SW_REGISTER_FAILED:"SW_REGISTER_FAILED",PERMISSION_DENIED:"PERMISSION_DENIED",TOKEN_FAILED:"TOKEN_FAILED",SERVER_REGISTER_FAILED:"SERVER_REGISTER_FAILED"});class Ws extends Error{constructor(e,t,s){super(t),this.name="PushError",this.code=e,void 0!==s&&(this.cause=s)}}const Fs={apiKey:"AIzaSyB8VhRg6rSvUI7K3Ua7h6sBpLvaQGmIkRc",authDomain:"chatting-c3e5d.firebaseapp.com",projectId:"chatting-c3e5d",storageBucket:"chatting-c3e5d.firebasestorage.app",messagingSenderId:"1020496565673",appId:"1:1020496565673:web:5039167257fd83f5ce20b8"},js="pendingNavigation",$s="pending-room",Hs="deviceInfo",Bs="device-id",Vs="talkflow_device_id";function Gs(){return"undefined"==typeof indexedDB?Promise.resolve(null):new Promise((e,t)=>{const s=indexedDB.open("talkflowPush",2);s.onupgradeneeded=()=>{const e=s.result;e.objectStoreNames.contains(js)||e.createObjectStore(js,{keyPath:"id"}),e.objectStoreNames.contains(Hs)||e.createObjectStore(Hs,{keyPath:"id"})},s.onsuccess=()=>e(s.result),s.onerror=()=>t(s.error||new Error("IndexedDB open failed"))})}function Js(){return Gs().then(e=>e?new Promise((t,s)=>{const i=e.transaction(Hs,"readonly"),n=i.objectStore(Hs).get(Bs);n.onsuccess=()=>{const e=n.result;t(e&&e.value?e.value:null)},n.onerror=()=>s(n.error||new Error("IndexedDB read failed")),i.oncomplete=()=>e.close(),i.onerror=()=>e.close(),i.onabort=()=>e.close()}):null)}function zs(e){return Gs().then(t=>!!t&&new Promise(s=>{try{const i=t.transaction(Hs,"readwrite");i.objectStore(Hs).put({id:Bs,value:e}),i.oncomplete=()=>{t.close(),s(!0)},i.onerror=()=>{t.close(),s(!1)},i.onabort=()=>{t.close(),s(!1)}}catch(e){try{t.close()}catch(e){}s(!1)}})).catch(()=>!1)}function Ks(){return"web-"+("undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substring(2))}async function qs(e){const t=await Gs();if(!t)return null;const s=function(e){return e&&"string"==typeof e&&""!==e.trim()?"pending-room:"+e:$s}(e),i=!!e&&s!==$s;return new Promise((n,r)=>{const o=t.transaction(js,"readwrite"),a=o.objectStore(js);let c=null;const l=a.get(s);l.onsuccess=()=>{const t=l.result;if(t&&t.roomId){if((t.projectId||null)===(e||null))return c=t.roomId,void a.delete(s)}if(!i)return;const n=a.get($s);n.onsuccess=()=>{const e=n.result;e&&e.roomId&&!e.projectId&&(c=e.roomId,a.delete($s))}},l.onerror=()=>{r(l.error||new Error("IndexedDB read failed"))},o.oncomplete=()=>{t.close(),n(c)},o.onerror=()=>{t.close(),r(o.error||new Error("IndexedDB transaction failed"))},o.onabort=()=>{t.close(),r(o.error||new Error("IndexedDB transaction aborted"))}})}class Xs{constructor(e){this.apiClient=e.apiClient,this.projectId=e.projectId||null,this.firebaseConfig=e.firebaseConfig||Fs,this.vapidKey=e.vapidKey||"BGP8qaSm1ntjWd4n9pc0lX_rw4BmMxm9u4pvRIANCitbmYaV0iy-gn05suTKBo88kUBejxdxM8sb6x2nt3avu8c",this.serviceWorkerPath=e.serviceWorkerPath||"/firebase-messaging-sw.js",this.logger=new p(e.logLevel||u.WARN,"PushManager"),this._messaging=null,this._currentToken=null,this._enabled=!1,this._enablePromise=null,this._foregroundMessageUnsubscribe=null,this._swRegistration=null,this._projectRegisteredToSW=!1,this._visibilityHandler=null,this._deviceIdCache=null}static async consumePendingRoom(e){return qs(e)}static getPermissionState(){return"undefined"==typeof window||"undefined"==typeof Notification?"unsupported":"undefined"!=typeof navigator&&"serviceWorker"in navigator?Notification.permission:"unsupported"}async enable(){if(this._enabled)this.logger.debug("푸시 알림이 이미 활성화되어 있습니다.");else{if(this._enablePromise)return this.logger.debug("푸시 알림 활성화가 이미 진행 중입니다."),this._enablePromise;this._enablePromise=this._enableInternal();try{return await this._enablePromise}finally{this._enablePromise=null}}}async _enableInternal(){if("undefined"==typeof window||!("Notification"in window))throw new Ws(Us.UNSUPPORTED_BROWSER,"푸시 알림은 브라우저 환경에서만 사용 가능합니다");if(!("serviceWorker"in navigator))throw new Ws(Us.UNSUPPORTED_BROWSER,"이 브라우저는 서비스 워커를 지원하지 않습니다");if("denied"===Notification.permission)throw new Ws(Us.PERMISSION_DENIED,"알림 권한이 이미 거부되어 있습니다. 브라우저 사이트 설정에서 허용해주세요.");let e,t,s;try{e=await import("firebase/app"),t=await import("firebase/messaging")}catch(e){throw new Ws(Us.FIREBASE_NOT_INSTALLED,"firebase 패키지가 설치되지 않았습니다. npm install firebase 를 실행하세요.",e)}try{s=e.getApp("talkflow")}catch{s=e.initializeApp(this.firebaseConfig,"talkflow")}const i=await this._registerServiceWorker();if("granted"!==await Notification.requestPermission())throw new Ws(Us.PERMISSION_DENIED,"알림 권한이 거부되었습니다. 브라우저 설정에서 허용해주세요.");this._messaging=t.getMessaging(s);const n={serviceWorkerRegistration:i};this.vapidKey&&(n.vapidKey=this.vapidKey);try{this._currentToken=await t.getToken(this._messaging,n)}catch(e){throw new Ws(Us.TOKEN_FAILED,"FCM 토큰 획득 중 오류 발생: "+(e?.message||e),e)}if(!this._currentToken)throw new Ws(Us.TOKEN_FAILED,"FCM 토큰 획득 실패 (응답이 비어있음)");await this._registerTokenToServer(this._currentToken),this._foregroundMessageUnsubscribe&&this._foregroundMessageUnsubscribe(),this._foregroundMessageUnsubscribe=t.onMessage(this._messaging,e=>{this.logger.debug("포그라운드 푸시 수신:",e),this._onForegroundMessage(e)}),this._swRegistration=i,await this._registerProjectToSW(),this._installVisibilityReRegister();try{await i.update()}catch(e){this.logger.debug("SW 업데이트 체크 실패 (무시):",e.message)}const r=await this._getSWVersion(i);r?this.logger.debug("SW 버전:",r):this.logger.warn("[TalkFlow] 서비스 워커가 구버전(v1)입니다. 이미지 미리보기 등 리치 알림 기능을 사용하려면 firebase-messaging-sw.js 를 v2 로 업데이트하세요. 가이드: https://docs.talkflow.ai/push/sw-upgrade"),this._enabled=!0,this.logger.info("푸시 알림 활성화 완료")}async _registerServiceWorker(){try{const e=await navigator.serviceWorker.register(this.serviceWorkerPath,{updateViaCache:"none"});return this.logger.debug("서비스 워커 등록 완료:",this.serviceWorkerPath),e}catch(e){throw new Ws(Us.SW_REGISTER_FAILED,`서비스 워커 등록 실패: ${this.serviceWorkerPath}\n프로젝트 public 폴더에 firebase-messaging-sw.js 파일을 배치하세요.`,e)}}async _registerTokenToServer(e){try{const t=await this._getDeviceId();await this.apiClient.post("/api/v1/push/devices",{deviceToken:e,deviceType:"WEB",deviceId:t}),this.logger.info("디바이스 토큰 서버 등록 완료")}catch(e){if(this.logger.error("디바이스 토큰 서버 등록 실패:",e),e instanceof Ws)throw e;throw new Ws(Us.SERVER_REGISTER_FAILED,"디바이스 토큰 서버 등록 실패: "+(e?.message||e),e)}}async _getDeviceId(){if(this._deviceIdCache)return this._deviceIdCache;try{let e=await Js();if(!e&&"undefined"!=typeof localStorage){const t=localStorage.getItem(Vs);if(t){e=t;if(await zs(e)){if(await Js()===e)try{localStorage.removeItem(Vs),this.logger.debug("deviceId migrated from localStorage to IndexedDB")}catch(e){}else this.logger.warn("deviceId IDB read-back 불일치, localStorage 보존")}else this.logger.warn("deviceId IDB 저장 실패 (private mode / quota 등), localStorage 보존")}}if(!e){e=Ks();await zs(e)||this.logger.warn("신규 deviceId IDB 저장 실패, 이번 세션만 유효")}return this._deviceIdCache=e,e}catch(e){if(this.logger.warn("IndexedDB deviceId 조회/저장 실패, fallback:",e),!this._deviceIdCache){let e=null;if("undefined"!=typeof localStorage)try{e=localStorage.getItem(Vs)}catch(e){}this._deviceIdCache=e||Ks()}return this._deviceIdCache}}_onForegroundMessage(e){}async consumePendingRoom(){return Xs.consumePendingRoom(this.projectId)}reset(){if(this._foregroundMessageUnsubscribe)try{this._foregroundMessageUnsubscribe()}catch(e){this.logger.debug("포그라운드 푸시 리스너 해제 실패 (무시):",e?.message||e)}this._uninstallVisibilityReRegister(),this._unregisterProjectFromSW(),this._foregroundMessageUnsubscribe=null,this._enablePromise=null,this._messaging=null,this._currentToken=null,this._enabled=!1,this._swRegistration=null,this._projectRegisteredToSW=!1}async _registerProjectToSW(){if(this.projectId)try{const e=(await navigator.serviceWorker.ready).active||this._swRegistration&&this._swRegistration.active;if(!e)return void this.logger.debug("SW active worker 없음 — projectId 등록 스킵");e.postMessage({type:"TALKFLOW_REGISTER_PROJECT",projectId:this.projectId}),this._projectRegisteredToSW=!0}catch(e){this.logger.debug("SW projectId 등록 실패 (무시):",e?.message||e)}}_unregisterProjectFromSW(){if(this._projectRegisteredToSW)try{if("undefined"==typeof navigator||!navigator.serviceWorker)return;const e=navigator.serviceWorker.controller;if(!e)return;e.postMessage({type:"TALKFLOW_UNREGISTER_PROJECT"})}catch(e){this.logger.debug("SW projectId 해제 실패 (무시):",e?.message||e)}}_installVisibilityReRegister(){"undefined"==typeof document||this._visibilityHandler||(this._visibilityHandler=()=>{"visible"===document.visibilityState&&this._enabled&&this.projectId&&this._registerProjectToSW().catch(()=>{})},document.addEventListener("visibilitychange",this._visibilityHandler))}_uninstallVisibilityReRegister(){if("undefined"!=typeof document&&this._visibilityHandler){try{document.removeEventListener("visibilitychange",this._visibilityHandler)}catch(e){}this._visibilityHandler=null}}getToken(){return this._currentToken}isEnabled(){return this._enabled}async getMyDevices(){const e=await this.apiClient.get("/api/v1/push/devices/me");return e&&"object"==typeof e&&"data"in e?e.data:e}async setDeviceEnabled(e,t){await this.apiClient.patch("/api/v1/push/devices/me/enabled",{deviceId:e,enabled:t}),this.logger.info(`디바이스 푸시 enabled=${t}: deviceId=${e}`)}async setCurrentDeviceEnabled(e){const t=await this._getDeviceId();await this.setDeviceEnabled(t,e)}async _getSWVersion(e){try{const t=await navigator.serviceWorker.ready,s=t.waiting||t.installing||t.active||e.waiting||e.installing||e.active;return s?new Promise(e=>{const t=setTimeout(()=>e(null),2e3),i=new MessageChannel;i.port1.onmessage=s=>{clearTimeout(t),e(s.data?.version||null)};try{s.postMessage({type:"TALKFLOW_SW_VERSION"},[i.port2])}catch(s){clearTimeout(t),e(null)}}):null}catch{return null}}setLogLevel(e){this.logger.setLevel(e)}}const Ys=[["connected","connected"],["disconnected","disconnected"],["reconnecting","reconnecting"],["error","connectionError"]],Qs=[["message","chatMessage"],["newMessage","newChatMessage"],["messageUpdated","messageUpdated"],["messageDeleted","messageDeleted"],["reactionChanged","reactionChanged"],["linkPreviewAttached","linkPreviewAttached"],["messageTranslated","messageTranslated"],["messageRead","messageRead"],["typing","typing"],["memberJoined","memberJoined"],["memberLeft","memberLeft"],["roomSubscribed","roomSubscribed"],["roomUnsubscribed","roomUnsubscribed"],["roomListSubscribed","roomListSubscribed"],["roomListUnsubscribed","roomListUnsubscribed"],["roomListUpdate","roomListUpdate"],["roomListMessage","roomListMessage"],["roomListCreated","roomListCreated"],["roomListJoined","roomListJoined"],["roomListLeft","roomListLeft"],["roomListSelfLeft","roomListSelfLeft"],["roomListKicked","roomListKicked"],["roomListSelfKicked","roomListSelfKicked"],["roomListBanned","roomListBanned"],["roomListSelfBanned","roomListSelfBanned"],["roomListRoomUpdated","roomListRoomUpdated"],["retentionCleanup","retentionCleanup"]],Zs=[["localStreamStarted","localStreamStarted"],["localStreamStopped","localStreamStopped"],["remoteTrack","remoteTrack"],["screenShareStarted","screenShareStarted"],["screenShareEnded","screenShareEnded"],["deviceChange","deviceChange"],["mediaStateChanged","mediaStateChanged"],["callStarted","callStarted"],["callEnded","callEnded"],["callRequested","callRequested"],["callAccepted","callAccepted"],["callRejected","callRejected"],["callCancelled","callCancelled"],["callBusy","callBusy"],["incomingCall","incomingCall"],["incomingCallWhileBusy","incomingCallWhileBusy"],["callInvitation","callInvitation"],["userJoined","userJoined"],["userLeft","userLeft"],["participantLeft","participantLeft"],["participantMediaState","participantMediaState"],["peerConnected","peerConnected"],["peerDisconnected","peerDisconnected"],["peerClosed","peerClosed"],["error","webrtcError"]];function ei(e,t,s){s.forEach(([s,i])=>{e.on(s,e=>{t.emit(i,e)})})}const ti=["getRooms","getRoom","getRoomInfo","setMyRoomLanguage","createOneToOneRoom","createGroupRoom","joinGroupRoom","leaveRoom","updateGroupRoom","inviteToGroupRoom","kickMember","banMember","unbanMember","getBannedMembers","getAvailableGroupRooms","getAllGroupRooms","enterRoom","getMessages","fetchLinkPreview","sendMessage","sendMessageOptimistic","sendTextMessage","sendTextMessageOptimistic","sendReply","sendReplyOptimistic","uploadFile","sendFileMessage","sendFileMessageOptimistic","editMessage","deleteMessage","markAsRead","pinMessage","unpinMessage","toggleReaction","subscribeRoom","unsubscribeRoom","unsubscribeAllRooms","setActiveRoom","clearActiveRoom","getActiveRoom","subscribeRoomList","unsubscribeRoomList","isRoomListSubscribed","getSubscribedRooms","isSubscribed","startTyping","stopTyping","getAssistants","getRoomAiMeta","rateAssistantMessage","summarizeWithAssistant","translateWithAssistant","getRoomPmPrompt","upsertRoomPmPrompt","activateRoomPmPrompt","deactivateRoomPmPrompt","getRoomPmPromptVersions","activateRoomPmPromptVersion","previewRoomPmPrompt"],si=["initializeIceServers","getTurnCredentials","createCallRoom","getCallRoom","joinCallRoomApi","leaveCallRoomApi","enableIncomingCalls","disableIncomingCalls","isIncomingCallsEnabled","startCall","callUser","acceptCall","rejectCall","cancelCall","endCall","toggleVideo","toggleAudio","setVideoEnabled","setAudioEnabled","startScreenShare","stopScreenShare","getLocalStream","getDevices","switchDevice","startDeviceChangeDetection","stopDeviceChangeDetection","applyVideoConstraints","getVideoSettings","getAudioSettings","isInCall","getCurrentRoom","getParticipants","getMediaState","getConnectionSummary","getStats"];function ii(e,t,s){s.forEach(s=>{e[s]=function(...e){return this[t][s](...e)}})}class ni extends t{constructor(e){super(),this._validateOptions(e);const t=e.env||h.environment,i=(e.serverUrl||d(t)).replace(/\/$/,"");this.options={serverUrl:i,env:t,apiKey:e.apiKey,projectId:e.projectId,jwtToken:e.jwtToken||null,useSockJS:!1!==e.useSockJS,reconnectDelay:e.reconnectDelay||h.reconnectDelay,maxReconnectAttempts:e.maxReconnectAttempts||h.maxReconnectAttempts,iceServers:e.iceServers||h.iceServers,autoSubscribeRoomList:!1!==e.autoSubscribeRoomList,logLevel:void 0!==e.logLevel?e.logLevel:u.WARN},this.logger=new p(this.options.logLevel,"TalkFlowClient"),this._initialized=!1,this._state=s.DISCONNECTED,this._userId=null,this.options.jwtToken&&(this._userId=_(this.options.jwtToken)),this.apiClient=new g({baseUrl:this.options.serverUrl,apiKey:this.options.apiKey,projectId:this.options.projectId,jwtToken:this.options.jwtToken,logLevel:this.options.logLevel}),this.connectionManager=null,this._chat=null,this._webrtc=null,this._pushManager=null,this._pushEnablePromise=null,this.options.jwtToken&&this._userId&&this._initializeSubClients(),this._initialized=!0,this.logger.info("TalkFlowClient initialized",{userId:this._userId,hasToken:!!this.options.jwtToken})}get chat(){return this._chat}get webrtc(){return this._webrtc}get pushManager(){return this._pushManager}get userId(){return this._userId}_validateOptions(e){if(!e)throw new Error("Options are required");if(!e.apiKey)throw new Error("apiKey is required");if(!e.projectId)throw new Error("projectId is required");if(e.apiKey.startsWith("sk-")){const t=e.env||"production";"development"===t?console.warn("⚠️ [TalkFlow] Server Key (sk-) 를 개발 모드에서 사용 중입니다. 프로덕션 배포 전에 반드시 Client Key (ck-) 로 교체하세요."):console.error("🚨 [TalkFlow] Server Key (sk-) 가 비개발 환경 ("+t+") 에서 감지되었습니다. 보안 위험: Server Key 를 브라우저에 포함하면 공격자가 임의 사용자로 JWT 를 발급받을 수 있습니다. 반드시 Client Key (ck-) 로 교체하세요. 서버에서도 프로덕션 모드에서 Server Key 의 브라우저 호출을 차단합니다.")}}_initializeSubClients(){!function(e){if(!e.connectionManager){if(!e.userId)throw new Error("userId is required to initialize sub-clients. Please set JWT token first.");e.connectionManager=new Ms({serverUrl:e.options.serverUrl,jwtToken:e.options.jwtToken,apiKey:e.options.apiKey,projectId:e.options.projectId,useSockJS:e.options.useSockJS,reconnectDelay:e.options.reconnectDelay,maxReconnectAttempts:e.options.maxReconnectAttempts,logLevel:e.options.logLevel}),e._chat=new Ls({connectionManager:e.connectionManager,apiClient:e.apiClient,userId:e._userId,logLevel:e.options.logLevel}),e._webrtc=new xs({connectionManager:e.connectionManager,apiClient:e.apiClient,userId:e._userId,iceServers:e.options.iceServers,logLevel:e.options.logLevel}),e._setupEventForwarding(),e.logger.debug("Sub-clients initialized")}}(this)}_setupEventForwarding(){var e;(e=this).connectionManager&&(e.connectionManager.on("stateChange",({state:t,prevState:s})=>{e._state=t,e.emit("stateChange",{state:t,prevState:s})}),ei(e.connectionManager,e,Ys),e.chat&&ei(e.chat,e,Qs),e.webrtc&&ei(e.webrtc,e,Zs))}isConnected(){return!!this.connectionManager&&this.connectionManager.isConnected()}getState(){return this._state}hasToken(){return!!this.options.jwtToken}async registerUser(e){const t={...e};if(void 0===t.preferredLanguage){const e=ni.detectBrowserLanguage();e&&(t.preferredLanguage=e)}const s=await this.apiClient.post("/api/v1/users/auth",t);return s.data&&s.data.accessToken&&(await this.setToken(s.data.accessToken),this.logger.info("User authenticated, token auto-set")),s}async updateMyInfo(e){return this._checkToken(),this.apiClient.put("/api/v1/users/update",e)}async setPreferredLanguage(e){return this.updateMyInfo({preferredLanguage:e})}static detectBrowserLanguage(){return"undefined"!=typeof navigator&&navigator.language&&navigator.language.trim().toLowerCase()||null}static displayText(e,t){return e&&e.translations&&t&&e.translations[t]?e.translations[t]:e?e.content:null}async checkUserExists(e){return this.apiClient.get(`/api/v1/users/${e}/exists`)}async getUsers(e={}){this._checkToken();const{size:t=50,lastId:s,lastSortValue:i}=e;return this.apiClient.get("/api/v1/users",{size:t,lastId:s,lastSortValue:i})}async searchUsers(e){this._checkToken();const{keyword:t,limit:s=20}=e;return this.apiClient.get("/api/v1/users/search",{keyword:t,limit:s})}_checkToken(){if(!this.options.jwtToken)throw new Error('JWT token is required for this operation. Obtain it from your backend (POST /api/v1/users/auth with Server API Key) and pass it via setToken(). See README "프로덕션 인증 플로우".')}getUserId(){return this.userId}isInitialized(){return this._initialized}isReady(){return this._initialized&&!!this.connectionManager}setLogLevel(e){this.options.logLevel=e,this.logger.setLevel(e),this.apiClient.logger?.setLevel(e),this.connectionManager&&this.connectionManager.setLogLevel(e),this.chat&&this.chat.setLogLevel(e),this.webrtc&&this.webrtc.setLogLevel(e)}getStatus(){return{initialized:this._initialized,ready:this.isReady(),hasToken:this.hasToken(),connectionState:this._state,isConnected:this.isConnected(),userId:this.userId,chat:this.chat?{subscribedRooms:this.chat.getSubscribedRooms()}:null,webrtc:this.webrtc?{isInCall:this.webrtc.isInCall(),currentRoom:this.webrtc.getCurrentRoom(),participants:this.webrtc.getParticipants(),mediaState:this.webrtc.getMediaState()}:null}}async destroy(){await this.disconnect(),this.chat&&this.chat.destroy(),this.webrtc&&this.webrtc.destroy(),this.connectionManager&&await this.connectionManager.destroy(),this.removeAllListeners(),this._initialized=!1,this.logger.info("TalkFlowClient destroyed")}}ni.ConnectionState=s,ni.ErrorTypes=i,ni.LogLevel=u,ni.Environment=c,function(e){e.prototype.connect=async function(e,t={}){const{enablePush:s=!1}=t;if(e&&await this.setToken(e),!this.options.jwtToken)throw new Error('JWT token is required. Obtain it from your backend (which calls POST /api/v1/users/auth with a Server API Key) and pass it to the SDK via the jwtToken option, setToken(), or connect(jwt). See README "프로덕션 인증 플로우".');if(y(this.options.jwtToken))throw new Error("JWT token has expired. Please update the token before connecting.");if(this.connectionManager||this._initializeSubClients(),await this.connectionManager.connect(),this.webrtc&&await this.webrtc.enableIncomingCalls(),this.chat&&this.options.autoSubscribeRoomList)try{await this.chat.subscribeRoomList()}catch(e){this.logger.warn("Failed to auto-subscribe room list (non-fatal):",e)}s&&this.enablePushNotifications(),this.logger.info("Connected to server")},e.prototype.disconnect=async function(){this.connectionManager&&(this.webrtc&&this.webrtc.isInCall()&&this.webrtc.endCall(),this.webrtc&&this.webrtc.disableIncomingCalls(),this.chat&&(this.chat.unsubscribeAllRooms(),this.chat.unsubscribeRoomList()),await this.connectionManager.disconnect(),this.logger.info("Disconnected from server"))},e.prototype.logout=async function(){try{await this.apiClient.post("/v1/auth/signout"),this.logger.info("Logged out from server")}catch(e){this.logger.warn("Server logout failed (proceeding with local cleanup):",e.message)}await this.disconnect(),this.pushManager&&(this.pushManager.reset(),this._pushEnablePromise=null),this.options.jwtToken=null,this._userId=null,this.apiClient.setJwtToken(null),this.emit("loggedOut")},e.prototype.enablePushNotifications=async function(e={}){if(!this.options.jwtToken){const e=new Error("JWT token is required to enable push notifications.");return this.emit("pushFailed",{reason:"NO_TOKEN",error:e}),{ok:!1,reason:"NO_TOKEN",error:e}}if(!this.pushManager){this._pushManager=new Xs({apiClient:this.apiClient,projectId:this.options.projectId,firebaseConfig:e.firebaseConfig,vapidKey:e.vapidKey,serviceWorkerPath:e.serviceWorkerPath,logLevel:this.options.logLevel});const t=3e5;this.pushManager._onForegroundMessage=e=>{const s=e.data||{};if(s.projectId&&s.projectId!==this.options.projectId)return void this.logger.debug("다른 프로젝트 푸시 무시:",s.projectId);const i=this.chat?.getActiveRoom();if(i&&i===s.roomId)this.logger.debug("포그라운드 푸시 suppress (현재 방):",s.roomId);else{if(s.messageId){if(this._recentPushMessageIds||(this._recentPushMessageIds=new Map),this._recentPushMessageIds.has(s.messageId))return void this.logger.debug("포그라운드 푸시 dedup:",s.messageId);const e=setTimeout(()=>{this._recentPushMessageIds.delete(s.messageId)},t);this._recentPushMessageIds.set(s.messageId,e)}this.emit("pushNotification",{title:e.notification?.title||s.title,body:e.notification?.body||s.body,data:s})}}}if(this.pushManager.isEnabled())return this.logger.debug("웹 푸시가 이미 활성화되어 있어 중복 호출을 건너뜁니다."),{ok:!0,alreadyEnabled:!0};if(this._pushEnablePromise)return this.logger.debug("웹 푸시 활성화가 이미 진행 중입니다."),this._pushEnablePromise;const t=(async()=>{try{return await this.pushManager.enable(),this.emit("pushEnabled"),{ok:!0}}catch(e){const t=e&&e.code?e.code:"UNKNOWN";return this.logger.warn("Failed to enable push notifications:",t,e?.message),this.emit("pushFailed",{reason:t,error:e}),{ok:!1,reason:t,error:e}}})();return this._pushEnablePromise=t,t.finally(()=>{this._pushEnablePromise===t&&(this._pushEnablePromise=null)}),t},e.prototype.consumePendingRoom=async function(){return Xs.consumePendingRoom(this.options.projectId)},e.prototype.setCurrentDeviceEnabled=function(e){return this.pushManager?.setCurrentDeviceEnabled(e)},e.prototype.setDeviceEnabled=function(e,t){return this.pushManager?.setDeviceEnabled(e,t)},e.prototype.getMyDevices=function(){return this.pushManager?.getMyDevices()},e.prototype.getPushPermissionState=function(){return Xs.getPermissionState()},e.prototype.isPushEnabled=function(){return this.pushManager?.isEnabled()??!1},e.prototype.getPushToken=function(){return this.pushManager?.getToken()??null},e.prototype.resetPush=function(){this.pushManager?.reset(),this._pushEnablePromise=null},e.prototype.setToken=async function(e){const{userId:t}=b(e,{validateExpiry:!1}),s=this.userId&&this.userId!==t;this.options.jwtToken=e,this._userId=t,this.apiClient.setJwtToken(e),s&&this.connectionManager?(await this.disconnect(),this.pushManager&&(this.pushManager.reset(),this._pushEnablePromise=null),this.connectionManager=null,this._chat=null,this._webrtc=null,this._initializeSubClients()):this.connectionManager?this.connectionManager.updateToken(e):this._initializeSubClients(),this.logger.info("JWT token set",{userId:t}),this.emit("tokenSet",{userId:t})},e.prototype.updateToken=async function(e){await this.setToken(e)}}(ni),function(e){ii(e.prototype,"chat",ti),ii(e.prototype,"webrtc",si)}(ni),e.AssistantMode={GENERAL:"GENERAL",PEOPLE_ONLY:"PEOPLE_ONLY",CALL_ONLY:"CALL_ONLY"},e.ChatClient=Ls,e.ChatMessageType={TEXT:"TEXT",IMAGE:"IMAGE",FILE:"FILE",VIDEO:"VIDEO",AUDIO:"AUDIO",SYSTEM:"SYSTEM"},e.ChatRoomType=r,e.ConnectionManager=Ms,e.ConnectionState=s,e.DefaultConfig=h,e.Endpoints=l,e.EngagementIntensity={QUIET:"QUIET",NORMAL:"NORMAL",ACTIVE:"ACTIVE"},e.Environment=c,e.ErrorTypes=i,e.EventEmitter=t,e.LogLevel=u,e.Logger=p,e.MediaStreamManager=Ds,e.PeerConnectionManager=Ps,e.PersonaRole={LEGAL_ADVISOR:"LEGAL_ADVISOR",MARKETING:"MARKETING",PRODUCT_PLANNING:"PRODUCT_PLANNING",HR:"HR",FINANCE:"FINANCE",CUSTOMER_SUPPORT:"CUSTOMER_SUPPORT",SALES:"SALES",ENGINEERING:"ENGINEERING",DATA_ANALYST:"DATA_ANALYST",PROJECT_MANAGEMENT:"PROJECT_MANAGEMENT",RESEARCH:"RESEARCH",TRANSLATION:"TRANSLATION",DESIGN:"DESIGN",PM:"PM"},e.PmPromptLayerEditorType={SUPER_ADMIN:"SUPER_ADMIN",PROJECT_ADMIN:"PROJECT_ADMIN",ROOM_OWNER:"ROOM_OWNER"},e.PmPromptLayerScope={PROJECT:"PROJECT",ROOM:"ROOM"},e.PushError=Ws,e.PushErrorCode=Us,e.PushManager=Xs,e.RoomAiType={NONE:"NONE",PERSONA_MULTI:"PERSONA_MULTI",PM_BACKSTAGE:"PM_BACKSTAGE"},e.RoomListEventType=o,e.SenderType={USER:"USER",ASSISTANT:"ASSISTANT"},e.SignalTypes=n,e.SummarizeFormat={MINUTES:"MINUTES",SHORT:"SHORT",TIMELINE:"TIMELINE",ACTIONS:"ACTIONS",OPTIONS:"OPTIONS"},e.WebRTCClient=xs,e.WebSocketPaths=a,e.decodeJWTPayload=function(e){try{const t=m(e).split(".");return 3!==t.length?null:JSON.parse(f(t[1]))}catch(e){return console.error("Failed to decode JWT payload:",e),null}},e.default=ni,e.extractUserIdFromJWT=_,e.getJWTRemainingTime=function(e){try{const t=m(e).split(".");if(3!==t.length)return-1;const s=JSON.parse(f(t[1]));return s.exp?1e3*s.exp-Date.now():1/0}catch(e){return console.error("Failed to get JWT remaining time:",e),-1}},e.getServerUrl=d,e.isJWTExpired=y,e.validateAndParseJWT=b,Object.defineProperty(e,"__esModule",{value:!0})});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TalkFlowSDK={})}(this,function(e){"use strict";class t{constructor(){this._events=new Map}on(e,t){return this._events.has(e)||this._events.set(e,new Set),this._events.get(e).add(t),()=>this.off(e,t)}once(e,t){const s=(...i)=>{this.off(e,s),t.apply(this,i)};return s._originalListener=t,this.on(e,s)}off(e,t){const s=this._events.get(e);if(s){for(const e of s)if(e===t||e._originalListener===t){s.delete(e);break}0===s.size&&this._events.delete(e)}}emit(e,t){const s=this._events.get(e);s&&s.forEach(s=>{try{s(t)}catch(t){console.error(`Error in event listener for '${e}':`,t)}})}removeAllListeners(e){e?this._events.delete(e):this._events.clear()}listenerCount(e){const t=this._events.get(e);return t?t.size:0}eventNames(){return Array.from(this._events.keys())}}const s={DISCONNECTED:"disconnected",CONNECTING:"connecting",CONNECTED:"connected",RECONNECTING:"reconnecting",ERROR:"error"},i={CONNECTION_FAILED:"CONNECTION_FAILED",CONNECTION_LOST:"CONNECTION_LOST",CONNECTION_TIMEOUT:"CONNECTION_TIMEOUT",JWT_INVALID:"JWT_INVALID",JWT_EXPIRED:"JWT_EXPIRED",JWT_PARSE_FAILED:"JWT_PARSE_FAILED",UNAUTHORIZED:"UNAUTHORIZED",API_ERROR:"API_ERROR",API_TIMEOUT:"API_TIMEOUT",CHAT_ROOM_NOT_FOUND:"CHAT_ROOM_NOT_FOUND",CHAT_MESSAGE_FAILED:"CHAT_MESSAGE_FAILED",CHAT_SUBSCRIPTION_FAILED:"CHAT_SUBSCRIPTION_FAILED",MEDIA_ACCESS_DENIED:"MEDIA_ACCESS_DENIED",SCREEN_SHARE_DENIED:"SCREEN_SHARE_DENIED",PEER_CONNECTION_FAILED:"PEER_CONNECTION_FAILED",ICE_CONNECTION_FAILED:"ICE_CONNECTION_FAILED",SIGNALING_FAILED:"SIGNALING_FAILED",DEVICE_SWITCH_FAILED:"DEVICE_SWITCH_FAILED",ENUMERATE_DEVICES_FAILED:"ENUMERATE_DEVICES_FAILED",CALL_ROOM_NOT_FOUND:"CALL_ROOM_NOT_FOUND",INVALID_STATE:"INVALID_STATE",UNKNOWN_ERROR:"UNKNOWN_ERROR"},n={CALL_OFFER:"call_offer",CALL_ANSWER:"call_answer",ICE_CANDIDATE:"ice_candidate",JOIN_ROOM:"join_room",LEAVE_ROOM:"leave_room",PEER_JOINED:"peer_joined",PEER_LEFT:"peer_left",VIDEO_STATE_CHANGED:"video_state_changed",AUDIO_STATE_CHANGED:"audio_state_changed",SCREEN_SHARE_STARTED:"screen_share_started",SCREEN_SHARE_ENDED:"screen_share_ended",CALL_REQUEST:"call_request",CALL_ACCEPT:"call_accept",CALL_REJECT:"call_reject",CALL_CANCEL:"call_cancel",CALL_END:"call_end",CALL_INVITATION:"call_invitation",CALL_BUSY:"call_busy"},r={DIRECT:"DIRECT",GROUP:"GROUP",PRIVATE_GROUP:"PRIVATE_GROUP",TEAM:"TEAM"},o={MESSAGE_RECEIVED:"MESSAGE_RECEIVED",MESSAGE_DELETED:"MESSAGE_DELETED",MESSAGE_UPDATED:"MESSAGE_UPDATED",ROOM_CREATED:"ROOM_CREATED",ROOM_JOINED:"ROOM_JOINED",ROOM_LEFT:"ROOM_LEFT",ROOM_UPDATED:"ROOM_UPDATED",ROOM_KICKED:"ROOM_KICKED",ROOM_BANNED:"ROOM_BANNED",MESSAGE_RETENTION_CLEANUP:"MESSAGE_RETENTION_CLEANUP"},a={SOCKJS_ENDPOINT:"/ws-chat",NATIVE_ENDPOINT:"/ws-chat-native",APP_PREFIX:"/app",TOPIC_PREFIX:"/topic",QUEUE_PREFIX:"/queue",USER_PREFIX:"/user",getChatDestination:e=>`/topic/chat/${e}`,getChatReadDestination:e=>`/topic/chat/${e}/read`,getChatTypingDestination:e=>`/topic/chat/${e}/typing`,getChatAssistantStreamDestination:e=>`/topic/chat/${e}/assistant-stream`,ROOM_LIST_USER_DESTINATION:"/user/queue/rooms",getWebRTCDestination:e=>`/topic/webrtc/${e}`,getWebRTCUserDestination:()=>"/user/queue/webrtc",CHAT_SEND:"/app/chat/send",CHAT_READ:"/app/chat/read",CHAT_TYPING:"/app/chat/typing",WEBRTC_SIGNAL:"/app/webrtc/signal"},c={DEVELOPMENT:"development",STAGING:"staging",PRODUCTION:"production"},l={[c.DEVELOPMENT]:{serverUrl:"https://dev-chat.apiorbit.net",wsEndpoint:"/ws-chat"},[c.STAGING]:{serverUrl:"https://stg-api.talk-x.app",wsEndpoint:"/ws-chat"},[c.PRODUCTION]:{serverUrl:"https://prod-api.talk-x.app",wsEndpoint:"/ws-chat"}},h={environment:c.PRODUCTION,reconnectDelay:5e3,maxReconnectAttempts:10,heartbeatIncoming:1e4,heartbeatOutgoing:1e4,apiTimeout:3e4,iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],logLevel:2};function d(e){return(l[e]||l[c.PRODUCTION]).serverUrl}const u={DEBUG:0,INFO:1,WARN:2,ERROR:3,NONE:4};class p{constructor(e=u.WARN,t="TalkFlow"){this.level=e,this.prefix=t}setLevel(e){this.level=e}setPrefix(e){this.prefix=e}_format(e,...t){return[`[${(new Date).toISOString()}] [${e}] [${this.prefix}]`,...t]}debug(...e){this.level<=u.DEBUG&&console.debug(...this._format("DEBUG",...e))}info(...e){this.level<=u.INFO&&console.info(...this._format("INFO",...e))}warn(...e){this.level<=u.WARN&&console.warn(...this._format("WARN",...e))}error(...e){this.level<=u.ERROR&&console.error(...this._format("ERROR",...e))}}class g{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.apiKey=e.apiKey,this.projectId=e.projectId,this.jwtToken=e.jwtToken,this.timeout=e.timeout||h.apiTimeout,this.logger=new p(e.logLevel,"ApiClient")}setJwtToken(e){this.jwtToken=e}_getHeaders(){const e={"Content-Type":"application/json","X-API-KEY":this.apiKey,"X-PROJECT-ID":this.projectId};return this.jwtToken&&(e.Authorization=this.jwtToken.startsWith("Bearer ")?this.jwtToken:`Bearer ${this.jwtToken}`),e}async request(e,t,s={}){const{body:n,params:r}=s;let o=`${this.baseUrl}${t}`;if(r){const e=new URLSearchParams;Object.entries(r).forEach(([t,s])=>{null!=s&&e.append(t,s)});const t=e.toString();t&&(o+=`?${t}`)}const a=new AbortController,c=setTimeout(()=>a.abort(),this.timeout);let l;try{this.logger.debug(`${e} ${o}`,n?{body:n}:""),l=await fetch(o,{method:e,headers:this._getHeaders(),body:n?JSON.stringify(n):void 0,signal:a.signal})}catch(t){if(clearTimeout(c),"AbortError"===t.name){const e=new Error("Request timeout");throw e.code=i.API_TIMEOUT,e}throw this.logger.error(`API Error: ${e} ${o}`,t),t}clearTimeout(c);const h=l.headers.get("content-type");let d;if(d=h&&h.includes("application/json")?await l.json():await l.text(),!l.ok){const t=new Error(d?.message||`HTTP ${l.status}`);throw t.code=i.API_ERROR,t.status=l.status,t.response=d,this.logger.error(`API Error: ${e} ${o}`,t),t}return this.logger.debug(`Response ${l.status}:`,d),d}get(e,t){return this.request("GET",e,{params:t})}post(e,t,s){return this.request("POST",e,{body:t,params:s})}put(e,t){return this.request("PUT",e,{body:t})}patch(e,t){return this.request("PATCH",e,{body:t})}delete(e,t){return this.request("DELETE",e,{params:t})}upload(e,t,s={}){const{fieldName:n="file",onProgress:r,signal:o,timeout:a=6e5}=s;return new Promise((s,c)=>{const l=`${this.baseUrl}${e}`,h=new XMLHttpRequest,d=new FormData;d.append(n,t),h.open("POST",l),h.timeout=a,h.setRequestHeader("X-API-KEY",this.apiKey),h.setRequestHeader("X-PROJECT-ID",this.projectId),this.jwtToken&&h.setRequestHeader("Authorization",this.jwtToken.startsWith("Bearer ")?this.jwtToken:`Bearer ${this.jwtToken}`),"function"==typeof r&&(h.upload.onprogress=e=>{e.lengthComputable&&r({loaded:e.loaded,total:e.total,percent:Math.round(e.loaded/e.total*100)})});const u=()=>h.abort();if(o){if(o.aborted)return void c(new Error("Upload cancelled"));o.addEventListener("abort",u)}const p=()=>{o&&o.removeEventListener("abort",u)};h.onload=()=>{p();let e=h.responseText;if((h.getResponseHeader("content-type")||"").includes("application/json"))try{e=JSON.parse(h.responseText)}catch{}if(h.status>=200&&h.status<300)this.logger.debug(`Upload ${h.status}:`,e),s(e);else{const t=new Error(e?.message||`HTTP ${h.status}`);t.code=i.API_ERROR,t.status=h.status,t.response=e,this.logger.error(`Upload Error: POST ${l}`,t),c(t)}},h.onerror=()=>{p();const e=new Error("Network error during upload");e.code=i.API_ERROR,this.logger.error(`Upload Network Error: POST ${l}`,e),c(e)},h.ontimeout=()=>{p();const e=new Error("Upload timeout");e.code=i.API_TIMEOUT,this.logger.error(`Upload Timeout: POST ${l}`,e),c(e)},h.onabort=()=>{p(),c(new Error("Upload cancelled"))},this.logger.debug(`POST ${l} (multipart, ${t.size} bytes)`),h.send(d)})}}function m(e){return e&&"string"==typeof e?e.replace(/^Bearer\s+/i,""):""}function f(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const s=t.length%4;s&&(t+="=".repeat(4-s));const i=atob(t),n=Uint8Array.from(i,e=>e.charCodeAt(0));return(new TextDecoder).decode(n)}function b(e,t={}){const{bufferSeconds:s=30,validateExpiry:n=!0}=t;if(!e||"string"!=typeof e){const e=new Error("JWT token is required");throw e.code=i.JWT_INVALID,e}const r=m(e).split(".");if(3!==r.length){const e=new Error("Invalid JWT format: expected 3 parts separated by dots");throw e.code=i.JWT_INVALID,e}let o;try{o=JSON.parse(f(r[1]))}catch(e){const t=new Error("Invalid JWT: failed to decode payload");throw t.code=i.JWT_PARSE_FAILED,t.originalError=e,t}if(n&&o.exp){const e=1e3*o.exp,t=1e3*s,n=Date.now();if(e<n+t){const t=new Error(e<n?"JWT token expired":`JWT token expires within ${s} seconds`);throw t.code=i.JWT_EXPIRED,t.expiredAt=new Date(e).toISOString(),t}}if(o.iat){const e=6e4;if(1e3*o.iat>Date.now()+e){const e=new Error("JWT token issued in the future");throw e.code=i.JWT_INVALID,e}}const a=o.userId||o.sub||o.user_id;if(!a){const e=new Error("Cannot extract userId from JWT: missing userId, sub, or user_id claim");throw e.code=i.JWT_INVALID,e}return{userId:a,payload:o}}function _(e){try{const t=m(e).split(".");if(3!==t.length)return null;const s=JSON.parse(f(t[1]));return s.userId||s.sub||s.user_id||null}catch(e){return console.error("Failed to extract userId from JWT:",e),null}}function y(e,t=0){try{const s=m(e).split(".");if(3!==s.length)return!0;const i=JSON.parse(f(s[1]));if(!i.exp)return!1;const n=1e3*i.exp,r=1e3*t;return n<Date.now()+r}catch(e){return console.error("Failed to check JWT expiration:",e),!0}}const E="\n",v="\0";class S{get body(){return!this._body&&this.isBinaryBody&&(this._body=(new TextDecoder).decode(this._binaryBody)),this._body||""}get binaryBody(){return this._binaryBody||this.isBinaryBody||(this._binaryBody=(new TextEncoder).encode(this._body)),this._binaryBody}constructor(e){const{command:t,headers:s,body:i,binaryBody:n,escapeHeaderValues:r,skipContentLengthHeader:o}=e;this.command=t,this.headers=Object.assign({},s||{}),n?(this._binaryBody=n,this.isBinaryBody=!0):(this._body=i||"",this.isBinaryBody=!1),this.escapeHeaderValues=r||!1,this.skipContentLengthHeader=o||!1}static fromRawFrame(e,t){const s={},i=e=>e.replace(/^\s+|\s+$/g,"");for(const n of e.headers.reverse()){n.indexOf(":");const r=i(n[0]);let o=i(n[1]);t&&"CONNECT"!==e.command&&"CONNECTED"!==e.command&&(o=S.hdrValueUnEscape(o)),s[r]=o}return new S({command:e.command,headers:s,binaryBody:e.binaryBody,escapeHeaderValues:t})}toString(){return this.serializeCmdAndHeaders()}serialize(){const e=this.serializeCmdAndHeaders();return this.isBinaryBody?S.toUnit8Array(e,this._binaryBody).buffer:e+this._body+v}serializeCmdAndHeaders(){const e=[this.command];this.skipContentLengthHeader&&delete this.headers["content-length"];for(const t of Object.keys(this.headers||{})){const s=this.headers[t];this.escapeHeaderValues&&"CONNECT"!==this.command&&"CONNECTED"!==this.command?e.push(`${t}:${S.hdrValueEscape(`${s}`)}`):e.push(`${t}:${s}`)}return(this.isBinaryBody||!this.isBodyEmpty()&&!this.skipContentLengthHeader)&&e.push(`content-length:${this.bodyLength()}`),e.join(E)+E+E}isBodyEmpty(){return 0===this.bodyLength()}bodyLength(){const e=this.binaryBody;return e?e.length:0}static sizeOfUTF8(e){return e?(new TextEncoder).encode(e).length:0}static toUnit8Array(e,t){const s=(new TextEncoder).encode(e),i=new Uint8Array([0]),n=new Uint8Array(s.length+t.length+i.length);return n.set(s),n.set(t,s.length),n.set(i,s.length+t.length),n}static marshall(e){return new S(e).serialize()}static hdrValueEscape(e){return e.replace(/\\/g,"\\\\").replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/:/g,"\\c")}static hdrValueUnEscape(e){return e.replace(/\\r/g,"\r").replace(/\\n/g,"\n").replace(/\\c/g,":").replace(/\\\\/g,"\\")}}class I{constructor(e,t){this.onFrame=e,this.onIncomingPing=t,this._encoder=new TextEncoder,this._decoder=new TextDecoder,this._token=[],this._initState()}parseChunk(e,t=!1){let s;if(s="string"==typeof e?this._encoder.encode(e):new Uint8Array(e),t&&0!==s[s.length-1]){const e=new Uint8Array(s.length+1);e.set(s,0),e[s.length]=0,s=e}for(let e=0;e<s.length;e++){const t=s[e];this._onByte(t)}}_collectFrame(e){0!==e&&13!==e&&(10!==e?(this._onByte=this._collectCommand,this._reinjectByte(e)):this.onIncomingPing())}_collectCommand(e){if(13!==e)return 10===e?(this._results.command=this._consumeTokenAsUTF8(),void(this._onByte=this._collectHeaders)):void this._consumeByte(e)}_collectHeaders(e){13!==e&&(10!==e?(this._onByte=this._collectHeaderKey,this._reinjectByte(e)):this._setupCollectBody())}_reinjectByte(e){this._onByte(e)}_collectHeaderKey(e){if(58===e)return this._headerKey=this._consumeTokenAsUTF8(),void(this._onByte=this._collectHeaderValue);this._consumeByte(e)}_collectHeaderValue(e){if(13!==e)return 10===e?(this._results.headers.push([this._headerKey,this._consumeTokenAsUTF8()]),this._headerKey=void 0,void(this._onByte=this._collectHeaders)):void this._consumeByte(e)}_setupCollectBody(){const e=this._results.headers.filter(e=>"content-length"===e[0])[0];e?(this._bodyBytesRemaining=parseInt(e[1],10),this._onByte=this._collectBodyFixedSize):this._onByte=this._collectBodyNullTerminated}_collectBodyNullTerminated(e){0!==e?this._consumeByte(e):this._retrievedBody()}_collectBodyFixedSize(e){0!==this._bodyBytesRemaining--?this._consumeByte(e):this._retrievedBody()}_retrievedBody(){this._results.binaryBody=this._consumeTokenAsRaw();try{this.onFrame(this._results)}catch(e){console.log("Ignoring an exception thrown by a frame handler. Original exception: ",e)}this._initState()}_consumeByte(e){this._token.push(e)}_consumeTokenAsUTF8(){return this._decoder.decode(this._consumeTokenAsRaw())}_consumeTokenAsRaw(){const e=new Uint8Array(this._token);return this._token=[],e}_initState(){this._results={command:void 0,headers:[],binaryBody:void 0},this._token=[],this._headerKey=void 0,this._onByte=this._collectFrame}}var w,T,C,R;!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.OPEN=1]="OPEN",e[e.CLOSING=2]="CLOSING",e[e.CLOSED=3]="CLOSED"}(w||(w={})),function(e){e[e.ACTIVE=0]="ACTIVE",e[e.DEACTIVATING=1]="DEACTIVATING",e[e.INACTIVE=2]="INACTIVE"}(T||(T={})),function(e){e[e.LINEAR=0]="LINEAR",e[e.EXPONENTIAL=1]="EXPONENTIAL"}(C||(C={})),function(e){e.Interval="interval",e.Worker="worker"}(R||(R={}));class A{constructor(e,t=R.Interval,s){this._interval=e,this._strategy=t,this._debug=s,this._workerScript=`\n var startTime = Date.now();\n setInterval(function() {\n self.postMessage(Date.now() - startTime);\n }, ${this._interval});\n `}start(e){this.stop(),this.shouldUseWorker()?this.runWorker(e):this.runInterval(e)}stop(){this.disposeWorker(),this.disposeInterval()}shouldUseWorker(){return"undefined"!=typeof Worker&&this._strategy===R.Worker}runWorker(e){this._debug("Using runWorker for outgoing pings"),this._worker||(this._worker=new Worker(URL.createObjectURL(new Blob([this._workerScript],{type:"text/javascript"}))),this._worker.onmessage=t=>e(t.data))}runInterval(e){if(this._debug("Using runInterval for outgoing pings"),!this._timer){const t=Date.now();this._timer=setInterval(()=>{e(Date.now()-t)},this._interval)}}disposeWorker(){this._worker&&(this._worker.terminate(),delete this._worker,this._debug("Outgoing ping disposeWorker"))}disposeInterval(){this._timer&&(clearInterval(this._timer),delete this._timer,this._debug("Outgoing ping disposeInterval"))}}class N{constructor(e){this.versions=e}supportedVersions(){return this.versions.join(",")}protocolVersions(){return this.versions.map(e=>`v${e.replace(".","")}.stomp`)}}N.V1_0="1.0",N.V1_1="1.1",N.V1_2="1.2",N.default=new N([N.V1_2,N.V1_1,N.V1_0]);class O{get connectedVersion(){return this._connectedVersion}get connected(){return this._connected}constructor(e,t,s){this._client=e,this._webSocket=t,this._connected=!1,this._serverFrameHandlers={CONNECTED:e=>{this.debug(`connected to server ${e.headers.server}`),this._connected=!0,this._connectedVersion=e.headers.version,this._connectedVersion===N.V1_2&&(this._escapeHeaderValues=!0),this._setupHeartbeat(e.headers),this.onConnect(e)},MESSAGE:e=>{const t=e.headers.subscription,s=this._subscriptions[t]||this.onUnhandledMessage,i=e,n=this,r=this._connectedVersion===N.V1_2?i.headers.ack:i.headers["message-id"];i.ack=(e={})=>n.ack(r,t,e),i.nack=(e={})=>n.nack(r,t,e),s(i)},RECEIPT:e=>{const t=this._receiptWatchers[e.headers["receipt-id"]];t?(t(e),delete this._receiptWatchers[e.headers["receipt-id"]]):this.onUnhandledReceipt(e)},ERROR:e=>{this.onStompError(e)}},this._counter=0,this._subscriptions={},this._receiptWatchers={},this._partialData="",this._escapeHeaderValues=!1,this._lastServerActivityTS=Date.now(),this.debug=s.debug,this.stompVersions=s.stompVersions,this.connectHeaders=s.connectHeaders,this.disconnectHeaders=s.disconnectHeaders,this.heartbeatIncoming=s.heartbeatIncoming,this.heartbeatToleranceMultiplier=s.heartbeatGracePeriods,this.heartbeatOutgoing=s.heartbeatOutgoing,this.splitLargeFrames=s.splitLargeFrames,this.maxWebSocketChunkSize=s.maxWebSocketChunkSize,this.forceBinaryWSFrames=s.forceBinaryWSFrames,this.logRawCommunication=s.logRawCommunication,this.appendMissingNULLonIncoming=s.appendMissingNULLonIncoming,this.discardWebsocketOnCommFailure=s.discardWebsocketOnCommFailure,this.onConnect=s.onConnect,this.onDisconnect=s.onDisconnect,this.onStompError=s.onStompError,this.onWebSocketClose=s.onWebSocketClose,this.onWebSocketError=s.onWebSocketError,this.onUnhandledMessage=s.onUnhandledMessage,this.onUnhandledReceipt=s.onUnhandledReceipt,this.onUnhandledFrame=s.onUnhandledFrame,this.onHeartbeatReceived=s.onHeartbeatReceived,this.onHeartbeatLost=s.onHeartbeatLost}start(){const e=new I(e=>{const t=S.fromRawFrame(e,this._escapeHeaderValues);this.logRawCommunication||this.debug(`<<< ${t}`);(this._serverFrameHandlers[t.command]||this.onUnhandledFrame)(t)},()=>{this.debug("<<< PONG"),this.onHeartbeatReceived()});this._webSocket.onmessage=t=>{if(this.debug("Received data"),this._lastServerActivityTS=Date.now(),this.logRawCommunication){const e=t.data instanceof ArrayBuffer?(new TextDecoder).decode(t.data):t.data;this.debug(`<<< ${e}`)}e.parseChunk(t.data,this.appendMissingNULLonIncoming)},this._webSocket.onclose=e=>{this.debug(`Connection closed to ${this._webSocket.url}`),this._cleanUp(),this.onWebSocketClose(e)},this._webSocket.onerror=e=>{this.onWebSocketError(e)},this._webSocket.onopen=()=>{const e=Object.assign({},this.connectHeaders);this.debug("Web Socket Opened..."),e["accept-version"]=this.stompVersions.supportedVersions(),e["heart-beat"]=[this.heartbeatOutgoing,this.heartbeatIncoming].join(","),this._transmit({command:"CONNECT",headers:e})}}_setupHeartbeat(e){if(e.version!==N.V1_1&&e.version!==N.V1_2)return;if(!e["heart-beat"])return;const[t,s]=e["heart-beat"].split(",").map(e=>parseInt(e,10));if(0!==this.heartbeatOutgoing&&0!==s){const e=Math.max(this.heartbeatOutgoing,s);this.debug(`send PING every ${e}ms`),this._pinger=new A(e,this._client.heartbeatStrategy,this.debug),this._pinger.start(()=>{this._webSocket.readyState===w.OPEN&&(this._webSocket.send(E),this.debug(">>> PING"))})}if(0!==this.heartbeatIncoming&&0!==t){const e=Math.max(this.heartbeatIncoming,t);this.debug(`check PONG every ${e}ms`),this._ponger=setInterval(()=>{const t=Date.now()-this._lastServerActivityTS;t>e*this.heartbeatToleranceMultiplier&&(this.debug(`did not receive server activity for the last ${t}ms`),this.onHeartbeatLost(),this._closeOrDiscardWebsocket())},e)}}_closeOrDiscardWebsocket(){this.discardWebsocketOnCommFailure?(this.debug("Discarding websocket, the underlying socket may linger for a while"),this.discardWebsocket()):(this.debug("Issuing close on the websocket"),this._closeWebsocket())}forceDisconnect(){this._webSocket&&(this._webSocket.readyState!==w.CONNECTING&&this._webSocket.readyState!==w.OPEN||this._closeOrDiscardWebsocket())}_closeWebsocket(){this._webSocket.onmessage=()=>{},this._webSocket.close()}discardWebsocket(){var e,t;"function"!=typeof this._webSocket.terminate&&(e=this._webSocket,t=e=>this.debug(e),e.terminate=function(){const s=()=>{};this.onerror=s,this.onmessage=s,this.onopen=s;const i=new Date,n=Math.random().toString().substring(2,8),r=this.onclose;this.onclose=e=>{const s=(new Date).getTime()-i.getTime();t(`Discarded socket (#${n}) closed after ${s}ms, with code/reason: ${e.code}/${e.reason}`)},this.close(),r?.call(e,{code:4001,reason:`Quick discarding socket (#${n}) without waiting for the shutdown sequence.`,wasClean:!1})}),this._webSocket.terminate()}_transmit(e){const{command:t,headers:s,body:i,binaryBody:n,skipContentLengthHeader:r}=e,o=new S({command:t,headers:s,body:i,binaryBody:n,escapeHeaderValues:this._escapeHeaderValues,skipContentLengthHeader:r});let a=o.serialize();if(this.logRawCommunication?this.debug(`>>> ${a}`):this.debug(`>>> ${o}`),this.forceBinaryWSFrames&&"string"==typeof a&&(a=(new TextEncoder).encode(a)),"string"==typeof a&&this.splitLargeFrames){let e=a;for(;e.length>0;){const t=e.substring(0,this.maxWebSocketChunkSize);e=e.substring(this.maxWebSocketChunkSize),this._webSocket.send(t),this.debug(`chunk sent = ${t.length}, remaining = ${e.length}`)}}else this._webSocket.send(a)}dispose(){if(this.connected)try{const e=Object.assign({},this.disconnectHeaders);e.receipt||(e.receipt="close-"+this._counter++),this.watchForReceipt(e.receipt,e=>{this._closeWebsocket(),this._cleanUp(),this.onDisconnect(e)}),this._transmit({command:"DISCONNECT",headers:e})}catch(e){this.debug(`Ignoring error during disconnect ${e}`)}else this._webSocket.readyState!==w.CONNECTING&&this._webSocket.readyState!==w.OPEN||this._closeWebsocket()}_cleanUp(){this._connected=!1,this._pinger&&(this._pinger.stop(),this._pinger=void 0),this._ponger&&(clearInterval(this._ponger),this._ponger=void 0)}publish(e){const{destination:t,headers:s,body:i,binaryBody:n,skipContentLengthHeader:r}=e,o=Object.assign({destination:t},s);this._transmit({command:"SEND",headers:o,body:i,binaryBody:n,skipContentLengthHeader:r})}watchForReceipt(e,t){this._receiptWatchers[e]=t}subscribe(e,t,s={}){(s=Object.assign({},s)).id||(s.id="sub-"+this._counter++),s.destination=e,this._subscriptions[s.id]=t,this._transmit({command:"SUBSCRIBE",headers:s});const i=this;return{id:s.id,unsubscribe:e=>i.unsubscribe(s.id,e)}}unsubscribe(e,t={}){t=Object.assign({},t),delete this._subscriptions[e],t.id=e,this._transmit({command:"UNSUBSCRIBE",headers:t})}begin(e){const t=e||"tx-"+this._counter++;this._transmit({command:"BEGIN",headers:{transaction:t}});const s=this;return{id:t,commit(){s.commit(t)},abort(){s.abort(t)}}}commit(e){this._transmit({command:"COMMIT",headers:{transaction:e}})}abort(e){this._transmit({command:"ABORT",headers:{transaction:e}})}ack(e,t,s={}){s=Object.assign({},s),this._connectedVersion===N.V1_2?s.id=e:s["message-id"]=e,s.subscription=t,this._transmit({command:"ACK",headers:s})}nack(e,t,s={}){return s=Object.assign({},s),this._connectedVersion===N.V1_2?s.id=e:s["message-id"]=e,s.subscription=t,this._transmit({command:"NACK",headers:s})}}class k{get webSocket(){return this._stompHandler?._webSocket}get disconnectHeaders(){return this._disconnectHeaders}set disconnectHeaders(e){this._disconnectHeaders=e,this._stompHandler&&(this._stompHandler.disconnectHeaders=this._disconnectHeaders)}get connected(){return!!this._stompHandler&&this._stompHandler.connected}get connectedVersion(){return this._stompHandler?this._stompHandler.connectedVersion:void 0}get active(){return this.state===T.ACTIVE}_changeState(e){this.state=e,this.onChangeState(e)}constructor(e={}){this.stompVersions=N.default,this.connectionTimeout=0,this.reconnectDelay=5e3,this._nextReconnectDelay=0,this.maxReconnectDelay=9e5,this.reconnectTimeMode=C.LINEAR,this.heartbeatIncoming=1e4,this.heartbeatToleranceMultiplier=2,this.heartbeatOutgoing=1e4,this.heartbeatStrategy=R.Interval,this.splitLargeFrames=!1,this.maxWebSocketChunkSize=8192,this.forceBinaryWSFrames=!1,this.appendMissingNULLonIncoming=!1,this.discardWebsocketOnCommFailure=!1,this.state=T.INACTIVE;const t=()=>{};this.debug=t,this.beforeConnect=t,this.onConnect=t,this.onDisconnect=t,this.onUnhandledMessage=t,this.onUnhandledReceipt=t,this.onUnhandledFrame=t,this.onHeartbeatReceived=t,this.onHeartbeatLost=t,this.onStompError=t,this.onWebSocketClose=t,this.onWebSocketError=t,this.logRawCommunication=!1,this.onChangeState=t,this.connectHeaders={},this._disconnectHeaders={},this.configure(e)}configure(e){Object.assign(this,e),this.maxReconnectDelay>0&&this.maxReconnectDelay<this.reconnectDelay&&(this.debug(`Warning: maxReconnectDelay (${this.maxReconnectDelay}ms) is less than reconnectDelay (${this.reconnectDelay}ms). Using reconnectDelay as the maxReconnectDelay delay.`),this.maxReconnectDelay=this.reconnectDelay)}activate(){const e=()=>{this.active?this.debug("Already ACTIVE, ignoring request to activate"):(this._changeState(T.ACTIVE),this._nextReconnectDelay=this.reconnectDelay,this._connect())};this.state===T.DEACTIVATING?(this.debug("Waiting for deactivation to finish before activating"),this.deactivate().then(()=>{e()})):e()}async _connect(){if(await this.beforeConnect(this),this._stompHandler)return void this.debug("There is already a stompHandler, skipping the call to connect");if(!this.active)return void this.debug("Client has been marked inactive, will not attempt to connect");this.connectionTimeout>0&&(this._connectionWatcher&&clearTimeout(this._connectionWatcher),this._connectionWatcher=setTimeout(()=>{this.connected||(this.debug(`Connection not established in ${this.connectionTimeout}ms, closing socket`),this.forceDisconnect())},this.connectionTimeout)),this.debug("Opening Web Socket...");const e=this._createWebSocket();this._stompHandler=new O(this,e,{debug:this.debug,stompVersions:this.stompVersions,connectHeaders:this.connectHeaders,disconnectHeaders:this._disconnectHeaders,heartbeatIncoming:this.heartbeatIncoming,heartbeatGracePeriods:this.heartbeatToleranceMultiplier,heartbeatOutgoing:this.heartbeatOutgoing,heartbeatStrategy:this.heartbeatStrategy,splitLargeFrames:this.splitLargeFrames,maxWebSocketChunkSize:this.maxWebSocketChunkSize,forceBinaryWSFrames:this.forceBinaryWSFrames,logRawCommunication:this.logRawCommunication,appendMissingNULLonIncoming:this.appendMissingNULLonIncoming,discardWebsocketOnCommFailure:this.discardWebsocketOnCommFailure,onConnect:e=>{if(this._connectionWatcher&&(clearTimeout(this._connectionWatcher),this._connectionWatcher=void 0),this._nextReconnectDelay=this.reconnectDelay,!this.active)return this.debug("STOMP got connected while deactivate was issued, will disconnect now"),void this._disposeStompHandler();this.onConnect(e)},onDisconnect:e=>{this.onDisconnect(e)},onStompError:e=>{this.onStompError(e)},onWebSocketClose:e=>{this._stompHandler=void 0,this.state===T.DEACTIVATING&&this._changeState(T.INACTIVE),this.onWebSocketClose(e),this.active&&this._schedule_reconnect()},onWebSocketError:e=>{this.onWebSocketError(e)},onUnhandledMessage:e=>{this.onUnhandledMessage(e)},onUnhandledReceipt:e=>{this.onUnhandledReceipt(e)},onUnhandledFrame:e=>{this.onUnhandledFrame(e)},onHeartbeatReceived:()=>{this.onHeartbeatReceived()},onHeartbeatLost:()=>{this.onHeartbeatLost()}}),this._stompHandler.start()}_createWebSocket(){let e;if(this.webSocketFactory)e=this.webSocketFactory();else{if(!this.brokerURL)throw new Error("Either brokerURL or webSocketFactory must be provided");e=new WebSocket(this.brokerURL,this.stompVersions.protocolVersions())}return e.binaryType="arraybuffer",e}_schedule_reconnect(){this._nextReconnectDelay>0&&(this.debug(`STOMP: scheduling reconnection in ${this._nextReconnectDelay}ms`),this._reconnector=setTimeout(()=>{this.reconnectTimeMode===C.EXPONENTIAL&&(this._nextReconnectDelay=2*this._nextReconnectDelay,0!==this.maxReconnectDelay&&(this._nextReconnectDelay=Math.min(this._nextReconnectDelay,this.maxReconnectDelay))),this._connect()},this._nextReconnectDelay))}async deactivate(e={}){const t=e.force||!1,s=this.active;let i;if(this.state===T.INACTIVE)return this.debug("Already INACTIVE, nothing more to do"),Promise.resolve();if(this._changeState(T.DEACTIVATING),this._nextReconnectDelay=0,this._reconnector&&(clearTimeout(this._reconnector),this._reconnector=void 0),!this._stompHandler||this.webSocket.readyState===w.CLOSED)return this._changeState(T.INACTIVE),Promise.resolve();{const e=this._stompHandler.onWebSocketClose;i=new Promise((t,s)=>{this._stompHandler.onWebSocketClose=s=>{e(s),t()}})}return t?this._stompHandler?.discardWebsocket():s&&this._disposeStompHandler(),i}forceDisconnect(){this._stompHandler&&this._stompHandler.forceDisconnect()}_disposeStompHandler(){this._stompHandler&&this._stompHandler.dispose()}publish(e){this._checkConnection(),this._stompHandler.publish(e)}_checkConnection(){if(!this.connected)throw new TypeError("There is no underlying STOMP connection")}watchForReceipt(e,t){this._checkConnection(),this._stompHandler.watchForReceipt(e,t)}subscribe(e,t,s={}){return this._checkConnection(),this._stompHandler.subscribe(e,t,s)}unsubscribe(e,t={}){this._checkConnection(),this._stompHandler.unsubscribe(e,t)}begin(e){return this._checkConnection(),this._stompHandler.begin(e)}commit(e){this._checkConnection(),this._stompHandler.commit(e)}abort(e){this._checkConnection(),this._stompHandler.abort(e)}ack(e,t,s={}){this._checkConnection(),this._stompHandler.ack(e,t,s)}nack(e,t,s={}){this._checkConnection(),this._stompHandler.nack(e,t,s)}}var M="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function L(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var D,P,x,U,W,F,j={exports:{}},$={};function H(){if(x)return P;x=1;var e=(D||(D=1,M.crypto&&M.crypto.getRandomValues?$.randomBytes=function(e){var t=new Uint8Array(e);return M.crypto.getRandomValues(t),t}:$.randomBytes=function(e){for(var t=new Array(e),s=0;s<e;s++)t[s]=Math.floor(256*Math.random());return t}),$),t="abcdefghijklmnopqrstuvwxyz012345";return P={string:function(s){for(var i=e.randomBytes(s),n=[],r=0;r<s;r++)n.push(t.substr(i[r]%32,1));return n.join("")},number:function(e){return Math.floor(Math.random()*e)},numberString:function(e){var t=(""+(e-1)).length;return(new Array(t+1).join("0")+this.number(e)).slice(-t)}}}function B(){return U||(U=1,function(e){var t=H(),s={},i=!1,n=M.chrome&&M.chrome.app&&M.chrome.app.runtime;e.exports={attachEvent:function(e,t){void 0!==M.addEventListener?M.addEventListener(e,t,!1):M.document&&M.attachEvent&&(M.document.attachEvent("on"+e,t),M.attachEvent("on"+e,t))},detachEvent:function(e,t){void 0!==M.addEventListener?M.removeEventListener(e,t,!1):M.document&&M.detachEvent&&(M.document.detachEvent("on"+e,t),M.detachEvent("on"+e,t))},unloadAdd:function(e){if(n)return null;var r=t.string(8);return s[r]=e,i&&setTimeout(this.triggerUnloadCallbacks,0),r},unloadDel:function(e){e in s&&delete s[e]},triggerUnloadCallbacks:function(){for(var e in s)s[e](),delete s[e]}};n||e.exports.attachEvent("unload",function(){i||(i=!0,e.exports.triggerUnloadCallbacks())})}(j)),j.exports}var V,G,J,K,z,q={};function X(){if(J)return G;J=1;var e=F?W:(F=1,W=function(e,t){if(t=t.split(":")[0],!(e=+e))return!1;switch(t){case"http":case"ws":return 80!==e;case"https":case"wss":return 443!==e;case"ftp":return 21!==e;case"gopher":return 70!==e;case"file":return!1}return 0!==e}),t=function(){if(V)return q;V=1;var e=Object.prototype.hasOwnProperty;function t(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(e){return null}}function s(e){try{return encodeURIComponent(e)}catch(e){return null}}return q.stringify=function(t,i){i=i||"";var n,r,o=[];for(r in"string"!=typeof i&&(i="?"),t)if(e.call(t,r)){if((n=t[r])||null!=n&&!isNaN(n)||(n=""),r=s(r),n=s(n),null===r||null===n)continue;o.push(r+"="+n)}return o.length?i+o.join("&"):""},q.parse=function(e){for(var s,i=/([^=?#&]+)=?([^&]*)/g,n={};s=i.exec(e);){var r=t(s[1]),o=t(s[2]);null===r||null===o||r in n||(n[r]=o)}return n},q}(),s=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/,i=/[\n\r\t]/g,n=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,r=/:\d+$/,o=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,a=/^[a-zA-Z]:/;function c(e){return(e||"").toString().replace(s,"")}var l=[["#","hash"],["?","query"],function(e,t){return u(t.protocol)?e.replace(/\\/g,"/"):e},["/","pathname"],["@","auth",1],[NaN,"host",void 0,1,1],[/:(\d*)$/,"port",void 0,1],[NaN,"hostname",void 0,1,1]],h={hash:1,query:1};function d(e){var t,s=("undefined"!=typeof window?window:void 0!==M?M:"undefined"!=typeof self?self:{}).location||{},i={},r=typeof(e=e||s);if("blob:"===e.protocol)i=new g(unescape(e.pathname),{});else if("string"===r)for(t in i=new g(e,{}),h)delete i[t];else if("object"===r){for(t in e)t in h||(i[t]=e[t]);void 0===i.slashes&&(i.slashes=n.test(e.href))}return i}function u(e){return"file:"===e||"ftp:"===e||"http:"===e||"https:"===e||"ws:"===e||"wss:"===e}function p(e,t){e=(e=c(e)).replace(i,""),t=t||{};var s,n=o.exec(e),r=n[1]?n[1].toLowerCase():"",a=!!n[2],l=!!n[3],h=0;return a?l?(s=n[2]+n[3]+n[4],h=n[2].length+n[3].length):(s=n[2]+n[4],h=n[2].length):l?(s=n[3]+n[4],h=n[3].length):s=n[4],"file:"===r?h>=2&&(s=s.slice(2)):u(r)?s=n[4]:r?a&&(s=s.slice(2)):h>=2&&u(t.protocol)&&(s=n[4]),{protocol:r,slashes:a||u(r),slashesCount:h,rest:s}}function g(s,n,r){if(s=(s=c(s)).replace(i,""),!(this instanceof g))return new g(s,n,r);var o,h,m,f,b,_,y=l.slice(),E=typeof n,v=this,S=0;for("object"!==E&&"string"!==E&&(r=n,n=null),r&&"function"!=typeof r&&(r=t.parse),o=!(h=p(s||"",n=d(n))).protocol&&!h.slashes,v.slashes=h.slashes||o&&n.slashes,v.protocol=h.protocol||n.protocol||"",s=h.rest,("file:"===h.protocol&&(2!==h.slashesCount||a.test(s))||!h.slashes&&(h.protocol||h.slashesCount<2||!u(v.protocol)))&&(y[3]=[/(.*)/,"pathname"]);S<y.length;S++)"function"!=typeof(f=y[S])?(m=f[0],_=f[1],m!=m?v[_]=s:"string"==typeof m?~(b="@"===m?s.lastIndexOf(m):s.indexOf(m))&&("number"==typeof f[2]?(v[_]=s.slice(0,b),s=s.slice(b+f[2])):(v[_]=s.slice(b),s=s.slice(0,b))):(b=m.exec(s))&&(v[_]=b[1],s=s.slice(0,b.index)),v[_]=v[_]||o&&f[3]&&n[_]||"",f[4]&&(v[_]=v[_].toLowerCase())):s=f(s,v);r&&(v.query=r(v.query)),o&&n.slashes&&"/"!==v.pathname.charAt(0)&&(""!==v.pathname||""!==n.pathname)&&(v.pathname=function(e,t){if(""===e)return t;for(var s=(t||"/").split("/").slice(0,-1).concat(e.split("/")),i=s.length,n=s[i-1],r=!1,o=0;i--;)"."===s[i]?s.splice(i,1):".."===s[i]?(s.splice(i,1),o++):o&&(0===i&&(r=!0),s.splice(i,1),o--);return r&&s.unshift(""),"."!==n&&".."!==n||s.push(""),s.join("/")}(v.pathname,n.pathname)),"/"!==v.pathname.charAt(0)&&u(v.protocol)&&(v.pathname="/"+v.pathname),e(v.port,v.protocol)||(v.host=v.hostname,v.port=""),v.username=v.password="",v.auth&&(~(b=v.auth.indexOf(":"))?(v.username=v.auth.slice(0,b),v.username=encodeURIComponent(decodeURIComponent(v.username)),v.password=v.auth.slice(b+1),v.password=encodeURIComponent(decodeURIComponent(v.password))):v.username=encodeURIComponent(decodeURIComponent(v.auth)),v.auth=v.password?v.username+":"+v.password:v.username),v.origin="file:"!==v.protocol&&u(v.protocol)&&v.host?v.protocol+"//"+v.host:"null",v.href=v.toString()}return g.prototype={set:function(s,i,n){var o=this;switch(s){case"query":"string"==typeof i&&i.length&&(i=(n||t.parse)(i)),o[s]=i;break;case"port":o[s]=i,e(i,o.protocol)?i&&(o.host=o.hostname+":"+i):(o.host=o.hostname,o[s]="");break;case"hostname":o[s]=i,o.port&&(i+=":"+o.port),o.host=i;break;case"host":o[s]=i,r.test(i)?(i=i.split(":"),o.port=i.pop(),o.hostname=i.join(":")):(o.hostname=i,o.port="");break;case"protocol":o.protocol=i.toLowerCase(),o.slashes=!n;break;case"pathname":case"hash":if(i){var a="pathname"===s?"/":"#";o[s]=i.charAt(0)!==a?a+i:i}else o[s]=i;break;case"username":case"password":o[s]=encodeURIComponent(i);break;case"auth":var c=i.indexOf(":");~c?(o.username=i.slice(0,c),o.username=encodeURIComponent(decodeURIComponent(o.username)),o.password=i.slice(c+1),o.password=encodeURIComponent(decodeURIComponent(o.password))):o.username=encodeURIComponent(decodeURIComponent(i))}for(var h=0;h<l.length;h++){var d=l[h];d[4]&&(o[d[1]]=o[d[1]].toLowerCase())}return o.auth=o.password?o.username+":"+o.password:o.username,o.origin="file:"!==o.protocol&&u(o.protocol)&&o.host?o.protocol+"//"+o.host:"null",o.href=o.toString(),o},toString:function(e){e&&"function"==typeof e||(e=t.stringify);var s,i=this,n=i.host,o=i.protocol;o&&":"!==o.charAt(o.length-1)&&(o+=":");var a=o+(i.protocol&&i.slashes||u(i.protocol)?"//":"");return i.username?(a+=i.username,i.password&&(a+=":"+i.password),a+="@"):i.password?(a+=":"+i.password,a+="@"):"file:"!==i.protocol&&u(i.protocol)&&!n&&"/"!==i.pathname&&(a+="@"),(":"===n[n.length-1]||r.test(i.hostname)&&!i.port)&&(n+=":"),a+=n+i.pathname,(s="object"==typeof i.query?e(i.query):i.query)&&(a+="?"!==s.charAt(0)?"?"+s:s),i.hash&&(a+=i.hash),a}},g.extractProtocol=p,g.location=d,g.trimLeft=c,g.qs=t,G=g}function Y(){if(z)return K;z=1;var e=X();return K={getOrigin:function(t){if(!t)return null;var s=new e(t);if("file:"===s.protocol)return null;var i=s.port;return i||(i="https:"===s.protocol?"443":"80"),s.protocol+"//"+s.hostname+":"+i},isOriginEqual:function(e,t){return this.getOrigin(e)===this.getOrigin(t)},isSchemeEqual:function(e,t){return e.split(":")[0]===t.split(":")[0]},addPath:function(e,t){var s=e.split("?");return s[0]+t+(s[1]?"?"+s[1]:"")},addQuery:function(e,t){return e+(-1===e.indexOf("?")?"?"+t:"&"+t)},isLoopbackAddr:function(e){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(e)||/^\[::1\]$/.test(e)}}}var Q,Z={exports:{}};function ee(){return Q||(Q=1,"function"==typeof Object.create?Z.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:Z.exports=function(e,t){if(t){e.super_=t;var s=function(){};s.prototype=t.prototype,e.prototype=new s,e.prototype.constructor=e}}),Z.exports}var te,se,ie,ne={};function re(){if(se)return te;function e(){this._listeners={}}return se=1,e.prototype.addEventListener=function(e,t){e in this._listeners||(this._listeners[e]=[]);var s=this._listeners[e];-1===s.indexOf(t)&&(s=s.concat([t])),this._listeners[e]=s},e.prototype.removeEventListener=function(e,t){var s=this._listeners[e];if(s){var i=s.indexOf(t);-1===i||(s.length>1?this._listeners[e]=s.slice(0,i).concat(s.slice(i+1)):delete this._listeners[e])}},e.prototype.dispatchEvent=function(){var e=arguments[0],t=e.type,s=1===arguments.length?[e]:Array.apply(null,arguments);if(this["on"+t]&&this["on"+t].apply(this,s),t in this._listeners)for(var i=this._listeners[t],n=0;n<i.length;n++)i[n].apply(this,s)},te=e}function oe(){if(ie)return ne;ie=1;var e=ee(),t=re();function s(){t.call(this)}return e(s,t),s.prototype.removeAllListeners=function(e){e?delete this._listeners[e]:this._listeners={}},s.prototype.once=function(e,t){var s=this,i=!1;this.on(e,function n(){s.removeListener(e,n),i||(i=!0,t.apply(this,arguments))})},s.prototype.emit=function(){var e=arguments[0],t=this._listeners[e];if(t){for(var s=arguments.length,i=new Array(s-1),n=1;n<s;n++)i[n-1]=arguments[n];for(var r=0;r<t.length;r++)t[r].apply(this,i)}},s.prototype.on=s.prototype.addListener=t.prototype.addEventListener,s.prototype.removeListener=t.prototype.removeEventListener,ne.EventEmitter=s,ne}var ae,ce,le,he,de,ue,pe,ge,me,fe,be,_e,ye,Ee,ve,Se,Ie,we,Te,Ce,Re,Ae,Ne,Oe,ke,Me,Le,De,Pe,xe,Ue,We,Fe,je,$e,He={exports:{}};function Be(){if(le)return ce;le=1;var e=B(),t=Y(),s=ee(),i=oe().EventEmitter,n=function(){if(ae)return He.exports;ae=1;var e=M.WebSocket||M.MozWebSocket;return He.exports=e?function(t){return new e(t)}:void 0,He.exports}();function r(s,o,a){if(!r.enabled())throw new Error("Transport created when disabled");i.call(this);var c=this,l=t.addPath(s,"/websocket");l="https"===l.slice(0,5)?"wss"+l.slice(5):"ws"+l.slice(4),this.url=l,this.ws=new n(this.url,[],a),this.ws.onmessage=function(e){e.data,c.emit("message",e.data)},this.unloadRef=e.unloadAdd(function(){c.ws.close()}),this.ws.onclose=function(e){e.code,e.reason,c.emit("close",e.code,e.reason),c._cleanup()},this.ws.onerror=function(e){c.emit("close",1006,"WebSocket connection broken"),c._cleanup()}}return s(r,i),r.prototype.send=function(e){var t="["+e+"]";this.ws.send(t)},r.prototype.close=function(){var e=this.ws;this._cleanup(),e&&e.close()},r.prototype._cleanup=function(){var t=this.ws;t&&(t.onmessage=t.onclose=t.onerror=null),e.unloadDel(this.unloadRef),this.unloadRef=this.ws=null,this.removeAllListeners()},r.enabled=function(){return!!n},r.transportName="websocket",r.roundTrips=2,ce=r}function Ve(){if(me)return ge;me=1;var e=ee(),t=Y(),s=function(){if(de)return he;de=1;var e=ee(),t=oe().EventEmitter;function s(e,s){t.call(this),this.sendBuffer=[],this.sender=s,this.url=e}return e(s,t),s.prototype.send=function(e){this.sendBuffer.push(e),this.sendStop||this.sendSchedule()},s.prototype.sendScheduleWait=function(){var e,t=this;this.sendStop=function(){t.sendStop=null,clearTimeout(e)},e=setTimeout(function(){t.sendStop=null,t.sendSchedule()},25)},s.prototype.sendSchedule=function(){this.sendBuffer.length;var e=this;if(this.sendBuffer.length>0){var t="["+this.sendBuffer.join(",")+"]";this.sendStop=this.sender(this.url,t,function(t){e.sendStop=null,t?(e.emit("close",t.code||1006,"Sending error: "+t),e.close()):e.sendScheduleWait()}),this.sendBuffer=[]}},s.prototype._cleanup=function(){this.removeAllListeners()},s.prototype.close=function(){this._cleanup(),this.sendStop&&(this.sendStop(),this.sendStop=null)},he=s}(),i=function(){if(pe)return ue;pe=1;var e=ee(),t=oe().EventEmitter;function s(e,s,i){t.call(this),this.Receiver=e,this.receiveUrl=s,this.AjaxObject=i,this._scheduleReceiver()}return e(s,t),s.prototype._scheduleReceiver=function(){var e=this,t=this.poll=new this.Receiver(this.receiveUrl,this.AjaxObject);t.on("message",function(t){e.emit("message",t)}),t.once("close",function(s,i){e.pollIsClosing,e.poll=t=null,e.pollIsClosing||("network"===i?e._scheduleReceiver():(e.emit("close",s||1006,i),e.removeAllListeners()))})},s.prototype.abort=function(){this.removeAllListeners(),this.pollIsClosing=!0,this.poll&&this.poll.abort()},ue=s}();function n(e,n,r,o,a){var c=t.addPath(e,n),l=this;s.call(this,e,r),this.poll=new i(o,c,a),this.poll.on("message",function(e){l.emit("message",e)}),this.poll.once("close",function(e,t){l.poll=null,l.emit("close",e,t),l.close()})}return e(n,s),n.prototype.close=function(){s.prototype.close.call(this),this.removeAllListeners(),this.poll&&(this.poll.abort(),this.poll=null)},ge=n}function Ge(){if(be)return fe;be=1;var e=ee(),t=Y(),s=Ve();function i(e,i,n,r){s.call(this,e,i,function(e){return function(s,i,n){var r={};"string"==typeof i&&(r.headers={"Content-type":"text/plain"});var o=t.addPath(s,"/xhr_send"),a=new e("POST",o,i,r);return a.once("finish",function(e){if(a=null,200!==e&&204!==e)return n(new Error("http status "+e));n()}),function(){a.close(),a=null;var e=new Error("Aborted");e.code=1e3,n(e)}}}(r),n,r)}return e(i,s),fe=i}function Je(){if(ye)return _e;ye=1;var e=ee(),t=oe().EventEmitter;function s(e,s){t.call(this);var i=this;this.bufferPosition=0,this.xo=new s("POST",e,null),this.xo.on("chunk",this._chunkHandler.bind(this)),this.xo.once("finish",function(e,t){i._chunkHandler(e,t),i.xo=null;var s=200===e?"network":"permanent";i.emit("close",null,s),i._cleanup()})}return e(s,t),s.prototype._chunkHandler=function(e,t){if(200===e&&t)for(var s=-1;;this.bufferPosition+=s+1){var i=t.slice(this.bufferPosition);if(-1===(s=i.indexOf("\n")))break;var n=i.slice(0,s);n&&this.emit("message",n)}},s.prototype._cleanup=function(){this.removeAllListeners()},s.prototype.abort=function(){this.xo&&(this.xo.close(),this.emit("close",null,"user"),this.xo=null),this._cleanup()},_e=s}function Ke(){if(ve)return Ee;ve=1;var e=oe().EventEmitter,t=ee(),s=B(),i=Y(),n=M.XMLHttpRequest;function r(t,s,i,n){var r=this;e.call(this),setTimeout(function(){r._start(t,s,i,n)},0)}t(r,e),r.prototype._start=function(e,t,o,a){var c=this;try{this.xhr=new n}catch(e){}if(!this.xhr)return this.emit("finish",0,"no xhr support"),void this._cleanup();t=i.addQuery(t,"t="+ +new Date),this.unloadRef=s.unloadAdd(function(){c._cleanup(!0)});try{this.xhr.open(e,t,!0),this.timeout&&"timeout"in this.xhr&&(this.xhr.timeout=this.timeout,this.xhr.ontimeout=function(){c.emit("finish",0,""),c._cleanup(!1)})}catch(e){return this.emit("finish",0,""),void this._cleanup(!1)}if(a&&a.noCredentials||!r.supportsCORS||(this.xhr.withCredentials=!0),a&&a.headers)for(var l in a.headers)this.xhr.setRequestHeader(l,a.headers[l]);this.xhr.onreadystatechange=function(){if(c.xhr){var e,t,s=c.xhr;switch(s.readyState,s.readyState){case 3:try{t=s.status,e=s.responseText}catch(e){}1223===t&&(t=204),200===t&&e&&e.length>0&&c.emit("chunk",t,e);break;case 4:1223===(t=s.status)&&(t=204),12005!==t&&12029!==t||(t=0),s.responseText,c.emit("finish",t,s.responseText),c._cleanup(!1)}}};try{c.xhr.send(o)}catch(e){c.emit("finish",0,""),c._cleanup(!1)}},r.prototype._cleanup=function(e){if(this.xhr){if(this.removeAllListeners(),s.unloadDel(this.unloadRef),this.xhr.onreadystatechange=function(){},this.xhr.ontimeout&&(this.xhr.ontimeout=null),e)try{this.xhr.abort()}catch(e){}this.unloadRef=this.xhr=null}},r.prototype.close=function(){this._cleanup(!0)},r.enabled=!!n;var o=["Active"].concat("Object").join("X");!r.enabled&&o in M&&(n=function(){try{return new M[o]("Microsoft.XMLHTTP")}catch(e){return null}},r.enabled=!!new n);var a=!1;try{a="withCredentials"in new n}catch(e){}return r.supportsCORS=a,Ee=r}function ze(){if(Ie)return Se;Ie=1;var e=ee(),t=Ke();function s(e,s,i,n){t.call(this,e,s,i,n)}return e(s,t),s.enabled=t.enabled&&t.supportsCORS,Se=s}function qe(){if(Te)return we;Te=1;var e=ee(),t=Ke();function s(e,s,i){t.call(this,e,s,i,{noCredentials:!0})}return e(s,t),s.enabled=t.enabled,we=s}function Xe(){return Re?Ce:(Re=1,Ce={isOpera:function(){return M.navigator&&/opera/i.test(M.navigator.userAgent)},isKonqueror:function(){return M.navigator&&/konqueror/i.test(M.navigator.userAgent)},hasDomain:function(){if(!M.document)return!0;try{return!!M.document.domain}catch(e){return!1}}})}function Ye(){if(Ne)return Ae;Ne=1;var e=ee(),t=Ge(),s=Je(),i=ze(),n=qe(),r=Xe();function o(e){if(!n.enabled&&!i.enabled)throw new Error("Transport created when disabled");t.call(this,e,"/xhr_streaming",s,i)}return e(o,t),o.enabled=function(e){return!e.nullOrigin&&(!r.isOpera()&&i.enabled)},o.transportName="xhr-streaming",o.roundTrips=2,o.needBody=!!M.document,Ae=o}function Qe(){if(ke)return Oe;ke=1;var e=oe().EventEmitter,t=ee(),s=B(),i=Xe(),n=Y();function r(t,s,i){var n=this;e.call(this),setTimeout(function(){n._start(t,s,i)},0)}return t(r,e),r.prototype._start=function(e,t,i){var r=this,o=new M.XDomainRequest;t=n.addQuery(t,"t="+ +new Date),o.onerror=function(){r._error()},o.ontimeout=function(){r._error()},o.onprogress=function(){o.responseText,r.emit("chunk",200,o.responseText)},o.onload=function(){r.emit("finish",200,o.responseText),r._cleanup(!1)},this.xdr=o,this.unloadRef=s.unloadAdd(function(){r._cleanup(!0)});try{this.xdr.open(e,t),this.timeout&&(this.xdr.timeout=this.timeout),this.xdr.send(i)}catch(e){this._error()}},r.prototype._error=function(){this.emit("finish",0,""),this._cleanup(!1)},r.prototype._cleanup=function(e){if(this.xdr){if(this.removeAllListeners(),s.unloadDel(this.unloadRef),this.xdr.ontimeout=this.xdr.onerror=this.xdr.onprogress=this.xdr.onload=null,e)try{this.xdr.abort()}catch(e){}this.unloadRef=this.xdr=null}},r.prototype.close=function(){this._cleanup(!0)},r.enabled=!(!M.XDomainRequest||!i.hasDomain()),Oe=r}function Ze(){if(Le)return Me;Le=1;var e=ee(),t=Ge(),s=Je(),i=Qe();function n(e){if(!i.enabled)throw new Error("Transport created when disabled");t.call(this,e,"/xhr_streaming",s,i)}return e(n,t),n.enabled=function(e){return!e.cookie_needed&&!e.nullOrigin&&(i.enabled&&e.sameScheme)},n.transportName="xdr-streaming",n.roundTrips=2,Me=n}function et(){return Pe?De:(Pe=1,De=M.EventSource)}function tt(){if(Fe)return We;Fe=1;var e=ee(),t=Ge(),s=function(){if(Ue)return xe;Ue=1;var e=ee(),t=oe().EventEmitter,s=et();function i(e){t.call(this);var i=this,n=this.es=new s(e);n.onmessage=function(e){e.data,i.emit("message",decodeURI(e.data))},n.onerror=function(e){n.readyState;var t=2!==n.readyState?"network":"permanent";i._cleanup(),i._close(t)}}return e(i,t),i.prototype.abort=function(){this._cleanup(),this._close("user")},i.prototype._cleanup=function(){var e=this.es;e&&(e.onmessage=e.onerror=null,e.close(),this.es=null)},i.prototype._close=function(e){var t=this;setTimeout(function(){t.emit("close",null,e),t.removeAllListeners()},200)},xe=i}(),i=ze(),n=et();function r(e){if(!r.enabled())throw new Error("Transport created when disabled");t.call(this,e,"/eventsource",s,i)}return e(r,t),r.enabled=function(){return!!n},r.transportName="eventsource",r.roundTrips=2,We=r}function st(){return $e?je:($e=1,je="1.6.1")}var it,nt,rt,ot,at,ct,lt,ht,dt,ut,pt,gt,mt,ft,bt,_t,yt,Et,vt,St,It,wt,Tt,Ct={exports:{}};function Rt(){return it||(it=1,function(e){var t=B(),s=Xe();e.exports={WPrefix:"_jp",currentWindowId:null,polluteGlobalNamespace:function(){e.exports.WPrefix in M||(M[e.exports.WPrefix]={})},postMessage:function(t,s){M.parent!==M&&M.parent.postMessage(JSON.stringify({windowId:e.exports.currentWindowId,type:t,data:s||""}),"*")},createIframe:function(e,s){var i,n,r=M.document.createElement("iframe"),o=function(){clearTimeout(i);try{r.onload=null}catch(e){}r.onerror=null},a=function(){r&&(o(),setTimeout(function(){r&&r.parentNode.removeChild(r),r=null},0),t.unloadDel(n))},c=function(e){r&&(a(),s(e))};return r.src=e,r.style.display="none",r.style.position="absolute",r.onerror=function(){c("onerror")},r.onload=function(){clearTimeout(i),i=setTimeout(function(){c("onload timeout")},2e3)},M.document.body.appendChild(r),i=setTimeout(function(){c("timeout")},15e3),n=t.unloadAdd(a),{post:function(e,t){setTimeout(function(){try{r&&r.contentWindow&&r.contentWindow.postMessage(e,t)}catch(e){}},0)},cleanup:a,loaded:o}},createHtmlfile:function(s,i){var n,r,o,a=["Active"].concat("Object").join("X"),c=new M[a]("htmlfile"),l=function(){clearTimeout(n),o.onerror=null},h=function(){c&&(l(),t.unloadDel(r),o.parentNode.removeChild(o),o=c=null,CollectGarbage())},d=function(e){c&&(h(),i(e))};c.open(),c.write('<html><script>document.domain="'+M.document.domain+'";<\/script></html>'),c.close(),c.parentWindow[e.exports.WPrefix]=M[e.exports.WPrefix];var u=c.createElement("div");return c.body.appendChild(u),o=c.createElement("iframe"),u.appendChild(o),o.src=s,o.onerror=function(){d("onerror")},n=setTimeout(function(){d("timeout")},15e3),r=t.unloadAdd(h),{post:function(e,t){try{setTimeout(function(){o&&o.contentWindow&&o.contentWindow.postMessage(e,t)},0)}catch(e){}},cleanup:h,loaded:l}}},e.exports.iframeEnabled=!1,M.document&&(e.exports.iframeEnabled=("function"==typeof M.postMessage||"object"==typeof M.postMessage)&&!s.isKonqueror())}(Ct)),Ct.exports}function At(){if(rt)return nt;rt=1;var e=ee(),t=oe().EventEmitter,s=st(),i=Y(),n=Rt(),r=B(),o=H();function a(e,s,c){if(!a.enabled())throw new Error("Transport created when disabled");t.call(this);var l=this;this.origin=i.getOrigin(c),this.baseUrl=c,this.transUrl=s,this.transport=e,this.windowId=o.string(8);var h=i.addPath(c,"/iframe.html")+"#"+this.windowId;this.iframeObj=n.createIframe(h,function(e){l.emit("close",1006,"Unable to load an iframe ("+e+")"),l.close()}),this.onmessageCallback=this._message.bind(this),r.attachEvent("message",this.onmessageCallback)}return e(a,t),a.prototype.close=function(){if(this.removeAllListeners(),this.iframeObj){r.detachEvent("message",this.onmessageCallback);try{this.postMessage("c")}catch(e){}this.iframeObj.cleanup(),this.iframeObj=null,this.onmessageCallback=this.iframeObj=null}},a.prototype._message=function(e){if(e.data,!i.isOriginEqual(e.origin,this.origin))return e.origin,void this.origin;var t;try{t=JSON.parse(e.data)}catch(t){return void e.data}if(t.windowId!==this.windowId)return t.windowId,void this.windowId;switch(t.type){case"s":this.iframeObj.loaded(),this.postMessage("s",JSON.stringify([s,this.transport,this.transUrl,this.baseUrl]));break;case"t":this.emit("message",t.data);break;case"c":var n;try{n=JSON.parse(t.data)}catch(e){return void t.data}this.emit("close",n[0],n[1]),this.close()}},a.prototype.postMessage=function(e,t){this.iframeObj.post(JSON.stringify({windowId:this.windowId,type:e,data:t||""}),this.origin)},a.prototype.send=function(e){this.postMessage("m",e)},a.enabled=function(){return n.iframeEnabled},a.transportName="iframe",a.roundTrips=2,nt=a}function Nt(){return at||(at=1,ot={isObject:function(e){var t=typeof e;return"function"===t||"object"===t&&!!e},extend:function(e){if(!this.isObject(e))return e;for(var t,s,i=1,n=arguments.length;i<n;i++)for(s in t=arguments[i])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e}}),ot}function Ot(){if(lt)return ct;lt=1;var e=ee(),t=At(),s=Nt();return ct=function(i){function n(e,s){t.call(this,i.transportName,e,s)}return e(n,t),n.enabled=function(e,n){if(!M.document)return!1;var r=s.extend({},n);return r.sameOrigin=!0,i.enabled(r)&&t.enabled()},n.transportName="iframe-"+i.transportName,n.needBody=!0,n.roundTrips=t.roundTrips+i.roundTrips-1,n.facadeTransport=i,n},ct}function kt(){if(pt)return ut;pt=1;var e=ee(),t=function(){if(dt)return ht;dt=1;var e=ee(),t=Rt(),s=Y(),i=oe().EventEmitter,n=H();function r(e){i.call(this);var o=this;t.polluteGlobalNamespace(),this.id="a"+n.string(6),e=s.addQuery(e,"c="+decodeURIComponent(t.WPrefix+"."+this.id)),r.htmlfileEnabled;var a=r.htmlfileEnabled?t.createHtmlfile:t.createIframe;M[t.WPrefix][this.id]={start:function(){o.iframeObj.loaded()},message:function(e){o.emit("message",e)},stop:function(){o._cleanup(),o._close("network")}},this.iframeObj=a(e,function(){o._cleanup(),o._close("permanent")})}e(r,i),r.prototype.abort=function(){this._cleanup(),this._close("user")},r.prototype._cleanup=function(){this.iframeObj&&(this.iframeObj.cleanup(),this.iframeObj=null),delete M[t.WPrefix][this.id]},r.prototype._close=function(e){this.emit("close",null,e),this.removeAllListeners()},r.htmlfileEnabled=!1;var o=["Active"].concat("Object").join("X");if(o in M)try{r.htmlfileEnabled=!!new M[o]("htmlfile")}catch(e){}return r.enabled=r.htmlfileEnabled||t.iframeEnabled,ht=r}(),s=qe(),i=Ge();function n(e){if(!t.enabled)throw new Error("Transport created when disabled");i.call(this,e,"/htmlfile",t,s)}return e(n,i),n.enabled=function(e){return t.enabled&&e.sameOrigin},n.transportName="htmlfile",n.roundTrips=2,ut=n}function Mt(){if(mt)return gt;mt=1;var e=ee(),t=Ge(),s=Je(),i=ze(),n=qe();function r(e){if(!n.enabled&&!i.enabled)throw new Error("Transport created when disabled");t.call(this,e,"/xhr",s,i)}return e(r,t),r.enabled=function(e){return!e.nullOrigin&&(!(!n.enabled||!e.sameOrigin)||i.enabled)},r.transportName="xhr-polling",r.roundTrips=2,gt=r}function Lt(){if(bt)return ft;bt=1;var e=ee(),t=Ge(),s=Ze(),i=Je(),n=Qe();function r(e){if(!n.enabled)throw new Error("Transport created when disabled");t.call(this,e,"/xhr",i,n)}return e(r,t),r.enabled=s.enabled,r.transportName="xdr-polling",r.roundTrips=2,ft=r}function Dt(){if(vt)return Et;vt=1;var e,t,s=H(),i=Y();return Et=function(n,r,o){e||((e=M.document.createElement("form")).style.display="none",e.style.position="absolute",e.method="POST",e.enctype="application/x-www-form-urlencoded",e.acceptCharset="UTF-8",(t=M.document.createElement("textarea")).name="d",e.appendChild(t),M.document.body.appendChild(e));var a="a"+s.string(8);e.target=a,e.action=i.addQuery(i.addPath(n,"/jsonp_send"),"i="+a);var c=function(e){try{return M.document.createElement('<iframe name="'+e+'">')}catch(s){var t=M.document.createElement("iframe");return t.name=e,t}}(a);c.id=a,c.style.display="none",e.appendChild(c);try{t.value=r}catch(e){}e.submit();var l=function(e){c.onerror&&(c.onreadystatechange=c.onerror=c.onload=null,setTimeout(function(){c.parentNode.removeChild(c),c=null},500),t.value="",o(e))};return c.onerror=function(){l()},c.onload=function(){l()},c.onreadystatechange=function(e){c.readyState,"complete"===c.readyState&&l()},function(){l(new Error("Aborted"))}},Et}function Pt(){if(It)return St;It=1;var e=ee(),t=Ve(),s=function(){if(yt)return _t;yt=1;var e=Rt(),t=H(),s=Xe(),i=Y(),n=ee(),r=oe().EventEmitter;function o(s){var n=this;r.call(this),e.polluteGlobalNamespace(),this.id="a"+t.string(6);var a=i.addQuery(s,"c="+encodeURIComponent(e.WPrefix+"."+this.id));M[e.WPrefix][this.id]=this._callback.bind(this),this._createScript(a),this.timeoutId=setTimeout(function(){n._abort(new Error("JSONP script loaded abnormally (timeout)"))},o.timeout)}return n(o,r),o.prototype.abort=function(){if(M[e.WPrefix][this.id]){var t=new Error("JSONP user aborted read");t.code=1e3,this._abort(t)}},o.timeout=35e3,o.scriptErrorTimeout=1e3,o.prototype._callback=function(e){this._cleanup(),this.aborting||(e&&this.emit("message",e),this.emit("close",null,"network"),this.removeAllListeners())},o.prototype._abort=function(e){this._cleanup(),this.aborting=!0,this.emit("close",e.code,e.message),this.removeAllListeners()},o.prototype._cleanup=function(){if(clearTimeout(this.timeoutId),this.script2&&(this.script2.parentNode.removeChild(this.script2),this.script2=null),this.script){var t=this.script;t.parentNode.removeChild(t),t.onreadystatechange=t.onerror=t.onload=t.onclick=null,this.script=null}delete M[e.WPrefix][this.id]},o.prototype._scriptError=function(){var e=this;this.errorTimer||(this.errorTimer=setTimeout(function(){e.loadedOkay||e._abort(new Error("JSONP script loaded abnormally (onerror)"))},o.scriptErrorTimeout))},o.prototype._createScript=function(e){var i,n=this,r=this.script=M.document.createElement("script");if(r.id="a"+t.string(8),r.src=e,r.type="text/javascript",r.charset="UTF-8",r.onerror=this._scriptError.bind(this),r.onload=function(){n._abort(new Error("JSONP script loaded abnormally (onload)"))},r.onreadystatechange=function(){if(r.readyState,/loaded|closed/.test(r.readyState)){if(r&&r.htmlFor&&r.onclick){n.loadedOkay=!0;try{r.onclick()}catch(e){}}r&&n._abort(new Error("JSONP script loaded abnormally (onreadystatechange)"))}},void 0===r.async&&M.document.attachEvent)if(s.isOpera())(i=this.script2=M.document.createElement("script")).text="try{var a = document.getElementById('"+r.id+"'); if(a)a.onerror();}catch(x){};",r.async=i.async=!1;else{try{r.htmlFor=r.id,r.event="onclick"}catch(e){}r.async=!0}void 0!==r.async&&(r.async=!0);var o=M.document.getElementsByTagName("head")[0];o.insertBefore(r,o.firstChild),i&&o.insertBefore(i,o.firstChild)},_t=o}(),i=Dt();function n(e){if(!n.enabled())throw new Error("Transport created when disabled");t.call(this,e,"/jsonp",i,s)}return e(n,t),n.enabled=function(){return!!M.document},n.transportName="jsonp-polling",n.roundTrips=1,n.needBody=!0,St=n}function xt(){return Tt?wt:(Tt=1,wt=[Be(),Ye(),Ze(),tt(),Ot()(tt()),kt(),Ot()(kt()),Mt(),Lt(),Ot()(Mt()),Pt()])}var Ut,Wt,Ft,jt,$t,Ht,Bt,Vt,Gt,Jt,Kt,zt,qt,Xt,Yt,Qt,Zt,es,ts,ss,is,ns,rs,os,as,cs,ls,hs,ds,us,ps,gs,ms,fs={};function bs(){if(Ut)return fs;Ut=1;var e,t=Array.prototype,s=Object.prototype,i=Function.prototype,n=String.prototype,r=t.slice,o=s.toString,a=function(e){return"[object Function]"===s.toString.call(e)},c=function(e){return"[object String]"===o.call(e)},l=Object.defineProperty&&function(){try{return Object.defineProperty({},"x",{}),!0}catch(e){return!1}}();e=l?function(e,t,s,i){!i&&t in e||Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:!0,value:s})}:function(e,t,s,i){!i&&t in e||(e[t]=s)};var h=function(t,i,n){for(var r in i)s.hasOwnProperty.call(i,r)&&e(t,r,i[r],n)},d=function(e){if(null==e)throw new TypeError("can't convert "+e+" to object");return Object(e)};function u(){}h(i,{bind:function(e){var t=this;if(!a(t))throw new TypeError("Function.prototype.bind called on incompatible "+t);for(var s=r.call(arguments,1),i=Math.max(0,t.length-s.length),n=[],o=0;o<i;o++)n.push("$"+o);var c=Function("binder","return function ("+n.join(",")+"){ return binder.apply(this, arguments); }")(function(){if(this instanceof c){var i=t.apply(this,s.concat(r.call(arguments)));return Object(i)===i?i:this}return t.apply(e,s.concat(r.call(arguments)))});return t.prototype&&(u.prototype=t.prototype,c.prototype=new u,u.prototype=null),c}}),h(Array,{isArray:function(e){return"[object Array]"===o.call(e)}});var p,g,m,f=Object("a"),b="a"!==f[0]||!(0 in f);h(t,{forEach:function(e){var t=d(this),s=b&&c(this)?this.split(""):t,i=arguments[1],n=-1,r=s.length>>>0;if(!a(e))throw new TypeError;for(;++n<r;)n in s&&e.call(i,s[n],n,t)}},(p=t.forEach,g=!0,m=!0,p&&(p.call("foo",function(e,t,s){"object"!=typeof s&&(g=!1)}),p.call([1],function(){m="string"==typeof this},"x")),!(p&&g&&m)));var _=Array.prototype.indexOf&&-1!==[0,1].indexOf(1,2);h(t,{indexOf:function(e){var t=b&&c(this)?this.split(""):d(this),s=t.length>>>0;if(!s)return-1;var i,n=0;for(arguments.length>1&&((i=+arguments[1])!=i?i=0:0!==i&&i!==1/0&&i!==-1/0&&(i=(i>0||-1)*Math.floor(Math.abs(i))),n=i),n=n>=0?n:Math.max(0,s+n);n<s;n++)if(n in t&&t[n]===e)return n;return-1}},_);var y,E=n.split;2!=="ab".split(/(?:ab)*/).length||4!==".".split(/(.?)(.?)/).length||"t"==="tesst".split(/(s)*/)[1]||4!=="test".split(/(?:)/,-1).length||"".split(/.?/).length||".".split(/()()/).length>1?(y=void 0===/()??/.exec("")[1],n.split=function(e,s){var i=this;if(void 0===e&&0===s)return[];if("[object RegExp]"!==o.call(e))return E.call(this,e,s);var n,r,a,c,l=[],h=(e.ignoreCase?"i":"")+(e.multiline?"m":"")+(e.extended?"x":"")+(e.sticky?"y":""),d=0;for(e=new RegExp(e.source,h+"g"),i+="",y||(n=new RegExp("^"+e.source+"$(?!\\s)",h)),s=void 0===s?-1>>>0:s>>>0;(r=e.exec(i))&&!((a=r.index+r[0].length)>d&&(l.push(i.slice(d,r.index)),!y&&r.length>1&&r[0].replace(n,function(){for(var e=1;e<arguments.length-2;e++)void 0===arguments[e]&&(r[e]=void 0)}),r.length>1&&r.index<i.length&&t.push.apply(l,r.slice(1)),c=r[0].length,d=a,l.length>=s));)e.lastIndex===r.index&&e.lastIndex++;return d===i.length?!c&&e.test("")||l.push(""):l.push(i.slice(d)),l.length>s?l.slice(0,s):l}):"0".split(void 0,0).length&&(n.split=function(e,t){return void 0===e&&0===t?[]:E.call(this,e,t)});var v=n.substr,S="".substr&&"b"!=="0b".substr(-1);return h(n,{substr:function(e,t){return v.call(this,e<0&&(e=this.length+e)<0?0:e,t)}},S),fs}function _s(){if(Ft)return Wt;Ft=1;var e,t=/[\x00-\x1f\ud800-\udfff\ufffe\uffff\u0300-\u0333\u033d-\u0346\u034a-\u034c\u0350-\u0352\u0357-\u0358\u035c-\u0362\u0374\u037e\u0387\u0591-\u05af\u05c4\u0610-\u0617\u0653-\u0654\u0657-\u065b\u065d-\u065e\u06df-\u06e2\u06eb-\u06ec\u0730\u0732-\u0733\u0735-\u0736\u073a\u073d\u073f-\u0741\u0743\u0745\u0747\u07eb-\u07f1\u0951\u0958-\u095f\u09dc-\u09dd\u09df\u0a33\u0a36\u0a59-\u0a5b\u0a5e\u0b5c-\u0b5d\u0e38-\u0e39\u0f43\u0f4d\u0f52\u0f57\u0f5c\u0f69\u0f72-\u0f76\u0f78\u0f80-\u0f83\u0f93\u0f9d\u0fa2\u0fa7\u0fac\u0fb9\u1939-\u193a\u1a17\u1b6b\u1cda-\u1cdb\u1dc0-\u1dcf\u1dfc\u1dfe\u1f71\u1f73\u1f75\u1f77\u1f79\u1f7b\u1f7d\u1fbb\u1fbe\u1fc9\u1fcb\u1fd3\u1fdb\u1fe3\u1feb\u1fee-\u1fef\u1ff9\u1ffb\u1ffd\u2000-\u2001\u20d0-\u20d1\u20d4-\u20d7\u20e7-\u20e9\u2126\u212a-\u212b\u2329-\u232a\u2adc\u302b-\u302c\uaab2-\uaab3\uf900-\ufa0d\ufa10\ufa12\ufa15-\ufa1e\ufa20\ufa22\ufa25-\ufa26\ufa2a-\ufa2d\ufa30-\ufa6d\ufa70-\ufad9\ufb1d\ufb1f\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufb4e\ufff0-\uffff]/g;return Wt={quote:function(s){var i=JSON.stringify(s);return t.lastIndex=0,t.test(i)?(e||(e=function(e){var t,s={},i=[];for(t=0;t<65536;t++)i.push(String.fromCharCode(t));return e.lastIndex=0,i.join("").replace(e,function(e){return s[e]="\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4),""}),e.lastIndex=0,s}(t)),i.replace(t,function(t){return e[t]})):i}}}function ys(){if($t)return jt;$t=1;return jt=function(e){return{filterToEnabled:function(t,s){var i={main:[],facade:[]};return t?"string"==typeof t&&(t=[t]):t=[],e.forEach(function(e){e&&("websocket"===e.transportName&&!1===s.websocket||(t.length&&-1===t.indexOf(e.transportName)?e.transportName:e.enabled(s)?(e.transportName,i.main.push(e),e.facadeTransport&&i.facade.push(e.facadeTransport)):e.transportName))}),i}}}}function Es(){if(Bt)return Ht;Bt=1;var e={};return["log","debug","warn"].forEach(function(t){var s;try{s=M.console&&M.console[t]&&M.console[t].apply}catch(e){}e[t]=s?function(){return M.console[t].apply(M.console,arguments)}:"log"===t?function(){}:e.log}),Ht=e}function vs(){if(Gt)return Vt;function e(e){this.type=e}return Gt=1,e.prototype.initEvent=function(e,t,s){return this.type=e,this.bubbles=t,this.cancelable=s,this.timeStamp=+new Date,this},e.prototype.stopPropagation=function(){},e.prototype.preventDefault=function(){},e.CAPTURING_PHASE=1,e.AT_TARGET=2,e.BUBBLING_PHASE=3,Vt=e}function Ss(){return Kt?Jt:(Kt=1,Jt=M.location||{origin:"http://localhost:80",protocol:"http:",host:"localhost",port:80,href:"http://localhost/",hash:""})}function Is(){if(ts)return es;ts=1;var e=oe().EventEmitter,t=ee(),s=Nt();function i(t,i){e.call(this);var n=this,r=+new Date;this.xo=new i("GET",t),this.xo.once("finish",function(e,t){var i,o;if(200===e){if(o=+new Date-r,t)try{i=JSON.parse(t)}catch(e){}s.isObject(i)||(i={})}n.emit("finish",i,o),n.removeAllListeners()})}return t(i,e),i.prototype.close=function(){this.removeAllListeners(),this.xo.close()},es=i}function ws(){if(is)return ss;is=1;var e=ee(),t=oe().EventEmitter,s=qe(),i=Is();function n(e){var n=this;t.call(this),this.ir=new i(e,s),this.ir.once("finish",function(e,t){n.ir=null,n.emit("message",JSON.stringify([e,t]))})}return e(n,t),n.transportName="iframe-info-receiver",n.prototype.close=function(){this.ir&&(this.ir.close(),this.ir=null),this.removeAllListeners()},ss=n}function Ts(){if(as)return os;as=1;var e=oe().EventEmitter,t=ee(),s=Y(),i=Qe(),n=ze(),r=qe(),o=function(){if(Zt)return Qt;Zt=1;var e=oe().EventEmitter;function t(){var s=this;e.call(this),this.to=setTimeout(function(){s.emit("finish",200,"{}")},t.timeout)}return ee()(t,e),t.prototype.close=function(){clearTimeout(this.to)},t.timeout=2e3,Qt=t}(),a=function(){if(rs)return ns;rs=1;var e=oe().EventEmitter,t=ee(),s=B(),i=At(),n=ws();function r(t,r){var o=this;e.call(this);var a=function(){var e=o.ifr=new i(n.transportName,r,t);e.once("message",function(e){if(e){var t;try{t=JSON.parse(e)}catch(e){return o.emit("finish"),void o.close()}var s=t[0],i=t[1];o.emit("finish",s,i)}o.close()}),e.once("close",function(){o.emit("finish"),o.close()})};M.document.body?a():s.attachEvent("load",a)}return t(r,e),r.enabled=function(){return i.enabled()},r.prototype.close=function(){this.ifr&&this.ifr.close(),this.removeAllListeners(),this.ifr=null},ns=r}(),c=Is();function l(t,s){var i=this;e.call(this),setTimeout(function(){i.doXhr(t,s)},0)}return t(l,e),l._getReceiver=function(e,t,s){return s.sameOrigin?new c(t,r):n.enabled?new c(t,n):i.enabled&&s.sameScheme?new c(t,i):a.enabled()?new a(e,t):new c(t,o)},l.prototype.doXhr=function(e,t){var i=this,n=s.addPath(e,"/info");this.xo=l._getReceiver(e,n,t),this.timeoutRef=setTimeout(function(){i._cleanup(!1),i.emit("finish")},l.timeout),this.xo.once("finish",function(e,t){i._cleanup(!0),i.emit("finish",e,t)})},l.prototype._cleanup=function(e){clearTimeout(this.timeoutRef),this.timeoutRef=null,!e&&this.xo&&this.xo.close(),this.xo=null},l.prototype.close=function(){this.removeAllListeners(),this._cleanup(!1)},l.timeout=8e3,os=l}function Cs(){if(ds)return hs;ds=1;var e=Y(),t=B(),s=function(){if(ls)return cs;ls=1;var e=Rt();function t(e){this._transport=e,e.on("message",this._transportMessage.bind(this)),e.on("close",this._transportClose.bind(this))}return t.prototype._transportClose=function(t,s){e.postMessage("c",JSON.stringify([t,s]))},t.prototype._transportMessage=function(t){e.postMessage("t",t)},t.prototype._send=function(e){this._transport.send(e)},t.prototype._close=function(){this._transport.close(),this._transport.removeAllListeners()},cs=t}(),i=ws(),n=Rt(),r=Ss();return hs=function(o,a){var c,l={};a.forEach(function(e){e.facadeTransport&&(l[e.facadeTransport.transportName]=e.facadeTransport)}),l[i.transportName]=i,o.bootstrap_iframe=function(){var i;n.currentWindowId=r.hash.slice(1);t.attachEvent("message",function(t){if(t.source===parent&&(void 0===c&&(c=t.origin),t.origin===c)){var a;try{a=JSON.parse(t.data)}catch(e){return void t.data}if(a.windowId===n.currentWindowId)switch(a.type){case"s":var h;try{h=JSON.parse(a.data)}catch(e){a.data;break}var d=h[0],u=h[1],p=h[2],g=h[3];if(d!==o.version)throw new Error('Incompatible SockJS! Main site uses: "'+d+'", the iframe: "'+o.version+'".');if(!e.isOriginEqual(p,r.href)||!e.isOriginEqual(g,r.href))throw new Error("Can't connect to different domain from within an iframe. ("+r.href+", "+p+", "+g+")");i=new s(new l[u](p,g));break;case"m":i._send(a.data);break;case"c":i&&i._close(),i=null}}}),n.postMessage("s")}},hs}function Rs(){if(ps)return us;ps=1,bs();var e,t=X(),s=ee(),i=H(),n=_s(),r=Y(),o=B(),a=ys(),c=Nt(),l=Xe(),h=Es(),d=vs(),u=re(),p=Ss(),g=function(){if(qt)return zt;qt=1;var e=ee(),t=vs();function s(){t.call(this),this.initEvent("close",!1,!1),this.wasClean=!1,this.code=0,this.reason=""}return e(s,t),zt=s}(),m=function(){if(Yt)return Xt;Yt=1;var e=ee(),t=vs();function s(e){t.call(this),this.initEvent("message",!1,!1),this.data=e}return e(s,t),Xt=s}(),f=Ts(),b=function(){};function _(e,s,n){if(!(this instanceof _))return new _(e,s,n);if(arguments.length<1)throw new TypeError("Failed to construct 'SockJS: 1 argument required, but only 0 present");u.call(this),this.readyState=_.CONNECTING,this.extensions="",this.protocol="",(n=n||{}).protocols_whitelist&&h.warn("'protocols_whitelist' is DEPRECATED. Use 'transports' instead."),this._transportsWhitelist=n.transports,this._transportOptions=n.transportOptions||{},this._timeout=n.timeout||0;var o=n.sessionId||8;if("function"==typeof o)this._generateSessionId=o;else{if("number"!=typeof o)throw new TypeError("If sessionId is used in the options, it needs to be a number or a function.");this._generateSessionId=function(){return i.string(o)}}this._server=n.server||i.numberString(1e3);var a=new t(e);if(!a.host||!a.protocol)throw new SyntaxError("The URL '"+e+"' is invalid");if(a.hash)throw new SyntaxError("The URL must not contain a fragment");if("http:"!==a.protocol&&"https:"!==a.protocol)throw new SyntaxError("The URL's scheme must be either 'http:' or 'https:'. '"+a.protocol+"' is not allowed.");var c="https:"===a.protocol;if("https:"===p.protocol&&!c&&!r.isLoopbackAddr(a.hostname))throw new Error("SecurityError: An insecure SockJS connection may not be initiated from a page loaded over HTTPS");s?Array.isArray(s)||(s=[s]):s=[];var d=s.sort();d.forEach(function(e,t){if(!e)throw new SyntaxError("The protocols entry '"+e+"' is invalid.");if(t<d.length-1&&e===d[t+1])throw new SyntaxError("The protocols entry '"+e+"' is duplicated.")});var g=r.getOrigin(p.href);this._origin=g?g.toLowerCase():null,a.set("pathname",a.pathname.replace(/\/+$/,"")),this.url=a.href,this.url,this._urlInfo={nullOrigin:!l.hasDomain(),sameOrigin:r.isOriginEqual(this.url,p.href),sameScheme:r.isSchemeEqual(this.url,p.href)},this._ir=new f(this.url,this._urlInfo),this._ir.once("finish",this._receiveInfo.bind(this))}function y(e){return 1e3===e||e>=3e3&&e<=4999}return s(_,u),_.prototype.close=function(e,t){if(e&&!y(e))throw new Error("InvalidAccessError: Invalid code");if(t&&t.length>123)throw new SyntaxError("reason argument has an invalid length");if(this.readyState!==_.CLOSING&&this.readyState!==_.CLOSED){this._close(e||1e3,t||"Normal closure",!0)}},_.prototype.send=function(e){if("string"!=typeof e&&(e=""+e),this.readyState===_.CONNECTING)throw new Error("InvalidStateError: The connection has not been established yet");this.readyState===_.OPEN&&this._transport.send(n.quote(e))},_.version=st(),_.CONNECTING=0,_.OPEN=1,_.CLOSING=2,_.CLOSED=3,_.prototype._receiveInfo=function(t,s){if(this._ir=null,t){this._rto=this.countRTO(s),this._transUrl=t.base_url?t.base_url:this.url,t=c.extend(t,this._urlInfo);var i=e.filterToEnabled(this._transportsWhitelist,t);this._transports=i.main,this._transports.length,this._connect()}else this._close(1002,"Cannot connect to server")},_.prototype._connect=function(){for(var e=this._transports.shift();e;e=this._transports.shift()){if(b(e.transportName),e.needBody&&(!M.document.body||void 0!==M.document.readyState&&"complete"!==M.document.readyState&&"interactive"!==M.document.readyState))return this._transports.unshift(e),void o.attachEvent("load",this._connect.bind(this));var t=Math.max(this._timeout,this._rto*e.roundTrips||5e3);this._transportTimeoutId=setTimeout(this._transportTimeout.bind(this),t);var s=r.addPath(this._transUrl,"/"+this._server+"/"+this._generateSessionId()),i=this._transportOptions[e.transportName],n=new e(s,this._transUrl,i);return n.on("message",this._transportMessage.bind(this)),n.once("close",this._transportClose.bind(this)),n.transportName=e.transportName,void(this._transport=n)}this._close(2e3,"All transports failed",!1)},_.prototype._transportTimeout=function(){this.readyState===_.CONNECTING&&(this._transport&&this._transport.close(),this._transportClose(2007,"Transport timed out"))},_.prototype._transportMessage=function(e){var t,s=this,i=e.slice(0,1),n=e.slice(1);switch(i){case"o":return void this._open();case"h":return this.dispatchEvent(new d("heartbeat")),void this.transport}if(n)try{t=JSON.parse(n)}catch(e){}if(void 0!==t)switch(i){case"a":Array.isArray(t)&&t.forEach(function(e){s.transport,s.dispatchEvent(new m(e))});break;case"m":this.transport,this.dispatchEvent(new m(t));break;case"c":Array.isArray(t)&&2===t.length&&this._close(t[0],t[1],!0)}},_.prototype._transportClose=function(e,t){this.transport,this._transport&&(this._transport.removeAllListeners(),this._transport=null,this.transport=null),y(e)||2e3===e||this.readyState!==_.CONNECTING?this._close(e,t):this._connect()},_.prototype._open=function(){this._transport&&this._transport.transportName,this.readyState,this.readyState===_.CONNECTING?(this._transportTimeoutId&&(clearTimeout(this._transportTimeoutId),this._transportTimeoutId=null),this.readyState=_.OPEN,this.transport=this._transport.transportName,this.dispatchEvent(new d("open")),this.transport):this._close(1006,"Server lost session")},_.prototype._close=function(e,t,s){this.transport,this.readyState;var i=!1;if(this._ir&&(i=!0,this._ir.close(),this._ir=null),this._transport&&(this._transport.close(),this._transport=null,this.transport=null),this.readyState===_.CLOSED)throw new Error("InvalidStateError: SockJS has already been closed");this.readyState=_.CLOSING,setTimeout(function(){this.readyState=_.CLOSED,i&&this.dispatchEvent(new d("error"));var n=new g("close");n.wasClean=s||!1,n.code=e||1e3,n.reason=t,this.dispatchEvent(n),this.onmessage=this.onclose=this.onerror=null}.bind(this),0)},_.prototype.countRTO=function(e){return e>100?4*e:300+e},us=function(t){return e=a(t),Cs()(_,t),_}}var As=function(){if(ms)return gs;ms=1;var e=xt();return gs=Rs()(e),"_sockjs_onload"in M&&setTimeout(M._sockjs_onload,1),gs}(),Ns=L(As);const Os=()=>"undefined"!=typeof window&&window.StompJs&&window.StompJs.Client?window.StompJs.Client:k,ks=()=>"undefined"!=typeof window&&window.SockJS?window.SockJS:Ns;class Ms extends t{constructor(e){super(),this.serverUrl=e.serverUrl.replace(/\/$/,""),this.jwtToken=e.jwtToken,this.apiKey=e.apiKey,this.projectId=e.projectId,this.useSockJS=!1!==e.useSockJS,this.reconnectDelay=e.reconnectDelay||h.reconnectDelay,this.maxReconnectAttempts=e.maxReconnectAttempts||h.maxReconnectAttempts,this.heartbeatIncoming=e.heartbeatIncoming||h.heartbeatIncoming,this.heartbeatOutgoing=e.heartbeatOutgoing||h.heartbeatOutgoing,this.logger=new p(e.logLevel||u.WARN,"ConnectionManager"),this.state=s.DISCONNECTED,this.stompClient=null,this.reconnectAttempts=0,this.subscriptions=new Map,this.pendingSubscriptions=[],this.userId=null}_setState(e){const t=this.state;this.state=e,this.emit("stateChange",{state:e,prevState:t}),this.logger.info(`State changed: ${t} -> ${e}`)}_getWebSocketUrl(){const e=this.useSockJS?a.SOCKJS_ENDPOINT:a.NATIVE_ENDPOINT;return`${this.serverUrl}${e}`}_createStompClient(){const e=this._getWebSocketUrl(),t={connectHeaders:{Authorization:this.jwtToken.startsWith("Bearer ")?this.jwtToken:`Bearer ${this.jwtToken}`,"X-API-KEY":this.apiKey,"X-PROJECT-ID":this.projectId},heartbeatIncoming:this.heartbeatIncoming,heartbeatOutgoing:this.heartbeatOutgoing,reconnectDelay:this.reconnectDelay,debug:e=>{this.logger.level<=u.DEBUG&&this.logger.debug("STOMP:",e)},onConnect:e=>this._onConnect(e),onDisconnect:e=>this._onDisconnect(e),onStompError:e=>this._onStompError(e),onWebSocketClose:e=>this._onWebSocketClose(e),onWebSocketError:e=>this._onWebSocketError(e)};if(this.useSockJS){const s=ks();t.webSocketFactory=()=>new s(e)}else{const e=this.serverUrl.startsWith("https")?"wss":"ws",s=this.serverUrl.replace(/^https?:\/\//,"");t.brokerURL=`${e}://${s}${a.NATIVE_ENDPOINT}`}return new(Os())(t)}async connect(){if(this.state!==s.CONNECTED){if(this.state!==s.CONNECTING)return this._setState(s.CONNECTING),this.reconnectAttempts=0,new Promise((e,t)=>{this._connectResolve=e,this._connectReject=t;try{this.stompClient=this._createStompClient(),this.stompClient.activate()}catch(e){this._setState(s.ERROR),this._drainPendingSubscriptions("Connection activation failed"),t(e)}});this.logger.warn("Connection in progress")}else this.logger.warn("Already connected")}_onConnect(e){this._setState(s.CONNECTED),this.reconnectAttempts=0,this.logger.info("Connected to server",e),this._restoreSubscriptions(),this._processPendingSubscriptions(),this.emit("connected",{frame:e}),this._connectResolve&&(this._connectResolve(),this._connectResolve=null,this._connectReject=null)}_onDisconnect(e){this.logger.info("Disconnected from server",e),this._setState(s.DISCONNECTED),this.emit("disconnected",{frame:e})}_onStompError(e){this.logger.error("STOMP error:",e),this._setState(s.ERROR);const t={type:i.CONNECTION_FAILED,message:e.headers?.message||"STOMP error",frame:e};this._drainPendingSubscriptions(`STOMP error: ${t.message}`),this.emit("error",t),this._connectReject&&(this._connectReject(new Error(t.message)),this._connectResolve=null,this._connectReject=null)}_onWebSocketClose(e){this.logger.warn("WebSocket closed:",e),this.state!==s.DISCONNECTED&&this._handleReconnect()}_onWebSocketError(e){this.logger.error("WebSocket error:",e),this._connectReject&&(this._drainPendingSubscriptions("WebSocket connection failed"),this._connectReject(new Error("WebSocket connection failed")),this._connectResolve=null,this._connectReject=null)}_handleReconnect(){if(this.reconnectAttempts++,this.reconnectAttempts>this.maxReconnectAttempts){if(this.stompClient){try{this.stompClient.deactivate()}catch(e){this.logger.warn("Error deactivating stomp client on max reconnect:",e)}this.stompClient=null}return this._drainPendingSubscriptions("Max reconnection attempts exceeded"),this._setState(s.ERROR),void this.emit("error",{type:i.CONNECTION_LOST,message:"Max reconnection attempts exceeded"})}this._setState(s.RECONNECTING),this.emit("reconnecting",{attempt:this.reconnectAttempts}),this.logger.info(`Reconnecting... attempt ${this.reconnectAttempts}`)}_restoreSubscriptions(){if(0===this.subscriptions.size)return;this.logger.info(`Restoring ${this.subscriptions.size} subscriptions after reconnect`);const e=new Map(this.subscriptions);this.subscriptions.clear(),e.forEach(({callback:e,headers:t},s)=>{this._subscribeInternal(s,e,t),this.logger.debug(`Restored subscription: ${s}`)})}_processPendingSubscriptions(){for(;this.pendingSubscriptions.length>0;){const{destination:e,callback:t,headers:s,resolve:i}=this.pendingSubscriptions.shift(),n=this._subscribeInternal(e,t,s);i&&i(n)}}_subscribeInternal(e,t,s={}){const i=this.stompClient.subscribe(e,e=>{try{const s=JSON.parse(e.body);t(s,e)}catch(s){this.logger.error("Failed to parse message:",s),t(e.body,e)}},s);return this.subscriptions.set(e,{subscription:i,callback:t,headers:s}),this.logger.debug(`Subscribed to: ${e}`),i}subscribe(e,t,i={}){return this.subscriptions.has(e)&&this.unsubscribe(e),this.state!==s.CONNECTED?new Promise((s,n)=>{this.pendingSubscriptions.push({destination:e,callback:t,headers:i,resolve:s,reject:n}),this.logger.debug(`Queued subscription for: ${e}`)}):Promise.resolve(this._subscribeInternal(e,t,i))}unsubscribe(e){const t=this.subscriptions.get(e);t&&(t.subscription.unsubscribe(),this.subscriptions.delete(e),this.logger.debug(`Unsubscribed from: ${e}`))}unsubscribeAll(){this.subscriptions.forEach(({subscription:e},t)=>{e.unsubscribe(),this.logger.debug(`Unsubscribed from: ${t}`)}),this.subscriptions.clear()}send(e,t,i={}){return this.state!==s.CONNECTED?(this.logger.warn("Cannot send message: not connected"),!1):(this.stompClient.publish({destination:e,body:JSON.stringify(t),headers:i}),this.logger.debug(`Sent to ${e}:`,t),!0)}updateToken(e){this.jwtToken=e,this.stompClient&&(this.stompClient.connectHeaders={...this.stompClient.connectHeaders,Authorization:e.startsWith("Bearer ")?e:`Bearer ${e}`})}async disconnect(){this._drainPendingSubscriptions("Disconnected before subscription completed"),this.stompClient&&(this.unsubscribeAll(),await this.stompClient.deactivate(),this.stompClient=null),this._setState(s.DISCONNECTED),this.logger.info("Disconnected")}_drainPendingSubscriptions(e){if(0===this.pendingSubscriptions.length)return;const t=this.pendingSubscriptions;this.pendingSubscriptions=[],t.forEach(({destination:t,reject:s})=>{s&&s(new Error(`${e}: ${t}`))}),this.logger.debug(`Drained ${t.length} pending subscriptions: ${e}`)}isConnected(){return this.state===s.CONNECTED}getState(){return this.state}setLogLevel(e){this.logger.setLevel(e)}async destroy(){await this.disconnect(),this.removeAllListeners(),this.logger.info("ConnectionManager destroyed")}}class Ls extends t{constructor(e){super(),this.connectionManager=e.connectionManager,this.apiClient=e.apiClient,this.userId=e.userId,this.logger=new p(e.logLevel||u.WARN,"ChatClient"),this.subscribedRooms=new Map,this.roomListSubscribed=!1,this._activeRoomId=null,this._typingTimers=new Map,this._assistantTypingTimers=new Map,this._assistantTypingTimeoutMs=3e4,this._assistantTypingUserId="__assistant__",this._assistantTypingUserName="AI",this._assistantProgress=new Map,this._assistantPhaseLabels={THINKING:"생각 중…",SEARCHING:"검색 중…",PLANNING:"기획 중…",WRITING:"작성 중…"},this._assistantProgressFallbackTtlMs=35e3,this._seenChatMessageIdsByRoom=new Map,this._seenRoomListMessageIdsByRoom=new Map,this._maxSeenPerRoom=200}_shouldDedupMessage(e,t,s){if(!t||!s)return!1;let i=e.get(t);if(i||(i=new Map,e.set(t,i)),i.has(s))return!0;if(i.set(s,!0),i.size>this._maxSeenPerRoom){const e=i.keys().next().value;i.delete(e)}return!1}async getRooms(e={}){const{size:t=50,lastId:s,lastSortValue:i,type:n}=e;return this.apiClient.get("/api/v1/rooms/my",{size:t,lastId:s,lastSortValue:i,type:n})}async getRoom(e){return this.apiClient.get(`/api/v1/rooms/${e}`)}async enterRoom(e){const t=this.subscribedRooms.has(e);t||await this.subscribeRoom(e),this.setActiveRoom(e);try{return await this.getRoom(e)}catch(s){throw this.getActiveRoom()===e&&this.clearActiveRoom(),t||this.unsubscribeRoom(e),s}}async getRoomInfo(e){return this.apiClient.get(`/api/v1/rooms/${e}/info`)}async setMyRoomLanguage(e,t){return this.apiClient.put(`/api/v1/rooms/${e}/my-language`,{language:t})}async createOneToOneRoom(e){return this.apiClient.post(`/api/v1/rooms/direct/${e}`)}async createGroupRoom(e){const t=e.roomType||r.GROUP;if(t===r.PRIVATE_GROUP){if(!e.password||e.password.length<4)throw new Error("PRIVATE_GROUP requires a password of at least 4 characters")}else if(t===r.GROUP){if(e.password)throw new Error("Public GROUP rooms cannot have a password")}else if(t===r.TEAM&&e.password)throw new Error("TEAM rooms cannot have a password (invite-only)");return this.apiClient.post("/api/v1/rooms/group",{roomName:e.roomName,description:e.description,invitedUserIds:e.invitedUserIds,roomType:t,password:e.password,messageRetentionHours:e.messageRetentionHours,invitedAssistantPersonaIds:e.invitedAssistantPersonaIds,assistantMode:e.assistantMode,roomAiType:e.roomAiType,engagementIntensity:e.engagementIntensity})}async getAssistants(){const e=await this.apiClient.get("/api/v1/assistants");return this._unwrapSuccessResponse(e)}async getRoomAiMeta(){const e=await this.apiClient.get("/api/v1/rooms/ai-meta");return this._unwrapSuccessResponse(e)}async rateAssistantMessage(e,t,s,i){if(!Number.isInteger(s)||s<1||s>5)throw new Error("rating must be an integer between 1 and 5");await this.apiClient.post(`/api/v1/chat-messages/${e}/messages/${t}/rating`,{rating:s,comment:i})}async summarizeWithAssistant(e,t={}){const{personaId:s,format:i,messageCount:n}=t;if(!s)throw new Error("summarizeWithAssistant requires options.personaId");const r=await this.apiClient.post(`/api/v1/rooms/${e}/assistant/tools/summarize`,{personaId:s,format:i,messageCount:n});return this._unwrapSuccessResponse(r)}async translateWithAssistant(e,t={}){const{personaId:s,targetLang:i,sourceMessageId:n}=t;if(!s)throw new Error("translateWithAssistant requires options.personaId");if(!n)throw new Error("translateWithAssistant requires options.sourceMessageId");const r=await this.apiClient.post(`/api/v1/rooms/${e}/assistant/tools/translate`,{personaId:s,targetLang:i,sourceMessageId:n});return this._unwrapSuccessResponse(r)}async getRoomPmPrompt(e){const t=await this.apiClient.get(`/api/v1/rooms/${e}/pm-prompt`);return this._unwrapSuccessResponse(t)}async upsertRoomPmPrompt(e,t){if("string"!=typeof t||!t.trim())throw new Error("upsertRoomPmPrompt requires non-blank content");if(t.length>2e3)throw new Error("upsertRoomPmPrompt content exceeds 2000 characters");const s=await this.apiClient.put(`/api/v1/rooms/${e}/pm-prompt`,{content:t});return this._unwrapSuccessResponse(s)}async activateRoomPmPrompt(e){const t=await this.apiClient.patch(`/api/v1/rooms/${e}/pm-prompt/activate`);return this._unwrapSuccessResponse(t)}async deactivateRoomPmPrompt(e){const t=await this.apiClient.patch(`/api/v1/rooms/${e}/pm-prompt/deactivate`);return this._unwrapSuccessResponse(t)}async getRoomPmPromptVersions(e){const t=await this.apiClient.get(`/api/v1/rooms/${e}/pm-prompt/versions`);return this._unwrapSuccessResponse(t)}async activateRoomPmPromptVersion(e,t){if(!Number.isInteger(t)||t<1)throw new Error("activateRoomPmPromptVersion requires a positive integer version");const s=await this.apiClient.post(`/api/v1/rooms/${e}/pm-prompt/versions/${t}/activate`);return this._unwrapSuccessResponse(s)}async previewRoomPmPrompt(e){const t=await this.apiClient.get(`/api/v1/rooms/${e}/pm-prompt/preview`);return this._unwrapSuccessResponse(t)}async joinGroupRoom(e,t){const s=t?{password:t}:void 0;return this.apiClient.post(`/api/v1/rooms/group/${e}/join`,s)}async leaveRoom(e){const t=await this.apiClient.post(`/api/v1/rooms/${e}/leave`);return this.unsubscribeRoom(e),t}async updateGroupRoom(e,t){return this.apiClient.put(`/api/v1/rooms/group/${e}`,t)}async inviteToGroupRoom(e,t){const s=Array.isArray(t)?{userIds:t}:{userIds:t?.userIds,assistantPersonaIds:t?.assistantPersonaIds};return this.apiClient.post(`/api/v1/rooms/group/${e}/invite`,s)}async kickMember(e,t){return this.apiClient.delete(`/api/v1/rooms/${e}/members/${t}`)}async banMember(e,t){return this.apiClient.post(`/api/v1/rooms/${e}/banned-members`,{userId:t})}async unbanMember(e,t){return this.apiClient.delete(`/api/v1/rooms/${e}/banned-members/${t}`)}async getBannedMembers(e){const t=await this.apiClient.get(`/api/v1/rooms/${e}/banned-members`);return t&&"object"==typeof t&&"data"in t?t.data:t}async pinMessage(e,t){return this.apiClient.post(`/api/v1/rooms/group/${e}/pin/${t}`)}async unpinMessage(e){return this.apiClient.post(`/api/v1/rooms/group/${e}/unpin`)}async toggleReaction(e,t,s){return this.apiClient.post(`/api/v1/chat-messages/${e}/messages/${t}/reaction`,{emoji:s})}async getAvailableGroupRooms(e={}){const{size:t=50,lastId:s,lastSortValue:i}=e;return this.apiClient.get("/api/v1/rooms/groups/available",{size:t,lastId:s,lastSortValue:i})}async getAllGroupRooms(e={}){const{size:t=50,lastId:s,lastSortValue:i}=e;return this.apiClient.get("/api/v1/rooms/groups/all",{size:t,lastId:s,lastSortValue:i})}async getMessages(e,t={}){const{size:s=50,lastId:i,lastSortValue:n}=t,r=await this.apiClient.get(`/api/v1/chat-messages/${e}/list`,{size:s,lastId:i,lastSortValue:n}),o=this._unwrapSuccessResponse(r);return o&&Array.isArray(o.content)&&o.content.forEach(e=>this._normalizeMessageTimestamps(e)),r}async fetchLinkPreview(e){const t="string"==typeof e?e.trim():"";if(!t)throw new Error("url is required");const s=await this.apiClient.post("/api/v1/link-preview",{url:t});return this._unwrapSuccessResponse(s)}async sendMessage(e,t){const s=this._generateMessageId();return this._sendMessageWithId(e,s,t)}sendMessageOptimistic(e,t){const s=this._generateMessageId(),i=this._predictMessageIdsFromData(s,t),n=this._sendMessageWithId(e,s,t).then(e=>this._attachOptimisticMetadata(i,e));return{baseMessageId:s,messageIds:i,promise:n}}async _sendMessageWithId(e,t,s){this.stopTyping(e);const i=await this.apiClient.post(`/api/v1/chat-messages/${e}/send`,{messageId:t,message:s.message,fileInfos:s.fileInfos,separateFiles:!1!==s.separateFiles,replyToMessageId:s.replyToMessageId}),n=this._unwrapSuccessResponse(i);return n&&Array.isArray(n.messages)&&n.messages.forEach(e=>this._normalizeMessageTimestamps(e)),n}async sendTextMessage(e,t){return this.sendMessage(e,{message:t})}sendTextMessageOptimistic(e,t){return this.sendMessageOptimistic(e,{message:t})}async uploadFile(e,t,s={}){if(!e)throw new Error("roomId is required");if(!t)throw new Error("file is required");const i=await this.apiClient.upload(`/api/v1/files/${e}/upload`,t,{onProgress:s.onProgress,signal:s.signal});return this._unwrapSuccessResponse(i)}async sendFileMessage(e,t,s={}){const i=this._normalizeFileArray(t),n=await this._uploadFiles(e,i,s),r=this._applyFileMetadata(n,s.metadata);return this.sendMessage(e,{message:s.message,fileInfos:r,separateFiles:s.separateFiles,replyToMessageId:s.replyToMessageId})}sendFileMessageOptimistic(e,t,s={}){const i=this._normalizeFileArray(t),n=this._generateMessageId(),r=this._predictMessageIds(n,this._predictGroupCount(i,!1!==s.separateFiles),this._hasTextMessage(s.message)),o=(async()=>{const t=await this._uploadFiles(e,i,s),o=this._applyFileMetadata(t,s.metadata),a=await this._sendMessageWithId(e,n,{message:s.message,fileInfos:o,separateFiles:s.separateFiles,replyToMessageId:s.replyToMessageId});return this._attachOptimisticMetadata(r,a)})();return{baseMessageId:n,messageIds:r,promise:o}}_normalizeFileArray(e){const t=Array.isArray(e)?e:[e];if(0===t.length)throw new Error("At least one file is required");if(t.length>20)throw new Error("A maximum of 20 files can be sent in one message");return t}async _uploadFiles(e,t,s={}){return Promise.all(t.map((t,i)=>this.uploadFile(e,t,{signal:s.signal,onProgress:s.onUploadProgress?e=>s.onUploadProgress({...e,fileIndex:i}):void 0})))}_applyFileMetadata(e,t){return null==t?e:e.map((e,s)=>{const i=Array.isArray(t)?t[s]:t;return null==i?e:{...e,metadata:i}})}async sendReply(e,t,s){return this.sendMessage(e,{message:t,replyToMessageId:s})}sendReplyOptimistic(e,t,s){return this.sendMessageOptimistic(e,{message:t,replyToMessageId:s})}async deleteMessage(e,t,s="ALL"){return this.apiClient.post(`/api/v1/chat-messages/${e}/messages/${t}/delete`,{deleteType:s})}async editMessage(e,t,s){return this.apiClient.put(`/api/v1/chat-messages/${e}/messages/${t}`,{message:s})}_hasTextMessage(e){return"string"==typeof e&&e.trim().length>0}_classifyFileType(e){const t=(e||"").toLowerCase();return t.startsWith("image/")?"IMAGE":t.startsWith("video/")?"VIDEO":t.startsWith("audio/")?"AUDIO":t.includes("pdf")||t.includes("document")?"DOCUMENT":"FILE"}_predictGroupCount(e,t){if(!e||0===e.length)return 0;if(t)return e.length;const s=new Set;for(const t of e){const e=t&&(t.type||t.fileType)||"";s.add(this._classifyFileType(e))}return s.size}_predictMessageIds(e,t,s){const i=(s?1:0)+t;if(0===i)return[];if(1===i)return[e];const n=[];s&&n.push(e);for(let s=0;s<t;s++)n.push(`${e}#${s}`);return n}_predictMessageIdsFromData(e,t){const s=t&&t.fileInfos||[],i=!t||!1!==t.separateFiles,n=this._predictGroupCount(s,i),r=this._hasTextMessage(t&&t.message);return this._predictMessageIds(e,n,r)}_attachOptimisticMetadata(e,t){const s=t&&Array.isArray(t.messages)?t.messages.map(e=>e&&e.messageId||null):[],i=s.length===e.length&&e.every((e,t)=>e===s[t]);return i||this.logger.warn("Optimistic messageId prediction mismatch — server may have changed grouping rules. Use result.optimistic.actualMessageIds to reconcile.",{predicted:e,actual:s}),{...t,optimistic:{predictedMessageIds:e,actualMessageIds:s,predictionMatched:i}}}_generateMessageId(){return"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}_unwrapSuccessResponse(e){return e&&"object"==typeof e&&Object.prototype.hasOwnProperty.call(e,"data")?e.data:e}_normalizeMessageTimestamps(e){return e&&"object"==typeof e?(e.sentAt=this._toEpochMillis(e.sentAt),e.editedAt=this._toEpochMillis(e.editedAt),e.replyTo&&"object"==typeof e.replyTo&&(e.replyTo.sentAt=this._toEpochMillis(e.replyTo.sentAt)),e):e}_toEpochMillis(e){if("string"!=typeof e)return e;const t=Date.parse(e);return Number.isNaN(t)?e:t}async subscribeRoom(e){if(this.subscribedRooms.has(e))return void this.logger.warn(`Already subscribed to room: ${e}`);const t=a.getChatDestination(e);await this.connectionManager.subscribe(t,t=>{this._handleChatMessage(e,t)});const s=a.getChatReadDestination(e);await this.connectionManager.subscribe(s,t=>{this._handleReadEvent(e,t)});const i=a.getChatTypingDestination(e);await this.connectionManager.subscribe(i,t=>{this._handleTypingEvent(e,t)});const n=a.getChatAssistantStreamDestination(e);await this.connectionManager.subscribe(n,t=>{this._handleAssistantStreamEvent(e,t)});const r=t=>{t.roomId===e&&this.emit("memberJoined",{roomId:e,members:t.members||[],participantCount:t.activeParticipantCount,timestamp:t.timestamp})},o=t=>{t.roomId===e&&this.emit("memberLeft",{roomId:e,members:t.members||[],participantCount:t.activeParticipantCount,timestamp:t.timestamp})};this.on("roomListJoined",r),this.on("roomListLeft",o),this.subscribedRooms.set(e,{chatDestination:t,readDestination:s,typingDestination:i,assistantStreamDestination:n,memberJoinedHandler:r,memberLeftHandler:o,subscribedAt:new Date}),this.logger.info(`Subscribed to room: ${e}`),this.emit("roomSubscribed",{roomId:e})}unsubscribeRoom(e){const t=this.subscribedRooms.get(e);t?(this.connectionManager.unsubscribe(t.chatDestination),this.connectionManager.unsubscribe(t.readDestination),t.typingDestination&&this.connectionManager.unsubscribe(t.typingDestination),t.assistantStreamDestination&&this.connectionManager.unsubscribe(t.assistantStreamDestination),t.memberJoinedHandler&&this.off("roomListJoined",t.memberJoinedHandler),t.memberLeftHandler&&this.off("roomListLeft",t.memberLeftHandler),this._clearTypingTimer(e),this._clearAssistantTypingTimer(e),this._clearAssistantProgress(e,!1),this._activeRoomId===e&&(this._activeRoomId=null),this.subscribedRooms.delete(e),this._seenChatMessageIdsByRoom.delete(e),this._seenRoomListMessageIdsByRoom.delete(e),this.logger.info(`Unsubscribed from room: ${e}`),this.emit("roomUnsubscribed",{roomId:e})):this.logger.warn(`Not subscribed to room: ${e}`)}unsubscribeAllRooms(){this.subscribedRooms.forEach((e,t)=>{this.unsubscribeRoom(t)})}setActiveRoom(e){this._activeRoomId=e,this.logger.debug(`Active room set: ${e}`)}clearActiveRoom(){this.logger.debug(`Active room cleared (was: ${this._activeRoomId})`),this._activeRoomId=null}getActiveRoom(){return this._activeRoomId}async subscribeRoomList(){if(this.roomListSubscribed)return void this.logger.warn("Already subscribed to room list");const e=a.ROOM_LIST_USER_DESTINATION;await this.connectionManager.subscribe(e,e=>{this._handleRoomListEvent(e)}),this.roomListSubscribed=!0,this.logger.info("Subscribed to room list"),this.emit("roomListSubscribed",{})}unsubscribeRoomList(){this.roomListSubscribed?(this.connectionManager.unsubscribe(a.ROOM_LIST_USER_DESTINATION),this.roomListSubscribed=!1,this.logger.info("Unsubscribed from room list"),this.emit("roomListUnsubscribed",{})):this.logger.warn("Not subscribed to room list")}isRoomListSubscribed(){return this.roomListSubscribed}markAsRead(e,t){return this.connectionManager.isConnected()?this.connectionManager.send(a.CHAT_READ,{roomId:e,messageId:t}):(this.logger.warn("Cannot mark as read: not connected"),!1)}_handleChatMessage(e,t){if(this.logger.debug(`Message received in room ${e} (${t.eventType}):`,t),"MESSAGE_CREATED"===t.eventType&&this._shouldDedupMessage(this._seenChatMessageIdsByRoom,e,t.messageId))this.logger.debug(`Duplicate MESSAGE_CREATED suppressed: room=${e}, messageId=${t.messageId}`);else switch("MESSAGE_UPDATED"===t.eventType&&(void 0===t.translations&&(t.translations=null),void 0===t.sourceLang&&(t.sourceLang=null),void 0===t.translationsOf&&(t.translationsOf=null)),this.emit("message",{roomId:e,message:t}),t.eventType){case"MESSAGE_CREATED":"ASSISTANT"===t.senderType&&(this._clearAssistantTypingTimer(e),this.emit("typing",{roomId:e,userId:this._assistantTypingUserId,userName:this._assistantTypingUserName,typing:!1,senderType:"ASSISTANT"}),this._clearAssistantProgress(e,!0,"message")),t.userId!==this.userId&&(this.emit("newMessage",{roomId:e,message:t}),this._activeRoomId===e&&t.messageId&&this.markAsRead(e,t.messageId));break;case"MESSAGE_UPDATED":this.emit("messageUpdated",{roomId:e,message:t});break;case"MESSAGE_DELETED":this.emit("messageDeleted",{roomId:e,message:t});break;case"REACTION_CHANGED":this.emit("reactionChanged",{roomId:e,message:t});break;case"LINK_PREVIEW_ATTACHED":this.emit("linkPreviewAttached",{roomId:e,message:t});break;case"MESSAGE_TRANSLATED":this.emit("messageTranslated",{roomId:e,message:t});break;default:this.logger.warn(`Unknown eventType "${t.eventType}" — falling back to legacy behavior`),t.userId!==this.userId&&(this.emit("newMessage",{roomId:e,message:t}),this._activeRoomId===e&&t.messageId&&this.markAsRead(e,t.messageId))}}_handleRoomListEvent(e){if(this.logger.debug("Room list event:",e),e.eventType===o.MESSAGE_RECEIVED&&e.messageId&&this._shouldDedupMessage(this._seenRoomListMessageIdsByRoom,e.roomId,e.messageId))this.logger.debug(`Duplicate roomList MESSAGE_RECEIVED suppressed: room=${e.roomId}, messageId=${e.messageId}`);else switch(this.emit("roomListUpdate",e),e.eventType){case o.MESSAGE_RECEIVED:this.emit("roomListMessage",e);break;case o.MESSAGE_DELETED:this.emit("roomListMessageDeleted",e);break;case o.MESSAGE_UPDATED:this.emit("roomListMessageUpdated",e);break;case o.ROOM_CREATED:this.emit("roomListCreated",e);break;case o.ROOM_JOINED:this.emit("roomListJoined",e);break;case o.ROOM_LEFT:this.emit("roomListLeft",e),e.actorId===this.userId&&this.emit("roomListSelfLeft",e);break;case o.ROOM_KICKED:this.emit("roomListKicked",e),this._isSelfInMembers(e)&&this.emit("roomListSelfKicked",e);break;case o.ROOM_BANNED:this.emit("roomListBanned",e),this._isSelfInMembers(e)&&this.emit("roomListSelfBanned",e);break;case o.ROOM_UPDATED:this.emit("roomListRoomUpdated",e);break;case o.MESSAGE_RETENTION_CLEANUP:this.emit("retentionCleanup",{roomId:e.roomId,cutoffTime:e.cutoffTime});break;default:this.logger.warn("Unknown room list event type:",e.eventType)}}_handleReadEvent(e,t){this.logger.debug(`Read event in room ${e}:`,t);const s=t.roomId||e;t.events&&Array.isArray(t.events)?t.events.forEach(e=>{this.emit("messageRead",{roomId:s,messageId:e.messageId,userId:t.userId,remainingUnreadCount:e.remainingUnreadCount})}):this.emit("messageRead",{roomId:s,messageId:t.messageId,userId:t.userId,remainingUnreadCount:t.remainingUnreadCount})}startTyping(e){if(!this.connectionManager.isConnected())return;const t=this._typingTimers.get(e);t?clearTimeout(t):this.connectionManager.send(a.CHAT_TYPING,{roomId:e,typing:!0});const s=setTimeout(()=>{this.stopTyping(e)},3e3);this._typingTimers.set(e,s)}stopTyping(e){this._clearTypingTimer(e),this.connectionManager.isConnected()&&this.connectionManager.send(a.CHAT_TYPING,{roomId:e,typing:!1})}_isSelfInMembers(e){return Array.isArray(e.members)&&e.members.some(e=>e&&e.userId===this.userId)}_handleTypingEvent(e,t){"ASSISTANT"!==t.senderType&&t.userId===this.userId||("ASSISTANT"===t.senderType&&!0===t.typing&&this._startAssistantTypingTimer(e),this.emit("typing",{roomId:e,userId:t.userId,userName:t.userName,typing:t.typing,senderType:t.senderType||"USER"}))}_startAssistantTypingTimer(e){this._clearAssistantTypingTimer(e);const t=setTimeout(()=>{this._assistantTypingTimers.delete(e),this.emit("typing",{roomId:e,userId:this._assistantTypingUserId,userName:this._assistantTypingUserName,typing:!1,senderType:"ASSISTANT"}),this.logger.debug(`Assistant typing auto-cleared (timeout): room=${e}`)},this._assistantTypingTimeoutMs);this._assistantTypingTimers.set(e,t)}_clearAssistantTypingTimer(e){const t=this._assistantTypingTimers.get(e);t&&(clearTimeout(t),this._assistantTypingTimers.delete(e))}_clearTypingTimer(e){const t=this._typingTimers.get(e);t&&(clearTimeout(t),this._typingTimers.delete(e))}_handleAssistantStreamEvent(e,t){if(t&&t.type){if("PHASE"===t.type){const s=t.phase||null,i=s&&this._assistantPhaseLabels[s]||null,n=this._assistantProgress.get(e),r=n&&n.streamId===t.streamId&&n.text||"";return this._startAssistantProgressTimer(e,t,{phase:s,text:r}),void this.emit("assistantProgress",{roomId:e,streamId:t.streamId||null,personaId:t.personaId||null,phase:s,label:i,active:!0,text:r||null})}if("DELTA"===t.type){const s=this._assistantProgress.get(e);if(s?.streamId&&t.streamId&&s.streamId!==t.streamId)return void this.logger.debug(`Stale assistant DELTA ignored: room=${e}, delta=${t.streamId}, active=${s.streamId}`);const i=s&&s.phase||"WRITING",n=(s&&s.text||"")+(t.delta||"");return this._startAssistantProgressTimer(e,t,{phase:i,text:n}),void this.emit("assistantProgress",{roomId:e,streamId:t.streamId||null,personaId:t.personaId||null,phase:i,label:this._assistantPhaseLabels[i]||null,active:!0,text:n,delta:t.delta||null,seq:"number"==typeof t.seq?t.seq:null})}if("DONE"===t.type){const s=this._assistantProgress.get(e);if(s?.streamId&&t.streamId&&s.streamId!==t.streamId)return void this.logger.debug(`Stale assistant DONE ignored: room=${e}, done=${t.streamId}, active=${s.streamId}`);s&&s.timer&&clearTimeout(s.timer),this._assistantProgress.delete(e),this.emit("assistantProgress",{roomId:e,streamId:t.streamId||null,personaId:t.personaId||null,phase:null,label:null,active:!1,status:t.status||null,messageId:t.messageId||null})}}}_startAssistantProgressTimer(e,t,s){const i=this._assistantProgress.get(e);i&&i.timer&&clearTimeout(i.timer);let n=this._assistantProgressFallbackTtlMs;"number"==typeof t.expiresAt&&(n=Math.min(12e4,Math.max(5e3,t.expiresAt-Date.now())));const r=setTimeout(()=>{this._clearAssistantProgress(e,!0,"timeout"),this.logger.debug(`Assistant progress auto-cleared (timeout): room=${e}`)},n);this._assistantProgress.set(e,{streamId:t.streamId||null,personaId:t.personaId||null,phase:s.phase,text:s.text||"",timer:r})}_clearAssistantProgress(e,t,s){const i=this._assistantProgress.get(e);i&&(i.timer&&clearTimeout(i.timer),this._assistantProgress.delete(e),t&&this.emit("assistantProgress",{roomId:e,streamId:i.streamId||null,personaId:i.personaId||null,phase:null,label:null,active:!1,reason:s||null}))}getSubscribedRooms(){return Array.from(this.subscribedRooms.keys())}isSubscribed(e){return this.subscribedRooms.has(e)}setLogLevel(e){this.logger.setLevel(e)}destroy(){this.unsubscribeAllRooms(),this.roomListSubscribed&&this.unsubscribeRoomList(),this._typingTimers.forEach(e=>clearTimeout(e)),this._typingTimers.clear(),this._assistantTypingTimers.forEach(e=>clearTimeout(e)),this._assistantTypingTimers.clear(),this._assistantProgress.forEach(e=>e.timer&&clearTimeout(e.timer)),this._assistantProgress.clear(),this._seenChatMessageIdsByRoom.clear(),this._seenRoomListMessageIdsByRoom.clear(),this.removeAllListeners(),this.logger.info("ChatClient destroyed")}}class Ds extends t{constructor(e={}){super(),this.localStream=null,this.screenStream=null,this.videoEnabled=!0,this.audioEnabled=!0,this.logger=new p(e.logLevel||u.WARN,"MediaStreamManager"),this._deviceChangeHandler=null}async getUserMedia(e={video:!0,audio:!0}){try{return this.localStream=await navigator.mediaDevices.getUserMedia(e),this.videoEnabled=!1!==e.video,this.audioEnabled=!1!==e.audio,this.emit("streamStarted",{stream:this.localStream}),this.logger.info("User media stream started"),this.localStream}catch(e){throw this.logger.error("Failed to get user media:",e),this.emit("error",{type:i.MEDIA_ACCESS_DENIED,message:this._getMediaErrorMessage(e),error:e}),e}}_getMediaErrorMessage(e){switch(e.name){case"NotAllowedError":return"Camera/Microphone permission denied";case"NotFoundError":return"Camera/Microphone not found";case"NotReadableError":return"Camera/Microphone is already in use";case"OverconstrainedError":return"Camera/Microphone constraints cannot be satisfied";case"AbortError":return"Media access aborted";default:return e.message||"Unknown media error"}}async getDisplayMedia(e={video:!0,audio:!1}){try{return this.screenStream=await navigator.mediaDevices.getDisplayMedia(e),this.screenStream.getVideoTracks()[0].onended=()=>{this.emit("screenShareEnded",{}),this.screenStream=null},this.emit("screenShareStarted",{stream:this.screenStream}),this.logger.info("Screen share stream started"),this.screenStream}catch(e){throw this.logger.error("Failed to get display media:",e),this.emit("error",{type:i.SCREEN_SHARE_DENIED,message:"NotAllowedError"===e.name?"Screen share permission denied":e.message,error:e}),e}}toggleVideo(){if(!this.localStream)return this.logger.warn("No local stream available"),this.videoEnabled;const e=this.localStream.getVideoTracks();return 0===e.length?(this.logger.warn("No video track available"),this.videoEnabled):(this.videoEnabled=!this.videoEnabled,e.forEach(e=>{e.enabled=this.videoEnabled}),this.emit("videoToggled",{enabled:this.videoEnabled}),this.logger.debug(`Video toggled: ${this.videoEnabled}`),this.videoEnabled)}toggleAudio(){if(!this.localStream)return this.logger.warn("No local stream available"),this.audioEnabled;const e=this.localStream.getAudioTracks();return 0===e.length?(this.logger.warn("No audio track available"),this.audioEnabled):(this.audioEnabled=!this.audioEnabled,e.forEach(e=>{e.enabled=this.audioEnabled}),this.emit("audioToggled",{enabled:this.audioEnabled}),this.logger.debug(`Audio toggled: ${this.audioEnabled}`),this.audioEnabled)}setVideoEnabled(e){if(!this.localStream)return void this.logger.warn("No local stream available");this.localStream.getVideoTracks().forEach(t=>{t.enabled=e}),this.videoEnabled=e,this.emit("videoToggled",{enabled:e})}setAudioEnabled(e){if(!this.localStream)return void this.logger.warn("No local stream available");this.localStream.getAudioTracks().forEach(t=>{t.enabled=e}),this.audioEnabled=e,this.emit("audioToggled",{enabled:e})}getLocalStream(){return this.localStream}getScreenStream(){return this.screenStream}isVideoEnabled(){return this.videoEnabled}isAudioEnabled(){return this.audioEnabled}stopAll(){this.localStream&&(this.localStream.getTracks().forEach(e=>e.stop()),this.localStream=null,this.emit("streamStopped",{}),this.logger.info("All media tracks stopped")),this.screenStream&&(this.screenStream.getTracks().forEach(e=>e.stop()),this.screenStream=null)}replaceTrack(e,t){this.localStream?(this.localStream.removeTrack(e),this.localStream.addTrack(t),e.stop(),this.emit("trackReplaced",{oldTrack:e,newTrack:t}),this.logger.debug(`Track replaced: ${e.kind}`)):this.logger.warn("No local stream available")}getTrack(e){if(!this.localStream)return null;const t="video"===e?this.localStream.getVideoTracks():this.localStream.getAudioTracks();return t.length>0?t[0]:null}async getDevices(){try{const e=await navigator.mediaDevices.enumerateDevices();return{videoInputs:e.filter(e=>"videoinput"===e.kind),audioInputs:e.filter(e=>"audioinput"===e.kind),audioOutputs:e.filter(e=>"audiooutput"===e.kind)}}catch(e){throw this.logger.error("Failed to enumerate devices:",e),this.emit("error",{type:i.ENUMERATE_DEVICES_FAILED,message:e.message,error:e}),e}}async switchDevice(e,t){if(!this.localStream)throw new Error("No local stream available");try{const s="video"===t?{video:{deviceId:{exact:e}},audio:!1}:{video:!1,audio:{deviceId:{exact:e}}},i=(await navigator.mediaDevices.getUserMedia(s)).getTracks()[0],n="video"===t?this.localStream.getVideoTracks()[0]:this.localStream.getAudioTracks()[0];return n&&(this.replaceTrack(n,i),this.emit("deviceSwitched",{kind:t,deviceId:e,newTrack:i}),this.logger.info(`${t} device switched to ${e}`)),i}catch(e){throw this.logger.error(`Failed to switch ${t} device:`,e),this.emit("error",{type:i.DEVICE_SWITCH_FAILED,message:e.message,error:e}),e}}startDeviceChangeDetection(){this._deviceChangeHandler||(this._deviceChangeHandler=async()=>{try{const e=await this.getDevices();this.emit("deviceChange",e),this.logger.debug("Device change detected")}catch(e){this.logger.warn("Failed to get devices on change:",e)}},navigator.mediaDevices.addEventListener("devicechange",this._deviceChangeHandler),this.logger.debug("Device change detection started"))}stopDeviceChangeDetection(){this._deviceChangeHandler&&(navigator.mediaDevices.removeEventListener("devicechange",this._deviceChangeHandler),this._deviceChangeHandler=null,this.logger.debug("Device change detection stopped"))}getStreamInfo(){return this.localStream?{hasStream:!0,videoEnabled:this.videoEnabled,audioEnabled:this.audioEnabled,tracks:this.localStream.getTracks().map(e=>({kind:e.kind,id:e.id,label:e.label,enabled:e.enabled,readyState:e.readyState,muted:e.muted}))}:{hasStream:!1,videoEnabled:this.videoEnabled,audioEnabled:this.audioEnabled,tracks:[]}}async applyVideoConstraints(e){if(!this.localStream)throw new Error("No local stream available");const t=this.localStream.getVideoTracks()[0];if(!t)throw new Error("No video track available");try{await t.applyConstraints(e),this.emit("videoConstraintsApplied",{constraints:e}),this.logger.info("Video constraints applied:",e)}catch(e){throw this.logger.error("Failed to apply video constraints:",e),e}}getVideoSettings(){if(!this.localStream)return null;const e=this.localStream.getVideoTracks()[0];return e?e.getSettings():null}getAudioSettings(){if(!this.localStream)return null;const e=this.localStream.getAudioTracks()[0];return e?e.getSettings():null}setLogLevel(e){this.logger.setLevel(e)}destroy(){this.stopAll(),this.stopDeviceChangeDetection(),this.removeAllListeners(),this.logger.info("MediaStreamManager destroyed")}}class Ps extends t{constructor(e={}){super(),this.iceServers=e.iceServers||h.iceServers,this.logger=new p(e.logLevel||u.WARN,"PeerConnectionManager"),this.peers=new Map,this.localStream=null}setLocalStream(e){this.localStream=e,this.peers.forEach(e=>{this._addTracksToConnection(e.connection)})}setIceServers(e){this.iceServers=e}createPeerConnection(e,t=!1,s={}){if(this.peers.has(e))return this.logger.warn(`Peer connection already exists: ${e}`),this.peers.get(e).connection;const i={iceServers:this.iceServers,iceCandidatePoolSize:10},n=new RTCPeerConnection(i),r={connection:n,polite:t,makingOffer:!1,ignoreOffer:!1,isSettingRemoteAnswerPending:!1,skipAutoNegotiation:s.skipAutoNegotiation||!1};return this.peers.set(e,r),this._setupConnectionHandlers(e,n,r),this.localStream&&this._addTracksToConnection(n),this.logger.info(`Peer connection created: ${e} (polite: ${t}, skipAutoNegotiation: ${r.skipAutoNegotiation})`),n}_setupConnectionHandlers(e,t,s){t.onicecandidate=t=>{t.candidate&&this.emit("iceCandidate",{peerId:e,candidate:t.candidate})},t.oniceconnectionstatechange=()=>{this.logger.debug(`ICE connection state (${e}): ${t.iceConnectionState}`),this.emit("iceConnectionStateChange",{peerId:e,state:t.iceConnectionState}),"failed"===t.iceConnectionState&&this.emit("error",{type:i.ICE_CONNECTION_FAILED,peerId:e,message:"ICE connection failed"})},t.onconnectionstatechange=()=>{this.logger.debug(`Connection state (${e}): ${t.connectionState}`),this.emit("connectionStateChange",{peerId:e,state:t.connectionState}),"connected"===t.connectionState?this.emit("peerConnected",{peerId:e}):"disconnected"!==t.connectionState&&"failed"!==t.connectionState||this.emit("peerDisconnected",{peerId:e})},t.onnegotiationneeded=async()=>{if(s.skipAutoNegotiation)this.logger.debug(`Skipping auto negotiation for ${e} (manual offer will be sent)`);else try{s.makingOffer=!0,await t.setLocalDescription(),this.emit("negotiationNeeded",{peerId:e,description:t.localDescription})}catch(t){this.logger.error(`Negotiation error (${e}):`,t)}finally{s.makingOffer=!1}},t.ontrack=t=>{this.logger.info(`Remote track received from ${e}:`,t.track.kind),this.emit("remoteTrack",{peerId:e,track:t.track,streams:t.streams})},t.ondatachannel=t=>{this.logger.info(`Data channel received from ${e}`),this.emit("dataChannel",{peerId:e,channel:t.channel})}}_addTracksToConnection(e){if(!this.localStream)return;const t=e.getSenders();this.localStream.getTracks().forEach(s=>{t.find(e=>e.track&&e.track.kind===s.kind)||e.addTrack(s,this.localStream)})}async createOffer(e){const t=this.peers.get(e);if(!t)throw new Error(`Peer not found: ${e}`);try{const s=await t.connection.createOffer();return await t.connection.setLocalDescription(s),this.logger.debug(`Offer created for ${e}`),t.connection.localDescription}catch(t){throw this.logger.error(`Failed to create offer for ${e}:`,t),t}}async createAnswer(e){const t=this.peers.get(e);if(!t)throw new Error(`Peer not found: ${e}`);try{const s=await t.connection.createAnswer();return await t.connection.setLocalDescription(s),this.logger.debug(`Answer created for ${e}`),t.connection.localDescription}catch(t){throw this.logger.error(`Failed to create answer for ${e}:`,t),t}}async handleRemoteDescription(e,t){const s=this.peers.get(e);if(!s)throw new Error(`Peer not found: ${e}`);const{connection:i,polite:n,makingOffer:r}=s,o="offer"===t.type&&(r||"stable"!==i.signalingState);if(s.ignoreOffer=!n&&o,s.ignoreOffer)this.logger.debug(`Ignoring offer collision from ${e} (I am impolite)`);else try{if(o&&n&&(this.logger.debug(`Offer collision detected, rolling back local offer for ${e} (I am polite)`),await i.setLocalDescription({type:"rollback"})),s.isSettingRemoteAnswerPending="answer"===t.type,await i.setRemoteDescription(t),s.isSettingRemoteAnswerPending=!1,this.logger.debug(`Remote ${t.type} set for ${e}`),"offer"===t.type){const t=await this.createAnswer(e);this.emit("answerCreated",{peerId:e,answer:t})}}catch(t){throw this.logger.error(`Failed to set remote description for ${e}:`,t),t}}async addIceCandidate(e,t){const s=this.peers.get(e);if(!s)return this.logger.warn(`Peer not found for ICE candidate: ${e}`),!1;if(!s.connection.remoteDescription)return this.logger.debug(`Remote description not set yet for ${e}, ICE candidate queued`),!1;try{return await s.connection.addIceCandidate(t),this.logger.debug(`ICE candidate added for ${e}`),!0}catch(t){return s.ignoreOffer||this.logger.error(`Failed to add ICE candidate for ${e}:`,t),!1}}getPeerConnection(e){const t=this.peers.get(e);return t?t.connection:null}getPeerIds(){return Array.from(this.peers.keys())}closePeerConnection(e){const t=this.peers.get(e);t&&(t.connection.close(),this.peers.delete(e),this.emit("peerClosed",{peerId:e}),this.logger.info(`Peer connection closed: ${e}`))}closeAllPeerConnections(){this.peers.forEach((e,t)=>{e.connection.close(),this.logger.debug(`Peer connection closed: ${t}`)}),this.peers.clear(),this.emit("allPeersClosed",{})}async replaceTrack(e,t){const s=[];this.peers.forEach((i,n)=>{const r=i.connection.getSenders().find(t=>t.track&&t.track.kind===e.kind);r&&s.push(r.replaceTrack(t).then(()=>this.logger.debug(`Track replaced for ${n}`)).catch(e=>this.logger.error(`Failed to replace track for ${n}:`,e)))}),await Promise.all(s)}async getStats(e){const t=this.peers.get(e);return t?t.connection.getStats():null}getConnectionSummary(){const e={};return this.peers.forEach((t,s)=>{e[s]={connectionState:t.connection.connectionState,iceConnectionState:t.connection.iceConnectionState,signalingState:t.connection.signalingState,polite:t.polite}}),e}setLogLevel(e){this.logger.setLevel(e)}destroy(){this.closeAllPeerConnections(),this.localStream=null,this.removeAllListeners(),this.logger.info("PeerConnectionManager destroyed")}}class xs extends t{constructor(e){super(),this.connectionManager=e.connectionManager,this.apiClient=e.apiClient,this.userId=e.userId,this.logLevel=e.logLevel||u.WARN,this.logger=new p(this.logLevel,"WebRTCClient"),this.mediaManager=new Ds({logLevel:this.logLevel}),this.peerManager=new Ps({iceServers:e.iceServers||h.iceServers,logLevel:this.logLevel}),this.currentRoom=null,this.isGroupCall=!1,this.participants=new Map,this._iceServersFetched=!1,this._waitingForCallAccept=!1,this._pendingCallTarget=null,this._pendingIceCandidates=new Map,this._setupEventHandlers()}async initializeIceServers(){if(!this._iceServersFetched)try{const e=await this.getTurnCredentials();e&&e.iceServers&&(this.peerManager.setIceServers(e.iceServers),this._iceServersFetched=!0,this.logger.info("ICE servers fetched successfully"))}catch(e){this.logger.warn("Failed to fetch TURN credentials, using fallback ICE servers:",e.message),this._setFallbackIceServers()}}_setFallbackIceServers(){this.peerManager.setIceServers([{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}])}_setupEventHandlers(){this.mediaManager.on("streamStarted",e=>this.emit("localStreamStarted",e)),this.mediaManager.on("streamStopped",e=>this.emit("localStreamStopped",e)),this.mediaManager.on("videoToggled",()=>this._sendMediaState()),this.mediaManager.on("audioToggled",()=>this._sendMediaState()),this.mediaManager.on("screenShareStarted",e=>this.emit("screenShareStarted",e)),this.mediaManager.on("screenShareEnded",e=>this.emit("screenShareEnded",e)),this.mediaManager.on("error",e=>this.emit("error",e)),this.peerManager.on("remoteTrack",e=>this.emit("remoteTrack",e)),this.peerManager.on("peerConnected",e=>this.emit("peerConnected",e)),this.peerManager.on("peerDisconnected",e=>this.emit("peerDisconnected",e)),this.peerManager.on("peerClosed",e=>this.emit("peerClosed",e)),this.peerManager.on("error",e=>this.emit("error",e)),this.peerManager.on("iceCandidate",({peerId:e,candidate:t})=>{this._sendSignal({type:n.ICE_CANDIDATE,receiverId:e,data:{candidate:t}})}),this.peerManager.on("negotiationNeeded",({peerId:e,description:t})=>{this._sendSignal({type:n.CALL_OFFER,receiverId:e,data:{sdp:t}})}),this.peerManager.on("answerCreated",({peerId:e,answer:t})=>{this._sendSignal({type:n.CALL_ANSWER,receiverId:e,data:{sdp:t}})})}async getTurnCredentials(){return(await this.apiClient.get("/api/v1/webrtc/turn-credentials")).data}async createCallRoom(e){return this.apiClient.post("/api/v1/webrtc/rooms",e)}async getCallRoom(e){return this.apiClient.get(`/api/v1/webrtc/rooms/${e}`)}async joinCallRoomApi(e){return this.apiClient.post(`/api/v1/webrtc/rooms/${e}/join`)}async leaveCallRoomApi(e){return this.apiClient.delete(`/api/v1/webrtc/rooms/${e}/leave`)}async enableIncomingCalls(){this._incomingCallsEnabled?this.logger.debug("Incoming calls already enabled"):(await this._subscribeToDirectSignaling(),this._incomingCallsEnabled=!0,this.logger.info("Incoming calls enabled - now listening for call invitations"))}disableIncomingCalls(){if(!this._incomingCallsEnabled)return;const e=a.getWebRTCUserDestination();this.connectionManager.unsubscribe(e),this._incomingCallsEnabled=!1,this.logger.info("Incoming calls disabled")}isIncomingCallsEnabled(){return this._incomingCallsEnabled||!1}async startCall(e){const{roomId:t,isGroup:s=!1,mediaConstraints:r={video:!0,audio:!0}}=e;try{await this.initializeIceServers();const e=await this.mediaManager.getUserMedia(r);return this.peerManager.setLocalStream(e),this.currentRoom=t,this.isGroupCall=s,await this._subscribeToSignaling(t,s),this._sendSignal({type:n.JOIN_ROOM,roomId:t}),this.logger.info(`Call started in room: ${t}`),this.emit("callStarted",{roomId:t,isGroup:s,localStream:e}),e}catch(e){throw this.logger.error("Failed to start call:",e),this.emit("error",{type:i.PEER_CONNECTION_FAILED,message:e.message,error:e}),e}}async callUser(e,t={video:!0,audio:!0}){try{await this.initializeIceServers();const s=await this.mediaManager.getUserMedia(t);this.peerManager.setLocalStream(s),await this._subscribeToDirectSignaling(),this._waitingForCallAccept=!0,this._pendingCallTarget=e,this._sendSignal({type:n.CALL_REQUEST,receiverId:e}),this.currentRoom=null,this.isGroupCall=!1,this.emit("callRequested",{targetUserId:e,localStream:s})}catch(e){throw this.logger.error("Failed to call user:",e),this._waitingForCallAccept=!1,this._pendingCallTarget=null,e}}async acceptCall(e,t={video:!0,audio:!0}){try{await this.initializeIceServers();const s=await this.mediaManager.getUserMedia(t);this.peerManager.setLocalStream(s),this.peerManager.createPeerConnection(e,!0,{skipAutoNegotiation:!0}),this._sendSignal({type:n.CALL_ACCEPT,receiverId:e}),this.emit("callAccepted",{callerId:e})}catch(e){throw this.logger.error("Failed to accept call:",e),e}}rejectCall(e){this._sendSignal({type:n.CALL_REJECT,receiverId:e}),this.emit("callRejected",{callerId:e})}cancelCall(){this._waitingForCallAccept&&this._pendingCallTarget&&(this._sendSignal({type:n.CALL_CANCEL,receiverId:this._pendingCallTarget}),this.emit("callCancelled",{targetUserId:this._pendingCallTarget}),this._waitingForCallAccept=!1,this._pendingCallTarget=null,this.mediaManager.stopAll())}endCall(){this._waitingForCallAccept&&this._pendingCallTarget&&this._sendSignal({type:n.CALL_CANCEL,receiverId:this._pendingCallTarget}),this._waitingForCallAccept=!1,this._pendingCallTarget=null,this.currentRoom&&(this._sendSignal({type:n.LEAVE_ROOM,roomId:this.currentRoom}),this._unsubscribeFromSignaling()),this.peerManager.getPeerIds().forEach(e=>{this._sendSignal({type:n.CALL_END,receiverId:e})}),this.peerManager.closeAllPeerConnections(),this.mediaManager.stopAll(),this.participants.clear(),this._pendingIceCandidates.clear();const e=this.currentRoom;this.currentRoom=null,this.isGroupCall=!1,this.emit("callEnded",{roomId:e}),this.logger.info("Call ended")}toggleVideo(){return this.mediaManager.toggleVideo()}toggleAudio(){return this.mediaManager.toggleAudio()}async startScreenShare(){const e=await this.mediaManager.getDisplayMedia(),t=e.getVideoTracks()[0],s=this.mediaManager.getTrack("video");return s&&t&&await this.peerManager.replaceTrack(s,t),t.onended=async()=>{const e=this.mediaManager.getTrack("video");e&&await this.peerManager.replaceTrack(t,e),this.emit("screenShareEnded",{})},e}stopScreenShare(){const e=this.mediaManager.getScreenStream();e&&e.getTracks().forEach(e=>e.stop())}getLocalStream(){return this.mediaManager.getLocalStream()}async getDevices(){return this.mediaManager.getDevices()}async switchDevice(e,t){const s=this.mediaManager.getTrack(t),i=await this.mediaManager.switchDevice(e,t);return s&&await this.peerManager.replaceTrack(s,i),i}setVideoEnabled(e){this.mediaManager.setVideoEnabled(e),this._sendMediaState()}setAudioEnabled(e){this.mediaManager.setAudioEnabled(e),this._sendMediaState()}startDeviceChangeDetection(){this.mediaManager.startDeviceChangeDetection(),this.mediaManager.on("deviceChange",e=>{this.emit("deviceChange",e)})}stopDeviceChangeDetection(){this.mediaManager.stopDeviceChangeDetection()}async applyVideoConstraints(e){return this.mediaManager.applyVideoConstraints(e)}getVideoSettings(){return this.mediaManager.getVideoSettings()}getAudioSettings(){return this.mediaManager.getAudioSettings()}async _subscribeToSignaling(e,t){if(t){const t=a.getWebRTCDestination(e);await this.connectionManager.subscribe(t,e=>{this._handleSignal(e)})}await this._subscribeToDirectSignaling()}async _subscribeToDirectSignaling(){const e=a.getWebRTCUserDestination();await this.connectionManager.subscribe(e,e=>{this._handleSignal(e)})}_unsubscribeFromSignaling(){if(this.currentRoom&&this.isGroupCall){const e=a.getWebRTCDestination(this.currentRoom);this.connectionManager.unsubscribe(e)}if(!this._incomingCallsEnabled){const e=a.getWebRTCUserDestination();this.connectionManager.unsubscribe(e)}}_sendSignal(e){const t={type:e.type,roomId:e.roomId||this.currentRoom,receiverId:e.receiverId,data:e.data};this.connectionManager.send(a.WEBRTC_SIGNAL,t),this.logger.debug("Signal sent:",t)}_sendMediaState(){if(!this.currentRoom&&0===this.peerManager.getPeerIds().length)return;const e={videoEnabled:this.mediaManager.isVideoEnabled(),audioEnabled:this.mediaManager.isAudioEnabled()};this._sendSignal({type:n.VIDEO_STATE_CHANGED,data:e}),this.emit("mediaStateChanged",e)}async _handleSignal(e){const{type:t,senderId:s,data:i}=e;if(s!==this.userId)switch(this.logger.debug(`Signal received: ${t} from ${s}`),t){case n.JOIN_ROOM:case n.PEER_JOINED:await this._handleUserJoined(s);break;case n.LEAVE_ROOM:case n.PEER_LEFT:this._handleUserLeft(s);break;case n.CALL_OFFER:await this._handleOffer(s,i.sdp);break;case n.CALL_ANSWER:await this._handleAnswer(s,i.sdp);break;case n.ICE_CANDIDATE:await this._handleIceCandidate(s,i.candidate);break;case n.VIDEO_STATE_CHANGED:case n.AUDIO_STATE_CHANGED:this._handleMediaState(s,i);break;case n.CALL_REQUEST:this.isInCall()||this._waitingForCallAccept?(this._sendSignal({type:n.CALL_BUSY,receiverId:s}),this.emit("incomingCallWhileBusy",{callerId:s})):this.emit("incomingCall",{callerId:s});break;case n.CALL_BUSY:this._waitingForCallAccept=!1,this._pendingCallTarget=null,this.mediaManager.stopAll(),this.emit("callBusy",{userId:s});break;case n.CALL_INVITATION:this.emit("callInvitation",{callRoomId:i?.callRoomId||e.roomId,title:i?.title,hostUserId:i?.hostUserId||s,maxParticipants:i?.maxParticipants,createdAt:i?.createdAt});break;case n.CALL_ACCEPT:await this._handleCallAccepted(s);break;case n.CALL_REJECT:this._waitingForCallAccept=!1,this._pendingCallTarget=null,this.mediaManager.stopAll(),this.emit("callRejected",{userId:s});break;case n.CALL_CANCEL:this._waitingForCallAccept=!1,this._pendingCallTarget=null,this.emit("callCancelled",{userId:s});break;case n.CALL_END:this._handleCallEnded(s);break;default:this.logger.warn(`Unknown signal type: ${t}`)}}async _handleUserJoined(e){this.participants.set(e,{joinedAt:new Date});const t=this.userId<e;this.peerManager.createPeerConnection(e,t),this.emit("userJoined",{userId:e}),this.logger.info(`User joined: ${e} (I am ${t?"polite":"impolite"})`)}_handleUserLeft(e){this.participants.delete(e),this.peerManager.closePeerConnection(e),this.emit("userLeft",{userId:e}),this.logger.info(`User left: ${e}`)}async _handleOffer(e,t){if(!this.peerManager.getPeerConnection(e)){const t=this.userId<e;this.peerManager.createPeerConnection(e,t,{skipAutoNegotiation:!0})}await this.peerManager.handleRemoteDescription(e,t),await this._processPendingIceCandidates(e)}async _handleAnswer(e,t){await this.peerManager.handleRemoteDescription(e,t),await this._processPendingIceCandidates(e)}async _handleIceCandidate(e,t){if(!this.peerManager.getPeerConnection(e))return void this._queueIceCandidate(e,t);await this.peerManager.addIceCandidate(e,new RTCIceCandidate(t))||this._queueIceCandidate(e,t)}_queueIceCandidate(e,t){this._pendingIceCandidates.has(e)||this._pendingIceCandidates.set(e,[]),this._pendingIceCandidates.get(e).push(t),this.logger.debug(`ICE candidate queued for ${e}`)}async _processPendingIceCandidates(e){const t=this._pendingIceCandidates.get(e);if(t&&0!==t.length){this.logger.debug(`Processing ${t.length} pending ICE candidates for ${e}`);for(const s of t)await this.peerManager.addIceCandidate(e,new RTCIceCandidate(s));this._pendingIceCandidates.delete(e)}}_handleMediaState(e,t){this.emit("participantMediaState",{userId:e,videoEnabled:t.videoEnabled,audioEnabled:t.audioEnabled})}async _handleCallAccepted(e){this._waitingForCallAccept=!1,this._pendingCallTarget=null,this.peerManager.createPeerConnection(e,!1,{skipAutoNegotiation:!0});const t=await this.peerManager.createOffer(e);this._sendSignal({type:n.CALL_OFFER,receiverId:e,data:{sdp:t}}),this.emit("callAccepted",{userId:e})}_handleCallEnded(e){this.peerManager.closePeerConnection(e),this.participants.delete(e),this.emit("participantLeft",{userId:e}),0===this.peerManager.getPeerIds().length&&this.endCall()}isInCall(){return null!==this.currentRoom||this.peerManager.getPeerIds().length>0}getCurrentRoom(){return this.currentRoom}getParticipants(){return Array.from(this.participants.keys())}getConnectionSummary(){return this.peerManager.getConnectionSummary()}async getStats(e){return this.peerManager.getStats(e)}getMediaState(){return{videoEnabled:this.mediaManager.isVideoEnabled(),audioEnabled:this.mediaManager.isAudioEnabled(),streamInfo:this.mediaManager.getStreamInfo()}}setLogLevel(e){this.logger.setLevel(e),this.mediaManager.setLogLevel(e),this.peerManager.setLogLevel(e)}destroy(){this.endCall(),this.mediaManager.destroy(),this.peerManager.destroy(),this.removeAllListeners(),this.logger.info("WebRTCClient destroyed")}}const Us=Object.freeze({UNSUPPORTED_BROWSER:"UNSUPPORTED_BROWSER",FIREBASE_NOT_INSTALLED:"FIREBASE_NOT_INSTALLED",SW_REGISTER_FAILED:"SW_REGISTER_FAILED",PERMISSION_DENIED:"PERMISSION_DENIED",TOKEN_FAILED:"TOKEN_FAILED",SERVER_REGISTER_FAILED:"SERVER_REGISTER_FAILED"});class Ws extends Error{constructor(e,t,s){super(t),this.name="PushError",this.code=e,void 0!==s&&(this.cause=s)}}const Fs={apiKey:"AIzaSyB8VhRg6rSvUI7K3Ua7h6sBpLvaQGmIkRc",authDomain:"chatting-c3e5d.firebaseapp.com",projectId:"chatting-c3e5d",storageBucket:"chatting-c3e5d.firebasestorage.app",messagingSenderId:"1020496565673",appId:"1:1020496565673:web:5039167257fd83f5ce20b8"},js="pendingNavigation",$s="pending-room",Hs="deviceInfo",Bs="device-id",Vs="talkflow_device_id";function Gs(){return"undefined"==typeof indexedDB?Promise.resolve(null):new Promise((e,t)=>{const s=indexedDB.open("talkflowPush",2);s.onupgradeneeded=()=>{const e=s.result;e.objectStoreNames.contains(js)||e.createObjectStore(js,{keyPath:"id"}),e.objectStoreNames.contains(Hs)||e.createObjectStore(Hs,{keyPath:"id"})},s.onsuccess=()=>e(s.result),s.onerror=()=>t(s.error||new Error("IndexedDB open failed"))})}function Js(){return Gs().then(e=>e?new Promise((t,s)=>{const i=e.transaction(Hs,"readonly"),n=i.objectStore(Hs).get(Bs);n.onsuccess=()=>{const e=n.result;t(e&&e.value?e.value:null)},n.onerror=()=>s(n.error||new Error("IndexedDB read failed")),i.oncomplete=()=>e.close(),i.onerror=()=>e.close(),i.onabort=()=>e.close()}):null)}function Ks(e){return Gs().then(t=>!!t&&new Promise(s=>{try{const i=t.transaction(Hs,"readwrite");i.objectStore(Hs).put({id:Bs,value:e}),i.oncomplete=()=>{t.close(),s(!0)},i.onerror=()=>{t.close(),s(!1)},i.onabort=()=>{t.close(),s(!1)}}catch(e){try{t.close()}catch(e){}s(!1)}})).catch(()=>!1)}function zs(){return"web-"+("undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substring(2))}async function qs(e){const t=await Gs();if(!t)return null;const s=function(e){return e&&"string"==typeof e&&""!==e.trim()?"pending-room:"+e:$s}(e),i=!!e&&s!==$s;return new Promise((n,r)=>{const o=t.transaction(js,"readwrite"),a=o.objectStore(js);let c=null;const l=a.get(s);l.onsuccess=()=>{const t=l.result;if(t&&t.roomId){if((t.projectId||null)===(e||null))return c=t.roomId,void a.delete(s)}if(!i)return;const n=a.get($s);n.onsuccess=()=>{const e=n.result;e&&e.roomId&&!e.projectId&&(c=e.roomId,a.delete($s))}},l.onerror=()=>{r(l.error||new Error("IndexedDB read failed"))},o.oncomplete=()=>{t.close(),n(c)},o.onerror=()=>{t.close(),r(o.error||new Error("IndexedDB transaction failed"))},o.onabort=()=>{t.close(),r(o.error||new Error("IndexedDB transaction aborted"))}})}class Xs{constructor(e){this.apiClient=e.apiClient,this.projectId=e.projectId||null,this.firebaseConfig=e.firebaseConfig||Fs,this.vapidKey=e.vapidKey||"BGP8qaSm1ntjWd4n9pc0lX_rw4BmMxm9u4pvRIANCitbmYaV0iy-gn05suTKBo88kUBejxdxM8sb6x2nt3avu8c",this.serviceWorkerPath=e.serviceWorkerPath||"/firebase-messaging-sw.js",this.logger=new p(e.logLevel||u.WARN,"PushManager"),this._messaging=null,this._currentToken=null,this._enabled=!1,this._enablePromise=null,this._foregroundMessageUnsubscribe=null,this._swRegistration=null,this._projectRegisteredToSW=!1,this._visibilityHandler=null,this._deviceIdCache=null}static async consumePendingRoom(e){return qs(e)}static getPermissionState(){return"undefined"==typeof window||"undefined"==typeof Notification?"unsupported":"undefined"!=typeof navigator&&"serviceWorker"in navigator?Notification.permission:"unsupported"}async enable(){if(this._enabled)this.logger.debug("푸시 알림이 이미 활성화되어 있습니다.");else{if(this._enablePromise)return this.logger.debug("푸시 알림 활성화가 이미 진행 중입니다."),this._enablePromise;this._enablePromise=this._enableInternal();try{return await this._enablePromise}finally{this._enablePromise=null}}}async _enableInternal(){if("undefined"==typeof window||!("Notification"in window))throw new Ws(Us.UNSUPPORTED_BROWSER,"푸시 알림은 브라우저 환경에서만 사용 가능합니다");if(!("serviceWorker"in navigator))throw new Ws(Us.UNSUPPORTED_BROWSER,"이 브라우저는 서비스 워커를 지원하지 않습니다");if("denied"===Notification.permission)throw new Ws(Us.PERMISSION_DENIED,"알림 권한이 이미 거부되어 있습니다. 브라우저 사이트 설정에서 허용해주세요.");let e,t,s;try{e=await import("firebase/app"),t=await import("firebase/messaging")}catch(e){throw new Ws(Us.FIREBASE_NOT_INSTALLED,"firebase 패키지가 설치되지 않았습니다. npm install firebase 를 실행하세요.",e)}try{s=e.getApp("talkflow")}catch{s=e.initializeApp(this.firebaseConfig,"talkflow")}const i=await this._registerServiceWorker();if("granted"!==await Notification.requestPermission())throw new Ws(Us.PERMISSION_DENIED,"알림 권한이 거부되었습니다. 브라우저 설정에서 허용해주세요.");this._messaging=t.getMessaging(s);const n={serviceWorkerRegistration:i};this.vapidKey&&(n.vapidKey=this.vapidKey);try{this._currentToken=await t.getToken(this._messaging,n)}catch(e){throw new Ws(Us.TOKEN_FAILED,"FCM 토큰 획득 중 오류 발생: "+(e?.message||e),e)}if(!this._currentToken)throw new Ws(Us.TOKEN_FAILED,"FCM 토큰 획득 실패 (응답이 비어있음)");await this._registerTokenToServer(this._currentToken),this._foregroundMessageUnsubscribe&&this._foregroundMessageUnsubscribe(),this._foregroundMessageUnsubscribe=t.onMessage(this._messaging,e=>{this.logger.debug("포그라운드 푸시 수신:",e),this._onForegroundMessage(e)}),this._swRegistration=i,await this._registerProjectToSW(),this._installVisibilityReRegister();try{await i.update()}catch(e){this.logger.debug("SW 업데이트 체크 실패 (무시):",e.message)}const r=await this._getSWVersion(i);r?this.logger.debug("SW 버전:",r):this.logger.warn("[TalkFlow] 서비스 워커가 구버전(v1)입니다. 이미지 미리보기 등 리치 알림 기능을 사용하려면 firebase-messaging-sw.js 를 v2 로 업데이트하세요. 가이드: https://docs.talkflow.ai/push/sw-upgrade"),this._enabled=!0,this.logger.info("푸시 알림 활성화 완료")}async _registerServiceWorker(){try{const e=await navigator.serviceWorker.register(this.serviceWorkerPath,{updateViaCache:"none"});return this.logger.debug("서비스 워커 등록 완료:",this.serviceWorkerPath),e}catch(e){throw new Ws(Us.SW_REGISTER_FAILED,`서비스 워커 등록 실패: ${this.serviceWorkerPath}\n프로젝트 public 폴더에 firebase-messaging-sw.js 파일을 배치하세요.`,e)}}async _registerTokenToServer(e){try{const t=await this._getDeviceId();await this.apiClient.post("/api/v1/push/devices",{deviceToken:e,deviceType:"WEB",deviceId:t}),this.logger.info("디바이스 토큰 서버 등록 완료")}catch(e){if(this.logger.error("디바이스 토큰 서버 등록 실패:",e),e instanceof Ws)throw e;throw new Ws(Us.SERVER_REGISTER_FAILED,"디바이스 토큰 서버 등록 실패: "+(e?.message||e),e)}}async _getDeviceId(){if(this._deviceIdCache)return this._deviceIdCache;try{let e=await Js();if(!e&&"undefined"!=typeof localStorage){const t=localStorage.getItem(Vs);if(t){e=t;if(await Ks(e)){if(await Js()===e)try{localStorage.removeItem(Vs),this.logger.debug("deviceId migrated from localStorage to IndexedDB")}catch(e){}else this.logger.warn("deviceId IDB read-back 불일치, localStorage 보존")}else this.logger.warn("deviceId IDB 저장 실패 (private mode / quota 등), localStorage 보존")}}if(!e){e=zs();await Ks(e)||this.logger.warn("신규 deviceId IDB 저장 실패, 이번 세션만 유효")}return this._deviceIdCache=e,e}catch(e){if(this.logger.warn("IndexedDB deviceId 조회/저장 실패, fallback:",e),!this._deviceIdCache){let e=null;if("undefined"!=typeof localStorage)try{e=localStorage.getItem(Vs)}catch(e){}this._deviceIdCache=e||zs()}return this._deviceIdCache}}_onForegroundMessage(e){}async consumePendingRoom(){return Xs.consumePendingRoom(this.projectId)}reset(){if(this._foregroundMessageUnsubscribe)try{this._foregroundMessageUnsubscribe()}catch(e){this.logger.debug("포그라운드 푸시 리스너 해제 실패 (무시):",e?.message||e)}this._uninstallVisibilityReRegister(),this._unregisterProjectFromSW(),this._foregroundMessageUnsubscribe=null,this._enablePromise=null,this._messaging=null,this._currentToken=null,this._enabled=!1,this._swRegistration=null,this._projectRegisteredToSW=!1}async _registerProjectToSW(){if(this.projectId)try{const e=(await navigator.serviceWorker.ready).active||this._swRegistration&&this._swRegistration.active;if(!e)return void this.logger.debug("SW active worker 없음 — projectId 등록 스킵");e.postMessage({type:"TALKFLOW_REGISTER_PROJECT",projectId:this.projectId}),this._projectRegisteredToSW=!0}catch(e){this.logger.debug("SW projectId 등록 실패 (무시):",e?.message||e)}}_unregisterProjectFromSW(){if(this._projectRegisteredToSW)try{if("undefined"==typeof navigator||!navigator.serviceWorker)return;const e=navigator.serviceWorker.controller;if(!e)return;e.postMessage({type:"TALKFLOW_UNREGISTER_PROJECT"})}catch(e){this.logger.debug("SW projectId 해제 실패 (무시):",e?.message||e)}}_installVisibilityReRegister(){"undefined"==typeof document||this._visibilityHandler||(this._visibilityHandler=()=>{"visible"===document.visibilityState&&this._enabled&&this.projectId&&this._registerProjectToSW().catch(()=>{})},document.addEventListener("visibilitychange",this._visibilityHandler))}_uninstallVisibilityReRegister(){if("undefined"!=typeof document&&this._visibilityHandler){try{document.removeEventListener("visibilitychange",this._visibilityHandler)}catch(e){}this._visibilityHandler=null}}getToken(){return this._currentToken}isEnabled(){return this._enabled}async getMyDevices(){const e=await this.apiClient.get("/api/v1/push/devices/me");return e&&"object"==typeof e&&"data"in e?e.data:e}async setDeviceEnabled(e,t){await this.apiClient.patch("/api/v1/push/devices/me/enabled",{deviceId:e,enabled:t}),this.logger.info(`디바이스 푸시 enabled=${t}: deviceId=${e}`)}async setCurrentDeviceEnabled(e){const t=await this._getDeviceId();await this.setDeviceEnabled(t,e)}async _getSWVersion(e){try{const t=await navigator.serviceWorker.ready,s=t.waiting||t.installing||t.active||e.waiting||e.installing||e.active;return s?new Promise(e=>{const t=setTimeout(()=>e(null),2e3),i=new MessageChannel;i.port1.onmessage=s=>{clearTimeout(t),e(s.data?.version||null)};try{s.postMessage({type:"TALKFLOW_SW_VERSION"},[i.port2])}catch(s){clearTimeout(t),e(null)}}):null}catch{return null}}setLogLevel(e){this.logger.setLevel(e)}}const Ys=[["connected","connected"],["disconnected","disconnected"],["reconnecting","reconnecting"],["error","connectionError"]],Qs=[["message","chatMessage"],["newMessage","newChatMessage"],["messageUpdated","messageUpdated"],["messageDeleted","messageDeleted"],["reactionChanged","reactionChanged"],["linkPreviewAttached","linkPreviewAttached"],["messageTranslated","messageTranslated"],["messageRead","messageRead"],["typing","typing"],["assistantProgress","assistantProgress"],["memberJoined","memberJoined"],["memberLeft","memberLeft"],["roomSubscribed","roomSubscribed"],["roomUnsubscribed","roomUnsubscribed"],["roomListSubscribed","roomListSubscribed"],["roomListUnsubscribed","roomListUnsubscribed"],["roomListUpdate","roomListUpdate"],["roomListMessage","roomListMessage"],["roomListCreated","roomListCreated"],["roomListJoined","roomListJoined"],["roomListLeft","roomListLeft"],["roomListSelfLeft","roomListSelfLeft"],["roomListKicked","roomListKicked"],["roomListSelfKicked","roomListSelfKicked"],["roomListBanned","roomListBanned"],["roomListSelfBanned","roomListSelfBanned"],["roomListRoomUpdated","roomListRoomUpdated"],["retentionCleanup","retentionCleanup"]],Zs=[["localStreamStarted","localStreamStarted"],["localStreamStopped","localStreamStopped"],["remoteTrack","remoteTrack"],["screenShareStarted","screenShareStarted"],["screenShareEnded","screenShareEnded"],["deviceChange","deviceChange"],["mediaStateChanged","mediaStateChanged"],["callStarted","callStarted"],["callEnded","callEnded"],["callRequested","callRequested"],["callAccepted","callAccepted"],["callRejected","callRejected"],["callCancelled","callCancelled"],["callBusy","callBusy"],["incomingCall","incomingCall"],["incomingCallWhileBusy","incomingCallWhileBusy"],["callInvitation","callInvitation"],["userJoined","userJoined"],["userLeft","userLeft"],["participantLeft","participantLeft"],["participantMediaState","participantMediaState"],["peerConnected","peerConnected"],["peerDisconnected","peerDisconnected"],["peerClosed","peerClosed"],["error","webrtcError"]];function ei(e,t,s){s.forEach(([s,i])=>{e.on(s,e=>{t.emit(i,e)})})}const ti=["getRooms","getRoom","getRoomInfo","setMyRoomLanguage","createOneToOneRoom","createGroupRoom","joinGroupRoom","leaveRoom","updateGroupRoom","inviteToGroupRoom","kickMember","banMember","unbanMember","getBannedMembers","getAvailableGroupRooms","getAllGroupRooms","enterRoom","getMessages","fetchLinkPreview","sendMessage","sendMessageOptimistic","sendTextMessage","sendTextMessageOptimistic","sendReply","sendReplyOptimistic","uploadFile","sendFileMessage","sendFileMessageOptimistic","editMessage","deleteMessage","markAsRead","pinMessage","unpinMessage","toggleReaction","subscribeRoom","unsubscribeRoom","unsubscribeAllRooms","setActiveRoom","clearActiveRoom","getActiveRoom","subscribeRoomList","unsubscribeRoomList","isRoomListSubscribed","getSubscribedRooms","isSubscribed","startTyping","stopTyping","getAssistants","getRoomAiMeta","rateAssistantMessage","summarizeWithAssistant","translateWithAssistant","getRoomPmPrompt","upsertRoomPmPrompt","activateRoomPmPrompt","deactivateRoomPmPrompt","getRoomPmPromptVersions","activateRoomPmPromptVersion","previewRoomPmPrompt"],si=["initializeIceServers","getTurnCredentials","createCallRoom","getCallRoom","joinCallRoomApi","leaveCallRoomApi","enableIncomingCalls","disableIncomingCalls","isIncomingCallsEnabled","startCall","callUser","acceptCall","rejectCall","cancelCall","endCall","toggleVideo","toggleAudio","setVideoEnabled","setAudioEnabled","startScreenShare","stopScreenShare","getLocalStream","getDevices","switchDevice","startDeviceChangeDetection","stopDeviceChangeDetection","applyVideoConstraints","getVideoSettings","getAudioSettings","isInCall","getCurrentRoom","getParticipants","getMediaState","getConnectionSummary","getStats"];function ii(e,t,s){s.forEach(s=>{e[s]=function(...e){return this[t][s](...e)}})}class ni extends t{constructor(e){super(),this._validateOptions(e);const t=e.env||h.environment,i=(e.serverUrl||d(t)).replace(/\/$/,"");this.options={serverUrl:i,env:t,apiKey:e.apiKey,projectId:e.projectId,jwtToken:e.jwtToken||null,useSockJS:!1!==e.useSockJS,reconnectDelay:e.reconnectDelay||h.reconnectDelay,maxReconnectAttempts:e.maxReconnectAttempts||h.maxReconnectAttempts,iceServers:e.iceServers||h.iceServers,autoSubscribeRoomList:!1!==e.autoSubscribeRoomList,logLevel:void 0!==e.logLevel?e.logLevel:u.WARN},this.logger=new p(this.options.logLevel,"TalkFlowClient"),this._initialized=!1,this._state=s.DISCONNECTED,this._userId=null,this.options.jwtToken&&(this._userId=_(this.options.jwtToken)),this.apiClient=new g({baseUrl:this.options.serverUrl,apiKey:this.options.apiKey,projectId:this.options.projectId,jwtToken:this.options.jwtToken,logLevel:this.options.logLevel}),this.connectionManager=null,this._chat=null,this._webrtc=null,this._pushManager=null,this._pushEnablePromise=null,this.options.jwtToken&&this._userId&&this._initializeSubClients(),this._initialized=!0,this.logger.info("TalkFlowClient initialized",{userId:this._userId,hasToken:!!this.options.jwtToken})}get chat(){return this._chat}get webrtc(){return this._webrtc}get pushManager(){return this._pushManager}get userId(){return this._userId}_validateOptions(e){if(!e)throw new Error("Options are required");if(!e.apiKey)throw new Error("apiKey is required");if(!e.projectId)throw new Error("projectId is required");if(e.apiKey.startsWith("sk-")){const t=e.env||"production";"development"===t?console.warn("⚠️ [TalkFlow] Server Key (sk-) 를 개발 모드에서 사용 중입니다. 프로덕션 배포 전에 반드시 Client Key (ck-) 로 교체하세요."):console.error("🚨 [TalkFlow] Server Key (sk-) 가 비개발 환경 ("+t+") 에서 감지되었습니다. 보안 위험: Server Key 를 브라우저에 포함하면 공격자가 임의 사용자로 JWT 를 발급받을 수 있습니다. 반드시 Client Key (ck-) 로 교체하세요. 서버에서도 프로덕션 모드에서 Server Key 의 브라우저 호출을 차단합니다.")}}_initializeSubClients(){!function(e){if(!e.connectionManager){if(!e.userId)throw new Error("userId is required to initialize sub-clients. Please set JWT token first.");e.connectionManager=new Ms({serverUrl:e.options.serverUrl,jwtToken:e.options.jwtToken,apiKey:e.options.apiKey,projectId:e.options.projectId,useSockJS:e.options.useSockJS,reconnectDelay:e.options.reconnectDelay,maxReconnectAttempts:e.options.maxReconnectAttempts,logLevel:e.options.logLevel}),e._chat=new Ls({connectionManager:e.connectionManager,apiClient:e.apiClient,userId:e._userId,logLevel:e.options.logLevel}),e._webrtc=new xs({connectionManager:e.connectionManager,apiClient:e.apiClient,userId:e._userId,iceServers:e.options.iceServers,logLevel:e.options.logLevel}),e._setupEventForwarding(),e.logger.debug("Sub-clients initialized")}}(this)}_setupEventForwarding(){var e;(e=this).connectionManager&&(e.connectionManager.on("stateChange",({state:t,prevState:s})=>{e._state=t,e.emit("stateChange",{state:t,prevState:s})}),ei(e.connectionManager,e,Ys),e.chat&&ei(e.chat,e,Qs),e.webrtc&&ei(e.webrtc,e,Zs))}isConnected(){return!!this.connectionManager&&this.connectionManager.isConnected()}getState(){return this._state}hasToken(){return!!this.options.jwtToken}async registerUser(e){const t={...e};if(void 0===t.preferredLanguage){const e=ni.detectBrowserLanguage();e&&(t.preferredLanguage=e)}const s=await this.apiClient.post("/api/v1/users/auth",t);return s.data&&s.data.accessToken&&(await this.setToken(s.data.accessToken),this.logger.info("User authenticated, token auto-set")),s}async updateMyInfo(e){return this._checkToken(),this.apiClient.put("/api/v1/users/update",e)}async setPreferredLanguage(e){return this.updateMyInfo({preferredLanguage:e})}static detectBrowserLanguage(){return"undefined"!=typeof navigator&&navigator.language&&navigator.language.trim().toLowerCase()||null}static displayText(e,t){return e&&e.translations&&t&&e.translations[t]?e.translations[t]:e?e.content:null}async checkUserExists(e){return this.apiClient.get(`/api/v1/users/${e}/exists`)}async getUsers(e={}){this._checkToken();const{size:t=50,lastId:s,lastSortValue:i}=e;return this.apiClient.get("/api/v1/users",{size:t,lastId:s,lastSortValue:i})}async searchUsers(e){this._checkToken();const{keyword:t,limit:s=20}=e;return this.apiClient.get("/api/v1/users/search",{keyword:t,limit:s})}_checkToken(){if(!this.options.jwtToken)throw new Error('JWT token is required for this operation. Obtain it from your backend (POST /api/v1/users/auth with Server API Key) and pass it via setToken(). See README "프로덕션 인증 플로우".')}getUserId(){return this.userId}isInitialized(){return this._initialized}isReady(){return this._initialized&&!!this.connectionManager}setLogLevel(e){this.options.logLevel=e,this.logger.setLevel(e),this.apiClient.logger?.setLevel(e),this.connectionManager&&this.connectionManager.setLogLevel(e),this.chat&&this.chat.setLogLevel(e),this.webrtc&&this.webrtc.setLogLevel(e)}getStatus(){return{initialized:this._initialized,ready:this.isReady(),hasToken:this.hasToken(),connectionState:this._state,isConnected:this.isConnected(),userId:this.userId,chat:this.chat?{subscribedRooms:this.chat.getSubscribedRooms()}:null,webrtc:this.webrtc?{isInCall:this.webrtc.isInCall(),currentRoom:this.webrtc.getCurrentRoom(),participants:this.webrtc.getParticipants(),mediaState:this.webrtc.getMediaState()}:null}}async destroy(){await this.disconnect(),this.chat&&this.chat.destroy(),this.webrtc&&this.webrtc.destroy(),this.connectionManager&&await this.connectionManager.destroy(),this.removeAllListeners(),this._initialized=!1,this.logger.info("TalkFlowClient destroyed")}}ni.ConnectionState=s,ni.ErrorTypes=i,ni.LogLevel=u,ni.Environment=c,function(e){e.prototype.connect=async function(e,t={}){const{enablePush:s=!1}=t;if(e&&await this.setToken(e),!this.options.jwtToken)throw new Error('JWT token is required. Obtain it from your backend (which calls POST /api/v1/users/auth with a Server API Key) and pass it to the SDK via the jwtToken option, setToken(), or connect(jwt). See README "프로덕션 인증 플로우".');if(y(this.options.jwtToken))throw new Error("JWT token has expired. Please update the token before connecting.");if(this.connectionManager||this._initializeSubClients(),await this.connectionManager.connect(),this.webrtc&&await this.webrtc.enableIncomingCalls(),this.chat&&this.options.autoSubscribeRoomList)try{await this.chat.subscribeRoomList()}catch(e){this.logger.warn("Failed to auto-subscribe room list (non-fatal):",e)}s&&this.enablePushNotifications(),this.logger.info("Connected to server")},e.prototype.disconnect=async function(){this.connectionManager&&(this.webrtc&&this.webrtc.isInCall()&&this.webrtc.endCall(),this.webrtc&&this.webrtc.disableIncomingCalls(),this.chat&&(this.chat.unsubscribeAllRooms(),this.chat.unsubscribeRoomList()),await this.connectionManager.disconnect(),this.logger.info("Disconnected from server"))},e.prototype.logout=async function(){try{await this.apiClient.post("/v1/auth/signout"),this.logger.info("Logged out from server")}catch(e){this.logger.warn("Server logout failed (proceeding with local cleanup):",e.message)}await this.disconnect(),this.pushManager&&(this.pushManager.reset(),this._pushEnablePromise=null),this.options.jwtToken=null,this._userId=null,this.apiClient.setJwtToken(null),this.emit("loggedOut")},e.prototype.enablePushNotifications=async function(e={}){if(!this.options.jwtToken){const e=new Error("JWT token is required to enable push notifications.");return this.emit("pushFailed",{reason:"NO_TOKEN",error:e}),{ok:!1,reason:"NO_TOKEN",error:e}}if(!this.pushManager){this._pushManager=new Xs({apiClient:this.apiClient,projectId:this.options.projectId,firebaseConfig:e.firebaseConfig,vapidKey:e.vapidKey,serviceWorkerPath:e.serviceWorkerPath,logLevel:this.options.logLevel});const t=3e5;this.pushManager._onForegroundMessage=e=>{const s=e.data||{};if(s.projectId&&s.projectId!==this.options.projectId)return void this.logger.debug("다른 프로젝트 푸시 무시:",s.projectId);const i=this.chat?.getActiveRoom();if(i&&i===s.roomId)this.logger.debug("포그라운드 푸시 suppress (현재 방):",s.roomId);else{if(s.messageId){if(this._recentPushMessageIds||(this._recentPushMessageIds=new Map),this._recentPushMessageIds.has(s.messageId))return void this.logger.debug("포그라운드 푸시 dedup:",s.messageId);const e=setTimeout(()=>{this._recentPushMessageIds.delete(s.messageId)},t);this._recentPushMessageIds.set(s.messageId,e)}this.emit("pushNotification",{title:e.notification?.title||s.title,body:e.notification?.body||s.body,data:s})}}}if(this.pushManager.isEnabled())return this.logger.debug("웹 푸시가 이미 활성화되어 있어 중복 호출을 건너뜁니다."),{ok:!0,alreadyEnabled:!0};if(this._pushEnablePromise)return this.logger.debug("웹 푸시 활성화가 이미 진행 중입니다."),this._pushEnablePromise;const t=(async()=>{try{return await this.pushManager.enable(),this.emit("pushEnabled"),{ok:!0}}catch(e){const t=e&&e.code?e.code:"UNKNOWN";return this.logger.warn("Failed to enable push notifications:",t,e?.message),this.emit("pushFailed",{reason:t,error:e}),{ok:!1,reason:t,error:e}}})();return this._pushEnablePromise=t,t.finally(()=>{this._pushEnablePromise===t&&(this._pushEnablePromise=null)}),t},e.prototype.consumePendingRoom=async function(){return Xs.consumePendingRoom(this.options.projectId)},e.prototype.setCurrentDeviceEnabled=function(e){return this.pushManager?.setCurrentDeviceEnabled(e)},e.prototype.setDeviceEnabled=function(e,t){return this.pushManager?.setDeviceEnabled(e,t)},e.prototype.getMyDevices=function(){return this.pushManager?.getMyDevices()},e.prototype.getPushPermissionState=function(){return Xs.getPermissionState()},e.prototype.isPushEnabled=function(){return this.pushManager?.isEnabled()??!1},e.prototype.getPushToken=function(){return this.pushManager?.getToken()??null},e.prototype.resetPush=function(){this.pushManager?.reset(),this._pushEnablePromise=null},e.prototype.setToken=async function(e){const{userId:t}=b(e,{validateExpiry:!1}),s=this.userId&&this.userId!==t;this.options.jwtToken=e,this._userId=t,this.apiClient.setJwtToken(e),s&&this.connectionManager?(await this.disconnect(),this.pushManager&&(this.pushManager.reset(),this._pushEnablePromise=null),this.connectionManager=null,this._chat=null,this._webrtc=null,this._initializeSubClients()):this.connectionManager?this.connectionManager.updateToken(e):this._initializeSubClients(),this.logger.info("JWT token set",{userId:t}),this.emit("tokenSet",{userId:t})},e.prototype.updateToken=async function(e){await this.setToken(e)}}(ni),function(e){ii(e.prototype,"chat",ti),ii(e.prototype,"webrtc",si)}(ni),e.AssistantMode={GENERAL:"GENERAL",PEOPLE_ONLY:"PEOPLE_ONLY",CALL_ONLY:"CALL_ONLY"},e.ChatClient=Ls,e.ChatMessageType={TEXT:"TEXT",IMAGE:"IMAGE",FILE:"FILE",VIDEO:"VIDEO",AUDIO:"AUDIO",SYSTEM:"SYSTEM"},e.ChatRoomType=r,e.ConnectionManager=Ms,e.ConnectionState=s,e.DefaultConfig=h,e.Endpoints=l,e.EngagementIntensity={QUIET:"QUIET",NORMAL:"NORMAL",ACTIVE:"ACTIVE"},e.Environment=c,e.ErrorTypes=i,e.EventEmitter=t,e.LogLevel=u,e.Logger=p,e.MediaStreamManager=Ds,e.PeerConnectionManager=Ps,e.PersonaRole={LEGAL_ADVISOR:"LEGAL_ADVISOR",MARKETING:"MARKETING",PRODUCT_PLANNING:"PRODUCT_PLANNING",HR:"HR",FINANCE:"FINANCE",CUSTOMER_SUPPORT:"CUSTOMER_SUPPORT",SALES:"SALES",ENGINEERING:"ENGINEERING",DATA_ANALYST:"DATA_ANALYST",PROJECT_MANAGEMENT:"PROJECT_MANAGEMENT",RESEARCH:"RESEARCH",TRANSLATION:"TRANSLATION",DESIGN:"DESIGN",PM:"PM"},e.PmPromptLayerEditorType={SUPER_ADMIN:"SUPER_ADMIN",PROJECT_ADMIN:"PROJECT_ADMIN",ROOM_OWNER:"ROOM_OWNER"},e.PmPromptLayerScope={PROJECT:"PROJECT",ROOM:"ROOM"},e.PushError=Ws,e.PushErrorCode=Us,e.PushManager=Xs,e.RoomAiType={NONE:"NONE",PERSONA_MULTI:"PERSONA_MULTI",PM_BACKSTAGE:"PM_BACKSTAGE"},e.RoomListEventType=o,e.SenderType={USER:"USER",ASSISTANT:"ASSISTANT"},e.SignalTypes=n,e.SummarizeFormat={MINUTES:"MINUTES",SHORT:"SHORT",TIMELINE:"TIMELINE",ACTIONS:"ACTIONS",OPTIONS:"OPTIONS"},e.WebRTCClient=xs,e.WebSocketPaths=a,e.decodeJWTPayload=function(e){try{const t=m(e).split(".");return 3!==t.length?null:JSON.parse(f(t[1]))}catch(e){return console.error("Failed to decode JWT payload:",e),null}},e.default=ni,e.extractUserIdFromJWT=_,e.getJWTRemainingTime=function(e){try{const t=m(e).split(".");if(3!==t.length)return-1;const s=JSON.parse(f(t[1]));return s.exp?1e3*s.exp-Date.now():1/0}catch(e){return console.error("Failed to get JWT remaining time:",e),-1}},e.getServerUrl=d,e.isJWTExpired=y,e.validateAndParseJWT=b,Object.defineProperty(e,"__esModule",{value:!0})});
2
2
  //# sourceMappingURL=talkflow-sdk.standalone.js.map