@16x/webphone-sdk 3.1.16 → 3.1.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/dist/{CCBarClient-CaX9tQqd.js → CCBarClient-5z2ZCceq.js} +177 -102
- package/dist/CCBarClient-UAJK9WcJ.cjs +1 -0
- package/dist/{Diagnostics-BkIvNuAI.cjs → Diagnostics-DhX9Uc67.cjs} +1 -1
- package/dist/{Diagnostics-Cqmr7y9b.js → Diagnostics-qnipur6s.js} +1 -1
- package/dist/core/CCBarClient.d.ts +3 -0
- package/dist/core/CallManager.d.ts +5 -0
- package/dist/diagnostics/index.cjs +1 -1
- package/dist/diagnostics/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +2 -2
- package/dist/index.umd.js +10 -10
- package/dist/legacy/index.cjs +1 -1
- package/dist/legacy/index.js +1 -1
- package/dist/version.d.ts +1 -1
- package/package.json +1 -1
- package/dist/CCBarClient-CQbwpylz.cjs +0 -1
package/dist/index.umd.js
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.CCBarSDK={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},c=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),l=(e,t)=>{let r={};for(var i in e)n(r,i,{get:e[i],enumerable:!0});return t||n(r,Symbol.toStringTag,{value:`Module`}),r},u=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},d=(e,r,i)=>(i=e==null?{}:t(a(e)),u(r||!e||!e.__esModule||!o.call(e,`default`)?n(i,`default`,{value:e,enumerable:!0}):i,e)),f=e=>o.call(e,`module.exports`)?e[`module.exports`]:u(n({},`__esModule`,{value:!0}),e),p,m,h=s((()=>{p={AUTH_TOKEN_UNAVAILABLE:`获取登录凭证失败,请检查凭证获取服务后重试。`,AUTH_TOKEN_EXPIRED:`登录凭证已过期,请重新获取凭证后登录。`,AUTH_TOKEN_REJECTED:`服务端未接受当前登录凭证,请核实凭证类型和权限。`,AUTH_PERMISSION_DENIED:`当前账号没有执行此操作的权限,请联系管理员。`,CONFIG_INVALID:`配置不完整或格式不正确,请检查软电话配置。`,CONFIG_ORIGIN_NOT_ALLOWED:`当前页面域名未获授权,请联系管理员配置访问域名。`,NETWORK_OFFLINE:`网络连接已断开,请检查网络后重试。`,NETWORK_TIMEOUT:`请求超时,请检查网络后重试。`,SIP_WS_UNAVAILABLE:`无法连接 SIP 服务,请检查 SIP WSS 地址和网络。`,REGISTRATION_FAILED:`SIP 注册失败,请检查坐席配置后重试。`,REGISTRATION_REJECTED:`SIP 服务拒绝了当前账号,请核对分机和 SIP 凭证。`,MEDIA_PERMISSION_DENIED:`麦克风权限未开启,请在浏览器设置中允许使用麦克风。`,MEDIA_DEVICE_NOT_FOUND:`未找到可用的音频设备,请连接麦克风或耳机后重试。`,MEDIA_DEVICE_IN_USE:`音频设备正在被其他程序使用,请关闭占用设备的程序后重试。`,MEDIA_PLAYBACK_BLOCKED:`浏览器阻止了声音播放,请点击页面并检查浏览器音频设置。`,CALL_INVALID_DESTINATION:`被叫号码格式不正确,请检查后重试。`,CALL_INVALID_USERDATA:`通话附加数据格式不正确,请检查后重试。`,CALL_ALREADY_EXISTS:`当前已有进行中的通话,请先结束当前通话。`,CALL_REJECTED:`对方或呼叫平台拒绝了本次呼叫。`,CALL_BUSY:`对方正在通话中,请稍后重试。`,CALL_NOT_CONNECTED:`当前没有可操作的通话,请先拨打或接听电话。`,NOT_SIGNED_IN:`请先登录,并等待 SIP 注册成功后再操作。`,CALL_OPERATION_NOT_ALLOWED:`当前通话状态不支持此操作,请检查通话状态后重试。`,CAPABILITY_NOT_SUPPORTED:`当前浏览器或设备不支持此功能。`,H5_BACKGROUND_NOT_SUPPORTED:`页面在后台时无法执行此操作,请返回通话页面后重试。`,SDK_ALREADY_DISPOSED:`软电话实例已关闭,请重新创建实例后操作。`,SDK_INTERNAL_ERROR:`软电话发生异常,请稍后重试;如问题持续,请联系技术支持。`,LEGACY_PLATFORM_UNREACHABLE:`无法连接坐席服务,请检查 API host 和网络。`,LEGACY_PLATFORM_REJECTED:`坐席服务未能完成请求,请核对账号权限和接口配置。`},m=class extends Error{code;category;retryable;requestId;callId;cause;serverCode;platformCode;status;constructor(e,t,n,r={}){super(p[e]),this.name=`CCBarError`,this.code=e,this.category=t,this.retryable=n,this.requestId=r.requestId,this.callId=r.callId,this.cause=r.cause,this.serverCode=r.serverCode,this.platformCode=r.platformCode,this.status=r.status}}}));h();var g=class{handlers=new Map;on(e,t){let n=this.handlers.get(e)??new Set;n.add(t),this.handlers.set(e,n);let r=!0;return()=>{r&&(r=!1,n.delete(t))}}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,t){[...this.handlers.get(e)??[]].forEach(e=>{try{e(t)}catch{}})}listenerCount(){return[...this.handlers.values()].reduce((e,t)=>e+t.size,0)}clear(){this.handlers.clear()}},_={new:new Set([`dialing`,`ringing`,`failed`]),dialing:new Set([`ringing`,`connecting`,`ended`,`failed`]),ringing:new Set([`connecting`,`ended`,`failed`]),connecting:new Set([`active`,`ended`,`failed`]),active:new Set([`held`,`ended`,`failed`]),held:new Set([`active`,`ended`,`failed`]),ended:new Set,failed:new Set},v=(e,t)=>_[e].has(t);function y(e,t){if(!v(e,t))throw new b(e,t);return t}var b=class extends m{constructor(e,t){super(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{cause:{from:e,to:t}})}},x=y;function S(e){if(e.code!==`OK`)throw TypeError(`Unexpected session response code: ${e.code}`);if(e.data===void 0||e.data===null)throw TypeError(`Unexpected session response: missing data`);return e.data}h();var C=[`progress`,`accepted`,`confirmed`,`ended`,`failed`,`hold`,`unhold`,`mediaConnected`],w=3e4,ee=class{options;currentState=`new`;sessionUnsubscribers=[];capabilities;disposed=!1;pendingOperation;localHeld=!1;remoteHeld=!1;incomingOperation;ownerTabId;ownerLost=!1;id;destination;platform;constructor(e){this.options=e,this.id=e.id,this.destination=e.destination,this.platform=e.platform,this.capabilities=e.capabilities??new Set;try{C.forEach(t=>{this.sessionUnsubscribers.push(e.session.on(t,e=>this.handleSessionEvent(t,e)))})}catch(t){this.cleanupSessionListeners();try{e.session.terminate()}catch{}throw new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:this.id,cause:t})}}get state(){return this.currentState}getResourceCounts(){return{timers:this.pendingOperation?.timer===void 0?0:1,listeners:this.sessionUnsubscribers.length}}async mute(e){this.assertNotDisposed(),this.assertOwner(e),this.assertMediaControlAllowed(),this.assertCapability(`mute`),this.invoke(()=>this.options.session.mute())}async unmute(e){this.assertNotDisposed(),this.assertOwner(e),this.assertMediaControlAllowed(),this.assertCapability(`mute`),this.invoke(()=>this.options.session.unmute())}async answer(e,t){this.assertNotDisposed(),this.assertOwner(t),this.assertIncomingCall(),this.assertCapability(`inbound`),this.assertIncomingOperationAvailable(),this.incomingOperation=`answer`;try{this.options.session.answer(e)}catch(e){throw this.incomingOperation=void 0,this.finishFailedIncomingOperation(e),this.operationError(e)}this.transitionIfAllowed(`connecting`,void 0,`accepted`)}async reject(e={},t){this.assertNotDisposed(),this.assertOwner(t),this.assertIncomingCall(),this.assertIncomingOperationAvailable(),this.incomingOperation=`reject`;let n;try{this.options.session.terminate()}catch(e){n=e}finally{this.incomingOperation=void 0,this.transitionIfStillRinging(`ended`,{reason:e.reason?.trim()||`rejected`})}if(n!==void 0)throw this.operationError(n)}async hold(e){this.assertNotDisposed(),this.assertOwner(e),this.assertHoldCapability(),this.assertState(`active`),this.assertCapability(`hold`),await this.startPendingOperation(`hold`,()=>this.options.session.hold())}async resume(e){if(this.assertNotDisposed(),this.assertOwner(e),this.assertHoldCapability(),this.assertState(`held`),this.assertCapability(`hold`),this.remoteHeld&&!this.localHeld)throw this.operationError({reason:`remote_hold_active`});await this.startPendingOperation(`resume`,()=>this.options.session.unhold())}async sendDtmf(e,t){if(this.assertNotDisposed(),this.assertOwner(t),!/^[0-9A-D*#]$/.test(e))throw this.operationError();this.assertState(`active`),this.assertCapability(`dtmf`),this.invoke(()=>this.options.session.sendDtmf(e))}async transfer(e,t){if(this.assertNotDisposed(),this.assertOwner(t),this.assertTransferCapability(),this.assertState(`active`),this.assertCapability(`blind_transfer`),!E(e)||e.target.trim()===``)throw this.operationError();this.invoke(()=>this.options.session.refer(e.target.trim()))}async hangup(e){if(this.assertNotDisposed(),this.assertOwner(e),T(this.currentState))throw this.operationError();try{this.options.session.terminate(),T(this.currentState)||this.transitionTo(`ended`)}catch(e){throw this.operationError(e)}}beginOutbound(){this.assertNotDisposed(),this.assertCapability(`outbound`),this.transitionTo(`dialing`)}beginIncoming(){this.assertNotDisposed(),this.transitionTo(`ringing`)}setOwnerTabId(e){this.ownerTabId=e,this.ownerLost=!1}clearOwnerTabId(e={}){this.ownerTabId=void 0,this.ownerLost=e.lost===!0}getOwnerTabId(){return this.ownerTabId}assertOwnerForManager(e){this.assertOwner(e)}canBeReclaimed(){return this.currentState===`new`||this.currentState===`dialing`||this.currentState===`ringing`}dispose(){if(!this.disposed){if(this.rejectPendingOperation(),this.incomingOperation=void 0,this.disposed=!0,!T(this.currentState))try{this.options.session.terminate()}catch(e){this.reportOperationError(e)}this.cleanupSessionListeners();try{this.options.onDisposed?.()}catch{}}}handleSessionEvent(e,t){if((e===`accepted`||e===`confirmed`||e===`ended`||e===`failed`)&&(this.incomingOperation=void 0),!(this.disposed||T(this.currentState)))switch(e){case`progress`:this.transitionIfAllowed(`ringing`,t,e);break;case`accepted`:this.transitionIfAllowed(`connecting`,t,e);break;case`confirmed`:this.transitionToActive(t);break;case`mediaConnected`:this.currentState===`connecting`&&this.transitionTo(`active`,t);break;case`hold`:this.updateHoldState(!0,t,e);break;case`unhold`:this.updateHoldState(!1,t,e);break;case`ended`:this.transitionIfAllowed(`ended`,t,e);break;case`failed`:this.transitionIfAllowed(`failed`,t,e)}}transitionToActive(e){this.currentState!==`active`&&((this.currentState===`dialing`||this.currentState===`ringing`)&&this.transitionTo(`connecting`,e),this.transitionIfAllowed(`active`,e,`confirmed`))}transitionIfAllowed(e,t,n){this.currentState!==e&&(v(this.currentState,e)?this.transitionTo(e,t):this.reportIllegalTransition(e,n))}updateHoldState(e,t,n){let r=typeof t==`object`&&t?t.originator:void 0;r===`remote`?this.remoteHeld=e:r===`both`?(this.localHeld=e,this.remoteHeld=e):this.localHeld=e;let i=this.localHeld||this.remoteHeld?`held`:`active`;this.transitionIfAllowed(i,t,n)}transitionIfStillRinging(e,t){this.currentState===`ringing`&&this.transitionTo(e,t)}transitionTo(e,t){if(this.currentState===e)return;if(!v(this.currentState,e))throw this.operationError();let n=this.currentState;this.currentState=e,T(e)&&this.rejectPendingOperation();try{this.options.onStateChanged?.({callId:this.id,from:n,to:e},t)}catch{}finally{T(e)&&this.dispose()}}startPendingOperation(e,t){if(this.pendingOperation!==void 0)throw this.operationError({reason:`pending_operation_in_progress`,operation:this.pendingOperation.kind});return new Promise((n,r)=>{let i={kind:e,resolve:n,reject:r};this.pendingOperation=i,i.timer=setTimeout(()=>this.timeoutPendingOperation(i),w);let a;try{a=t()}catch(e){this.rejectPendingOperation(e);return}a.then(()=>this.resolvePendingOperation(i),e=>this.rejectPendingOperation(e,i))})}resolvePendingOperation(e){if(this.pendingOperation===e){if(this.clearPendingTimer(e),this.pendingOperation=void 0,this.disposed||T(this.currentState)){e.reject(this.operationError());return}try{this.localHeld=e.kind===`hold`;let t=this.localHeld||this.remoteHeld?`held`:`active`;this.transitionTo(t),e.resolve()}catch(t){e.reject(this.operationError(t))}}}rejectPendingOperation(e,t){let n=this.pendingOperation;n===void 0||t!==void 0&&n!==t||(this.clearPendingTimer(n),this.pendingOperation=void 0,n.reject(this.operationError(e)))}timeoutPendingOperation(e){this.pendingOperation===e&&(this.rejectPendingOperation(Error(`${e.kind} operation timed out`),e),this.dispose())}clearPendingTimer(e){e.timer!==void 0&&(clearTimeout(e.timer),e.timer=void 0)}reportIllegalTransition(e,t){this.reportOperationError({event:t,from:this.currentState,to:e})}reportOperationError(e){let t=e instanceof m&&e.callId===this.id?e:this.operationError(e);try{this.options.onError?.(t)}catch{}}finishFailedIncomingOperation(e){this.reportOperationError(e);try{this.options.session.terminate()}catch(t){e={operation:e,cleanup:t}}this.transitionIfStillRinging(`ended`,{reason:`incoming_operation_failed`,cause:e})}cleanupSessionListeners(){this.sessionUnsubscribers.splice(0).forEach(e=>{try{e()}catch{}})}assertState(e){if(this.currentState!==e)throw this.operationError()}assertMediaControlAllowed(){if(this.currentState!==`active`&&this.currentState!==`held`)throw this.operationError()}assertHoldCapability(){if(this.platform===`mobile-web`)throw this.capabilityError()}assertTransferCapability(){if(this.platform===`mobile-web`)throw this.capabilityError()}assertIncomingCall(){if(this.options.incoming!==!0||this.currentState!==`ringing`)throw this.operationError()}assertIncomingOperationAvailable(){if(this.incomingOperation!==void 0)throw this.operationError()}assertCapability(e){if(!this.capabilities.has(e))throw this.capabilityError()}invoke(e){try{e()}catch(e){throw this.operationError(e)}}assertNotDisposed(){if(this.disposed)throw this.operationError()}assertOwner(e){if(e!==void 0&&(this.ownerLost||this.ownerTabId!==void 0&&this.ownerTabId!==e))throw this.operationError()}capabilityError(){return new m(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:this.id})}operationError(e){return new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:this.id,cause:e})}};function T(e){return e===`ended`||e===`failed`}function E(e){return typeof e==`object`&&!!e&&e.type===`blind`&&typeof e.target==`string`}var D=0;function te(){return D+=1,`call_${Date.now().toString(36)}_${D.toString(36)}`}h();var ne=`X-User-Data`,O=/[^\x20-\x7E]/,re=`userdata 只能是可见 ASCII(不能有换行/制表/中文):换行会构成 SIP 头注入;要传中文或 JSON 请调用方先 encodeURIComponent / base64,再在平台侧解回来`;function ie(e){if(typeof e!=`string`)return[];let t=e.trim();if(t===``)return[];if(O.test(t))throw new m(`CALL_INVALID_USERDATA`,`call`,!1,{cause:re});return[`${ne}: ${t}`]}h();var ae=class{events=new oe;calls=new Map;options;incomingUnsubscribe;activeCallId=null;incomingSessionSnapshot;callSessions=new Map;callOwners=new Map;ownerLostCalls=new Set;pendingDialCount=0;pendingDestinations=new Set;activeOperationPromise=Promise.resolve();operationGeneration=0;automaticActiveTransition;disposed=!1;terminalNotified=new Set;terminalOperations=new Map;disposeOperation;constructor(e){this.options=e,this.incomingSessionSnapshot=e.session;try{this.incomingUnsubscribe=e.sip.onIncoming(e=>this.handleIncoming(e))}catch(e){throw new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}}on(e,t){return this.disposed?()=>void 0:this.events.on(e,t)}async dial(e,t){this.assertNotDisposed();let n=this.operationGeneration,r=e.destination.trim();if(r===``)throw new m(`CALL_INVALID_DESTINATION`,`call`,!1);let i=/^\+?\d{3,20}$/.test(r),a=/^sips?:[^\s<>@]+(?:@[^\s<>@]+)?$/i.test(r);if(!i&&!a)throw new m(`CALL_INVALID_DESTINATION`,`call`,!1);let o=ie(e.userdata);this.requireCapability(t,`outbound`);let s=this.callLimit(t);if(this.options.platform===`mobile-web`&&this.calls.size+this.pendingDialCount>=s)throw this.capabilityError();if(this.calls.size+this.pendingDialCount>=s||this.pendingDestinations.has(r)||[...this.calls.values()].some(e=>e.destination===r))throw new m(`CALL_ALREADY_EXISTS`,`call`,!1);this.pendingDialCount+=1,this.pendingDestinations.add(r);let c=te(),l;try{l=await this.holdActiveCallForNewCall(),this.assertGeneration(n,c);let i;try{i=this.options.sip.dial(r,this.dialOptions(c,t,e.type,o))}catch(e){throw this.dialError(e,c)}this.assertGeneration(n,c);let a;try{a=new ee({id:c,destination:r,platform:this.options.platform,capabilities:this.effectiveCapabilities(t),session:i,onStateChanged:(e,t)=>this.handleStateChanged(a,e,t),onError:e=>this.events.emit(`error`,{error:e}),onDisposed:()=>this.handleDisposed(a)})}catch(e){throw this.dialError(e,c)}if(!this.isCurrentGeneration(n))throw a.dispose(),this.callOperationError(a.id);this.calls.set(a.id,a),this.callSessions.set(a.id,i),this.options.onCallCreated?.(a.id,i);try{a.beginOutbound()}catch(e){throw a.dispose(),this.calls.delete(a.id),this.callSessions.delete(a.id),this.dialError(e,a.id)}if(!this.isCurrentGeneration(n))throw a.dispose(),this.calls.delete(a.id),this.callSessions.delete(a.id),this.callOperationError(a.id);return this.events.emit(`call.created`,{callId:a.id,state:a.state}),a}catch(e){if(this.isCurrentGeneration(n)&&l!==void 0&&this.isManagedCall(l)&&l.state===`held`)try{await l.resume()}catch(t){throw this.compensationError(l.id,void 0,e,t)}throw e}finally{--this.pendingDialCount,this.pendingDestinations.delete(r)}}async answer(e,t,n,r){this.assertNotDisposed();let i=this.requireCall(e);if(this.options.platform===`mobile-web`&&t.policy.mobileIncomingEnabled!==!0)throw this.capabilityError(e);let a={iceServers:t.iceServers,pcConfig:{iceServers:t.iceServers},...n===void 0?{}:{mediaConstraints:n}};await i.answer(a,r)}async reject(e,t,n){this.assertNotDisposed(),await this.requireCall(e).reject(t,n)}getCalls(){return[...this.calls.values()]}hasNonTerminalCalls(){return this.calls.size>0}getResourceCounts(){let e=[...this.calls.values()].map(e=>e.getResourceCounts());return{timers:e.reduce((e,t)=>e+t.timers,0),listeners:this.events.listenerCount()+e.reduce((e,t)=>e+t.listeners,0),terminalRecords:this.terminalNotified.size+this.terminalOperations.size}}getActiveCall(){return this.activeCallId===null?void 0:this.calls.get(this.activeCallId)}async setActiveCall(e,t){this.assertNotDisposed(),this.requireCall(e).assertOwnerForManager(t),await this.enqueueActiveOperation(t=>this.switchActiveCall(e,t))}async claimCall(e,t){this.assertNotDisposed();let n=t.trim();if(n===``)throw this.callOperationError(e);let r=this.requireCall(e),i=this.callOwners.get(e);if(i!==n){if(i!==void 0||this.ownerLostCalls.has(e)&&!r.canBeReclaimed())throw this.callOperationError(e);this.ownerLostCalls.delete(e),this.callOwners.set(e,n),r.setOwnerTabId(n),this.emitOwnershipChanged({callId:e,state:`owned`,ownerTabId:n})}}async releaseCall(e,t){this.assertNotDisposed();let n=this.requireCall(e);if(this.callOwners.get(e)!==t)throw this.callOperationError(e);this.callOwners.delete(e);let r=!n.canBeReclaimed();r?this.ownerLostCalls.add(e):this.ownerLostCalls.delete(e),n.clearOwnerTabId({lost:r}),this.emitOwnershipChanged({callId:e,state:r?`owner-lost`:`released`})}getCallOwner(e){return this.callOwners.get(e)}releaseOwnedCalls(e){for(let[t,n]of[...this.callOwners.entries()]){if(n!==e)continue;let r=this.calls.get(t);if(r===void 0){this.callOwners.delete(t),this.ownerLostCalls.delete(t);continue}this.callOwners.delete(t);let i=!r.canBeReclaimed();i?this.ownerLostCalls.add(t):this.ownerLostCalls.delete(t),r.clearOwnerTabId({lost:i}),this.emitOwnershipChanged({callId:t,state:i?`owner-lost`:`released`})}}dispose(e={}){if(this.disposeOperation!==void 0)return this.disposeOperation;this.disposed=!0,this.operationGeneration+=1,this.automaticActiveTransition=void 0,this.activeOperationPromise=Promise.resolve(),this.events.clear();try{this.incomingUnsubscribe()}catch{}this.activeCallId=null;let t=[...this.calls.values()];this.calls.clear(),this.callSessions.clear(),this.callOwners.clear(),this.ownerLostCalls.clear();let n=Promise.all(t.map(async t=>{let n;try{e.terminateCalls===!0&&t.state!==`ended`&&t.state!==`failed`?await t.hangup():t.dispose()}catch(e){n=e,t.dispose()}try{await this.notifyCallTerminal(t.id)}catch(e){n??=e}if(n!==void 0)throw n})).finally(()=>{this.terminalNotified.clear(),this.terminalOperations.clear()}).then(()=>void 0);return this.disposeOperation=n,n}updateSession(e){this.disposed||(this.incomingSessionSnapshot=e)}async switchActiveCall(e,t){this.assertGeneration(t,e);let n=this.requireCall(e),r=this.getActiveCall();if(r?.id===n.id)return;if(n.state!==`held`&&n.state!==`active`)throw this.callOperationError(e);let i=n.state===`held`;try{if(r!==void 0&&await r.hold(),this.assertGeneration(t,n.id),n.state===`held`&&await n.resume(),this.assertGeneration(t,n.id),!this.isManagedCall(n)||n.state!==`active`)throw this.callOperationError(n.id);this.commitActive(n,t)}catch(a){if(!this.isCurrentGeneration(t))throw this.callOperationError(n.id,a);if(r===void 0)throw this.callOperationError(e,a);try{let e=n.state===`active`;i&&e&&this.isManagedCall(n)&&await n.hold(),this.assertGeneration(t,n.id),r.state===`held`&&this.isManagedCall(r)&&await r.resume(),this.assertGeneration(t,r.id),r.state===`active`&&this.isManagedCall(r)&&this.commitActive(r,t)}catch(e){throw this.compensationError(r.id,n.id,a,e)}throw this.isManagedCall(r)&&r.state===`active`&&this.commitActive(r,t),this.callOperationError(n.id,{operation:a,restoredCallId:r.id})}}handleStateChanged(e,t,n){if(this.disposed)return;let r=this.callSessions.get(e.id);if(r!==void 0&&this.options.onCallStateChanged?.(e.id,r),this.events.emit(`call.stateChanged`,t),t.to===`active`&&this.activeCallId!==e.id){let t=this.getActiveCall();if(this.options.autoHoldPreviousCall===!0&&t!==void 0&&t.id!==e.id&&t.state===`active`){let n=this.operationGeneration;this.enqueueActiveOperation(n=>this.switchAutomaticActiveCall(t,e,n)).catch(e=>{this.isCurrentGeneration(n)&&this.events.emit(`error`,{error:e})})}else this.commitActive(e)}t.to===`held`&&this.activeCallId===e.id&&this.automaticActiveTransition?.previous.id!==e.id&&(this.activeCallId=null,this.events.emit(`call.activeChanged`,{callId:null})),(t.to===`ended`||t.to===`failed`)&&(this.calls.delete(e.id),this.callSessions.delete(e.id),this.callOwners.delete(e.id),this.ownerLostCalls.delete(e.id),this.activeCallId===e.id&&this.automaticActiveTransition?.previous.id!==e.id&&(this.activeCallId=null,this.events.emit(`call.activeChanged`,{callId:null})),this.notifyCallTerminal(e.id),t.to===`ended`?this.events.emit(`call.ended`,{callId:e.id,reason:se(n)}):this.events.emit(`call.failed`,{callId:e.id,error:k(n,e.id)}))}async switchAutomaticActiveCall(e,t,n){this.automaticActiveTransition={previous:e,target:t};let r;try{if(this.assertGeneration(n,t.id),!this.isManagedCall(t)||t.state!==`active`)return;if(!this.isManagedCall(e)||e.state!==`active`){this.commitActive(t,n);return}if(await e.hold(),this.assertGeneration(n,t.id),!this.isManagedCall(e)){this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,n);return}if(!this.isManagedCall(t)||t.state!==`active`)r=Error(`target call is no longer active`);else{this.commitActive(t,n);return}}catch(e){r=e}finally{this.automaticActiveTransition?.target.id===t.id&&(this.automaticActiveTransition=void 0)}if(!this.isCurrentGeneration(n))return;if(!this.isManagedCall(e)){this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,n);return}let i=await this.restoreAutomaticActiveCall(e,t,r,n);if(this.isCurrentGeneration(n)){if(i.error!==void 0)throw i.error;if(!this.isManagedCall(e)){this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,n);return}throw this.callOperationError(t.id,{operation:r,restoredCallId:e.id})}}async restoreAutomaticActiveCall(e,t,n,r){if(!this.isCurrentGeneration(r))return{};if(!this.isManagedCall(e))return this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,r),{};let i;try{this.isManagedCall(t)&&t.state===`active`&&await t.hold(),this.assertGeneration(r,t.id),this.isManagedCall(e)&&e.state===`held`&&await e.resume(),this.assertGeneration(r,e.id)}catch(e){i=e}return this.isCurrentGeneration(r)?this.isManagedCall(e)?i===void 0?(e.state===`active`&&this.commitActive(e,r),{}):{error:this.compensationError(e.id,t.id,n,i)}:(this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,r),{}):{}}handleDisposed(e){this.disposed||(this.calls.delete(e.id),this.callSessions.delete(e.id),this.callOwners.delete(e.id),this.ownerLostCalls.delete(e.id),this.notifyCallTerminal(e.id),this.activeCallId===e.id&&(this.activeCallId=null,this.events.emit(`call.activeChanged`,{callId:null})))}commitActive(e,t=this.operationGeneration){this.isCurrentGeneration(t)&&this.isManagedCall(e)&&e.state===`active`&&this.activeCallId!==e.id&&(this.activeCallId=e.id,this.events.emit(`call.activeChanged`,{callId:e.id}))}handleIncoming(e){if(this.disposed)return;let t=te(),n=this.incomingSessionSnapshot;if(n===void 0||!n.policy.incomingEnabled||!this.effectiveCapabilities(n).has(`inbound`)){this.terminateUnsupportedIncoming(e),this.events.emit(`error`,{error:this.capabilityError(t)});return}let r=e.from??e.id;if(this.calls.size+this.pendingDialCount>=this.callLimit(n)){this.terminateUnsupportedIncoming(e),this.events.emit(`error`,{error:new m(`CALL_ALREADY_EXISTS`,`call`,!1,{callId:t})});return}let i;try{i=new ee({id:t,destination:r,platform:this.options.platform,incoming:!0,capabilities:this.effectiveCapabilities(n),session:e,onStateChanged:(e,t)=>this.handleStateChanged(i,e,t),onError:e=>this.events.emit(`error`,{error:e}),onDisposed:()=>this.handleDisposed(i)})}catch(e){this.events.emit(`error`,{error:this.callOperationError(t,e)});return}this.calls.set(i.id,i),this.callSessions.set(i.id,e),this.options.onCallCreated?.(i.id,e);try{i.beginIncoming(),this.events.emit(`call.incoming`,{callId:i.id,from:r})}catch(e){i.dispose(),this.events.emit(`error`,{error:this.callOperationError(i.id,e)})}}terminateUnsupportedIncoming(e){try{e.terminate()}catch{}}async holdActiveCallForNewCall(){if(this.options.autoHoldPreviousCall!==!0)return;let e=this.getActiveCall();if(e!==void 0&&e.state===`active`)return await e.hold(),e}enqueueActiveOperation(e){let t=this.operationGeneration,n=()=>this.isCurrentGeneration(t)?e(t):Promise.reject(this.callOperationError(``)),r=this.activeOperationPromise.then(n,n);return this.activeOperationPromise=r.catch(()=>void 0),r}isManagedCall(e){return!this.disposed&&this.calls.get(e.id)===e&&e.state!==`ended`&&e.state!==`failed`}isCurrentGeneration(e){return!this.disposed&&this.operationGeneration===e}assertGeneration(e,t){if(!this.isCurrentGeneration(e))throw this.callOperationError(t??``)}effectiveCapabilities(e){let t=new Set(e.capabilities);return this.options.platform===`mobile-web`&&(t.delete(`hold`),t.delete(`blind_transfer`),e.policy.mobileIncomingEnabled!==!0&&t.delete(`inbound`)),t}requireCapability(e,t,n){if(!this.effectiveCapabilities(e).has(t))throw this.capabilityError(n)}requireCall(e){let t=this.calls.get(e);if(t===void 0)throw this.callOperationError(e);return t}emitOwnershipChanged(e){this.events.emit(`call.ownershipChanged`,e)}notifyCallTerminal(e){let t=this.terminalOperations.get(e);if(t!==void 0)return t;if(this.terminalNotified.has(e))return Promise.resolve();this.terminalNotified.add(e);let n;try{n=this.options.onCallTerminal?.(e)}catch(t){this.events.emit(`error`,{error:this.callOperationError(e,t)});let n=Promise.reject(this.callOperationError(e,t));return this.terminalOperations.set(e,n),n.catch(()=>void 0).finally(()=>this.pruneTerminalRecord(e,n)),n}let r=Promise.resolve(n).catch(t=>{throw this.events.emit(`error`,{error:this.callOperationError(e,t)}),t});return this.terminalOperations.set(e,r),r.catch(()=>void 0).finally(()=>this.pruneTerminalRecord(e,r)),r}pruneTerminalRecord(e,t){this.terminalOperations.get(e)===t&&this.terminalOperations.delete(e),this.calls.has(e)||this.terminalNotified.delete(e)}assertNotDisposed(){if(this.disposed)throw new m(`SDK_ALREADY_DISPOSED`,`internal`,!1)}callOperationError(e,t){return new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e,cause:t})}capabilityError(e){return new m(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:e})}compensationError(e,t,n,r){return this.callOperationError(e,{operation:n,rollback:r,originalCallId:e,targetCallId:t})}callLimit(e){let t=this.options.platform===`mobile-web`?1:2,n=this.options.maxConcurrentCalls??t;return Math.min(t,Math.max(1,n),Math.max(1,e.policy.maxConcurrentCalls))}dialOptions(e,t,n,r=[]){return{iceServers:t.iceServers,extraHeaders:[`X-XCall-Call-ID: ${e}`,`X-XCall-Session-ID: ${t.sessionId}`,...r],...n===void 0?{}:{type:n}}}dialError(e,t){return e instanceof m?new m(e.code,e.category,e.retryable,{requestId:e.requestId,callId:t,cause:e.cause??e,serverCode:e.serverCode,platformCode:e.platformCode,status:e.status}):new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t,cause:e})}},oe=class{handlers=new Map;on(e,t){let n=this.handlers.get(e)??new Set,r=t;n.add(r),this.handlers.set(e,n);let i=!0;return()=>{i&&(i=!1,n.delete(r))}}emit(e,t){let n=this.handlers.get(e);n!==void 0&&[...n].forEach(e=>{try{e(t)}catch{}})}listenerCount(){return[...this.handlers.values()].reduce((e,t)=>e+t.size,0)}clear(){this.handlers.clear()}};function se(e){if(typeof e!=`object`||!e||!(`reason`in e))return`ended`;let t=e.reason;return typeof t==`string`&&t!==``?t:`ended`}function k(e,t){if(e instanceof m)return new m(e.code,e.category,e.retryable,{requestId:e.requestId,callId:t,cause:e.cause??e,serverCode:e.serverCode,platformCode:e.platformCode,status:e.status});if(typeof e==`object`&&e&&`error`in e){let n=e.error;if(n instanceof m)return new m(n.code,n.category,n.retryable,{requestId:n.requestId,callId:t,cause:n.cause??n,serverCode:n.serverCode,platformCode:n.platformCode,status:n.status});if(n instanceof Error)return new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t,cause:n})}return new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t,cause:e})}h();var ce=`q7X4p6MvK1z8Lb3A`,le=`W9e2T4mN0aQ7Ru6C`,ue=16,de=`�`;function A(e){for(let t of e){let e=t.codePointAt(0)??0;if(e===127||e<32&&e!==9)return!0}return!1}async function j(e,t={}){let n=String(e??``).replace(/\s+/g,``);if(!n)throw new m(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`解密的密文为空:坐席账号里没有 password/registerPassword`});let r=t.subtle??globalThis.crypto?.subtle;if(r===void 0)throw new m(`CONFIG_INVALID`,`configuration`,!1,{cause:`需要 WebCrypto 才能解 SIP 密码:请在安全上下文(https / localhost)或 Node 18+ 里运行`});let i=he(n);if(i===void 0)throw new m(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`密文不是合法的 Base64:确认取的是 password/registerPassword 原值,没有被截断或转义`});let a=await r.importKey(`raw`,ge(t.key??ce),`AES-CBC`,!1,[`decrypt`]);try{let e=await r.decrypt({name:`AES-CBC`,iv:ge(t.iv??le)},a,i);return new TextDecoder(`utf-8`).decode(e).trim()}catch(e){throw new m(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`SIP 密码解密失败(检查 key/iv 与该环境是否一致):${e instanceof Error?e.message:String(e)}`})}}async function fe(e,t={}){let n=String(e??``).replace(/\s+/g,``);if(pe(n))try{let e=await j(n,t);return me(e)?e:void 0}catch{return}}function pe(e){let t=he(e);return t!==void 0&&t.byteLength>0&&t.byteLength%ue===0}function me(e){return e.length===0||e.includes(de)?!1:!A(e)}function he(e){if(e.length!==0&&e.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(e))try{let t=atob(e),n=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}catch{return}}function ge(e){let t=new TextEncoder().encode(e),n=new Uint8Array(new ArrayBuffer(t.byteLength));return n.set(t),n}var M=`3.1.16`,N=`[REDACTED]`,_e=/\bBearer\s+[^\s,;"'}]+/gi,P=/(\bAuthorization\s*[:=]\s*)Digest\s+[^\r\n]*/gi,ve=/(\bAuthorization\s*[:=]\s*)(?:(Bearer|Basic|Digest|Token)\s+)?[^\s,;"'}]+/gi,ye=/\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,be=/\b((?:sip|sips|turn|turns|ws|wss):(?:\/\/)?)[^/?#@\s:]+:[^/?#@\s]+@/gi,xe=/(\b(?:sip(?:Register)?Ticket|registerTicket|wssTicket|turnCredential|credential|accessToken|refreshToken|appSecret|password|jwt|ticket)\b\s*[:=]\s*)(["']?)([^\s,;&}"']+)(["']?)/gi,Se=/(?<!\d)(1[3-9]\d)\d{4}(\d{4})(?!\d)/g,Ce=/(?:authorization|token|ticket|credential|password|secret)$/i;function we(e,t={}){let n=e.replace(_e,`Bearer ${N}`).replace(P,(e,t)=>`${t}Digest ${N}`).replace(ve,(e,t,n)=>`${t}${n===void 0?``:`${n} `}${N}`).replace(ye,N).replace(be,(e,t)=>`${t}${N}@`).replace(xe,(e,t)=>`${t}${N}`);return t.maskPhoneNumbers!==!1&&(n=n.replace(Se,`$1****$2`)),n}function Te(e,t={}){return Ee(e,t,new WeakSet)}function Ee(e,t,n){if(typeof e==`string`)return we(e,t);if(typeof e!=`object`||!e)return e;if(n.has(e))return`[Circular]`;if(n.add(e),Array.isArray(e))return e.map(e=>Ee(e,t,n));let r={};return Object.entries(e).forEach(([e,i])=>{r[e]=Ce.test(e)?N:Ee(i,t,n)}),r}h();function De(e){if(!ke(e))throw F(`Invalid worker message`);if(e.version!==1)throw F(`Unsupported worker protocol version`);if(e.type===`attach`||e.type===`detach`)return Oe(e),e;if(e.type===`command`){if(Oe(e),typeof e.command!=`string`||e.payload!==void 0&&!ke(e.payload))throw F(`Invalid worker command`);return e}if(e.type===`response`){if(typeof e.requestId!=`string`||typeof e.ok!=`boolean`)throw F(`Invalid worker response`);return e}if(e.type===`event`){if(typeof e.event!=`string`||!(`payload`in e))throw F(`Invalid worker event`);return e}throw F(`Unknown worker message type`)}function Oe(e){if(typeof e.requestId!=`string`||typeof e.tabId!=`string`)throw F(`Worker request requires requestId and tabId`)}function ke(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function F(e){return new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}h();var Ae=class{port;timeoutMs;pending=new Map;eventHandlers=new Set;closed=!1;lifecycleState=`connected`;constructor(e,t={}){this.port=e,this.timeoutMs=t.timeoutMs??15e3,this.port.onmessage=e=>this.handleMessage(e.data),this.port.start()}request(e){return this.closed?Promise.reject(new m(`SDK_ALREADY_DISPOSED`,`internal`,!1)):this.pending.has(e.requestId)?Promise.reject(new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{requestId:e.requestId})):this.lifecycleState===`reconnecting`&&e.type===`command`&&(e.command===`dial`||e.command===`answer`)?Promise.reject(new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!0,{callId:e.payload?.callId})):new Promise((t,n)=>{let r=setTimeout(()=>{this.pending.delete(e.requestId),n(new m(`NETWORK_TIMEOUT`,`network`,!0,{requestId:e.requestId}))},this.timeoutMs);this.pending.set(e.requestId,{resolve:e=>t(e),reject:n,timer:r}),this.port.postMessage(e)})}onEvent(e){return this.closed?()=>void 0:(this.eventHandlers.add(e),()=>this.eventHandlers.delete(e))}getLifecycleState(){return this.lifecycleState}close(){this.closed||(this.closed=!0,this.pending.forEach(e=>{clearTimeout(e.timer),e.reject(new m(`SDK_ALREADY_DISPOSED`,`internal`,!1))}),this.pending.clear(),this.eventHandlers.clear(),this.port.close())}handleMessage(e){try{let t=De(e);if(t.type===`event`){t.event===`connection.stateChanged`&&je(t.payload)&&(this.lifecycleState=t.payload.state),this.eventHandlers.forEach(e=>e(t));return}if(t.type!==`response`)return;let n=this.pending.get(t.requestId);if(n===void 0)return;this.pending.delete(t.requestId),clearTimeout(n.timer),t.ok?n.resolve(t.result):n.reject(Me(t))}catch(e){this.pending.forEach(t=>{clearTimeout(t.timer),t.reject(e)}),this.pending.clear()}}};function je(e){return typeof e==`object`&&!!e&&`state`in e&&(e.state===`connected`||e.state===`reconnecting`)}function Me(e){let t=e.error;return new m(t?.code??`SDK_INTERNAL_ERROR`,t?.category??`internal`,t?.retryable??!1,{requestId:e.requestId,...t?.message===void 0?{}:{cause:t.message},...t?.serverCode===void 0?{}:{serverCode:t.serverCode},...t?.platformCode===void 0?{}:{platformCode:t.platformCode},...t?.status===void 0?{}:{status:t.status}})}h();function I(e={}){if((e.enabled??`auto`)===!1)return{mode:`single-tab`,reason:`disabled`};let t=e.locationHref??Ne(),n=L(e.url,t),r=t=>{if(e.fallback===`error`)throw new m(`CONFIG_INVALID`,`configuration`,!1,{cause:t});return{mode:`single-tab`,reason:t}};if(n===void 0)return r(`SharedWorker URL is unavailable`);if(!Fe(n,t))return r(`SharedWorker URL must be same-origin`);let i=e.workerCtor??Pe();if(i===void 0)return r(`SharedWorker is not supported`);let a;try{a=new i(n,e.name===void 0?void 0:{name:e.name})}catch(e){return r(`SharedWorker construction failed: ${e instanceof Error?e.message:String(e)}`)}let o=e.tabId??Ie(),s=new Ae(a.port),c={version:1,type:`attach`,requestId:Le(),tabId:o},l=s.request(c).then(()=>void 0).catch(e=>{throw s.close(),e});return{mode:`shared`,worker:a,client:s,tabId:o,workerUrl:n,ready:l}}function L(e,t=Ne()){try{return t===void 0?void 0:new URL(e??`./shared-worker.js`,t).toString()}catch{return}}function Ne(){return typeof location>`u`?void 0:location.href}function Pe(){if(typeof SharedWorker==`function`)return SharedWorker}function Fe(e,t){if(t===void 0)return!0;try{return new URL(e,t).origin===new URL(t).origin}catch{return!1}}function Ie(){return`tab-${typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():Math.random().toString(36).slice(2)}`}function Le(){return`attach-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}h();var Re=class{mediaDevices;createAudioElement;outputCapability;outputDeviceId;outputGeneration=0;outputTail;constructor(e={}){this.mediaDevices=e.mediaDevices===null?void 0:e.mediaDevices??ze(),this.createAudioElement=e.createAudioElement}async requestPermission(e={}){let t=this.requireMediaDevices(),n;try{n=await t.getUserMedia({audio:e})}catch(e){throw He(e)}Be(n)}async getDevices(){if(this.mediaDevices===void 0)return[];try{return(await this.mediaDevices.enumerateDevices()).filter(e=>e.kind===`audioinput`||e.kind===`audiooutput`&&this.supportsOutputSelection())}catch(e){throw Ue(e)}}getCapabilities(){return{input:this.mediaDevices!==void 0,output:this.supportsOutputSelection()}}supportsOutputSelection(){if(this.outputCapability!==void 0)return this.outputCapability;let e=this.createAudioElementSafely();return this.outputCapability=e!==void 0&&typeof e.setSinkId==`function`,this.outputCapability}async setOutputDevice(e,t){if(!this.supportsOutputSelection())throw new m(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);this.outputDeviceId=e;let n=++this.outputGeneration;t!==void 0&&await this.enqueueOutput(async()=>{n===this.outputGeneration&&await this.applyOutputDevice(e,t)})}async applyConfiguredOutputDevice(e){if(this.outputDeviceId===void 0||e===void 0)return;let t=this.outputDeviceId,n=this.outputGeneration;await this.enqueueOutput(async()=>{n===this.outputGeneration&&await this.applyOutputDevice(t,e)})}getOutputDeviceId(){return this.outputDeviceId}async applyOutputDevice(e,t){let n=t;if(typeof n.setSinkId!=`function`)throw new m(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);try{await n.setSinkId(e)}catch(e){throw We(e)}}enqueueOutput(e){let t=this.outputTail,n=t===void 0?e():t.then(e,e),r=n.catch(()=>void 0);return this.outputTail=r,r.then(()=>{this.outputTail===r&&(this.outputTail=void 0)}),n}async openInputStream(e){let t=this.requireMediaDevices();try{return await t.getUserMedia({audio:{deviceId:{exact:e}}})}catch(e){throw Ve(e)}}requireMediaDevices(){if(this.mediaDevices===void 0)throw new m(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);return this.mediaDevices}createAudioElementSafely(){if(this.createAudioElement!==void 0)try{return this.createAudioElement()}catch{return}if(typeof document<`u`)try{return document.createElement(`audio`)}catch{return}}};function ze(){return globalThis.navigator?.mediaDevices}function Be(e){let t;try{t=e.getTracks()}catch{return}t.forEach(e=>{try{e.stop()}catch{}})}function Ve(e){let t=Ge(e);return t===`NotFoundError`||t===`OverconstrainedError`?new m(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:e}):t===`NotReadableError`||t===`AbortError`?new m(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:e}):t===`NotAllowedError`||t===`SecurityError`?new m(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:e}):new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}function He(e){let t=Ge(e);return t===`NotFoundError`||t===`OverconstrainedError`?new m(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:e}):t===`NotReadableError`||t===`AbortError`?new m(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:e}):t===`NotAllowedError`||t===`SecurityError`?new m(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:e}):new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}function Ue(e){let t=Ge(e);return t===`NotFoundError`?new m(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:e}):t===`NotAllowedError`||t===`SecurityError`?new m(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:e}):t===`AbortError`||t===`NotReadableError`?new m(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:e}):new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}function We(e){let t=Ge(e);return t===`NotFoundError`?new m(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:e}):t===`NotAllowedError`||t===`SecurityError`?new m(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:e}):t===`AbortError`||t===`NotReadableError`?new m(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:e}):new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}function Ge(e){if(typeof e!=`object`||!e||!(`name`in e))return;let t=e.name;return typeof t==`string`?t:void 0}h();var Ke=class{createAudioElement;bindings=new Map;audioOwners=new Map;trackOwners=new Map;generations=new Map;pendingPlays=new Map;constructor(e=qe){this.createAudioElement=e}async bind(e,t){let n=this.bindings.get(e);if(n?.stream===t)return;let r=Je(e,t),i;try{i=this.createAudioElement()}catch(t){throw Ye(r,this.trackOwners),new m(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:e,cause:t})}let a=this.audioOwners.get(i);if(a!==void 0&&a!==e)throw Ye(r,this.trackOwners),new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e});try{i.autoplay=!0,i.playsInline=!0}catch(t){throw Ye(r,this.trackOwners),new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e,cause:t})}try{i.srcObject=t}catch(t){throw Ye(r,this.trackOwners),new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e,cause:t})}this.acquireTracks(r),n!==void 0&&this.releaseBinding(n,n.audio!==i);let o=this.nextGeneration(e);this.audioOwners.set(i,e);let s={callId:e,audio:i,stream:t,tracks:r,generation:o};this.bindings.set(e,s),this.beginPlay(e);try{await i.play()}catch(t){if(!this.isCurrent(e,o))return;throw new m(`MEDIA_PLAYBACK_BLOCKED`,`media`,!1,{callId:e,cause:t})}finally{this.finishPlay(e)}this.isCurrent(e,o)}async play(e){let t=this.bindings.get(e);if(t===void 0)throw new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e});let n=t.generation;this.beginPlay(e);try{await t.audio.play()}catch(t){if(!this.isCurrent(e,n))return;throw new m(`MEDIA_PLAYBACK_BLOCKED`,`media`,!1,{callId:e,cause:t})}finally{this.finishPlay(e)}this.isCurrent(e,n)}getAudioElement(e){return this.bindings.get(e)?.audio}getResourceCounts(){return{tracks:this.trackOwners.size,audioElements:this.audioOwners.size}}release(e){this.nextGeneration(e);let t=this.bindings.get(e);t!==void 0&&this.releaseBinding(t),this.cleanupGeneration(e)}releaseAll(){[...this.bindings.keys()].forEach(e=>this.release(e))}releaseBinding(e,t=!0){if(this.bindings.get(e.callId)===e&&this.bindings.delete(e.callId),this.audioOwners.get(e.audio)===e.callId&&this.audioOwners.delete(e.audio),t)try{e.audio.srcObject=null}catch{}e.tracks.forEach(e=>this.releaseTrack(e))}acquireTracks(e){e.forEach(e=>this.trackOwners.set(e,(this.trackOwners.get(e)??0)+1))}releaseTrack(e){let t=this.trackOwners.get(e);if(t===void 0||t<=1){this.trackOwners.delete(e),Ze(e);return}this.trackOwners.set(e,t-1)}beginPlay(e){this.pendingPlays.set(e,(this.pendingPlays.get(e)??0)+1)}finishPlay(e){let t=this.pendingPlays.get(e)??0;t<=1?this.pendingPlays.delete(e):this.pendingPlays.set(e,t-1),this.cleanupGeneration(e)}nextGeneration(e){let t=(this.generations.get(e)??0)+1;return this.generations.set(e,t),t}cleanupGeneration(e){!this.bindings.has(e)&&!this.pendingPlays.has(e)&&this.generations.delete(e)}isCurrent(e,t){return this.generations.get(e)===t&&this.bindings.get(e)?.generation===t}};function qe(){if(typeof document>`u`)throw new m(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);return document.createElement(`audio`)}function Je(e,t){try{return[...new Set(t.getAudioTracks())].filter(e=>e.kind===`audio`)}catch(n){try{return[...new Set(t.getTracks())].filter(e=>e.kind===`audio`)}catch(r){throw Xe(t),new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e,cause:n??r})}}}function Ye(e,t){e.forEach(e=>{(t.get(e)??0)===0&&Ze(e)})}function Xe(e){try{[...new Set(e.getTracks())].filter(e=>e.kind===`audio`).forEach(Ze)}catch{}}function Ze(e){try{e.stop()}catch{}}h();var Qe=class{deviceManager;remoteAudio;getActiveCall;createRemoteStream;calls=new Map;resources=new Set;inputOperations=new Map;senderQueues=new Map;releaseOperations=new Map;callReleaseOperations=new Map;releaseErrors=new WeakMap;releaseAllOperation;disposeOperation;disposing=!1;disposed=!1;constructor(e={}){let t={mediaDevices:e.mediaDevices,createAudioElement:e.createAudioElement};this.deviceManager=new Re(t),this.remoteAudio=new Ke(e.createAudioElement),this.getActiveCall=e.getActiveCall,this.createRemoteStream=e.createRemoteStream??it}requestPermission(e){return this.assertNotDisposed(),this.deviceManager.requestPermission(e)}getDevices(){return this.assertNotDisposed(),this.deviceManager.getDevices()}getCapabilities(){return this.assertNotDisposed(),this.deviceManager.getCapabilities()}supportsOutputSelection(){return this.assertNotDisposed(),this.deviceManager.supportsOutputSelection()}registerCallMedia(e,t){this.assertNotDisposed();let n=this.calls.get(e);n!==void 0&&this.releaseResource(n).catch(e=>{this.releaseErrors.set(n,e)});let r=$e(t)?t:{peerConnection:t},i={callId:e,peerConnection:r.peerConnection,senders:new Map,localTracks:new Set,pendingTracks:new Set,generation:1,released:!1,peerClosed:!1};if(this.captureSenders(i,r.getSenderKind),this.resources.add(i),r.localTracks?.forEach(e=>{e.kind===`audio`&&i.localTracks.add(e)}),this.calls.set(e,i),r.trackSource!==void 0)try{i.trackSourceUnsubscribe=r.trackSource.onTrack(e=>this.handleTrackEvent(i,e))}catch{}return async()=>{let e=this.releaseOperations.get(i);if(e!==void 0)await e;else if(this.releaseErrors.has(i))throw this.releaseErrors.get(i);else await this.releaseResource(i);let t=this.releaseErrors.get(i);if(t!==void 0)throw t}}async setInputDevice(e,t){this.assertNotDisposed();let n=t??this.getActiveCall?.();this.assertActiveCall(n),this.assertDeviceSelectionCapability(n);let r=this.ensureCallMedia(n),i=(this.inputOperations.get(n.callId)??Promise.resolve()).then(()=>this.performInputSwitch(e,n,r),()=>this.performInputSwitch(e,n,r));this.inputOperations.set(n.callId,i);try{await i}finally{this.inputOperations.get(n.callId)===i&&this.inputOperations.delete(n.callId)}}setOutputDevice(e,t){this.assertNotDisposed();let n=t??this.getActiveCall?.()?.callId,r=n===void 0?void 0:this.remoteAudio.getAudioElement(n);return this.deviceManager.setOutputDevice(e,r)}async bindRemoteTrack(e,t){this.assertNotDisposed();let n;try{await this.remoteAudio.bind(e,t)}catch(e){n=e}let r;try{await this.deviceManager.applyConfiguredOutputDevice(this.remoteAudio.getAudioElement(e))}catch(e){r=e}if(n!==void 0)throw n;if(r!==void 0)throw r}playRemoteAudio(e){return this.assertNotDisposed(),this.remoteAudio.play(e)}getResourceCounts(){let e=new Set;this.resources.forEach(t=>{t.localTracks.forEach(t=>e.add(t)),t.pendingTracks.forEach(t=>e.add(t))});let t=this.remoteAudio.getResourceCounts();return{listeners:[...this.resources].filter(e=>e.trackSourceUnsubscribe!==void 0).length,tracks:e.size+t.tracks,peerConnections:this.resources.size,audioElements:t.audioElements}}releaseResource(e){let t=this.releaseOperations.get(e);if(t!==void 0)return t;if(!this.resources.has(e))return Promise.resolve();let n=e.callId;this.remoteAudio.release(n),this.releaseErrors.delete(e),this.calls.get(n)===e&&this.calls.delete(n),e.generation+=1,e.released=!0,this.unsubscribeTrackSource(e);let r=new Set([...e.localTracks,...e.pendingTracks]),i=[...e.senders.values()].filter(e=>e.audio).map(t=>({senderResource:t,promise:this.enqueueSender(e,t,()=>tt(t.sender),!0)})),a=Promise.all(i.map(async e=>{try{return await e.promise,{senderResource:e.senderResource,cause:void 0}}catch(t){return{senderResource:e.senderResource,cause:t}}})).then(async t=>{let i=new Set,a=[];if(t.forEach(e=>{if(e.cause!==void 0){a.push(e.cause);let t=R(e.senderResource.sender);t?.kind===`audio`&&i.add(t);return}let t=R(e.senderResource.sender);t?.kind===`audio`&&r.add(t)}),r.forEach(e=>{i.has(e)||rt(e)}),a.length>0)throw e.localTracks.clear(),e.pendingTracks.clear(),i.forEach(t=>e.localTracks.add(t)),new m(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:n,cause:a[0]});if(!e.peerClosed&&e.peerConnection.close!==void 0)try{await e.peerConnection.close(),e.peerClosed=!0}catch(t){let r=[...e.senders.values()].map(e=>R(e.sender)).find(e=>e?.kind===`audio`);throw e.localTracks.clear(),e.pendingTracks.clear(),r!=null&&e.localTracks.add(r),new m(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:n,cause:t})}e.localTracks.clear(),e.pendingTracks.clear(),e.senders.clear(),this.resources.delete(e),this.releaseUnusedSenderQueues()}).catch(t=>{throw this.releaseErrors.set(e,t),this.calls.get(n)===void 0&&this.calls.set(n,e),t}).finally(()=>{this.releaseOperations.get(e)===a&&this.releaseOperations.delete(e)});return this.releaseOperations.set(e,a),a}releaseCall(e){let t=this.callReleaseOperations.get(e);if(t!==void 0)return t;let n=[...this.resources].filter(t=>t.callId===e);if(n.length===0)return Promise.resolve();let r=Promise.all(n.map(async e=>{try{return await this.releaseResource(e),{cause:void 0}}catch(e){return{cause:e}}})).then(e=>{let t=e.find(e=>e.cause!==void 0)?.cause;if(t!==void 0)throw t}).finally(()=>{this.callReleaseOperations.get(e)===r&&this.callReleaseOperations.delete(e)});return this.callReleaseOperations.set(e,r),r}releaseAll(){if(this.releaseAllOperation!==void 0)return this.releaseAllOperation;this.remoteAudio.releaseAll();let e=new Set([...this.resources].map(e=>e.callId)),t=Promise.all([...e].map(async e=>{try{return await this.releaseCall(e),{cause:void 0}}catch(e){return{cause:e}}})).then(e=>{let t=e.find(e=>e.cause!==void 0)?.cause;if(t!==void 0)throw t}).finally(()=>{this.releaseAllOperation===t&&(this.releaseAllOperation=void 0)});return this.releaseAllOperation=t,t}dispose(){if(this.disposeOperation!==void 0)return this.disposeOperation;this.disposing=!0;let e=this.releaseAll(),t=this.waitForInputOperations(),n=Promise.allSettled([e,t]).then(e=>{let t=e.find(e=>e.status===`rejected`);if(t?.status===`rejected`)throw t.reason;this.inputOperations.clear(),this.disposed=!0,this.disposing=!1}).finally(()=>{this.disposeOperation===n&&!this.disposed&&(this.disposeOperation=void 0),!this.disposed&&this.disposeOperation===void 0&&(this.disposing=!1)});return this.disposeOperation=n,n}async waitForInputOperations(){let e=[...this.inputOperations.values()];e.length!==0&&await Promise.allSettled(e)}async performInputSwitch(e,t,n){if(this.assertActiveCall(t),this.assertDeviceSelectionCapability(t),!this.isCurrentResource(n)||t.peerConnection!==n.peerConnection)throw this.callOperationError(t.callId);let r=this.findAudioSender(n),i=R(r.sender),a=n.generation,o=await this.deviceManager.openInputStream(e),s;try{s=o.getTracks()}catch(e){throw nt(o),new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t.callId,cause:e})}let c;try{c=o.getAudioTracks()}catch(e){throw z(s),new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t.callId,cause:e})}let l=c[0];if(l===void 0)throw z(s),new m(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{callId:t.callId});if(!this.canCommitInputSwitch(t,n,r,i,a))throw z(s),this.callOperationError(t.callId);s.forEach(e=>n.pendingTracks.add(e)),n.pendingTracks.add(l);try{await this.enqueueSender(n,r,()=>r.sender.replaceTrack(l))}catch(e){throw n.released?this.callOperationError(t.callId):(n.released||(s.forEach(e=>n.pendingTracks.delete(e)),n.pendingTracks.delete(l),await this.rollbackSender(n,r,i,l),z(s)),new m(`MEDIA_DEVICE_IN_USE`,`media`,!0,{callId:t.callId,cause:e}))}if(!this.canCommitInputSwitch(t,n,r,l,a)){if(!n.released)try{await this.enqueueSender(n,r,()=>R(r.sender)===l?tt(r.sender):Promise.resolve()),s.forEach(e=>n.pendingTracks.delete(e)),n.pendingTracks.delete(l),z(s)}catch(e){throw new m(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:t.callId,cause:e})}throw this.callOperationError(t.callId)}s.forEach(e=>n.pendingTracks.delete(e)),n.pendingTracks.delete(l),n.localTracks.add(l),i!==null&&i!==l&&(n.localTracks.delete(i),rt(i)),s.forEach(e=>{e!==l&&rt(e)})}ensureCallMedia(e){let t=this.calls.get(e.callId);if(t!==void 0&&t.peerConnection===e.peerConnection)return t;if(e.peerConnection===void 0)throw this.capabilityError(e.callId);this.registerCallMedia(e.callId,e.peerConnection);let n=this.calls.get(e.callId);if(n===void 0)throw this.callOperationError(e.callId);return n}captureSenders(e,t){let n;try{n=e.peerConnection.getSenders()}catch(t){throw new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e.callId,cause:t})}n.forEach(n=>{let r=R(n),i;try{i=t?.(n)??n.senderKind??n.kind}catch(t){throw new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e.callId,cause:t})}e.senders.set(n,{sender:n,audio:i===`audio`||i===void 0&&r?.kind===`audio`,queue:this.senderQueues.get(n)??this.createSenderQueue(n)}),r?.kind===`audio`&&e.localTracks.add(r)})}findAudioSender(e){let t=[...e.senders.values()].find(e=>e.audio&&(R(e.sender)?.kind===`audio`||R(e.sender)===null));if(t===void 0)throw this.capabilityError(e.callId);return t}handleTrackEvent(e,t){if(!this.isCurrentResource(e)||t.track.kind!==`audio`)return;let n=t.streams[0]??this.createRemoteStream(t.track);n!==void 0&&this.bindRemoteTrack(e.callId,n).catch(()=>void 0)}canCommitInputSwitch(e,t,n,r,i){if(this.disposed||!this.isCurrentResource(t,i)||e.state!==`active`||e.peerConnection!==t.peerConnection||!t.senders.has(n.sender))return!1;try{if(!t.peerConnection.getSenders().includes(n.sender))return!1}catch{return!1}return R(n.sender)===r}enqueueSender(e,t,n,r=!1){t.queue.pending+=1;let i=t.queue.chain.then(async()=>{if(e.released&&!r)throw this.callOperationError(e.callId);return n()},async()=>{if(e.released&&!r)throw this.callOperationError(e.callId);return n()}),a=i.finally(()=>{--t.queue.pending});return t.queue.chain=a.catch(()=>void 0),i}createSenderQueue(e){let t={chain:Promise.resolve(),pending:0};return this.senderQueues.set(e,t),t}releaseUnusedSenderQueues(){let e=new Set;this.resources.forEach(t=>t.senders.forEach(t=>e.add(t.sender))),this.senderQueues.forEach((t,n)=>{t.pending===0&&!e.has(n)&&this.senderQueues.delete(n)})}async rollbackSender(e,t,n,r){e.released||R(t.sender)!==r||await this.enqueueSender(e,t,()=>t.sender.replaceTrack(n)).catch(()=>void 0)}isCurrentResource(e,t=e.generation){return!this.disposed&&this.calls.get(e.callId)===e&&e.generation===t}unsubscribeTrackSource(e){let t=e.trackSourceUnsubscribe;if(e.trackSourceUnsubscribe=void 0,t!==void 0)try{t()}catch{}}assertActiveCall(e){if(e===void 0||e.state!==`active`)throw new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e?.callId})}assertDeviceSelectionCapability(e){if(e.capabilities===void 0||!e.capabilities.has(`device_selection`))throw this.capabilityError(e.callId)}capabilityError(e){return new m(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:e})}callOperationError(e){return new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e})}assertNotDisposed(){if(this.disposed||this.disposing)throw new m(`SDK_ALREADY_DISPOSED`,`internal`,!1)}};function $e(e){return`peerConnection`in e}function R(e){try{return e.track}catch{return null}}function et(e){return typeof e==`object`&&!!e&&e.name===`InvalidStateError`}function tt(e){try{return e.replaceTrack(null).catch(e=>{if(!et(e))throw e})}catch(e){return et(e)?Promise.resolve():Promise.reject(e)}}function nt(e){try{z(e.getTracks())}catch{}}function z(e){e.forEach(rt)}function rt(e){try{e.stop()}catch{}}function it(e){if(typeof MediaStream<`u`)try{return new MediaStream([e])}catch{return}}h();function at(e,t={}){let n=new Map,r=new Map,i=new Set,a=t.ownershipRequired===!0,o=!1,s=!1,c,l=()=>e(),u=new Qe({getActiveCall:l});return{publicMedia:{requestPermission:()=>(d(),u.requestPermission()),getDevices:()=>(d(),u.getDevices()),getCapabilities:()=>(d(),u.getCapabilities()),supportsOutputSelection:()=>(d(),u.supportsOutputSelection()),setInputDevice:e=>(d(),u.setInputDevice(e,l())),setOutputDevice:e=>(d(),u.setOutputDevice(e)),playRemoteAudio:e=>(d(),u.playRemoteAudio(e)),releaseAll:()=>(d(),u.releaseAll())},registerCall(e,t){o||s||!ot(t)||(r.set(e,t),(!a||i.has(e))&&f(e,t))},async setCallOwnership(e,t){if(o)return;if(t!==`owned`){i.delete(e),await u.releaseCall(e),n.delete(e);return}i.add(e);let a=r.get(e);a!==void 0&&f(e,a)},contextFor(e,t,r){let i=n.get(e);if(i!==void 0)return{callId:e,state:t,capabilities:r,peerConnection:i.peerConnection}},async releaseCall(e){o||(await u.releaseCall(e),n.delete(e),r.delete(e),i.delete(e))},releaseAll:async()=>{await u.releaseAll(),n.clear(),r.clear(),i.clear()},getResourceCounts:()=>u.getResourceCounts(),dispose:()=>{if(c!==void 0)return c;s=!0;let e=u.dispose().then(()=>{o=!0,s=!1,n.clear(),r.clear(),i.clear()}).finally(()=>{c===e&&!o&&(c=void 0,s=!1)});return c=e,e}};function d(){if(o)throw new m(`SDK_ALREADY_DISPOSED`,`internal`,!1)}function f(e,t){if(!ot(t)||typeof t.getMediaRegistration!=`function`)return;let r=t.getMediaRegistration();if(st(r)&&n.get(e)?.peerConnection!==r.peerConnection){n.set(e,r);try{u.registerCallMedia(e,r)}catch{n.delete(e)}}}}function ot(e){return typeof e==`object`&&!!e}function st(e){return typeof e==`object`&&!!e&&`peerConnection`in e&&typeof e.peerConnection==`object`&&e.peerConnection!==null}var ct=1e3,lt=3e4;function ut(e,t=Math.random){let n=Math.min(lt,ct*2**Math.max(0,Math.floor(e))),r=Math.min(1,Math.max(0,t()));return Math.round(n*(1+r*.2))}var dt=class{recover;random;isOnline;onAttempt;attempt=0;pendingTimer;running=!1;online=!0;generation=0;disposed=!1;restartAfterRun=!1;constructor(e){this.recover=e.recover,this.random=e.random??Math.random,this.isOnline=e.isOnline??(()=>!0),this.onAttempt=e.onAttempt}start(){if(this.disposed||!this.online||!this.isOnline()||this.pendingTimer!==void 0||this.running)return;let e=this.generation,t=ut(this.attempt,this.random);this.pendingTimer=setTimeout(()=>{this.pendingTimer=void 0,this.run(e)},t)}notifyOffline(){this.disposed||(this.online=!1,this.generation+=1,this.clearPendingTimer(),this.restartAfterRun=!1)}notifyOnline(){this.disposed||(this.online=!0,this.running&&(this.restartAfterRun=!0),this.start())}cancel(){this.disposed||(this.generation+=1,this.clearPendingTimer(),this.attempt=0,this.restartAfterRun=!1)}dispose(){this.disposed||(this.disposed=!0,this.generation+=1,this.clearPendingTimer(),this.restartAfterRun=!1)}getTimerCount(){return this.pendingTimer===void 0?0:1}async run(e){if(this.disposed||!this.online||e!==this.generation||this.running)return;this.running=!0;try{this.onAttempt?.(this.attempt)}catch{}let t=!1;try{await this.recover(),this.isCurrent(e)&&(this.attempt=0)}catch{this.isCurrent(e)&&(this.attempt+=1,t=!0)}finally{this.running=!1}this.restartAfterRun?(this.restartAfterRun=!1,this.isCurrent(this.generation)&&this.start()):t&&this.isCurrent(e)&&this.start()}isCurrent(e){return!this.disposed&&this.online&&e===this.generation&&this.isOnline()}clearPendingTimer(){this.pendingTimer!==void 0&&(clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}},ft=class{capacity;entries=[];constructor(e){if(this.capacity=e,!Number.isInteger(e)||e<=0)throw RangeError(`RingBuffer capacity must be a positive integer`)}push(e){this.entries.length===this.capacity&&this.entries.shift(),this.entries.push(e)}toArray(){return[...this.entries]}},pt=`@16x/webphone-sdk`,mt=200,ht=class{dependencies;logs=new ft(mt);now;constructor(e){this.dependencies=e,this.now=e.now??(()=>new Date)}log(e,t,n){this.logs.push({timestamp:this.now().toISOString(),level:e,message:we(t),...n===void 0?{}:{context:Te(n)}})}async getReport(e={}){let t=e.includeRecentLogs!==!1,n=e.includeDeviceNames===!0,r=e.maskPhoneNumbers!==!1,i=this.dependencies.getSnapshot(),a=this.dependencies.getPermission===void 0?i.permission:await gt(this.dependencies.getPermission,i.permission),o=n?await _t(this.dependencies.getDeviceNames):void 0,s=yt(vt(this.dependencies.getUserAgent));return Te({generatedAt:this.now().toISOString(),sdk:{name:pt,version:M},browser:s.browser,os:s.os,...i,permission:a,recentLogs:t?this.logs.toArray():[],...o===void 0?{}:{deviceNames:o}},{maskPhoneNumbers:r})}};async function gt(e,t){try{return await e()}catch{return t}}async function _t(e){if(e===void 0)return[];try{return[...await e()]}catch{return[]}}function vt(e){if(e!==void 0)try{return e()}catch{return``}return typeof navigator>`u`?``:navigator.userAgent}function yt(e){return{browser:bt(e),os:xt(e)}}function bt(e){for(let[t,n]of[[`Edge`,/Edg\/([\d.]+)/],[`Chrome`,/(?:Chrome|CriOS)\/([\d.]+)/],[`Firefox`,/(?:Firefox|FxiOS)\/([\d.]+)/],[`Safari`,/Version\/([\d.]+).*Safari/]]){let r=e.match(n);if(r?.[1]!==void 0)return{name:t,version:r[1]}}return{name:`unknown`,version:``}}function xt(e){let t=e.match(/(?:iPhone|iPad).*OS ([\d_]+)/);if(t?.[1]!==void 0)return{name:`iOS`,version:t[1].replaceAll(`_`,`.`)};let n=e.match(/Android ([\d.]+)/);if(n?.[1]!==void 0)return{name:`Android`,version:n[1]};let r=e.match(/Windows NT ([\d.]+)/);if(r?.[1]!==void 0)return{name:`Windows`,version:r[1]};let i=e.match(/Mac OS X ([\d_]+)/);return i?.[1]===void 0?/Linux/.test(e)?{name:`Linux`,version:``}:{name:`unknown`,version:``}:{name:`macOS`,version:i[1].replaceAll(`_`,`.`)}}var St=l({bugs:()=>Nt,contributors:()=>Ot,default:()=>Lt,dependencies:()=>B,description:()=>Tt,devDependencies:()=>It,files:()=>Pt,homepage:()=>Dt,keywords:()=>jt,license:()=>`MIT`,main:()=>At,name:()=>Ct,repository:()=>Mt,scripts:()=>Ft,title:()=>wt,types:()=>kt,version:()=>Et}),Ct,wt,Tt,Et,Dt,Ot,kt,At,jt,Mt,Nt,Pt,Ft,B,It,Lt,Rt=s((()=>{Ct=`jssip`,wt=`JsSIP`,Tt=`The Javascript SIP library`,Et=`3.13.8`,Dt=`https://jssip.net`,Ot=[`José Luis Millán <jmillan@aliax.net> (https://github.com/jmillan)`,`Iñaki Baz Castillo <ibc@aliax.net> (https://inakibaz.me)`],kt=`lib/JsSIP.d.ts`,At=`lib/JsSIP.js`,jt=[`sip`,`websocket`,`webrtc`,`node`,`browser`,`library`],Mt={type:`git`,url:`https://github.com/versatica/JsSIP.git`},Nt={url:`https://github.com/versatica/JsSIP/issues`},Pt=[`LICENSE`,`README.md`,`npm-scripts.mjs`,`lib`],Ft={lint:`node npm-scripts.mjs lint`,"lint:fix":`node npm-scripts.mjs lint:fix`,test:`node npm-scripts.mjs test`,coverage:`node npm-scripts.mjs coverage`,build:`node npm-scripts.mjs build`,"typescript:build":`node npm-scripts.mjs typescript:build`,release:`node npm-scripts.mjs release`,docs:`node npm-scripts.mjs docs`,"docs:watch":`node npm-scripts.mjs docs:watch`,"docs:check":`node npm-scripts.mjs docs:check`},B={debug:`^4.3.1`,events:`^3.3.0`,"sdp-transform":`^2.14.1`},It={"@eslint/eslintrc":`^3.3.3`,"@eslint/js":`^9.39.2`,"@types/debug":`^4.1.12`,"@types/events":`^3.0.3`,"@types/jest":`^30.0.0`,"@types/node":`^25.0.10`,cpx:`^1.5.0`,esbuild:`^0.27.2`,eslint:`^9.39.1`,"eslint-config-prettier":`^10.1.8`,"eslint-plugin-jest":`^29.12.1`,"eslint-plugin-prettier":`^5.5.5`,globals:`^17.0.0`,jest:`^30.2.0`,"open-cli":`^8.0.0`,pegjs:`^0.7.0`,prettier:`^3.8.1`,"ts-jest":`^29.4.6`,typedoc:`^0.28.16`,typescript:`^5.9.3`,"typescript-eslint":`^8.53.1`},Lt={name:Ct,title:wt,description:Tt,version:Et,homepage:Dt,contributors:Ot,types:kt,main:At,keywords:jt,license:`MIT`,repository:Mt,bugs:Nt,files:Pt,scripts:Ft,dependencies:B,devDependencies:It}})),V=c(((e,t)=>{var n=(Rt(),f(St).default);t.exports={USER_AGENT:`${n.title} ${n.version}`,SIP:`sip`,SIPS:`sips`,causes:{CONNECTION_ERROR:`Connection Error`,REQUEST_TIMEOUT:`Request Timeout`,SIP_FAILURE_CODE:`SIP Failure Code`,INTERNAL_ERROR:`Internal Error`,BUSY:`Busy`,REJECTED:`Rejected`,REDIRECTED:`Redirected`,UNAVAILABLE:`Unavailable`,NOT_FOUND:`Not Found`,ADDRESS_INCOMPLETE:`Address Incomplete`,INCOMPATIBLE_SDP:`Incompatible SDP`,MISSING_SDP:`Missing SDP`,AUTHENTICATION_ERROR:`Authentication Error`,BYE:`Terminated`,WEBRTC_ERROR:`WebRTC Error`,CANCELED:`Canceled`,NO_ANSWER:`No Answer`,EXPIRES:`Expires`,NO_ACK:`No ACK`,DIALOG_ERROR:`Dialog Error`,USER_DENIED_MEDIA_ACCESS:`User Denied Media Access`,BAD_MEDIA_DESCRIPTION:`Bad Media Description`,RTP_TIMEOUT:`RTP Timeout`},SIP_ERROR_CAUSES:{REDIRECTED:[300,301,302,305,380],BUSY:[486,600],REJECTED:[403,603],NOT_FOUND:[404,604],UNAVAILABLE:[480,410,408,430],ADDRESS_INCOMPLETE:[484,424],INCOMPATIBLE_SDP:[488,606],AUTHENTICATION_ERROR:[401,407]},ACK:`ACK`,BYE:`BYE`,CANCEL:`CANCEL`,INFO:`INFO`,INVITE:`INVITE`,MESSAGE:`MESSAGE`,NOTIFY:`NOTIFY`,OPTIONS:`OPTIONS`,REGISTER:`REGISTER`,REFER:`REFER`,UPDATE:`UPDATE`,SUBSCRIBE:`SUBSCRIBE`,DTMF_TRANSPORT:{INFO:`INFO`,RFC2833:`RFC2833`},REASON_PHRASE:{100:`Trying`,180:`Ringing`,181:`Call Is Being Forwarded`,182:`Queued`,183:`Session Progress`,199:`Early Dialog Terminated`,200:`OK`,202:`Accepted`,204:`No Notification`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Moved Temporarily`,305:`Use Proxy`,380:`Alternative Service`,400:`Bad Request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,410:`Gone`,412:`Conditional Request Failed`,413:`Request Entity Too Large`,414:`Request-URI Too Long`,415:`Unsupported Media Type`,416:`Unsupported URI Scheme`,417:`Unknown Resource-Priority`,420:`Bad Extension`,421:`Extension Required`,422:`Session Interval Too Small`,423:`Interval Too Brief`,424:`Bad Location Information`,428:`Use Identity Header`,429:`Provide Referrer Identity`,430:`Flow Failed`,433:`Anonymity Disallowed`,436:`Bad Identity-Info`,437:`Unsupported Certificate`,438:`Invalid Identity Header`,439:`First Hop Lacks Outbound Support`,440:`Max-Breadth Exceeded`,469:`Bad Info Package`,470:`Consent Needed`,478:`Unresolvable Destination`,480:`Temporarily Unavailable`,481:`Call/Transaction Does Not Exist`,482:`Loop Detected`,483:`Too Many Hops`,484:`Address Incomplete`,485:`Ambiguous`,486:`Busy Here`,487:`Request Terminated`,488:`Not Acceptable Here`,489:`Bad Event`,491:`Request Pending`,493:`Undecipherable`,494:`Security Agreement Required`,500:`JsSIP Internal Error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Service Unavailable`,504:`Server Time-out`,505:`Version Not Supported`,513:`Message Too Large`,580:`Precondition Failure`,600:`Busy Everywhere`,603:`Decline`,604:`Does Not Exist Anywhere`,606:`Not Acceptable`},ALLOWED_METHODS:`INVITE,ACK,CANCEL,BYE,UPDATE,MESSAGE,OPTIONS,REFER,INFO,NOTIFY,SUBSCRIBE`,ACCEPTED_BODY_TYPES:`application/sdp, application/dtmf-relay`,MAX_FORWARDS:69,SESSION_EXPIRES:90,MIN_SESSION_EXPIRES:60,CONNECTION_RECOVERY_MAX_INTERVAL:30,CONNECTION_RECOVERY_MIN_INTERVAL:2}})),H=c(((e,t)=>{t.exports={ConfigurationError:class extends Error{constructor(e,t){super(),this.code=1,this.name=`CONFIGURATION_ERROR`,this.parameter=e,this.value=t,this.message=this.value?`Invalid value ${JSON.stringify(this.value)} for parameter "${this.parameter}"`:`Missing parameter: ${this.parameter}`}},InvalidStateError:class extends Error{constructor(e){super(),this.code=2,this.name=`INVALID_STATE_ERROR`,this.status=e,this.message=`Invalid status: ${e}`}},NotSupportedError:class extends Error{constructor(e){super(),this.code=3,this.name=`NOT_SUPPORTED_ERROR`,this.message=e}},NotReadyError:class extends Error{constructor(e){super(),this.code=4,this.name=`NOT_READY_ERROR`,this.message=e}}}})),zt=c(((e,t)=>{var n=W(),r=U();t.exports=class e{static parse(e){if(e=r.parse(e,`Name_Addr_Header`),e!==-1)return e}constructor(e,t,r){if(!e||!(e instanceof n))throw TypeError(`missing or invalid "uri" parameter`);this._uri=e,this._parameters={},this.display_name=t;for(let e in r)Object.prototype.hasOwnProperty.call(r,e)&&this.setParam(e,r[e])}get uri(){return this._uri}get display_name(){return this._display_name}set display_name(e){this._display_name=e===0?`0`:e}setParam(e,t){e&&(this._parameters[e.toLowerCase()]=t==null?null:t.toString())}getParam(e){if(e)return this._parameters[e.toLowerCase()]}hasParam(e){if(e)return this._parameters.hasOwnProperty(e.toLowerCase())&&!0||!1}deleteParam(e){if(e=e.toLowerCase(),this._parameters.hasOwnProperty(e)){let t=this._parameters[e];return delete this._parameters[e],t}}clearParams(){this._parameters={}}clone(){return new e(this._uri.clone(),this._display_name,JSON.parse(JSON.stringify(this._parameters)))}_quote(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}toString(){let e=this._display_name?`"${this._quote(this._display_name)}" `:``;e+=`<${this._uri.toString()}>`;for(let t in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,t)&&(e+=`;${t}`,this._parameters[t]!==null&&(e+=`=${this._parameters[t]}`));return e}}})),U=c(((e,t)=>{t.exports=(function(){function e(e){return`"`+e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\x08/g,`\\b`).replace(/\t/g,`\\t`).replace(/\n/g,`\\n`).replace(/\f/g,`\\f`).replace(/\r/g,`\\r`).replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g,escape)+`"`}var t={parse:function(t,n){var r={CRLF:l,DIGIT:u,ALPHA:d,HEXDIG:f,WSP:p,OCTET:m,DQUOTE:h,SP:g,HTAB:_,alphanum:v,reserved:y,unreserved:b,mark:x,escaped:S,LWS:C,SWS:w,HCOLON:ee,TEXT_UTF8_TRIM:T,TEXT_UTF8char:E,UTF8_NONASCII:D,UTF8_CONT:te,LHEX:ne,token:O,token_nodot:re,separators:ie,word:ae,STAR:oe,SLASH:se,EQUAL:k,LPAREN:ce,RPAREN:le,RAQUOT:ue,LAQUOT:de,COMMA:A,SEMI:j,COLON:fe,LDQUOT:pe,RDQUOT:me,comment:he,ctext:ge,quoted_string:M,quoted_string_clean:N,qdtext:_e,quoted_pair:P,SIP_URI_noparams:ve,SIP_URI:ye,uri_scheme:be,uri_scheme_sips:xe,uri_scheme_sip:Se,userinfo:Ce,user:we,user_unreserved:Te,password:Ee,hostport:De,host:Oe,hostname:ke,domainlabel:F,toplabel:Ae,IPv6reference:je,IPv6address:Me,h16:I,ls32:L,IPv4address:Ne,dec_octet:Pe,port:Fe,uri_parameters:Ie,uri_parameter:Le,transport_param:Re,user_param:ze,method_param:Be,ttl_param:Ve,maddr_param:He,lr_param:Ue,other_param:We,pname:Ge,pvalue:Ke,paramchar:qe,param_unreserved:Je,headers:Ye,header:Xe,hname:Ze,hvalue:Qe,hnv_unreserved:$e,Request_Response:R,Request_Line:et,Request_URI:tt,absoluteURI:nt,hier_part:z,net_path:rt,abs_path:it,opaque_part:at,uric:ot,uric_no_slash:st,path_segments:ct,segment:lt,param:ut,pchar:dt,scheme:ft,authority:pt,srvr:mt,reg_name:ht,query:gt,SIP_Version:_t,INVITEm:vt,ACKm:yt,OPTIONSm:bt,BYEm:xt,CANCELm:St,REGISTERm:Ct,SUBSCRIBEm:wt,NOTIFYm:Tt,REFERm:Et,Method:Dt,Status_Line:Ot,Status_Code:kt,extension_code:At,Reason_Phrase:jt,Allow_Events:Mt,Call_ID:Nt,Contact:Pt,contact_param:Ft,name_addr:B,display_name:It,contact_params:Lt,c_p_q:Rt,c_p_expires:V,delta_seconds:H,qvalue:U,generic_param:G,gen_value:K,Content_Disposition:Bt,disp_type:Vt,disp_param:Ht,handling_param:q,Content_Encoding:Ut,Content_Length:Wt,Content_Type:Gt,media_type:Kt,m_type:J,discrete_type:qt,composite_type:Jt,extension_token:Y,x_token:X,m_subtype:Yt,m_parameter:Xt,m_value:Zt,CSeq:Qt,CSeq_value:$t,Expires:en,Event:tn,event_type:nn,From:rn,from_param:an,tag_param:on,Max_Forwards:sn,Min_Expires:cn,Name_Addr_Header:ln,Proxy_Authenticate:un,challenge:dn,other_challenge:fn,auth_param:pn,digest_cln:mn,realm:hn,realm_value:gn,domain:_n,URI:vn,nonce:yn,nonce_value:bn,opaque:xn,stale:Sn,algorithm:Cn,qop_options:wn,qop_value:Tn,Proxy_Require:En,Record_Route:Dn,rec_route:On,Reason:kn,reason_param:Z,reason_cause:An,Require:jn,Route:Mn,route_param:Nn,Subscription_State:Pn,substate_value:Fn,subexp_params:In,event_reason_value:Ln,Subject:Rn,Supported:zn,To:Bn,to_param:Vn,Via:Hn,via_param:Un,via_params:Wn,via_ttl:Gn,via_maddr:Kn,via_received:qn,via_branch:Jn,response_port:Yn,rport:Xn,sent_protocol:Zn,protocol_name:Qn,transport:$n,sent_by:er,via_host:tr,via_port:nr,ttl:rr,WWW_Authenticate:ir,Session_Expires:ar,s_e_expires:or,s_e_params:sr,s_e_refresher:cr,extension_header:lr,header_value:ur,message_body:dr,uuid_URI:fr,uuid:pr,hex4:Q,hex8:mr,hex12:hr,Refer_To:gr,Replaces:_r,call_id:vr,replaces_param:yr,to_tag:br,from_tag:xr,early_flag:Sr};if(n!==void 0){if(r[n]===void 0)throw Error(`Invalid rule name: `+e(n)+`.`)}else n=`CRLF`;var i=0,a=0,o=0,s=[];function c(e){i<o||(i>o&&(o=i,s=[]),s.push(e))}function l(){var e;return t.substr(i,2)===`\r
|
|
1
|
+
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.CCBarSDK={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},c=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),l=(e,t)=>{let r={};for(var i in e)n(r,i,{get:e[i],enumerable:!0});return t||n(r,Symbol.toStringTag,{value:`Module`}),r},u=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},d=(e,r,i)=>(i=e==null?{}:t(a(e)),u(r||!e||!e.__esModule||!o.call(e,`default`)?n(i,`default`,{value:e,enumerable:!0}):i,e)),f=e=>o.call(e,`module.exports`)?e[`module.exports`]:u(n({},`__esModule`,{value:!0}),e),p,m,h=s((()=>{p={AUTH_TOKEN_UNAVAILABLE:`获取登录凭证失败,请检查凭证获取服务后重试。`,AUTH_TOKEN_EXPIRED:`登录凭证已过期,请重新获取凭证后登录。`,AUTH_TOKEN_REJECTED:`服务端未接受当前登录凭证,请核实凭证类型和权限。`,AUTH_PERMISSION_DENIED:`当前账号没有执行此操作的权限,请联系管理员。`,CONFIG_INVALID:`配置不完整或格式不正确,请检查软电话配置。`,CONFIG_ORIGIN_NOT_ALLOWED:`当前页面域名未获授权,请联系管理员配置访问域名。`,NETWORK_OFFLINE:`网络连接已断开,请检查网络后重试。`,NETWORK_TIMEOUT:`请求超时,请检查网络后重试。`,SIP_WS_UNAVAILABLE:`无法连接 SIP 服务,请检查 SIP WSS 地址和网络。`,REGISTRATION_FAILED:`SIP 注册失败,请检查坐席配置后重试。`,REGISTRATION_REJECTED:`SIP 服务拒绝了当前账号,请核对分机和 SIP 凭证。`,MEDIA_PERMISSION_DENIED:`麦克风权限未开启,请在浏览器设置中允许使用麦克风。`,MEDIA_DEVICE_NOT_FOUND:`未找到可用的音频设备,请连接麦克风或耳机后重试。`,MEDIA_DEVICE_IN_USE:`音频设备正在被其他程序使用,请关闭占用设备的程序后重试。`,MEDIA_PLAYBACK_BLOCKED:`浏览器阻止了声音播放,请点击页面并检查浏览器音频设置。`,CALL_INVALID_DESTINATION:`被叫号码格式不正确,请检查后重试。`,CALL_INVALID_USERDATA:`通话附加数据格式不正确,请检查后重试。`,CALL_ALREADY_EXISTS:`当前已有进行中的通话,请先结束当前通话。`,CALL_REJECTED:`对方或呼叫平台拒绝了本次呼叫。`,CALL_BUSY:`对方正在通话中,请稍后重试。`,CALL_NOT_CONNECTED:`当前没有可操作的通话,请先拨打或接听电话。`,NOT_SIGNED_IN:`请先登录,并等待 SIP 注册成功后再操作。`,CALL_OPERATION_NOT_ALLOWED:`当前通话状态不支持此操作,请检查通话状态后重试。`,CAPABILITY_NOT_SUPPORTED:`当前浏览器或设备不支持此功能。`,H5_BACKGROUND_NOT_SUPPORTED:`页面在后台时无法执行此操作,请返回通话页面后重试。`,SDK_ALREADY_DISPOSED:`软电话实例已关闭,请重新创建实例后操作。`,SDK_INTERNAL_ERROR:`软电话发生异常,请稍后重试;如问题持续,请联系技术支持。`,LEGACY_PLATFORM_UNREACHABLE:`无法连接坐席服务,请检查 API host 和网络。`,LEGACY_PLATFORM_REJECTED:`坐席服务未能完成请求,请核对账号权限和接口配置。`},m=class extends Error{code;category;retryable;requestId;callId;cause;serverCode;platformCode;status;constructor(e,t,n,r={}){super(p[e]),this.name=`CCBarError`,this.code=e,this.category=t,this.retryable=n,this.requestId=r.requestId,this.callId=r.callId,this.cause=r.cause,this.serverCode=r.serverCode,this.platformCode=r.platformCode,this.status=r.status}}}));h();var g=class{handlers=new Map;on(e,t){let n=this.handlers.get(e)??new Set;n.add(t),this.handlers.set(e,n);let r=!0;return()=>{r&&(r=!1,n.delete(t))}}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,t){[...this.handlers.get(e)??[]].forEach(e=>{try{e(t)}catch{}})}listenerCount(){return[...this.handlers.values()].reduce((e,t)=>e+t.size,0)}clear(){this.handlers.clear()}},_={new:new Set([`dialing`,`ringing`,`failed`]),dialing:new Set([`ringing`,`connecting`,`ended`,`failed`]),ringing:new Set([`connecting`,`ended`,`failed`]),connecting:new Set([`active`,`ended`,`failed`]),active:new Set([`held`,`ended`,`failed`]),held:new Set([`active`,`ended`,`failed`]),ended:new Set,failed:new Set},v=(e,t)=>_[e].has(t);function y(e,t){if(!v(e,t))throw new b(e,t);return t}var b=class extends m{constructor(e,t){super(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{cause:{from:e,to:t}})}},x=y;function S(e){if(e.code!==`OK`)throw TypeError(`Unexpected session response code: ${e.code}`);if(e.data===void 0||e.data===null)throw TypeError(`Unexpected session response: missing data`);return e.data}h();var C=[`progress`,`accepted`,`confirmed`,`ended`,`failed`,`hold`,`unhold`,`mediaConnected`],w=3e4,ee=class{options;currentState=`new`;sessionUnsubscribers=[];capabilities;disposed=!1;pendingOperation;localHeld=!1;remoteHeld=!1;incomingOperation;ownerTabId;ownerLost=!1;id;destination;platform;constructor(e){this.options=e,this.id=e.id,this.destination=e.destination,this.platform=e.platform,this.capabilities=e.capabilities??new Set;try{C.forEach(t=>{this.sessionUnsubscribers.push(e.session.on(t,e=>this.handleSessionEvent(t,e)))})}catch(t){this.cleanupSessionListeners();try{e.session.terminate()}catch{}throw new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:this.id,cause:t})}}get state(){return this.currentState}getResourceCounts(){return{timers:this.pendingOperation?.timer===void 0?0:1,listeners:this.sessionUnsubscribers.length}}async mute(e){this.assertNotDisposed(),this.assertOwner(e),this.assertMediaControlAllowed(),this.assertCapability(`mute`),this.invoke(()=>this.options.session.mute())}async unmute(e){this.assertNotDisposed(),this.assertOwner(e),this.assertMediaControlAllowed(),this.assertCapability(`mute`),this.invoke(()=>this.options.session.unmute())}async answer(e,t){this.assertNotDisposed(),this.assertOwner(t),this.assertIncomingCall(),this.assertCapability(`inbound`),this.assertIncomingOperationAvailable(),this.incomingOperation=`answer`;try{this.options.session.answer(e)}catch(e){throw this.incomingOperation=void 0,this.finishFailedIncomingOperation(e),this.operationError(e)}this.transitionIfAllowed(`connecting`,void 0,`accepted`)}async reject(e={},t){this.assertNotDisposed(),this.assertOwner(t),this.assertIncomingCall(),this.assertIncomingOperationAvailable(),this.incomingOperation=`reject`;let n;try{this.options.session.terminate()}catch(e){n=e}finally{this.incomingOperation=void 0,this.transitionIfStillRinging(`ended`,{reason:e.reason?.trim()||`rejected`})}if(n!==void 0)throw this.operationError(n)}async hold(e){this.assertNotDisposed(),this.assertOwner(e),this.assertHoldCapability(),this.assertState(`active`),this.assertCapability(`hold`),await this.startPendingOperation(`hold`,()=>this.options.session.hold())}async resume(e){if(this.assertNotDisposed(),this.assertOwner(e),this.assertHoldCapability(),this.assertState(`held`),this.assertCapability(`hold`),this.remoteHeld&&!this.localHeld)throw this.operationError({reason:`remote_hold_active`});await this.startPendingOperation(`resume`,()=>this.options.session.unhold())}async sendDtmf(e,t){if(this.assertNotDisposed(),this.assertOwner(t),!/^[0-9A-D*#]$/.test(e))throw this.operationError();this.assertState(`active`),this.assertCapability(`dtmf`),this.invoke(()=>this.options.session.sendDtmf(e))}async transfer(e,t){if(this.assertNotDisposed(),this.assertOwner(t),this.assertTransferCapability(),this.assertState(`active`),this.assertCapability(`blind_transfer`),!E(e)||e.target.trim()===``)throw this.operationError();this.invoke(()=>this.options.session.refer(e.target.trim()))}async hangup(e){if(this.assertNotDisposed(),this.assertOwner(e),T(this.currentState))throw this.operationError();try{this.options.session.terminate(),T(this.currentState)||this.transitionTo(`ended`)}catch(e){throw this.operationError(e)}}beginOutbound(){this.assertNotDisposed(),this.assertCapability(`outbound`),this.transitionTo(`dialing`)}beginIncoming(){this.assertNotDisposed(),this.transitionTo(`ringing`)}setOwnerTabId(e){this.ownerTabId=e,this.ownerLost=!1}clearOwnerTabId(e={}){this.ownerTabId=void 0,this.ownerLost=e.lost===!0}getOwnerTabId(){return this.ownerTabId}assertOwnerForManager(e){this.assertOwner(e)}canBeReclaimed(){return this.currentState===`new`||this.currentState===`dialing`||this.currentState===`ringing`}dispose(){if(!this.disposed){if(this.rejectPendingOperation(),this.incomingOperation=void 0,this.disposed=!0,!T(this.currentState))try{this.options.session.terminate()}catch(e){this.reportOperationError(e)}this.cleanupSessionListeners();try{this.options.onDisposed?.()}catch{}}}handleSessionEvent(e,t){if((e===`accepted`||e===`confirmed`||e===`ended`||e===`failed`)&&(this.incomingOperation=void 0),!(this.disposed||T(this.currentState)))switch(e){case`progress`:this.transitionIfAllowed(`ringing`,t,e);break;case`accepted`:this.transitionIfAllowed(`connecting`,t,e);break;case`confirmed`:this.transitionToActive(t);break;case`mediaConnected`:this.currentState===`connecting`&&this.transitionTo(`active`,t);break;case`hold`:this.updateHoldState(!0,t,e);break;case`unhold`:this.updateHoldState(!1,t,e);break;case`ended`:this.transitionIfAllowed(`ended`,t,e);break;case`failed`:this.transitionIfAllowed(`failed`,t,e)}}transitionToActive(e){this.currentState!==`active`&&((this.currentState===`dialing`||this.currentState===`ringing`)&&this.transitionTo(`connecting`,e),this.transitionIfAllowed(`active`,e,`confirmed`))}transitionIfAllowed(e,t,n){this.currentState!==e&&(v(this.currentState,e)?this.transitionTo(e,t):this.reportIllegalTransition(e,n))}updateHoldState(e,t,n){let r=typeof t==`object`&&t?t.originator:void 0;r===`remote`?this.remoteHeld=e:r===`both`?(this.localHeld=e,this.remoteHeld=e):this.localHeld=e;let i=this.localHeld||this.remoteHeld?`held`:`active`;this.transitionIfAllowed(i,t,n)}transitionIfStillRinging(e,t){this.currentState===`ringing`&&this.transitionTo(e,t)}transitionTo(e,t){if(this.currentState===e)return;if(!v(this.currentState,e))throw this.operationError();let n=this.currentState;this.currentState=e,T(e)&&this.rejectPendingOperation();try{this.options.onStateChanged?.({callId:this.id,from:n,to:e},t)}catch{}finally{T(e)&&this.dispose()}}startPendingOperation(e,t){if(this.pendingOperation!==void 0)throw this.operationError({reason:`pending_operation_in_progress`,operation:this.pendingOperation.kind});return new Promise((n,r)=>{let i={kind:e,resolve:n,reject:r};this.pendingOperation=i,i.timer=setTimeout(()=>this.timeoutPendingOperation(i),w);let a;try{a=t()}catch(e){this.rejectPendingOperation(e);return}a.then(()=>this.resolvePendingOperation(i),e=>this.rejectPendingOperation(e,i))})}resolvePendingOperation(e){if(this.pendingOperation===e){if(this.clearPendingTimer(e),this.pendingOperation=void 0,this.disposed||T(this.currentState)){e.reject(this.operationError());return}try{this.localHeld=e.kind===`hold`;let t=this.localHeld||this.remoteHeld?`held`:`active`;this.transitionTo(t),e.resolve()}catch(t){e.reject(this.operationError(t))}}}rejectPendingOperation(e,t){let n=this.pendingOperation;n===void 0||t!==void 0&&n!==t||(this.clearPendingTimer(n),this.pendingOperation=void 0,n.reject(this.operationError(e)))}timeoutPendingOperation(e){this.pendingOperation===e&&(this.rejectPendingOperation(Error(`${e.kind} operation timed out`),e),this.dispose())}clearPendingTimer(e){e.timer!==void 0&&(clearTimeout(e.timer),e.timer=void 0)}reportIllegalTransition(e,t){this.reportOperationError({event:t,from:this.currentState,to:e})}reportOperationError(e){let t=e instanceof m&&e.callId===this.id?e:this.operationError(e);try{this.options.onError?.(t)}catch{}}finishFailedIncomingOperation(e){this.reportOperationError(e);try{this.options.session.terminate()}catch(t){e={operation:e,cleanup:t}}this.transitionIfStillRinging(`ended`,{reason:`incoming_operation_failed`,cause:e})}cleanupSessionListeners(){this.sessionUnsubscribers.splice(0).forEach(e=>{try{e()}catch{}})}assertState(e){if(this.currentState!==e)throw this.operationError()}assertMediaControlAllowed(){if(this.currentState!==`active`&&this.currentState!==`held`)throw this.operationError()}assertHoldCapability(){if(this.platform===`mobile-web`)throw this.capabilityError()}assertTransferCapability(){if(this.platform===`mobile-web`)throw this.capabilityError()}assertIncomingCall(){if(this.options.incoming!==!0||this.currentState!==`ringing`)throw this.operationError()}assertIncomingOperationAvailable(){if(this.incomingOperation!==void 0)throw this.operationError()}assertCapability(e){if(!this.capabilities.has(e))throw this.capabilityError()}invoke(e){try{e()}catch(e){throw this.operationError(e)}}assertNotDisposed(){if(this.disposed)throw this.operationError()}assertOwner(e){if(e!==void 0&&(this.ownerLost||this.ownerTabId!==void 0&&this.ownerTabId!==e))throw this.operationError()}capabilityError(){return new m(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:this.id})}operationError(e){return new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:this.id,cause:e})}};function T(e){return e===`ended`||e===`failed`}function E(e){return typeof e==`object`&&!!e&&e.type===`blind`&&typeof e.target==`string`}var D=0;function te(){return D+=1,`call_${Date.now().toString(36)}_${D.toString(36)}`}h();var ne=`X-User-Data`,O=/[^\x20-\x7E]/,re=`userdata 只能是可见 ASCII(不能有换行/制表/中文):换行会构成 SIP 头注入;要传中文或 JSON 请调用方先 encodeURIComponent / base64,再在平台侧解回来`;function ie(e){if(typeof e!=`string`)return[];let t=e.trim();if(t===``)return[];if(O.test(t))throw new m(`CALL_INVALID_USERDATA`,`call`,!1,{cause:re});return[`${ne}: ${t}`]}h();var ae=class{events=new oe;calls=new Map;options;incomingUnsubscribe;activeCallId=null;incomingSessionSnapshot;callSessions=new Map;callOwners=new Map;ownerLostCalls=new Set;pendingDialCount=0;pendingDestinations=new Set;activeOperationPromise=Promise.resolve();operationGeneration=0;automaticActiveTransition;disposed=!1;terminalNotified=new Set;terminalOperations=new Map;disposeOperation;constructor(e){this.options=e,this.incomingSessionSnapshot=e.session;try{this.incomingUnsubscribe=e.sip.onIncoming(e=>this.handleIncoming(e))}catch(e){throw new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}}on(e,t){return this.disposed?()=>void 0:this.events.on(e,t)}async dial(e,t){this.assertNotDisposed();let n=this.operationGeneration,r=e.destination.trim();if(r===``)throw new m(`CALL_INVALID_DESTINATION`,`call`,!1);let i=/^\+?\d{3,20}$/.test(r),a=/^sips?:[^\s<>@]+(?:@[^\s<>@]+)?$/i.test(r);if(!i&&!a)throw new m(`CALL_INVALID_DESTINATION`,`call`,!1);let o=ie(e.userdata);this.requireCapability(t,`outbound`);let s=this.callLimit(t);if(this.options.platform===`mobile-web`&&this.calls.size+this.pendingDialCount>=s)throw this.capabilityError();if(this.calls.size+this.pendingDialCount>=s||this.pendingDestinations.has(r)||[...this.calls.values()].some(e=>e.destination===r))throw new m(`CALL_ALREADY_EXISTS`,`call`,!1);this.pendingDialCount+=1,this.pendingDestinations.add(r);let c=te(),l;try{l=await this.holdActiveCallForNewCall(),this.assertGeneration(n,c);let i;try{i=this.options.sip.dial(r,this.dialOptions(c,t,e.type,o))}catch(e){throw this.dialError(e,c)}this.assertGeneration(n,c);let a;try{a=new ee({id:c,destination:r,platform:this.options.platform,capabilities:this.effectiveCapabilities(t),session:i,onStateChanged:(e,t)=>this.handleStateChanged(a,e,t),onError:e=>this.events.emit(`error`,{error:e}),onDisposed:()=>this.handleDisposed(a)})}catch(e){throw this.dialError(e,c)}if(!this.isCurrentGeneration(n))throw a.dispose(),this.callOperationError(a.id);this.calls.set(a.id,a),this.callSessions.set(a.id,i),this.options.onCallCreated?.(a.id,i);try{a.beginOutbound()}catch(e){throw a.dispose(),this.calls.delete(a.id),this.callSessions.delete(a.id),this.dialError(e,a.id)}if(!this.isCurrentGeneration(n))throw a.dispose(),this.calls.delete(a.id),this.callSessions.delete(a.id),this.callOperationError(a.id);return this.events.emit(`call.created`,{callId:a.id,state:a.state}),a}catch(e){if(this.isCurrentGeneration(n)&&l!==void 0&&this.isManagedCall(l)&&l.state===`held`)try{await l.resume()}catch(t){throw this.compensationError(l.id,void 0,e,t)}throw e}finally{--this.pendingDialCount,this.pendingDestinations.delete(r)}}async answer(e,t,n,r){this.assertNotDisposed();let i=this.requireCall(e);if(this.options.platform===`mobile-web`&&t.policy.mobileIncomingEnabled!==!0)throw this.capabilityError(e);let a={iceServers:t.iceServers,pcConfig:{iceServers:t.iceServers},...n===void 0?{}:{mediaConstraints:n}};await i.answer(a,r)}async reject(e,t,n){this.assertNotDisposed(),await this.requireCall(e).reject(t,n)}getCalls(){return[...this.calls.values()]}hasNonTerminalCalls(){return this.calls.size>0}getResourceCounts(){let e=[...this.calls.values()].map(e=>e.getResourceCounts());return{timers:e.reduce((e,t)=>e+t.timers,0),listeners:this.events.listenerCount()+e.reduce((e,t)=>e+t.listeners,0),terminalRecords:this.terminalNotified.size+this.terminalOperations.size}}getActiveCall(){return this.activeCallId===null?void 0:this.calls.get(this.activeCallId)}async setActiveCall(e,t){this.assertNotDisposed(),this.requireCall(e).assertOwnerForManager(t),await this.enqueueActiveOperation(t=>this.switchActiveCall(e,t))}async claimCall(e,t){this.assertNotDisposed();let n=t.trim();if(n===``)throw this.callOperationError(e);let r=this.requireCall(e),i=this.callOwners.get(e);if(i!==n){if(i!==void 0||this.ownerLostCalls.has(e)&&!r.canBeReclaimed())throw this.callOperationError(e);this.ownerLostCalls.delete(e),this.callOwners.set(e,n),r.setOwnerTabId(n),this.emitOwnershipChanged({callId:e,state:`owned`,ownerTabId:n})}}async releaseCall(e,t){this.assertNotDisposed();let n=this.requireCall(e);if(this.callOwners.get(e)!==t)throw this.callOperationError(e);this.callOwners.delete(e);let r=!n.canBeReclaimed();r?this.ownerLostCalls.add(e):this.ownerLostCalls.delete(e),n.clearOwnerTabId({lost:r}),this.emitOwnershipChanged({callId:e,state:r?`owner-lost`:`released`})}getCallOwner(e){return this.callOwners.get(e)}releaseOwnedCalls(e){for(let[t,n]of[...this.callOwners.entries()]){if(n!==e)continue;let r=this.calls.get(t);if(r===void 0){this.callOwners.delete(t),this.ownerLostCalls.delete(t);continue}this.callOwners.delete(t);let i=!r.canBeReclaimed();i?this.ownerLostCalls.add(t):this.ownerLostCalls.delete(t),r.clearOwnerTabId({lost:i}),this.emitOwnershipChanged({callId:t,state:i?`owner-lost`:`released`})}}dispose(e={}){if(this.disposeOperation!==void 0)return this.disposeOperation;this.disposed=!0,this.operationGeneration+=1,this.automaticActiveTransition=void 0,this.activeOperationPromise=Promise.resolve(),this.events.clear();try{this.incomingUnsubscribe()}catch{}this.activeCallId=null;let t=[...this.calls.values()];this.calls.clear(),this.callSessions.clear(),this.callOwners.clear(),this.ownerLostCalls.clear();let n=Promise.all(t.map(async t=>{let n;try{e.terminateCalls===!0&&t.state!==`ended`&&t.state!==`failed`?await t.hangup():t.dispose()}catch(e){n=e,t.dispose()}try{await this.notifyCallTerminal(t.id)}catch(e){n??=e}if(n!==void 0)throw n})).finally(()=>{this.terminalNotified.clear(),this.terminalOperations.clear()}).then(()=>void 0);return this.disposeOperation=n,n}async forceTerminateCalls(e=5e3){if(this.disposed)return;let t=[...this.calls.values()];for(let n of t){if(this.disposed)return;if(this.calls.get(n.id)===n){try{await Promise.race([n.hangup().catch(()=>void 0),new Promise(t=>setTimeout(t,Math.max(0,e)))])}catch{}try{n.dispose()}catch{}if(this.calls.get(n.id)===n){this.calls.delete(n.id),this.callSessions.delete(n.id),this.callOwners.delete(n.id),this.ownerLostCalls.delete(n.id),this.activeCallId===n.id&&(this.activeCallId=null);try{await this.notifyCallTerminal(n.id)}catch{}}}}}updateSession(e){this.disposed||(this.incomingSessionSnapshot=e)}async switchActiveCall(e,t){this.assertGeneration(t,e);let n=this.requireCall(e),r=this.getActiveCall();if(r?.id===n.id)return;if(n.state!==`held`&&n.state!==`active`)throw this.callOperationError(e);let i=n.state===`held`;try{if(r!==void 0&&await r.hold(),this.assertGeneration(t,n.id),n.state===`held`&&await n.resume(),this.assertGeneration(t,n.id),!this.isManagedCall(n)||n.state!==`active`)throw this.callOperationError(n.id);this.commitActive(n,t)}catch(a){if(!this.isCurrentGeneration(t))throw this.callOperationError(n.id,a);if(r===void 0)throw this.callOperationError(e,a);try{let e=n.state===`active`;i&&e&&this.isManagedCall(n)&&await n.hold(),this.assertGeneration(t,n.id),r.state===`held`&&this.isManagedCall(r)&&await r.resume(),this.assertGeneration(t,r.id),r.state===`active`&&this.isManagedCall(r)&&this.commitActive(r,t)}catch(e){throw this.compensationError(r.id,n.id,a,e)}throw this.isManagedCall(r)&&r.state===`active`&&this.commitActive(r,t),this.callOperationError(n.id,{operation:a,restoredCallId:r.id})}}handleStateChanged(e,t,n){if(this.disposed)return;let r=this.callSessions.get(e.id);if(r!==void 0&&this.options.onCallStateChanged?.(e.id,r),this.events.emit(`call.stateChanged`,t),t.to===`active`&&this.activeCallId!==e.id){let t=this.getActiveCall();if(this.options.autoHoldPreviousCall===!0&&t!==void 0&&t.id!==e.id&&t.state===`active`){let n=this.operationGeneration;this.enqueueActiveOperation(n=>this.switchAutomaticActiveCall(t,e,n)).catch(e=>{this.isCurrentGeneration(n)&&this.events.emit(`error`,{error:e})})}else this.commitActive(e)}t.to===`held`&&this.activeCallId===e.id&&this.automaticActiveTransition?.previous.id!==e.id&&(this.activeCallId=null,this.events.emit(`call.activeChanged`,{callId:null})),(t.to===`ended`||t.to===`failed`)&&(this.calls.delete(e.id),this.callSessions.delete(e.id),this.callOwners.delete(e.id),this.ownerLostCalls.delete(e.id),this.activeCallId===e.id&&this.automaticActiveTransition?.previous.id!==e.id&&(this.activeCallId=null,this.events.emit(`call.activeChanged`,{callId:null})),this.notifyCallTerminal(e.id),t.to===`ended`?this.events.emit(`call.ended`,{callId:e.id,reason:se(n)}):this.events.emit(`call.failed`,{callId:e.id,error:ce(n,e.id)}))}async switchAutomaticActiveCall(e,t,n){this.automaticActiveTransition={previous:e,target:t};let r;try{if(this.assertGeneration(n,t.id),!this.isManagedCall(t)||t.state!==`active`)return;if(!this.isManagedCall(e)||e.state!==`active`){this.commitActive(t,n);return}if(await e.hold(),this.assertGeneration(n,t.id),!this.isManagedCall(e)){this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,n);return}if(!this.isManagedCall(t)||t.state!==`active`)r=Error(`target call is no longer active`);else{this.commitActive(t,n);return}}catch(e){r=e}finally{this.automaticActiveTransition?.target.id===t.id&&(this.automaticActiveTransition=void 0)}if(!this.isCurrentGeneration(n))return;if(!this.isManagedCall(e)){this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,n);return}let i=await this.restoreAutomaticActiveCall(e,t,r,n);if(this.isCurrentGeneration(n)){if(i.error!==void 0)throw i.error;if(!this.isManagedCall(e)){this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,n);return}throw this.callOperationError(t.id,{operation:r,restoredCallId:e.id})}}async restoreAutomaticActiveCall(e,t,n,r){if(!this.isCurrentGeneration(r))return{};if(!this.isManagedCall(e))return this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,r),{};let i;try{this.isManagedCall(t)&&t.state===`active`&&await t.hold(),this.assertGeneration(r,t.id),this.isManagedCall(e)&&e.state===`held`&&await e.resume(),this.assertGeneration(r,e.id)}catch(e){i=e}return this.isCurrentGeneration(r)?this.isManagedCall(e)?i===void 0?(e.state===`active`&&this.commitActive(e,r),{}):{error:this.compensationError(e.id,t.id,n,i)}:(this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,r),{}):{}}handleDisposed(e){this.disposed||(this.calls.delete(e.id),this.callSessions.delete(e.id),this.callOwners.delete(e.id),this.ownerLostCalls.delete(e.id),this.notifyCallTerminal(e.id),this.activeCallId===e.id&&(this.activeCallId=null,this.events.emit(`call.activeChanged`,{callId:null})))}commitActive(e,t=this.operationGeneration){this.isCurrentGeneration(t)&&this.isManagedCall(e)&&e.state===`active`&&this.activeCallId!==e.id&&(this.activeCallId=e.id,this.events.emit(`call.activeChanged`,{callId:e.id}))}handleIncoming(e){if(this.disposed)return;let t=te(),n=this.incomingSessionSnapshot;if(n===void 0||!n.policy.incomingEnabled||!this.effectiveCapabilities(n).has(`inbound`)){this.terminateUnsupportedIncoming(e),this.events.emit(`error`,{error:this.capabilityError(t)});return}let r=e.from??e.id;if(this.calls.size+this.pendingDialCount>=this.callLimit(n)){this.terminateUnsupportedIncoming(e),this.events.emit(`error`,{error:new m(`CALL_ALREADY_EXISTS`,`call`,!1,{callId:t})});return}let i;try{i=new ee({id:t,destination:r,platform:this.options.platform,incoming:!0,capabilities:this.effectiveCapabilities(n),session:e,onStateChanged:(e,t)=>this.handleStateChanged(i,e,t),onError:e=>this.events.emit(`error`,{error:e}),onDisposed:()=>this.handleDisposed(i)})}catch(e){this.events.emit(`error`,{error:this.callOperationError(t,e)});return}this.calls.set(i.id,i),this.callSessions.set(i.id,e),this.options.onCallCreated?.(i.id,e);try{i.beginIncoming(),this.events.emit(`call.incoming`,{callId:i.id,from:r})}catch(e){i.dispose(),this.events.emit(`error`,{error:this.callOperationError(i.id,e)})}}terminateUnsupportedIncoming(e){try{e.terminate()}catch{}}async holdActiveCallForNewCall(){if(this.options.autoHoldPreviousCall!==!0)return;let e=this.getActiveCall();if(e!==void 0&&e.state===`active`)return await e.hold(),e}enqueueActiveOperation(e){let t=this.operationGeneration,n=()=>this.isCurrentGeneration(t)?e(t):Promise.reject(this.callOperationError(``)),r=this.activeOperationPromise.then(n,n);return this.activeOperationPromise=r.catch(()=>void 0),r}isManagedCall(e){return!this.disposed&&this.calls.get(e.id)===e&&e.state!==`ended`&&e.state!==`failed`}isCurrentGeneration(e){return!this.disposed&&this.operationGeneration===e}assertGeneration(e,t){if(!this.isCurrentGeneration(e))throw this.callOperationError(t??``)}effectiveCapabilities(e){let t=new Set(e.capabilities);return this.options.platform===`mobile-web`&&(t.delete(`hold`),t.delete(`blind_transfer`),e.policy.mobileIncomingEnabled!==!0&&t.delete(`inbound`)),t}requireCapability(e,t,n){if(!this.effectiveCapabilities(e).has(t))throw this.capabilityError(n)}requireCall(e){let t=this.calls.get(e);if(t===void 0)throw this.callOperationError(e);return t}emitOwnershipChanged(e){this.events.emit(`call.ownershipChanged`,e)}notifyCallTerminal(e){let t=this.terminalOperations.get(e);if(t!==void 0)return t;if(this.terminalNotified.has(e))return Promise.resolve();this.terminalNotified.add(e);let n;try{n=this.options.onCallTerminal?.(e)}catch(t){this.events.emit(`error`,{error:this.callOperationError(e,t)});let n=Promise.reject(this.callOperationError(e,t));return this.terminalOperations.set(e,n),n.catch(()=>void 0).finally(()=>this.pruneTerminalRecord(e,n)),n}let r=Promise.resolve(n).catch(t=>{throw this.events.emit(`error`,{error:this.callOperationError(e,t)}),t});return this.terminalOperations.set(e,r),r.catch(()=>void 0).finally(()=>this.pruneTerminalRecord(e,r)),r}pruneTerminalRecord(e,t){this.terminalOperations.get(e)===t&&this.terminalOperations.delete(e),this.calls.has(e)||this.terminalNotified.delete(e)}assertNotDisposed(){if(this.disposed)throw new m(`SDK_ALREADY_DISPOSED`,`internal`,!1)}callOperationError(e,t){return new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e,cause:t})}capabilityError(e){return new m(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:e})}compensationError(e,t,n,r){return this.callOperationError(e,{operation:n,rollback:r,originalCallId:e,targetCallId:t})}callLimit(e){let t=this.options.platform===`mobile-web`?1:2,n=this.options.maxConcurrentCalls??t;return Math.min(t,Math.max(1,n),Math.max(1,e.policy.maxConcurrentCalls))}dialOptions(e,t,n,r=[]){return{iceServers:t.iceServers,extraHeaders:[`X-XCall-Call-ID: ${e}`,`X-XCall-Session-ID: ${t.sessionId}`,...r],...n===void 0?{}:{type:n}}}dialError(e,t){return e instanceof m?new m(e.code,e.category,e.retryable,{requestId:e.requestId,callId:t,cause:e.cause??e,serverCode:e.serverCode,platformCode:e.platformCode,status:e.status}):new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t,cause:e})}},oe=class{handlers=new Map;on(e,t){let n=this.handlers.get(e)??new Set,r=t;n.add(r),this.handlers.set(e,n);let i=!0;return()=>{i&&(i=!1,n.delete(r))}}emit(e,t){let n=this.handlers.get(e);n!==void 0&&[...n].forEach(e=>{try{e(t)}catch{}})}listenerCount(){return[...this.handlers.values()].reduce((e,t)=>e+t.size,0)}clear(){this.handlers.clear()}};function se(e){if(typeof e!=`object`||!e||!(`reason`in e))return`ended`;let t=e.reason;return typeof t==`string`&&t!==``?t:`ended`}function k(e){if(typeof e!=`object`||!e)return;let{cause:t,cause_code:n,message:r}=e,i=typeof n==`number`?n:void 0,a=typeof t==`string`?t:void 0;if(i===void 0&&typeof r==`object`&&r){let e=r.data;if(typeof e==`string`){let t=/^SIP\/2\.0\s+(\d{3})/m.exec(e);if(t)return{code:Number(t[1])}}}return i===void 0&&a===void 0?void 0:{code:i,cause:a}}function ce(e,t){if(e instanceof m)return new m(e.code,e.category,e.retryable,{requestId:e.requestId,callId:t,cause:e.cause??e,serverCode:e.serverCode,platformCode:e.platformCode,status:e.status});if(typeof e==`object`&&e&&`error`in e){let n=e.error;if(n instanceof m)return new m(n.code,n.category,n.retryable,{requestId:n.requestId,callId:t,cause:n.cause??n,serverCode:n.serverCode,platformCode:n.platformCode,status:n.status});if(n instanceof Error)return new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t,cause:n})}let n=k(e);return n===void 0?new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t,cause:e}):n.code===486||n.cause===`Busy`?new m(`CALL_BUSY`,`call`,!1,{callId:t,cause:e}):n.code===408||n.cause===`Request Timeout`?new m(`NETWORK_TIMEOUT`,`call`,!0,{callId:t,cause:e}):new m(`CALL_REJECTED`,`call`,!1,{callId:t,cause:e})}h();var le=`q7X4p6MvK1z8Lb3A`,ue=`W9e2T4mN0aQ7Ru6C`,de=16,A=`�`;function j(e){for(let t of e){let e=t.codePointAt(0)??0;if(e===127||e<32&&e!==9)return!0}return!1}async function fe(e,t={}){let n=String(e??``).replace(/\s+/g,``);if(!n)throw new m(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`解密的密文为空:坐席账号里没有 password/registerPassword`});let r=t.subtle??globalThis.crypto?.subtle;if(r===void 0)throw new m(`CONFIG_INVALID`,`configuration`,!1,{cause:`需要 WebCrypto 才能解 SIP 密码:请在安全上下文(https / localhost)或 Node 18+ 里运行`});let i=ge(n);if(i===void 0)throw new m(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`密文不是合法的 Base64:确认取的是 password/registerPassword 原值,没有被截断或转义`});let a=await r.importKey(`raw`,_e(t.key??le),`AES-CBC`,!1,[`decrypt`]);try{let e=await r.decrypt({name:`AES-CBC`,iv:_e(t.iv??ue)},a,i);return new TextDecoder(`utf-8`).decode(e).trim()}catch(e){throw new m(`LEGACY_PLATFORM_REJECTED`,`auth`,!1,{cause:`SIP 密码解密失败(检查 key/iv 与该环境是否一致):${e instanceof Error?e.message:String(e)}`})}}async function pe(e,t={}){let n=String(e??``).replace(/\s+/g,``);if(me(n))try{let e=await fe(n,t);return he(e)?e:void 0}catch{return}}function me(e){let t=ge(e);return t!==void 0&&t.byteLength>0&&t.byteLength%de===0}function he(e){return e.length===0||e.includes(A)?!1:!j(e)}function ge(e){if(e.length!==0&&e.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(e))try{let t=atob(e),n=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}catch{return}}function _e(e){let t=new TextEncoder().encode(e),n=new Uint8Array(new ArrayBuffer(t.byteLength));return n.set(t),n}var M=`3.1.18`,N=`[REDACTED]`,ve=/\bBearer\s+[^\s,;"'}]+/gi,ye=/(\bAuthorization\s*[:=]\s*)Digest\s+[^\r\n]*/gi,be=/(\bAuthorization\s*[:=]\s*)(?:(Bearer|Basic|Digest|Token)\s+)?[^\s,;"'}]+/gi,xe=/\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,Se=/\b((?:sip|sips|turn|turns|ws|wss):(?:\/\/)?)[^/?#@\s:]+:[^/?#@\s]+@/gi,Ce=/(\b(?:sip(?:Register)?Ticket|registerTicket|wssTicket|turnCredential|credential|accessToken|refreshToken|appSecret|password|jwt|ticket)\b\s*[:=]\s*)(["']?)([^\s,;&}"']+)(["']?)/gi,we=/(?<!\d)(1[3-9]\d)\d{4}(\d{4})(?!\d)/g,Te=/(?:authorization|token|ticket|credential|password|secret)$/i;function Ee(e,t={}){let n=e.replace(ve,`Bearer ${N}`).replace(ye,(e,t)=>`${t}Digest ${N}`).replace(be,(e,t,n)=>`${t}${n===void 0?``:`${n} `}${N}`).replace(xe,N).replace(Se,(e,t)=>`${t}${N}@`).replace(Ce,(e,t)=>`${t}${N}`);return t.maskPhoneNumbers!==!1&&(n=n.replace(we,`$1****$2`)),n}function De(e,t={}){return Oe(e,t,new WeakSet)}function Oe(e,t,n){if(typeof e==`string`)return Ee(e,t);if(typeof e!=`object`||!e)return e;if(n.has(e))return`[Circular]`;if(n.add(e),Array.isArray(e))return e.map(e=>Oe(e,t,n));let r={};return Object.entries(e).forEach(([e,i])=>{r[e]=Te.test(e)?N:Oe(i,t,n)}),r}h();function ke(e){if(!je(e))throw P(`Invalid worker message`);if(e.version!==1)throw P(`Unsupported worker protocol version`);if(e.type===`attach`||e.type===`detach`)return Ae(e),e;if(e.type===`command`){if(Ae(e),typeof e.command!=`string`||e.payload!==void 0&&!je(e.payload))throw P(`Invalid worker command`);return e}if(e.type===`response`){if(typeof e.requestId!=`string`||typeof e.ok!=`boolean`)throw P(`Invalid worker response`);return e}if(e.type===`event`){if(typeof e.event!=`string`||!(`payload`in e))throw P(`Invalid worker event`);return e}throw P(`Unknown worker message type`)}function Ae(e){if(typeof e.requestId!=`string`||typeof e.tabId!=`string`)throw P(`Worker request requires requestId and tabId`)}function je(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function P(e){return new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}h();var Me=class{port;timeoutMs;pending=new Map;eventHandlers=new Set;closed=!1;lifecycleState=`connected`;constructor(e,t={}){this.port=e,this.timeoutMs=t.timeoutMs??15e3,this.port.onmessage=e=>this.handleMessage(e.data),this.port.start()}request(e){return this.closed?Promise.reject(new m(`SDK_ALREADY_DISPOSED`,`internal`,!1)):this.pending.has(e.requestId)?Promise.reject(new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{requestId:e.requestId})):this.lifecycleState===`reconnecting`&&e.type===`command`&&(e.command===`dial`||e.command===`answer`)?Promise.reject(new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!0,{callId:e.payload?.callId})):new Promise((t,n)=>{let r=setTimeout(()=>{this.pending.delete(e.requestId),n(new m(`NETWORK_TIMEOUT`,`network`,!0,{requestId:e.requestId}))},this.timeoutMs);this.pending.set(e.requestId,{resolve:e=>t(e),reject:n,timer:r}),this.port.postMessage(e)})}onEvent(e){return this.closed?()=>void 0:(this.eventHandlers.add(e),()=>this.eventHandlers.delete(e))}getLifecycleState(){return this.lifecycleState}close(){this.closed||(this.closed=!0,this.pending.forEach(e=>{clearTimeout(e.timer),e.reject(new m(`SDK_ALREADY_DISPOSED`,`internal`,!1))}),this.pending.clear(),this.eventHandlers.clear(),this.port.close())}handleMessage(e){try{let t=ke(e);if(t.type===`event`){t.event===`connection.stateChanged`&&Ne(t.payload)&&(this.lifecycleState=t.payload.state),this.eventHandlers.forEach(e=>e(t));return}if(t.type!==`response`)return;let n=this.pending.get(t.requestId);if(n===void 0)return;this.pending.delete(t.requestId),clearTimeout(n.timer),t.ok?n.resolve(t.result):n.reject(F(t))}catch(e){this.pending.forEach(t=>{clearTimeout(t.timer),t.reject(e)}),this.pending.clear()}}};function Ne(e){return typeof e==`object`&&!!e&&`state`in e&&(e.state===`connected`||e.state===`reconnecting`)}function F(e){let t=e.error;return new m(t?.code??`SDK_INTERNAL_ERROR`,t?.category??`internal`,t?.retryable??!1,{requestId:e.requestId,...t?.message===void 0?{}:{cause:t.message},...t?.serverCode===void 0?{}:{serverCode:t.serverCode},...t?.platformCode===void 0?{}:{platformCode:t.platformCode},...t?.status===void 0?{}:{status:t.status}})}h();function I(e={}){if((e.enabled??`auto`)===!1)return{mode:`single-tab`,reason:`disabled`};let t=e.locationHref??Fe(),n=Pe(e.url,t),r=t=>{if(e.fallback===`error`)throw new m(`CONFIG_INVALID`,`configuration`,!1,{cause:t});return{mode:`single-tab`,reason:t}};if(n===void 0)return r(`SharedWorker URL is unavailable`);if(!Le(n,t))return r(`SharedWorker URL must be same-origin`);let i=e.workerCtor??Ie();if(i===void 0)return r(`SharedWorker is not supported`);let a;try{a=new i(n,e.name===void 0?void 0:{name:e.name})}catch(e){return r(`SharedWorker construction failed: ${e instanceof Error?e.message:String(e)}`)}let o=e.tabId??Re(),s=new Me(a.port),c={version:1,type:`attach`,requestId:ze(),tabId:o},l=s.request(c).then(()=>void 0).catch(e=>{throw s.close(),e});return{mode:`shared`,worker:a,client:s,tabId:o,workerUrl:n,ready:l}}function Pe(e,t=Fe()){try{return t===void 0?void 0:new URL(e??`./shared-worker.js`,t).toString()}catch{return}}function Fe(){return typeof location>`u`?void 0:location.href}function Ie(){if(typeof SharedWorker==`function`)return SharedWorker}function Le(e,t){if(t===void 0)return!0;try{return new URL(e,t).origin===new URL(t).origin}catch{return!1}}function Re(){return`tab-${typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():Math.random().toString(36).slice(2)}`}function ze(){return`attach-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}h();var Be=class{mediaDevices;createAudioElement;outputCapability;outputDeviceId;outputGeneration=0;outputTail;constructor(e={}){this.mediaDevices=e.mediaDevices===null?void 0:e.mediaDevices??Ve(),this.createAudioElement=e.createAudioElement}async requestPermission(e={}){let t=this.requireMediaDevices(),n;try{n=await t.getUserMedia({audio:e})}catch(e){throw We(e)}He(n)}async getDevices(){if(this.mediaDevices===void 0)return[];try{return(await this.mediaDevices.enumerateDevices()).filter(e=>e.kind===`audioinput`||e.kind===`audiooutput`&&this.supportsOutputSelection())}catch(e){throw Ge(e)}}getCapabilities(){return{input:this.mediaDevices!==void 0,output:this.supportsOutputSelection()}}supportsOutputSelection(){if(this.outputCapability!==void 0)return this.outputCapability;let e=this.createAudioElementSafely();return this.outputCapability=e!==void 0&&typeof e.setSinkId==`function`,this.outputCapability}async setOutputDevice(e,t){if(!this.supportsOutputSelection())throw new m(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);this.outputDeviceId=e;let n=++this.outputGeneration;t!==void 0&&await this.enqueueOutput(async()=>{n===this.outputGeneration&&await this.applyOutputDevice(e,t)})}async applyConfiguredOutputDevice(e){if(this.outputDeviceId===void 0||e===void 0)return;let t=this.outputDeviceId,n=this.outputGeneration;await this.enqueueOutput(async()=>{n===this.outputGeneration&&await this.applyOutputDevice(t,e)})}getOutputDeviceId(){return this.outputDeviceId}async applyOutputDevice(e,t){let n=t;if(typeof n.setSinkId!=`function`)throw new m(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);try{await n.setSinkId(e)}catch(e){throw Ke(e)}}enqueueOutput(e){let t=this.outputTail,n=t===void 0?e():t.then(e,e),r=n.catch(()=>void 0);return this.outputTail=r,r.then(()=>{this.outputTail===r&&(this.outputTail=void 0)}),n}async openInputStream(e){let t=this.requireMediaDevices();try{return await t.getUserMedia({audio:{deviceId:{exact:e}}})}catch(e){throw Ue(e)}}requireMediaDevices(){if(this.mediaDevices===void 0)throw new m(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);return this.mediaDevices}createAudioElementSafely(){if(this.createAudioElement!==void 0)try{return this.createAudioElement()}catch{return}if(typeof document<`u`)try{return document.createElement(`audio`)}catch{return}}};function Ve(){return globalThis.navigator?.mediaDevices}function He(e){let t;try{t=e.getTracks()}catch{return}t.forEach(e=>{try{e.stop()}catch{}})}function Ue(e){let t=qe(e);return t===`NotFoundError`||t===`OverconstrainedError`?new m(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:e}):t===`NotReadableError`||t===`AbortError`?new m(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:e}):t===`NotAllowedError`||t===`SecurityError`?new m(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:e}):new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}function We(e){let t=qe(e);return t===`NotFoundError`||t===`OverconstrainedError`?new m(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:e}):t===`NotReadableError`||t===`AbortError`?new m(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:e}):t===`NotAllowedError`||t===`SecurityError`?new m(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:e}):new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}function Ge(e){let t=qe(e);return t===`NotFoundError`?new m(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:e}):t===`NotAllowedError`||t===`SecurityError`?new m(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:e}):t===`AbortError`||t===`NotReadableError`?new m(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:e}):new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}function Ke(e){let t=qe(e);return t===`NotFoundError`?new m(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:e}):t===`NotAllowedError`||t===`SecurityError`?new m(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:e}):t===`AbortError`||t===`NotReadableError`?new m(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:e}):new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:e})}function qe(e){if(typeof e!=`object`||!e||!(`name`in e))return;let t=e.name;return typeof t==`string`?t:void 0}h();var Je=class{createAudioElement;bindings=new Map;audioOwners=new Map;trackOwners=new Map;generations=new Map;pendingPlays=new Map;constructor(e=Ye){this.createAudioElement=e}async bind(e,t){let n=this.bindings.get(e);if(n?.stream===t)return;let r=Xe(e,t),i;try{i=this.createAudioElement()}catch(t){throw L(r,this.trackOwners),new m(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:e,cause:t})}let a=this.audioOwners.get(i);if(a!==void 0&&a!==e)throw L(r,this.trackOwners),new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e});try{i.autoplay=!0,i.playsInline=!0}catch(t){throw L(r,this.trackOwners),new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e,cause:t})}try{i.srcObject=t}catch(t){throw L(r,this.trackOwners),new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e,cause:t})}this.acquireTracks(r),n!==void 0&&this.releaseBinding(n,n.audio!==i);let o=this.nextGeneration(e);this.audioOwners.set(i,e);let s={callId:e,audio:i,stream:t,tracks:r,generation:o};this.bindings.set(e,s),this.beginPlay(e);try{await i.play()}catch(t){if(!this.isCurrent(e,o))return;throw new m(`MEDIA_PLAYBACK_BLOCKED`,`media`,!1,{callId:e,cause:t})}finally{this.finishPlay(e)}this.isCurrent(e,o)}async play(e){let t=this.bindings.get(e);if(t===void 0)throw new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e});let n=t.generation;this.beginPlay(e);try{await t.audio.play()}catch(t){if(!this.isCurrent(e,n))return;throw new m(`MEDIA_PLAYBACK_BLOCKED`,`media`,!1,{callId:e,cause:t})}finally{this.finishPlay(e)}this.isCurrent(e,n)}getAudioElement(e){return this.bindings.get(e)?.audio}getResourceCounts(){return{tracks:this.trackOwners.size,audioElements:this.audioOwners.size}}release(e){this.nextGeneration(e);let t=this.bindings.get(e);t!==void 0&&this.releaseBinding(t),this.cleanupGeneration(e)}releaseAll(){[...this.bindings.keys()].forEach(e=>this.release(e))}releaseBinding(e,t=!0){if(this.bindings.get(e.callId)===e&&this.bindings.delete(e.callId),this.audioOwners.get(e.audio)===e.callId&&this.audioOwners.delete(e.audio),t)try{e.audio.srcObject=null}catch{}e.tracks.forEach(e=>this.releaseTrack(e))}acquireTracks(e){e.forEach(e=>this.trackOwners.set(e,(this.trackOwners.get(e)??0)+1))}releaseTrack(e){let t=this.trackOwners.get(e);if(t===void 0||t<=1){this.trackOwners.delete(e),Qe(e);return}this.trackOwners.set(e,t-1)}beginPlay(e){this.pendingPlays.set(e,(this.pendingPlays.get(e)??0)+1)}finishPlay(e){let t=this.pendingPlays.get(e)??0;t<=1?this.pendingPlays.delete(e):this.pendingPlays.set(e,t-1),this.cleanupGeneration(e)}nextGeneration(e){let t=(this.generations.get(e)??0)+1;return this.generations.set(e,t),t}cleanupGeneration(e){!this.bindings.has(e)&&!this.pendingPlays.has(e)&&this.generations.delete(e)}isCurrent(e,t){return this.generations.get(e)===t&&this.bindings.get(e)?.generation===t}};function Ye(){if(typeof document>`u`)throw new m(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);return document.createElement(`audio`)}function Xe(e,t){try{return[...new Set(t.getAudioTracks())].filter(e=>e.kind===`audio`)}catch(n){try{return[...new Set(t.getTracks())].filter(e=>e.kind===`audio`)}catch(r){throw Ze(t),new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e,cause:n??r})}}}function L(e,t){e.forEach(e=>{(t.get(e)??0)===0&&Qe(e)})}function Ze(e){try{[...new Set(e.getTracks())].filter(e=>e.kind===`audio`).forEach(Qe)}catch{}}function Qe(e){try{e.stop()}catch{}}h();var $e=class{deviceManager;remoteAudio;getActiveCall;createRemoteStream;calls=new Map;resources=new Set;inputOperations=new Map;senderQueues=new Map;releaseOperations=new Map;callReleaseOperations=new Map;releaseErrors=new WeakMap;releaseAllOperation;disposeOperation;disposing=!1;disposed=!1;constructor(e={}){let t={mediaDevices:e.mediaDevices,createAudioElement:e.createAudioElement};this.deviceManager=new Be(t),this.remoteAudio=new Je(e.createAudioElement),this.getActiveCall=e.getActiveCall,this.createRemoteStream=e.createRemoteStream??it}requestPermission(e){return this.assertNotDisposed(),this.deviceManager.requestPermission(e)}getDevices(){return this.assertNotDisposed(),this.deviceManager.getDevices()}getCapabilities(){return this.assertNotDisposed(),this.deviceManager.getCapabilities()}supportsOutputSelection(){return this.assertNotDisposed(),this.deviceManager.supportsOutputSelection()}registerCallMedia(e,t){this.assertNotDisposed();let n=this.calls.get(e);n!==void 0&&this.releaseResource(n).catch(e=>{this.releaseErrors.set(n,e)});let r=et(t)?t:{peerConnection:t},i={callId:e,peerConnection:r.peerConnection,senders:new Map,localTracks:new Set,pendingTracks:new Set,generation:1,released:!1,peerClosed:!1};if(this.captureSenders(i,r.getSenderKind),this.resources.add(i),r.localTracks?.forEach(e=>{e.kind===`audio`&&i.localTracks.add(e)}),this.calls.set(e,i),r.trackSource!==void 0)try{i.trackSourceUnsubscribe=r.trackSource.onTrack(e=>this.handleTrackEvent(i,e))}catch{}return async()=>{let e=this.releaseOperations.get(i);if(e!==void 0)await e;else if(this.releaseErrors.has(i))throw this.releaseErrors.get(i);else await this.releaseResource(i);let t=this.releaseErrors.get(i);if(t!==void 0)throw t}}async setInputDevice(e,t){this.assertNotDisposed();let n=t??this.getActiveCall?.();this.assertActiveCall(n),this.assertDeviceSelectionCapability(n);let r=this.ensureCallMedia(n),i=(this.inputOperations.get(n.callId)??Promise.resolve()).then(()=>this.performInputSwitch(e,n,r),()=>this.performInputSwitch(e,n,r));this.inputOperations.set(n.callId,i);try{await i}finally{this.inputOperations.get(n.callId)===i&&this.inputOperations.delete(n.callId)}}setOutputDevice(e,t){this.assertNotDisposed();let n=t??this.getActiveCall?.()?.callId,r=n===void 0?void 0:this.remoteAudio.getAudioElement(n);return this.deviceManager.setOutputDevice(e,r)}async bindRemoteTrack(e,t){this.assertNotDisposed();let n;try{await this.remoteAudio.bind(e,t)}catch(e){n=e}let r;try{await this.deviceManager.applyConfiguredOutputDevice(this.remoteAudio.getAudioElement(e))}catch(e){r=e}if(n!==void 0)throw n;if(r!==void 0)throw r}playRemoteAudio(e){return this.assertNotDisposed(),this.remoteAudio.play(e)}getResourceCounts(){let e=new Set;this.resources.forEach(t=>{t.localTracks.forEach(t=>e.add(t)),t.pendingTracks.forEach(t=>e.add(t))});let t=this.remoteAudio.getResourceCounts();return{listeners:[...this.resources].filter(e=>e.trackSourceUnsubscribe!==void 0).length,tracks:e.size+t.tracks,peerConnections:this.resources.size,audioElements:t.audioElements}}releaseResource(e){let t=this.releaseOperations.get(e);if(t!==void 0)return t;if(!this.resources.has(e))return Promise.resolve();let n=e.callId;this.remoteAudio.release(n),this.releaseErrors.delete(e),this.calls.get(n)===e&&this.calls.delete(n),e.generation+=1,e.released=!0,this.unsubscribeTrackSource(e);let r=new Set([...e.localTracks,...e.pendingTracks]),i=[...e.senders.values()].filter(e=>e.audio).map(t=>({senderResource:t,promise:this.enqueueSender(e,t,()=>nt(t.sender),!0)})),a=Promise.all(i.map(async e=>{try{return await e.promise,{senderResource:e.senderResource,cause:void 0}}catch(t){return{senderResource:e.senderResource,cause:t}}})).then(async t=>{let i=new Set,a=[];if(t.forEach(e=>{if(e.cause!==void 0){a.push(e.cause);let t=R(e.senderResource.sender);t?.kind===`audio`&&i.add(t);return}let t=R(e.senderResource.sender);t?.kind===`audio`&&r.add(t)}),r.forEach(e=>{i.has(e)||B(e)}),a.length>0)throw e.localTracks.clear(),e.pendingTracks.clear(),i.forEach(t=>e.localTracks.add(t)),new m(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:n,cause:a[0]});if(!e.peerClosed&&e.peerConnection.close!==void 0)try{await e.peerConnection.close(),e.peerClosed=!0}catch(t){let r=[...e.senders.values()].map(e=>R(e.sender)).find(e=>e?.kind===`audio`);throw e.localTracks.clear(),e.pendingTracks.clear(),r!=null&&e.localTracks.add(r),new m(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:n,cause:t})}e.localTracks.clear(),e.pendingTracks.clear(),e.senders.clear(),this.resources.delete(e),this.releaseUnusedSenderQueues()}).catch(t=>{throw this.releaseErrors.set(e,t),this.calls.get(n)===void 0&&this.calls.set(n,e),t}).finally(()=>{this.releaseOperations.get(e)===a&&this.releaseOperations.delete(e)});return this.releaseOperations.set(e,a),a}releaseCall(e){let t=this.callReleaseOperations.get(e);if(t!==void 0)return t;let n=[...this.resources].filter(t=>t.callId===e);if(n.length===0)return Promise.resolve();let r=Promise.all(n.map(async e=>{try{return await this.releaseResource(e),{cause:void 0}}catch(e){return{cause:e}}})).then(e=>{let t=e.find(e=>e.cause!==void 0)?.cause;if(t!==void 0)throw t}).finally(()=>{this.callReleaseOperations.get(e)===r&&this.callReleaseOperations.delete(e)});return this.callReleaseOperations.set(e,r),r}releaseAll(){if(this.releaseAllOperation!==void 0)return this.releaseAllOperation;this.remoteAudio.releaseAll();let e=new Set([...this.resources].map(e=>e.callId)),t=Promise.all([...e].map(async e=>{try{return await this.releaseCall(e),{cause:void 0}}catch(e){return{cause:e}}})).then(e=>{let t=e.find(e=>e.cause!==void 0)?.cause;if(t!==void 0)throw t}).finally(()=>{this.releaseAllOperation===t&&(this.releaseAllOperation=void 0)});return this.releaseAllOperation=t,t}dispose(){if(this.disposeOperation!==void 0)return this.disposeOperation;this.disposing=!0;let e=this.releaseAll(),t=this.waitForInputOperations(),n=Promise.allSettled([e,t]).then(e=>{let t=e.find(e=>e.status===`rejected`);if(t?.status===`rejected`)throw t.reason;this.inputOperations.clear(),this.disposed=!0,this.disposing=!1}).finally(()=>{this.disposeOperation===n&&!this.disposed&&(this.disposeOperation=void 0),!this.disposed&&this.disposeOperation===void 0&&(this.disposing=!1)});return this.disposeOperation=n,n}async waitForInputOperations(){let e=[...this.inputOperations.values()];e.length!==0&&await Promise.allSettled(e)}async performInputSwitch(e,t,n){if(this.assertActiveCall(t),this.assertDeviceSelectionCapability(t),!this.isCurrentResource(n)||t.peerConnection!==n.peerConnection)throw this.callOperationError(t.callId);let r=this.findAudioSender(n),i=R(r.sender),a=n.generation,o=await this.deviceManager.openInputStream(e),s;try{s=o.getTracks()}catch(e){throw rt(o),new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t.callId,cause:e})}let c;try{c=o.getAudioTracks()}catch(e){throw z(s),new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t.callId,cause:e})}let l=c[0];if(l===void 0)throw z(s),new m(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{callId:t.callId});if(!this.canCommitInputSwitch(t,n,r,i,a))throw z(s),this.callOperationError(t.callId);s.forEach(e=>n.pendingTracks.add(e)),n.pendingTracks.add(l);try{await this.enqueueSender(n,r,()=>r.sender.replaceTrack(l))}catch(e){throw n.released?this.callOperationError(t.callId):(n.released||(s.forEach(e=>n.pendingTracks.delete(e)),n.pendingTracks.delete(l),await this.rollbackSender(n,r,i,l),z(s)),new m(`MEDIA_DEVICE_IN_USE`,`media`,!0,{callId:t.callId,cause:e}))}if(!this.canCommitInputSwitch(t,n,r,l,a)){if(!n.released)try{await this.enqueueSender(n,r,()=>R(r.sender)===l?nt(r.sender):Promise.resolve()),s.forEach(e=>n.pendingTracks.delete(e)),n.pendingTracks.delete(l),z(s)}catch(e){throw new m(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:t.callId,cause:e})}throw this.callOperationError(t.callId)}s.forEach(e=>n.pendingTracks.delete(e)),n.pendingTracks.delete(l),n.localTracks.add(l),i!==null&&i!==l&&(n.localTracks.delete(i),B(i)),s.forEach(e=>{e!==l&&B(e)})}ensureCallMedia(e){let t=this.calls.get(e.callId);if(t!==void 0&&t.peerConnection===e.peerConnection)return t;if(e.peerConnection===void 0)throw this.capabilityError(e.callId);this.registerCallMedia(e.callId,e.peerConnection);let n=this.calls.get(e.callId);if(n===void 0)throw this.callOperationError(e.callId);return n}captureSenders(e,t){let n;try{n=e.peerConnection.getSenders()}catch(t){throw new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e.callId,cause:t})}n.forEach(n=>{let r=R(n),i;try{i=t?.(n)??n.senderKind??n.kind}catch(t){throw new m(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:e.callId,cause:t})}e.senders.set(n,{sender:n,audio:i===`audio`||i===void 0&&r?.kind===`audio`,queue:this.senderQueues.get(n)??this.createSenderQueue(n)}),r?.kind===`audio`&&e.localTracks.add(r)})}findAudioSender(e){let t=[...e.senders.values()].find(e=>e.audio&&(R(e.sender)?.kind===`audio`||R(e.sender)===null));if(t===void 0)throw this.capabilityError(e.callId);return t}handleTrackEvent(e,t){if(!this.isCurrentResource(e)||t.track.kind!==`audio`)return;let n=t.streams[0]??this.createRemoteStream(t.track);n!==void 0&&this.bindRemoteTrack(e.callId,n).catch(()=>void 0)}canCommitInputSwitch(e,t,n,r,i){if(this.disposed||!this.isCurrentResource(t,i)||e.state!==`active`||e.peerConnection!==t.peerConnection||!t.senders.has(n.sender))return!1;try{if(!t.peerConnection.getSenders().includes(n.sender))return!1}catch{return!1}return R(n.sender)===r}enqueueSender(e,t,n,r=!1){t.queue.pending+=1;let i=t.queue.chain.then(async()=>{if(e.released&&!r)throw this.callOperationError(e.callId);return n()},async()=>{if(e.released&&!r)throw this.callOperationError(e.callId);return n()}),a=i.finally(()=>{--t.queue.pending});return t.queue.chain=a.catch(()=>void 0),i}createSenderQueue(e){let t={chain:Promise.resolve(),pending:0};return this.senderQueues.set(e,t),t}releaseUnusedSenderQueues(){let e=new Set;this.resources.forEach(t=>t.senders.forEach(t=>e.add(t.sender))),this.senderQueues.forEach((t,n)=>{t.pending===0&&!e.has(n)&&this.senderQueues.delete(n)})}async rollbackSender(e,t,n,r){e.released||R(t.sender)!==r||await this.enqueueSender(e,t,()=>t.sender.replaceTrack(n)).catch(()=>void 0)}isCurrentResource(e,t=e.generation){return!this.disposed&&this.calls.get(e.callId)===e&&e.generation===t}unsubscribeTrackSource(e){let t=e.trackSourceUnsubscribe;if(e.trackSourceUnsubscribe=void 0,t!==void 0)try{t()}catch{}}assertActiveCall(e){if(e===void 0||e.state!==`active`)throw new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e?.callId})}assertDeviceSelectionCapability(e){if(e.capabilities===void 0||!e.capabilities.has(`device_selection`))throw this.capabilityError(e.callId)}capabilityError(e){return new m(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:e})}callOperationError(e){return new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:e})}assertNotDisposed(){if(this.disposed||this.disposing)throw new m(`SDK_ALREADY_DISPOSED`,`internal`,!1)}};function et(e){return`peerConnection`in e}function R(e){try{return e.track}catch{return null}}function tt(e){return typeof e==`object`&&!!e&&e.name===`InvalidStateError`}function nt(e){try{return e.replaceTrack(null).catch(e=>{if(!tt(e))throw e})}catch(e){return tt(e)?Promise.resolve():Promise.reject(e)}}function rt(e){try{z(e.getTracks())}catch{}}function z(e){e.forEach(B)}function B(e){try{e.stop()}catch{}}function it(e){if(typeof MediaStream<`u`)try{return new MediaStream([e])}catch{return}}h();function at(e,t={}){let n=new Map,r=new Map,i=new Set,a=t.ownershipRequired===!0,o=!1,s=!1,c,l=()=>e(),u=new $e({getActiveCall:l});return{publicMedia:{requestPermission:()=>(d(),u.requestPermission()),getDevices:()=>(d(),u.getDevices()),getCapabilities:()=>(d(),u.getCapabilities()),supportsOutputSelection:()=>(d(),u.supportsOutputSelection()),setInputDevice:e=>(d(),u.setInputDevice(e,l())),setOutputDevice:e=>(d(),u.setOutputDevice(e)),playRemoteAudio:e=>(d(),u.playRemoteAudio(e)),releaseAll:()=>(d(),u.releaseAll())},registerCall(e,t){o||s||!ot(t)||(r.set(e,t),(!a||i.has(e))&&f(e,t))},async setCallOwnership(e,t){if(o)return;if(t!==`owned`){i.delete(e),await u.releaseCall(e),n.delete(e);return}i.add(e);let a=r.get(e);a!==void 0&&f(e,a)},contextFor(e,t,r){let i=n.get(e);if(i!==void 0)return{callId:e,state:t,capabilities:r,peerConnection:i.peerConnection}},async releaseCall(e){o||(await u.releaseCall(e),n.delete(e),r.delete(e),i.delete(e))},releaseAll:async()=>{await u.releaseAll(),n.clear(),r.clear(),i.clear()},getResourceCounts:()=>u.getResourceCounts(),dispose:()=>{if(c!==void 0)return c;s=!0;let e=u.dispose().then(()=>{o=!0,s=!1,n.clear(),r.clear(),i.clear()}).finally(()=>{c===e&&!o&&(c=void 0,s=!1)});return c=e,e}};function d(){if(o)throw new m(`SDK_ALREADY_DISPOSED`,`internal`,!1)}function f(e,t){if(!ot(t)||typeof t.getMediaRegistration!=`function`)return;let r=t.getMediaRegistration();if(st(r)&&n.get(e)?.peerConnection!==r.peerConnection){n.set(e,r);try{u.registerCallMedia(e,r)}catch{n.delete(e)}}}}function ot(e){return typeof e==`object`&&!!e}function st(e){return typeof e==`object`&&!!e&&`peerConnection`in e&&typeof e.peerConnection==`object`&&e.peerConnection!==null}var ct=1e3,lt=3e4;function ut(e,t=Math.random){let n=Math.min(lt,ct*2**Math.max(0,Math.floor(e))),r=Math.min(1,Math.max(0,t()));return Math.round(n*(1+r*.2))}var dt=class{recover;isRecovered;random;isOnline;onAttempt;attempt=0;pendingTimer;running=!1;online=!0;generation=0;disposed=!1;restartAfterRun=!1;constructor(e){this.recover=e.recover,this.isRecovered=e.isRecovered,this.random=e.random??Math.random,this.isOnline=e.isOnline??(()=>!0),this.onAttempt=e.onAttempt}start(){if(this.disposed||!this.online||!this.isOnline()||this.pendingTimer!==void 0||this.running)return;let e=this.generation,t=ut(this.attempt,this.random);this.pendingTimer=setTimeout(()=>{this.pendingTimer=void 0,this.run(e)},t)}notifyOffline(){this.disposed||(this.online=!1,this.generation+=1,this.clearPendingTimer(),this.restartAfterRun=!1)}notifyOnline(){this.disposed||(this.online=!0,this.running&&(this.restartAfterRun=!0),this.start())}cancel(){this.disposed||(this.generation+=1,this.clearPendingTimer(),this.attempt=0,this.restartAfterRun=!1)}dispose(){this.disposed||(this.disposed=!0,this.generation+=1,this.clearPendingTimer(),this.restartAfterRun=!1)}getTimerCount(){return this.pendingTimer===void 0?0:1}async run(e){if(this.disposed||!this.online||e!==this.generation||this.running)return;this.running=!0;try{this.onAttempt?.(this.attempt)}catch{}let t=!1;try{await this.recover(),this.isCurrent(e)&&(this.attempt=0)}catch{this.isCurrent(e)&&(this.attempt+=1,t=!0)}finally{this.running=!1}!t&&this.isCurrent(e)&&this.isRecovered!==void 0&&!this.isRecovered()&&(this.attempt+=1,t=!0),this.restartAfterRun?(this.restartAfterRun=!1,this.isCurrent(this.generation)&&this.start()):t&&this.isCurrent(e)&&this.start()}isCurrent(e){return!this.disposed&&this.online&&e===this.generation&&this.isOnline()}clearPendingTimer(){this.pendingTimer!==void 0&&(clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}},ft=class{capacity;entries=[];constructor(e){if(this.capacity=e,!Number.isInteger(e)||e<=0)throw RangeError(`RingBuffer capacity must be a positive integer`)}push(e){this.entries.length===this.capacity&&this.entries.shift(),this.entries.push(e)}toArray(){return[...this.entries]}},pt=`@16x/webphone-sdk`,mt=200,ht=class{dependencies;logs=new ft(mt);now;constructor(e){this.dependencies=e,this.now=e.now??(()=>new Date)}log(e,t,n){this.logs.push({timestamp:this.now().toISOString(),level:e,message:Ee(t),...n===void 0?{}:{context:De(n)}})}async getReport(e={}){let t=e.includeRecentLogs!==!1,n=e.includeDeviceNames===!0,r=e.maskPhoneNumbers!==!1,i=this.dependencies.getSnapshot(),a=this.dependencies.getPermission===void 0?i.permission:await gt(this.dependencies.getPermission,i.permission),o=n?await _t(this.dependencies.getDeviceNames):void 0,s=yt(vt(this.dependencies.getUserAgent));return De({generatedAt:this.now().toISOString(),sdk:{name:pt,version:M},browser:s.browser,os:s.os,...i,permission:a,recentLogs:t?this.logs.toArray():[],...o===void 0?{}:{deviceNames:o}},{maskPhoneNumbers:r})}};async function gt(e,t){try{return await e()}catch{return t}}async function _t(e){if(e===void 0)return[];try{return[...await e()]}catch{return[]}}function vt(e){if(e!==void 0)try{return e()}catch{return``}return typeof navigator>`u`?``:navigator.userAgent}function yt(e){return{browser:bt(e),os:xt(e)}}function bt(e){for(let[t,n]of[[`Edge`,/Edg\/([\d.]+)/],[`Chrome`,/(?:Chrome|CriOS)\/([\d.]+)/],[`Firefox`,/(?:Firefox|FxiOS)\/([\d.]+)/],[`Safari`,/Version\/([\d.]+).*Safari/]]){let r=e.match(n);if(r?.[1]!==void 0)return{name:t,version:r[1]}}return{name:`unknown`,version:``}}function xt(e){let t=e.match(/(?:iPhone|iPad).*OS ([\d_]+)/);if(t?.[1]!==void 0)return{name:`iOS`,version:t[1].replaceAll(`_`,`.`)};let n=e.match(/Android ([\d.]+)/);if(n?.[1]!==void 0)return{name:`Android`,version:n[1]};let r=e.match(/Windows NT ([\d.]+)/);if(r?.[1]!==void 0)return{name:`Windows`,version:r[1]};let i=e.match(/Mac OS X ([\d_]+)/);return i?.[1]===void 0?/Linux/.test(e)?{name:`Linux`,version:``}:{name:`unknown`,version:``}:{name:`macOS`,version:i[1].replaceAll(`_`,`.`)}}var St=l({bugs:()=>Nt,contributors:()=>Ot,default:()=>Lt,dependencies:()=>Ft,description:()=>Tt,devDependencies:()=>It,files:()=>Pt,homepage:()=>Dt,keywords:()=>jt,license:()=>`MIT`,main:()=>At,name:()=>Ct,repository:()=>Mt,scripts:()=>V,title:()=>wt,types:()=>kt,version:()=>Et}),Ct,wt,Tt,Et,Dt,Ot,kt,At,jt,Mt,Nt,Pt,V,Ft,It,Lt,Rt=s((()=>{Ct=`jssip`,wt=`JsSIP`,Tt=`The Javascript SIP library`,Et=`3.13.8`,Dt=`https://jssip.net`,Ot=[`José Luis Millán <jmillan@aliax.net> (https://github.com/jmillan)`,`Iñaki Baz Castillo <ibc@aliax.net> (https://inakibaz.me)`],kt=`lib/JsSIP.d.ts`,At=`lib/JsSIP.js`,jt=[`sip`,`websocket`,`webrtc`,`node`,`browser`,`library`],Mt={type:`git`,url:`https://github.com/versatica/JsSIP.git`},Nt={url:`https://github.com/versatica/JsSIP/issues`},Pt=[`LICENSE`,`README.md`,`npm-scripts.mjs`,`lib`],V={lint:`node npm-scripts.mjs lint`,"lint:fix":`node npm-scripts.mjs lint:fix`,test:`node npm-scripts.mjs test`,coverage:`node npm-scripts.mjs coverage`,build:`node npm-scripts.mjs build`,"typescript:build":`node npm-scripts.mjs typescript:build`,release:`node npm-scripts.mjs release`,docs:`node npm-scripts.mjs docs`,"docs:watch":`node npm-scripts.mjs docs:watch`,"docs:check":`node npm-scripts.mjs docs:check`},Ft={debug:`^4.3.1`,events:`^3.3.0`,"sdp-transform":`^2.14.1`},It={"@eslint/eslintrc":`^3.3.3`,"@eslint/js":`^9.39.2`,"@types/debug":`^4.1.12`,"@types/events":`^3.0.3`,"@types/jest":`^30.0.0`,"@types/node":`^25.0.10`,cpx:`^1.5.0`,esbuild:`^0.27.2`,eslint:`^9.39.1`,"eslint-config-prettier":`^10.1.8`,"eslint-plugin-jest":`^29.12.1`,"eslint-plugin-prettier":`^5.5.5`,globals:`^17.0.0`,jest:`^30.2.0`,"open-cli":`^8.0.0`,pegjs:`^0.7.0`,prettier:`^3.8.1`,"ts-jest":`^29.4.6`,typedoc:`^0.28.16`,typescript:`^5.9.3`,"typescript-eslint":`^8.53.1`},Lt={name:Ct,title:wt,description:Tt,version:Et,homepage:Dt,contributors:Ot,types:kt,main:At,keywords:jt,license:`MIT`,repository:Mt,bugs:Nt,files:Pt,scripts:V,dependencies:Ft,devDependencies:It}})),H=c(((e,t)=>{var n=(Rt(),f(St).default);t.exports={USER_AGENT:`${n.title} ${n.version}`,SIP:`sip`,SIPS:`sips`,causes:{CONNECTION_ERROR:`Connection Error`,REQUEST_TIMEOUT:`Request Timeout`,SIP_FAILURE_CODE:`SIP Failure Code`,INTERNAL_ERROR:`Internal Error`,BUSY:`Busy`,REJECTED:`Rejected`,REDIRECTED:`Redirected`,UNAVAILABLE:`Unavailable`,NOT_FOUND:`Not Found`,ADDRESS_INCOMPLETE:`Address Incomplete`,INCOMPATIBLE_SDP:`Incompatible SDP`,MISSING_SDP:`Missing SDP`,AUTHENTICATION_ERROR:`Authentication Error`,BYE:`Terminated`,WEBRTC_ERROR:`WebRTC Error`,CANCELED:`Canceled`,NO_ANSWER:`No Answer`,EXPIRES:`Expires`,NO_ACK:`No ACK`,DIALOG_ERROR:`Dialog Error`,USER_DENIED_MEDIA_ACCESS:`User Denied Media Access`,BAD_MEDIA_DESCRIPTION:`Bad Media Description`,RTP_TIMEOUT:`RTP Timeout`},SIP_ERROR_CAUSES:{REDIRECTED:[300,301,302,305,380],BUSY:[486,600],REJECTED:[403,603],NOT_FOUND:[404,604],UNAVAILABLE:[480,410,408,430],ADDRESS_INCOMPLETE:[484,424],INCOMPATIBLE_SDP:[488,606],AUTHENTICATION_ERROR:[401,407]},ACK:`ACK`,BYE:`BYE`,CANCEL:`CANCEL`,INFO:`INFO`,INVITE:`INVITE`,MESSAGE:`MESSAGE`,NOTIFY:`NOTIFY`,OPTIONS:`OPTIONS`,REGISTER:`REGISTER`,REFER:`REFER`,UPDATE:`UPDATE`,SUBSCRIBE:`SUBSCRIBE`,DTMF_TRANSPORT:{INFO:`INFO`,RFC2833:`RFC2833`},REASON_PHRASE:{100:`Trying`,180:`Ringing`,181:`Call Is Being Forwarded`,182:`Queued`,183:`Session Progress`,199:`Early Dialog Terminated`,200:`OK`,202:`Accepted`,204:`No Notification`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Moved Temporarily`,305:`Use Proxy`,380:`Alternative Service`,400:`Bad Request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,410:`Gone`,412:`Conditional Request Failed`,413:`Request Entity Too Large`,414:`Request-URI Too Long`,415:`Unsupported Media Type`,416:`Unsupported URI Scheme`,417:`Unknown Resource-Priority`,420:`Bad Extension`,421:`Extension Required`,422:`Session Interval Too Small`,423:`Interval Too Brief`,424:`Bad Location Information`,428:`Use Identity Header`,429:`Provide Referrer Identity`,430:`Flow Failed`,433:`Anonymity Disallowed`,436:`Bad Identity-Info`,437:`Unsupported Certificate`,438:`Invalid Identity Header`,439:`First Hop Lacks Outbound Support`,440:`Max-Breadth Exceeded`,469:`Bad Info Package`,470:`Consent Needed`,478:`Unresolvable Destination`,480:`Temporarily Unavailable`,481:`Call/Transaction Does Not Exist`,482:`Loop Detected`,483:`Too Many Hops`,484:`Address Incomplete`,485:`Ambiguous`,486:`Busy Here`,487:`Request Terminated`,488:`Not Acceptable Here`,489:`Bad Event`,491:`Request Pending`,493:`Undecipherable`,494:`Security Agreement Required`,500:`JsSIP Internal Error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Service Unavailable`,504:`Server Time-out`,505:`Version Not Supported`,513:`Message Too Large`,580:`Precondition Failure`,600:`Busy Everywhere`,603:`Decline`,604:`Does Not Exist Anywhere`,606:`Not Acceptable`},ALLOWED_METHODS:`INVITE,ACK,CANCEL,BYE,UPDATE,MESSAGE,OPTIONS,REFER,INFO,NOTIFY,SUBSCRIBE`,ACCEPTED_BODY_TYPES:`application/sdp, application/dtmf-relay`,MAX_FORWARDS:69,SESSION_EXPIRES:90,MIN_SESSION_EXPIRES:60,CONNECTION_RECOVERY_MAX_INTERVAL:30,CONNECTION_RECOVERY_MIN_INTERVAL:2}})),U=c(((e,t)=>{t.exports={ConfigurationError:class extends Error{constructor(e,t){super(),this.code=1,this.name=`CONFIGURATION_ERROR`,this.parameter=e,this.value=t,this.message=this.value?`Invalid value ${JSON.stringify(this.value)} for parameter "${this.parameter}"`:`Missing parameter: ${this.parameter}`}},InvalidStateError:class extends Error{constructor(e){super(),this.code=2,this.name=`INVALID_STATE_ERROR`,this.status=e,this.message=`Invalid status: ${e}`}},NotSupportedError:class extends Error{constructor(e){super(),this.code=3,this.name=`NOT_SUPPORTED_ERROR`,this.message=e}},NotReadyError:class extends Error{constructor(e){super(),this.code=4,this.name=`NOT_READY_ERROR`,this.message=e}}}})),zt=c(((e,t)=>{var n=G(),r=W();t.exports=class e{static parse(e){if(e=r.parse(e,`Name_Addr_Header`),e!==-1)return e}constructor(e,t,r){if(!e||!(e instanceof n))throw TypeError(`missing or invalid "uri" parameter`);this._uri=e,this._parameters={},this.display_name=t;for(let e in r)Object.prototype.hasOwnProperty.call(r,e)&&this.setParam(e,r[e])}get uri(){return this._uri}get display_name(){return this._display_name}set display_name(e){this._display_name=e===0?`0`:e}setParam(e,t){e&&(this._parameters[e.toLowerCase()]=t==null?null:t.toString())}getParam(e){if(e)return this._parameters[e.toLowerCase()]}hasParam(e){if(e)return this._parameters.hasOwnProperty(e.toLowerCase())&&!0||!1}deleteParam(e){if(e=e.toLowerCase(),this._parameters.hasOwnProperty(e)){let t=this._parameters[e];return delete this._parameters[e],t}}clearParams(){this._parameters={}}clone(){return new e(this._uri.clone(),this._display_name,JSON.parse(JSON.stringify(this._parameters)))}_quote(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}toString(){let e=this._display_name?`"${this._quote(this._display_name)}" `:``;e+=`<${this._uri.toString()}>`;for(let t in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,t)&&(e+=`;${t}`,this._parameters[t]!==null&&(e+=`=${this._parameters[t]}`));return e}}})),W=c(((e,t)=>{t.exports=(function(){function e(e){return`"`+e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\x08/g,`\\b`).replace(/\t/g,`\\t`).replace(/\n/g,`\\n`).replace(/\f/g,`\\f`).replace(/\r/g,`\\r`).replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g,escape)+`"`}var t={parse:function(t,n){var r={CRLF:l,DIGIT:u,ALPHA:d,HEXDIG:f,WSP:p,OCTET:m,DQUOTE:h,SP:g,HTAB:_,alphanum:v,reserved:y,unreserved:b,mark:x,escaped:S,LWS:C,SWS:w,HCOLON:ee,TEXT_UTF8_TRIM:T,TEXT_UTF8char:E,UTF8_NONASCII:D,UTF8_CONT:te,LHEX:ne,token:O,token_nodot:re,separators:ie,word:ae,STAR:oe,SLASH:se,EQUAL:k,LPAREN:ce,RPAREN:le,RAQUOT:ue,LAQUOT:de,COMMA:A,SEMI:j,COLON:fe,LDQUOT:pe,RDQUOT:me,comment:he,ctext:ge,quoted_string:_e,quoted_string_clean:M,qdtext:N,quoted_pair:ve,SIP_URI_noparams:ye,SIP_URI:be,uri_scheme:xe,uri_scheme_sips:Se,uri_scheme_sip:Ce,userinfo:we,user:Te,user_unreserved:Ee,password:De,hostport:Oe,host:ke,hostname:Ae,domainlabel:je,toplabel:P,IPv6reference:Me,IPv6address:Ne,h16:F,ls32:I,IPv4address:Pe,dec_octet:Fe,port:Ie,uri_parameters:Le,uri_parameter:Re,transport_param:ze,user_param:Be,method_param:Ve,ttl_param:He,maddr_param:Ue,lr_param:We,other_param:Ge,pname:Ke,pvalue:qe,paramchar:Je,param_unreserved:Ye,headers:Xe,header:L,hname:Ze,hvalue:Qe,hnv_unreserved:$e,Request_Response:et,Request_Line:R,Request_URI:tt,absoluteURI:nt,hier_part:rt,net_path:z,abs_path:B,opaque_part:it,uric:at,uric_no_slash:ot,path_segments:st,segment:ct,param:lt,pchar:ut,scheme:dt,authority:ft,srvr:pt,reg_name:mt,query:ht,SIP_Version:gt,INVITEm:_t,ACKm:vt,OPTIONSm:yt,BYEm:bt,CANCELm:xt,REGISTERm:St,SUBSCRIBEm:Ct,NOTIFYm:wt,REFERm:Tt,Method:Et,Status_Line:Dt,Status_Code:Ot,extension_code:kt,Reason_Phrase:At,Allow_Events:jt,Call_ID:Mt,Contact:Nt,contact_param:Pt,name_addr:V,display_name:Ft,contact_params:It,c_p_q:Lt,c_p_expires:Rt,delta_seconds:H,qvalue:U,generic_param:W,gen_value:K,Content_Disposition:q,disp_type:Bt,disp_param:Vt,handling_param:Ht,Content_Encoding:J,Content_Length:Ut,Content_Type:Wt,media_type:Gt,m_type:Kt,discrete_type:Y,composite_type:qt,extension_token:Jt,x_token:Yt,m_subtype:X,m_parameter:Xt,m_value:Zt,CSeq:Qt,CSeq_value:$t,Expires:en,Event:tn,event_type:nn,From:rn,from_param:an,tag_param:on,Max_Forwards:sn,Min_Expires:cn,Name_Addr_Header:ln,Proxy_Authenticate:un,challenge:dn,other_challenge:fn,auth_param:pn,digest_cln:mn,realm:hn,realm_value:gn,domain:_n,URI:vn,nonce:yn,nonce_value:bn,opaque:xn,stale:Sn,algorithm:Cn,qop_options:wn,qop_value:Tn,Proxy_Require:En,Record_Route:Dn,rec_route:On,Reason:kn,reason_param:An,reason_cause:jn,Require:Mn,Route:Nn,route_param:Pn,Subscription_State:Fn,substate_value:In,subexp_params:Ln,event_reason_value:Rn,Subject:zn,Supported:Bn,To:Vn,to_param:Hn,Via:Un,via_param:Wn,via_params:Gn,via_ttl:Kn,via_maddr:qn,via_received:Jn,via_branch:Yn,response_port:Xn,rport:Zn,sent_protocol:Qn,protocol_name:$n,transport:er,sent_by:tr,via_host:nr,via_port:rr,ttl:ir,WWW_Authenticate:ar,Session_Expires:or,s_e_expires:sr,s_e_params:Z,s_e_refresher:cr,extension_header:lr,header_value:ur,message_body:dr,uuid_URI:fr,uuid:pr,hex4:Q,hex8:mr,hex12:hr,Refer_To:gr,Replaces:_r,call_id:vr,replaces_param:yr,to_tag:br,from_tag:xr,early_flag:Sr};if(n!==void 0){if(r[n]===void 0)throw Error(`Invalid rule name: `+e(n)+`.`)}else n=`CRLF`;var i=0,a=0,o=0,s=[];function c(e){i<o||(i>o&&(o=i,s=[]),s.push(e))}function l(){var e;return t.substr(i,2)===`\r
|
|
2
2
|
`?(e=`\r
|
|
3
|
-
`,i+=2):(e=null,a===0&&c(`"\\r\\n"`)),e}function u(){var e;return/^[0-9]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[0-9]`)),e}function d(){var e;return/^[a-zA-Z]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[a-zA-Z]`)),e}function f(){var e;return/^[0-9a-fA-F]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[0-9a-fA-F]`)),e}function p(){var e=g();return e===null&&(e=_()),e}function m(){var e;return/^[\0-\xFF]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[\\0-\\xFF]`)),e}function h(){var e;return/^["]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`["]`)),e}function g(){var e;return t.charCodeAt(i)===32?(e=` `,i++):(e=null,a===0&&c(`" "`)),e}function _(){var e;return t.charCodeAt(i)===9?(e=` `,i++):(e=null,a===0&&c(`"\\t"`)),e}function v(){var e;return/^[a-zA-Z0-9]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[a-zA-Z0-9]`)),e}function y(){var e;return t.charCodeAt(i)===59?(e=`;`,i++):(e=null,a===0&&c(`";"`)),e===null&&(t.charCodeAt(i)===47?(e=`/`,i++):(e=null,a===0&&c(`"/"`)),e===null&&(t.charCodeAt(i)===63?(e=`?`,i++):(e=null,a===0&&c(`"?"`)),e===null&&(t.charCodeAt(i)===58?(e=`:`,i++):(e=null,a===0&&c(`":"`)),e===null&&(t.charCodeAt(i)===64?(e=`@`,i++):(e=null,a===0&&c(`"@"`)),e===null&&(t.charCodeAt(i)===38?(e=`&`,i++):(e=null,a===0&&c(`"&"`)),e===null&&(t.charCodeAt(i)===61?(e=`=`,i++):(e=null,a===0&&c(`"="`)),e===null&&(t.charCodeAt(i)===43?(e=`+`,i++):(e=null,a===0&&c(`"+"`)),e===null&&(t.charCodeAt(i)===36?(e=`$`,i++):(e=null,a===0&&c(`"$"`)),e===null&&(t.charCodeAt(i)===44?(e=`,`,i++):(e=null,a===0&&c(`","`))))))))))),e}function b(){var e=v();return e===null&&(e=x()),e}function x(){var e;return t.charCodeAt(i)===45?(e=`-`,i++):(e=null,a===0&&c(`"-"`)),e===null&&(t.charCodeAt(i)===95?(e=`_`,i++):(e=null,a===0&&c(`"_"`)),e===null&&(t.charCodeAt(i)===46?(e=`.`,i++):(e=null,a===0&&c(`"."`)),e===null&&(t.charCodeAt(i)===33?(e=`!`,i++):(e=null,a===0&&c(`"!"`)),e===null&&(t.charCodeAt(i)===126?(e=`~`,i++):(e=null,a===0&&c(`"~"`)),e===null&&(t.charCodeAt(i)===42?(e=`*`,i++):(e=null,a===0&&c(`"*"`)),e===null&&(t.charCodeAt(i)===39?(e=`'`,i++):(e=null,a===0&&c(`"'"`)),e===null&&(t.charCodeAt(i)===40?(e=`(`,i++):(e=null,a===0&&c(`"("`)),e===null&&(t.charCodeAt(i)===41?(e=`)`,i++):(e=null,a===0&&c(`")"`)))))))))),e}function S(){var e,n,r,o=i,s=i;return t.charCodeAt(i)===37?(e=`%`,i++):(e=null,a===0&&c(`"%"`)),e===null?(e=null,i=s):(n=f(),n===null?(e=null,i=s):(r=f(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){return t.join(``)})(o,e)),e===null&&(i=o),e}function C(){var e,t,n,r=i,a=i,o=i;for(e=[],t=p();t!==null;)e.push(t),t=p();if(e===null?(e=null,i=o):(t=l(),t===null?(e=null,i=o):e=[e,t]),e=e===null?``:e,e!==null){if(n=p(),n!==null)for(t=[];n!==null;)t.push(n),n=p();else t=null;t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e!==null&&(e=(function(e){return` `})(r)),e===null&&(i=r),e}function w(){var e=C();return e=e===null?``:e,e}function ee(){var e,n,r,o=i,s=i;for(e=[],n=g(),n===null&&(n=_());n!==null;)e.push(n),n=g(),n===null&&(n=_());return e===null?(e=null,i=s):(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e){return`:`})(o)),e===null&&(i=o),e}function T(){var e,n,r,a,o=i,s=i,c;if(n=E(),n!==null)for(e=[];n!==null;)e.push(n),n=E();else e=null;if(e!==null){for(n=[],c=i,r=[],a=C();a!==null;)r.push(a),a=C();for(r===null?(r=null,i=c):(a=E(),a===null?(r=null,i=c):r=[r,a]);r!==null;){for(n.push(r),c=i,r=[],a=C();a!==null;)r.push(a),a=C();r===null?(r=null,i=c):(a=E(),a===null?(r=null,i=c):r=[r,a])}n===null?(e=null,i=s):e=[e,n]}else e=null,i=s;return e!==null&&(e=(function(e){return t.substring(i,e)})(o)),e===null&&(i=o),e}function E(){var e;return/^[!-~]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[!-~]`)),e===null&&(e=D()),e}function D(){var e;return/^[\x80-\uFFFF]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[\\x80-\\uFFFF]`)),e}function te(){var e;return/^[\x80-\xBF]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[\\x80-\\xBF]`)),e}function ne(){var e=u();return e===null&&(/^[a-f]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[a-f]`))),e}function O(){var e,n,r=i;if(n=v(),n===null&&(t.charCodeAt(i)===45?(n=`-`,i++):(n=null,a===0&&c(`"-"`)),n===null&&(t.charCodeAt(i)===46?(n=`.`,i++):(n=null,a===0&&c(`"."`)),n===null&&(t.charCodeAt(i)===33?(n=`!`,i++):(n=null,a===0&&c(`"!"`)),n===null&&(t.charCodeAt(i)===37?(n=`%`,i++):(n=null,a===0&&c(`"%"`)),n===null&&(t.charCodeAt(i)===42?(n=`*`,i++):(n=null,a===0&&c(`"*"`)),n===null&&(t.charCodeAt(i)===95?(n=`_`,i++):(n=null,a===0&&c(`"_"`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)),n===null&&(t.charCodeAt(i)===96?(n="`",i++):(n=null,a===0&&c('"`"')),n===null&&(t.charCodeAt(i)===39?(n=`'`,i++):(n=null,a===0&&c(`"'"`)),n===null&&(t.charCodeAt(i)===126?(n=`~`,i++):(n=null,a===0&&c(`"~"`)))))))))))),n!==null)for(e=[];n!==null;)e.push(n),n=v(),n===null&&(t.charCodeAt(i)===45?(n=`-`,i++):(n=null,a===0&&c(`"-"`)),n===null&&(t.charCodeAt(i)===46?(n=`.`,i++):(n=null,a===0&&c(`"."`)),n===null&&(t.charCodeAt(i)===33?(n=`!`,i++):(n=null,a===0&&c(`"!"`)),n===null&&(t.charCodeAt(i)===37?(n=`%`,i++):(n=null,a===0&&c(`"%"`)),n===null&&(t.charCodeAt(i)===42?(n=`*`,i++):(n=null,a===0&&c(`"*"`)),n===null&&(t.charCodeAt(i)===95?(n=`_`,i++):(n=null,a===0&&c(`"_"`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)),n===null&&(t.charCodeAt(i)===96?(n="`",i++):(n=null,a===0&&c('"`"')),n===null&&(t.charCodeAt(i)===39?(n=`'`,i++):(n=null,a===0&&c(`"'"`)),n===null&&(t.charCodeAt(i)===126?(n=`~`,i++):(n=null,a===0&&c(`"~"`))))))))))));else e=null;return e!==null&&(e=(function(e){return t.substring(i,e)})(r)),e===null&&(i=r),e}function re(){var e,n,r=i;if(n=v(),n===null&&(t.charCodeAt(i)===45?(n=`-`,i++):(n=null,a===0&&c(`"-"`)),n===null&&(t.charCodeAt(i)===33?(n=`!`,i++):(n=null,a===0&&c(`"!"`)),n===null&&(t.charCodeAt(i)===37?(n=`%`,i++):(n=null,a===0&&c(`"%"`)),n===null&&(t.charCodeAt(i)===42?(n=`*`,i++):(n=null,a===0&&c(`"*"`)),n===null&&(t.charCodeAt(i)===95?(n=`_`,i++):(n=null,a===0&&c(`"_"`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)),n===null&&(t.charCodeAt(i)===96?(n="`",i++):(n=null,a===0&&c('"`"')),n===null&&(t.charCodeAt(i)===39?(n=`'`,i++):(n=null,a===0&&c(`"'"`)),n===null&&(t.charCodeAt(i)===126?(n=`~`,i++):(n=null,a===0&&c(`"~"`))))))))))),n!==null)for(e=[];n!==null;)e.push(n),n=v(),n===null&&(t.charCodeAt(i)===45?(n=`-`,i++):(n=null,a===0&&c(`"-"`)),n===null&&(t.charCodeAt(i)===33?(n=`!`,i++):(n=null,a===0&&c(`"!"`)),n===null&&(t.charCodeAt(i)===37?(n=`%`,i++):(n=null,a===0&&c(`"%"`)),n===null&&(t.charCodeAt(i)===42?(n=`*`,i++):(n=null,a===0&&c(`"*"`)),n===null&&(t.charCodeAt(i)===95?(n=`_`,i++):(n=null,a===0&&c(`"_"`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)),n===null&&(t.charCodeAt(i)===96?(n="`",i++):(n=null,a===0&&c('"`"')),n===null&&(t.charCodeAt(i)===39?(n=`'`,i++):(n=null,a===0&&c(`"'"`)),n===null&&(t.charCodeAt(i)===126?(n=`~`,i++):(n=null,a===0&&c(`"~"`)))))))))));else e=null;return e!==null&&(e=(function(e){return t.substring(i,e)})(r)),e===null&&(i=r),e}function ie(){var e;return t.charCodeAt(i)===40?(e=`(`,i++):(e=null,a===0&&c(`"("`)),e===null&&(t.charCodeAt(i)===41?(e=`)`,i++):(e=null,a===0&&c(`")"`)),e===null&&(t.charCodeAt(i)===60?(e=`<`,i++):(e=null,a===0&&c(`"<"`)),e===null&&(t.charCodeAt(i)===62?(e=`>`,i++):(e=null,a===0&&c(`">"`)),e===null&&(t.charCodeAt(i)===64?(e=`@`,i++):(e=null,a===0&&c(`"@"`)),e===null&&(t.charCodeAt(i)===44?(e=`,`,i++):(e=null,a===0&&c(`","`)),e===null&&(t.charCodeAt(i)===59?(e=`;`,i++):(e=null,a===0&&c(`";"`)),e===null&&(t.charCodeAt(i)===58?(e=`:`,i++):(e=null,a===0&&c(`":"`)),e===null&&(t.charCodeAt(i)===92?(e=`\\`,i++):(e=null,a===0&&c(`"\\\\"`)),e===null&&(e=h(),e===null&&(t.charCodeAt(i)===47?(e=`/`,i++):(e=null,a===0&&c(`"/"`)),e===null&&(t.charCodeAt(i)===91?(e=`[`,i++):(e=null,a===0&&c(`"["`)),e===null&&(t.charCodeAt(i)===93?(e=`]`,i++):(e=null,a===0&&c(`"]"`)),e===null&&(t.charCodeAt(i)===63?(e=`?`,i++):(e=null,a===0&&c(`"?"`)),e===null&&(t.charCodeAt(i)===61?(e=`=`,i++):(e=null,a===0&&c(`"="`)),e===null&&(t.charCodeAt(i)===123?(e=`{`,i++):(e=null,a===0&&c(`"{"`)),e===null&&(t.charCodeAt(i)===125?(e=`}`,i++):(e=null,a===0&&c(`"}"`)),e===null&&(e=g(),e===null&&(e=_())))))))))))))))))),e}function ae(){var e,n,r=i;if(n=v(),n===null&&(t.charCodeAt(i)===45?(n=`-`,i++):(n=null,a===0&&c(`"-"`)),n===null&&(t.charCodeAt(i)===46?(n=`.`,i++):(n=null,a===0&&c(`"."`)),n===null&&(t.charCodeAt(i)===33?(n=`!`,i++):(n=null,a===0&&c(`"!"`)),n===null&&(t.charCodeAt(i)===37?(n=`%`,i++):(n=null,a===0&&c(`"%"`)),n===null&&(t.charCodeAt(i)===42?(n=`*`,i++):(n=null,a===0&&c(`"*"`)),n===null&&(t.charCodeAt(i)===95?(n=`_`,i++):(n=null,a===0&&c(`"_"`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)),n===null&&(t.charCodeAt(i)===96?(n="`",i++):(n=null,a===0&&c('"`"')),n===null&&(t.charCodeAt(i)===39?(n=`'`,i++):(n=null,a===0&&c(`"'"`)),n===null&&(t.charCodeAt(i)===126?(n=`~`,i++):(n=null,a===0&&c(`"~"`)),n===null&&(t.charCodeAt(i)===40?(n=`(`,i++):(n=null,a===0&&c(`"("`)),n===null&&(t.charCodeAt(i)===41?(n=`)`,i++):(n=null,a===0&&c(`")"`)),n===null&&(t.charCodeAt(i)===60?(n=`<`,i++):(n=null,a===0&&c(`"<"`)),n===null&&(t.charCodeAt(i)===62?(n=`>`,i++):(n=null,a===0&&c(`">"`)),n===null&&(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null&&(t.charCodeAt(i)===92?(n=`\\`,i++):(n=null,a===0&&c(`"\\\\"`)),n===null&&(n=h(),n===null&&(t.charCodeAt(i)===47?(n=`/`,i++):(n=null,a===0&&c(`"/"`)),n===null&&(t.charCodeAt(i)===91?(n=`[`,i++):(n=null,a===0&&c(`"["`)),n===null&&(t.charCodeAt(i)===93?(n=`]`,i++):(n=null,a===0&&c(`"]"`)),n===null&&(t.charCodeAt(i)===63?(n=`?`,i++):(n=null,a===0&&c(`"?"`)),n===null&&(t.charCodeAt(i)===123?(n=`{`,i++):(n=null,a===0&&c(`"{"`)),n===null&&(t.charCodeAt(i)===125?(n=`}`,i++):(n=null,a===0&&c(`"}"`))))))))))))))))))))))))),n!==null)for(e=[];n!==null;)e.push(n),n=v(),n===null&&(t.charCodeAt(i)===45?(n=`-`,i++):(n=null,a===0&&c(`"-"`)),n===null&&(t.charCodeAt(i)===46?(n=`.`,i++):(n=null,a===0&&c(`"."`)),n===null&&(t.charCodeAt(i)===33?(n=`!`,i++):(n=null,a===0&&c(`"!"`)),n===null&&(t.charCodeAt(i)===37?(n=`%`,i++):(n=null,a===0&&c(`"%"`)),n===null&&(t.charCodeAt(i)===42?(n=`*`,i++):(n=null,a===0&&c(`"*"`)),n===null&&(t.charCodeAt(i)===95?(n=`_`,i++):(n=null,a===0&&c(`"_"`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)),n===null&&(t.charCodeAt(i)===96?(n="`",i++):(n=null,a===0&&c('"`"')),n===null&&(t.charCodeAt(i)===39?(n=`'`,i++):(n=null,a===0&&c(`"'"`)),n===null&&(t.charCodeAt(i)===126?(n=`~`,i++):(n=null,a===0&&c(`"~"`)),n===null&&(t.charCodeAt(i)===40?(n=`(`,i++):(n=null,a===0&&c(`"("`)),n===null&&(t.charCodeAt(i)===41?(n=`)`,i++):(n=null,a===0&&c(`")"`)),n===null&&(t.charCodeAt(i)===60?(n=`<`,i++):(n=null,a===0&&c(`"<"`)),n===null&&(t.charCodeAt(i)===62?(n=`>`,i++):(n=null,a===0&&c(`">"`)),n===null&&(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null&&(t.charCodeAt(i)===92?(n=`\\`,i++):(n=null,a===0&&c(`"\\\\"`)),n===null&&(n=h(),n===null&&(t.charCodeAt(i)===47?(n=`/`,i++):(n=null,a===0&&c(`"/"`)),n===null&&(t.charCodeAt(i)===91?(n=`[`,i++):(n=null,a===0&&c(`"["`)),n===null&&(t.charCodeAt(i)===93?(n=`]`,i++):(n=null,a===0&&c(`"]"`)),n===null&&(t.charCodeAt(i)===63?(n=`?`,i++):(n=null,a===0&&c(`"?"`)),n===null&&(t.charCodeAt(i)===123?(n=`{`,i++):(n=null,a===0&&c(`"{"`)),n===null&&(t.charCodeAt(i)===125?(n=`}`,i++):(n=null,a===0&&c(`"}"`)))))))))))))))))))))))));else e=null;return e!==null&&(e=(function(e){return t.substring(i,e)})(r)),e===null&&(i=r),e}function oe(){var e,n,r,o=i,s=i;return e=w(),e===null?(e=null,i=s):(t.charCodeAt(i)===42?(n=`*`,i++):(n=null,a===0&&c(`"*"`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e){return`*`})(o)),e===null&&(i=o),e}function se(){var e,n,r,o=i,s=i;return e=w(),e===null?(e=null,i=s):(t.charCodeAt(i)===47?(n=`/`,i++):(n=null,a===0&&c(`"/"`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e){return`/`})(o)),e===null&&(i=o),e}function k(){var e,n,r,o=i,s=i;return e=w(),e===null?(e=null,i=s):(t.charCodeAt(i)===61?(n=`=`,i++):(n=null,a===0&&c(`"="`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e){return`=`})(o)),e===null&&(i=o),e}function ce(){var e,n,r,o=i,s=i;return e=w(),e===null?(e=null,i=s):(t.charCodeAt(i)===40?(n=`(`,i++):(n=null,a===0&&c(`"("`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e){return`(`})(o)),e===null&&(i=o),e}function le(){var e,n,r,o=i,s=i;return e=w(),e===null?(e=null,i=s):(t.charCodeAt(i)===41?(n=`)`,i++):(n=null,a===0&&c(`")"`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e){return`)`})(o)),e===null&&(i=o),e}function ue(){var e,n,r=i,o=i;return t.charCodeAt(i)===62?(e=`>`,i++):(e=null,a===0&&c(`">"`)),e===null?(e=null,i=o):(n=w(),n===null?(e=null,i=o):e=[e,n]),e!==null&&(e=(function(e){return`>`})(r)),e===null&&(i=r),e}function de(){var e,n,r=i,o=i;return e=w(),e===null?(e=null,i=o):(t.charCodeAt(i)===60?(n=`<`,i++):(n=null,a===0&&c(`"<"`)),n===null?(e=null,i=o):e=[e,n]),e!==null&&(e=(function(e){return`<`})(r)),e===null&&(i=r),e}function A(){var e,n,r,o=i,s=i;return e=w(),e===null?(e=null,i=s):(t.charCodeAt(i)===44?(n=`,`,i++):(n=null,a===0&&c(`","`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e){return`,`})(o)),e===null&&(i=o),e}function j(){var e,n,r,o=i,s=i;return e=w(),e===null?(e=null,i=s):(t.charCodeAt(i)===59?(n=`;`,i++):(n=null,a===0&&c(`";"`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e){return`;`})(o)),e===null&&(i=o),e}function fe(){var e,n,r,o=i,s=i;return e=w(),e===null?(e=null,i=s):(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e){return`:`})(o)),e===null&&(i=o),e}function pe(){var e,t,n=i,r=i;return e=w(),e===null?(e=null,i=r):(t=h(),t===null?(e=null,i=r):e=[e,t]),e!==null&&(e=(function(e){return`"`})(n)),e===null&&(i=n),e}function me(){var e,t,n=i,r=i;return e=h(),e===null?(e=null,i=r):(t=w(),t===null?(e=null,i=r):e=[e,t]),e!==null&&(e=(function(e){return`"`})(n)),e===null&&(i=n),e}function he(){var e,t,n,r=i;if(e=ce(),e!==null){for(t=[],n=ge(),n===null&&(n=P(),n===null&&(n=he()));n!==null;)t.push(n),n=ge(),n===null&&(n=P(),n===null&&(n=he()));t===null?(e=null,i=r):(n=le(),n===null?(e=null,i=r):e=[e,t,n])}else e=null,i=r;return e}function ge(){var e;return/^[!-']/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[!-']`)),e===null&&(/^[*-[]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[*-[]`)),e===null&&(/^[\]-~]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[\\]-~]`)),e===null&&(e=D(),e===null&&(e=C())))),e}function M(){var e,n,r,a,o=i,s=i;if(e=w(),e!==null){if(n=h(),n!==null){for(r=[],a=_e(),a===null&&(a=P());a!==null;)r.push(a),a=_e(),a===null&&(a=P());r===null?(e=null,i=s):(a=h(),a===null?(e=null,i=s):e=[e,n,r,a])}else e=null,i=s}else e=null,i=s;return e!==null&&(e=(function(e){return t.substring(i,e)})(o)),e===null&&(i=o),e}function N(){var e,n,r,a,o=i,s=i;if(e=w(),e!==null){if(n=h(),n!==null){for(r=[],a=_e(),a===null&&(a=P());a!==null;)r.push(a),a=_e(),a===null&&(a=P());r===null?(e=null,i=s):(a=h(),a===null?(e=null,i=s):e=[e,n,r,a])}else e=null,i=s}else e=null,i=s;return e!==null&&(e=(function(e){var n=t.substring(i,e).trim();return n.substring(1,n.length-1).replace(/\\([\x00-\x09\x0b-\x0c\x0e-\x7f])/g,`$1`)})(o)),e===null&&(i=o),e}function _e(){var e=C();return e===null&&(t.charCodeAt(i)===33?(e=`!`,i++):(e=null,a===0&&c(`"!"`)),e===null&&(/^[#-[]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[#-[]`)),e===null&&(/^[\]-~]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[\\]-~]`)),e===null&&(e=D())))),e}function P(){var e,n,r=i;return t.charCodeAt(i)===92?(e=`\\`,i++):(e=null,a===0&&c(`"\\\\"`)),e===null?(e=null,i=r):(/^[\0-\t]/.test(t.charAt(i))?(n=t.charAt(i),i++):(n=null,a===0&&c(`[\\0-\\t]`)),n===null&&(/^[\x0B-\f]/.test(t.charAt(i))?(n=t.charAt(i),i++):(n=null,a===0&&c(`[\\x0B-\\f]`)),n===null&&(/^[\x0E-]/.test(t.charAt(i))?(n=t.charAt(i),i++):(n=null,a===0&&c(`[\\x0E-]`)))),n===null?(e=null,i=r):e=[e,n]),e}function ve(){var e,n,r,o,s=i,l=i;return e=be(),e===null?(e=null,i=l):(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(e=null,i=l):(r=Ce(),r=r===null?``:r,r===null?(e=null,i=l):(o=De(),o===null?(e=null,i=l):e=[e,n,r,o]))),e!==null&&(e=(function(e){try{$.uri=new Tr($.scheme,$.user,$.host,$.port),delete $.scheme,delete $.user,delete $.host,delete $.host_type,delete $.port}catch{$=-1}})(s)),e===null&&(i=s),e}function ye(){var e,r,o,s,l,u,d=i,f=i;return e=be(),e===null?(e=null,i=f):(t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(e=null,i=f):(o=Ce(),o=o===null?``:o,o===null?(e=null,i=f):(s=De(),s===null?(e=null,i=f):(l=Ie(),l===null?(e=null,i=f):(u=Ye(),u=u===null?``:u,u===null?(e=null,i=f):e=[e,r,o,s,l,u]))))),e!==null&&(e=(function(e){try{$.uri=new Tr($.scheme,$.user,$.host,$.port,$.uri_params,$.uri_headers),delete $.scheme,delete $.user,delete $.host,delete $.host_type,delete $.port,delete $.uri_params,n===`SIP_URI`&&($=$.uri)}catch{$=-1}})(d)),e===null&&(i=d),e}function be(){var e=xe();return e===null&&(e=Se()),e}function xe(){var e,n=i;return t.substr(i,4).toLowerCase()===`sips`?(e=t.substr(i,4),i+=4):(e=null,a===0&&c(`"sips"`)),e!==null&&(e=(function(e,t){$.scheme=t.toLowerCase()})(n,e)),e===null&&(i=n),e}function Se(){var e,n=i;return t.substr(i,3).toLowerCase()===`sip`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"sip"`)),e!==null&&(e=(function(e,t){$.scheme=t.toLowerCase()})(n,e)),e===null&&(i=n),e}function Ce(){var e,n,r,o=i,s=i,l;return e=we(),e===null?(e=null,i=s):(l=i,t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(n=null,i=l):(r=Ee(),r===null?(n=null,i=l):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=s):(t.charCodeAt(i)===64?(r=`@`,i++):(r=null,a===0&&c(`"@"`)),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e){$.user=decodeURIComponent(t.substring(i-1,e))})(o)),e===null&&(i=o),e}function we(){var e,t=b();if(t===null&&(t=S(),t===null&&(t=Te())),t!==null)for(e=[];t!==null;)e.push(t),t=b(),t===null&&(t=S(),t===null&&(t=Te()));else e=null;return e}function Te(){var e;return t.charCodeAt(i)===38?(e=`&`,i++):(e=null,a===0&&c(`"&"`)),e===null&&(t.charCodeAt(i)===61?(e=`=`,i++):(e=null,a===0&&c(`"="`)),e===null&&(t.charCodeAt(i)===43?(e=`+`,i++):(e=null,a===0&&c(`"+"`)),e===null&&(t.charCodeAt(i)===36?(e=`$`,i++):(e=null,a===0&&c(`"$"`)),e===null&&(t.charCodeAt(i)===44?(e=`,`,i++):(e=null,a===0&&c(`","`)),e===null&&(t.charCodeAt(i)===59?(e=`;`,i++):(e=null,a===0&&c(`";"`)),e===null&&(t.charCodeAt(i)===63?(e=`?`,i++):(e=null,a===0&&c(`"?"`)),e===null&&(t.charCodeAt(i)===47?(e=`/`,i++):(e=null,a===0&&c(`"/"`))))))))),e}function Ee(){var e,n,r=i;for(e=[],n=b(),n===null&&(n=S(),n===null&&(t.charCodeAt(i)===38?(n=`&`,i++):(n=null,a===0&&c(`"&"`)),n===null&&(t.charCodeAt(i)===61?(n=`=`,i++):(n=null,a===0&&c(`"="`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)),n===null&&(t.charCodeAt(i)===36?(n=`$`,i++):(n=null,a===0&&c(`"$"`)),n===null&&(t.charCodeAt(i)===44?(n=`,`,i++):(n=null,a===0&&c(`","`))))))));n!==null;)e.push(n),n=b(),n===null&&(n=S(),n===null&&(t.charCodeAt(i)===38?(n=`&`,i++):(n=null,a===0&&c(`"&"`)),n===null&&(t.charCodeAt(i)===61?(n=`=`,i++):(n=null,a===0&&c(`"="`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)),n===null&&(t.charCodeAt(i)===36?(n=`$`,i++):(n=null,a===0&&c(`"$"`)),n===null&&(t.charCodeAt(i)===44?(n=`,`,i++):(n=null,a===0&&c(`","`))))))));return e!==null&&(e=(function(e){$.password=t.substring(i,e)})(r)),e===null&&(i=r),e}function De(){var e,n,r,o=i,s;return e=Oe(),e===null?(e=null,i=o):(s=i,t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(n=null,i=s):(r=Fe(),r===null?(n=null,i=s):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=o):e=[e,n]),e}function Oe(){var e,n=i;return e=ke(),e===null&&(e=Ne(),e===null&&(e=je())),e!==null&&(e=(function(e){return $.host=t.substring(i,e).toLowerCase(),$.host})(n)),e===null&&(i=n),e}function ke(){var e,n,r,o=i,s=i,l;for(e=[],l=i,n=F(),n===null?(n=null,i=l):(t.charCodeAt(i)===46?(r=`.`,i++):(r=null,a===0&&c(`"."`)),r===null?(n=null,i=l):n=[n,r]);n!==null;)e.push(n),l=i,n=F(),n===null?(n=null,i=l):(t.charCodeAt(i)===46?(r=`.`,i++):(r=null,a===0&&c(`"."`)),r===null?(n=null,i=l):n=[n,r]);return e===null?(e=null,i=s):(n=Ae(),n===null?(e=null,i=s):(t.charCodeAt(i)===46?(r=`.`,i++):(r=null,a===0&&c(`"."`)),r=r===null?``:r,r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e){return $.host_type=`domain`,t.substring(i,e)})(o)),e===null&&(i=o),e}function F(){var e,n,r,o=i;if(e=v(),e!==null){for(n=[],r=v(),r===null&&(t.charCodeAt(i)===45?(r=`-`,i++):(r=null,a===0&&c(`"-"`)),r===null&&(t.charCodeAt(i)===95?(r=`_`,i++):(r=null,a===0&&c(`"_"`))));r!==null;)n.push(r),r=v(),r===null&&(t.charCodeAt(i)===45?(r=`-`,i++):(r=null,a===0&&c(`"-"`)),r===null&&(t.charCodeAt(i)===95?(r=`_`,i++):(r=null,a===0&&c(`"_"`))));n===null?(e=null,i=o):e=[e,n]}else e=null,i=o;return e}function Ae(){var e,n,r,o=i;if(e=d(),e!==null){for(n=[],r=v(),r===null&&(t.charCodeAt(i)===45?(r=`-`,i++):(r=null,a===0&&c(`"-"`)),r===null&&(t.charCodeAt(i)===95?(r=`_`,i++):(r=null,a===0&&c(`"_"`))));r!==null;)n.push(r),r=v(),r===null&&(t.charCodeAt(i)===45?(r=`-`,i++):(r=null,a===0&&c(`"-"`)),r===null&&(t.charCodeAt(i)===95?(r=`_`,i++):(r=null,a===0&&c(`"_"`))));n===null?(e=null,i=o):e=[e,n]}else e=null,i=o;return e}function je(){var e,n,r,o=i,s=i;return t.charCodeAt(i)===91?(e=`[`,i++):(e=null,a===0&&c(`"["`)),e===null?(e=null,i=s):(n=Me(),n===null?(e=null,i=s):(t.charCodeAt(i)===93?(r=`]`,i++):(r=null,a===0&&c(`"]"`)),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e){return $.host_type=`IPv6`,t.substring(i,e)})(o)),e===null&&(i=o),e}function Me(){var e,n,r,o,s,l,u,d,f,p,m,h,g,_=i,v=i,y;return e=I(),e===null?(e=null,i=v):(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(e=null,i=v):(r=I(),r===null?(e=null,i=v):(t.charCodeAt(i)===58?(o=`:`,i++):(o=null,a===0&&c(`":"`)),o===null?(e=null,i=v):(s=I(),s===null?(e=null,i=v):(t.charCodeAt(i)===58?(l=`:`,i++):(l=null,a===0&&c(`":"`)),l===null?(e=null,i=v):(u=I(),u===null?(e=null,i=v):(t.charCodeAt(i)===58?(d=`:`,i++):(d=null,a===0&&c(`":"`)),d===null?(e=null,i=v):(f=I(),f===null?(e=null,i=v):(t.charCodeAt(i)===58?(p=`:`,i++):(p=null,a===0&&c(`":"`)),p===null?(e=null,i=v):(m=I(),m===null?(e=null,i=v):(t.charCodeAt(i)===58?(h=`:`,i++):(h=null,a===0&&c(`":"`)),h===null?(e=null,i=v):(g=L(),g===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d,f,p,m,h,g])))))))))))),e===null&&(v=i,t.substr(i,2)===`::`?(e=`::`,i+=2):(e=null,a===0&&c(`"::"`)),e===null?(e=null,i=v):(n=I(),n===null?(e=null,i=v):(t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(e=null,i=v):(o=I(),o===null?(e=null,i=v):(t.charCodeAt(i)===58?(s=`:`,i++):(s=null,a===0&&c(`":"`)),s===null?(e=null,i=v):(l=I(),l===null?(e=null,i=v):(t.charCodeAt(i)===58?(u=`:`,i++):(u=null,a===0&&c(`":"`)),u===null?(e=null,i=v):(d=I(),d===null?(e=null,i=v):(t.charCodeAt(i)===58?(f=`:`,i++):(f=null,a===0&&c(`":"`)),f===null?(e=null,i=v):(p=I(),p===null?(e=null,i=v):(t.charCodeAt(i)===58?(m=`:`,i++):(m=null,a===0&&c(`":"`)),m===null?(e=null,i=v):(h=L(),h===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d,f,p,m,h]))))))))))),e===null&&(v=i,t.substr(i,2)===`::`?(e=`::`,i+=2):(e=null,a===0&&c(`"::"`)),e===null?(e=null,i=v):(n=I(),n===null?(e=null,i=v):(t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(e=null,i=v):(o=I(),o===null?(e=null,i=v):(t.charCodeAt(i)===58?(s=`:`,i++):(s=null,a===0&&c(`":"`)),s===null?(e=null,i=v):(l=I(),l===null?(e=null,i=v):(t.charCodeAt(i)===58?(u=`:`,i++):(u=null,a===0&&c(`":"`)),u===null?(e=null,i=v):(d=I(),d===null?(e=null,i=v):(t.charCodeAt(i)===58?(f=`:`,i++):(f=null,a===0&&c(`":"`)),f===null?(e=null,i=v):(p=L(),p===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d,f,p]))))))))),e===null&&(v=i,t.substr(i,2)===`::`?(e=`::`,i+=2):(e=null,a===0&&c(`"::"`)),e===null?(e=null,i=v):(n=I(),n===null?(e=null,i=v):(t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(e=null,i=v):(o=I(),o===null?(e=null,i=v):(t.charCodeAt(i)===58?(s=`:`,i++):(s=null,a===0&&c(`":"`)),s===null?(e=null,i=v):(l=I(),l===null?(e=null,i=v):(t.charCodeAt(i)===58?(u=`:`,i++):(u=null,a===0&&c(`":"`)),u===null?(e=null,i=v):(d=L(),d===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d]))))))),e===null&&(v=i,t.substr(i,2)===`::`?(e=`::`,i+=2):(e=null,a===0&&c(`"::"`)),e===null?(e=null,i=v):(n=I(),n===null?(e=null,i=v):(t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(e=null,i=v):(o=I(),o===null?(e=null,i=v):(t.charCodeAt(i)===58?(s=`:`,i++):(s=null,a===0&&c(`":"`)),s===null?(e=null,i=v):(l=L(),l===null?(e=null,i=v):e=[e,n,r,o,s,l]))))),e===null&&(v=i,t.substr(i,2)===`::`?(e=`::`,i+=2):(e=null,a===0&&c(`"::"`)),e===null?(e=null,i=v):(n=I(),n===null?(e=null,i=v):(t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(e=null,i=v):(o=L(),o===null?(e=null,i=v):e=[e,n,r,o]))),e===null&&(v=i,t.substr(i,2)===`::`?(e=`::`,i+=2):(e=null,a===0&&c(`"::"`)),e===null?(e=null,i=v):(n=L(),n===null?(e=null,i=v):e=[e,n]),e===null&&(v=i,t.substr(i,2)===`::`?(e=`::`,i+=2):(e=null,a===0&&c(`"::"`)),e===null?(e=null,i=v):(n=I(),n===null?(e=null,i=v):e=[e,n]),e===null&&(v=i,e=I(),e===null?(e=null,i=v):(t.substr(i,2)===`::`?(n=`::`,i+=2):(n=null,a===0&&c(`"::"`)),n===null?(e=null,i=v):(r=I(),r===null?(e=null,i=v):(t.charCodeAt(i)===58?(o=`:`,i++):(o=null,a===0&&c(`":"`)),o===null?(e=null,i=v):(s=I(),s===null?(e=null,i=v):(t.charCodeAt(i)===58?(l=`:`,i++):(l=null,a===0&&c(`":"`)),l===null?(e=null,i=v):(u=I(),u===null?(e=null,i=v):(t.charCodeAt(i)===58?(d=`:`,i++):(d=null,a===0&&c(`":"`)),d===null?(e=null,i=v):(f=I(),f===null?(e=null,i=v):(t.charCodeAt(i)===58?(p=`:`,i++):(p=null,a===0&&c(`":"`)),p===null?(e=null,i=v):(m=L(),m===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d,f,p,m])))))))))),e===null&&(v=i,e=I(),e===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(n=null,i=y):(r=I(),r===null?(n=null,i=y):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=v):(t.substr(i,2)===`::`?(r=`::`,i+=2):(r=null,a===0&&c(`"::"`)),r===null?(e=null,i=v):(o=I(),o===null?(e=null,i=v):(t.charCodeAt(i)===58?(s=`:`,i++):(s=null,a===0&&c(`":"`)),s===null?(e=null,i=v):(l=I(),l===null?(e=null,i=v):(t.charCodeAt(i)===58?(u=`:`,i++):(u=null,a===0&&c(`":"`)),u===null?(e=null,i=v):(d=I(),d===null?(e=null,i=v):(t.charCodeAt(i)===58?(f=`:`,i++):(f=null,a===0&&c(`":"`)),f===null?(e=null,i=v):(p=L(),p===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d,f,p]))))))))),e===null&&(v=i,e=I(),e===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(n=null,i=y):(r=I(),r===null?(n=null,i=y):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(r=null,i=y):(o=I(),o===null?(r=null,i=y):r=[r,o]),r=r===null?``:r,r===null?(e=null,i=v):(t.substr(i,2)===`::`?(o=`::`,i+=2):(o=null,a===0&&c(`"::"`)),o===null?(e=null,i=v):(s=I(),s===null?(e=null,i=v):(t.charCodeAt(i)===58?(l=`:`,i++):(l=null,a===0&&c(`":"`)),l===null?(e=null,i=v):(u=I(),u===null?(e=null,i=v):(t.charCodeAt(i)===58?(d=`:`,i++):(d=null,a===0&&c(`":"`)),d===null?(e=null,i=v):(f=L(),f===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d,f])))))))),e===null&&(v=i,e=I(),e===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(n=null,i=y):(r=I(),r===null?(n=null,i=y):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(r=null,i=y):(o=I(),o===null?(r=null,i=y):r=[r,o]),r=r===null?``:r,r===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(o=`:`,i++):(o=null,a===0&&c(`":"`)),o===null?(o=null,i=y):(s=I(),s===null?(o=null,i=y):o=[o,s]),o=o===null?``:o,o===null?(e=null,i=v):(t.substr(i,2)===`::`?(s=`::`,i+=2):(s=null,a===0&&c(`"::"`)),s===null?(e=null,i=v):(l=I(),l===null?(e=null,i=v):(t.charCodeAt(i)===58?(u=`:`,i++):(u=null,a===0&&c(`":"`)),u===null?(e=null,i=v):(d=L(),d===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d]))))))),e===null&&(v=i,e=I(),e===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(n=null,i=y):(r=I(),r===null?(n=null,i=y):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(r=null,i=y):(o=I(),o===null?(r=null,i=y):r=[r,o]),r=r===null?``:r,r===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(o=`:`,i++):(o=null,a===0&&c(`":"`)),o===null?(o=null,i=y):(s=I(),s===null?(o=null,i=y):o=[o,s]),o=o===null?``:o,o===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(s=`:`,i++):(s=null,a===0&&c(`":"`)),s===null?(s=null,i=y):(l=I(),l===null?(s=null,i=y):s=[s,l]),s=s===null?``:s,s===null?(e=null,i=v):(t.substr(i,2)===`::`?(l=`::`,i+=2):(l=null,a===0&&c(`"::"`)),l===null?(e=null,i=v):(u=L(),u===null?(e=null,i=v):e=[e,n,r,o,s,l,u])))))),e===null&&(v=i,e=I(),e===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(n=null,i=y):(r=I(),r===null?(n=null,i=y):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(r=null,i=y):(o=I(),o===null?(r=null,i=y):r=[r,o]),r=r===null?``:r,r===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(o=`:`,i++):(o=null,a===0&&c(`":"`)),o===null?(o=null,i=y):(s=I(),s===null?(o=null,i=y):o=[o,s]),o=o===null?``:o,o===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(s=`:`,i++):(s=null,a===0&&c(`":"`)),s===null?(s=null,i=y):(l=I(),l===null?(s=null,i=y):s=[s,l]),s=s===null?``:s,s===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(l=`:`,i++):(l=null,a===0&&c(`":"`)),l===null?(l=null,i=y):(u=I(),u===null?(l=null,i=y):l=[l,u]),l=l===null?``:l,l===null?(e=null,i=v):(t.substr(i,2)===`::`?(u=`::`,i+=2):(u=null,a===0&&c(`"::"`)),u===null?(e=null,i=v):(d=I(),d===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d]))))))),e===null&&(v=i,e=I(),e===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(n=null,i=y):(r=I(),r===null?(n=null,i=y):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(r=null,i=y):(o=I(),o===null?(r=null,i=y):r=[r,o]),r=r===null?``:r,r===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(o=`:`,i++):(o=null,a===0&&c(`":"`)),o===null?(o=null,i=y):(s=I(),s===null?(o=null,i=y):o=[o,s]),o=o===null?``:o,o===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(s=`:`,i++):(s=null,a===0&&c(`":"`)),s===null?(s=null,i=y):(l=I(),l===null?(s=null,i=y):s=[s,l]),s=s===null?``:s,s===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(l=`:`,i++):(l=null,a===0&&c(`":"`)),l===null?(l=null,i=y):(u=I(),u===null?(l=null,i=y):l=[l,u]),l=l===null?``:l,l===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(u=`:`,i++):(u=null,a===0&&c(`":"`)),u===null?(u=null,i=y):(d=I(),d===null?(u=null,i=y):u=[u,d]),u=u===null?``:u,u===null?(e=null,i=v):(t.substr(i,2)===`::`?(d=`::`,i+=2):(d=null,a===0&&c(`"::"`)),d===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d]))))))))))))))))))))),e!==null&&(e=(function(e){return $.host_type=`IPv6`,t.substring(i,e)})(_)),e===null&&(i=_),e}function I(){var e,t,n,r,a=i;return e=f(),e===null?(e=null,i=a):(t=f(),t=t===null?``:t,t===null?(e=null,i=a):(n=f(),n=n===null?``:n,n===null?(e=null,i=a):(r=f(),r=r===null?``:r,r===null?(e=null,i=a):e=[e,t,n,r]))),e}function L(){var e,n,r,o=i;return e=I(),e===null?(e=null,i=o):(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(e=null,i=o):(r=I(),r===null?(e=null,i=o):e=[e,n,r])),e===null&&(e=Ne()),e}function Ne(){var e,n,r,o,s,l,u,d=i,f=i;return e=Pe(),e===null?(e=null,i=f):(t.charCodeAt(i)===46?(n=`.`,i++):(n=null,a===0&&c(`"."`)),n===null?(e=null,i=f):(r=Pe(),r===null?(e=null,i=f):(t.charCodeAt(i)===46?(o=`.`,i++):(o=null,a===0&&c(`"."`)),o===null?(e=null,i=f):(s=Pe(),s===null?(e=null,i=f):(t.charCodeAt(i)===46?(l=`.`,i++):(l=null,a===0&&c(`"."`)),l===null?(e=null,i=f):(u=Pe(),u===null?(e=null,i=f):e=[e,n,r,o,s,l,u])))))),e!==null&&(e=(function(e){return $.host_type=`IPv4`,t.substring(i,e)})(d)),e===null&&(i=d),e}function Pe(){var e,n,r,o=i;return t.substr(i,2)===`25`?(e=`25`,i+=2):(e=null,a===0&&c(`"25"`)),e===null?(e=null,i=o):(/^[0-5]/.test(t.charAt(i))?(n=t.charAt(i),i++):(n=null,a===0&&c(`[0-5]`)),n===null?(e=null,i=o):e=[e,n]),e===null&&(o=i,t.charCodeAt(i)===50?(e=`2`,i++):(e=null,a===0&&c(`"2"`)),e===null?(e=null,i=o):(/^[0-4]/.test(t.charAt(i))?(n=t.charAt(i),i++):(n=null,a===0&&c(`[0-4]`)),n===null?(e=null,i=o):(r=u(),r===null?(e=null,i=o):e=[e,n,r])),e===null&&(o=i,t.charCodeAt(i)===49?(e=`1`,i++):(e=null,a===0&&c(`"1"`)),e===null?(e=null,i=o):(n=u(),n===null?(e=null,i=o):(r=u(),r===null?(e=null,i=o):e=[e,n,r])),e===null&&(o=i,/^[1-9]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[1-9]`)),e===null?(e=null,i=o):(n=u(),n===null?(e=null,i=o):e=[e,n]),e===null&&(e=u())))),e}function Fe(){var e,t,n,r,a,o=i,s=i;return e=u(),e=e===null?``:e,e===null?(e=null,i=s):(t=u(),t=t===null?``:t,t===null?(e=null,i=s):(n=u(),n=n===null?``:n,n===null?(e=null,i=s):(r=u(),r=r===null?``:r,r===null?(e=null,i=s):(a=u(),a=a===null?``:a,a===null?(e=null,i=s):e=[e,t,n,r,a])))),e!==null&&(e=(function(e,t){return t=parseInt(t.join(``)),$.port=t,t})(o,e)),e===null&&(i=o),e}function Ie(){var e=[],n,r,o=i;for(t.charCodeAt(i)===59?(n=`;`,i++):(n=null,a===0&&c(`";"`)),n===null?(n=null,i=o):(r=Le(),r===null?(n=null,i=o):n=[n,r]);n!==null;)e.push(n),o=i,t.charCodeAt(i)===59?(n=`;`,i++):(n=null,a===0&&c(`";"`)),n===null?(n=null,i=o):(r=Le(),r===null?(n=null,i=o):n=[n,r]);return e}function Le(){var e=Re();return e===null&&(e=ze(),e===null&&(e=Be(),e===null&&(e=Ve(),e===null&&(e=He(),e===null&&(e=Ue(),e===null&&(e=We())))))),e}function Re(){var e,n,r=i,o=i;return t.substr(i,10).toLowerCase()===`transport=`?(e=t.substr(i,10),i+=10):(e=null,a===0&&c(`"transport="`)),e===null?(e=null,i=o):(t.substr(i,3).toLowerCase()===`udp`?(n=t.substr(i,3),i+=3):(n=null,a===0&&c(`"udp"`)),n===null&&(t.substr(i,3).toLowerCase()===`tcp`?(n=t.substr(i,3),i+=3):(n=null,a===0&&c(`"tcp"`)),n===null&&(t.substr(i,4).toLowerCase()===`sctp`?(n=t.substr(i,4),i+=4):(n=null,a===0&&c(`"sctp"`)),n===null&&(t.substr(i,3).toLowerCase()===`tls`?(n=t.substr(i,3),i+=3):(n=null,a===0&&c(`"tls"`)),n===null&&(n=O())))),n===null?(e=null,i=o):e=[e,n]),e!==null&&(e=(function(e,t){$.uri_params||($.uri_params={}),$.uri_params.transport=t.toLowerCase()})(r,e[1])),e===null&&(i=r),e}function ze(){var e,n,r=i,o=i;return t.substr(i,5).toLowerCase()===`user=`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"user="`)),e===null?(e=null,i=o):(t.substr(i,5).toLowerCase()===`phone`?(n=t.substr(i,5),i+=5):(n=null,a===0&&c(`"phone"`)),n===null&&(t.substr(i,2).toLowerCase()===`ip`?(n=t.substr(i,2),i+=2):(n=null,a===0&&c(`"ip"`)),n===null&&(n=O())),n===null?(e=null,i=o):e=[e,n]),e!==null&&(e=(function(e,t){$.uri_params||($.uri_params={}),$.uri_params.user=t.toLowerCase()})(r,e[1])),e===null&&(i=r),e}function Be(){var e,n,r=i,o=i;return t.substr(i,7).toLowerCase()===`method=`?(e=t.substr(i,7),i+=7):(e=null,a===0&&c(`"method="`)),e===null?(e=null,i=o):(n=Dt(),n===null?(e=null,i=o):e=[e,n]),e!==null&&(e=(function(e,t){$.uri_params||($.uri_params={}),$.uri_params.method=t})(r,e[1])),e===null&&(i=r),e}function Ve(){var e,n,r=i,o=i;return t.substr(i,4).toLowerCase()===`ttl=`?(e=t.substr(i,4),i+=4):(e=null,a===0&&c(`"ttl="`)),e===null?(e=null,i=o):(n=rr(),n===null?(e=null,i=o):e=[e,n]),e!==null&&(e=(function(e,t){$.params||($.params={}),$.params.ttl=t})(r,e[1])),e===null&&(i=r),e}function He(){var e,n,r=i,o=i;return t.substr(i,6).toLowerCase()===`maddr=`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"maddr="`)),e===null?(e=null,i=o):(n=Oe(),n===null?(e=null,i=o):e=[e,n]),e!==null&&(e=(function(e,t){$.uri_params||($.uri_params={}),$.uri_params.maddr=t})(r,e[1])),e===null&&(i=r),e}function Ue(){var e,n,r,o=i,s=i,l;return t.substr(i,2).toLowerCase()===`lr`?(e=t.substr(i,2),i+=2):(e=null,a===0&&c(`"lr"`)),e===null?(e=null,i=s):(l=i,t.charCodeAt(i)===61?(n=`=`,i++):(n=null,a===0&&c(`"="`)),n===null?(n=null,i=l):(r=O(),r===null?(n=null,i=l):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=s):e=[e,n]),e!==null&&(e=(function(e){$.uri_params||($.uri_params={}),$.uri_params.lr=void 0})(o)),e===null&&(i=o),e}function We(){var e,n,r,o=i,s=i,l;return e=Ge(),e===null?(e=null,i=s):(l=i,t.charCodeAt(i)===61?(n=`=`,i++):(n=null,a===0&&c(`"="`)),n===null?(n=null,i=l):(r=Ke(),r===null?(n=null,i=l):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=s):e=[e,n]),e!==null&&(e=(function(e,t,n){$.uri_params||($.uri_params={}),n=n===void 0?void 0:n[1],$.uri_params[t.toLowerCase()]=n})(o,e[0],e[1])),e===null&&(i=o),e}function Ge(){var e,t,n=i;if(t=qe(),t!==null)for(e=[];t!==null;)e.push(t),t=qe();else e=null;return e!==null&&(e=(function(e,t){return t.join(``)})(n,e)),e===null&&(i=n),e}function Ke(){var e,t,n=i;if(t=qe(),t!==null)for(e=[];t!==null;)e.push(t),t=qe();else e=null;return e!==null&&(e=(function(e,t){return t.join(``)})(n,e)),e===null&&(i=n),e}function qe(){var e=Je();return e===null&&(e=b(),e===null&&(e=S())),e}function Je(){var e;return t.charCodeAt(i)===91?(e=`[`,i++):(e=null,a===0&&c(`"["`)),e===null&&(t.charCodeAt(i)===93?(e=`]`,i++):(e=null,a===0&&c(`"]"`)),e===null&&(t.charCodeAt(i)===47?(e=`/`,i++):(e=null,a===0&&c(`"/"`)),e===null&&(t.charCodeAt(i)===58?(e=`:`,i++):(e=null,a===0&&c(`":"`)),e===null&&(t.charCodeAt(i)===38?(e=`&`,i++):(e=null,a===0&&c(`"&"`)),e===null&&(t.charCodeAt(i)===43?(e=`+`,i++):(e=null,a===0&&c(`"+"`)),e===null&&(t.charCodeAt(i)===36?(e=`$`,i++):(e=null,a===0&&c(`"$"`)))))))),e}function Ye(){var e,n,r,o,s,l=i,u;if(t.charCodeAt(i)===63?(e=`?`,i++):(e=null,a===0&&c(`"?"`)),e!==null){if(n=Xe(),n!==null){for(r=[],u=i,t.charCodeAt(i)===38?(o=`&`,i++):(o=null,a===0&&c(`"&"`)),o===null?(o=null,i=u):(s=Xe(),s===null?(o=null,i=u):o=[o,s]);o!==null;)r.push(o),u=i,t.charCodeAt(i)===38?(o=`&`,i++):(o=null,a===0&&c(`"&"`)),o===null?(o=null,i=u):(s=Xe(),s===null?(o=null,i=u):o=[o,s]);r===null?(e=null,i=l):e=[e,n,r]}else e=null,i=l}else e=null,i=l;return e}function Xe(){var e,n,r,o=i,s=i;return e=Ze(),e===null?(e=null,i=s):(t.charCodeAt(i)===61?(n=`=`,i++):(n=null,a===0&&c(`"="`)),n===null?(e=null,i=s):(r=Qe(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t,n){t=t.join(``).toLowerCase(),n=n.join(``),$.uri_headers||($.uri_headers={}),$.uri_headers[t]?$.uri_headers[t].push(n):$.uri_headers[t]=[n]})(o,e[0],e[2])),e===null&&(i=o),e}function Ze(){var e,t=$e();if(t===null&&(t=b(),t===null&&(t=S())),t!==null)for(e=[];t!==null;)e.push(t),t=$e(),t===null&&(t=b(),t===null&&(t=S()));else e=null;return e}function Qe(){var e=[],t=$e();for(t===null&&(t=b(),t===null&&(t=S()));t!==null;)e.push(t),t=$e(),t===null&&(t=b(),t===null&&(t=S()));return e}function $e(){var e;return t.charCodeAt(i)===91?(e=`[`,i++):(e=null,a===0&&c(`"["`)),e===null&&(t.charCodeAt(i)===93?(e=`]`,i++):(e=null,a===0&&c(`"]"`)),e===null&&(t.charCodeAt(i)===47?(e=`/`,i++):(e=null,a===0&&c(`"/"`)),e===null&&(t.charCodeAt(i)===63?(e=`?`,i++):(e=null,a===0&&c(`"?"`)),e===null&&(t.charCodeAt(i)===58?(e=`:`,i++):(e=null,a===0&&c(`":"`)),e===null&&(t.charCodeAt(i)===43?(e=`+`,i++):(e=null,a===0&&c(`"+"`)),e===null&&(t.charCodeAt(i)===36?(e=`$`,i++):(e=null,a===0&&c(`"$"`)))))))),e}function R(){var e=Ot();return e===null&&(e=et()),e}function et(){var e,t,n,r,a,o=i;return e=Dt(),e===null?(e=null,i=o):(t=g(),t===null?(e=null,i=o):(n=tt(),n===null?(e=null,i=o):(r=g(),r===null?(e=null,i=o):(a=_t(),a===null?(e=null,i=o):e=[e,t,n,r,a])))),e}function tt(){var e=ye();return e===null&&(e=nt()),e}function nt(){var e,n,r,o=i;return e=ft(),e===null?(e=null,i=o):(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(e=null,i=o):(r=z(),r===null&&(r=at()),r===null?(e=null,i=o):e=[e,n,r])),e}function z(){var e,n,r,o=i,s;return e=rt(),e===null&&(e=it()),e===null?(e=null,i=o):(s=i,t.charCodeAt(i)===63?(n=`?`,i++):(n=null,a===0&&c(`"?"`)),n===null?(n=null,i=s):(r=gt(),r===null?(n=null,i=s):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=o):e=[e,n]),e}function rt(){var e,n,r,o=i;return t.substr(i,2)===`//`?(e=`//`,i+=2):(e=null,a===0&&c(`"//"`)),e===null?(e=null,i=o):(n=pt(),n===null?(e=null,i=o):(r=it(),r=r===null?``:r,r===null?(e=null,i=o):e=[e,n,r])),e}function it(){var e,n,r=i;return t.charCodeAt(i)===47?(e=`/`,i++):(e=null,a===0&&c(`"/"`)),e===null?(e=null,i=r):(n=ct(),n===null?(e=null,i=r):e=[e,n]),e}function at(){var e,t,n,r=i;if(e=st(),e!==null){for(t=[],n=ot();n!==null;)t.push(n),n=ot();t===null?(e=null,i=r):e=[e,t]}else e=null,i=r;return e}function ot(){var e=y();return e===null&&(e=b(),e===null&&(e=S())),e}function st(){var e=b();return e===null&&(e=S(),e===null&&(t.charCodeAt(i)===59?(e=`;`,i++):(e=null,a===0&&c(`";"`)),e===null&&(t.charCodeAt(i)===63?(e=`?`,i++):(e=null,a===0&&c(`"?"`)),e===null&&(t.charCodeAt(i)===58?(e=`:`,i++):(e=null,a===0&&c(`":"`)),e===null&&(t.charCodeAt(i)===64?(e=`@`,i++):(e=null,a===0&&c(`"@"`)),e===null&&(t.charCodeAt(i)===38?(e=`&`,i++):(e=null,a===0&&c(`"&"`)),e===null&&(t.charCodeAt(i)===61?(e=`=`,i++):(e=null,a===0&&c(`"="`)),e===null&&(t.charCodeAt(i)===43?(e=`+`,i++):(e=null,a===0&&c(`"+"`)),e===null&&(t.charCodeAt(i)===36?(e=`$`,i++):(e=null,a===0&&c(`"$"`)),e===null&&(t.charCodeAt(i)===44?(e=`,`,i++):(e=null,a===0&&c(`","`)))))))))))),e}function ct(){var e,n,r,o,s=i,l;if(e=lt(),e!==null){for(n=[],l=i,t.charCodeAt(i)===47?(r=`/`,i++):(r=null,a===0&&c(`"/"`)),r===null?(r=null,i=l):(o=lt(),o===null?(r=null,i=l):r=[r,o]);r!==null;)n.push(r),l=i,t.charCodeAt(i)===47?(r=`/`,i++):(r=null,a===0&&c(`"/"`)),r===null?(r=null,i=l):(o=lt(),o===null?(r=null,i=l):r=[r,o]);n===null?(e=null,i=s):e=[e,n]}else e=null,i=s;return e}function lt(){var e,n,r,o,s=i,l;for(e=[],n=dt();n!==null;)e.push(n),n=dt();if(e!==null){for(n=[],l=i,t.charCodeAt(i)===59?(r=`;`,i++):(r=null,a===0&&c(`";"`)),r===null?(r=null,i=l):(o=ut(),o===null?(r=null,i=l):r=[r,o]);r!==null;)n.push(r),l=i,t.charCodeAt(i)===59?(r=`;`,i++):(r=null,a===0&&c(`";"`)),r===null?(r=null,i=l):(o=ut(),o===null?(r=null,i=l):r=[r,o]);n===null?(e=null,i=s):e=[e,n]}else e=null,i=s;return e}function ut(){for(var e=[],t=dt();t!==null;)e.push(t),t=dt();return e}function dt(){var e=b();return e===null&&(e=S(),e===null&&(t.charCodeAt(i)===58?(e=`:`,i++):(e=null,a===0&&c(`":"`)),e===null&&(t.charCodeAt(i)===64?(e=`@`,i++):(e=null,a===0&&c(`"@"`)),e===null&&(t.charCodeAt(i)===38?(e=`&`,i++):(e=null,a===0&&c(`"&"`)),e===null&&(t.charCodeAt(i)===61?(e=`=`,i++):(e=null,a===0&&c(`"="`)),e===null&&(t.charCodeAt(i)===43?(e=`+`,i++):(e=null,a===0&&c(`"+"`)),e===null&&(t.charCodeAt(i)===36?(e=`$`,i++):(e=null,a===0&&c(`"$"`)),e===null&&(t.charCodeAt(i)===44?(e=`,`,i++):(e=null,a===0&&c(`","`)))))))))),e}function ft(){var e,n,r,o=i,s=i;if(e=d(),e!==null){for(n=[],r=d(),r===null&&(r=u(),r===null&&(t.charCodeAt(i)===43?(r=`+`,i++):(r=null,a===0&&c(`"+"`)),r===null&&(t.charCodeAt(i)===45?(r=`-`,i++):(r=null,a===0&&c(`"-"`)),r===null&&(t.charCodeAt(i)===46?(r=`.`,i++):(r=null,a===0&&c(`"."`))))));r!==null;)n.push(r),r=d(),r===null&&(r=u(),r===null&&(t.charCodeAt(i)===43?(r=`+`,i++):(r=null,a===0&&c(`"+"`)),r===null&&(t.charCodeAt(i)===45?(r=`-`,i++):(r=null,a===0&&c(`"-"`)),r===null&&(t.charCodeAt(i)===46?(r=`.`,i++):(r=null,a===0&&c(`"."`))))));n===null?(e=null,i=s):e=[e,n]}else e=null,i=s;return e!==null&&(e=(function(e){$.scheme=t.substring(i,e)})(o)),e===null&&(i=o),e}function pt(){var e=mt();return e===null&&(e=ht()),e}function mt(){var e,n,r=i,o=i;return e=Ce(),e===null?(e=null,i=o):(t.charCodeAt(i)===64?(n=`@`,i++):(n=null,a===0&&c(`"@"`)),n===null?(e=null,i=o):e=[e,n]),e=e===null?``:e,e===null?(e=null,i=r):(n=De(),n===null?(e=null,i=r):e=[e,n]),e=e===null?``:e,e}function ht(){var e,n=b();if(n===null&&(n=S(),n===null&&(t.charCodeAt(i)===36?(n=`$`,i++):(n=null,a===0&&c(`"$"`)),n===null&&(t.charCodeAt(i)===44?(n=`,`,i++):(n=null,a===0&&c(`","`)),n===null&&(t.charCodeAt(i)===59?(n=`;`,i++):(n=null,a===0&&c(`";"`)),n===null&&(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null&&(t.charCodeAt(i)===64?(n=`@`,i++):(n=null,a===0&&c(`"@"`)),n===null&&(t.charCodeAt(i)===38?(n=`&`,i++):(n=null,a===0&&c(`"&"`)),n===null&&(t.charCodeAt(i)===61?(n=`=`,i++):(n=null,a===0&&c(`"="`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`))))))))))),n!==null)for(e=[];n!==null;)e.push(n),n=b(),n===null&&(n=S(),n===null&&(t.charCodeAt(i)===36?(n=`$`,i++):(n=null,a===0&&c(`"$"`)),n===null&&(t.charCodeAt(i)===44?(n=`,`,i++):(n=null,a===0&&c(`","`)),n===null&&(t.charCodeAt(i)===59?(n=`;`,i++):(n=null,a===0&&c(`";"`)),n===null&&(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null&&(t.charCodeAt(i)===64?(n=`@`,i++):(n=null,a===0&&c(`"@"`)),n===null&&(t.charCodeAt(i)===38?(n=`&`,i++):(n=null,a===0&&c(`"&"`)),n===null&&(t.charCodeAt(i)===61?(n=`=`,i++):(n=null,a===0&&c(`"="`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)))))))))));else e=null;return e}function gt(){for(var e=[],t=ot();t!==null;)e.push(t),t=ot();return e}function _t(){var e,n,r,o,s,l,d=i,f=i;if(t.substr(i,3).toLowerCase()===`sip`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"SIP"`)),e!==null){if(t.charCodeAt(i)===47?(n=`/`,i++):(n=null,a===0&&c(`"/"`)),n!==null){if(o=u(),o!==null)for(r=[];o!==null;)r.push(o),o=u();else r=null;if(r!==null){if(t.charCodeAt(i)===46?(o=`.`,i++):(o=null,a===0&&c(`"."`)),o!==null){if(l=u(),l!==null)for(s=[];l!==null;)s.push(l),l=u();else s=null;s===null?(e=null,i=f):e=[e,n,r,o,s]}else e=null,i=f}else e=null,i=f}else e=null,i=f}else e=null,i=f;return e!==null&&(e=(function(e){$.sip_version=t.substring(i,e)})(d)),e===null&&(i=d),e}function vt(){var e;return t.substr(i,6)===`INVITE`?(e=`INVITE`,i+=6):(e=null,a===0&&c(`"INVITE"`)),e}function yt(){var e;return t.substr(i,3)===`ACK`?(e=`ACK`,i+=3):(e=null,a===0&&c(`"ACK"`)),e}function bt(){var e;return t.substr(i,7)===`OPTIONS`?(e=`OPTIONS`,i+=7):(e=null,a===0&&c(`"OPTIONS"`)),e}function xt(){var e;return t.substr(i,3)===`BYE`?(e=`BYE`,i+=3):(e=null,a===0&&c(`"BYE"`)),e}function St(){var e;return t.substr(i,6)===`CANCEL`?(e=`CANCEL`,i+=6):(e=null,a===0&&c(`"CANCEL"`)),e}function Ct(){var e;return t.substr(i,8)===`REGISTER`?(e=`REGISTER`,i+=8):(e=null,a===0&&c(`"REGISTER"`)),e}function wt(){var e;return t.substr(i,9)===`SUBSCRIBE`?(e=`SUBSCRIBE`,i+=9):(e=null,a===0&&c(`"SUBSCRIBE"`)),e}function Tt(){var e;return t.substr(i,6)===`NOTIFY`?(e=`NOTIFY`,i+=6):(e=null,a===0&&c(`"NOTIFY"`)),e}function Et(){var e;return t.substr(i,5)===`REFER`?(e=`REFER`,i+=5):(e=null,a===0&&c(`"REFER"`)),e}function Dt(){var e,n=i;return e=vt(),e===null&&(e=yt(),e===null&&(e=bt(),e===null&&(e=xt(),e===null&&(e=St(),e===null&&(e=Ct(),e===null&&(e=wt(),e===null&&(e=Tt(),e===null&&(e=Et(),e===null&&(e=O()))))))))),e!==null&&(e=(function(e){return $.method=t.substring(i,e),$.method})(n)),e===null&&(i=n),e}function Ot(){var e,t,n,r,a,o=i;return e=_t(),e===null?(e=null,i=o):(t=g(),t===null?(e=null,i=o):(n=kt(),n===null?(e=null,i=o):(r=g(),r===null?(e=null,i=o):(a=jt(),a===null?(e=null,i=o):e=[e,t,n,r,a])))),e}function kt(){var e,t=i;return e=At(),e!==null&&(e=(function(e,t){$.status_code=parseInt(t.join(``))})(t,e)),e===null&&(i=t),e}function At(){var e,t,n,r=i;return e=u(),e===null?(e=null,i=r):(t=u(),t===null?(e=null,i=r):(n=u(),n===null?(e=null,i=r):e=[e,t,n])),e}function jt(){var e,n,r=i;for(e=[],n=y(),n===null&&(n=b(),n===null&&(n=S(),n===null&&(n=D(),n===null&&(n=te(),n===null&&(n=g(),n===null&&(n=_()))))));n!==null;)e.push(n),n=y(),n===null&&(n=b(),n===null&&(n=S(),n===null&&(n=D(),n===null&&(n=te(),n===null&&(n=g(),n===null&&(n=_()))))));return e!==null&&(e=(function(e){$.reason_phrase=t.substring(i,e)})(r)),e===null&&(i=r),e}function Mt(){var e,t,n,r,a=i,o;if(e=nn(),e!==null){for(t=[],o=i,n=A(),n===null?(n=null,i=o):(r=nn(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=A(),n===null?(n=null,i=o):(r=nn(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function Nt(){var e,n,r,o=i,s=i,l;return e=ae(),e===null?(e=null,i=s):(l=i,t.charCodeAt(i)===64?(n=`@`,i++):(n=null,a===0&&c(`"@"`)),n===null?(n=null,i=l):(r=ae(),r===null?(n=null,i=l):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=s):e=[e,n]),e!==null&&(e=(function(e){$=t.substring(i,e)})(o)),e===null&&(i=o),e}function Pt(){var e,t,n,r,a=i,o,s;if(e=oe(),e===null){if(o=i,e=Ft(),e!==null){for(t=[],s=i,n=A(),n===null?(n=null,i=s):(r=Ft(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=A(),n===null?(n=null,i=s):(r=Ft(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o}return e!==null&&(e=(function(e){var t,n=$.multi_header.length;for(t=0;t<n;t++)if($.multi_header[t].parsed===null){$=null;break}$=$===null?-1:$.multi_header})(a)),e===null&&(i=a),e}function Ft(){var e,t,n,r,a=i,o=i,s;if(e=ve(),e===null&&(e=B()),e!==null){for(t=[],s=i,n=j(),n===null?(n=null,i=s):(r=Lt(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=j(),n===null?(n=null,i=s):(r=Lt(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o;return e!==null&&(e=(function(e){var t;$.multi_header||($.multi_header=[]);try{t=new Er($.uri,$.display_name,$.params),delete $.uri,delete $.display_name,delete $.params}catch{t=null}$.multi_header.push({possition:i,offset:e,parsed:t})})(a)),e===null&&(i=a),e}function B(){var e,t,n,r,a=i;return e=It(),e=e===null?``:e,e===null?(e=null,i=a):(t=de(),t===null?(e=null,i=a):(n=ye(),n===null?(e=null,i=a):(r=ue(),r===null?(e=null,i=a):e=[e,t,n,r]))),e}function It(){var e,t,n,r,a=i,o=i,s;if(e=O(),e!==null){for(t=[],s=i,n=C(),n===null?(n=null,i=s):(r=O(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=C(),n===null?(n=null,i=s):(r=O(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o;return e===null&&(e=N()),e!==null&&(e=(function(e,t){typeof t==`string`?$.display_name=t:$.display_name=t[1].reduce(function(e,t){return e+t[0]+t[1]},t[0])})(a,e)),e===null&&(i=a),e}function Lt(){var e=Rt();return e===null&&(e=V(),e===null&&(e=G())),e}function Rt(){var e,n,r,o=i,s=i;return t.substr(i,1).toLowerCase()===`q`?(e=t.substr(i,1),i++):(e=null,a===0&&c(`"q"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=U(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){$.params||($.params={}),$.params.q=t})(o,e[2])),e===null&&(i=o),e}function V(){var e,n,r,o=i,s=i;return t.substr(i,7).toLowerCase()===`expires`?(e=t.substr(i,7),i+=7):(e=null,a===0&&c(`"expires"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=H(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){$.params||($.params={}),$.params.expires=t})(o,e[2])),e===null&&(i=o),e}function H(){var e,t,n=i;if(t=u(),t!==null)for(e=[];t!==null;)e.push(t),t=u();else e=null;return e!==null&&(e=(function(e,t){return parseInt(t.join(``))})(n,e)),e===null&&(i=n),e}function U(){var e,n,r,o,s,l=i,d=i,f;return t.charCodeAt(i)===48?(e=`0`,i++):(e=null,a===0&&c(`"0"`)),e===null?(e=null,i=d):(f=i,t.charCodeAt(i)===46?(n=`.`,i++):(n=null,a===0&&c(`"."`)),n===null?(n=null,i=f):(r=u(),r=r===null?``:r,r===null?(n=null,i=f):(o=u(),o=o===null?``:o,o===null?(n=null,i=f):(s=u(),s=s===null?``:s,s===null?(n=null,i=f):n=[n,r,o,s]))),n=n===null?``:n,n===null?(e=null,i=d):e=[e,n]),e!==null&&(e=(function(e){return parseFloat(t.substring(i,e))})(l)),e===null&&(i=l),e}function G(){var e,t,n,r=i,a=i,o;return e=O(),e===null?(e=null,i=a):(o=i,t=k(),t===null?(t=null,i=o):(n=K(),n===null?(t=null,i=o):t=[t,n]),t=t===null?``:t,t===null?(e=null,i=a):e=[e,t]),e!==null&&(e=(function(e,t,n){$.params||($.params={}),n=n===void 0?void 0:n[1],$.params[t.toLowerCase()]=n})(r,e[0],e[1])),e===null&&(i=r),e}function K(){var e=O();return e===null&&(e=Oe(),e===null&&(e=M())),e}function Bt(){var e,t,n,r,a=i,o;if(e=Vt(),e!==null){for(t=[],o=i,n=j(),n===null?(n=null,i=o):(r=Ht(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=j(),n===null?(n=null,i=o):(r=Ht(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function Vt(){var e;return t.substr(i,6).toLowerCase()===`render`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"render"`)),e===null&&(t.substr(i,7).toLowerCase()===`session`?(e=t.substr(i,7),i+=7):(e=null,a===0&&c(`"session"`)),e===null&&(t.substr(i,4).toLowerCase()===`icon`?(e=t.substr(i,4),i+=4):(e=null,a===0&&c(`"icon"`)),e===null&&(t.substr(i,5).toLowerCase()===`alert`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"alert"`)),e===null&&(e=O())))),e}function Ht(){var e=q();return e===null&&(e=G()),e}function q(){var e,n,r,o=i;return t.substr(i,8).toLowerCase()===`handling`?(e=t.substr(i,8),i+=8):(e=null,a===0&&c(`"handling"`)),e===null?(e=null,i=o):(n=k(),n===null?(e=null,i=o):(t.substr(i,8).toLowerCase()===`optional`?(r=t.substr(i,8),i+=8):(r=null,a===0&&c(`"optional"`)),r===null&&(t.substr(i,8).toLowerCase()===`required`?(r=t.substr(i,8),i+=8):(r=null,a===0&&c(`"required"`)),r===null&&(r=O())),r===null?(e=null,i=o):e=[e,n,r])),e}function Ut(){var e,t,n,r,a=i,o;if(e=O(),e!==null){for(t=[],o=i,n=A(),n===null?(n=null,i=o):(r=O(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=A(),n===null?(n=null,i=o):(r=O(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function Wt(){var e,t,n=i;if(t=u(),t!==null)for(e=[];t!==null;)e.push(t),t=u();else e=null;return e!==null&&(e=(function(e,t){$=parseInt(t.join(``))})(n,e)),e===null&&(i=n),e}function Gt(){var e,n=i;return e=Kt(),e!==null&&(e=(function(e){$=t.substring(i,e)})(n)),e===null&&(i=n),e}function Kt(){var e,t,n,r,a,o,s=i,c;if(e=J(),e!==null){if(t=se(),t!==null){if(n=Yt(),n!==null){for(r=[],c=i,a=j(),a===null?(a=null,i=c):(o=Xt(),o===null?(a=null,i=c):a=[a,o]);a!==null;)r.push(a),c=i,a=j(),a===null?(a=null,i=c):(o=Xt(),o===null?(a=null,i=c):a=[a,o]);r===null?(e=null,i=s):e=[e,t,n,r]}else e=null,i=s}else e=null,i=s}else e=null,i=s;return e}function J(){var e=qt();return e===null&&(e=Jt()),e}function qt(){var e;return t.substr(i,4).toLowerCase()===`text`?(e=t.substr(i,4),i+=4):(e=null,a===0&&c(`"text"`)),e===null&&(t.substr(i,5).toLowerCase()===`image`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"image"`)),e===null&&(t.substr(i,5).toLowerCase()===`audio`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"audio"`)),e===null&&(t.substr(i,5).toLowerCase()===`video`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"video"`)),e===null&&(t.substr(i,11).toLowerCase()===`application`?(e=t.substr(i,11),i+=11):(e=null,a===0&&c(`"application"`)),e===null&&(e=Y()))))),e}function Jt(){var e;return t.substr(i,7).toLowerCase()===`message`?(e=t.substr(i,7),i+=7):(e=null,a===0&&c(`"message"`)),e===null&&(t.substr(i,9).toLowerCase()===`multipart`?(e=t.substr(i,9),i+=9):(e=null,a===0&&c(`"multipart"`)),e===null&&(e=Y())),e}function Y(){var e=O();return e===null&&(e=X()),e}function X(){var e,n,r=i;return t.substr(i,2).toLowerCase()===`x-`?(e=t.substr(i,2),i+=2):(e=null,a===0&&c(`"x-"`)),e===null?(e=null,i=r):(n=O(),n===null?(e=null,i=r):e=[e,n]),e}function Yt(){var e=Y();return e===null&&(e=O()),e}function Xt(){var e,t,n,r=i;return e=O(),e===null?(e=null,i=r):(t=k(),t===null?(e=null,i=r):(n=Zt(),n===null?(e=null,i=r):e=[e,t,n])),e}function Zt(){var e=O();return e===null&&(e=M()),e}function Qt(){var e,t,n,r=i;return e=$t(),e===null?(e=null,i=r):(t=C(),t===null?(e=null,i=r):(n=Dt(),n===null?(e=null,i=r):e=[e,t,n])),e}function $t(){var e,t,n=i;if(t=u(),t!==null)for(e=[];t!==null;)e.push(t),t=u();else e=null;return e!==null&&(e=(function(e,t){$.value=parseInt(t.join(``))})(n,e)),e===null&&(i=n),e}function en(){var e,t=i;return e=H(),e!==null&&(e=(function(e,t){$=t})(t,e)),e===null&&(i=t),e}function tn(){var e,t,n,r,a=i,o=i,s;if(e=nn(),e!==null){for(t=[],s=i,n=j(),n===null?(n=null,i=s):(r=G(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=j(),n===null?(n=null,i=s):(r=G(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o;return e!==null&&(e=(function(e,t){$.event=t.join(``).toLowerCase()})(a,e[0])),e===null&&(i=a),e}function nn(){var e,n,r,o,s=i,l;if(e=re(),e!==null){for(n=[],l=i,t.charCodeAt(i)===46?(r=`.`,i++):(r=null,a===0&&c(`"."`)),r===null?(r=null,i=l):(o=re(),o===null?(r=null,i=l):r=[r,o]);r!==null;)n.push(r),l=i,t.charCodeAt(i)===46?(r=`.`,i++):(r=null,a===0&&c(`"."`)),r===null?(r=null,i=l):(o=re(),o===null?(r=null,i=l):r=[r,o]);n===null?(e=null,i=s):e=[e,n]}else e=null,i=s;return e}function rn(){var e,t,n,r,a=i,o=i,s;if(e=ve(),e===null&&(e=B()),e!==null){for(t=[],s=i,n=j(),n===null?(n=null,i=s):(r=an(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=j(),n===null?(n=null,i=s):(r=an(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o;return e!==null&&(e=(function(e){var t=$.tag;try{$=new Er($.uri,$.display_name,$.params),t&&$.setParam(`tag`,t)}catch{$=-1}})(a)),e===null&&(i=a),e}function an(){var e=on();return e===null&&(e=G()),e}function on(){var e,n,r,o=i,s=i;return t.substr(i,3).toLowerCase()===`tag`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"tag"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=O(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){$.tag=t})(o,e[2])),e===null&&(i=o),e}function sn(){var e,t,n=i;if(t=u(),t!==null)for(e=[];t!==null;)e.push(t),t=u();else e=null;return e!==null&&(e=(function(e,t){$=parseInt(t.join(``))})(n,e)),e===null&&(i=n),e}function cn(){var e,t=i;return e=H(),e!==null&&(e=(function(e,t){$=t})(t,e)),e===null&&(i=t),e}function ln(){var e,t,n,r,a,o,s,c=i,l=i,u;for(e=[],t=It();t!==null;)e.push(t),t=It();if(e!==null){if(t=de(),t!==null){if(n=ye(),n!==null){if(r=ue(),r!==null){for(a=[],u=i,o=j(),o===null?(o=null,i=u):(s=G(),s===null?(o=null,i=u):o=[o,s]);o!==null;)a.push(o),u=i,o=j(),o===null?(o=null,i=u):(s=G(),s===null?(o=null,i=u):o=[o,s]);a===null?(e=null,i=l):e=[e,t,n,r,a]}else e=null,i=l}else e=null,i=l}else e=null,i=l}else e=null,i=l;return e!==null&&(e=(function(e){try{$=new Er($.uri,$.display_name,$.params)}catch{$=-1}})(c)),e===null&&(i=c),e}function un(){return dn()}function dn(){var e,n,r,o,s,l,u=i,d;if(t.substr(i,6).toLowerCase()===`digest`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"Digest"`)),e!==null){if(n=C(),n!==null){if(r=mn(),r!==null){for(o=[],d=i,s=A(),s===null?(s=null,i=d):(l=mn(),l===null?(s=null,i=d):s=[s,l]);s!==null;)o.push(s),d=i,s=A(),s===null?(s=null,i=d):(l=mn(),l===null?(s=null,i=d):s=[s,l]);o===null?(e=null,i=u):e=[e,n,r,o]}else e=null,i=u}else e=null,i=u}else e=null,i=u;return e===null&&(e=fn()),e}function fn(){var e,t,n,r,a,o,s=i,c;if(e=O(),e!==null){if(t=C(),t!==null){if(n=pn(),n!==null){for(r=[],c=i,a=A(),a===null?(a=null,i=c):(o=pn(),o===null?(a=null,i=c):a=[a,o]);a!==null;)r.push(a),c=i,a=A(),a===null?(a=null,i=c):(o=pn(),o===null?(a=null,i=c):a=[a,o]);r===null?(e=null,i=s):e=[e,t,n,r]}else e=null,i=s}else e=null,i=s}else e=null,i=s;return e}function pn(){var e,t,n,r=i;return e=O(),e===null?(e=null,i=r):(t=k(),t===null?(e=null,i=r):(n=O(),n===null&&(n=M()),n===null?(e=null,i=r):e=[e,t,n])),e}function mn(){var e=hn();return e===null&&(e=_n(),e===null&&(e=yn(),e===null&&(e=xn(),e===null&&(e=Sn(),e===null&&(e=Cn(),e===null&&(e=wn(),e===null&&(e=pn()))))))),e}function hn(){var e,n,r,o=i;return t.substr(i,5).toLowerCase()===`realm`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"realm"`)),e===null?(e=null,i=o):(n=k(),n===null?(e=null,i=o):(r=gn(),r===null?(e=null,i=o):e=[e,n,r])),e}function gn(){var e,t=i;return e=N(),e!==null&&(e=(function(e,t){$.realm=t})(t,e)),e===null&&(i=t),e}function _n(){var e,n,r,o,s,l,u,d=i,f;if(t.substr(i,6).toLowerCase()===`domain`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"domain"`)),e!==null){if(n=k(),n!==null){if(r=pe(),r!==null){if(o=vn(),o!==null){if(s=[],f=i,u=g(),u!==null)for(l=[];u!==null;)l.push(u),u=g();else l=null;for(l===null?(l=null,i=f):(u=vn(),u===null?(l=null,i=f):l=[l,u]);l!==null;){if(s.push(l),f=i,u=g(),u!==null)for(l=[];u!==null;)l.push(u),u=g();else l=null;l===null?(l=null,i=f):(u=vn(),u===null?(l=null,i=f):l=[l,u])}s===null?(e=null,i=d):(l=me(),l===null?(e=null,i=d):e=[e,n,r,o,s,l])}else e=null,i=d}else e=null,i=d}else e=null,i=d}else e=null,i=d;return e}function vn(){var e=nt();return e===null&&(e=it()),e}function yn(){var e,n,r,o=i;return t.substr(i,5).toLowerCase()===`nonce`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"nonce"`)),e===null?(e=null,i=o):(n=k(),n===null?(e=null,i=o):(r=bn(),r===null?(e=null,i=o):e=[e,n,r])),e}function bn(){var e,t=i;return e=N(),e!==null&&(e=(function(e,t){$.nonce=t})(t,e)),e===null&&(i=t),e}function xn(){var e,n,r,o=i,s=i;return t.substr(i,6).toLowerCase()===`opaque`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"opaque"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=N(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){$.opaque=t})(o,e[2])),e===null&&(i=o),e}function Sn(){var e,n,r,o=i,s;return t.substr(i,5).toLowerCase()===`stale`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"stale"`)),e===null?(e=null,i=o):(n=k(),n===null?(e=null,i=o):(s=i,t.substr(i,4).toLowerCase()===`true`?(r=t.substr(i,4),i+=4):(r=null,a===0&&c(`"true"`)),r!==null&&(r=(function(e){$.stale=!0})(s)),r===null&&(i=s),r===null&&(s=i,t.substr(i,5).toLowerCase()===`false`?(r=t.substr(i,5),i+=5):(r=null,a===0&&c(`"false"`)),r!==null&&(r=(function(e){$.stale=!1})(s)),r===null&&(i=s)),r===null?(e=null,i=o):e=[e,n,r])),e}function Cn(){var e,n,r,o=i,s=i;return t.substr(i,9).toLowerCase()===`algorithm`?(e=t.substr(i,9),i+=9):(e=null,a===0&&c(`"algorithm"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(t.substr(i,3).toLowerCase()===`md5`?(r=t.substr(i,3),i+=3):(r=null,a===0&&c(`"MD5"`)),r===null&&(t.substr(i,8).toLowerCase()===`md5-sess`?(r=t.substr(i,8),i+=8):(r=null,a===0&&c(`"MD5-sess"`)),r===null&&(r=O())),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){$.algorithm=t.toUpperCase()})(o,e[2])),e===null&&(i=o),e}function wn(){var e,n,r,o,s,l,u,d=i,f,p;if(t.substr(i,3).toLowerCase()===`qop`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"qop"`)),e!==null){if(n=k(),n!==null){if(r=pe(),r!==null){if(f=i,o=Tn(),o!==null){for(s=[],p=i,t.charCodeAt(i)===44?(l=`,`,i++):(l=null,a===0&&c(`","`)),l===null?(l=null,i=p):(u=Tn(),u===null?(l=null,i=p):l=[l,u]);l!==null;)s.push(l),p=i,t.charCodeAt(i)===44?(l=`,`,i++):(l=null,a===0&&c(`","`)),l===null?(l=null,i=p):(u=Tn(),u===null?(l=null,i=p):l=[l,u]);s===null?(o=null,i=f):o=[o,s]}else o=null,i=f;o===null?(e=null,i=d):(s=me(),s===null?(e=null,i=d):e=[e,n,r,o,s])}else e=null,i=d}else e=null,i=d}else e=null,i=d;return e}function Tn(){var e,n=i;return t.substr(i,8).toLowerCase()===`auth-int`?(e=t.substr(i,8),i+=8):(e=null,a===0&&c(`"auth-int"`)),e===null&&(t.substr(i,4).toLowerCase()===`auth`?(e=t.substr(i,4),i+=4):(e=null,a===0&&c(`"auth"`)),e===null&&(e=O())),e!==null&&(e=(function(e,t){$.qop||($.qop=[]),$.qop.push(t.toLowerCase())})(n,e)),e===null&&(i=n),e}function En(){var e,t,n,r,a=i,o;if(e=O(),e!==null){for(t=[],o=i,n=A(),n===null?(n=null,i=o):(r=O(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=A(),n===null?(n=null,i=o):(r=O(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function Dn(){var e,t,n,r,a=i,o=i,s;if(e=On(),e!==null){for(t=[],s=i,n=A(),n===null?(n=null,i=s):(r=On(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=A(),n===null?(n=null,i=s):(r=On(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o;return e!==null&&(e=(function(e){var t,n=$.multi_header.length;for(t=0;t<n;t++)if($.multi_header[t].parsed===null){$=null;break}$=$===null?-1:$.multi_header})(a)),e===null&&(i=a),e}function On(){var e,t,n,r,a=i,o=i,s;if(e=B(),e!==null){for(t=[],s=i,n=j(),n===null?(n=null,i=s):(r=G(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=j(),n===null?(n=null,i=s):(r=G(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o;return e!==null&&(e=(function(e){var t;$.multi_header||($.multi_header=[]);try{t=new Er($.uri,$.display_name,$.params),delete $.uri,delete $.display_name,delete $.params}catch{t=null}$.multi_header.push({possition:i,offset:e,parsed:t})})(a)),e===null&&(i=a),e}function kn(){var e,n,r,o,s=i,l=i,u;if(t.substr(i,3).toLowerCase()===`sip`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"SIP"`)),e===null&&(e=O()),e!==null){for(n=[],u=i,r=j(),r===null?(r=null,i=u):(o=Z(),o===null?(r=null,i=u):r=[r,o]);r!==null;)n.push(r),u=i,r=j(),r===null?(r=null,i=u):(o=Z(),o===null?(r=null,i=u):r=[r,o]);n===null?(e=null,i=l):e=[e,n]}else e=null,i=l;return e!==null&&(e=(function(e,t){if($.protocol=t.toLowerCase(),$.params||($.params={}),$.params.text&&$.params.text[0]===`"`){var n=$.params.text;$.text=n.substring(1,n.length-1),delete $.params.text}})(s,e[0])),e===null&&(i=s),e}function Z(){var e=An();return e===null&&(e=G()),e}function An(){var e,n,r,o,s=i,l=i;if(t.substr(i,5).toLowerCase()===`cause`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"cause"`)),e!==null){if(n=k(),n!==null){if(o=u(),o!==null)for(r=[];o!==null;)r.push(o),o=u();else r=null;r===null?(e=null,i=l):e=[e,n,r]}else e=null,i=l}else e=null,i=l;return e!==null&&(e=(function(e,t){$.cause=parseInt(t.join(``))})(s,e[2])),e===null&&(i=s),e}function jn(){var e,t,n,r,a=i,o;if(e=O(),e!==null){for(t=[],o=i,n=A(),n===null?(n=null,i=o):(r=O(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=A(),n===null?(n=null,i=o):(r=O(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function Mn(){var e,t,n,r,a=i,o;if(e=Nn(),e!==null){for(t=[],o=i,n=A(),n===null?(n=null,i=o):(r=Nn(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=A(),n===null?(n=null,i=o):(r=Nn(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function Nn(){var e,t,n,r,a=i,o;if(e=B(),e!==null){for(t=[],o=i,n=j(),n===null?(n=null,i=o):(r=G(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=j(),n===null?(n=null,i=o):(r=G(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function Pn(){var e,t,n,r,a=i,o;if(e=Fn(),e!==null){for(t=[],o=i,n=j(),n===null?(n=null,i=o):(r=In(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=j(),n===null?(n=null,i=o):(r=In(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function Fn(){var e,n=i;return t.substr(i,6).toLowerCase()===`active`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"active"`)),e===null&&(t.substr(i,7).toLowerCase()===`pending`?(e=t.substr(i,7),i+=7):(e=null,a===0&&c(`"pending"`)),e===null&&(t.substr(i,10).toLowerCase()===`terminated`?(e=t.substr(i,10),i+=10):(e=null,a===0&&c(`"terminated"`)),e===null&&(e=O()))),e!==null&&(e=(function(e){$.state=t.substring(i,e)})(n)),e===null&&(i=n),e}function In(){var e,n,r,o=i,s=i;return t.substr(i,6).toLowerCase()===`reason`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"reason"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=Ln(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){t!==void 0&&($.reason=t)})(o,e[2])),e===null&&(i=o),e===null&&(o=i,s=i,t.substr(i,7).toLowerCase()===`expires`?(e=t.substr(i,7),i+=7):(e=null,a===0&&c(`"expires"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=H(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){t!==void 0&&($.expires=t)})(o,e[2])),e===null&&(i=o),e===null&&(o=i,s=i,t.substr(i,11).toLowerCase()===`retry_after`?(e=t.substr(i,11),i+=11):(e=null,a===0&&c(`"retry_after"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=H(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){t!==void 0&&($.retry_after=t)})(o,e[2])),e===null&&(i=o),e===null&&(e=G()))),e}function Ln(){var e;return t.substr(i,11).toLowerCase()===`deactivated`?(e=t.substr(i,11),i+=11):(e=null,a===0&&c(`"deactivated"`)),e===null&&(t.substr(i,9).toLowerCase()===`probation`?(e=t.substr(i,9),i+=9):(e=null,a===0&&c(`"probation"`)),e===null&&(t.substr(i,8).toLowerCase()===`rejected`?(e=t.substr(i,8),i+=8):(e=null,a===0&&c(`"rejected"`)),e===null&&(t.substr(i,7).toLowerCase()===`timeout`?(e=t.substr(i,7),i+=7):(e=null,a===0&&c(`"timeout"`)),e===null&&(t.substr(i,6).toLowerCase()===`giveup`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"giveup"`)),e===null&&(t.substr(i,10).toLowerCase()===`noresource`?(e=t.substr(i,10),i+=10):(e=null,a===0&&c(`"noresource"`)),e===null&&(t.substr(i,9).toLowerCase()===`invariant`?(e=t.substr(i,9),i+=9):(e=null,a===0&&c(`"invariant"`)),e===null&&(e=O()))))))),e}function Rn(){var e=T();return e=e===null?``:e,e}function zn(){var e,t,n,r,a=i,o;if(e=O(),e!==null){for(t=[],o=i,n=A(),n===null?(n=null,i=o):(r=O(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=A(),n===null?(n=null,i=o):(r=O(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e=e===null?``:e,e}function Bn(){var e,t,n,r,a=i,o=i,s;if(e=ve(),e===null&&(e=B()),e!==null){for(t=[],s=i,n=j(),n===null?(n=null,i=s):(r=Vn(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=j(),n===null?(n=null,i=s):(r=Vn(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o;return e!==null&&(e=(function(e){var t=$.tag;try{$=new Er($.uri,$.display_name,$.params),t&&$.setParam(`tag`,t)}catch{$=-1}})(a)),e===null&&(i=a),e}function Vn(){var e=on();return e===null&&(e=G()),e}function Hn(){var e,t,n,r,a=i,o;if(e=Un(),e!==null){for(t=[],o=i,n=A(),n===null?(n=null,i=o):(r=Un(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=A(),n===null?(n=null,i=o):(r=Un(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function Un(){var e,t,n,r,a,o,s=i,c;if(e=Zn(),e!==null){if(t=C(),t!==null){if(n=er(),n!==null){for(r=[],c=i,a=j(),a===null?(a=null,i=c):(o=Wn(),o===null?(a=null,i=c):a=[a,o]);a!==null;)r.push(a),c=i,a=j(),a===null?(a=null,i=c):(o=Wn(),o===null?(a=null,i=c):a=[a,o]);r===null?(e=null,i=s):e=[e,t,n,r]}else e=null,i=s}else e=null,i=s}else e=null,i=s;return e}function Wn(){var e=Gn();return e===null&&(e=Kn(),e===null&&(e=qn(),e===null&&(e=Jn(),e===null&&(e=Yn(),e===null&&(e=G()))))),e}function Gn(){var e,n,r,o=i,s=i;return t.substr(i,3).toLowerCase()===`ttl`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"ttl"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=rr(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){$.ttl=t})(o,e[2])),e===null&&(i=o),e}function Kn(){var e,n,r,o=i,s=i;return t.substr(i,5).toLowerCase()===`maddr`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"maddr"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=Oe(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){$.maddr=t})(o,e[2])),e===null&&(i=o),e}function qn(){var e,n,r,o=i,s=i;return t.substr(i,8).toLowerCase()===`received`?(e=t.substr(i,8),i+=8):(e=null,a===0&&c(`"received"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=Ne(),r===null&&(r=Me()),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){$.received=t})(o,e[2])),e===null&&(i=o),e}function Jn(){var e,n,r,o=i,s=i;return t.substr(i,6).toLowerCase()===`branch`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"branch"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=O(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){$.branch=t})(o,e[2])),e===null&&(i=o),e}function Yn(){var e,n,r,o=i,s;return t.substr(i,5).toLowerCase()===`rport`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"rport"`)),e===null?(e=null,i=o):(s=i,n=k(),n===null?(n=null,i=s):(r=Xn(),r===null?(n=null,i=s):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=o):e=[e,n]),e}function Xn(){var e,t,n,r,a,o=i,s=i;return e=u(),e=e===null?``:e,e===null?(e=null,i=s):(t=u(),t=t===null?``:t,t===null?(e=null,i=s):(n=u(),n=n===null?``:n,n===null?(e=null,i=s):(r=u(),r=r===null?``:r,r===null?(e=null,i=s):(a=u(),a=a===null?``:a,a===null?(e=null,i=s):e=[e,t,n,r,a])))),e!==null&&(e=(function(e,t){$.rport=parseInt(t.join(``))})(o,e)),e===null&&(i=o),e}function Zn(){var e,t,n,r,a,o=i;return e=Qn(),e===null?(e=null,i=o):(t=se(),t===null?(e=null,i=o):(n=O(),n===null?(e=null,i=o):(r=se(),r===null?(e=null,i=o):(a=$n(),a===null?(e=null,i=o):e=[e,t,n,r,a])))),e}function Qn(){var e,n=i;return t.substr(i,3).toLowerCase()===`sip`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"SIP"`)),e===null&&(e=O()),e!==null&&(e=(function(e,t){$.protocol=t})(n,e)),e===null&&(i=n),e}function $n(){var e,n=i;return t.substr(i,3).toLowerCase()===`udp`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"UDP"`)),e===null&&(t.substr(i,3).toLowerCase()===`tcp`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"TCP"`)),e===null&&(t.substr(i,3).toLowerCase()===`tls`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"TLS"`)),e===null&&(t.substr(i,4).toLowerCase()===`sctp`?(e=t.substr(i,4),i+=4):(e=null,a===0&&c(`"SCTP"`)),e===null&&(e=O())))),e!==null&&(e=(function(e,t){$.transport=t})(n,e)),e===null&&(i=n),e}function er(){var e,t,n,r=i,a;return e=tr(),e===null?(e=null,i=r):(a=i,t=fe(),t===null?(t=null,i=a):(n=nr(),n===null?(t=null,i=a):t=[t,n]),t=t===null?``:t,t===null?(e=null,i=r):e=[e,t]),e}function tr(){var e,n=i;return e=Ne(),e===null&&(e=je(),e===null&&(e=ke())),e!==null&&(e=(function(e){$.host=t.substring(i,e)})(n)),e===null&&(i=n),e}function nr(){var e,t,n,r,a,o=i,s=i;return e=u(),e=e===null?``:e,e===null?(e=null,i=s):(t=u(),t=t===null?``:t,t===null?(e=null,i=s):(n=u(),n=n===null?``:n,n===null?(e=null,i=s):(r=u(),r=r===null?``:r,r===null?(e=null,i=s):(a=u(),a=a===null?``:a,a===null?(e=null,i=s):e=[e,t,n,r,a])))),e!==null&&(e=(function(e,t){$.port=parseInt(t.join(``))})(o,e)),e===null&&(i=o),e}function rr(){var e,t,n,r=i,a=i;return e=u(),e===null?(e=null,i=a):(t=u(),t=t===null?``:t,t===null?(e=null,i=a):(n=u(),n=n===null?``:n,n===null?(e=null,i=a):e=[e,t,n])),e!==null&&(e=(function(e,t){return parseInt(t.join(``))})(r,e)),e===null&&(i=r),e}function ir(){return dn()}function ar(){var e,t,n,r,a=i,o;if(e=or(),e!==null){for(t=[],o=i,n=j(),n===null?(n=null,i=o):(r=sr(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=j(),n===null?(n=null,i=o):(r=sr(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function or(){var e,t=i;return e=H(),e!==null&&(e=(function(e,t){$.expires=t})(t,e)),e===null&&(i=t),e}function sr(){var e=cr();return e===null&&(e=G()),e}function cr(){var e,n,r,o=i,s=i;return t.substr(i,9).toLowerCase()===`refresher`?(e=t.substr(i,9),i+=9):(e=null,a===0&&c(`"refresher"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(t.substr(i,3).toLowerCase()===`uac`?(r=t.substr(i,3),i+=3):(r=null,a===0&&c(`"uac"`)),r===null&&(t.substr(i,3).toLowerCase()===`uas`?(r=t.substr(i,3),i+=3):(r=null,a===0&&c(`"uas"`))),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){$.refresher=t.toLowerCase()})(o,e[2])),e===null&&(i=o),e}function lr(){var e,t,n,r=i;return e=O(),e===null?(e=null,i=r):(t=ee(),t===null?(e=null,i=r):(n=ur(),n===null?(e=null,i=r):e=[e,t,n])),e}function ur(){var e=[],t=E();for(t===null&&(t=te(),t===null&&(t=C()));t!==null;)e.push(t),t=E(),t===null&&(t=te(),t===null&&(t=C()));return e}function dr(){for(var e=[],t=m();t!==null;)e.push(t),t=m();return e}function fr(){var e,n,r=i;return t.substr(i,5)===`uuid:`?(e=`uuid:`,i+=5):(e=null,a===0&&c(`"uuid:"`)),e===null?(e=null,i=r):(n=pr(),n===null?(e=null,i=r):e=[e,n]),e}function pr(){var e,n,r,o,s,l,u,d,f,p=i,m=i;return e=mr(),e===null?(e=null,i=m):(t.charCodeAt(i)===45?(n=`-`,i++):(n=null,a===0&&c(`"-"`)),n===null?(e=null,i=m):(r=Q(),r===null?(e=null,i=m):(t.charCodeAt(i)===45?(o=`-`,i++):(o=null,a===0&&c(`"-"`)),o===null?(e=null,i=m):(s=Q(),s===null?(e=null,i=m):(t.charCodeAt(i)===45?(l=`-`,i++):(l=null,a===0&&c(`"-"`)),l===null?(e=null,i=m):(u=Q(),u===null?(e=null,i=m):(t.charCodeAt(i)===45?(d=`-`,i++):(d=null,a===0&&c(`"-"`)),d===null?(e=null,i=m):(f=hr(),f===null?(e=null,i=m):e=[e,n,r,o,s,l,u,d,f])))))))),e!==null&&(e=(function(e,n){$=t.substring(i+5,e)})(p,e[0])),e===null&&(i=p),e}function Q(){var e,t,n,r,a=i;return e=f(),e===null?(e=null,i=a):(t=f(),t===null?(e=null,i=a):(n=f(),n===null?(e=null,i=a):(r=f(),r===null?(e=null,i=a):e=[e,t,n,r]))),e}function mr(){var e,t,n=i;return e=Q(),e===null?(e=null,i=n):(t=Q(),t===null?(e=null,i=n):e=[e,t]),e}function hr(){var e,t,n,r=i;return e=Q(),e===null?(e=null,i=r):(t=Q(),t===null?(e=null,i=r):(n=Q(),n===null?(e=null,i=r):e=[e,t,n])),e}function gr(){var e,t,n,r,a=i,o=i,s;if(e=ve(),e===null&&(e=B()),e!==null){for(t=[],s=i,n=j(),n===null?(n=null,i=s):(r=G(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=j(),n===null?(n=null,i=s):(r=G(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o;return e!==null&&(e=(function(e){try{$=new Er($.uri,$.display_name,$.params)}catch{$=-1}})(a)),e===null&&(i=a),e}function _r(){var e,t,n,r,a=i,o;if(e=vr(),e!==null){for(t=[],o=i,n=j(),n===null?(n=null,i=o):(r=yr(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=j(),n===null?(n=null,i=o):(r=yr(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function vr(){var e,n,r,o=i,s=i,l;return e=ae(),e===null?(e=null,i=s):(l=i,t.charCodeAt(i)===64?(n=`@`,i++):(n=null,a===0&&c(`"@"`)),n===null?(n=null,i=l):(r=ae(),r===null?(n=null,i=l):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=s):e=[e,n]),e!==null&&(e=(function(e){$.call_id=t.substring(i,e)})(o)),e===null&&(i=o),e}function yr(){var e=br();return e===null&&(e=xr(),e===null&&(e=Sr(),e===null&&(e=G()))),e}function br(){var e,n,r,o=i,s=i;return t.substr(i,6)===`to-tag`?(e=`to-tag`,i+=6):(e=null,a===0&&c(`"to-tag"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=O(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){$.to_tag=t})(o,e[2])),e===null&&(i=o),e}function xr(){var e,n,r,o=i,s=i;return t.substr(i,8)===`from-tag`?(e=`from-tag`,i+=8):(e=null,a===0&&c(`"from-tag"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=O(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){$.from_tag=t})(o,e[2])),e===null&&(i=o),e}function Sr(){var e,n=i;return t.substr(i,10)===`early-only`?(e=`early-only`,i+=10):(e=null,a===0&&c(`"early-only"`)),e!==null&&(e=(function(e){$.early_only=!0})(n)),e===null&&(i=n),e}function Cr(e){e.sort();for(var t=null,n=[],r=0;r<e.length;r++)e[r]!==t&&(n.push(e[r]),t=e[r]);return n}function wr(){for(var e=1,n=1,r=!1,a=0;a<Math.max(i,o);a++){var s=t.charAt(a);s===`
|
|
4
|
-
`?(r||e++,n=1,r=!1):s===`\r`||s===`\u2028`||s===`\u2029`?(e++,n=1,r=!0):(n++,r=!1)}return{line:e,column:n}}var Tr=W(),Er=zt(),$={};if(r[n]()===null||i!==t.length){var Dr=Math.max(i,o),Or=Dr<t.length?t.charAt(Dr):null,kr=wr();return new this.SyntaxError(Cr(s),Or,Dr,kr.line,kr.column),-1}return $},toSource:function(){return this._source}};return t.SyntaxError=function(t,n,r,i,a){function o(t,n){var r,i;switch(t.length){case 0:r=`end of input`;break;case 1:r=t[0];break;default:r=t.slice(0,t.length-1).join(`, `)+` or `+t[t.length-1]}return i=n?e(n):`end of input`,`Expected `+r+` but `+i+` found.`}this.name=`SyntaxError`,this.expected=t,this.found=n,this.message=o(t,n),this.offset=r,this.line=i,this.column=a},t.SyntaxError.prototype=Error.prototype,t})()})),W=c(((e,t)=>{var n=V(),r=G(),i=U();t.exports=class e{static parse(e){if(e=i.parse(e,`SIP_URI`),e!==-1)return e}constructor(e,t,r,i,a={},o={}){if(!r)throw TypeError(`missing or invalid "host" parameter`);this._parameters={},this._headers={},this._scheme=e||n.SIP,this._user=t,this._host=r,this._port=i;for(let e in a)Object.prototype.hasOwnProperty.call(a,e)&&this.setParam(e,a[e]);for(let e in o)Object.prototype.hasOwnProperty.call(o,e)&&this.setHeader(e,o[e])}get scheme(){return this._scheme}set scheme(e){this._scheme=e.toLowerCase()}get user(){return this._user}set user(e){this._user=e}get host(){return this._host}set host(e){this._host=e.toLowerCase()}get port(){return this._port}set port(e){this._port=e===0?e:parseInt(e,10)||null}setParam(e,t){e&&(this._parameters[e.toLowerCase()]=t==null?null:t.toString())}getParam(e){if(e)return this._parameters[e.toLowerCase()]}hasParam(e){if(e)return this._parameters.hasOwnProperty(e.toLowerCase())&&!0||!1}deleteParam(e){if(e=e.toLowerCase(),this._parameters.hasOwnProperty(e)){let t=this._parameters[e];return delete this._parameters[e],t}}clearParams(){this._parameters={}}setHeader(e,t){this._headers[r.headerize(e)]=Array.isArray(t)?t:[t]}getHeader(e){if(e)return this._headers[r.headerize(e)]}hasHeader(e){if(e)return this._headers.hasOwnProperty(r.headerize(e))&&!0||!1}deleteHeader(e){if(e=r.headerize(e),this._headers.hasOwnProperty(e)){let t=this._headers[e];return delete this._headers[e],t}}clearHeaders(){this._headers={}}clone(){return new e(this._scheme,this._user,this._host,this._port,JSON.parse(JSON.stringify(this._parameters)),JSON.parse(JSON.stringify(this._headers)))}toString(){let e=[],t=`${this._scheme}:`;this._user&&(t+=`${r.escapeUser(this._user)}@`),t+=this._host,(this._port||this._port===0)&&(t+=`:${this._port}`);for(let e in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,e)&&(t+=`;${e}`,this._parameters[e]!==null&&(t+=`=${this._parameters[e]}`));for(let t in this._headers)if(Object.prototype.hasOwnProperty.call(this._headers,t))for(let n of this._headers[t])e.push(`${t}=${n}`);return e.length>0&&(t+=`?${e.join(`&`)}`),t}toAor(e){let t=`${this._scheme}:`;return this._user&&(t+=`${r.escapeUser(this._user)}@`),t+=this._host,e&&(this._port||this._port===0)&&(t+=`:${this._port}`),t}}})),G=c((e=>{var t=V(),n=W(),r=U();e.str_utf8_length=e=>unescape(encodeURIComponent(e)).length;var i=e.isFunction=e=>e!==void 0&&Object.prototype.toString.call(e)===`[object Function]`;e.isString=e=>e!==void 0&&Object.prototype.toString.call(e)===`[object String]`,e.isDecimal=e=>!isNaN(e)&&parseFloat(e)===parseInt(e,10),e.isEmpty=e=>e===null||e===``||e===void 0||Array.isArray(e)&&e.length===0||typeof e==`number`&&isNaN(e),e.hasMethods=function(e,...t){for(let n of t)if(i(e[n]))return!1;return!0};var a=e.createRandomToken=(e,t=32)=>{let n,r,i=``;for(n=0;n<e;n++)r=Math.random()*t|0,i+=r.toString(t);return i};e.newTag=()=>a(10),e.newUUID=()=>`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)}),e.hostType=e=>{if(e&&(e=r.parse(e,`host`),e!==-1))return e.host_type};var o=e.escapeUser=e=>encodeURIComponent(decodeURIComponent(e)).replace(/%3A/gi,`:`).replace(/%2B/gi,`+`).replace(/%3F/gi,`?`).replace(/%2F/gi,`/`);e.normalizeTarget=(e,r)=>{if(e){if(e instanceof n)return e;if(typeof e==`string`){let i=e.split(`@`),a,s;switch(i.length){case 1:if(!r)return;a=e,s=r;break;case 2:a=i[0],s=i[1];break;default:a=i.slice(0,i.length-1).join(`@`),s=i[i.length-1]}a=a.replace(/^(sips?|tel):/i,``),/^[-.()]*\+?[0-9\-.()]+$/.test(a)&&(a=a.replace(/[-.()]/g,``)),e=`${t.SIP}:${o(a)}@${s}`;let c;return(c=n.parse(e))?c:void 0}}},e.headerize=e=>{let t={"Call-Id":`Call-ID`,Cseq:`CSeq`,"Www-Authenticate":`WWW-Authenticate`},n=e.toLowerCase().replace(/_/g,`-`).split(`-`),r=``,i=n.length,a=0;for(;a<i;a++)a!==0&&(r+=`-`),r+=n[a].charAt(0).toUpperCase()+n[a].substring(1);return t[r]&&(r=t[r]),r},e.sipErrorCause=e=>{for(let n in t.SIP_ERROR_CAUSES)if(t.SIP_ERROR_CAUSES[n].indexOf(e)!==-1)return t.causes[n];return t.causes.SIP_FAILURE_CODE},e.getRandomTestNetIP=()=>{function e(e,t){return Math.floor(Math.random()*(t-e+1)+e)}return`192.0.2.${e(1,254)}`},e.calculateMD5=e=>{function t(e,t){return e<<t|e>>>32-t}function n(e,t){let n=e&2147483648,r=t&2147483648,i=e&1073741824,a=t&1073741824,o=(e&1073741823)+(t&1073741823);return i&a?o^2147483648^n^r:i|a?o&1073741824?o^3221225472^n^r:o^1073741824^n^r:o^n^r}function r(e,t,n){return e&t|~e&n}function i(e,t,n){return e&n|t&~n}function a(e,t,n){return e^t^n}function o(e,t,n){return t^(e|~n)}function s(e,i,a,o,s,c,l){return e=n(e,n(n(r(i,a,o),s),l)),n(t(e,c),i)}function c(e,r,a,o,s,c,l){return e=n(e,n(n(i(r,a,o),s),l)),n(t(e,c),r)}function l(e,r,i,o,s,c,l){return e=n(e,n(n(a(r,i,o),s),l)),n(t(e,c),r)}function u(e,r,i,a,s,c,l){return e=n(e,n(n(o(r,i,a),s),l)),n(t(e,c),r)}function d(e){let t,n=e.length,r=n+8,i=((r-r%64)/64+1)*16,a=Array(i-1),o=0,s=0;for(;s<n;)t=(s-s%4)/4,o=s%4*8,a[t]=a[t]|e.charCodeAt(s)<<o,s++;return t=(s-s%4)/4,o=s%4*8,a[t]=a[t]|128<<o,a[i-2]=n<<3,a[i-1]=n>>>29,a}function f(e){let t=``,n=``,r,i=0;for(;i<=3;i++)r=e>>>i*8&255,n=`0${r.toString(16)}`,t+=n.substr(n.length-2,2);return t}function p(e){let t=``;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r<128?t+=String.fromCharCode(r):r>127&&r<2048?(t+=String.fromCharCode(r>>6|192),t+=String.fromCharCode(r&63|128)):(t+=String.fromCharCode(r>>12|224),t+=String.fromCharCode(r>>6&63|128),t+=String.fromCharCode(r&63|128))}return t}let m=[],h,g,_,v,y,b,x,S,C;for(e=p(e),m=d(e),b=1732584193,x=4023233417,S=2562383102,C=271733878,h=0;h<m.length;h+=16)g=b,_=x,v=S,y=C,b=s(b,x,S,C,m[h+0],7,3614090360),C=s(C,b,x,S,m[h+1],12,3905402710),S=s(S,C,b,x,m[h+2],17,606105819),x=s(x,S,C,b,m[h+3],22,3250441966),b=s(b,x,S,C,m[h+4],7,4118548399),C=s(C,b,x,S,m[h+5],12,1200080426),S=s(S,C,b,x,m[h+6],17,2821735955),x=s(x,S,C,b,m[h+7],22,4249261313),b=s(b,x,S,C,m[h+8],7,1770035416),C=s(C,b,x,S,m[h+9],12,2336552879),S=s(S,C,b,x,m[h+10],17,4294925233),x=s(x,S,C,b,m[h+11],22,2304563134),b=s(b,x,S,C,m[h+12],7,1804603682),C=s(C,b,x,S,m[h+13],12,4254626195),S=s(S,C,b,x,m[h+14],17,2792965006),x=s(x,S,C,b,m[h+15],22,1236535329),b=c(b,x,S,C,m[h+1],5,4129170786),C=c(C,b,x,S,m[h+6],9,3225465664),S=c(S,C,b,x,m[h+11],14,643717713),x=c(x,S,C,b,m[h+0],20,3921069994),b=c(b,x,S,C,m[h+5],5,3593408605),C=c(C,b,x,S,m[h+10],9,38016083),S=c(S,C,b,x,m[h+15],14,3634488961),x=c(x,S,C,b,m[h+4],20,3889429448),b=c(b,x,S,C,m[h+9],5,568446438),C=c(C,b,x,S,m[h+14],9,3275163606),S=c(S,C,b,x,m[h+3],14,4107603335),x=c(x,S,C,b,m[h+8],20,1163531501),b=c(b,x,S,C,m[h+13],5,2850285829),C=c(C,b,x,S,m[h+2],9,4243563512),S=c(S,C,b,x,m[h+7],14,1735328473),x=c(x,S,C,b,m[h+12],20,2368359562),b=l(b,x,S,C,m[h+5],4,4294588738),C=l(C,b,x,S,m[h+8],11,2272392833),S=l(S,C,b,x,m[h+11],16,1839030562),x=l(x,S,C,b,m[h+14],23,4259657740),b=l(b,x,S,C,m[h+1],4,2763975236),C=l(C,b,x,S,m[h+4],11,1272893353),S=l(S,C,b,x,m[h+7],16,4139469664),x=l(x,S,C,b,m[h+10],23,3200236656),b=l(b,x,S,C,m[h+13],4,681279174),C=l(C,b,x,S,m[h+0],11,3936430074),S=l(S,C,b,x,m[h+3],16,3572445317),x=l(x,S,C,b,m[h+6],23,76029189),b=l(b,x,S,C,m[h+9],4,3654602809),C=l(C,b,x,S,m[h+12],11,3873151461),S=l(S,C,b,x,m[h+15],16,530742520),x=l(x,S,C,b,m[h+2],23,3299628645),b=u(b,x,S,C,m[h+0],6,4096336452),C=u(C,b,x,S,m[h+7],10,1126891415),S=u(S,C,b,x,m[h+14],15,2878612391),x=u(x,S,C,b,m[h+5],21,4237533241),b=u(b,x,S,C,m[h+12],6,1700485571),C=u(C,b,x,S,m[h+3],10,2399980690),S=u(S,C,b,x,m[h+10],15,4293915773),x=u(x,S,C,b,m[h+1],21,2240044497),b=u(b,x,S,C,m[h+8],6,1873313359),C=u(C,b,x,S,m[h+15],10,4264355552),S=u(S,C,b,x,m[h+6],15,2734768916),x=u(x,S,C,b,m[h+13],21,1309151649),b=u(b,x,S,C,m[h+4],6,4149444226),C=u(C,b,x,S,m[h+11],10,3174756917),S=u(S,C,b,x,m[h+2],15,718787259),x=u(x,S,C,b,m[h+9],21,3951481745),b=n(b,g),x=n(x,_),S=n(S,v),C=n(C,y);return(f(b)+f(x)+f(S)+f(C)).toLowerCase()},e.closeMediaStream=e=>{if(e)try{let t;if(e.getTracks){t=e.getTracks();for(let e of t)e.stop()}else{t=e.getAudioTracks();for(let e of t)e.stop();t=e.getVideoTracks();for(let e of t)e.stop()}}catch{(typeof e.stop==`function`||typeof e.stop==`object`)&&e.stop()}},e.cloneArray=e=>e&&e.slice()||[],e.cloneObject=(e,t={})=>e&&Object.assign({},e)||t})),K=c(((e,t)=>{var n=typeof Reflect==`object`?Reflect:null,r=n&&typeof n.apply==`function`?n.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},i=n&&typeof n.ownKeys==`function`?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};function a(e){console&&console.warn&&console.warn(e)}var o=Number.isNaN||function(e){return e!==e};function s(){s.init.call(this)}t.exports=s,t.exports.once=y,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var c=10;function l(e){if(typeof e!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof e)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return c},set:function(e){if(typeof e!=`number`||e<0||o(e))throw RangeError(`The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received `+e+`.`);c=e}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if(typeof e!=`number`||e<0||o(e))throw RangeError(`The value of "n" is out of range. It must be a non-negative number. Received `+e+`.`);return this._maxListeners=e,this};function u(e){return e._maxListeners===void 0?s.defaultMaxListeners:e._maxListeners}s.prototype.getMaxListeners=function(){return u(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i=e===`error`,a=this._events;if(a!==void 0)i&&=a.error===void 0;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var s=Error(`Unhandled error.`+(o?` (`+o.message+`)`:``));throw s.context=o,s}var c=a[e];if(c===void 0)return!1;if(typeof c==`function`)r(c,this,t);else for(var l=c.length,u=g(c,l),n=0;n<l;++n)r(u[n],this,t);return!0};function d(e,t,n,r){var i,o,s;if(l(n),o=e._events,o===void 0?(o=e._events=Object.create(null),e._eventsCount=0):(o.newListener!==void 0&&(e.emit(`newListener`,t,n.listener?n.listener:n),o=e._events),s=o[t]),s===void 0)s=o[t]=n,++e._eventsCount;else if(typeof s==`function`?s=o[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),i=u(e),i>0&&s.length>i&&!s.warned){s.warned=!0;var c=Error(`Possible EventEmitter memory leak detected. `+s.length+` `+String(t)+` listeners added. Use emitter.setMaxListeners() to increase limit`);c.name=`MaxListenersExceededWarning`,c.emitter=e,c.type=t,c.count=s.length,a(c)}return e}s.prototype.addListener=function(e,t){return d(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return d(this,e,t,!0)};function f(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function p(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=f.bind(r);return i.listener=n,r.wrapFn=i,i}s.prototype.once=function(e,t){return l(t),this.on(e,p(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return l(t),this.prependListener(e,p(this,e,t)),this},s.prototype.removeListener=function(e,t){var n,r,i,a,o;if(l(t),r=this._events,r===void 0||(n=r[e],n===void 0))return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit(`removeListener`,e,n.listener||t));else if(typeof n!=`function`){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,i=a;break}if(i<0)return this;i===0?n.shift():_(n,i),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit(`removeListener`,e,o||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,n=this._events,r;if(n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var i=Object.keys(n),a;for(r=0;r<i.length;++r)a=i[r],a!==`removeListener`&&this.removeAllListeners(a);return this.removeAllListeners(`removeListener`),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t==`function`)this.removeListener(e,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this};function m(e,t,n){var r=e._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i==`function`?n?[i.listener||i]:[i]:n?v(i):g(i,i.length)}s.prototype.listeners=function(e){return m(this,e,!0)},s.prototype.rawListeners=function(e){return m(this,e,!1)},s.listenerCount=function(e,t){return typeof e.listenerCount==`function`?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h;function h(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n==`function`)return 1;if(n!==void 0)return n.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?i(this._events):[]};function g(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function _(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function v(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function y(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,a),r(n)}function a(){typeof e.removeListener==`function`&&e.removeListener(`error`,i),n([].slice.call(arguments))}x(e,t,a,{once:!0}),t!==`error`&&b(e,i,{once:!0})})}function b(e,t,n){typeof e.on==`function`&&x(e,`error`,t,n)}function x(e,t,n,r){if(typeof e.on==`function`)r.once?e.once(t,n):e.on(t,n);else if(typeof e.addEventListener==`function`)e.addEventListener(t,function i(a){r.once&&e.removeEventListener(t,i),n(a)});else throw TypeError(`The "emitter" argument must be of type EventEmitter. Received type `+typeof e)}})),Bt=c(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),Vt=c(((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=Bt(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}t.exports=n})),Ht=c(((e,t)=>{e.formatArgs=r,e.save=i,e.load=a,e.useColors=n,e.storage=o(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=`#0000CC.#0000FF.#0033CC.#0033FF.#0066CC.#0066FF.#0099CC.#0099FF.#00CC00.#00CC33.#00CC66.#00CC99.#00CCCC.#00CCFF.#3300CC.#3300FF.#3333CC.#3333FF.#3366CC.#3366FF.#3399CC.#3399FF.#33CC00.#33CC33.#33CC66.#33CC99.#33CCCC.#33CCFF.#6600CC.#6600FF.#6633CC.#6633FF.#66CC00.#66CC33.#9900CC.#9900FF.#9933CC.#9933FF.#99CC00.#99CC33.#CC0000.#CC0033.#CC0066.#CC0099.#CC00CC.#CC00FF.#CC3300.#CC3333.#CC3366.#CC3399.#CC33CC.#CC33FF.#CC6600.#CC6633.#CC9900.#CC9933.#CCCC00.#CCCC33.#FF0000.#FF0033.#FF0066.#FF0099.#FF00CC.#FF00FF.#FF3300.#FF3333.#FF3366.#FF3399.#FF33CC.#FF33FF.#FF6600.#FF6633.#FF9900.#FF9933.#FFCC00.#FFCC33`.split(`.`);function n(){if(typeof window<`u`&&window.process&&(window.process.type===`renderer`||window.process.__nwjs))return!0;if(typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<`u`&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<`u`&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<`u`&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function i(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function a(){let t;try{t=e.storage.getItem(`debug`)||e.storage.getItem(`DEBUG`)}catch{}return!t&&typeof process<`u`&&`env`in process&&(t=process.env.DEBUG),t}function o(){try{return localStorage}catch{}}t.exports=Vt()(e);var{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),q=c(((e,t)=>{var n=Ht(),r=`JsSIP`;t.exports=class{constructor(e){e?(this._debug=n.default(`${r}:${e}`),this._warn=n.default(`${r}:WARN:${e}`),this._error=n.default(`${r}:ERROR:${e}`)):(this._debug=n.default(r),this._warn=n.default(`${r}:WARN`),this._error=n.default(`${r}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}}})),Ut=c(((e,t)=>{var n=t.exports={v:[{name:`version`,reg:/^(\d*)$/}],o:[{name:`origin`,reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:[`username`,`sessionId`,`sessionVersion`,`netType`,`ipVer`,`address`],format:`%s %s %d %s IP%d %s`}],s:[{name:`name`}],i:[{name:`description`}],u:[{name:`uri`}],e:[{name:`email`}],p:[{name:`phone`}],z:[{name:`timezones`}],r:[{name:`repeats`}],t:[{name:`timing`,reg:/^(\d*) (\d*)/,names:[`start`,`stop`],format:`%d %d`}],c:[{name:`connection`,reg:/^IN IP(\d) (\S*)/,names:[`version`,`ip`],format:`IN IP%d %s`}],b:[{push:`bandwidth`,reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:[`type`,`limit`],format:`%s:%s`}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:[`type`,`port`,`protocol`,`payloads`],format:`%s %d %s %s`}],a:[{push:`rtp`,reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:[`payload`,`codec`,`rate`,`encoding`],format:function(e){return e.encoding?`rtpmap:%d %s/%s/%s`:e.rate?`rtpmap:%d %s/%s`:`rtpmap:%d %s`}},{push:`fmtp`,reg:/^fmtp:(\d*) ([\S| ]*)/,names:[`payload`,`config`],format:`fmtp:%d %s`},{name:`control`,reg:/^control:(.*)/,format:`control:%s`},{name:`rtcp`,reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:[`port`,`netType`,`ipVer`,`address`],format:function(e){return e.address==null?`rtcp:%d`:`rtcp:%d %s IP%d %s`}},{push:`rtcpFbTrrInt`,reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:[`payload`,`value`],format:`rtcp-fb:%s trr-int %d`},{push:`rtcpFb`,reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:[`payload`,`type`,`subtype`],format:function(e){return e.subtype==null?`rtcp-fb:%s %s`:`rtcp-fb:%s %s %s`}},{push:`ext`,reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:[`value`,`direction`,`encrypt-uri`,`uri`,`config`],format:function(e){return`extmap:%d`+(e.direction?`/%s`:`%v`)+(e[`encrypt-uri`]?` %s`:`%v`)+` %s`+(e.config?` %s`:``)}},{name:`extmapAllowMixed`,reg:/^(extmap-allow-mixed)/},{push:`crypto`,reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:[`id`,`suite`,`config`,`sessionConfig`],format:function(e){return e.sessionConfig==null?`crypto:%d %s %s`:`crypto:%d %s %s %s`}},{name:`setup`,reg:/^setup:(\w*)/,format:`setup:%s`},{name:`connectionType`,reg:/^connection:(new|existing)/,format:`connection:%s`},{name:`mid`,reg:/^mid:([^\s]*)/,format:`mid:%s`},{name:`msid`,reg:/^msid:(.*)/,format:`msid:%s`},{name:`ptime`,reg:/^ptime:(\d*(?:\.\d*)*)/,format:`ptime:%d`},{name:`maxptime`,reg:/^maxptime:(\d*(?:\.\d*)*)/,format:`maxptime:%d`},{name:`direction`,reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:`icelite`,reg:/^(ice-lite)/},{name:`iceUfrag`,reg:/^ice-ufrag:(\S*)/,format:`ice-ufrag:%s`},{name:`icePwd`,reg:/^ice-pwd:(\S*)/,format:`ice-pwd:%s`},{name:`fingerprint`,reg:/^fingerprint:(\S*) (\S*)/,names:[`type`,`hash`],format:`fingerprint:%s %s`},{push:`candidates`,reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:[`foundation`,`component`,`transport`,`priority`,`ip`,`port`,`type`,`raddr`,`rport`,`tcptype`,`generation`,`network-id`,`network-cost`],format:function(e){var t=`candidate:%s %d %s %d %s %d typ %s`;return t+=e.raddr==null?`%v%v`:` raddr %s rport %d`,t+=e.tcptype==null?`%v`:` tcptype %s`,e.generation!=null&&(t+=` generation %d`),t+=e[`network-id`]==null?`%v`:` network-id %d`,t+=e[`network-cost`]==null?`%v`:` network-cost %d`,t}},{name:`endOfCandidates`,reg:/^(end-of-candidates)/},{name:`remoteCandidates`,reg:/^remote-candidates:(.*)/,format:`remote-candidates:%s`},{name:`iceOptions`,reg:/^ice-options:(\S*)/,format:`ice-options:%s`},{push:`ssrcs`,reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:[`id`,`attribute`,`value`],format:function(e){var t=`ssrc:%d`;return e.attribute!=null&&(t+=` %s`,e.value!=null&&(t+=`:%s`)),t}},{push:`ssrcGroups`,reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:[`semantics`,`ssrcs`],format:`ssrc-group:%s %s`},{name:`msidSemantic`,reg:/^msid-semantic:\s?(\w*) (\S*)/,names:[`semantic`,`token`],format:`msid-semantic: %s %s`},{push:`groups`,reg:/^group:(\w*) (.*)/,names:[`type`,`mids`],format:`group:%s %s`},{name:`rtcpMux`,reg:/^(rtcp-mux)/},{name:`rtcpRsize`,reg:/^(rtcp-rsize)/},{name:`sctpmap`,reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:[`sctpmapNumber`,`app`,`maxMessageSize`],format:function(e){return e.maxMessageSize==null?`sctpmap:%s %s`:`sctpmap:%s %s %s`}},{name:`xGoogleFlag`,reg:/^x-google-flag:([^\s]*)/,format:`x-google-flag:%s`},{push:`rids`,reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:[`id`,`direction`,`params`],format:function(e){return e.params?`rid:%s %s %s`:`rid:%s %s`}},{push:`imageattrs`,reg:RegExp(`^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?`),names:[`pt`,`dir1`,`attrs1`,`dir2`,`attrs2`],format:function(e){return`imageattr:%s %s %s`+(e.dir2?` %s %s`:``)}},{name:`simulcast`,reg:RegExp(`^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$`),names:[`dir1`,`list1`,`dir2`,`list2`],format:function(e){return`simulcast:%s %s`+(e.dir2?` %s %s`:``)}},{name:`simulcast_03`,reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:[`value`],format:`simulcast: %s`},{name:`framerate`,reg:/^framerate:(\d+(?:$|\.\d+))/,format:`framerate:%s`},{name:`sourceFilter`,reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:[`filterMode`,`netType`,`addressTypes`,`destAddress`,`srcList`],format:`source-filter: %s %s %s %s %s`},{name:`bundleOnly`,reg:/^(bundle-only)/},{name:`label`,reg:/^label:(.+)/,format:`label:%s`},{name:`sctpPort`,reg:/^sctp-port:(\d+)$/,format:`sctp-port:%s`},{name:`maxMessageSize`,reg:/^max-message-size:(\d+)$/,format:`max-message-size:%s`},{push:`tsRefClocks`,reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:[`clksrc`,`clksrcExt`],format:function(e){return`ts-refclk:%s`+(e.clksrcExt==null?``:`=%s`)}},{name:`mediaClk`,reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:[`id`,`mediaClockName`,`mediaClockValue`,`rateNumerator`,`rateDenominator`],format:function(e){var t=`mediaclk:`;return t+=e.id==null?`%v%s`:`id=%s %s`,t+=e.mediaClockValue==null?``:`=%s`,t+=e.rateNumerator==null?``:` rate=%s`,t+=e.rateDenominator==null?``:`/%s`,t}},{name:`keywords`,reg:/^keywds:(.+)$/,format:`keywds:%s`},{name:`content`,reg:/^content:(.+)/,format:`content:%s`},{name:`bfcpFloorCtrl`,reg:/^floorctrl:(c-only|s-only|c-s)/,format:`floorctrl:%s`},{name:`bfcpConfId`,reg:/^confid:(\d+)/,format:`confid:%s`},{name:`bfcpUserId`,reg:/^userid:(\d+)/,format:`userid:%s`},{name:`bfcpFloorId`,reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:[`id`,`mStream`],format:`floorid:%s mstrm:%s`},{push:`invalid`,names:[`value`]}]};Object.keys(n).forEach(function(e){n[e].forEach(function(e){e.reg||=/(.*)/,e.format||=`%s`})})})),Wt=c((e=>{var t=function(e){return String(Number(e))===e?Number(e):e},n=function(e,n,r,i){if(i&&!r)n[i]=t(e[1]);else for(var a=0;a<r.length;a+=1)e[a+1]!=null&&(n[r[a]]=t(e[a+1]))},r=function(e,t,r){var i=e.name&&e.names;e.push&&!t[e.push]?t[e.push]=[]:i&&!t[e.name]&&(t[e.name]={});var a=e.push?{}:i?t[e.name]:t;n(r.match(e.reg),a,e.names,e.name),e.push&&t[e.push].push(a)},i=Ut(),a=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},n=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(a).forEach(function(e){var t=e[0],a=e.slice(2);t===`m`&&(n.push({rtp:[],fmtp:[]}),o=n[n.length-1]);for(var s=0;s<(i[t]||[]).length;s+=1){var c=i[t][s];if(c.reg.test(a))return r(c,o,a)}}),t.media=n,t};var o=function(e,n){var r=n.split(/=(.+)/,2);return r.length===2?e[r[0]]=t(r[1]):r.length===1&&n.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(` `).map(Number)},e.parseRemoteCandidates=function(e){for(var n=[],r=e.split(` `).map(t),i=0;i<r.length;i+=3)n.push({component:r[i],ip:r[i+1],port:r[i+2]});return n},e.parseImageAttributes=function(e){return e.split(` `).map(function(e){return e.substring(1,e.length-1).split(`,`).reduce(o,{})})},e.parseSimulcastStreamList=function(e){return e.split(`;`).map(function(e){return e.split(`,`).map(function(e){var n,r=!1;return e[0]===`~`?(n=t(e.substring(1,e.length)),r=!0):n=t(e),{scid:n,paused:r}})})}})),Gt=c(((e,t)=>{var n=Ut(),r=/%[sdv%]/g,i=function(e){var t=1,n=arguments,i=n.length;return e.replace(r,function(e){if(t>=i)return e;var r=n[t];switch(t+=1,e){case`%%`:return`%`;case`%s`:return String(r);case`%d`:return Number(r);case`%v`:return``}})},a=function(e,t,n){var r=t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format,a=[e+`=`+r];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?a.push(n[t.name][s]):a.push(n[t.names[o]])}else a.push(n[t.name]);return i.apply(null,a)},o=[`v`,`o`,`s`,`i`,`u`,`e`,`p`,`c`,`b`,`t`,`r`,`z`,`a`],s=[`i`,`c`,`b`,`a`];t.exports=function(e,t){t||={},e.version??=0,e.name??=` `,e.media.forEach(function(e){e.payloads??=``});var r=t.outerOrder||o,i=t.innerOrder||s,c=[];return r.forEach(function(t){n[t].forEach(function(n){n.name in e&&e[n.name]!=null?c.push(a(t,n,e)):n.push in e&&e[n.push]!=null&&e[n.push].forEach(function(e){c.push(a(t,n,e))})})}),e.media.forEach(function(e){c.push(a(`m`,n.m[0],e)),i.forEach(function(t){n[t].forEach(function(n){n.name in e&&e[n.name]!=null?c.push(a(t,n,e)):n.push in e&&e[n.push]!=null&&e[n.push].forEach(function(e){c.push(a(t,n,e))})})})}),c.join(`\r
|
|
3
|
+
`,i+=2):(e=null,a===0&&c(`"\\r\\n"`)),e}function u(){var e;return/^[0-9]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[0-9]`)),e}function d(){var e;return/^[a-zA-Z]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[a-zA-Z]`)),e}function f(){var e;return/^[0-9a-fA-F]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[0-9a-fA-F]`)),e}function p(){var e=g();return e===null&&(e=_()),e}function m(){var e;return/^[\0-\xFF]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[\\0-\\xFF]`)),e}function h(){var e;return/^["]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`["]`)),e}function g(){var e;return t.charCodeAt(i)===32?(e=` `,i++):(e=null,a===0&&c(`" "`)),e}function _(){var e;return t.charCodeAt(i)===9?(e=` `,i++):(e=null,a===0&&c(`"\\t"`)),e}function v(){var e;return/^[a-zA-Z0-9]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[a-zA-Z0-9]`)),e}function y(){var e;return t.charCodeAt(i)===59?(e=`;`,i++):(e=null,a===0&&c(`";"`)),e===null&&(t.charCodeAt(i)===47?(e=`/`,i++):(e=null,a===0&&c(`"/"`)),e===null&&(t.charCodeAt(i)===63?(e=`?`,i++):(e=null,a===0&&c(`"?"`)),e===null&&(t.charCodeAt(i)===58?(e=`:`,i++):(e=null,a===0&&c(`":"`)),e===null&&(t.charCodeAt(i)===64?(e=`@`,i++):(e=null,a===0&&c(`"@"`)),e===null&&(t.charCodeAt(i)===38?(e=`&`,i++):(e=null,a===0&&c(`"&"`)),e===null&&(t.charCodeAt(i)===61?(e=`=`,i++):(e=null,a===0&&c(`"="`)),e===null&&(t.charCodeAt(i)===43?(e=`+`,i++):(e=null,a===0&&c(`"+"`)),e===null&&(t.charCodeAt(i)===36?(e=`$`,i++):(e=null,a===0&&c(`"$"`)),e===null&&(t.charCodeAt(i)===44?(e=`,`,i++):(e=null,a===0&&c(`","`))))))))))),e}function b(){var e=v();return e===null&&(e=x()),e}function x(){var e;return t.charCodeAt(i)===45?(e=`-`,i++):(e=null,a===0&&c(`"-"`)),e===null&&(t.charCodeAt(i)===95?(e=`_`,i++):(e=null,a===0&&c(`"_"`)),e===null&&(t.charCodeAt(i)===46?(e=`.`,i++):(e=null,a===0&&c(`"."`)),e===null&&(t.charCodeAt(i)===33?(e=`!`,i++):(e=null,a===0&&c(`"!"`)),e===null&&(t.charCodeAt(i)===126?(e=`~`,i++):(e=null,a===0&&c(`"~"`)),e===null&&(t.charCodeAt(i)===42?(e=`*`,i++):(e=null,a===0&&c(`"*"`)),e===null&&(t.charCodeAt(i)===39?(e=`'`,i++):(e=null,a===0&&c(`"'"`)),e===null&&(t.charCodeAt(i)===40?(e=`(`,i++):(e=null,a===0&&c(`"("`)),e===null&&(t.charCodeAt(i)===41?(e=`)`,i++):(e=null,a===0&&c(`")"`)))))))))),e}function S(){var e,n,r,o=i,s=i;return t.charCodeAt(i)===37?(e=`%`,i++):(e=null,a===0&&c(`"%"`)),e===null?(e=null,i=s):(n=f(),n===null?(e=null,i=s):(r=f(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){return t.join(``)})(o,e)),e===null&&(i=o),e}function C(){var e,t,n,r=i,a=i,o=i;for(e=[],t=p();t!==null;)e.push(t),t=p();if(e===null?(e=null,i=o):(t=l(),t===null?(e=null,i=o):e=[e,t]),e=e===null?``:e,e!==null){if(n=p(),n!==null)for(t=[];n!==null;)t.push(n),n=p();else t=null;t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e!==null&&(e=(function(e){return` `})(r)),e===null&&(i=r),e}function w(){var e=C();return e=e===null?``:e,e}function ee(){var e,n,r,o=i,s=i;for(e=[],n=g(),n===null&&(n=_());n!==null;)e.push(n),n=g(),n===null&&(n=_());return e===null?(e=null,i=s):(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e){return`:`})(o)),e===null&&(i=o),e}function T(){var e,n,r,a,o=i,s=i,c;if(n=E(),n!==null)for(e=[];n!==null;)e.push(n),n=E();else e=null;if(e!==null){for(n=[],c=i,r=[],a=C();a!==null;)r.push(a),a=C();for(r===null?(r=null,i=c):(a=E(),a===null?(r=null,i=c):r=[r,a]);r!==null;){for(n.push(r),c=i,r=[],a=C();a!==null;)r.push(a),a=C();r===null?(r=null,i=c):(a=E(),a===null?(r=null,i=c):r=[r,a])}n===null?(e=null,i=s):e=[e,n]}else e=null,i=s;return e!==null&&(e=(function(e){return t.substring(i,e)})(o)),e===null&&(i=o),e}function E(){var e;return/^[!-~]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[!-~]`)),e===null&&(e=D()),e}function D(){var e;return/^[\x80-\uFFFF]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[\\x80-\\uFFFF]`)),e}function te(){var e;return/^[\x80-\xBF]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[\\x80-\\xBF]`)),e}function ne(){var e=u();return e===null&&(/^[a-f]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[a-f]`))),e}function O(){var e,n,r=i;if(n=v(),n===null&&(t.charCodeAt(i)===45?(n=`-`,i++):(n=null,a===0&&c(`"-"`)),n===null&&(t.charCodeAt(i)===46?(n=`.`,i++):(n=null,a===0&&c(`"."`)),n===null&&(t.charCodeAt(i)===33?(n=`!`,i++):(n=null,a===0&&c(`"!"`)),n===null&&(t.charCodeAt(i)===37?(n=`%`,i++):(n=null,a===0&&c(`"%"`)),n===null&&(t.charCodeAt(i)===42?(n=`*`,i++):(n=null,a===0&&c(`"*"`)),n===null&&(t.charCodeAt(i)===95?(n=`_`,i++):(n=null,a===0&&c(`"_"`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)),n===null&&(t.charCodeAt(i)===96?(n="`",i++):(n=null,a===0&&c('"`"')),n===null&&(t.charCodeAt(i)===39?(n=`'`,i++):(n=null,a===0&&c(`"'"`)),n===null&&(t.charCodeAt(i)===126?(n=`~`,i++):(n=null,a===0&&c(`"~"`)))))))))))),n!==null)for(e=[];n!==null;)e.push(n),n=v(),n===null&&(t.charCodeAt(i)===45?(n=`-`,i++):(n=null,a===0&&c(`"-"`)),n===null&&(t.charCodeAt(i)===46?(n=`.`,i++):(n=null,a===0&&c(`"."`)),n===null&&(t.charCodeAt(i)===33?(n=`!`,i++):(n=null,a===0&&c(`"!"`)),n===null&&(t.charCodeAt(i)===37?(n=`%`,i++):(n=null,a===0&&c(`"%"`)),n===null&&(t.charCodeAt(i)===42?(n=`*`,i++):(n=null,a===0&&c(`"*"`)),n===null&&(t.charCodeAt(i)===95?(n=`_`,i++):(n=null,a===0&&c(`"_"`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)),n===null&&(t.charCodeAt(i)===96?(n="`",i++):(n=null,a===0&&c('"`"')),n===null&&(t.charCodeAt(i)===39?(n=`'`,i++):(n=null,a===0&&c(`"'"`)),n===null&&(t.charCodeAt(i)===126?(n=`~`,i++):(n=null,a===0&&c(`"~"`))))))))))));else e=null;return e!==null&&(e=(function(e){return t.substring(i,e)})(r)),e===null&&(i=r),e}function re(){var e,n,r=i;if(n=v(),n===null&&(t.charCodeAt(i)===45?(n=`-`,i++):(n=null,a===0&&c(`"-"`)),n===null&&(t.charCodeAt(i)===33?(n=`!`,i++):(n=null,a===0&&c(`"!"`)),n===null&&(t.charCodeAt(i)===37?(n=`%`,i++):(n=null,a===0&&c(`"%"`)),n===null&&(t.charCodeAt(i)===42?(n=`*`,i++):(n=null,a===0&&c(`"*"`)),n===null&&(t.charCodeAt(i)===95?(n=`_`,i++):(n=null,a===0&&c(`"_"`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)),n===null&&(t.charCodeAt(i)===96?(n="`",i++):(n=null,a===0&&c('"`"')),n===null&&(t.charCodeAt(i)===39?(n=`'`,i++):(n=null,a===0&&c(`"'"`)),n===null&&(t.charCodeAt(i)===126?(n=`~`,i++):(n=null,a===0&&c(`"~"`))))))))))),n!==null)for(e=[];n!==null;)e.push(n),n=v(),n===null&&(t.charCodeAt(i)===45?(n=`-`,i++):(n=null,a===0&&c(`"-"`)),n===null&&(t.charCodeAt(i)===33?(n=`!`,i++):(n=null,a===0&&c(`"!"`)),n===null&&(t.charCodeAt(i)===37?(n=`%`,i++):(n=null,a===0&&c(`"%"`)),n===null&&(t.charCodeAt(i)===42?(n=`*`,i++):(n=null,a===0&&c(`"*"`)),n===null&&(t.charCodeAt(i)===95?(n=`_`,i++):(n=null,a===0&&c(`"_"`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)),n===null&&(t.charCodeAt(i)===96?(n="`",i++):(n=null,a===0&&c('"`"')),n===null&&(t.charCodeAt(i)===39?(n=`'`,i++):(n=null,a===0&&c(`"'"`)),n===null&&(t.charCodeAt(i)===126?(n=`~`,i++):(n=null,a===0&&c(`"~"`)))))))))));else e=null;return e!==null&&(e=(function(e){return t.substring(i,e)})(r)),e===null&&(i=r),e}function ie(){var e;return t.charCodeAt(i)===40?(e=`(`,i++):(e=null,a===0&&c(`"("`)),e===null&&(t.charCodeAt(i)===41?(e=`)`,i++):(e=null,a===0&&c(`")"`)),e===null&&(t.charCodeAt(i)===60?(e=`<`,i++):(e=null,a===0&&c(`"<"`)),e===null&&(t.charCodeAt(i)===62?(e=`>`,i++):(e=null,a===0&&c(`">"`)),e===null&&(t.charCodeAt(i)===64?(e=`@`,i++):(e=null,a===0&&c(`"@"`)),e===null&&(t.charCodeAt(i)===44?(e=`,`,i++):(e=null,a===0&&c(`","`)),e===null&&(t.charCodeAt(i)===59?(e=`;`,i++):(e=null,a===0&&c(`";"`)),e===null&&(t.charCodeAt(i)===58?(e=`:`,i++):(e=null,a===0&&c(`":"`)),e===null&&(t.charCodeAt(i)===92?(e=`\\`,i++):(e=null,a===0&&c(`"\\\\"`)),e===null&&(e=h(),e===null&&(t.charCodeAt(i)===47?(e=`/`,i++):(e=null,a===0&&c(`"/"`)),e===null&&(t.charCodeAt(i)===91?(e=`[`,i++):(e=null,a===0&&c(`"["`)),e===null&&(t.charCodeAt(i)===93?(e=`]`,i++):(e=null,a===0&&c(`"]"`)),e===null&&(t.charCodeAt(i)===63?(e=`?`,i++):(e=null,a===0&&c(`"?"`)),e===null&&(t.charCodeAt(i)===61?(e=`=`,i++):(e=null,a===0&&c(`"="`)),e===null&&(t.charCodeAt(i)===123?(e=`{`,i++):(e=null,a===0&&c(`"{"`)),e===null&&(t.charCodeAt(i)===125?(e=`}`,i++):(e=null,a===0&&c(`"}"`)),e===null&&(e=g(),e===null&&(e=_())))))))))))))))))),e}function ae(){var e,n,r=i;if(n=v(),n===null&&(t.charCodeAt(i)===45?(n=`-`,i++):(n=null,a===0&&c(`"-"`)),n===null&&(t.charCodeAt(i)===46?(n=`.`,i++):(n=null,a===0&&c(`"."`)),n===null&&(t.charCodeAt(i)===33?(n=`!`,i++):(n=null,a===0&&c(`"!"`)),n===null&&(t.charCodeAt(i)===37?(n=`%`,i++):(n=null,a===0&&c(`"%"`)),n===null&&(t.charCodeAt(i)===42?(n=`*`,i++):(n=null,a===0&&c(`"*"`)),n===null&&(t.charCodeAt(i)===95?(n=`_`,i++):(n=null,a===0&&c(`"_"`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)),n===null&&(t.charCodeAt(i)===96?(n="`",i++):(n=null,a===0&&c('"`"')),n===null&&(t.charCodeAt(i)===39?(n=`'`,i++):(n=null,a===0&&c(`"'"`)),n===null&&(t.charCodeAt(i)===126?(n=`~`,i++):(n=null,a===0&&c(`"~"`)),n===null&&(t.charCodeAt(i)===40?(n=`(`,i++):(n=null,a===0&&c(`"("`)),n===null&&(t.charCodeAt(i)===41?(n=`)`,i++):(n=null,a===0&&c(`")"`)),n===null&&(t.charCodeAt(i)===60?(n=`<`,i++):(n=null,a===0&&c(`"<"`)),n===null&&(t.charCodeAt(i)===62?(n=`>`,i++):(n=null,a===0&&c(`">"`)),n===null&&(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null&&(t.charCodeAt(i)===92?(n=`\\`,i++):(n=null,a===0&&c(`"\\\\"`)),n===null&&(n=h(),n===null&&(t.charCodeAt(i)===47?(n=`/`,i++):(n=null,a===0&&c(`"/"`)),n===null&&(t.charCodeAt(i)===91?(n=`[`,i++):(n=null,a===0&&c(`"["`)),n===null&&(t.charCodeAt(i)===93?(n=`]`,i++):(n=null,a===0&&c(`"]"`)),n===null&&(t.charCodeAt(i)===63?(n=`?`,i++):(n=null,a===0&&c(`"?"`)),n===null&&(t.charCodeAt(i)===123?(n=`{`,i++):(n=null,a===0&&c(`"{"`)),n===null&&(t.charCodeAt(i)===125?(n=`}`,i++):(n=null,a===0&&c(`"}"`))))))))))))))))))))))))),n!==null)for(e=[];n!==null;)e.push(n),n=v(),n===null&&(t.charCodeAt(i)===45?(n=`-`,i++):(n=null,a===0&&c(`"-"`)),n===null&&(t.charCodeAt(i)===46?(n=`.`,i++):(n=null,a===0&&c(`"."`)),n===null&&(t.charCodeAt(i)===33?(n=`!`,i++):(n=null,a===0&&c(`"!"`)),n===null&&(t.charCodeAt(i)===37?(n=`%`,i++):(n=null,a===0&&c(`"%"`)),n===null&&(t.charCodeAt(i)===42?(n=`*`,i++):(n=null,a===0&&c(`"*"`)),n===null&&(t.charCodeAt(i)===95?(n=`_`,i++):(n=null,a===0&&c(`"_"`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)),n===null&&(t.charCodeAt(i)===96?(n="`",i++):(n=null,a===0&&c('"`"')),n===null&&(t.charCodeAt(i)===39?(n=`'`,i++):(n=null,a===0&&c(`"'"`)),n===null&&(t.charCodeAt(i)===126?(n=`~`,i++):(n=null,a===0&&c(`"~"`)),n===null&&(t.charCodeAt(i)===40?(n=`(`,i++):(n=null,a===0&&c(`"("`)),n===null&&(t.charCodeAt(i)===41?(n=`)`,i++):(n=null,a===0&&c(`")"`)),n===null&&(t.charCodeAt(i)===60?(n=`<`,i++):(n=null,a===0&&c(`"<"`)),n===null&&(t.charCodeAt(i)===62?(n=`>`,i++):(n=null,a===0&&c(`">"`)),n===null&&(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null&&(t.charCodeAt(i)===92?(n=`\\`,i++):(n=null,a===0&&c(`"\\\\"`)),n===null&&(n=h(),n===null&&(t.charCodeAt(i)===47?(n=`/`,i++):(n=null,a===0&&c(`"/"`)),n===null&&(t.charCodeAt(i)===91?(n=`[`,i++):(n=null,a===0&&c(`"["`)),n===null&&(t.charCodeAt(i)===93?(n=`]`,i++):(n=null,a===0&&c(`"]"`)),n===null&&(t.charCodeAt(i)===63?(n=`?`,i++):(n=null,a===0&&c(`"?"`)),n===null&&(t.charCodeAt(i)===123?(n=`{`,i++):(n=null,a===0&&c(`"{"`)),n===null&&(t.charCodeAt(i)===125?(n=`}`,i++):(n=null,a===0&&c(`"}"`)))))))))))))))))))))))));else e=null;return e!==null&&(e=(function(e){return t.substring(i,e)})(r)),e===null&&(i=r),e}function oe(){var e,n,r,o=i,s=i;return e=w(),e===null?(e=null,i=s):(t.charCodeAt(i)===42?(n=`*`,i++):(n=null,a===0&&c(`"*"`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e){return`*`})(o)),e===null&&(i=o),e}function se(){var e,n,r,o=i,s=i;return e=w(),e===null?(e=null,i=s):(t.charCodeAt(i)===47?(n=`/`,i++):(n=null,a===0&&c(`"/"`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e){return`/`})(o)),e===null&&(i=o),e}function k(){var e,n,r,o=i,s=i;return e=w(),e===null?(e=null,i=s):(t.charCodeAt(i)===61?(n=`=`,i++):(n=null,a===0&&c(`"="`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e){return`=`})(o)),e===null&&(i=o),e}function ce(){var e,n,r,o=i,s=i;return e=w(),e===null?(e=null,i=s):(t.charCodeAt(i)===40?(n=`(`,i++):(n=null,a===0&&c(`"("`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e){return`(`})(o)),e===null&&(i=o),e}function le(){var e,n,r,o=i,s=i;return e=w(),e===null?(e=null,i=s):(t.charCodeAt(i)===41?(n=`)`,i++):(n=null,a===0&&c(`")"`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e){return`)`})(o)),e===null&&(i=o),e}function ue(){var e,n,r=i,o=i;return t.charCodeAt(i)===62?(e=`>`,i++):(e=null,a===0&&c(`">"`)),e===null?(e=null,i=o):(n=w(),n===null?(e=null,i=o):e=[e,n]),e!==null&&(e=(function(e){return`>`})(r)),e===null&&(i=r),e}function de(){var e,n,r=i,o=i;return e=w(),e===null?(e=null,i=o):(t.charCodeAt(i)===60?(n=`<`,i++):(n=null,a===0&&c(`"<"`)),n===null?(e=null,i=o):e=[e,n]),e!==null&&(e=(function(e){return`<`})(r)),e===null&&(i=r),e}function A(){var e,n,r,o=i,s=i;return e=w(),e===null?(e=null,i=s):(t.charCodeAt(i)===44?(n=`,`,i++):(n=null,a===0&&c(`","`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e){return`,`})(o)),e===null&&(i=o),e}function j(){var e,n,r,o=i,s=i;return e=w(),e===null?(e=null,i=s):(t.charCodeAt(i)===59?(n=`;`,i++):(n=null,a===0&&c(`";"`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e){return`;`})(o)),e===null&&(i=o),e}function fe(){var e,n,r,o=i,s=i;return e=w(),e===null?(e=null,i=s):(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(e=null,i=s):(r=w(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e){return`:`})(o)),e===null&&(i=o),e}function pe(){var e,t,n=i,r=i;return e=w(),e===null?(e=null,i=r):(t=h(),t===null?(e=null,i=r):e=[e,t]),e!==null&&(e=(function(e){return`"`})(n)),e===null&&(i=n),e}function me(){var e,t,n=i,r=i;return e=h(),e===null?(e=null,i=r):(t=w(),t===null?(e=null,i=r):e=[e,t]),e!==null&&(e=(function(e){return`"`})(n)),e===null&&(i=n),e}function he(){var e,t,n,r=i;if(e=ce(),e!==null){for(t=[],n=ge(),n===null&&(n=ve(),n===null&&(n=he()));n!==null;)t.push(n),n=ge(),n===null&&(n=ve(),n===null&&(n=he()));t===null?(e=null,i=r):(n=le(),n===null?(e=null,i=r):e=[e,t,n])}else e=null,i=r;return e}function ge(){var e;return/^[!-']/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[!-']`)),e===null&&(/^[*-[]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[*-[]`)),e===null&&(/^[\]-~]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[\\]-~]`)),e===null&&(e=D(),e===null&&(e=C())))),e}function _e(){var e,n,r,a,o=i,s=i;if(e=w(),e!==null){if(n=h(),n!==null){for(r=[],a=N(),a===null&&(a=ve());a!==null;)r.push(a),a=N(),a===null&&(a=ve());r===null?(e=null,i=s):(a=h(),a===null?(e=null,i=s):e=[e,n,r,a])}else e=null,i=s}else e=null,i=s;return e!==null&&(e=(function(e){return t.substring(i,e)})(o)),e===null&&(i=o),e}function M(){var e,n,r,a,o=i,s=i;if(e=w(),e!==null){if(n=h(),n!==null){for(r=[],a=N(),a===null&&(a=ve());a!==null;)r.push(a),a=N(),a===null&&(a=ve());r===null?(e=null,i=s):(a=h(),a===null?(e=null,i=s):e=[e,n,r,a])}else e=null,i=s}else e=null,i=s;return e!==null&&(e=(function(e){var n=t.substring(i,e).trim();return n.substring(1,n.length-1).replace(/\\([\x00-\x09\x0b-\x0c\x0e-\x7f])/g,`$1`)})(o)),e===null&&(i=o),e}function N(){var e=C();return e===null&&(t.charCodeAt(i)===33?(e=`!`,i++):(e=null,a===0&&c(`"!"`)),e===null&&(/^[#-[]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[#-[]`)),e===null&&(/^[\]-~]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[\\]-~]`)),e===null&&(e=D())))),e}function ve(){var e,n,r=i;return t.charCodeAt(i)===92?(e=`\\`,i++):(e=null,a===0&&c(`"\\\\"`)),e===null?(e=null,i=r):(/^[\0-\t]/.test(t.charAt(i))?(n=t.charAt(i),i++):(n=null,a===0&&c(`[\\0-\\t]`)),n===null&&(/^[\x0B-\f]/.test(t.charAt(i))?(n=t.charAt(i),i++):(n=null,a===0&&c(`[\\x0B-\\f]`)),n===null&&(/^[\x0E-]/.test(t.charAt(i))?(n=t.charAt(i),i++):(n=null,a===0&&c(`[\\x0E-]`)))),n===null?(e=null,i=r):e=[e,n]),e}function ye(){var e,n,r,o,s=i,l=i;return e=xe(),e===null?(e=null,i=l):(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(e=null,i=l):(r=we(),r=r===null?``:r,r===null?(e=null,i=l):(o=Oe(),o===null?(e=null,i=l):e=[e,n,r,o]))),e!==null&&(e=(function(e){try{$.uri=new Tr($.scheme,$.user,$.host,$.port),delete $.scheme,delete $.user,delete $.host,delete $.host_type,delete $.port}catch{$=-1}})(s)),e===null&&(i=s),e}function be(){var e,r,o,s,l,u,d=i,f=i;return e=xe(),e===null?(e=null,i=f):(t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(e=null,i=f):(o=we(),o=o===null?``:o,o===null?(e=null,i=f):(s=Oe(),s===null?(e=null,i=f):(l=Le(),l===null?(e=null,i=f):(u=Xe(),u=u===null?``:u,u===null?(e=null,i=f):e=[e,r,o,s,l,u]))))),e!==null&&(e=(function(e){try{$.uri=new Tr($.scheme,$.user,$.host,$.port,$.uri_params,$.uri_headers),delete $.scheme,delete $.user,delete $.host,delete $.host_type,delete $.port,delete $.uri_params,n===`SIP_URI`&&($=$.uri)}catch{$=-1}})(d)),e===null&&(i=d),e}function xe(){var e=Se();return e===null&&(e=Ce()),e}function Se(){var e,n=i;return t.substr(i,4).toLowerCase()===`sips`?(e=t.substr(i,4),i+=4):(e=null,a===0&&c(`"sips"`)),e!==null&&(e=(function(e,t){$.scheme=t.toLowerCase()})(n,e)),e===null&&(i=n),e}function Ce(){var e,n=i;return t.substr(i,3).toLowerCase()===`sip`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"sip"`)),e!==null&&(e=(function(e,t){$.scheme=t.toLowerCase()})(n,e)),e===null&&(i=n),e}function we(){var e,n,r,o=i,s=i,l;return e=Te(),e===null?(e=null,i=s):(l=i,t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(n=null,i=l):(r=De(),r===null?(n=null,i=l):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=s):(t.charCodeAt(i)===64?(r=`@`,i++):(r=null,a===0&&c(`"@"`)),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e){$.user=decodeURIComponent(t.substring(i-1,e))})(o)),e===null&&(i=o),e}function Te(){var e,t=b();if(t===null&&(t=S(),t===null&&(t=Ee())),t!==null)for(e=[];t!==null;)e.push(t),t=b(),t===null&&(t=S(),t===null&&(t=Ee()));else e=null;return e}function Ee(){var e;return t.charCodeAt(i)===38?(e=`&`,i++):(e=null,a===0&&c(`"&"`)),e===null&&(t.charCodeAt(i)===61?(e=`=`,i++):(e=null,a===0&&c(`"="`)),e===null&&(t.charCodeAt(i)===43?(e=`+`,i++):(e=null,a===0&&c(`"+"`)),e===null&&(t.charCodeAt(i)===36?(e=`$`,i++):(e=null,a===0&&c(`"$"`)),e===null&&(t.charCodeAt(i)===44?(e=`,`,i++):(e=null,a===0&&c(`","`)),e===null&&(t.charCodeAt(i)===59?(e=`;`,i++):(e=null,a===0&&c(`";"`)),e===null&&(t.charCodeAt(i)===63?(e=`?`,i++):(e=null,a===0&&c(`"?"`)),e===null&&(t.charCodeAt(i)===47?(e=`/`,i++):(e=null,a===0&&c(`"/"`))))))))),e}function De(){var e,n,r=i;for(e=[],n=b(),n===null&&(n=S(),n===null&&(t.charCodeAt(i)===38?(n=`&`,i++):(n=null,a===0&&c(`"&"`)),n===null&&(t.charCodeAt(i)===61?(n=`=`,i++):(n=null,a===0&&c(`"="`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)),n===null&&(t.charCodeAt(i)===36?(n=`$`,i++):(n=null,a===0&&c(`"$"`)),n===null&&(t.charCodeAt(i)===44?(n=`,`,i++):(n=null,a===0&&c(`","`))))))));n!==null;)e.push(n),n=b(),n===null&&(n=S(),n===null&&(t.charCodeAt(i)===38?(n=`&`,i++):(n=null,a===0&&c(`"&"`)),n===null&&(t.charCodeAt(i)===61?(n=`=`,i++):(n=null,a===0&&c(`"="`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)),n===null&&(t.charCodeAt(i)===36?(n=`$`,i++):(n=null,a===0&&c(`"$"`)),n===null&&(t.charCodeAt(i)===44?(n=`,`,i++):(n=null,a===0&&c(`","`))))))));return e!==null&&(e=(function(e){$.password=t.substring(i,e)})(r)),e===null&&(i=r),e}function Oe(){var e,n,r,o=i,s;return e=ke(),e===null?(e=null,i=o):(s=i,t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(n=null,i=s):(r=Ie(),r===null?(n=null,i=s):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=o):e=[e,n]),e}function ke(){var e,n=i;return e=Ae(),e===null&&(e=Pe(),e===null&&(e=Me())),e!==null&&(e=(function(e){return $.host=t.substring(i,e).toLowerCase(),$.host})(n)),e===null&&(i=n),e}function Ae(){var e,n,r,o=i,s=i,l;for(e=[],l=i,n=je(),n===null?(n=null,i=l):(t.charCodeAt(i)===46?(r=`.`,i++):(r=null,a===0&&c(`"."`)),r===null?(n=null,i=l):n=[n,r]);n!==null;)e.push(n),l=i,n=je(),n===null?(n=null,i=l):(t.charCodeAt(i)===46?(r=`.`,i++):(r=null,a===0&&c(`"."`)),r===null?(n=null,i=l):n=[n,r]);return e===null?(e=null,i=s):(n=P(),n===null?(e=null,i=s):(t.charCodeAt(i)===46?(r=`.`,i++):(r=null,a===0&&c(`"."`)),r=r===null?``:r,r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e){return $.host_type=`domain`,t.substring(i,e)})(o)),e===null&&(i=o),e}function je(){var e,n,r,o=i;if(e=v(),e!==null){for(n=[],r=v(),r===null&&(t.charCodeAt(i)===45?(r=`-`,i++):(r=null,a===0&&c(`"-"`)),r===null&&(t.charCodeAt(i)===95?(r=`_`,i++):(r=null,a===0&&c(`"_"`))));r!==null;)n.push(r),r=v(),r===null&&(t.charCodeAt(i)===45?(r=`-`,i++):(r=null,a===0&&c(`"-"`)),r===null&&(t.charCodeAt(i)===95?(r=`_`,i++):(r=null,a===0&&c(`"_"`))));n===null?(e=null,i=o):e=[e,n]}else e=null,i=o;return e}function P(){var e,n,r,o=i;if(e=d(),e!==null){for(n=[],r=v(),r===null&&(t.charCodeAt(i)===45?(r=`-`,i++):(r=null,a===0&&c(`"-"`)),r===null&&(t.charCodeAt(i)===95?(r=`_`,i++):(r=null,a===0&&c(`"_"`))));r!==null;)n.push(r),r=v(),r===null&&(t.charCodeAt(i)===45?(r=`-`,i++):(r=null,a===0&&c(`"-"`)),r===null&&(t.charCodeAt(i)===95?(r=`_`,i++):(r=null,a===0&&c(`"_"`))));n===null?(e=null,i=o):e=[e,n]}else e=null,i=o;return e}function Me(){var e,n,r,o=i,s=i;return t.charCodeAt(i)===91?(e=`[`,i++):(e=null,a===0&&c(`"["`)),e===null?(e=null,i=s):(n=Ne(),n===null?(e=null,i=s):(t.charCodeAt(i)===93?(r=`]`,i++):(r=null,a===0&&c(`"]"`)),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e){return $.host_type=`IPv6`,t.substring(i,e)})(o)),e===null&&(i=o),e}function Ne(){var e,n,r,o,s,l,u,d,f,p,m,h,g,_=i,v=i,y;return e=F(),e===null?(e=null,i=v):(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(e=null,i=v):(r=F(),r===null?(e=null,i=v):(t.charCodeAt(i)===58?(o=`:`,i++):(o=null,a===0&&c(`":"`)),o===null?(e=null,i=v):(s=F(),s===null?(e=null,i=v):(t.charCodeAt(i)===58?(l=`:`,i++):(l=null,a===0&&c(`":"`)),l===null?(e=null,i=v):(u=F(),u===null?(e=null,i=v):(t.charCodeAt(i)===58?(d=`:`,i++):(d=null,a===0&&c(`":"`)),d===null?(e=null,i=v):(f=F(),f===null?(e=null,i=v):(t.charCodeAt(i)===58?(p=`:`,i++):(p=null,a===0&&c(`":"`)),p===null?(e=null,i=v):(m=F(),m===null?(e=null,i=v):(t.charCodeAt(i)===58?(h=`:`,i++):(h=null,a===0&&c(`":"`)),h===null?(e=null,i=v):(g=I(),g===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d,f,p,m,h,g])))))))))))),e===null&&(v=i,t.substr(i,2)===`::`?(e=`::`,i+=2):(e=null,a===0&&c(`"::"`)),e===null?(e=null,i=v):(n=F(),n===null?(e=null,i=v):(t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(e=null,i=v):(o=F(),o===null?(e=null,i=v):(t.charCodeAt(i)===58?(s=`:`,i++):(s=null,a===0&&c(`":"`)),s===null?(e=null,i=v):(l=F(),l===null?(e=null,i=v):(t.charCodeAt(i)===58?(u=`:`,i++):(u=null,a===0&&c(`":"`)),u===null?(e=null,i=v):(d=F(),d===null?(e=null,i=v):(t.charCodeAt(i)===58?(f=`:`,i++):(f=null,a===0&&c(`":"`)),f===null?(e=null,i=v):(p=F(),p===null?(e=null,i=v):(t.charCodeAt(i)===58?(m=`:`,i++):(m=null,a===0&&c(`":"`)),m===null?(e=null,i=v):(h=I(),h===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d,f,p,m,h]))))))))))),e===null&&(v=i,t.substr(i,2)===`::`?(e=`::`,i+=2):(e=null,a===0&&c(`"::"`)),e===null?(e=null,i=v):(n=F(),n===null?(e=null,i=v):(t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(e=null,i=v):(o=F(),o===null?(e=null,i=v):(t.charCodeAt(i)===58?(s=`:`,i++):(s=null,a===0&&c(`":"`)),s===null?(e=null,i=v):(l=F(),l===null?(e=null,i=v):(t.charCodeAt(i)===58?(u=`:`,i++):(u=null,a===0&&c(`":"`)),u===null?(e=null,i=v):(d=F(),d===null?(e=null,i=v):(t.charCodeAt(i)===58?(f=`:`,i++):(f=null,a===0&&c(`":"`)),f===null?(e=null,i=v):(p=I(),p===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d,f,p]))))))))),e===null&&(v=i,t.substr(i,2)===`::`?(e=`::`,i+=2):(e=null,a===0&&c(`"::"`)),e===null?(e=null,i=v):(n=F(),n===null?(e=null,i=v):(t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(e=null,i=v):(o=F(),o===null?(e=null,i=v):(t.charCodeAt(i)===58?(s=`:`,i++):(s=null,a===0&&c(`":"`)),s===null?(e=null,i=v):(l=F(),l===null?(e=null,i=v):(t.charCodeAt(i)===58?(u=`:`,i++):(u=null,a===0&&c(`":"`)),u===null?(e=null,i=v):(d=I(),d===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d]))))))),e===null&&(v=i,t.substr(i,2)===`::`?(e=`::`,i+=2):(e=null,a===0&&c(`"::"`)),e===null?(e=null,i=v):(n=F(),n===null?(e=null,i=v):(t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(e=null,i=v):(o=F(),o===null?(e=null,i=v):(t.charCodeAt(i)===58?(s=`:`,i++):(s=null,a===0&&c(`":"`)),s===null?(e=null,i=v):(l=I(),l===null?(e=null,i=v):e=[e,n,r,o,s,l]))))),e===null&&(v=i,t.substr(i,2)===`::`?(e=`::`,i+=2):(e=null,a===0&&c(`"::"`)),e===null?(e=null,i=v):(n=F(),n===null?(e=null,i=v):(t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(e=null,i=v):(o=I(),o===null?(e=null,i=v):e=[e,n,r,o]))),e===null&&(v=i,t.substr(i,2)===`::`?(e=`::`,i+=2):(e=null,a===0&&c(`"::"`)),e===null?(e=null,i=v):(n=I(),n===null?(e=null,i=v):e=[e,n]),e===null&&(v=i,t.substr(i,2)===`::`?(e=`::`,i+=2):(e=null,a===0&&c(`"::"`)),e===null?(e=null,i=v):(n=F(),n===null?(e=null,i=v):e=[e,n]),e===null&&(v=i,e=F(),e===null?(e=null,i=v):(t.substr(i,2)===`::`?(n=`::`,i+=2):(n=null,a===0&&c(`"::"`)),n===null?(e=null,i=v):(r=F(),r===null?(e=null,i=v):(t.charCodeAt(i)===58?(o=`:`,i++):(o=null,a===0&&c(`":"`)),o===null?(e=null,i=v):(s=F(),s===null?(e=null,i=v):(t.charCodeAt(i)===58?(l=`:`,i++):(l=null,a===0&&c(`":"`)),l===null?(e=null,i=v):(u=F(),u===null?(e=null,i=v):(t.charCodeAt(i)===58?(d=`:`,i++):(d=null,a===0&&c(`":"`)),d===null?(e=null,i=v):(f=F(),f===null?(e=null,i=v):(t.charCodeAt(i)===58?(p=`:`,i++):(p=null,a===0&&c(`":"`)),p===null?(e=null,i=v):(m=I(),m===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d,f,p,m])))))))))),e===null&&(v=i,e=F(),e===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(n=null,i=y):(r=F(),r===null?(n=null,i=y):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=v):(t.substr(i,2)===`::`?(r=`::`,i+=2):(r=null,a===0&&c(`"::"`)),r===null?(e=null,i=v):(o=F(),o===null?(e=null,i=v):(t.charCodeAt(i)===58?(s=`:`,i++):(s=null,a===0&&c(`":"`)),s===null?(e=null,i=v):(l=F(),l===null?(e=null,i=v):(t.charCodeAt(i)===58?(u=`:`,i++):(u=null,a===0&&c(`":"`)),u===null?(e=null,i=v):(d=F(),d===null?(e=null,i=v):(t.charCodeAt(i)===58?(f=`:`,i++):(f=null,a===0&&c(`":"`)),f===null?(e=null,i=v):(p=I(),p===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d,f,p]))))))))),e===null&&(v=i,e=F(),e===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(n=null,i=y):(r=F(),r===null?(n=null,i=y):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(r=null,i=y):(o=F(),o===null?(r=null,i=y):r=[r,o]),r=r===null?``:r,r===null?(e=null,i=v):(t.substr(i,2)===`::`?(o=`::`,i+=2):(o=null,a===0&&c(`"::"`)),o===null?(e=null,i=v):(s=F(),s===null?(e=null,i=v):(t.charCodeAt(i)===58?(l=`:`,i++):(l=null,a===0&&c(`":"`)),l===null?(e=null,i=v):(u=F(),u===null?(e=null,i=v):(t.charCodeAt(i)===58?(d=`:`,i++):(d=null,a===0&&c(`":"`)),d===null?(e=null,i=v):(f=I(),f===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d,f])))))))),e===null&&(v=i,e=F(),e===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(n=null,i=y):(r=F(),r===null?(n=null,i=y):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(r=null,i=y):(o=F(),o===null?(r=null,i=y):r=[r,o]),r=r===null?``:r,r===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(o=`:`,i++):(o=null,a===0&&c(`":"`)),o===null?(o=null,i=y):(s=F(),s===null?(o=null,i=y):o=[o,s]),o=o===null?``:o,o===null?(e=null,i=v):(t.substr(i,2)===`::`?(s=`::`,i+=2):(s=null,a===0&&c(`"::"`)),s===null?(e=null,i=v):(l=F(),l===null?(e=null,i=v):(t.charCodeAt(i)===58?(u=`:`,i++):(u=null,a===0&&c(`":"`)),u===null?(e=null,i=v):(d=I(),d===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d]))))))),e===null&&(v=i,e=F(),e===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(n=null,i=y):(r=F(),r===null?(n=null,i=y):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(r=null,i=y):(o=F(),o===null?(r=null,i=y):r=[r,o]),r=r===null?``:r,r===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(o=`:`,i++):(o=null,a===0&&c(`":"`)),o===null?(o=null,i=y):(s=F(),s===null?(o=null,i=y):o=[o,s]),o=o===null?``:o,o===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(s=`:`,i++):(s=null,a===0&&c(`":"`)),s===null?(s=null,i=y):(l=F(),l===null?(s=null,i=y):s=[s,l]),s=s===null?``:s,s===null?(e=null,i=v):(t.substr(i,2)===`::`?(l=`::`,i+=2):(l=null,a===0&&c(`"::"`)),l===null?(e=null,i=v):(u=I(),u===null?(e=null,i=v):e=[e,n,r,o,s,l,u])))))),e===null&&(v=i,e=F(),e===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(n=null,i=y):(r=F(),r===null?(n=null,i=y):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(r=null,i=y):(o=F(),o===null?(r=null,i=y):r=[r,o]),r=r===null?``:r,r===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(o=`:`,i++):(o=null,a===0&&c(`":"`)),o===null?(o=null,i=y):(s=F(),s===null?(o=null,i=y):o=[o,s]),o=o===null?``:o,o===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(s=`:`,i++):(s=null,a===0&&c(`":"`)),s===null?(s=null,i=y):(l=F(),l===null?(s=null,i=y):s=[s,l]),s=s===null?``:s,s===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(l=`:`,i++):(l=null,a===0&&c(`":"`)),l===null?(l=null,i=y):(u=F(),u===null?(l=null,i=y):l=[l,u]),l=l===null?``:l,l===null?(e=null,i=v):(t.substr(i,2)===`::`?(u=`::`,i+=2):(u=null,a===0&&c(`"::"`)),u===null?(e=null,i=v):(d=F(),d===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d]))))))),e===null&&(v=i,e=F(),e===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(n=null,i=y):(r=F(),r===null?(n=null,i=y):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(r=`:`,i++):(r=null,a===0&&c(`":"`)),r===null?(r=null,i=y):(o=F(),o===null?(r=null,i=y):r=[r,o]),r=r===null?``:r,r===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(o=`:`,i++):(o=null,a===0&&c(`":"`)),o===null?(o=null,i=y):(s=F(),s===null?(o=null,i=y):o=[o,s]),o=o===null?``:o,o===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(s=`:`,i++):(s=null,a===0&&c(`":"`)),s===null?(s=null,i=y):(l=F(),l===null?(s=null,i=y):s=[s,l]),s=s===null?``:s,s===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(l=`:`,i++):(l=null,a===0&&c(`":"`)),l===null?(l=null,i=y):(u=F(),u===null?(l=null,i=y):l=[l,u]),l=l===null?``:l,l===null?(e=null,i=v):(y=i,t.charCodeAt(i)===58?(u=`:`,i++):(u=null,a===0&&c(`":"`)),u===null?(u=null,i=y):(d=F(),d===null?(u=null,i=y):u=[u,d]),u=u===null?``:u,u===null?(e=null,i=v):(t.substr(i,2)===`::`?(d=`::`,i+=2):(d=null,a===0&&c(`"::"`)),d===null?(e=null,i=v):e=[e,n,r,o,s,l,u,d]))))))))))))))))))))),e!==null&&(e=(function(e){return $.host_type=`IPv6`,t.substring(i,e)})(_)),e===null&&(i=_),e}function F(){var e,t,n,r,a=i;return e=f(),e===null?(e=null,i=a):(t=f(),t=t===null?``:t,t===null?(e=null,i=a):(n=f(),n=n===null?``:n,n===null?(e=null,i=a):(r=f(),r=r===null?``:r,r===null?(e=null,i=a):e=[e,t,n,r]))),e}function I(){var e,n,r,o=i;return e=F(),e===null?(e=null,i=o):(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(e=null,i=o):(r=F(),r===null?(e=null,i=o):e=[e,n,r])),e===null&&(e=Pe()),e}function Pe(){var e,n,r,o,s,l,u,d=i,f=i;return e=Fe(),e===null?(e=null,i=f):(t.charCodeAt(i)===46?(n=`.`,i++):(n=null,a===0&&c(`"."`)),n===null?(e=null,i=f):(r=Fe(),r===null?(e=null,i=f):(t.charCodeAt(i)===46?(o=`.`,i++):(o=null,a===0&&c(`"."`)),o===null?(e=null,i=f):(s=Fe(),s===null?(e=null,i=f):(t.charCodeAt(i)===46?(l=`.`,i++):(l=null,a===0&&c(`"."`)),l===null?(e=null,i=f):(u=Fe(),u===null?(e=null,i=f):e=[e,n,r,o,s,l,u])))))),e!==null&&(e=(function(e){return $.host_type=`IPv4`,t.substring(i,e)})(d)),e===null&&(i=d),e}function Fe(){var e,n,r,o=i;return t.substr(i,2)===`25`?(e=`25`,i+=2):(e=null,a===0&&c(`"25"`)),e===null?(e=null,i=o):(/^[0-5]/.test(t.charAt(i))?(n=t.charAt(i),i++):(n=null,a===0&&c(`[0-5]`)),n===null?(e=null,i=o):e=[e,n]),e===null&&(o=i,t.charCodeAt(i)===50?(e=`2`,i++):(e=null,a===0&&c(`"2"`)),e===null?(e=null,i=o):(/^[0-4]/.test(t.charAt(i))?(n=t.charAt(i),i++):(n=null,a===0&&c(`[0-4]`)),n===null?(e=null,i=o):(r=u(),r===null?(e=null,i=o):e=[e,n,r])),e===null&&(o=i,t.charCodeAt(i)===49?(e=`1`,i++):(e=null,a===0&&c(`"1"`)),e===null?(e=null,i=o):(n=u(),n===null?(e=null,i=o):(r=u(),r===null?(e=null,i=o):e=[e,n,r])),e===null&&(o=i,/^[1-9]/.test(t.charAt(i))?(e=t.charAt(i),i++):(e=null,a===0&&c(`[1-9]`)),e===null?(e=null,i=o):(n=u(),n===null?(e=null,i=o):e=[e,n]),e===null&&(e=u())))),e}function Ie(){var e,t,n,r,a,o=i,s=i;return e=u(),e=e===null?``:e,e===null?(e=null,i=s):(t=u(),t=t===null?``:t,t===null?(e=null,i=s):(n=u(),n=n===null?``:n,n===null?(e=null,i=s):(r=u(),r=r===null?``:r,r===null?(e=null,i=s):(a=u(),a=a===null?``:a,a===null?(e=null,i=s):e=[e,t,n,r,a])))),e!==null&&(e=(function(e,t){return t=parseInt(t.join(``)),$.port=t,t})(o,e)),e===null&&(i=o),e}function Le(){var e=[],n,r,o=i;for(t.charCodeAt(i)===59?(n=`;`,i++):(n=null,a===0&&c(`";"`)),n===null?(n=null,i=o):(r=Re(),r===null?(n=null,i=o):n=[n,r]);n!==null;)e.push(n),o=i,t.charCodeAt(i)===59?(n=`;`,i++):(n=null,a===0&&c(`";"`)),n===null?(n=null,i=o):(r=Re(),r===null?(n=null,i=o):n=[n,r]);return e}function Re(){var e=ze();return e===null&&(e=Be(),e===null&&(e=Ve(),e===null&&(e=He(),e===null&&(e=Ue(),e===null&&(e=We(),e===null&&(e=Ge())))))),e}function ze(){var e,n,r=i,o=i;return t.substr(i,10).toLowerCase()===`transport=`?(e=t.substr(i,10),i+=10):(e=null,a===0&&c(`"transport="`)),e===null?(e=null,i=o):(t.substr(i,3).toLowerCase()===`udp`?(n=t.substr(i,3),i+=3):(n=null,a===0&&c(`"udp"`)),n===null&&(t.substr(i,3).toLowerCase()===`tcp`?(n=t.substr(i,3),i+=3):(n=null,a===0&&c(`"tcp"`)),n===null&&(t.substr(i,4).toLowerCase()===`sctp`?(n=t.substr(i,4),i+=4):(n=null,a===0&&c(`"sctp"`)),n===null&&(t.substr(i,3).toLowerCase()===`tls`?(n=t.substr(i,3),i+=3):(n=null,a===0&&c(`"tls"`)),n===null&&(n=O())))),n===null?(e=null,i=o):e=[e,n]),e!==null&&(e=(function(e,t){$.uri_params||($.uri_params={}),$.uri_params.transport=t.toLowerCase()})(r,e[1])),e===null&&(i=r),e}function Be(){var e,n,r=i,o=i;return t.substr(i,5).toLowerCase()===`user=`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"user="`)),e===null?(e=null,i=o):(t.substr(i,5).toLowerCase()===`phone`?(n=t.substr(i,5),i+=5):(n=null,a===0&&c(`"phone"`)),n===null&&(t.substr(i,2).toLowerCase()===`ip`?(n=t.substr(i,2),i+=2):(n=null,a===0&&c(`"ip"`)),n===null&&(n=O())),n===null?(e=null,i=o):e=[e,n]),e!==null&&(e=(function(e,t){$.uri_params||($.uri_params={}),$.uri_params.user=t.toLowerCase()})(r,e[1])),e===null&&(i=r),e}function Ve(){var e,n,r=i,o=i;return t.substr(i,7).toLowerCase()===`method=`?(e=t.substr(i,7),i+=7):(e=null,a===0&&c(`"method="`)),e===null?(e=null,i=o):(n=Et(),n===null?(e=null,i=o):e=[e,n]),e!==null&&(e=(function(e,t){$.uri_params||($.uri_params={}),$.uri_params.method=t})(r,e[1])),e===null&&(i=r),e}function He(){var e,n,r=i,o=i;return t.substr(i,4).toLowerCase()===`ttl=`?(e=t.substr(i,4),i+=4):(e=null,a===0&&c(`"ttl="`)),e===null?(e=null,i=o):(n=ir(),n===null?(e=null,i=o):e=[e,n]),e!==null&&(e=(function(e,t){$.params||($.params={}),$.params.ttl=t})(r,e[1])),e===null&&(i=r),e}function Ue(){var e,n,r=i,o=i;return t.substr(i,6).toLowerCase()===`maddr=`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"maddr="`)),e===null?(e=null,i=o):(n=ke(),n===null?(e=null,i=o):e=[e,n]),e!==null&&(e=(function(e,t){$.uri_params||($.uri_params={}),$.uri_params.maddr=t})(r,e[1])),e===null&&(i=r),e}function We(){var e,n,r,o=i,s=i,l;return t.substr(i,2).toLowerCase()===`lr`?(e=t.substr(i,2),i+=2):(e=null,a===0&&c(`"lr"`)),e===null?(e=null,i=s):(l=i,t.charCodeAt(i)===61?(n=`=`,i++):(n=null,a===0&&c(`"="`)),n===null?(n=null,i=l):(r=O(),r===null?(n=null,i=l):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=s):e=[e,n]),e!==null&&(e=(function(e){$.uri_params||($.uri_params={}),$.uri_params.lr=void 0})(o)),e===null&&(i=o),e}function Ge(){var e,n,r,o=i,s=i,l;return e=Ke(),e===null?(e=null,i=s):(l=i,t.charCodeAt(i)===61?(n=`=`,i++):(n=null,a===0&&c(`"="`)),n===null?(n=null,i=l):(r=qe(),r===null?(n=null,i=l):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=s):e=[e,n]),e!==null&&(e=(function(e,t,n){$.uri_params||($.uri_params={}),n=n===void 0?void 0:n[1],$.uri_params[t.toLowerCase()]=n})(o,e[0],e[1])),e===null&&(i=o),e}function Ke(){var e,t,n=i;if(t=Je(),t!==null)for(e=[];t!==null;)e.push(t),t=Je();else e=null;return e!==null&&(e=(function(e,t){return t.join(``)})(n,e)),e===null&&(i=n),e}function qe(){var e,t,n=i;if(t=Je(),t!==null)for(e=[];t!==null;)e.push(t),t=Je();else e=null;return e!==null&&(e=(function(e,t){return t.join(``)})(n,e)),e===null&&(i=n),e}function Je(){var e=Ye();return e===null&&(e=b(),e===null&&(e=S())),e}function Ye(){var e;return t.charCodeAt(i)===91?(e=`[`,i++):(e=null,a===0&&c(`"["`)),e===null&&(t.charCodeAt(i)===93?(e=`]`,i++):(e=null,a===0&&c(`"]"`)),e===null&&(t.charCodeAt(i)===47?(e=`/`,i++):(e=null,a===0&&c(`"/"`)),e===null&&(t.charCodeAt(i)===58?(e=`:`,i++):(e=null,a===0&&c(`":"`)),e===null&&(t.charCodeAt(i)===38?(e=`&`,i++):(e=null,a===0&&c(`"&"`)),e===null&&(t.charCodeAt(i)===43?(e=`+`,i++):(e=null,a===0&&c(`"+"`)),e===null&&(t.charCodeAt(i)===36?(e=`$`,i++):(e=null,a===0&&c(`"$"`)))))))),e}function Xe(){var e,n,r,o,s,l=i,u;if(t.charCodeAt(i)===63?(e=`?`,i++):(e=null,a===0&&c(`"?"`)),e!==null){if(n=L(),n!==null){for(r=[],u=i,t.charCodeAt(i)===38?(o=`&`,i++):(o=null,a===0&&c(`"&"`)),o===null?(o=null,i=u):(s=L(),s===null?(o=null,i=u):o=[o,s]);o!==null;)r.push(o),u=i,t.charCodeAt(i)===38?(o=`&`,i++):(o=null,a===0&&c(`"&"`)),o===null?(o=null,i=u):(s=L(),s===null?(o=null,i=u):o=[o,s]);r===null?(e=null,i=l):e=[e,n,r]}else e=null,i=l}else e=null,i=l;return e}function L(){var e,n,r,o=i,s=i;return e=Ze(),e===null?(e=null,i=s):(t.charCodeAt(i)===61?(n=`=`,i++):(n=null,a===0&&c(`"="`)),n===null?(e=null,i=s):(r=Qe(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t,n){t=t.join(``).toLowerCase(),n=n.join(``),$.uri_headers||($.uri_headers={}),$.uri_headers[t]?$.uri_headers[t].push(n):$.uri_headers[t]=[n]})(o,e[0],e[2])),e===null&&(i=o),e}function Ze(){var e,t=$e();if(t===null&&(t=b(),t===null&&(t=S())),t!==null)for(e=[];t!==null;)e.push(t),t=$e(),t===null&&(t=b(),t===null&&(t=S()));else e=null;return e}function Qe(){var e=[],t=$e();for(t===null&&(t=b(),t===null&&(t=S()));t!==null;)e.push(t),t=$e(),t===null&&(t=b(),t===null&&(t=S()));return e}function $e(){var e;return t.charCodeAt(i)===91?(e=`[`,i++):(e=null,a===0&&c(`"["`)),e===null&&(t.charCodeAt(i)===93?(e=`]`,i++):(e=null,a===0&&c(`"]"`)),e===null&&(t.charCodeAt(i)===47?(e=`/`,i++):(e=null,a===0&&c(`"/"`)),e===null&&(t.charCodeAt(i)===63?(e=`?`,i++):(e=null,a===0&&c(`"?"`)),e===null&&(t.charCodeAt(i)===58?(e=`:`,i++):(e=null,a===0&&c(`":"`)),e===null&&(t.charCodeAt(i)===43?(e=`+`,i++):(e=null,a===0&&c(`"+"`)),e===null&&(t.charCodeAt(i)===36?(e=`$`,i++):(e=null,a===0&&c(`"$"`)))))))),e}function et(){var e=Dt();return e===null&&(e=R()),e}function R(){var e,t,n,r,a,o=i;return e=Et(),e===null?(e=null,i=o):(t=g(),t===null?(e=null,i=o):(n=tt(),n===null?(e=null,i=o):(r=g(),r===null?(e=null,i=o):(a=gt(),a===null?(e=null,i=o):e=[e,t,n,r,a])))),e}function tt(){var e=be();return e===null&&(e=nt()),e}function nt(){var e,n,r,o=i;return e=dt(),e===null?(e=null,i=o):(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null?(e=null,i=o):(r=rt(),r===null&&(r=it()),r===null?(e=null,i=o):e=[e,n,r])),e}function rt(){var e,n,r,o=i,s;return e=z(),e===null&&(e=B()),e===null?(e=null,i=o):(s=i,t.charCodeAt(i)===63?(n=`?`,i++):(n=null,a===0&&c(`"?"`)),n===null?(n=null,i=s):(r=ht(),r===null?(n=null,i=s):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=o):e=[e,n]),e}function z(){var e,n,r,o=i;return t.substr(i,2)===`//`?(e=`//`,i+=2):(e=null,a===0&&c(`"//"`)),e===null?(e=null,i=o):(n=ft(),n===null?(e=null,i=o):(r=B(),r=r===null?``:r,r===null?(e=null,i=o):e=[e,n,r])),e}function B(){var e,n,r=i;return t.charCodeAt(i)===47?(e=`/`,i++):(e=null,a===0&&c(`"/"`)),e===null?(e=null,i=r):(n=st(),n===null?(e=null,i=r):e=[e,n]),e}function it(){var e,t,n,r=i;if(e=ot(),e!==null){for(t=[],n=at();n!==null;)t.push(n),n=at();t===null?(e=null,i=r):e=[e,t]}else e=null,i=r;return e}function at(){var e=y();return e===null&&(e=b(),e===null&&(e=S())),e}function ot(){var e=b();return e===null&&(e=S(),e===null&&(t.charCodeAt(i)===59?(e=`;`,i++):(e=null,a===0&&c(`";"`)),e===null&&(t.charCodeAt(i)===63?(e=`?`,i++):(e=null,a===0&&c(`"?"`)),e===null&&(t.charCodeAt(i)===58?(e=`:`,i++):(e=null,a===0&&c(`":"`)),e===null&&(t.charCodeAt(i)===64?(e=`@`,i++):(e=null,a===0&&c(`"@"`)),e===null&&(t.charCodeAt(i)===38?(e=`&`,i++):(e=null,a===0&&c(`"&"`)),e===null&&(t.charCodeAt(i)===61?(e=`=`,i++):(e=null,a===0&&c(`"="`)),e===null&&(t.charCodeAt(i)===43?(e=`+`,i++):(e=null,a===0&&c(`"+"`)),e===null&&(t.charCodeAt(i)===36?(e=`$`,i++):(e=null,a===0&&c(`"$"`)),e===null&&(t.charCodeAt(i)===44?(e=`,`,i++):(e=null,a===0&&c(`","`)))))))))))),e}function st(){var e,n,r,o,s=i,l;if(e=ct(),e!==null){for(n=[],l=i,t.charCodeAt(i)===47?(r=`/`,i++):(r=null,a===0&&c(`"/"`)),r===null?(r=null,i=l):(o=ct(),o===null?(r=null,i=l):r=[r,o]);r!==null;)n.push(r),l=i,t.charCodeAt(i)===47?(r=`/`,i++):(r=null,a===0&&c(`"/"`)),r===null?(r=null,i=l):(o=ct(),o===null?(r=null,i=l):r=[r,o]);n===null?(e=null,i=s):e=[e,n]}else e=null,i=s;return e}function ct(){var e,n,r,o,s=i,l;for(e=[],n=ut();n!==null;)e.push(n),n=ut();if(e!==null){for(n=[],l=i,t.charCodeAt(i)===59?(r=`;`,i++):(r=null,a===0&&c(`";"`)),r===null?(r=null,i=l):(o=lt(),o===null?(r=null,i=l):r=[r,o]);r!==null;)n.push(r),l=i,t.charCodeAt(i)===59?(r=`;`,i++):(r=null,a===0&&c(`";"`)),r===null?(r=null,i=l):(o=lt(),o===null?(r=null,i=l):r=[r,o]);n===null?(e=null,i=s):e=[e,n]}else e=null,i=s;return e}function lt(){for(var e=[],t=ut();t!==null;)e.push(t),t=ut();return e}function ut(){var e=b();return e===null&&(e=S(),e===null&&(t.charCodeAt(i)===58?(e=`:`,i++):(e=null,a===0&&c(`":"`)),e===null&&(t.charCodeAt(i)===64?(e=`@`,i++):(e=null,a===0&&c(`"@"`)),e===null&&(t.charCodeAt(i)===38?(e=`&`,i++):(e=null,a===0&&c(`"&"`)),e===null&&(t.charCodeAt(i)===61?(e=`=`,i++):(e=null,a===0&&c(`"="`)),e===null&&(t.charCodeAt(i)===43?(e=`+`,i++):(e=null,a===0&&c(`"+"`)),e===null&&(t.charCodeAt(i)===36?(e=`$`,i++):(e=null,a===0&&c(`"$"`)),e===null&&(t.charCodeAt(i)===44?(e=`,`,i++):(e=null,a===0&&c(`","`)))))))))),e}function dt(){var e,n,r,o=i,s=i;if(e=d(),e!==null){for(n=[],r=d(),r===null&&(r=u(),r===null&&(t.charCodeAt(i)===43?(r=`+`,i++):(r=null,a===0&&c(`"+"`)),r===null&&(t.charCodeAt(i)===45?(r=`-`,i++):(r=null,a===0&&c(`"-"`)),r===null&&(t.charCodeAt(i)===46?(r=`.`,i++):(r=null,a===0&&c(`"."`))))));r!==null;)n.push(r),r=d(),r===null&&(r=u(),r===null&&(t.charCodeAt(i)===43?(r=`+`,i++):(r=null,a===0&&c(`"+"`)),r===null&&(t.charCodeAt(i)===45?(r=`-`,i++):(r=null,a===0&&c(`"-"`)),r===null&&(t.charCodeAt(i)===46?(r=`.`,i++):(r=null,a===0&&c(`"."`))))));n===null?(e=null,i=s):e=[e,n]}else e=null,i=s;return e!==null&&(e=(function(e){$.scheme=t.substring(i,e)})(o)),e===null&&(i=o),e}function ft(){var e=pt();return e===null&&(e=mt()),e}function pt(){var e,n,r=i,o=i;return e=we(),e===null?(e=null,i=o):(t.charCodeAt(i)===64?(n=`@`,i++):(n=null,a===0&&c(`"@"`)),n===null?(e=null,i=o):e=[e,n]),e=e===null?``:e,e===null?(e=null,i=r):(n=Oe(),n===null?(e=null,i=r):e=[e,n]),e=e===null?``:e,e}function mt(){var e,n=b();if(n===null&&(n=S(),n===null&&(t.charCodeAt(i)===36?(n=`$`,i++):(n=null,a===0&&c(`"$"`)),n===null&&(t.charCodeAt(i)===44?(n=`,`,i++):(n=null,a===0&&c(`","`)),n===null&&(t.charCodeAt(i)===59?(n=`;`,i++):(n=null,a===0&&c(`";"`)),n===null&&(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null&&(t.charCodeAt(i)===64?(n=`@`,i++):(n=null,a===0&&c(`"@"`)),n===null&&(t.charCodeAt(i)===38?(n=`&`,i++):(n=null,a===0&&c(`"&"`)),n===null&&(t.charCodeAt(i)===61?(n=`=`,i++):(n=null,a===0&&c(`"="`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`))))))))))),n!==null)for(e=[];n!==null;)e.push(n),n=b(),n===null&&(n=S(),n===null&&(t.charCodeAt(i)===36?(n=`$`,i++):(n=null,a===0&&c(`"$"`)),n===null&&(t.charCodeAt(i)===44?(n=`,`,i++):(n=null,a===0&&c(`","`)),n===null&&(t.charCodeAt(i)===59?(n=`;`,i++):(n=null,a===0&&c(`";"`)),n===null&&(t.charCodeAt(i)===58?(n=`:`,i++):(n=null,a===0&&c(`":"`)),n===null&&(t.charCodeAt(i)===64?(n=`@`,i++):(n=null,a===0&&c(`"@"`)),n===null&&(t.charCodeAt(i)===38?(n=`&`,i++):(n=null,a===0&&c(`"&"`)),n===null&&(t.charCodeAt(i)===61?(n=`=`,i++):(n=null,a===0&&c(`"="`)),n===null&&(t.charCodeAt(i)===43?(n=`+`,i++):(n=null,a===0&&c(`"+"`)))))))))));else e=null;return e}function ht(){for(var e=[],t=at();t!==null;)e.push(t),t=at();return e}function gt(){var e,n,r,o,s,l,d=i,f=i;if(t.substr(i,3).toLowerCase()===`sip`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"SIP"`)),e!==null){if(t.charCodeAt(i)===47?(n=`/`,i++):(n=null,a===0&&c(`"/"`)),n!==null){if(o=u(),o!==null)for(r=[];o!==null;)r.push(o),o=u();else r=null;if(r!==null){if(t.charCodeAt(i)===46?(o=`.`,i++):(o=null,a===0&&c(`"."`)),o!==null){if(l=u(),l!==null)for(s=[];l!==null;)s.push(l),l=u();else s=null;s===null?(e=null,i=f):e=[e,n,r,o,s]}else e=null,i=f}else e=null,i=f}else e=null,i=f}else e=null,i=f;return e!==null&&(e=(function(e){$.sip_version=t.substring(i,e)})(d)),e===null&&(i=d),e}function _t(){var e;return t.substr(i,6)===`INVITE`?(e=`INVITE`,i+=6):(e=null,a===0&&c(`"INVITE"`)),e}function vt(){var e;return t.substr(i,3)===`ACK`?(e=`ACK`,i+=3):(e=null,a===0&&c(`"ACK"`)),e}function yt(){var e;return t.substr(i,7)===`OPTIONS`?(e=`OPTIONS`,i+=7):(e=null,a===0&&c(`"OPTIONS"`)),e}function bt(){var e;return t.substr(i,3)===`BYE`?(e=`BYE`,i+=3):(e=null,a===0&&c(`"BYE"`)),e}function xt(){var e;return t.substr(i,6)===`CANCEL`?(e=`CANCEL`,i+=6):(e=null,a===0&&c(`"CANCEL"`)),e}function St(){var e;return t.substr(i,8)===`REGISTER`?(e=`REGISTER`,i+=8):(e=null,a===0&&c(`"REGISTER"`)),e}function Ct(){var e;return t.substr(i,9)===`SUBSCRIBE`?(e=`SUBSCRIBE`,i+=9):(e=null,a===0&&c(`"SUBSCRIBE"`)),e}function wt(){var e;return t.substr(i,6)===`NOTIFY`?(e=`NOTIFY`,i+=6):(e=null,a===0&&c(`"NOTIFY"`)),e}function Tt(){var e;return t.substr(i,5)===`REFER`?(e=`REFER`,i+=5):(e=null,a===0&&c(`"REFER"`)),e}function Et(){var e,n=i;return e=_t(),e===null&&(e=vt(),e===null&&(e=yt(),e===null&&(e=bt(),e===null&&(e=xt(),e===null&&(e=St(),e===null&&(e=Ct(),e===null&&(e=wt(),e===null&&(e=Tt(),e===null&&(e=O()))))))))),e!==null&&(e=(function(e){return $.method=t.substring(i,e),$.method})(n)),e===null&&(i=n),e}function Dt(){var e,t,n,r,a,o=i;return e=gt(),e===null?(e=null,i=o):(t=g(),t===null?(e=null,i=o):(n=Ot(),n===null?(e=null,i=o):(r=g(),r===null?(e=null,i=o):(a=At(),a===null?(e=null,i=o):e=[e,t,n,r,a])))),e}function Ot(){var e,t=i;return e=kt(),e!==null&&(e=(function(e,t){$.status_code=parseInt(t.join(``))})(t,e)),e===null&&(i=t),e}function kt(){var e,t,n,r=i;return e=u(),e===null?(e=null,i=r):(t=u(),t===null?(e=null,i=r):(n=u(),n===null?(e=null,i=r):e=[e,t,n])),e}function At(){var e,n,r=i;for(e=[],n=y(),n===null&&(n=b(),n===null&&(n=S(),n===null&&(n=D(),n===null&&(n=te(),n===null&&(n=g(),n===null&&(n=_()))))));n!==null;)e.push(n),n=y(),n===null&&(n=b(),n===null&&(n=S(),n===null&&(n=D(),n===null&&(n=te(),n===null&&(n=g(),n===null&&(n=_()))))));return e!==null&&(e=(function(e){$.reason_phrase=t.substring(i,e)})(r)),e===null&&(i=r),e}function jt(){var e,t,n,r,a=i,o;if(e=nn(),e!==null){for(t=[],o=i,n=A(),n===null?(n=null,i=o):(r=nn(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=A(),n===null?(n=null,i=o):(r=nn(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function Mt(){var e,n,r,o=i,s=i,l;return e=ae(),e===null?(e=null,i=s):(l=i,t.charCodeAt(i)===64?(n=`@`,i++):(n=null,a===0&&c(`"@"`)),n===null?(n=null,i=l):(r=ae(),r===null?(n=null,i=l):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=s):e=[e,n]),e!==null&&(e=(function(e){$=t.substring(i,e)})(o)),e===null&&(i=o),e}function Nt(){var e,t,n,r,a=i,o,s;if(e=oe(),e===null){if(o=i,e=Pt(),e!==null){for(t=[],s=i,n=A(),n===null?(n=null,i=s):(r=Pt(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=A(),n===null?(n=null,i=s):(r=Pt(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o}return e!==null&&(e=(function(e){var t,n=$.multi_header.length;for(t=0;t<n;t++)if($.multi_header[t].parsed===null){$=null;break}$=$===null?-1:$.multi_header})(a)),e===null&&(i=a),e}function Pt(){var e,t,n,r,a=i,o=i,s;if(e=ye(),e===null&&(e=V()),e!==null){for(t=[],s=i,n=j(),n===null?(n=null,i=s):(r=It(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=j(),n===null?(n=null,i=s):(r=It(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o;return e!==null&&(e=(function(e){var t;$.multi_header||($.multi_header=[]);try{t=new Er($.uri,$.display_name,$.params),delete $.uri,delete $.display_name,delete $.params}catch{t=null}$.multi_header.push({possition:i,offset:e,parsed:t})})(a)),e===null&&(i=a),e}function V(){var e,t,n,r,a=i;return e=Ft(),e=e===null?``:e,e===null?(e=null,i=a):(t=de(),t===null?(e=null,i=a):(n=be(),n===null?(e=null,i=a):(r=ue(),r===null?(e=null,i=a):e=[e,t,n,r]))),e}function Ft(){var e,t,n,r,a=i,o=i,s;if(e=O(),e!==null){for(t=[],s=i,n=C(),n===null?(n=null,i=s):(r=O(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=C(),n===null?(n=null,i=s):(r=O(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o;return e===null&&(e=M()),e!==null&&(e=(function(e,t){typeof t==`string`?$.display_name=t:$.display_name=t[1].reduce(function(e,t){return e+t[0]+t[1]},t[0])})(a,e)),e===null&&(i=a),e}function It(){var e=Lt();return e===null&&(e=Rt(),e===null&&(e=W())),e}function Lt(){var e,n,r,o=i,s=i;return t.substr(i,1).toLowerCase()===`q`?(e=t.substr(i,1),i++):(e=null,a===0&&c(`"q"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=U(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){$.params||($.params={}),$.params.q=t})(o,e[2])),e===null&&(i=o),e}function Rt(){var e,n,r,o=i,s=i;return t.substr(i,7).toLowerCase()===`expires`?(e=t.substr(i,7),i+=7):(e=null,a===0&&c(`"expires"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=H(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){$.params||($.params={}),$.params.expires=t})(o,e[2])),e===null&&(i=o),e}function H(){var e,t,n=i;if(t=u(),t!==null)for(e=[];t!==null;)e.push(t),t=u();else e=null;return e!==null&&(e=(function(e,t){return parseInt(t.join(``))})(n,e)),e===null&&(i=n),e}function U(){var e,n,r,o,s,l=i,d=i,f;return t.charCodeAt(i)===48?(e=`0`,i++):(e=null,a===0&&c(`"0"`)),e===null?(e=null,i=d):(f=i,t.charCodeAt(i)===46?(n=`.`,i++):(n=null,a===0&&c(`"."`)),n===null?(n=null,i=f):(r=u(),r=r===null?``:r,r===null?(n=null,i=f):(o=u(),o=o===null?``:o,o===null?(n=null,i=f):(s=u(),s=s===null?``:s,s===null?(n=null,i=f):n=[n,r,o,s]))),n=n===null?``:n,n===null?(e=null,i=d):e=[e,n]),e!==null&&(e=(function(e){return parseFloat(t.substring(i,e))})(l)),e===null&&(i=l),e}function W(){var e,t,n,r=i,a=i,o;return e=O(),e===null?(e=null,i=a):(o=i,t=k(),t===null?(t=null,i=o):(n=K(),n===null?(t=null,i=o):t=[t,n]),t=t===null?``:t,t===null?(e=null,i=a):e=[e,t]),e!==null&&(e=(function(e,t,n){$.params||($.params={}),n=n===void 0?void 0:n[1],$.params[t.toLowerCase()]=n})(r,e[0],e[1])),e===null&&(i=r),e}function K(){var e=O();return e===null&&(e=ke(),e===null&&(e=_e())),e}function q(){var e,t,n,r,a=i,o;if(e=Bt(),e!==null){for(t=[],o=i,n=j(),n===null?(n=null,i=o):(r=Vt(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=j(),n===null?(n=null,i=o):(r=Vt(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function Bt(){var e;return t.substr(i,6).toLowerCase()===`render`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"render"`)),e===null&&(t.substr(i,7).toLowerCase()===`session`?(e=t.substr(i,7),i+=7):(e=null,a===0&&c(`"session"`)),e===null&&(t.substr(i,4).toLowerCase()===`icon`?(e=t.substr(i,4),i+=4):(e=null,a===0&&c(`"icon"`)),e===null&&(t.substr(i,5).toLowerCase()===`alert`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"alert"`)),e===null&&(e=O())))),e}function Vt(){var e=Ht();return e===null&&(e=W()),e}function Ht(){var e,n,r,o=i;return t.substr(i,8).toLowerCase()===`handling`?(e=t.substr(i,8),i+=8):(e=null,a===0&&c(`"handling"`)),e===null?(e=null,i=o):(n=k(),n===null?(e=null,i=o):(t.substr(i,8).toLowerCase()===`optional`?(r=t.substr(i,8),i+=8):(r=null,a===0&&c(`"optional"`)),r===null&&(t.substr(i,8).toLowerCase()===`required`?(r=t.substr(i,8),i+=8):(r=null,a===0&&c(`"required"`)),r===null&&(r=O())),r===null?(e=null,i=o):e=[e,n,r])),e}function J(){var e,t,n,r,a=i,o;if(e=O(),e!==null){for(t=[],o=i,n=A(),n===null?(n=null,i=o):(r=O(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=A(),n===null?(n=null,i=o):(r=O(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function Ut(){var e,t,n=i;if(t=u(),t!==null)for(e=[];t!==null;)e.push(t),t=u();else e=null;return e!==null&&(e=(function(e,t){$=parseInt(t.join(``))})(n,e)),e===null&&(i=n),e}function Wt(){var e,n=i;return e=Gt(),e!==null&&(e=(function(e){$=t.substring(i,e)})(n)),e===null&&(i=n),e}function Gt(){var e,t,n,r,a,o,s=i,c;if(e=Kt(),e!==null){if(t=se(),t!==null){if(n=X(),n!==null){for(r=[],c=i,a=j(),a===null?(a=null,i=c):(o=Xt(),o===null?(a=null,i=c):a=[a,o]);a!==null;)r.push(a),c=i,a=j(),a===null?(a=null,i=c):(o=Xt(),o===null?(a=null,i=c):a=[a,o]);r===null?(e=null,i=s):e=[e,t,n,r]}else e=null,i=s}else e=null,i=s}else e=null,i=s;return e}function Kt(){var e=Y();return e===null&&(e=qt()),e}function Y(){var e;return t.substr(i,4).toLowerCase()===`text`?(e=t.substr(i,4),i+=4):(e=null,a===0&&c(`"text"`)),e===null&&(t.substr(i,5).toLowerCase()===`image`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"image"`)),e===null&&(t.substr(i,5).toLowerCase()===`audio`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"audio"`)),e===null&&(t.substr(i,5).toLowerCase()===`video`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"video"`)),e===null&&(t.substr(i,11).toLowerCase()===`application`?(e=t.substr(i,11),i+=11):(e=null,a===0&&c(`"application"`)),e===null&&(e=Jt()))))),e}function qt(){var e;return t.substr(i,7).toLowerCase()===`message`?(e=t.substr(i,7),i+=7):(e=null,a===0&&c(`"message"`)),e===null&&(t.substr(i,9).toLowerCase()===`multipart`?(e=t.substr(i,9),i+=9):(e=null,a===0&&c(`"multipart"`)),e===null&&(e=Jt())),e}function Jt(){var e=O();return e===null&&(e=Yt()),e}function Yt(){var e,n,r=i;return t.substr(i,2).toLowerCase()===`x-`?(e=t.substr(i,2),i+=2):(e=null,a===0&&c(`"x-"`)),e===null?(e=null,i=r):(n=O(),n===null?(e=null,i=r):e=[e,n]),e}function X(){var e=Jt();return e===null&&(e=O()),e}function Xt(){var e,t,n,r=i;return e=O(),e===null?(e=null,i=r):(t=k(),t===null?(e=null,i=r):(n=Zt(),n===null?(e=null,i=r):e=[e,t,n])),e}function Zt(){var e=O();return e===null&&(e=_e()),e}function Qt(){var e,t,n,r=i;return e=$t(),e===null?(e=null,i=r):(t=C(),t===null?(e=null,i=r):(n=Et(),n===null?(e=null,i=r):e=[e,t,n])),e}function $t(){var e,t,n=i;if(t=u(),t!==null)for(e=[];t!==null;)e.push(t),t=u();else e=null;return e!==null&&(e=(function(e,t){$.value=parseInt(t.join(``))})(n,e)),e===null&&(i=n),e}function en(){var e,t=i;return e=H(),e!==null&&(e=(function(e,t){$=t})(t,e)),e===null&&(i=t),e}function tn(){var e,t,n,r,a=i,o=i,s;if(e=nn(),e!==null){for(t=[],s=i,n=j(),n===null?(n=null,i=s):(r=W(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=j(),n===null?(n=null,i=s):(r=W(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o;return e!==null&&(e=(function(e,t){$.event=t.join(``).toLowerCase()})(a,e[0])),e===null&&(i=a),e}function nn(){var e,n,r,o,s=i,l;if(e=re(),e!==null){for(n=[],l=i,t.charCodeAt(i)===46?(r=`.`,i++):(r=null,a===0&&c(`"."`)),r===null?(r=null,i=l):(o=re(),o===null?(r=null,i=l):r=[r,o]);r!==null;)n.push(r),l=i,t.charCodeAt(i)===46?(r=`.`,i++):(r=null,a===0&&c(`"."`)),r===null?(r=null,i=l):(o=re(),o===null?(r=null,i=l):r=[r,o]);n===null?(e=null,i=s):e=[e,n]}else e=null,i=s;return e}function rn(){var e,t,n,r,a=i,o=i,s;if(e=ye(),e===null&&(e=V()),e!==null){for(t=[],s=i,n=j(),n===null?(n=null,i=s):(r=an(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=j(),n===null?(n=null,i=s):(r=an(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o;return e!==null&&(e=(function(e){var t=$.tag;try{$=new Er($.uri,$.display_name,$.params),t&&$.setParam(`tag`,t)}catch{$=-1}})(a)),e===null&&(i=a),e}function an(){var e=on();return e===null&&(e=W()),e}function on(){var e,n,r,o=i,s=i;return t.substr(i,3).toLowerCase()===`tag`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"tag"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=O(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){$.tag=t})(o,e[2])),e===null&&(i=o),e}function sn(){var e,t,n=i;if(t=u(),t!==null)for(e=[];t!==null;)e.push(t),t=u();else e=null;return e!==null&&(e=(function(e,t){$=parseInt(t.join(``))})(n,e)),e===null&&(i=n),e}function cn(){var e,t=i;return e=H(),e!==null&&(e=(function(e,t){$=t})(t,e)),e===null&&(i=t),e}function ln(){var e,t,n,r,a,o,s,c=i,l=i,u;for(e=[],t=Ft();t!==null;)e.push(t),t=Ft();if(e!==null){if(t=de(),t!==null){if(n=be(),n!==null){if(r=ue(),r!==null){for(a=[],u=i,o=j(),o===null?(o=null,i=u):(s=W(),s===null?(o=null,i=u):o=[o,s]);o!==null;)a.push(o),u=i,o=j(),o===null?(o=null,i=u):(s=W(),s===null?(o=null,i=u):o=[o,s]);a===null?(e=null,i=l):e=[e,t,n,r,a]}else e=null,i=l}else e=null,i=l}else e=null,i=l}else e=null,i=l;return e!==null&&(e=(function(e){try{$=new Er($.uri,$.display_name,$.params)}catch{$=-1}})(c)),e===null&&(i=c),e}function un(){return dn()}function dn(){var e,n,r,o,s,l,u=i,d;if(t.substr(i,6).toLowerCase()===`digest`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"Digest"`)),e!==null){if(n=C(),n!==null){if(r=mn(),r!==null){for(o=[],d=i,s=A(),s===null?(s=null,i=d):(l=mn(),l===null?(s=null,i=d):s=[s,l]);s!==null;)o.push(s),d=i,s=A(),s===null?(s=null,i=d):(l=mn(),l===null?(s=null,i=d):s=[s,l]);o===null?(e=null,i=u):e=[e,n,r,o]}else e=null,i=u}else e=null,i=u}else e=null,i=u;return e===null&&(e=fn()),e}function fn(){var e,t,n,r,a,o,s=i,c;if(e=O(),e!==null){if(t=C(),t!==null){if(n=pn(),n!==null){for(r=[],c=i,a=A(),a===null?(a=null,i=c):(o=pn(),o===null?(a=null,i=c):a=[a,o]);a!==null;)r.push(a),c=i,a=A(),a===null?(a=null,i=c):(o=pn(),o===null?(a=null,i=c):a=[a,o]);r===null?(e=null,i=s):e=[e,t,n,r]}else e=null,i=s}else e=null,i=s}else e=null,i=s;return e}function pn(){var e,t,n,r=i;return e=O(),e===null?(e=null,i=r):(t=k(),t===null?(e=null,i=r):(n=O(),n===null&&(n=_e()),n===null?(e=null,i=r):e=[e,t,n])),e}function mn(){var e=hn();return e===null&&(e=_n(),e===null&&(e=yn(),e===null&&(e=xn(),e===null&&(e=Sn(),e===null&&(e=Cn(),e===null&&(e=wn(),e===null&&(e=pn()))))))),e}function hn(){var e,n,r,o=i;return t.substr(i,5).toLowerCase()===`realm`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"realm"`)),e===null?(e=null,i=o):(n=k(),n===null?(e=null,i=o):(r=gn(),r===null?(e=null,i=o):e=[e,n,r])),e}function gn(){var e,t=i;return e=M(),e!==null&&(e=(function(e,t){$.realm=t})(t,e)),e===null&&(i=t),e}function _n(){var e,n,r,o,s,l,u,d=i,f;if(t.substr(i,6).toLowerCase()===`domain`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"domain"`)),e!==null){if(n=k(),n!==null){if(r=pe(),r!==null){if(o=vn(),o!==null){if(s=[],f=i,u=g(),u!==null)for(l=[];u!==null;)l.push(u),u=g();else l=null;for(l===null?(l=null,i=f):(u=vn(),u===null?(l=null,i=f):l=[l,u]);l!==null;){if(s.push(l),f=i,u=g(),u!==null)for(l=[];u!==null;)l.push(u),u=g();else l=null;l===null?(l=null,i=f):(u=vn(),u===null?(l=null,i=f):l=[l,u])}s===null?(e=null,i=d):(l=me(),l===null?(e=null,i=d):e=[e,n,r,o,s,l])}else e=null,i=d}else e=null,i=d}else e=null,i=d}else e=null,i=d;return e}function vn(){var e=nt();return e===null&&(e=B()),e}function yn(){var e,n,r,o=i;return t.substr(i,5).toLowerCase()===`nonce`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"nonce"`)),e===null?(e=null,i=o):(n=k(),n===null?(e=null,i=o):(r=bn(),r===null?(e=null,i=o):e=[e,n,r])),e}function bn(){var e,t=i;return e=M(),e!==null&&(e=(function(e,t){$.nonce=t})(t,e)),e===null&&(i=t),e}function xn(){var e,n,r,o=i,s=i;return t.substr(i,6).toLowerCase()===`opaque`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"opaque"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=M(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){$.opaque=t})(o,e[2])),e===null&&(i=o),e}function Sn(){var e,n,r,o=i,s;return t.substr(i,5).toLowerCase()===`stale`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"stale"`)),e===null?(e=null,i=o):(n=k(),n===null?(e=null,i=o):(s=i,t.substr(i,4).toLowerCase()===`true`?(r=t.substr(i,4),i+=4):(r=null,a===0&&c(`"true"`)),r!==null&&(r=(function(e){$.stale=!0})(s)),r===null&&(i=s),r===null&&(s=i,t.substr(i,5).toLowerCase()===`false`?(r=t.substr(i,5),i+=5):(r=null,a===0&&c(`"false"`)),r!==null&&(r=(function(e){$.stale=!1})(s)),r===null&&(i=s)),r===null?(e=null,i=o):e=[e,n,r])),e}function Cn(){var e,n,r,o=i,s=i;return t.substr(i,9).toLowerCase()===`algorithm`?(e=t.substr(i,9),i+=9):(e=null,a===0&&c(`"algorithm"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(t.substr(i,3).toLowerCase()===`md5`?(r=t.substr(i,3),i+=3):(r=null,a===0&&c(`"MD5"`)),r===null&&(t.substr(i,8).toLowerCase()===`md5-sess`?(r=t.substr(i,8),i+=8):(r=null,a===0&&c(`"MD5-sess"`)),r===null&&(r=O())),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){$.algorithm=t.toUpperCase()})(o,e[2])),e===null&&(i=o),e}function wn(){var e,n,r,o,s,l,u,d=i,f,p;if(t.substr(i,3).toLowerCase()===`qop`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"qop"`)),e!==null){if(n=k(),n!==null){if(r=pe(),r!==null){if(f=i,o=Tn(),o!==null){for(s=[],p=i,t.charCodeAt(i)===44?(l=`,`,i++):(l=null,a===0&&c(`","`)),l===null?(l=null,i=p):(u=Tn(),u===null?(l=null,i=p):l=[l,u]);l!==null;)s.push(l),p=i,t.charCodeAt(i)===44?(l=`,`,i++):(l=null,a===0&&c(`","`)),l===null?(l=null,i=p):(u=Tn(),u===null?(l=null,i=p):l=[l,u]);s===null?(o=null,i=f):o=[o,s]}else o=null,i=f;o===null?(e=null,i=d):(s=me(),s===null?(e=null,i=d):e=[e,n,r,o,s])}else e=null,i=d}else e=null,i=d}else e=null,i=d;return e}function Tn(){var e,n=i;return t.substr(i,8).toLowerCase()===`auth-int`?(e=t.substr(i,8),i+=8):(e=null,a===0&&c(`"auth-int"`)),e===null&&(t.substr(i,4).toLowerCase()===`auth`?(e=t.substr(i,4),i+=4):(e=null,a===0&&c(`"auth"`)),e===null&&(e=O())),e!==null&&(e=(function(e,t){$.qop||($.qop=[]),$.qop.push(t.toLowerCase())})(n,e)),e===null&&(i=n),e}function En(){var e,t,n,r,a=i,o;if(e=O(),e!==null){for(t=[],o=i,n=A(),n===null?(n=null,i=o):(r=O(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=A(),n===null?(n=null,i=o):(r=O(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function Dn(){var e,t,n,r,a=i,o=i,s;if(e=On(),e!==null){for(t=[],s=i,n=A(),n===null?(n=null,i=s):(r=On(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=A(),n===null?(n=null,i=s):(r=On(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o;return e!==null&&(e=(function(e){var t,n=$.multi_header.length;for(t=0;t<n;t++)if($.multi_header[t].parsed===null){$=null;break}$=$===null?-1:$.multi_header})(a)),e===null&&(i=a),e}function On(){var e,t,n,r,a=i,o=i,s;if(e=V(),e!==null){for(t=[],s=i,n=j(),n===null?(n=null,i=s):(r=W(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=j(),n===null?(n=null,i=s):(r=W(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o;return e!==null&&(e=(function(e){var t;$.multi_header||($.multi_header=[]);try{t=new Er($.uri,$.display_name,$.params),delete $.uri,delete $.display_name,delete $.params}catch{t=null}$.multi_header.push({possition:i,offset:e,parsed:t})})(a)),e===null&&(i=a),e}function kn(){var e,n,r,o,s=i,l=i,u;if(t.substr(i,3).toLowerCase()===`sip`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"SIP"`)),e===null&&(e=O()),e!==null){for(n=[],u=i,r=j(),r===null?(r=null,i=u):(o=An(),o===null?(r=null,i=u):r=[r,o]);r!==null;)n.push(r),u=i,r=j(),r===null?(r=null,i=u):(o=An(),o===null?(r=null,i=u):r=[r,o]);n===null?(e=null,i=l):e=[e,n]}else e=null,i=l;return e!==null&&(e=(function(e,t){if($.protocol=t.toLowerCase(),$.params||($.params={}),$.params.text&&$.params.text[0]===`"`){var n=$.params.text;$.text=n.substring(1,n.length-1),delete $.params.text}})(s,e[0])),e===null&&(i=s),e}function An(){var e=jn();return e===null&&(e=W()),e}function jn(){var e,n,r,o,s=i,l=i;if(t.substr(i,5).toLowerCase()===`cause`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"cause"`)),e!==null){if(n=k(),n!==null){if(o=u(),o!==null)for(r=[];o!==null;)r.push(o),o=u();else r=null;r===null?(e=null,i=l):e=[e,n,r]}else e=null,i=l}else e=null,i=l;return e!==null&&(e=(function(e,t){$.cause=parseInt(t.join(``))})(s,e[2])),e===null&&(i=s),e}function Mn(){var e,t,n,r,a=i,o;if(e=O(),e!==null){for(t=[],o=i,n=A(),n===null?(n=null,i=o):(r=O(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=A(),n===null?(n=null,i=o):(r=O(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function Nn(){var e,t,n,r,a=i,o;if(e=Pn(),e!==null){for(t=[],o=i,n=A(),n===null?(n=null,i=o):(r=Pn(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=A(),n===null?(n=null,i=o):(r=Pn(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function Pn(){var e,t,n,r,a=i,o;if(e=V(),e!==null){for(t=[],o=i,n=j(),n===null?(n=null,i=o):(r=W(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=j(),n===null?(n=null,i=o):(r=W(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function Fn(){var e,t,n,r,a=i,o;if(e=In(),e!==null){for(t=[],o=i,n=j(),n===null?(n=null,i=o):(r=Ln(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=j(),n===null?(n=null,i=o):(r=Ln(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function In(){var e,n=i;return t.substr(i,6).toLowerCase()===`active`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"active"`)),e===null&&(t.substr(i,7).toLowerCase()===`pending`?(e=t.substr(i,7),i+=7):(e=null,a===0&&c(`"pending"`)),e===null&&(t.substr(i,10).toLowerCase()===`terminated`?(e=t.substr(i,10),i+=10):(e=null,a===0&&c(`"terminated"`)),e===null&&(e=O()))),e!==null&&(e=(function(e){$.state=t.substring(i,e)})(n)),e===null&&(i=n),e}function Ln(){var e,n,r,o=i,s=i;return t.substr(i,6).toLowerCase()===`reason`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"reason"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=Rn(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){t!==void 0&&($.reason=t)})(o,e[2])),e===null&&(i=o),e===null&&(o=i,s=i,t.substr(i,7).toLowerCase()===`expires`?(e=t.substr(i,7),i+=7):(e=null,a===0&&c(`"expires"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=H(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){t!==void 0&&($.expires=t)})(o,e[2])),e===null&&(i=o),e===null&&(o=i,s=i,t.substr(i,11).toLowerCase()===`retry_after`?(e=t.substr(i,11),i+=11):(e=null,a===0&&c(`"retry_after"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=H(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){t!==void 0&&($.retry_after=t)})(o,e[2])),e===null&&(i=o),e===null&&(e=W()))),e}function Rn(){var e;return t.substr(i,11).toLowerCase()===`deactivated`?(e=t.substr(i,11),i+=11):(e=null,a===0&&c(`"deactivated"`)),e===null&&(t.substr(i,9).toLowerCase()===`probation`?(e=t.substr(i,9),i+=9):(e=null,a===0&&c(`"probation"`)),e===null&&(t.substr(i,8).toLowerCase()===`rejected`?(e=t.substr(i,8),i+=8):(e=null,a===0&&c(`"rejected"`)),e===null&&(t.substr(i,7).toLowerCase()===`timeout`?(e=t.substr(i,7),i+=7):(e=null,a===0&&c(`"timeout"`)),e===null&&(t.substr(i,6).toLowerCase()===`giveup`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"giveup"`)),e===null&&(t.substr(i,10).toLowerCase()===`noresource`?(e=t.substr(i,10),i+=10):(e=null,a===0&&c(`"noresource"`)),e===null&&(t.substr(i,9).toLowerCase()===`invariant`?(e=t.substr(i,9),i+=9):(e=null,a===0&&c(`"invariant"`)),e===null&&(e=O()))))))),e}function zn(){var e=T();return e=e===null?``:e,e}function Bn(){var e,t,n,r,a=i,o;if(e=O(),e!==null){for(t=[],o=i,n=A(),n===null?(n=null,i=o):(r=O(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=A(),n===null?(n=null,i=o):(r=O(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e=e===null?``:e,e}function Vn(){var e,t,n,r,a=i,o=i,s;if(e=ye(),e===null&&(e=V()),e!==null){for(t=[],s=i,n=j(),n===null?(n=null,i=s):(r=Hn(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=j(),n===null?(n=null,i=s):(r=Hn(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o;return e!==null&&(e=(function(e){var t=$.tag;try{$=new Er($.uri,$.display_name,$.params),t&&$.setParam(`tag`,t)}catch{$=-1}})(a)),e===null&&(i=a),e}function Hn(){var e=on();return e===null&&(e=W()),e}function Un(){var e,t,n,r,a=i,o;if(e=Wn(),e!==null){for(t=[],o=i,n=A(),n===null?(n=null,i=o):(r=Wn(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=A(),n===null?(n=null,i=o):(r=Wn(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function Wn(){var e,t,n,r,a,o,s=i,c;if(e=Qn(),e!==null){if(t=C(),t!==null){if(n=tr(),n!==null){for(r=[],c=i,a=j(),a===null?(a=null,i=c):(o=Gn(),o===null?(a=null,i=c):a=[a,o]);a!==null;)r.push(a),c=i,a=j(),a===null?(a=null,i=c):(o=Gn(),o===null?(a=null,i=c):a=[a,o]);r===null?(e=null,i=s):e=[e,t,n,r]}else e=null,i=s}else e=null,i=s}else e=null,i=s;return e}function Gn(){var e=Kn();return e===null&&(e=qn(),e===null&&(e=Jn(),e===null&&(e=Yn(),e===null&&(e=Xn(),e===null&&(e=W()))))),e}function Kn(){var e,n,r,o=i,s=i;return t.substr(i,3).toLowerCase()===`ttl`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"ttl"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=ir(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){$.ttl=t})(o,e[2])),e===null&&(i=o),e}function qn(){var e,n,r,o=i,s=i;return t.substr(i,5).toLowerCase()===`maddr`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"maddr"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=ke(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){$.maddr=t})(o,e[2])),e===null&&(i=o),e}function Jn(){var e,n,r,o=i,s=i;return t.substr(i,8).toLowerCase()===`received`?(e=t.substr(i,8),i+=8):(e=null,a===0&&c(`"received"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=Pe(),r===null&&(r=Ne()),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){$.received=t})(o,e[2])),e===null&&(i=o),e}function Yn(){var e,n,r,o=i,s=i;return t.substr(i,6).toLowerCase()===`branch`?(e=t.substr(i,6),i+=6):(e=null,a===0&&c(`"branch"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=O(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){$.branch=t})(o,e[2])),e===null&&(i=o),e}function Xn(){var e,n,r,o=i,s;return t.substr(i,5).toLowerCase()===`rport`?(e=t.substr(i,5),i+=5):(e=null,a===0&&c(`"rport"`)),e===null?(e=null,i=o):(s=i,n=k(),n===null?(n=null,i=s):(r=Zn(),r===null?(n=null,i=s):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=o):e=[e,n]),e}function Zn(){var e,t,n,r,a,o=i,s=i;return e=u(),e=e===null?``:e,e===null?(e=null,i=s):(t=u(),t=t===null?``:t,t===null?(e=null,i=s):(n=u(),n=n===null?``:n,n===null?(e=null,i=s):(r=u(),r=r===null?``:r,r===null?(e=null,i=s):(a=u(),a=a===null?``:a,a===null?(e=null,i=s):e=[e,t,n,r,a])))),e!==null&&(e=(function(e,t){$.rport=parseInt(t.join(``))})(o,e)),e===null&&(i=o),e}function Qn(){var e,t,n,r,a,o=i;return e=$n(),e===null?(e=null,i=o):(t=se(),t===null?(e=null,i=o):(n=O(),n===null?(e=null,i=o):(r=se(),r===null?(e=null,i=o):(a=er(),a===null?(e=null,i=o):e=[e,t,n,r,a])))),e}function $n(){var e,n=i;return t.substr(i,3).toLowerCase()===`sip`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"SIP"`)),e===null&&(e=O()),e!==null&&(e=(function(e,t){$.protocol=t})(n,e)),e===null&&(i=n),e}function er(){var e,n=i;return t.substr(i,3).toLowerCase()===`udp`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"UDP"`)),e===null&&(t.substr(i,3).toLowerCase()===`tcp`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"TCP"`)),e===null&&(t.substr(i,3).toLowerCase()===`tls`?(e=t.substr(i,3),i+=3):(e=null,a===0&&c(`"TLS"`)),e===null&&(t.substr(i,4).toLowerCase()===`sctp`?(e=t.substr(i,4),i+=4):(e=null,a===0&&c(`"SCTP"`)),e===null&&(e=O())))),e!==null&&(e=(function(e,t){$.transport=t})(n,e)),e===null&&(i=n),e}function tr(){var e,t,n,r=i,a;return e=nr(),e===null?(e=null,i=r):(a=i,t=fe(),t===null?(t=null,i=a):(n=rr(),n===null?(t=null,i=a):t=[t,n]),t=t===null?``:t,t===null?(e=null,i=r):e=[e,t]),e}function nr(){var e,n=i;return e=Pe(),e===null&&(e=Me(),e===null&&(e=Ae())),e!==null&&(e=(function(e){$.host=t.substring(i,e)})(n)),e===null&&(i=n),e}function rr(){var e,t,n,r,a,o=i,s=i;return e=u(),e=e===null?``:e,e===null?(e=null,i=s):(t=u(),t=t===null?``:t,t===null?(e=null,i=s):(n=u(),n=n===null?``:n,n===null?(e=null,i=s):(r=u(),r=r===null?``:r,r===null?(e=null,i=s):(a=u(),a=a===null?``:a,a===null?(e=null,i=s):e=[e,t,n,r,a])))),e!==null&&(e=(function(e,t){$.port=parseInt(t.join(``))})(o,e)),e===null&&(i=o),e}function ir(){var e,t,n,r=i,a=i;return e=u(),e===null?(e=null,i=a):(t=u(),t=t===null?``:t,t===null?(e=null,i=a):(n=u(),n=n===null?``:n,n===null?(e=null,i=a):e=[e,t,n])),e!==null&&(e=(function(e,t){return parseInt(t.join(``))})(r,e)),e===null&&(i=r),e}function ar(){return dn()}function or(){var e,t,n,r,a=i,o;if(e=sr(),e!==null){for(t=[],o=i,n=j(),n===null?(n=null,i=o):(r=Z(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=j(),n===null?(n=null,i=o):(r=Z(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function sr(){var e,t=i;return e=H(),e!==null&&(e=(function(e,t){$.expires=t})(t,e)),e===null&&(i=t),e}function Z(){var e=cr();return e===null&&(e=W()),e}function cr(){var e,n,r,o=i,s=i;return t.substr(i,9).toLowerCase()===`refresher`?(e=t.substr(i,9),i+=9):(e=null,a===0&&c(`"refresher"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(t.substr(i,3).toLowerCase()===`uac`?(r=t.substr(i,3),i+=3):(r=null,a===0&&c(`"uac"`)),r===null&&(t.substr(i,3).toLowerCase()===`uas`?(r=t.substr(i,3),i+=3):(r=null,a===0&&c(`"uas"`))),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){$.refresher=t.toLowerCase()})(o,e[2])),e===null&&(i=o),e}function lr(){var e,t,n,r=i;return e=O(),e===null?(e=null,i=r):(t=ee(),t===null?(e=null,i=r):(n=ur(),n===null?(e=null,i=r):e=[e,t,n])),e}function ur(){var e=[],t=E();for(t===null&&(t=te(),t===null&&(t=C()));t!==null;)e.push(t),t=E(),t===null&&(t=te(),t===null&&(t=C()));return e}function dr(){for(var e=[],t=m();t!==null;)e.push(t),t=m();return e}function fr(){var e,n,r=i;return t.substr(i,5)===`uuid:`?(e=`uuid:`,i+=5):(e=null,a===0&&c(`"uuid:"`)),e===null?(e=null,i=r):(n=pr(),n===null?(e=null,i=r):e=[e,n]),e}function pr(){var e,n,r,o,s,l,u,d,f,p=i,m=i;return e=mr(),e===null?(e=null,i=m):(t.charCodeAt(i)===45?(n=`-`,i++):(n=null,a===0&&c(`"-"`)),n===null?(e=null,i=m):(r=Q(),r===null?(e=null,i=m):(t.charCodeAt(i)===45?(o=`-`,i++):(o=null,a===0&&c(`"-"`)),o===null?(e=null,i=m):(s=Q(),s===null?(e=null,i=m):(t.charCodeAt(i)===45?(l=`-`,i++):(l=null,a===0&&c(`"-"`)),l===null?(e=null,i=m):(u=Q(),u===null?(e=null,i=m):(t.charCodeAt(i)===45?(d=`-`,i++):(d=null,a===0&&c(`"-"`)),d===null?(e=null,i=m):(f=hr(),f===null?(e=null,i=m):e=[e,n,r,o,s,l,u,d,f])))))))),e!==null&&(e=(function(e,n){$=t.substring(i+5,e)})(p,e[0])),e===null&&(i=p),e}function Q(){var e,t,n,r,a=i;return e=f(),e===null?(e=null,i=a):(t=f(),t===null?(e=null,i=a):(n=f(),n===null?(e=null,i=a):(r=f(),r===null?(e=null,i=a):e=[e,t,n,r]))),e}function mr(){var e,t,n=i;return e=Q(),e===null?(e=null,i=n):(t=Q(),t===null?(e=null,i=n):e=[e,t]),e}function hr(){var e,t,n,r=i;return e=Q(),e===null?(e=null,i=r):(t=Q(),t===null?(e=null,i=r):(n=Q(),n===null?(e=null,i=r):e=[e,t,n])),e}function gr(){var e,t,n,r,a=i,o=i,s;if(e=ye(),e===null&&(e=V()),e!==null){for(t=[],s=i,n=j(),n===null?(n=null,i=s):(r=W(),r===null?(n=null,i=s):n=[n,r]);n!==null;)t.push(n),s=i,n=j(),n===null?(n=null,i=s):(r=W(),r===null?(n=null,i=s):n=[n,r]);t===null?(e=null,i=o):e=[e,t]}else e=null,i=o;return e!==null&&(e=(function(e){try{$=new Er($.uri,$.display_name,$.params)}catch{$=-1}})(a)),e===null&&(i=a),e}function _r(){var e,t,n,r,a=i,o;if(e=vr(),e!==null){for(t=[],o=i,n=j(),n===null?(n=null,i=o):(r=yr(),r===null?(n=null,i=o):n=[n,r]);n!==null;)t.push(n),o=i,n=j(),n===null?(n=null,i=o):(r=yr(),r===null?(n=null,i=o):n=[n,r]);t===null?(e=null,i=a):e=[e,t]}else e=null,i=a;return e}function vr(){var e,n,r,o=i,s=i,l;return e=ae(),e===null?(e=null,i=s):(l=i,t.charCodeAt(i)===64?(n=`@`,i++):(n=null,a===0&&c(`"@"`)),n===null?(n=null,i=l):(r=ae(),r===null?(n=null,i=l):n=[n,r]),n=n===null?``:n,n===null?(e=null,i=s):e=[e,n]),e!==null&&(e=(function(e){$.call_id=t.substring(i,e)})(o)),e===null&&(i=o),e}function yr(){var e=br();return e===null&&(e=xr(),e===null&&(e=Sr(),e===null&&(e=W()))),e}function br(){var e,n,r,o=i,s=i;return t.substr(i,6)===`to-tag`?(e=`to-tag`,i+=6):(e=null,a===0&&c(`"to-tag"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=O(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){$.to_tag=t})(o,e[2])),e===null&&(i=o),e}function xr(){var e,n,r,o=i,s=i;return t.substr(i,8)===`from-tag`?(e=`from-tag`,i+=8):(e=null,a===0&&c(`"from-tag"`)),e===null?(e=null,i=s):(n=k(),n===null?(e=null,i=s):(r=O(),r===null?(e=null,i=s):e=[e,n,r])),e!==null&&(e=(function(e,t){$.from_tag=t})(o,e[2])),e===null&&(i=o),e}function Sr(){var e,n=i;return t.substr(i,10)===`early-only`?(e=`early-only`,i+=10):(e=null,a===0&&c(`"early-only"`)),e!==null&&(e=(function(e){$.early_only=!0})(n)),e===null&&(i=n),e}function Cr(e){e.sort();for(var t=null,n=[],r=0;r<e.length;r++)e[r]!==t&&(n.push(e[r]),t=e[r]);return n}function wr(){for(var e=1,n=1,r=!1,a=0;a<Math.max(i,o);a++){var s=t.charAt(a);s===`
|
|
4
|
+
`?(r||e++,n=1,r=!1):s===`\r`||s===`\u2028`||s===`\u2029`?(e++,n=1,r=!0):(n++,r=!1)}return{line:e,column:n}}var Tr=G(),Er=zt(),$={};if(r[n]()===null||i!==t.length){var Dr=Math.max(i,o),Or=Dr<t.length?t.charAt(Dr):null,kr=wr();return new this.SyntaxError(Cr(s),Or,Dr,kr.line,kr.column),-1}return $},toSource:function(){return this._source}};return t.SyntaxError=function(t,n,r,i,a){function o(t,n){var r,i;switch(t.length){case 0:r=`end of input`;break;case 1:r=t[0];break;default:r=t.slice(0,t.length-1).join(`, `)+` or `+t[t.length-1]}return i=n?e(n):`end of input`,`Expected `+r+` but `+i+` found.`}this.name=`SyntaxError`,this.expected=t,this.found=n,this.message=o(t,n),this.offset=r,this.line=i,this.column=a},t.SyntaxError.prototype=Error.prototype,t})()})),G=c(((e,t)=>{var n=H(),r=K(),i=W();t.exports=class e{static parse(e){if(e=i.parse(e,`SIP_URI`),e!==-1)return e}constructor(e,t,r,i,a={},o={}){if(!r)throw TypeError(`missing or invalid "host" parameter`);this._parameters={},this._headers={},this._scheme=e||n.SIP,this._user=t,this._host=r,this._port=i;for(let e in a)Object.prototype.hasOwnProperty.call(a,e)&&this.setParam(e,a[e]);for(let e in o)Object.prototype.hasOwnProperty.call(o,e)&&this.setHeader(e,o[e])}get scheme(){return this._scheme}set scheme(e){this._scheme=e.toLowerCase()}get user(){return this._user}set user(e){this._user=e}get host(){return this._host}set host(e){this._host=e.toLowerCase()}get port(){return this._port}set port(e){this._port=e===0?e:parseInt(e,10)||null}setParam(e,t){e&&(this._parameters[e.toLowerCase()]=t==null?null:t.toString())}getParam(e){if(e)return this._parameters[e.toLowerCase()]}hasParam(e){if(e)return this._parameters.hasOwnProperty(e.toLowerCase())&&!0||!1}deleteParam(e){if(e=e.toLowerCase(),this._parameters.hasOwnProperty(e)){let t=this._parameters[e];return delete this._parameters[e],t}}clearParams(){this._parameters={}}setHeader(e,t){this._headers[r.headerize(e)]=Array.isArray(t)?t:[t]}getHeader(e){if(e)return this._headers[r.headerize(e)]}hasHeader(e){if(e)return this._headers.hasOwnProperty(r.headerize(e))&&!0||!1}deleteHeader(e){if(e=r.headerize(e),this._headers.hasOwnProperty(e)){let t=this._headers[e];return delete this._headers[e],t}}clearHeaders(){this._headers={}}clone(){return new e(this._scheme,this._user,this._host,this._port,JSON.parse(JSON.stringify(this._parameters)),JSON.parse(JSON.stringify(this._headers)))}toString(){let e=[],t=`${this._scheme}:`;this._user&&(t+=`${r.escapeUser(this._user)}@`),t+=this._host,(this._port||this._port===0)&&(t+=`:${this._port}`);for(let e in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,e)&&(t+=`;${e}`,this._parameters[e]!==null&&(t+=`=${this._parameters[e]}`));for(let t in this._headers)if(Object.prototype.hasOwnProperty.call(this._headers,t))for(let n of this._headers[t])e.push(`${t}=${n}`);return e.length>0&&(t+=`?${e.join(`&`)}`),t}toAor(e){let t=`${this._scheme}:`;return this._user&&(t+=`${r.escapeUser(this._user)}@`),t+=this._host,e&&(this._port||this._port===0)&&(t+=`:${this._port}`),t}}})),K=c((e=>{var t=H(),n=G(),r=W();e.str_utf8_length=e=>unescape(encodeURIComponent(e)).length;var i=e.isFunction=e=>e!==void 0&&Object.prototype.toString.call(e)===`[object Function]`;e.isString=e=>e!==void 0&&Object.prototype.toString.call(e)===`[object String]`,e.isDecimal=e=>!isNaN(e)&&parseFloat(e)===parseInt(e,10),e.isEmpty=e=>e===null||e===``||e===void 0||Array.isArray(e)&&e.length===0||typeof e==`number`&&isNaN(e),e.hasMethods=function(e,...t){for(let n of t)if(i(e[n]))return!1;return!0};var a=e.createRandomToken=(e,t=32)=>{let n,r,i=``;for(n=0;n<e;n++)r=Math.random()*t|0,i+=r.toString(t);return i};e.newTag=()=>a(10),e.newUUID=()=>`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)}),e.hostType=e=>{if(e&&(e=r.parse(e,`host`),e!==-1))return e.host_type};var o=e.escapeUser=e=>encodeURIComponent(decodeURIComponent(e)).replace(/%3A/gi,`:`).replace(/%2B/gi,`+`).replace(/%3F/gi,`?`).replace(/%2F/gi,`/`);e.normalizeTarget=(e,r)=>{if(e){if(e instanceof n)return e;if(typeof e==`string`){let i=e.split(`@`),a,s;switch(i.length){case 1:if(!r)return;a=e,s=r;break;case 2:a=i[0],s=i[1];break;default:a=i.slice(0,i.length-1).join(`@`),s=i[i.length-1]}a=a.replace(/^(sips?|tel):/i,``),/^[-.()]*\+?[0-9\-.()]+$/.test(a)&&(a=a.replace(/[-.()]/g,``)),e=`${t.SIP}:${o(a)}@${s}`;let c;return(c=n.parse(e))?c:void 0}}},e.headerize=e=>{let t={"Call-Id":`Call-ID`,Cseq:`CSeq`,"Www-Authenticate":`WWW-Authenticate`},n=e.toLowerCase().replace(/_/g,`-`).split(`-`),r=``,i=n.length,a=0;for(;a<i;a++)a!==0&&(r+=`-`),r+=n[a].charAt(0).toUpperCase()+n[a].substring(1);return t[r]&&(r=t[r]),r},e.sipErrorCause=e=>{for(let n in t.SIP_ERROR_CAUSES)if(t.SIP_ERROR_CAUSES[n].indexOf(e)!==-1)return t.causes[n];return t.causes.SIP_FAILURE_CODE},e.getRandomTestNetIP=()=>{function e(e,t){return Math.floor(Math.random()*(t-e+1)+e)}return`192.0.2.${e(1,254)}`},e.calculateMD5=e=>{function t(e,t){return e<<t|e>>>32-t}function n(e,t){let n=e&2147483648,r=t&2147483648,i=e&1073741824,a=t&1073741824,o=(e&1073741823)+(t&1073741823);return i&a?o^2147483648^n^r:i|a?o&1073741824?o^3221225472^n^r:o^1073741824^n^r:o^n^r}function r(e,t,n){return e&t|~e&n}function i(e,t,n){return e&n|t&~n}function a(e,t,n){return e^t^n}function o(e,t,n){return t^(e|~n)}function s(e,i,a,o,s,c,l){return e=n(e,n(n(r(i,a,o),s),l)),n(t(e,c),i)}function c(e,r,a,o,s,c,l){return e=n(e,n(n(i(r,a,o),s),l)),n(t(e,c),r)}function l(e,r,i,o,s,c,l){return e=n(e,n(n(a(r,i,o),s),l)),n(t(e,c),r)}function u(e,r,i,a,s,c,l){return e=n(e,n(n(o(r,i,a),s),l)),n(t(e,c),r)}function d(e){let t,n=e.length,r=n+8,i=((r-r%64)/64+1)*16,a=Array(i-1),o=0,s=0;for(;s<n;)t=(s-s%4)/4,o=s%4*8,a[t]=a[t]|e.charCodeAt(s)<<o,s++;return t=(s-s%4)/4,o=s%4*8,a[t]=a[t]|128<<o,a[i-2]=n<<3,a[i-1]=n>>>29,a}function f(e){let t=``,n=``,r,i=0;for(;i<=3;i++)r=e>>>i*8&255,n=`0${r.toString(16)}`,t+=n.substr(n.length-2,2);return t}function p(e){let t=``;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r<128?t+=String.fromCharCode(r):r>127&&r<2048?(t+=String.fromCharCode(r>>6|192),t+=String.fromCharCode(r&63|128)):(t+=String.fromCharCode(r>>12|224),t+=String.fromCharCode(r>>6&63|128),t+=String.fromCharCode(r&63|128))}return t}let m=[],h,g,_,v,y,b,x,S,C;for(e=p(e),m=d(e),b=1732584193,x=4023233417,S=2562383102,C=271733878,h=0;h<m.length;h+=16)g=b,_=x,v=S,y=C,b=s(b,x,S,C,m[h+0],7,3614090360),C=s(C,b,x,S,m[h+1],12,3905402710),S=s(S,C,b,x,m[h+2],17,606105819),x=s(x,S,C,b,m[h+3],22,3250441966),b=s(b,x,S,C,m[h+4],7,4118548399),C=s(C,b,x,S,m[h+5],12,1200080426),S=s(S,C,b,x,m[h+6],17,2821735955),x=s(x,S,C,b,m[h+7],22,4249261313),b=s(b,x,S,C,m[h+8],7,1770035416),C=s(C,b,x,S,m[h+9],12,2336552879),S=s(S,C,b,x,m[h+10],17,4294925233),x=s(x,S,C,b,m[h+11],22,2304563134),b=s(b,x,S,C,m[h+12],7,1804603682),C=s(C,b,x,S,m[h+13],12,4254626195),S=s(S,C,b,x,m[h+14],17,2792965006),x=s(x,S,C,b,m[h+15],22,1236535329),b=c(b,x,S,C,m[h+1],5,4129170786),C=c(C,b,x,S,m[h+6],9,3225465664),S=c(S,C,b,x,m[h+11],14,643717713),x=c(x,S,C,b,m[h+0],20,3921069994),b=c(b,x,S,C,m[h+5],5,3593408605),C=c(C,b,x,S,m[h+10],9,38016083),S=c(S,C,b,x,m[h+15],14,3634488961),x=c(x,S,C,b,m[h+4],20,3889429448),b=c(b,x,S,C,m[h+9],5,568446438),C=c(C,b,x,S,m[h+14],9,3275163606),S=c(S,C,b,x,m[h+3],14,4107603335),x=c(x,S,C,b,m[h+8],20,1163531501),b=c(b,x,S,C,m[h+13],5,2850285829),C=c(C,b,x,S,m[h+2],9,4243563512),S=c(S,C,b,x,m[h+7],14,1735328473),x=c(x,S,C,b,m[h+12],20,2368359562),b=l(b,x,S,C,m[h+5],4,4294588738),C=l(C,b,x,S,m[h+8],11,2272392833),S=l(S,C,b,x,m[h+11],16,1839030562),x=l(x,S,C,b,m[h+14],23,4259657740),b=l(b,x,S,C,m[h+1],4,2763975236),C=l(C,b,x,S,m[h+4],11,1272893353),S=l(S,C,b,x,m[h+7],16,4139469664),x=l(x,S,C,b,m[h+10],23,3200236656),b=l(b,x,S,C,m[h+13],4,681279174),C=l(C,b,x,S,m[h+0],11,3936430074),S=l(S,C,b,x,m[h+3],16,3572445317),x=l(x,S,C,b,m[h+6],23,76029189),b=l(b,x,S,C,m[h+9],4,3654602809),C=l(C,b,x,S,m[h+12],11,3873151461),S=l(S,C,b,x,m[h+15],16,530742520),x=l(x,S,C,b,m[h+2],23,3299628645),b=u(b,x,S,C,m[h+0],6,4096336452),C=u(C,b,x,S,m[h+7],10,1126891415),S=u(S,C,b,x,m[h+14],15,2878612391),x=u(x,S,C,b,m[h+5],21,4237533241),b=u(b,x,S,C,m[h+12],6,1700485571),C=u(C,b,x,S,m[h+3],10,2399980690),S=u(S,C,b,x,m[h+10],15,4293915773),x=u(x,S,C,b,m[h+1],21,2240044497),b=u(b,x,S,C,m[h+8],6,1873313359),C=u(C,b,x,S,m[h+15],10,4264355552),S=u(S,C,b,x,m[h+6],15,2734768916),x=u(x,S,C,b,m[h+13],21,1309151649),b=u(b,x,S,C,m[h+4],6,4149444226),C=u(C,b,x,S,m[h+11],10,3174756917),S=u(S,C,b,x,m[h+2],15,718787259),x=u(x,S,C,b,m[h+9],21,3951481745),b=n(b,g),x=n(x,_),S=n(S,v),C=n(C,y);return(f(b)+f(x)+f(S)+f(C)).toLowerCase()},e.closeMediaStream=e=>{if(e)try{let t;if(e.getTracks){t=e.getTracks();for(let e of t)e.stop()}else{t=e.getAudioTracks();for(let e of t)e.stop();t=e.getVideoTracks();for(let e of t)e.stop()}}catch{(typeof e.stop==`function`||typeof e.stop==`object`)&&e.stop()}},e.cloneArray=e=>e&&e.slice()||[],e.cloneObject=(e,t={})=>e&&Object.assign({},e)||t})),q=c(((e,t)=>{var n=typeof Reflect==`object`?Reflect:null,r=n&&typeof n.apply==`function`?n.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},i=n&&typeof n.ownKeys==`function`?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};function a(e){console&&console.warn&&console.warn(e)}var o=Number.isNaN||function(e){return e!==e};function s(){s.init.call(this)}t.exports=s,t.exports.once=y,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var c=10;function l(e){if(typeof e!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof e)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return c},set:function(e){if(typeof e!=`number`||e<0||o(e))throw RangeError(`The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received `+e+`.`);c=e}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if(typeof e!=`number`||e<0||o(e))throw RangeError(`The value of "n" is out of range. It must be a non-negative number. Received `+e+`.`);return this._maxListeners=e,this};function u(e){return e._maxListeners===void 0?s.defaultMaxListeners:e._maxListeners}s.prototype.getMaxListeners=function(){return u(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i=e===`error`,a=this._events;if(a!==void 0)i&&=a.error===void 0;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var s=Error(`Unhandled error.`+(o?` (`+o.message+`)`:``));throw s.context=o,s}var c=a[e];if(c===void 0)return!1;if(typeof c==`function`)r(c,this,t);else for(var l=c.length,u=g(c,l),n=0;n<l;++n)r(u[n],this,t);return!0};function d(e,t,n,r){var i,o,s;if(l(n),o=e._events,o===void 0?(o=e._events=Object.create(null),e._eventsCount=0):(o.newListener!==void 0&&(e.emit(`newListener`,t,n.listener?n.listener:n),o=e._events),s=o[t]),s===void 0)s=o[t]=n,++e._eventsCount;else if(typeof s==`function`?s=o[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),i=u(e),i>0&&s.length>i&&!s.warned){s.warned=!0;var c=Error(`Possible EventEmitter memory leak detected. `+s.length+` `+String(t)+` listeners added. Use emitter.setMaxListeners() to increase limit`);c.name=`MaxListenersExceededWarning`,c.emitter=e,c.type=t,c.count=s.length,a(c)}return e}s.prototype.addListener=function(e,t){return d(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return d(this,e,t,!0)};function f(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function p(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=f.bind(r);return i.listener=n,r.wrapFn=i,i}s.prototype.once=function(e,t){return l(t),this.on(e,p(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return l(t),this.prependListener(e,p(this,e,t)),this},s.prototype.removeListener=function(e,t){var n,r,i,a,o;if(l(t),r=this._events,r===void 0||(n=r[e],n===void 0))return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit(`removeListener`,e,n.listener||t));else if(typeof n!=`function`){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,i=a;break}if(i<0)return this;i===0?n.shift():_(n,i),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit(`removeListener`,e,o||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,n=this._events,r;if(n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var i=Object.keys(n),a;for(r=0;r<i.length;++r)a=i[r],a!==`removeListener`&&this.removeAllListeners(a);return this.removeAllListeners(`removeListener`),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t==`function`)this.removeListener(e,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this};function m(e,t,n){var r=e._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i==`function`?n?[i.listener||i]:[i]:n?v(i):g(i,i.length)}s.prototype.listeners=function(e){return m(this,e,!0)},s.prototype.rawListeners=function(e){return m(this,e,!1)},s.listenerCount=function(e,t){return typeof e.listenerCount==`function`?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h;function h(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n==`function`)return 1;if(n!==void 0)return n.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?i(this._events):[]};function g(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function _(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function v(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function y(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,a),r(n)}function a(){typeof e.removeListener==`function`&&e.removeListener(`error`,i),n([].slice.call(arguments))}x(e,t,a,{once:!0}),t!==`error`&&b(e,i,{once:!0})})}function b(e,t,n){typeof e.on==`function`&&x(e,`error`,t,n)}function x(e,t,n,r){if(typeof e.on==`function`)r.once?e.once(t,n):e.on(t,n);else if(typeof e.addEventListener==`function`)e.addEventListener(t,function i(a){r.once&&e.removeEventListener(t,i),n(a)});else throw TypeError(`The "emitter" argument must be of type EventEmitter. Received type `+typeof e)}})),Bt=c(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),Vt=c(((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=Bt(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}t.exports=n})),Ht=c(((e,t)=>{e.formatArgs=r,e.save=i,e.load=a,e.useColors=n,e.storage=o(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=`#0000CC.#0000FF.#0033CC.#0033FF.#0066CC.#0066FF.#0099CC.#0099FF.#00CC00.#00CC33.#00CC66.#00CC99.#00CCCC.#00CCFF.#3300CC.#3300FF.#3333CC.#3333FF.#3366CC.#3366FF.#3399CC.#3399FF.#33CC00.#33CC33.#33CC66.#33CC99.#33CCCC.#33CCFF.#6600CC.#6600FF.#6633CC.#6633FF.#66CC00.#66CC33.#9900CC.#9900FF.#9933CC.#9933FF.#99CC00.#99CC33.#CC0000.#CC0033.#CC0066.#CC0099.#CC00CC.#CC00FF.#CC3300.#CC3333.#CC3366.#CC3399.#CC33CC.#CC33FF.#CC6600.#CC6633.#CC9900.#CC9933.#CCCC00.#CCCC33.#FF0000.#FF0033.#FF0066.#FF0099.#FF00CC.#FF00FF.#FF3300.#FF3333.#FF3366.#FF3399.#FF33CC.#FF33FF.#FF6600.#FF6633.#FF9900.#FF9933.#FFCC00.#FFCC33`.split(`.`);function n(){if(typeof window<`u`&&window.process&&(window.process.type===`renderer`||window.process.__nwjs))return!0;if(typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<`u`&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<`u`&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<`u`&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function i(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function a(){let t;try{t=e.storage.getItem(`debug`)||e.storage.getItem(`DEBUG`)}catch{}return!t&&typeof process<`u`&&`env`in process&&(t=process.env.DEBUG),t}function o(){try{return localStorage}catch{}}t.exports=Vt()(e);var{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),J=c(((e,t)=>{var n=Ht(),r=`JsSIP`;t.exports=class{constructor(e){e?(this._debug=n.default(`${r}:${e}`),this._warn=n.default(`${r}:WARN:${e}`),this._error=n.default(`${r}:ERROR:${e}`)):(this._debug=n.default(r),this._warn=n.default(`${r}:WARN`),this._error=n.default(`${r}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}}})),Ut=c(((e,t)=>{var n=t.exports={v:[{name:`version`,reg:/^(\d*)$/}],o:[{name:`origin`,reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:[`username`,`sessionId`,`sessionVersion`,`netType`,`ipVer`,`address`],format:`%s %s %d %s IP%d %s`}],s:[{name:`name`}],i:[{name:`description`}],u:[{name:`uri`}],e:[{name:`email`}],p:[{name:`phone`}],z:[{name:`timezones`}],r:[{name:`repeats`}],t:[{name:`timing`,reg:/^(\d*) (\d*)/,names:[`start`,`stop`],format:`%d %d`}],c:[{name:`connection`,reg:/^IN IP(\d) (\S*)/,names:[`version`,`ip`],format:`IN IP%d %s`}],b:[{push:`bandwidth`,reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:[`type`,`limit`],format:`%s:%s`}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:[`type`,`port`,`protocol`,`payloads`],format:`%s %d %s %s`}],a:[{push:`rtp`,reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:[`payload`,`codec`,`rate`,`encoding`],format:function(e){return e.encoding?`rtpmap:%d %s/%s/%s`:e.rate?`rtpmap:%d %s/%s`:`rtpmap:%d %s`}},{push:`fmtp`,reg:/^fmtp:(\d*) ([\S| ]*)/,names:[`payload`,`config`],format:`fmtp:%d %s`},{name:`control`,reg:/^control:(.*)/,format:`control:%s`},{name:`rtcp`,reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:[`port`,`netType`,`ipVer`,`address`],format:function(e){return e.address==null?`rtcp:%d`:`rtcp:%d %s IP%d %s`}},{push:`rtcpFbTrrInt`,reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:[`payload`,`value`],format:`rtcp-fb:%s trr-int %d`},{push:`rtcpFb`,reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:[`payload`,`type`,`subtype`],format:function(e){return e.subtype==null?`rtcp-fb:%s %s`:`rtcp-fb:%s %s %s`}},{push:`ext`,reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:[`value`,`direction`,`encrypt-uri`,`uri`,`config`],format:function(e){return`extmap:%d`+(e.direction?`/%s`:`%v`)+(e[`encrypt-uri`]?` %s`:`%v`)+` %s`+(e.config?` %s`:``)}},{name:`extmapAllowMixed`,reg:/^(extmap-allow-mixed)/},{push:`crypto`,reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:[`id`,`suite`,`config`,`sessionConfig`],format:function(e){return e.sessionConfig==null?`crypto:%d %s %s`:`crypto:%d %s %s %s`}},{name:`setup`,reg:/^setup:(\w*)/,format:`setup:%s`},{name:`connectionType`,reg:/^connection:(new|existing)/,format:`connection:%s`},{name:`mid`,reg:/^mid:([^\s]*)/,format:`mid:%s`},{name:`msid`,reg:/^msid:(.*)/,format:`msid:%s`},{name:`ptime`,reg:/^ptime:(\d*(?:\.\d*)*)/,format:`ptime:%d`},{name:`maxptime`,reg:/^maxptime:(\d*(?:\.\d*)*)/,format:`maxptime:%d`},{name:`direction`,reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:`icelite`,reg:/^(ice-lite)/},{name:`iceUfrag`,reg:/^ice-ufrag:(\S*)/,format:`ice-ufrag:%s`},{name:`icePwd`,reg:/^ice-pwd:(\S*)/,format:`ice-pwd:%s`},{name:`fingerprint`,reg:/^fingerprint:(\S*) (\S*)/,names:[`type`,`hash`],format:`fingerprint:%s %s`},{push:`candidates`,reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:[`foundation`,`component`,`transport`,`priority`,`ip`,`port`,`type`,`raddr`,`rport`,`tcptype`,`generation`,`network-id`,`network-cost`],format:function(e){var t=`candidate:%s %d %s %d %s %d typ %s`;return t+=e.raddr==null?`%v%v`:` raddr %s rport %d`,t+=e.tcptype==null?`%v`:` tcptype %s`,e.generation!=null&&(t+=` generation %d`),t+=e[`network-id`]==null?`%v`:` network-id %d`,t+=e[`network-cost`]==null?`%v`:` network-cost %d`,t}},{name:`endOfCandidates`,reg:/^(end-of-candidates)/},{name:`remoteCandidates`,reg:/^remote-candidates:(.*)/,format:`remote-candidates:%s`},{name:`iceOptions`,reg:/^ice-options:(\S*)/,format:`ice-options:%s`},{push:`ssrcs`,reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:[`id`,`attribute`,`value`],format:function(e){var t=`ssrc:%d`;return e.attribute!=null&&(t+=` %s`,e.value!=null&&(t+=`:%s`)),t}},{push:`ssrcGroups`,reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:[`semantics`,`ssrcs`],format:`ssrc-group:%s %s`},{name:`msidSemantic`,reg:/^msid-semantic:\s?(\w*) (\S*)/,names:[`semantic`,`token`],format:`msid-semantic: %s %s`},{push:`groups`,reg:/^group:(\w*) (.*)/,names:[`type`,`mids`],format:`group:%s %s`},{name:`rtcpMux`,reg:/^(rtcp-mux)/},{name:`rtcpRsize`,reg:/^(rtcp-rsize)/},{name:`sctpmap`,reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:[`sctpmapNumber`,`app`,`maxMessageSize`],format:function(e){return e.maxMessageSize==null?`sctpmap:%s %s`:`sctpmap:%s %s %s`}},{name:`xGoogleFlag`,reg:/^x-google-flag:([^\s]*)/,format:`x-google-flag:%s`},{push:`rids`,reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:[`id`,`direction`,`params`],format:function(e){return e.params?`rid:%s %s %s`:`rid:%s %s`}},{push:`imageattrs`,reg:RegExp(`^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?`),names:[`pt`,`dir1`,`attrs1`,`dir2`,`attrs2`],format:function(e){return`imageattr:%s %s %s`+(e.dir2?` %s %s`:``)}},{name:`simulcast`,reg:RegExp(`^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$`),names:[`dir1`,`list1`,`dir2`,`list2`],format:function(e){return`simulcast:%s %s`+(e.dir2?` %s %s`:``)}},{name:`simulcast_03`,reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:[`value`],format:`simulcast: %s`},{name:`framerate`,reg:/^framerate:(\d+(?:$|\.\d+))/,format:`framerate:%s`},{name:`sourceFilter`,reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:[`filterMode`,`netType`,`addressTypes`,`destAddress`,`srcList`],format:`source-filter: %s %s %s %s %s`},{name:`bundleOnly`,reg:/^(bundle-only)/},{name:`label`,reg:/^label:(.+)/,format:`label:%s`},{name:`sctpPort`,reg:/^sctp-port:(\d+)$/,format:`sctp-port:%s`},{name:`maxMessageSize`,reg:/^max-message-size:(\d+)$/,format:`max-message-size:%s`},{push:`tsRefClocks`,reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:[`clksrc`,`clksrcExt`],format:function(e){return`ts-refclk:%s`+(e.clksrcExt==null?``:`=%s`)}},{name:`mediaClk`,reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:[`id`,`mediaClockName`,`mediaClockValue`,`rateNumerator`,`rateDenominator`],format:function(e){var t=`mediaclk:`;return t+=e.id==null?`%v%s`:`id=%s %s`,t+=e.mediaClockValue==null?``:`=%s`,t+=e.rateNumerator==null?``:` rate=%s`,t+=e.rateDenominator==null?``:`/%s`,t}},{name:`keywords`,reg:/^keywds:(.+)$/,format:`keywds:%s`},{name:`content`,reg:/^content:(.+)/,format:`content:%s`},{name:`bfcpFloorCtrl`,reg:/^floorctrl:(c-only|s-only|c-s)/,format:`floorctrl:%s`},{name:`bfcpConfId`,reg:/^confid:(\d+)/,format:`confid:%s`},{name:`bfcpUserId`,reg:/^userid:(\d+)/,format:`userid:%s`},{name:`bfcpFloorId`,reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:[`id`,`mStream`],format:`floorid:%s mstrm:%s`},{push:`invalid`,names:[`value`]}]};Object.keys(n).forEach(function(e){n[e].forEach(function(e){e.reg||=/(.*)/,e.format||=`%s`})})})),Wt=c((e=>{var t=function(e){return String(Number(e))===e?Number(e):e},n=function(e,n,r,i){if(i&&!r)n[i]=t(e[1]);else for(var a=0;a<r.length;a+=1)e[a+1]!=null&&(n[r[a]]=t(e[a+1]))},r=function(e,t,r){var i=e.name&&e.names;e.push&&!t[e.push]?t[e.push]=[]:i&&!t[e.name]&&(t[e.name]={});var a=e.push?{}:i?t[e.name]:t;n(r.match(e.reg),a,e.names,e.name),e.push&&t[e.push].push(a)},i=Ut(),a=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},n=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(a).forEach(function(e){var t=e[0],a=e.slice(2);t===`m`&&(n.push({rtp:[],fmtp:[]}),o=n[n.length-1]);for(var s=0;s<(i[t]||[]).length;s+=1){var c=i[t][s];if(c.reg.test(a))return r(c,o,a)}}),t.media=n,t};var o=function(e,n){var r=n.split(/=(.+)/,2);return r.length===2?e[r[0]]=t(r[1]):r.length===1&&n.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(` `).map(Number)},e.parseRemoteCandidates=function(e){for(var n=[],r=e.split(` `).map(t),i=0;i<r.length;i+=3)n.push({component:r[i],ip:r[i+1],port:r[i+2]});return n},e.parseImageAttributes=function(e){return e.split(` `).map(function(e){return e.substring(1,e.length-1).split(`,`).reduce(o,{})})},e.parseSimulcastStreamList=function(e){return e.split(`;`).map(function(e){return e.split(`,`).map(function(e){var n,r=!1;return e[0]===`~`?(n=t(e.substring(1,e.length)),r=!0):n=t(e),{scid:n,paused:r}})})}})),Gt=c(((e,t)=>{var n=Ut(),r=/%[sdv%]/g,i=function(e){var t=1,n=arguments,i=n.length;return e.replace(r,function(e){if(t>=i)return e;var r=n[t];switch(t+=1,e){case`%%`:return`%`;case`%s`:return String(r);case`%d`:return Number(r);case`%v`:return``}})},a=function(e,t,n){var r=t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format,a=[e+`=`+r];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?a.push(n[t.name][s]):a.push(n[t.names[o]])}else a.push(n[t.name]);return i.apply(null,a)},o=[`v`,`o`,`s`,`i`,`u`,`e`,`p`,`c`,`b`,`t`,`r`,`z`,`a`],s=[`i`,`c`,`b`,`a`];t.exports=function(e,t){t||={},e.version??=0,e.name??=` `,e.media.forEach(function(e){e.payloads??=``});var r=t.outerOrder||o,i=t.innerOrder||s,c=[];return r.forEach(function(t){n[t].forEach(function(n){n.name in e&&e[n.name]!=null?c.push(a(t,n,e)):n.push in e&&e[n.push]!=null&&e[n.push].forEach(function(e){c.push(a(t,n,e))})})}),e.media.forEach(function(e){c.push(a(`m`,n.m[0],e)),i.forEach(function(t){n[t].forEach(function(n){n.name in e&&e[n.name]!=null?c.push(a(t,n,e)):n.push in e&&e[n.push]!=null&&e[n.push].forEach(function(e){c.push(a(t,n,e))})})})}),c.join(`\r
|
|
5
5
|
`)+`\r
|
|
6
|
-
`}})),Kt=c((e=>{var t=Wt(),n=Gt();e.grammar=Ut(),e.write=n,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList})),
|
|
6
|
+
`}})),Kt=c((e=>{var t=Wt(),n=Gt();e.grammar=Ut(),e.write=n,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList})),Y=c(((e,t)=>{var n=Kt(),r=J(),i=H(),a=K(),o=zt(),s=W(),c=new r(`SIPMessage`),l=class e{constructor(e,t,n,r,s,c){if(!e||!t||!n)return null;r||={},this.ua=n,this.headers={},this.method=e,this.ruri=t,this.body=c,this.extraHeaders=a.cloneArray(s),this.ua.configuration.extra_headers&&(this.extraHeaders=this.extraHeaders.concat(this.ua.configuration.extra_headers)),r.route_set?this.setHeader(`route`,r.route_set):n.configuration.use_preloaded_route&&this.setHeader(`route`,`<${n.transport.sip_uri};lr>`),this.setHeader(`via`,``),this.setHeader(`max-forwards`,i.MAX_FORWARDS);let l=r.to_uri||t,u=r.to_tag?{tag:r.to_tag}:null,d=r.to_display_name===void 0?null:r.to_display_name;this.to=new o(l,d,u),this.setHeader(`to`,this.to.toString());let f=r.from_uri||n.configuration.uri,p={tag:r.from_tag||a.newTag()},m;m=r.from_display_name===void 0?n.configuration.display_name?n.configuration.display_name:null:r.from_display_name,this.from=new o(f,m,p),this.setHeader(`from`,this.from.toString());let h=r.call_id||n.configuration.jssip_id+a.createRandomToken(15);this.call_id=h,this.setHeader(`call-id`,h);let g=r.cseq||Math.floor(Math.random()*1e4);this.cseq=g,this.setHeader(`cseq`,`${g} ${e}`)}setHeader(e,t){let n=RegExp(`^\\s*${e}\\s*:`,`i`);for(let e=0;e<this.extraHeaders.length;e++)n.test(this.extraHeaders[e])&&this.extraHeaders.splice(e,1);this.headers[a.headerize(e)]=Array.isArray(t)?t:[t]}getHeader(e){let t=this.headers[a.headerize(e)];if(t){if(t[0])return t[0]}else{let t=RegExp(`^\\s*${e}\\s*:`,`i`);for(let e of this.extraHeaders)if(t.test(e))return e.substring(e.indexOf(`:`)+1).trim()}}getHeaders(e){let t=this.headers[a.headerize(e)],n=[];if(t){for(let e of t)n.push(e);return n}{let t=RegExp(`^\\s*${e}\\s*:`,`i`);for(let e of this.extraHeaders)t.test(e)&&n.push(e.substring(e.indexOf(`:`)+1).trim());return n}}hasHeader(e){if(this.headers[a.headerize(e)])return!0;{let t=RegExp(`^\\s*${e}\\s*:`,`i`);for(let e of this.extraHeaders)if(t.test(e))return!0}return!1}parseSDP(e){return!e&&this.sdp||(this.sdp=n.parse(this.body||``)),this.sdp}toString(){let e=`${this.method} ${this.ruri} SIP/2.0\r\n`;for(let t in this.headers)if(Object.prototype.hasOwnProperty.call(this.headers,t))for(let n of this.headers[t])e+=`${t}: ${n}\r\n`;for(let t of this.extraHeaders)e+=`${t.trim()}\r\n`;let t=[];switch(this.method){case i.REGISTER:t.push(`path`,`gruu`);break;case i.INVITE:this.ua.configuration.session_timers&&t.push(`timer`),(this.ua.contact.pub_gruu||this.ua.contact.temp_gruu)&&t.push(`gruu`),t.push(`ice`,`replaces`);break;case i.UPDATE:this.ua.configuration.session_timers&&t.push(`timer`),t.push(`ice`)}t.push(`outbound`);let n=this.ua.configuration.user_agent||i.USER_AGENT;if(e+=`Allow: ${i.ALLOWED_METHODS}\r\n`,e+=`Supported: ${t}\r\n`,e+=`User-Agent: ${n}\r\n`,this.body){let t=a.str_utf8_length(this.body);e+=`Content-Length: ${t}\r\n\r\n`,e+=this.body}else e+=`Content-Length: 0\r
|
|
7
7
|
\r
|
|
8
8
|
`;return e}clone(){let t=new e(this.method,this.ruri,this.ua);return Object.keys(this.headers).forEach(function(e){t.headers[e]=this.headers[e].slice()},this),t.body=this.body,t.extraHeaders=a.cloneArray(this.extraHeaders),t.to=this.to,t.from=this.from,t.call_id=this.call_id,t.cseq=this.cseq,t}},u=class e extends l{constructor(e,t,n,r,a){super(i.INVITE,e,t,n,r,a),this.transaction=null}cancel(e){this.transaction.cancel(e)}clone(){let t=new e(this.ruri,this.ua);return Object.keys(this.headers).forEach(function(e){t.headers[e]=this.headers[e].slice()},this),t.body=this.body,t.extraHeaders=a.cloneArray(this.extraHeaders),t.to=this.to,t.from=this.from,t.call_id=this.call_id,t.cseq=this.cseq,t.transaction=this.transaction,t}},d=class{constructor(){this.data=null,this.headers=null,this.method=null,this.via=null,this.via_branch=null,this.call_id=null,this.cseq=null,this.from=null,this.from_tag=null,this.to=null,this.to_tag=null,this.body=null,this.sdp=null}addHeader(e,t){let n={raw:t};e=a.headerize(e),this.headers[e]?this.headers[e].push(n):this.headers[e]=[n]}getHeader(e){let t=this.headers[a.headerize(e)];if(t){if(t[0])return t[0].raw}else return}getHeaders(e){let t=this.headers[a.headerize(e)],n=[];if(!t)return[];for(let e of t)n.push(e.raw);return n}hasHeader(e){return!!this.headers[a.headerize(e)]}parseHeader(e,t=0){if(e=a.headerize(e),!this.headers[e]){c.debug(`header "${e}" not present`);return}if(t>=this.headers[e].length){c.debug(`not so many "${e}" headers present`);return}let n=this.headers[e][t],r=n.raw;if(n.parsed)return n.parsed;let i=s.parse(r,e.replace(/-/g,`_`));if(i===-1){this.headers[e].splice(t,1),c.debug(`error parsing "${e}" header field with value "${r}"`);return}return n.parsed=i,i}s(e,t){return this.parseHeader(e,t)}setHeader(e,t){let n={raw:t};this.headers[a.headerize(e)]=[n]}parseSDP(e){return!e&&this.sdp||(this.sdp=n.parse(this.body||``)),this.sdp}toString(){return this.data}};t.exports={OutgoingRequest:l,InitialOutgoingInviteRequest:u,IncomingRequest:class extends d{constructor(e){super(),this.ua=e,this.headers={},this.ruri=null,this.transport=null,this.server_transaction=null}reply(e,t,n,r,o,s){let c=[],l=this.getHeader(`To`);if(e||=null,t||=null,!e||e<100||e>699)throw TypeError(`Invalid status_code: ${e}`);if(t&&typeof t!=`string`&&!(t instanceof String))throw TypeError(`Invalid reason_phrase: ${t}`);t=t||i.REASON_PHRASE[e]||``,n=a.cloneArray(n),this.ua.configuration.extra_headers&&(n=n.concat(this.ua.configuration.extra_headers));let u=`SIP/2.0 ${e} ${t}\r\n`;if(this.method===i.INVITE&&e>100&&e<=200){let e=this.getHeaders(`record-route`);for(let t of e)u+=`Record-Route: ${t}\r\n`}let d=this.getHeaders(`via`);for(let e of d)u+=`Via: ${e}\r\n`;!this.to_tag&&e>100?l+=`;tag=${a.newTag()}`:this.to_tag&&!this.s(`to`).hasParam(`tag`)&&(l+=`;tag=${this.to_tag}`),u+=`To: ${l}\r\n`,u+=`From: ${this.getHeader(`From`)}\r\n`,u+=`Call-ID: ${this.call_id}\r\n`,u+=`CSeq: ${this.cseq} ${this.method}\r\n`;for(let e of n)u+=`${e.trim()}\r\n`;switch(this.method){case i.INVITE:this.ua.configuration.session_timers&&c.push(`timer`),(this.ua.contact.pub_gruu||this.ua.contact.temp_gruu)&&c.push(`gruu`),c.push(`ice`,`replaces`);break;case i.UPDATE:this.ua.configuration.session_timers&&c.push(`timer`),r&&c.push(`ice`),c.push(`replaces`)}if(c.push(`outbound`),this.method===i.OPTIONS?(u+=`Allow: ${i.ALLOWED_METHODS}\r\n`,u+=`Accept: ${i.ACCEPTED_BODY_TYPES}\r\n`):e===405?u+=`Allow: ${i.ALLOWED_METHODS}\r\n`:e===415&&(u+=`Accept: ${i.ACCEPTED_BODY_TYPES}\r\n`),u+=`Supported: ${c}\r\n`,r){let e=a.str_utf8_length(r);u+=`Content-Type: application/sdp\r
|
|
9
9
|
`,u+=`Content-Length: ${e}\r\n\r\n`,u+=r}else u+=`Content-Length: 0\r
|
|
10
10
|
\r
|
|
11
11
|
`;this.server_transaction.receiveResponse(e,u,o,s)}reply_sl(e=null,t=null){let n=this.getHeaders(`via`);if(!e||e<100||e>699)throw TypeError(`Invalid status_code: ${e}`);if(t&&typeof t!=`string`&&!(t instanceof String))throw TypeError(`Invalid reason_phrase: ${t}`);t=t||i.REASON_PHRASE[e]||``;let r=`SIP/2.0 ${e} ${t}\r\n`;for(let e of n)r+=`Via: ${e}\r\n`;let o=this.getHeader(`To`);if(!this.to_tag&&e>100?o+=`;tag=${a.newTag()}`:this.to_tag&&!this.s(`to`).hasParam(`tag`)&&(o+=`;tag=${this.to_tag}`),r+=`To: ${o}\r\n`,r+=`From: ${this.getHeader(`From`)}\r\n`,r+=`Call-ID: ${this.call_id}\r\n`,r+=`CSeq: ${this.cseq} ${this.method}\r\n`,this.ua.configuration.extra_headers)for(let e of this.ua.configuration.extra_headers)r+=`${e.trim()}\r\n`;r+=`Content-Length: 0\r
|
|
12
12
|
\r
|
|
13
|
-
`,this.transport.send(r)}},IncomingResponse:class extends d{constructor(){super(),this.headers={},this.status_code=null,this.reason_phrase=null}}}})),qt=c(((e,t)=>{var n=q(),r=G(),i=new n(`DigestAuthentication`);t.exports=class{constructor(e){this._credentials=e,this._cnonce=null,this._nc=0,this._ncHex=`00000000`,this._algorithm=null,this._realm=null,this._nonce=null,this._opaque=null,this._stale=null,this._qop=null,this._method=null,this._uri=null,this._ha1=null,this._response=null}get(e){switch(e){case`realm`:return this._realm;case`ha1`:return this._ha1;default:i.warn(`get() | cannot get "%s" parameter`,e);return}}authenticate({method:e,ruri:t,body:n},a,o=null){if(this._algorithm=a.algorithm,this._realm=a.realm,this._nonce=a.nonce,this._opaque=a.opaque,this._stale=a.stale,this._algorithm){if(this._algorithm!==`MD5`)return i.warn(`authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted`),!1}else this._algorithm=`MD5`;if(!this._nonce)return i.warn(`authenticate() | challenge without Digest nonce, authentication aborted`),!1;if(!this._realm)return i.warn(`authenticate() | challenge without Digest realm, authentication aborted`),!1;if(!this._credentials.password){if(!this._credentials.ha1)return i.warn(`authenticate() | no plain SIP password nor ha1 provided, authentication aborted`),!1;if(this._credentials.realm!==this._realm)return i.warn('authenticate() | no plain SIP password, and stored `realm` does not match the given `realm`, cannot authenticate [stored:"%s", given:"%s"]',this._credentials.realm,this._realm),!1}if(a.qop){if(a.qop.indexOf(`auth-int`)>-1)this._qop=`auth-int`;else if(a.qop.indexOf(`auth`)>-1)this._qop=`auth`;else return i.warn(`authenticate() | challenge without Digest qop different than "auth" or "auth-int", authentication aborted`),!1}else this._qop=null;this._method=e,this._uri=t,this._cnonce=o||r.createRandomToken(12),this._nc+=1;let s=Number(this._nc).toString(16);this._ncHex=`00000000`.substr(0,8-s.length)+s,this._nc===4294967296&&(this._nc=1,this._ncHex=`00000001`),this._ha1=this._credentials.password?r.calculateMD5(`${this._credentials.username}:${this._realm}:${this._credentials.password}`):this._credentials.ha1;let c,l;return this._qop===`auth`?(c=`${this._method}:${this._uri}`,l=r.calculateMD5(c),i.debug(`authenticate() | using qop=auth [a2:"%s"]`,c),this._response=r.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth:${l}`)):this._qop===`auth-int`?(c=`${this._method}:${this._uri}:${r.calculateMD5(n||``)}`,l=r.calculateMD5(c),i.debug(`authenticate() | using qop=auth-int [a2:"%s"]`,c),this._response=r.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth-int:${l}`)):this._qop===null&&(c=`${this._method}:${this._uri}`,l=r.calculateMD5(c),i.debug(`authenticate() | using qop=null [a2:"%s"]`,c),this._response=r.calculateMD5(`${this._ha1}:${this._nonce}:${l}`)),i.debug(`authenticate() | response generated`),!0}toString(){let e=[];if(!this._response)throw Error(`response field does not exist, cannot generate Authorization header`);return e.push(`algorithm=${this._algorithm}`),e.push(`username="${this._credentials.username}"`),e.push(`realm="${this._realm}"`),e.push(`nonce="${this._nonce}"`),e.push(`uri="${this._uri}"`),e.push(`response="${this._response}"`),this._opaque&&e.push(`opaque="${this._opaque}"`),this._qop&&(e.push(`qop=${this._qop}`),e.push(`cnonce="${this._cnonce}"`),e.push(`nc=${this._ncHex}`)),`Digest ${e.join(`, `)}`}}})),Jt=c(((e,t)=>{var n=500;t.exports={T1:n,T2:4e3,T4:5e3,TIMER_B:64*n,TIMER_D:0,TIMER_F:64*n,TIMER_H:64*n,TIMER_I:0,TIMER_J:0,TIMER_K:0,TIMER_L:64*n,TIMER_M:64*n,PROVISIONAL_RESPONSE_INTERVAL:6e4}})),Y=c(((e,t)=>{var n=K().EventEmitter,r=q(),i=V(),a=J(),o=Jt(),s=new r(`NonInviteClientTransaction`),c=new r(`InviteClientTransaction`),l=new r(`AckClientTransaction`),u=new r(`NonInviteServerTransaction`),d=new r(`InviteServerTransaction`),f={STATUS_TRYING:1,STATUS_PROCEEDING:2,STATUS_CALLING:3,STATUS_ACCEPTED:4,STATUS_COMPLETED:5,STATUS_TERMINATED:6,STATUS_CONFIRMED:7,NON_INVITE_CLIENT:`nict`,NON_INVITE_SERVER:`nist`,INVITE_CLIENT:`ict`,INVITE_SERVER:`ist`},p=class extends n{constructor(e,t,n,r){super(),this.type=f.NON_INVITE_CLIENT,this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.ua=e,this.transport=t,this.request=n,this.eventHandlers=r;let i=`SIP/2.0/${t.via_transport}`;i+=` ${e.configuration.via_host};branch=${this.id}`,this.request.setHeader(`via`,i),this.ua.newTransaction(this)}get C(){return f}stateChanged(e){this.state=e,this.emit(`stateChanged`)}send(){this.stateChanged(f.STATUS_TRYING),this.F=setTimeout(()=>{this.timer_F()},o.TIMER_F),this.transport.send(this.request)||this.onTransportError()}onTransportError(){s.debug(`transport error occurred, deleting transaction ${this.id}`),clearTimeout(this.F),clearTimeout(this.K),this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onTransportError()}timer_F(){s.debug(`Timer F expired for transaction ${this.id}`),this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout()}timer_K(){this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this)}receiveResponse(e){let t=e.status_code;if(t<200)switch(this.state){case f.STATUS_TRYING:case f.STATUS_PROCEEDING:this.stateChanged(f.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(e)}else switch(this.state){case f.STATUS_TRYING:case f.STATUS_PROCEEDING:this.stateChanged(f.STATUS_COMPLETED),clearTimeout(this.F),t===408?this.eventHandlers.onRequestTimeout():this.eventHandlers.onReceiveResponse(e),this.K=setTimeout(()=>{this.timer_K()},o.TIMER_K);break;case f.STATUS_COMPLETED:}}},m=class extends n{constructor(e,t,n,r){super(),this.type=f.INVITE_CLIENT,this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.ua=e,this.transport=t,this.request=n,this.eventHandlers=r,n.transaction=this;let i=`SIP/2.0/${t.via_transport}`;i+=` ${e.configuration.via_host};branch=${this.id}`,this.request.setHeader(`via`,i),this.ua.newTransaction(this)}get C(){return f}stateChanged(e){this.state=e,this.emit(`stateChanged`)}send(){this.stateChanged(f.STATUS_CALLING),this.B=setTimeout(()=>{this.timer_B()},o.TIMER_B),this.transport.send(this.request)||this.onTransportError()}onTransportError(){clearTimeout(this.B),clearTimeout(this.D),clearTimeout(this.M),this.state!==f.STATUS_ACCEPTED&&(c.debug(`transport error occurred, deleting transaction ${this.id}`),this.eventHandlers.onTransportError()),this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_M(){c.debug(`Timer M expired for transaction ${this.id}`),this.state===f.STATUS_ACCEPTED&&(clearTimeout(this.B),this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this))}timer_B(){c.debug(`Timer B expired for transaction ${this.id}`),this.state===f.STATUS_CALLING&&(this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout())}timer_D(){c.debug(`Timer D expired for transaction ${this.id}`),clearTimeout(this.B),this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this)}sendACK(e){let t=new a.OutgoingRequest(i.ACK,this.request.ruri,this.ua,{route_set:this.request.getHeaders(`route`),call_id:this.request.getHeader(`call-id`),cseq:this.request.cseq});t.setHeader(`from`,this.request.getHeader(`from`)),t.setHeader(`via`,this.request.getHeader(`via`)),t.setHeader(`to`,e.getHeader(`to`)),this.D=setTimeout(()=>{this.timer_D()},o.TIMER_D),this.transport.send(t)}cancel(e){if(this.state!==f.STATUS_PROCEEDING)return;let t=new a.OutgoingRequest(i.CANCEL,this.request.ruri,this.ua,{route_set:this.request.getHeaders(`route`),call_id:this.request.getHeader(`call-id`),cseq:this.request.cseq});t.setHeader(`from`,this.request.getHeader(`from`)),t.setHeader(`via`,this.request.getHeader(`via`)),t.setHeader(`to`,this.request.getHeader(`to`)),e&&t.setHeader(`reason`,e),this.transport.send(t)}receiveResponse(e){let t=e.status_code;if(t>=100&&t<=199)switch(this.state){case f.STATUS_CALLING:this.stateChanged(f.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(e);break;case f.STATUS_PROCEEDING:this.eventHandlers.onReceiveResponse(e)}else if(t>=200&&t<=299)switch(this.state){case f.STATUS_CALLING:case f.STATUS_PROCEEDING:this.stateChanged(f.STATUS_ACCEPTED),this.M=setTimeout(()=>{this.timer_M()},o.TIMER_M),this.eventHandlers.onReceiveResponse(e);break;case f.STATUS_ACCEPTED:this.eventHandlers.onReceiveResponse(e)}else if(t>=300&&t<=699)switch(this.state){case f.STATUS_CALLING:case f.STATUS_PROCEEDING:this.stateChanged(f.STATUS_COMPLETED),this.sendACK(e),this.eventHandlers.onReceiveResponse(e);break;case f.STATUS_COMPLETED:this.sendACK(e)}}},h=class extends n{constructor(e,t,n,r){super(),this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.transport=t,this.request=n,this.eventHandlers=r;let i=`SIP/2.0/${t.via_transport}`;i+=` ${e.configuration.via_host};branch=${this.id}`,this.request.setHeader(`via`,i)}get C(){return f}send(){this.transport.send(this.request)||this.onTransportError()}onTransportError(){l.debug(`transport error occurred for transaction ${this.id}`),this.eventHandlers.onTransportError()}},g=class extends n{constructor(e,t,n){super(),this.type=f.NON_INVITE_SERVER,this.id=n.via_branch,this.ua=e,this.transport=t,this.request=n,this.last_response=``,n.server_transaction=this,this.state=f.STATUS_TRYING,e.newTransaction(this)}get C(){return f}stateChanged(e){this.state=e,this.emit(`stateChanged`)}timer_J(){u.debug(`Timer J expired for transaction ${this.id}`),this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this)}onTransportError(){this.transportError||(this.transportError=!0,u.debug(`transport error occurred, deleting transaction ${this.id}`),clearTimeout(this.J),this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this))}receiveResponse(e,t,n,r){if(e===100)switch(this.state){case f.STATUS_TRYING:this.stateChanged(f.STATUS_PROCEEDING),this.transport.send(t)||this.onTransportError();break;case f.STATUS_PROCEEDING:this.last_response=t,this.transport.send(t)?n&&n():(this.onTransportError(),r&&r())}else if(e>=200&&e<=699)switch(this.state){case f.STATUS_TRYING:case f.STATUS_PROCEEDING:this.stateChanged(f.STATUS_COMPLETED),this.last_response=t,this.J=setTimeout(()=>{this.timer_J()},o.TIMER_J),this.transport.send(t)?n&&n():(this.onTransportError(),r&&r());break;case f.STATUS_COMPLETED:}}},_=class extends n{constructor(e,t,n){super(),this.type=f.INVITE_SERVER,this.id=n.via_branch,this.ua=e,this.transport=t,this.request=n,this.last_response=``,n.server_transaction=this,this.state=f.STATUS_PROCEEDING,e.newTransaction(this),this.resendProvisionalTimer=null,n.reply(100)}get C(){return f}stateChanged(e){this.state=e,this.emit(`stateChanged`)}timer_H(){d.debug(`Timer H expired for transaction ${this.id}`),this.state===f.STATUS_COMPLETED&&d.debug(`ACK not received, dialog will be terminated`),this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_I(){this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_L(){d.debug(`Timer L expired for transaction ${this.id}`),this.state===f.STATUS_ACCEPTED&&(this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this))}onTransportError(){this.transportError||(this.transportError=!0,d.debug(`transport error occurred, deleting transaction ${this.id}`),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),clearTimeout(this.L),clearTimeout(this.H),clearTimeout(this.I),this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this))}resend_provisional(){this.transport.send(this.last_response)||this.onTransportError()}receiveResponse(e,t,n,r){if(e>=100&&e<=199)switch(this.state){case f.STATUS_PROCEEDING:this.transport.send(t)||this.onTransportError(),this.last_response=t}if(e>100&&e<=199&&this.state===f.STATUS_PROCEEDING)this.resendProvisionalTimer===null&&(this.resendProvisionalTimer=setInterval(()=>{this.resend_provisional()},o.PROVISIONAL_RESPONSE_INTERVAL));else if(e>=200&&e<=299)switch(this.state){case f.STATUS_PROCEEDING:this.stateChanged(f.STATUS_ACCEPTED),this.last_response=t,this.L=setTimeout(()=>{this.timer_L()},o.TIMER_L),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null);case f.STATUS_ACCEPTED:this.transport.send(t)?n&&n():(this.onTransportError(),r&&r())}else if(e>=300&&e<=699)switch(this.state){case f.STATUS_PROCEEDING:this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),this.transport.send(t)?(this.stateChanged(f.STATUS_COMPLETED),this.H=setTimeout(()=>{this.timer_H()},o.TIMER_H),n&&n()):(this.onTransportError(),r&&r())}}};function v({_transactions:e},t){let n;switch(t.method){case i.INVITE:if(n=e.ist[t.via_branch],n){switch(n.state){case f.STATUS_PROCEEDING:n.transport.send(n.last_response);break;case f.STATUS_ACCEPTED:}return!0}break;case i.ACK:if(n=e.ist[t.via_branch],n){if(n.state===f.STATUS_ACCEPTED)return!1;if(n.state===f.STATUS_COMPLETED)return n.state=f.STATUS_CONFIRMED,n.I=setTimeout(()=>{n.timer_I()},o.TIMER_I),!0}else return!1;break;case i.CANCEL:return n=e.ist[t.via_branch],n?(t.reply_sl(200),n.state!==f.STATUS_PROCEEDING):(t.reply_sl(481),!0);default:if(n=e.nist[t.via_branch],n){switch(n.state){case f.STATUS_TRYING:break;case f.STATUS_PROCEEDING:case f.STATUS_COMPLETED:n.transport.send(n.last_response)}return!0}}}t.exports={C:f,NonInviteClientTransaction:p,InviteClientTransaction:m,AckClientTransaction:h,NonInviteServerTransaction:g,InviteServerTransaction:_,checkTransaction:v}})),X=c(((e,t)=>{var n=q(),r=V(),i=qt(),a=Y(),o=new n(`RequestSender`),s={onRequestTimeout:()=>{},onTransportError:()=>{},onReceiveResponse:()=>{},onAuthenticated:()=>{}};t.exports=class{constructor(e,t,n){this._ua=e,this._eventHandlers=n,this._method=t.method,this._request=t,this._auth=null,this._challenged=!1,this._staled=!1;for(let e in s)Object.prototype.hasOwnProperty.call(s,e)&&(this._eventHandlers[e]||(this._eventHandlers[e]=s[e]));e.status===e.C.STATUS_USER_CLOSED&&(this._method!==r.BYE||this._method!==r.ACK)&&this._eventHandlers.onTransportError()}send(){let e={onRequestTimeout:()=>{this._eventHandlers.onRequestTimeout()},onTransportError:()=>{this._eventHandlers.onTransportError()},onReceiveResponse:e=>{this._receiveResponse(e)}};switch(this._method){case`INVITE`:this.clientTransaction=new a.InviteClientTransaction(this._ua,this._ua.transport,this._request,e);break;case`ACK`:this.clientTransaction=new a.AckClientTransaction(this._ua,this._ua.transport,this._request,e);break;default:this.clientTransaction=new a.NonInviteClientTransaction(this._ua,this._ua.transport,this._request,e)}this._ua._configuration.authorization_jwt&&this._request.setHeader(`Authorization`,this._ua._configuration.authorization_jwt),this.clientTransaction.send()}_receiveResponse(e){let t,n,r=e.status_code;if((r===401||r===407)&&(this._ua.configuration.password!==null||this._ua.configuration.ha1!==null)){if(e.status_code===401?(t=e.parseHeader(`www-authenticate`),n=`authorization`):(t=e.parseHeader(`proxy-authenticate`),n=`proxy-authorization`),!t){o.debug(`${e.status_code} with wrong or missing challenge, cannot authenticate`),this._eventHandlers.onReceiveResponse(e);return}if(!this._challenged||!this._staled&&t.stale===!0){if(this._auth||=new i({username:this._ua.configuration.authorization_user,password:this._ua.configuration.password,realm:this._ua.configuration.realm,ha1:this._ua.configuration.ha1}),!this._auth.authenticate(this._request,t)){this._eventHandlers.onReceiveResponse(e);return}this._challenged=!0,this._ua.set(`realm`,this._auth.get(`realm`)),this._ua.set(`ha1`,this._auth.get(`ha1`)),t.stale&&(this._staled=!0),this._request=this._request.clone(),this._request.cseq+=1,this._request.setHeader(`cseq`,`${this._request.cseq} ${this._method}`),this._request.setHeader(n,this._auth.toString()),this._eventHandlers.onAuthenticated(this._request),this.send()}else this._eventHandlers.onReceiveResponse(e)}else this._eventHandlers.onReceiveResponse(e)}}})),Yt=c(((e,t)=>{var n=q(),r=G(),i=V(),a=J(),o=X(),s=new n(`Registrator`),c=10;t.exports=class{constructor(e,t){this._reg_id=1,this._ua=e,this._transport=t,this._registrar=e.configuration.registrar_server,this._expires=e.configuration.register_expires,this._call_id=r.createRandomToken(22),this._cseq=0,this._to_uri=e.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString(),this._contact+=`;+sip.ice`,this._extraHeaders=[],this._extraContactParams=``,this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._contact+=`;reg-id=${this._reg_id}`,this._contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(e){Array.isArray(e)||(e=[]),this._extraHeaders=e.slice()}setExtraContactParams(e){e instanceof Object||(e={}),this._extraContactParams=``;for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let n=e[t];this._extraContactParams+=`;${t}`,n&&(this._extraContactParams+=`=${n}`)}}register(){if(this._registering){s.debug(`Register request in progress...`);return}let e=r.cloneArray(this._extraHeaders),t;this._expires?(t=`${this._contact};expires=${this._expires}${this._extraContactParams}`,e.push(`Expires: ${this._expires}`)):t=`${this._contact}${this._extraContactParams}`,e.push(`Contact: ${t}`);let n=r.newTag();this._ua.configuration.register_from_tag_trail&&(typeof this._ua.configuration.register_from_tag_trail==`function`?n+=this._ua.configuration.register_from_tag_trail():n+=this._ua.configuration.register_from_tag_trail);let l=new a.OutgoingRequest(i.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1,from_tag:n},e),u=new o(this._ua,l,{onRequestTimeout:()=>{this._registrationFailure(null,i.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,i.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:e=>{if(e.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(e.status_code):break;case/^2[0-9]{2}$/.test(e.status_code):{if(this._registering=!1,!e.hasHeader(`Contact`)){s.debug(`no Contact header in response to REGISTER, response ignored`);break}let t=e.headers.Contact.reduce((e,t)=>e.concat(t.parsed),[]),n=t.find(e=>this._sipInstance===e.getParam(`+sip.instance`)&&this._reg_id===parseInt(e.getParam(`reg-id`)));if(n||=t.find(e=>e.uri.user===this._ua.contact.uri.user),!n){s.debug(`no Contact header pointing to us, response ignored`);break}let r=n.getParam(`expires`);!r&&e.hasHeader(`expires`)&&(r=e.getHeader(`expires`)),r||=this._expires,r=Number(r),r<c&&(r=c);let i=r>64?r*1e3/2+Math.floor((r/2-32)*1e3*Math.random()):r*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners(`registrationExpiring`).length===0?this.register():this._ua.emit(`registrationExpiring`)},i),n.hasParam(`temp-gruu`)&&(this._ua.contact.temp_gruu=n.getParam(`temp-gruu`).replace(/"/g,``)),n.hasParam(`pub-gruu`)&&(this._ua.contact.pub_gruu=n.getParam(`pub-gruu`).replace(/"/g,``)),this._registered||(this._registered=!0,this._ua.registered({response:e}));break}case/^423$/.test(e.status_code):e.hasHeader(`min-expires`)?(this._expires=Number(e.getHeader(`min-expires`)),this._expires<c&&(this._expires=c),this._registering=!1,this.register()):(s.debug(`423 response received for REGISTER without Min-Expires`),this._registrationFailure(e,i.causes.SIP_FAILURE_CODE));break;default:{let t=r.sipErrorCause(e.status_code);this._registrationFailure(e,t)}}}});this._registering=!0,u.send()}unregister(e={}){if(!this._registered){s.debug(`already unregistered`);return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);let t=r.cloneArray(this._extraHeaders);e.all?t.push(`Contact: *${this._extraContactParams}`):t.push(`Contact: ${this._contact};expires=0${this._extraContactParams}`),t.push(`Expires: 0`);let n=new a.OutgoingRequest(i.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},t);new o(this._ua,n,{onRequestTimeout:()=>{this._unregistered(null,i.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,i.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:e=>{switch(!0){case/^1[0-9]{2}$/.test(e.status_code):break;case/^2[0-9]{2}$/.test(e.status_code):this._unregistered(e);break;default:{let t=r.sipErrorCause(e.status_code);this._unregistered(e,t)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(e,t){this._registering=!1,this._ua.registrationFailed({response:e||null,cause:t}),this._registered&&(this._registered=!1,this._ua.unregistered({response:e||null,cause:t}))}_unregistered(e,t){this._registering=!1,this._registered=!1,this._ua.unregistered({response:e||null,cause:t||null})}}})),Xt=c(((e,t)=>{var n=V(),r=Y(),i=X(),a={onRequestTimeout:()=>{},onTransportError:()=>{},onSuccessResponse:()=>{},onErrorResponse:()=>{},onAuthenticated:()=>{},onDialogError:()=>{}};t.exports=class{constructor(e,t,n){this._dialog=e,this._ua=e._ua,this._request=t,this._eventHandlers=n,this._reattempt=!1,this._reattemptTimer=null;for(let e in a)Object.prototype.hasOwnProperty.call(a,e)&&(this._eventHandlers[e]||(this._eventHandlers[e]=a[e]))}get request(){return this._request}send(){let e=new i(this._ua,this._request,{onRequestTimeout:()=>{this._eventHandlers.onRequestTimeout()},onTransportError:()=>{this._eventHandlers.onTransportError()},onAuthenticated:e=>{this._eventHandlers.onAuthenticated(e)},onReceiveResponse:e=>{this._receiveResponse(e)}});if(e.send(),(this._request.method===n.INVITE||this._request.method===n.UPDATE&&this._request.body)&&e.clientTransaction.state!==r.C.STATUS_TERMINATED){this._dialog.uac_pending_reply=!0;let t=()=>{(e.clientTransaction.state===r.C.STATUS_ACCEPTED||e.clientTransaction.state===r.C.STATUS_COMPLETED||e.clientTransaction.state===r.C.STATUS_TERMINATED)&&(e.clientTransaction.removeListener(`stateChanged`,t),this._dialog.uac_pending_reply=!1)};e.clientTransaction.on(`stateChanged`,t)}}_receiveResponse(e){e.status_code===408||e.status_code===481?this._eventHandlers.onDialogError(e):e.method===n.INVITE&&e.status_code===491?this._reattempt?this._eventHandlers.onErrorResponse(e):(this._request.cseq=this._dialog.local_seqnum+=1,this._reattemptTimer=setTimeout(()=>{this._dialog.isTerminated()||(this._reattempt=!0,this.send())},1e3)):e.status_code>=200&&e.status_code<300?this._eventHandlers.onSuccessResponse(e):e.status_code>=300&&this._eventHandlers.onErrorResponse(e)}}})),Zt=c(((e,t)=>{var n=q(),r=J(),i=V(),a=Y(),o=Xt(),s=G(),c=new n(`Dialog`),l={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3};t.exports=class{static get C(){return l}constructor(e,t,n,i=l.STATUS_CONFIRMED){if(this._owner=e,this._ua=e._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,!t.hasHeader(`contact`))return{error:`unable to create a Dialog without Contact header field`};t instanceof r.IncomingResponse&&(i=t.status_code<200?l.STATUS_EARLY:l.STATUS_CONFIRMED);let a=t.parseHeader(`contact`);n===`UAS`?(this._id={call_id:t.call_id,local_tag:t.to_tag,remote_tag:t.from_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=i,this._remote_seqnum=t.cseq,this._local_uri=t.parseHeader(`to`).uri,this._remote_uri=t.parseHeader(`from`).uri,this._remote_target=a.uri,this._route_set=t.getHeaders(`record-route`),this._incoming_ack_seqnum=t.cseq,this._outgoing_ack_seqnum=null):n===`UAC`&&(this._id={call_id:t.call_id,local_tag:t.from_tag,remote_tag:t.to_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=i,this._local_seqnum=t.cseq,this._local_uri=t.parseHeader(`from`).uri,this._remote_uri=t.parseHeader(`to`).uri,this._remote_target=a.uri,this._route_set=t.getHeaders(`record-route`).reverse(),this._incoming_ack_seqnum=null,this._outgoing_ack_seqnum=this._local_seqnum),this._ua.newDialog(this),c.debug(`new ${n} dialog created with status ${this._state===l.STATUS_EARLY?`EARLY`:`CONFIRMED`}`)}get id(){return this._id}get local_seqnum(){return this._local_seqnum}set local_seqnum(e){this._local_seqnum=e}get owner(){return this._owner}get uac_pending_reply(){return this._uac_pending_reply}set uac_pending_reply(e){this._uac_pending_reply=e}get uas_pending_reply(){return this._uas_pending_reply}isTerminated(){return this._status===l.STATUS_TERMINATED}update(e,t){this._state=l.STATUS_CONFIRMED,c.debug(`dialog ${this._id.toString()} changed to CONFIRMED state`),t===`UAC`&&(this._route_set=e.getHeaders(`record-route`).reverse())}terminate(){c.debug(`dialog ${this._id.toString()} deleted`),this._ua.destroyDialog(this),this._state=l.STATUS_TERMINATED}sendRequest(e,t={}){let n=s.cloneArray(t.extraHeaders),r=s.cloneObject(t.eventHandlers),a=t.body||null,c=this._createRequest(e,n,a),l=r.onAuthenticated||(()=>{});return r.onAuthenticated=e=>{this._local_seqnum+=1,c.method===i.INVITE&&(this._outgoing_ack_seqnum=this._local_seqnum),l(e)},new o(this,c,r).send(),c}receiveRequest(e){this._checkInDialogRequest(e)&&(e.method===i.ACK&&this._incoming_ack_seqnum!==null?this._incoming_ack_seqnum=null:e.method===i.INVITE&&(this._incoming_ack_seqnum=e.cseq),this._owner.receiveRequest(e))}_createRequest(e,t,n){t=s.cloneArray(t),this._local_seqnum||=Math.floor(Math.random()*1e4);let a=e===i.CANCEL||e===i.ACK?this._outgoing_ack_seqnum:this._local_seqnum+=1;return e===i.INVITE&&(this._outgoing_ack_seqnum=a),new r.OutgoingRequest(e,this._remote_target,this._ua,{cseq:a,call_id:this._id.call_id,from_uri:this._local_uri,from_tag:this._id.local_tag,to_uri:this._remote_uri,to_tag:this._id.remote_tag,route_set:this._route_set},t,n)}_checkInDialogRequest(e){if(!this._remote_seqnum)this._remote_seqnum=e.cseq;else if(e.cseq<this._remote_seqnum){if(e.method===i.ACK){if(this._incoming_ack_seqnum===null||e.cseq!==this._incoming_ack_seqnum)return!1}else return e.reply(500),!1}else e.cseq>this._remote_seqnum&&(this._remote_seqnum=e.cseq);if(e.method===i.INVITE||e.method===i.UPDATE&&e.body){if(this._uac_pending_reply===!0)e.reply(491);else if(this._uas_pending_reply===!0){let t=(Math.random()*10|0)+1;return e.reply(500,null,[`Retry-After:${t}`]),!1}else{this._uas_pending_reply=!0;let t=()=>{(e.server_transaction.state===a.C.STATUS_ACCEPTED||e.server_transaction.state===a.C.STATUS_COMPLETED||e.server_transaction.state===a.C.STATUS_TERMINATED)&&(e.server_transaction.removeListener(`stateChanged`,t),this._uas_pending_reply=!1)};e.server_transaction.on(`stateChanged`,t)}e.hasHeader(`contact`)&&e.server_transaction.on(`stateChanged`,()=>{e.server_transaction.state===a.C.STATUS_ACCEPTED&&(this._remote_target=e.parseHeader(`contact`).uri)})}else e.method===i.NOTIFY&&e.hasHeader(`contact`)&&e.server_transaction.on(`stateChanged`,()=>{e.server_transaction.state===a.C.STATUS_COMPLETED&&(this._remote_target=e.parseHeader(`contact`).uri)});return!0}}})),Qt=c(((e,t)=>{var n=K().EventEmitter,r=q(),i=V(),a=H(),o=G(),s=new r(`RTCSession:DTMF`),c={MIN_DURATION:70,MAX_DURATION:6e3,DEFAULT_DURATION:100,MIN_INTER_TONE_GAP:50,DEFAULT_INTER_TONE_GAP:500};t.exports=class extends n{constructor(e){super(),this._session=e,this._direction=null,this._tone=null,this._duration=null,this._request=null}get tone(){return this._tone}get duration(){return this._duration}send(e,t={}){if(e===void 0)throw TypeError(`Not enough arguments`);if(this._direction=`outgoing`,this._session.status!==this._session.C.STATUS_CONFIRMED&&this._session.status!==this._session.C.STATUS_WAITING_FOR_ACK&&this._session.status!==this._session.C.STATUS_1XX_RECEIVED)throw new a.InvalidStateError(this._session.status);let n=o.cloneArray(t.extraHeaders);if(this.eventHandlers=o.cloneObject(t.eventHandlers),typeof e==`string`)e=e.toUpperCase();else if(typeof e==`number`)e=e.toString();else throw TypeError(`Invalid tone: ${e}`);if(e.match(/^[0-9A-DR#*]$/))this._tone=e;else throw TypeError(`Invalid tone: ${e}`);this._duration=t.duration,n.push(`Content-Type: application/dtmf-relay`);let r=`Signal=${this._tone}\r\n`;r+=`Duration=${this._duration}`,this._session.newDTMF({originator:`local`,dtmf:this,request:this._request}),this._session.sendRequest(i.INFO,{extraHeaders:n,eventHandlers:{onSuccessResponse:e=>{this.emit(`succeeded`,{originator:`remote`,response:e})},onErrorResponse:e=>{this.eventHandlers.onFailed&&this.eventHandlers.onFailed(),this.emit(`failed`,{originator:`remote`,response:e})},onRequestTimeout:()=>{this._session.onRequestTimeout()},onTransportError:()=>{this._session.onTransportError()},onDialogError:()=>{this._session.onDialogError()}},body:r})}init_incoming(e){let t=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/,n=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;if(this._direction=`incoming`,this._request=e,e.reply(200),e.body){let r=e.body.split(`
|
|
14
|
-
`);r.length>=1&&t.test(r[0])&&(this._tone=r[0].replace(t,`$2`)),r.length>=2&&n.test(r[1])&&(this._duration=parseInt(r[1].replace(n,`$2`),10))}this._duration||=c.DEFAULT_DURATION,this._tone?this._session.newDTMF({originator:`remote`,dtmf:this,request:e}):s.debug(`invalid INFO DTMF received, discarded`)}},t.exports.C=c}))
|
|
15
|
-
`,1)[0],`Status_Line`);if(t===-1){s.debug(`receiveNotify() | error parsing NOTIFY body: "${e.body}"`);return}switch(!0){case/^100$/.test(t.status_code):this.emit(`trying`,{request:e,status_line:t});break;case/^1[0-9]{2}$/.test(t.status_code):this.emit(`progress`,{request:e,status_line:t});break;case/^2[0-9]{2}$/.test(t.status_code):this.emit(`accepted`,{request:e,status_line:t});break;default:this.emit(`failed`,{request:e,status_line:t})}}_requestSucceeded(e){s.debug(`REFER succeeded`),s.debug(`emit "requestSucceeded"`),this.emit(`requestSucceeded`,{response:e})}_requestFailed(e,t){s.debug(`REFER failed`),s.debug(`emit "requestFailed"`),this.emit(`requestFailed`,{response:e||null,cause:t})}}})),nn=c(((e,t)=>{var n=K().EventEmitter,r=Kt(),i=q(),a=V(),o=H(),s=Y(),c=G(),l=Jt(),u=J(),d=Zt(),f=X(),p=Qt(),m=$t(),h=en(),g=tn(),_=W(),v=new i(`RTCSession`),y={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9},b=[`audio`,`video`];t.exports=class e extends n{static get C(){return y}constructor(e){v.debug(`new`),super(),this._id=null,this._ua=e,this._status=y.STATUS_NULL,this._dialog=null,this._earlyDialogs={},this._contact=null,this._from_tag=null,this._to_tag=null,this._connection=null,this._connectionPromiseQueue=Promise.resolve(),this._request=null,this._is_canceled=!1,this._cancel_reason=``,this._is_confirmed=!1,this._late_sdp=!1,this._rtcOfferConstraints=null,this._rtcAnswerConstraints=null,this._localMediaStream=null,this._localMediaStreamLocallyGenerated=!1,this._rtcReady=!0,this._iceReady=!1,this._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},this._direction=null,this._local_identity=null,this._remote_identity=null,this._start_time=null,this._end_time=null,this._tones=null,this._audioMuted=!1,this._videoMuted=!1,this._localHold=!1,this._remoteHold=!1,this._sessionTimers={enabled:this._ua.configuration.session_timers,refreshMethod:this._ua.configuration.session_timers_refresh_method,defaultExpires:a.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},this._referSubscribers={},this._data={}}get C(){return y}get causes(){return a.causes}get id(){return this._id}get connection(){return this._connection}get contact(){return this._contact}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}get start_time(){return this._start_time}get end_time(){return this._end_time}get data(){return this._data}set data(e){this._data=e}get status(){return this._status}isInProgress(){switch(this._status){case y.STATUS_NULL:case y.STATUS_INVITE_SENT:case y.STATUS_1XX_RECEIVED:case y.STATUS_INVITE_RECEIVED:case y.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}isEstablished(){switch(this._status){case y.STATUS_ANSWERED:case y.STATUS_WAITING_FOR_ACK:case y.STATUS_CONFIRMED:return!0;default:return!1}}isEnded(){switch(this._status){case y.STATUS_CANCELED:case y.STATUS_TERMINATED:return!0;default:return!1}}isMuted(){return{audio:this._audioMuted,video:this._videoMuted}}isOnHold(){return{local:this._localHold,remote:this._remoteHold}}connect(e,t={},n){v.debug(`connect()`);let r=e,i=c.cloneObject(t.eventHandlers),s=c.cloneArray(t.extraHeaders),l=c.cloneObject(t.mediaConstraints,{audio:!0,video:!0}),d=t.mediaStream||null,f=c.cloneObject(t.pcConfig,{iceServers:[]}),p=t.rtcConstraints||null,m=t.rtcOfferConstraints||null;if(this._rtcOfferConstraints=m,this._rtcAnswerConstraints=t.rtcAnswerConstraints||null,this._data=t.data||this._data,e===void 0)throw TypeError(`Not enough arguments`);if(this._status!==y.STATUS_NULL)throw new o.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new o.NotSupportedError(`WebRTC not supported`);if(e=this._ua.normalizeTarget(e),!e)throw TypeError(`Invalid target: ${r}`);this._sessionTimers.enabled&&c.isDecimal(t.sessionTimersExpires)&&(t.sessionTimersExpires>=a.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=t.sessionTimersExpires:this._sessionTimers.defaultExpires=a.SESSION_EXPIRES);for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&this.on(e,i[e]);this._from_tag=c.newTag();let h=t.anonymous||!1,g={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:h,outbound:!0}),h?(g.from_display_name=`Anonymous`,g.from_uri=new _(`sip`,`anonymous`,`anonymous.invalid`),s.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),s.push(`Privacy: id`)):t.fromUserName&&(g.from_uri=new _(`sip`,t.fromUserName,this._ua.configuration.uri.host),s.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),t.fromDisplayName&&(g.from_display_name=t.fromDisplayName),s.push(`Contact: ${this._contact}`),s.push(`Content-Type: application/sdp`),this._sessionTimers.enabled&&s.push(`Session-Expires: ${this._sessionTimers.defaultExpires}${this._ua.configuration.session_timers_force_refresher?`;refresher=uac`:``}`),this._request=new u.InitialOutgoingInviteRequest(e,this._ua,g,s),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(f,p),this._direction=`outgoing`,this._local_identity=this._request.from,this._remote_identity=this._request.to,n&&n(this),this._newRTCSession(`local`,this._request),this._sendInitialRequest(l,m,d)}init_incoming(e,t){v.debug(`init_incoming()`);let n,r=e.hasHeader(`Content-Type`)?e.getHeader(`Content-Type`).toLowerCase():void 0;if(e.body&&r!==`application/sdp`){e.reply(415);return}if(this._status=y.STATUS_INVITE_RECEIVED,this._from_tag=e.from_tag,this._id=e.call_id+this._from_tag,this._request=e,this._contact=this._ua.contact.toString(),e.hasHeader(`expires`)&&(n=e.getHeader(`expires`)*1e3),e.to_tag=c.newTag(),!this._createDialog(e,`UAS`,!0)){e.reply(500,`Missing Contact header field`);return}this._late_sdp=!e.body,this._status=y.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{e.reply(408),this._failed(`local`,null,a.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),n&&(this._timers.expiresTimer=setTimeout(()=>{this._status===y.STATUS_WAITING_FOR_ANSWER&&(e.reply(487),this._failed(`system`,null,a.causes.EXPIRES))},n)),this._direction=`incoming`,this._local_identity=e.to,this._remote_identity=e.from,t&&t(this),this._newRTCSession(`remote`,e),this._status!==y.STATUS_TERMINATED&&(e.reply(180,null,[`Contact: ${this._contact}`]),this._progress(`local`,null))}answer(e={}){v.debug(`answer()`);let t=this._request,n=c.cloneArray(e.extraHeaders),r=c.cloneObject(e.mediaConstraints),i=e.mediaStream||null,s=c.cloneObject(e.pcConfig,{iceServers:[]}),l=e.rtcConstraints||null,u=e.rtcAnswerConstraints||null,d=c.cloneObject(e.rtcOfferConstraints),f,p=!1,m=!1,h=!1,g=!1;if(this._rtcAnswerConstraints=u,this._rtcOfferConstraints=e.rtcOfferConstraints||null,this._data=e.data||this._data,this._direction!==`incoming`)throw new o.NotSupportedError(`"answer" not supported for outgoing RTCSession`);if(this._status!==y.STATUS_WAITING_FOR_ANSWER)throw new o.InvalidStateError(this._status);if(this._sessionTimers.enabled&&c.isDecimal(e.sessionTimersExpires)&&(e.sessionTimersExpires>=a.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=e.sessionTimersExpires:this._sessionTimers.defaultExpires=a.SESSION_EXPIRES),this._status=y.STATUS_ANSWERED,!this._createDialog(t,`UAS`)){t.reply(500,`Error creating dialog`);return}clearTimeout(this._timers.userNoAnswerTimer),n.unshift(`Contact: ${this._contact}`);let _=t.parseSDP();Array.isArray(_.media)||(_.media=[_.media]);for(let e of _.media)e.type===`audio`&&(p=!0,(!e.direction||e.direction===`sendrecv`)&&(h=!0)),e.type===`video`&&(m=!0,(!e.direction||e.direction===`sendrecv`)&&(g=!0));if(i&&r.audio===!1){f=i.getAudioTracks();for(let e of f)i.removeTrack(e)}if(i&&r.video===!1){f=i.getVideoTracks();for(let e of f)i.removeTrack(e)}!i&&r.audio===void 0&&(r.audio=h),!i&&r.video===void 0&&(r.video=g),!i&&!p&&!d.offerToReceiveAudio&&(r.audio=!1),!i&&!m&&!d.offerToReceiveVideo&&(r.video=!1),this._createRTCConnection(s,l),Promise.resolve().then(()=>{if(i)return i;if(r.audio||r.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(r).catch(e=>{throw this._status===y.STATUS_TERMINATED?Error(`terminated`):(t.reply(480),this._failed(`local`,null,a.causes.USER_DENIED_MEDIA_ACCESS),v.warn(`emit "getusermediafailed" [error:%o]`,e),this.emit(`getusermediafailed`,e),Error(`getUserMedia() failed`))})}).then(e=>{if(this._status===y.STATUS_TERMINATED)throw Error(`terminated`);this._localMediaStream=e,e&&e.getTracks().forEach(t=>{this._connection.addTrack(t,e)})}).then(()=>{if(this._late_sdp)return;let e={originator:`remote`,type:`offer`,sdp:t.body};v.debug(`emit "sdp"`),this.emit(`sdp`,e);let n=new RTCSessionDescription({type:`offer`,sdp:e.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(n)).catch(e=>{throw t.reply(488),this._failed(`system`,null,a.causes.WEBRTC_ERROR),v.warn(`emit "peerconnection:setremotedescriptionfailed" [error:%o]`,e),this.emit(`peerconnection:setremotedescriptionfailed`,e),Error(`peerconnection.setRemoteDescription() failed`)}),this._connectionPromiseQueue}).then(()=>{if(this._status===y.STATUS_TERMINATED)throw Error(`terminated`);return this._connecting(t),this._late_sdp?this._createLocalDescription(`offer`,this._rtcOfferConstraints).catch(()=>{throw t.reply(500),Error(`_createLocalDescription() failed`)}):this._createLocalDescription(`answer`,u).catch(()=>{throw t.reply(500),Error(`_createLocalDescription() failed`)})}).then(e=>{if(this._status===y.STATUS_TERMINATED)throw Error(`terminated`);this._handleSessionTimersInIncomingRequest(t,n),t.reply(200,null,n,e,()=>{this._status=y.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(t,e),this._setACKTimer(),this._accepted(`local`)},()=>{this._failed(`system`,null,a.causes.CONNECTION_ERROR)})}).catch(e=>{this._status!==y.STATUS_TERMINATED&&(v.warn(`answer() failed: ${e.message}`),this._failed(`system`,e.message,a.causes.INTERNAL_ERROR))})}terminate(e={}){v.debug(`terminate()`);let t=e.cause||a.causes.BYE,n=c.cloneArray(e.extraHeaders),r=e.body,i,l=e.status_code,u=e.reason_phrase;if(this._status===y.STATUS_TERMINATED)throw new o.InvalidStateError(this._status);switch(this._status){case y.STATUS_NULL:case y.STATUS_INVITE_SENT:case y.STATUS_1XX_RECEIVED:if(v.debug(`canceling session`),l&&(l<200||l>=700))throw TypeError(`Invalid status_code: ${l}`);l&&(u=u||a.REASON_PHRASE[l]||``,i=`SIP ;cause=${l} ;text="${u}"`),this._status===y.STATUS_NULL||this._status===y.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=i):this._status===y.STATUS_1XX_RECEIVED&&this._request.cancel(i),this._status=y.STATUS_CANCELED,this._failed(`local`,null,a.causes.CANCELED);break;case y.STATUS_WAITING_FOR_ANSWER:case y.STATUS_ANSWERED:if(v.debug(`rejecting session`),l||=480,l<300||l>=700)throw TypeError(`Invalid status_code: ${l}`);this._request.reply(l,u,n,r),this._failed(`local`,null,a.causes.REJECTED);break;case y.STATUS_WAITING_FOR_ACK:case y.STATUS_CONFIRMED:if(v.debug(`terminating session`),u=e.reason_phrase||a.REASON_PHRASE[l]||``,l&&(l<200||l>=700))throw TypeError(`Invalid status_code: ${l}`);if(l&&n.push(`Reason: SIP ;cause=${l}; text="${u}"`),this._status===y.STATUS_WAITING_FOR_ACK&&this._direction===`incoming`&&this._request.server_transaction.state!==s.C.STATUS_TERMINATED){let e=this._dialog;this.receiveRequest=({method:t})=>{t===a.ACK&&(this.sendRequest(a.BYE,{extraHeaders:n,body:r}),e.terminate())},this._request.server_transaction.on(`stateChanged`,()=>{this._request.server_transaction.state===s.C.STATUS_TERMINATED&&(this.sendRequest(a.BYE,{extraHeaders:n,body:r}),e.terminate())}),this._ended(`local`,null,t),this._dialog=e,this._ua.newDialog(e)}else this.sendRequest(a.BYE,{extraHeaders:n,body:r}),this._ended(`local`,null,t)}}sendDTMF(e,t={}){v.debug(`sendDTMF() | tones: %s`,e);let n=t.duration||null,r=t.interToneGap||null,i=t.transportType||a.DTMF_TRANSPORT.INFO;if(e===void 0)throw TypeError(`Not enough arguments`);if(this._status!==y.STATUS_CONFIRMED&&this._status!==y.STATUS_WAITING_FOR_ACK&&this._status!==y.STATUS_1XX_RECEIVED)throw new o.InvalidStateError(this._status);if(i!==a.DTMF_TRANSPORT.INFO&&i!==a.DTMF_TRANSPORT.RFC2833)throw TypeError(`invalid transportType: ${i}`);if(typeof e==`number`&&(e=e.toString()),!e||typeof e!=`string`||!e.match(/^[0-9A-DR#*,]+$/i))throw TypeError(`Invalid tones: ${e}`);if(n&&!c.isDecimal(n))throw TypeError(`Invalid tone duration: ${n}`);if(n?n<p.C.MIN_DURATION?(v.debug(`"duration" value is lower than the minimum allowed, setting it to ${p.C.MIN_DURATION} milliseconds`),n=p.C.MIN_DURATION):n>p.C.MAX_DURATION?(v.debug(`"duration" value is greater than the maximum allowed, setting it to ${p.C.MAX_DURATION} milliseconds`),n=p.C.MAX_DURATION):n=Math.abs(n):n=p.C.DEFAULT_DURATION,t.duration=n,r&&!c.isDecimal(r))throw TypeError(`Invalid interToneGap: ${r}`);if(r?r<p.C.MIN_INTER_TONE_GAP?(v.debug(`"interToneGap" value is lower than the minimum allowed, setting it to ${p.C.MIN_INTER_TONE_GAP} milliseconds`),r=p.C.MIN_INTER_TONE_GAP):r=Math.abs(r):r=p.C.DEFAULT_INTER_TONE_GAP,i===a.DTMF_TRANSPORT.RFC2833){let t=this._getDTMFRTPSender();t&&(e=t.toneBuffer+e,t.insertDTMF(e,n,r));return}if(this._tones){this._tones+=e;return}this._tones=e,s.call(this);function s(){let e;if(this._status===y.STATUS_TERMINATED||!this._tones){this._tones=null;return}let i=this._tones[0];if(this._tones=this._tones.substring(1),i===`,`)e=2e3;else{let a=new p(this);t.eventHandlers={onFailed:()=>{this._tones=null}},a.send(i,t),e=n+r}setTimeout(s.bind(this),e)}}sendInfo(e,t,n={}){if(v.debug(`sendInfo()`),this._status!==y.STATUS_CONFIRMED&&this._status!==y.STATUS_WAITING_FOR_ACK&&this._status!==y.STATUS_1XX_RECEIVED)throw new o.InvalidStateError(this._status);new m(this).send(e,t,n)}mute(e={audio:!0,video:!1}){v.debug(`mute()`);let t=!1,n=!1;this._audioMuted===!1&&e.audio&&(t=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&e.video&&(n=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(t===!0||n===!0)&&this._onmute({audio:t,video:n})}unmute(e={audio:!0,video:!0}){v.debug(`unmute()`);let t=!1,n=!1;this._audioMuted===!0&&e.audio&&(t=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&e.video&&(n=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(t===!0||n===!0)&&this._onunmute({audio:t,video:n})}hold(e={},t){if(v.debug(`hold()`),this._status!==y.STATUS_WAITING_FOR_ACK&&this._status!==y.STATUS_CONFIRMED||this._localHold===!0||!this.isReadyToReOffer())return!1;this._localHold=!0,this._onhold(`local`);let n={succeeded:()=>{t&&t()},failed:()=>{this.terminate({cause:a.causes.WEBRTC_ERROR,status_code:500,reason_phrase:`Hold Failed`})}};return e.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:n,extraHeaders:e.extraHeaders}):this._sendReinvite({eventHandlers:n,extraHeaders:e.extraHeaders}),!0}unhold(e={},t){if(v.debug(`unhold()`),this._status!==y.STATUS_WAITING_FOR_ACK&&this._status!==y.STATUS_CONFIRMED||this._localHold===!1||!this.isReadyToReOffer())return!1;this._localHold=!1,this._onunhold(`local`);let n={succeeded:()=>{t&&t()},failed:()=>{this.terminate({cause:a.causes.WEBRTC_ERROR,status_code:500,reason_phrase:`Unhold Failed`})}};return e.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:n,extraHeaders:e.extraHeaders}):this._sendReinvite({eventHandlers:n,extraHeaders:e.extraHeaders}),!0}renegotiate(e={},t){v.debug(`renegotiate()`);let n=e.rtcOfferConstraints||null;if(this._status!==y.STATUS_WAITING_FOR_ACK&&this._status!==y.STATUS_CONFIRMED||!this.isReadyToReOffer())return!1;let r={succeeded:()=>{t&&t()},failed:()=>{this.terminate({cause:a.causes.WEBRTC_ERROR,status_code:500,reason_phrase:`Media Renegotiation Failed`})}};return this._setLocalMediaStatus(),e.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:r,rtcOfferConstraints:n,extraHeaders:e.extraHeaders}):this._sendReinvite({eventHandlers:r,rtcOfferConstraints:n,extraHeaders:e.extraHeaders}),!0}refer(e,t){v.debug(`refer()`);let n=e;if(this._status!==y.STATUS_WAITING_FOR_ACK&&this._status!==y.STATUS_CONFIRMED)return!1;if(e=this._ua.normalizeTarget(e),!e)throw TypeError(`Invalid target: ${n}`);let r=new g(this);r.sendRefer(e,t);let i=r.id;return this._referSubscribers[i]=r,r.on(`requestFailed`,()=>{delete this._referSubscribers[i]}),r.on(`accepted`,()=>{delete this._referSubscribers[i]}),r.on(`failed`,()=>{delete this._referSubscribers[i]}),r.on(`authenticated`,()=>{delete this._referSubscribers[i],i=r.id,this._referSubscribers[i]=r}),r}sendRequest(e,t){if(v.debug(`sendRequest()`),this._dialog)return this._dialog.sendRequest(e,t);{let n=Object.values(this._earlyDialogs);if(n.length>0)return n[0].sendRequest(e,t);v.warn(`sendRequest() | no valid early dialog found`);return}}receiveRequest(e){if(v.debug(`receiveRequest()`),e.method===a.CANCEL)(this._status===y.STATUS_WAITING_FOR_ANSWER||this._status===y.STATUS_ANSWERED)&&(this._status=y.STATUS_CANCELED,this._request.reply(487),this._failed(`remote`,e,a.causes.CANCELED));else switch(e.method){case a.ACK:if(this._status!==y.STATUS_WAITING_FOR_ACK)return;if(this._status=y.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!e.body){this.terminate({cause:a.causes.MISSING_SDP,status_code:400});break}let t={originator:`remote`,type:`answer`,sdp:e.body};v.debug(`emit "sdp"`),this.emit(`sdp`,t);let n=new RTCSessionDescription({type:`answer`,sdp:t.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(n)).then(()=>{this._is_confirmed||this._confirmed(`remote`,e)}).catch(e=>{this.terminate({cause:a.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),v.warn(`emit "peerconnection:setremotedescriptionfailed" [error:%o]`,e),this.emit(`peerconnection:setremotedescriptionfailed`,e)})}else this._is_confirmed||this._confirmed(`remote`,e);break;case a.BYE:this._status===y.STATUS_CONFIRMED||this._status===y.STATUS_WAITING_FOR_ACK?(e.reply(200),this._ended(`remote`,e,a.causes.BYE)):this._status===y.STATUS_INVITE_RECEIVED||this._status===y.STATUS_WAITING_FOR_ANSWER?(e.reply(200),this._request.reply(487,`BYE Received`),this._ended(`remote`,e,a.causes.BYE)):e.reply(403,`Wrong Status`);break;case a.INVITE:this._status===y.STATUS_CONFIRMED?e.hasHeader(`replaces`)?this._receiveReplaces(e):this._receiveReinvite(e):e.reply(403,`Wrong Status`);break;case a.INFO:if(this._status===y.STATUS_1XX_RECEIVED||this._status===y.STATUS_WAITING_FOR_ANSWER||this._status===y.STATUS_ANSWERED||this._status===y.STATUS_WAITING_FOR_ACK||this._status===y.STATUS_CONFIRMED){let t=e.hasHeader(`Content-Type`)?e.getHeader(`Content-Type`).toLowerCase():void 0;t&&t.match(/^application\/dtmf-relay/i)?new p(this).init_incoming(e):t===void 0?e.reply(415):new m(this).init_incoming(e)}else e.reply(403,`Wrong Status`);break;case a.UPDATE:this._status===y.STATUS_CONFIRMED?this._receiveUpdate(e):e.reply(403,`Wrong Status`);break;case a.REFER:this._status===y.STATUS_CONFIRMED?this._receiveRefer(e):e.reply(403,`Wrong Status`);break;case a.NOTIFY:this._status===y.STATUS_CONFIRMED?this._receiveNotify(e):e.reply(403,`Wrong Status`);break;default:e.reply(501)}}onTransportError(){v.warn(`onTransportError()`),this._status!==y.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:a.causes.CONNECTION_ERROR,cause:a.causes.CONNECTION_ERROR})}onRequestTimeout(){v.warn(`onRequestTimeout()`),this._status!==y.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:a.causes.REQUEST_TIMEOUT,cause:a.causes.REQUEST_TIMEOUT})}onDialogError(){v.warn(`onDialogError()`),this._status!==y.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:a.causes.DIALOG_ERROR,cause:a.causes.DIALOG_ERROR})}newDTMF(e){v.debug(`newDTMF()`),this.emit(`newDTMF`,e)}newInfo(e){v.debug(`newInfo()`),this.emit(`newInfo`,e)}isReadyToReOffer(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(v.debug(`isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress`),!1):!0:(v.debug(`isReadyToReOffer() | session not established yet`),!1):(v.debug(`isReadyToReOffer() | internal WebRTC status not ready`),!1)}_close(){if(v.debug(`close()`),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(v.debug(`close() | closing local MediaStream`),c.closeMediaStream(this._localMediaStream)),this._status!==y.STATUS_TERMINATED){if(this._status=y.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(e){v.warn(`close() | error closing the RTCPeerConnection: %o`,e)}for(let e in this._timers)Object.prototype.hasOwnProperty.call(this._timers,e)&&clearTimeout(this._timers[e]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(let e in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,e)&&(this._earlyDialogs[e].terminate(),delete this._earlyDialogs[e]);for(let e in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,e)&&delete this._referSubscribers[e];this._ua.destroyRTCSession(this)}}_setInvite2xxTimer(e,t){let n=l.T1;function r(){this._status===y.STATUS_WAITING_FOR_ACK&&(e.reply(200,null,[`Contact: ${this._contact}`],t),n<l.T2&&(n*=2,n>l.T2&&(n=l.T2)),this._timers.invite2xxTimer=setTimeout(r.bind(this),n))}this._timers.invite2xxTimer=setTimeout(r.bind(this),n)}_setACKTimer(){this._timers.ackTimer=setTimeout(()=>{this._status===y.STATUS_WAITING_FOR_ACK&&(v.debug(`no ACK received, terminating the session`),clearTimeout(this._timers.invite2xxTimer),this.sendRequest(a.BYE),this._ended(`remote`,null,a.causes.NO_ACK))},l.TIMER_H)}_createRTCConnection(e,t){this._connection=new RTCPeerConnection(e,t),this._connection.addEventListener(`iceconnectionstatechange`,()=>{this._connection.iceConnectionState===`failed`&&this.terminate({cause:a.causes.RTP_TIMEOUT,status_code:408,reason_phrase:a.causes.RTP_TIMEOUT})}),v.debug(`emit "peerconnection"`),this.emit(`peerconnection`,{peerconnection:this._connection})}_createLocalDescription(e,t){if(v.debug(`createLocalDescription()`),e!==`offer`&&e!==`answer`)throw Error(`createLocalDescription() | invalid type "${e}"`);let n=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>e===`offer`?n.createOffer(t).catch(e=>(v.warn(`emit "peerconnection:createofferfailed" [error:%o]`,e),this.emit(`peerconnection:createofferfailed`,e),Promise.reject(e))):n.createAnswer(t).catch(e=>(v.warn(`emit "peerconnection:createanswerfailed" [error:%o]`,e),this.emit(`peerconnection:createanswerfailed`,e),Promise.reject(e)))).then(e=>n.setLocalDescription(e).catch(e=>(this._rtcReady=!0,v.warn(`emit "peerconnection:setlocaldescriptionfailed" [error:%o]`,e),this.emit(`peerconnection:setlocaldescriptionfailed`,e),Promise.reject(e)))).then(()=>{let r=t&&t.iceRestart;if(n.iceGatheringState===`complete`&&!r||n.iceGatheringState===`gathering`&&this._iceReady){this._rtcReady=!0;let t={originator:`local`,type:e,sdp:n.localDescription.sdp};return v.debug(`emit "sdp"`),this.emit(`sdp`,t),Promise.resolve(t.sdp)}return new Promise(t=>{let r=!1,i,a;this._iceReady=!1;let o=()=>{if(r)return;n.removeEventListener(`icecandidate`,i),n.removeEventListener(`icegatheringstatechange`,a),r=!0,this._rtcReady=!0,this._iceReady=!0;let o={originator:`local`,type:e,sdp:n.localDescription.sdp};v.debug(`emit "sdp"`),this.emit(`sdp`,o),t(o.sdp)};n.addEventListener(`icecandidate`,i=e=>{let t=e.candidate;t?this.emit(`icecandidate`,{candidate:t,ready:o}):o()}),n.addEventListener(`icegatheringstatechange`,a=()=>{n.iceGatheringState===`complete`&&o()})})})}_createDialog(e,t,n){let r=t===`UAS`?e.to_tag:e.from_tag,i=t===`UAS`?e.from_tag:e.to_tag,o=e.call_id+r+i,s=this._earlyDialogs[o];if(n)return s?!0:(s=new d(this,e,t,d.C.STATUS_EARLY),s.error?(v.debug(s.error),this._failed(`remote`,e,a.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[o]=s,!0));{if(this._from_tag=e.from_tag,this._to_tag=e.to_tag,s)return s.update(e,t),this._dialog=s,delete this._earlyDialogs[o],!0;let n=new d(this,e,t);return n.error?(v.debug(n.error),this._failed(`remote`,e,a.causes.INTERNAL_ERROR),!1):(this._dialog=n,!0)}}_receiveReinvite(e){v.debug(`receiveReinvite()`);let t=e.hasHeader(`Content-Type`)?e.getHeader(`Content-Type`).toLowerCase():void 0,n={request:e,callback:void 0,reject:i.bind(this)},r=!1;function i(t={}){r=!0;let n=t.status_code||403,i=t.reason_phrase||``,a=c.cloneArray(t.extraHeaders);if(this._status!==y.STATUS_CONFIRMED)return!1;if(n<300||n>=700)throw TypeError(`Invalid status_code: ${n}`);e.reply(n,i,a)}if(this.emit(`reinvite`,n),r)return;if(this._late_sdp=!1,!e.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold(`remote`)),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription(`offer`,this._rtcOfferConstraints)).then(e=>{a.call(this,e)}).catch(()=>{e.reply(500)});return}if(t!==`application/sdp`){v.debug(`invalid Content-Type`),e.reply(415);return}this._processInDialogSdpOffer(e).then(e=>{this._status!==y.STATUS_TERMINATED&&a.call(this,e)}).catch(e=>{v.warn(e)});function a(t){let r=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(e,r),this._late_sdp&&(t=this._mangleOffer(t)),e.reply(200,null,r,t,()=>{this._status=y.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(e,t),this._setACKTimer()}),typeof n.callback==`function`&&n.callback()}}_receiveUpdate(e){v.debug(`receiveUpdate()`);let t=e.hasHeader(`Content-Type`)?e.getHeader(`Content-Type`).toLowerCase():void 0,n={request:e,callback:void 0,reject:i.bind(this)},r=!1;function i(t={}){r=!0;let n=t.status_code||403,i=t.reason_phrase||``,a=c.cloneArray(t.extraHeaders);if(this._status!==y.STATUS_CONFIRMED)return!1;if(n<300||n>=700)throw TypeError(`Invalid status_code: ${n}`);e.reply(n,i,a)}if(this.emit(`update`,n),r)return;if(!e.body){a.call(this,null);return}if(t!==`application/sdp`){v.debug(`invalid Content-Type`),e.reply(415);return}this._processInDialogSdpOffer(e).then(e=>{this._status!==y.STATUS_TERMINATED&&a.call(this,e)}).catch(e=>{v.warn(e)});function a(t){let r=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(e,r),e.reply(200,null,r,t),typeof n.callback==`function`&&n.callback()}}_processInDialogSdpOffer(e){v.debug(`_processInDialogSdpOffer()`);let t=e.parseSDP(),n=!1;for(let e of t.media){if(b.indexOf(e.type)===-1)continue;let r=e.direction||t.direction||`sendrecv`;if(r===`sendonly`||r===`inactive`)n=!0;else{n=!1;break}}let r={originator:`remote`,type:`offer`,sdp:e.body};v.debug(`emit "sdp"`),this.emit(`sdp`,r);let i=new RTCSessionDescription({type:`offer`,sdp:r.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._status===y.STATUS_TERMINATED)throw Error(`terminated`);return this._connection.setRemoteDescription(i).catch(t=>{throw e.reply(488),v.warn(`emit "peerconnection:setremotedescriptionfailed" [error:%o]`,t),this.emit(`peerconnection:setremotedescriptionfailed`,t),t})}).then(()=>{if(this._status===y.STATUS_TERMINATED)throw Error(`terminated`);this._remoteHold===!0&&n===!1?(this._remoteHold=!1,this._onunhold(`remote`)):this._remoteHold===!1&&n===!0&&(this._remoteHold=!0,this._onhold(`remote`))}).then(()=>{if(this._status===y.STATUS_TERMINATED)throw Error(`terminated`);return this._createLocalDescription(`answer`,this._rtcAnswerConstraints).catch(t=>{throw e.reply(500),v.warn(`emit "peerconnection:createtelocaldescriptionfailed" [error:%o]`,t),t})}).catch(e=>{v.warn(`_processInDialogSdpOffer() failed [error: %o]`,e)}),this._connectionPromiseQueue}_receiveRefer(t){if(v.debug(`receiveRefer()`),!t.refer_to){v.debug(`no Refer-To header field present in REFER`),t.reply(400);return}if(t.refer_to.uri.scheme!==a.SIP){v.debug(`Refer-To header field points to a non-SIP URI scheme`),t.reply(416);return}t.reply(202);let n=new h(this,t.cseq);v.debug(`emit "refer"`),this.emit(`refer`,{request:t,accept:(e,t)=>{r.call(this,e,t)},reject:()=>{i.call(this)}});function r(r,i={}){if(r=typeof r==`function`?r:null,this._status!==y.STATUS_WAITING_FOR_ACK&&this._status!==y.STATUS_CONFIRMED)return!1;let a=new e(this._ua);if(a.on(`progress`,({response:e})=>{n.notify(e.status_code,e.reason_phrase)}),a.on(`accepted`,({response:e})=>{n.notify(e.status_code,e.reason_phrase)}),a.on(`_failed`,({message:e,cause:t})=>{e?n.notify(e.status_code,e.reason_phrase):n.notify(487,t)}),t.refer_to.uri.hasHeader(`replaces`)){let e=decodeURIComponent(t.refer_to.uri.getHeader(`replaces`));i.extraHeaders=c.cloneArray(i.extraHeaders),i.extraHeaders.push(`Replaces: ${e}`)}let o=t.refer_to.uri.clone();o.clearHeaders(),a.connect(o,i,r)}function i(){n.notify(603)}}_receiveNotify(e){switch(v.debug(`receiveNotify()`),e.event||e.reply(400),e.event.event){case`refer`:{let t,n;if(e.event.params&&e.event.params.id)t=e.event.params.id,n=this._referSubscribers[t];else if(Object.keys(this._referSubscribers).length===1)n=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{e.reply(400,`Missing event id parameter`);return}if(!n){e.reply(481,`Subscription does not exist`);return}n.receiveNotify(e),e.reply(200);break}default:e.reply(489)}}_receiveReplaces(t){v.debug(`receiveReplaces()`);function n(n){if(this._status!==y.STATUS_WAITING_FOR_ACK&&this._status!==y.STATUS_CONFIRMED)return!1;let r=new e(this._ua);r.on(`confirmed`,()=>{this.terminate()}),r.init_incoming(t,n)}function r(){v.debug(`Replaced INVITE rejected by the user`),t.reply(486)}this.emit(`replaces`,{request:t,accept:e=>{n.call(this,e)},reject:()=>{r.call(this)}})}_sendInitialRequest(e,t,n){let r=new f(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:e=>{this._request=e},onReceiveResponse:e=>{this._receiveInviteResponse(e)}});Promise.resolve().then(()=>{if(n)return n;if(e.audio||e.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(e).catch(e=>{throw this._status===y.STATUS_TERMINATED?Error(`terminated`):(this._failed(`local`,null,a.causes.USER_DENIED_MEDIA_ACCESS),v.warn(`emit "getusermediafailed" [error:%o]`,e),this.emit(`getusermediafailed`,e),e)})}).then(e=>{if(this._status===y.STATUS_TERMINATED)throw Error(`terminated`);return this._localMediaStream=e,e&&e.getTracks().forEach(t=>{this._connection.addTrack(t,e)}),this._connecting(this._request),this._createLocalDescription(`offer`,t).catch(e=>{throw this._failed(`local`,null,a.causes.WEBRTC_ERROR),e})}).then(e=>{if(this._is_canceled||this._status===y.STATUS_TERMINATED)throw Error(`terminated`);this._request.body=e,this._status=y.STATUS_INVITE_SENT,v.debug(`emit "sending" [request:%o]`,this._request),this.emit(`sending`,{request:this._request}),r.send()}).catch(e=>{this._status!==y.STATUS_TERMINATED&&v.warn(e)})}_getDTMFRTPSender(){let e=this._connection.getSenders().find(e=>e.track&&e.track.kind===`audio`);if(!(e&&e.dtmf)){v.warn(`sendDTMF() | no local audio track to send DTMF with`);return}return e.dtmf}_receiveInviteResponse(e){if(v.debug(`receiveInviteResponse()`),this._dialog&&e.status_code>=200&&e.status_code<=299){if(this._dialog.id.call_id===e.call_id&&this._dialog.id.local_tag===e.from_tag&&this._dialog.id.remote_tag===e.to_tag){this.sendRequest(a.ACK);return}{let t=new d(this,e,`UAC`);if(t.error!==void 0){v.debug(t.error);return}this.sendRequest(a.ACK),this.sendRequest(a.BYE);return}}if(this._is_canceled){e.status_code>=100&&e.status_code<200?this._request.cancel(this._cancel_reason):e.status_code>=200&&e.status_code<299&&this._acceptAndTerminate(e);return}if(this._status===y.STATUS_INVITE_SENT||this._status===y.STATUS_1XX_RECEIVED)switch(!0){case/^100$/.test(e.status_code):this._status=y.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(e.status_code):{if(!e.to_tag){v.debug(`1xx response received without to tag`);break}if(e.hasHeader(`contact`)&&!this._createDialog(e,`UAC`,!0))break;if(this._status=y.STATUS_1XX_RECEIVED,!e.body){this._progress(`remote`,e);break}let t={originator:`remote`,type:`answer`,sdp:e.body};v.debug(`emit "sdp"`),this.emit(`sdp`,t);let n=new RTCSessionDescription({type:`answer`,sdp:t.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(n)).then(()=>this._progress(`remote`,e)).catch(e=>{v.warn(`emit "peerconnection:setremotedescriptionfailed" [error:%o]`,e),this.emit(`peerconnection:setremotedescriptionfailed`,e)});break}case/^2[0-9]{2}$/.test(e.status_code):{if(this._status=y.STATUS_CONFIRMED,!e.body){this._acceptAndTerminate(e,400,a.causes.MISSING_SDP),this._failed(`remote`,e,a.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(e,`UAC`))break;let t={originator:`remote`,type:`answer`,sdp:e.body};v.debug(`emit "sdp"`),this.emit(`sdp`,t);let n=new RTCSessionDescription({type:`answer`,sdp:t.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState===`stable`)return this._connection.createOffer(this._rtcOfferConstraints).then(e=>this._connection.setLocalDescription(e)).catch(t=>{this._acceptAndTerminate(e,500,t.toString()),this._failed(`local`,e,a.causes.WEBRTC_ERROR)})}).then(()=>{this._connection.setRemoteDescription(n).then(()=>{this._handleSessionTimersInIncomingResponse(e),this._accepted(`remote`,e),this.sendRequest(a.ACK),this._confirmed(`local`,null)}).catch(t=>{this._acceptAndTerminate(e,488,`Not Acceptable Here`),this._failed(`remote`,e,a.causes.BAD_MEDIA_DESCRIPTION),v.warn(`emit "peerconnection:setremotedescriptionfailed" [error:%o]`,t),this.emit(`peerconnection:setremotedescriptionfailed`,t)})});break}default:{let t=c.sipErrorCause(e.status_code);this._failed(`remote`,e,t)}}}_sendReinvite(e={}){v.debug(`sendReinvite()`);let t=c.cloneArray(e.extraHeaders),n=c.cloneObject(e.eventHandlers),r=e.rtcOfferConstraints||this._rtcOfferConstraints||null,i=!1;t.push(`Contact: ${this._contact}`),t.push(`Content-Type: application/sdp`),this._sessionTimers.running&&t.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?`uac`:`uas`}`),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription(`offer`,r)).then(e=>{e=this._mangleOffer(e);let n={originator:`local`,type:`offer`,sdp:e};v.debug(`emit "sdp"`),this.emit(`sdp`,n),this.sendRequest(a.INVITE,{extraHeaders:t,body:e,eventHandlers:{onSuccessResponse:e=>{o.call(this,e),i=!0},onErrorResponse:e=>{s.call(this,e)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{s()});function o(e){if(this._status===y.STATUS_TERMINATED||(this.sendRequest(a.ACK),i))return;if(this._handleSessionTimersInIncomingResponse(e),!e.body){s.call(this);return}if(!e.hasHeader(`Content-Type`)||e.getHeader(`Content-Type`).toLowerCase()!==`application/sdp`){s.call(this);return}let t={originator:`remote`,type:`answer`,sdp:e.body};v.debug(`emit "sdp"`),this.emit(`sdp`,t);let r=new RTCSessionDescription({type:`answer`,sdp:t.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(r)).then(()=>{n.succeeded&&n.succeeded(e)}).catch(e=>{s.call(this),v.warn(`emit "peerconnection:setremotedescriptionfailed" [error:%o]`,e),this.emit(`peerconnection:setremotedescriptionfailed`,e)})}function s(e){n.failed&&n.failed(e)}}_sendUpdate(e={}){v.debug(`sendUpdate()`);let t=c.cloneArray(e.extraHeaders),n=c.cloneObject(e.eventHandlers),r=e.rtcOfferConstraints||this._rtcOfferConstraints||null,i=e.sdpOffer||!1,o=!1;t.push(`Contact: ${this._contact}`),this._sessionTimers.running&&t.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?`uac`:`uas`}`),i?(t.push(`Content-Type: application/sdp`),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription(`offer`,r)).then(e=>{e=this._mangleOffer(e);let n={originator:`local`,type:`offer`,sdp:e};v.debug(`emit "sdp"`),this.emit(`sdp`,n),this.sendRequest(a.UPDATE,{extraHeaders:t,body:e,eventHandlers:{onSuccessResponse:e=>{s.call(this,e),o=!0},onErrorResponse:e=>{l.call(this,e)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{l.call(this)})):this.sendRequest(a.UPDATE,{extraHeaders:t,eventHandlers:{onSuccessResponse:e=>{s.call(this,e)},onErrorResponse:e=>{l.call(this,e)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}});function s(e){if(this._status!==y.STATUS_TERMINATED&&!o){if(this._handleSessionTimersInIncomingResponse(e),i){if(!e.body){l.call(this);return}if(!e.hasHeader(`Content-Type`)||e.getHeader(`Content-Type`).toLowerCase()!==`application/sdp`){l.call(this);return}let t={originator:`remote`,type:`answer`,sdp:e.body};v.debug(`emit "sdp"`),this.emit(`sdp`,t);let r=new RTCSessionDescription({type:`answer`,sdp:t.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(r)).then(()=>{n.succeeded&&n.succeeded(e)}).catch(e=>{l.call(this),v.warn(`emit "peerconnection:setremotedescriptionfailed" [error:%o]`,e),this.emit(`peerconnection:setremotedescriptionfailed`,e)})}else n.succeeded&&n.succeeded(e)}}function l(e){n.failed&&n.failed(e)}}_acceptAndTerminate(e,t,n){v.debug(`acceptAndTerminate()`);let r=[];t&&(n=n||a.REASON_PHRASE[t]||``,r.push(`Reason: SIP ;cause=${t}; text="${n}"`)),(this._dialog||this._createDialog(e,`UAC`))&&(this.sendRequest(a.ACK),this.sendRequest(a.BYE,{extraHeaders:r})),this._status=y.STATUS_TERMINATED}_mangleOffer(e){if(!this._localHold&&!this._remoteHold)return e;if(e=r.parse(e),this._localHold&&!this._remoteHold){v.debug(`mangleOffer() | me on hold, mangling offer`);for(let t of e.media)b.indexOf(t.type)!==-1&&(t.direction?t.direction===`sendrecv`?t.direction=`sendonly`:t.direction===`recvonly`&&(t.direction=`inactive`):t.direction=`sendonly`)}else if(this._localHold&&this._remoteHold){v.debug(`mangleOffer() | both on hold, mangling offer`);for(let t of e.media)b.indexOf(t.type)!==-1&&(t.direction=`inactive`)}else if(this._remoteHold){v.debug(`mangleOffer() | remote on hold, mangling offer`);for(let t of e.media)b.indexOf(t.type)!==-1&&(t.direction?t.direction===`sendrecv`?t.direction=`recvonly`:t.direction===`recvonly`&&(t.direction=`inactive`):t.direction=`recvonly`)}return r.write(e)}_setLocalMediaStatus(){let e=!0,t=!0;(this._localHold||this._remoteHold)&&(e=!1,t=!1),this._audioMuted&&(e=!1),this._videoMuted&&(t=!1),this._toggleMuteAudio(!e),this._toggleMuteVideo(!t)}_handleSessionTimersInIncomingRequest(e,t){if(!this._sessionTimers.enabled)return;let n;e.session_expires&&e.session_expires>=a.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=e.session_expires,n=e.session_expires_refresher||`uas`):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,n=`uas`),t.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${n}`),this._sessionTimers.refresher=n===`uas`,this._runSessionTimer()}_handleSessionTimersInIncomingResponse(e){if(!this._sessionTimers.enabled)return;let t;e.session_expires&&e.session_expires>=a.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=e.session_expires,t=e.session_expires_refresher||`uac`):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,t=`uac`),this._sessionTimers.refresher=t===`uac`,this._runSessionTimer()}_runSessionTimer(){let e=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(()=>{this._status!==y.STATUS_TERMINATED&&this.isReadyToReOffer()&&(v.debug(`runSessionTimer() | sending session refresh request`),this._sessionTimers.refreshMethod===a.UPDATE?this._sendUpdate():this._sendReinvite())},e*500):this._sessionTimers.timer=setTimeout(()=>{this._status!==y.STATUS_TERMINATED&&(v.warn(`runSessionTimer() | timer expired, terminating the session`),this.terminate({cause:a.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:`Session Timer Expired`}))},e*1100)}_toggleMuteAudio(e){let t=this._connection.getSenders().filter(e=>e.track&&e.track.kind===`audio`);for(let n of t)n.track.enabled=!e}_toggleMuteVideo(e){let t=this._connection.getSenders().filter(e=>e.track&&e.track.kind===`video`);for(let n of t)n.track.enabled=!e}_newRTCSession(e,t){v.debug(`newRTCSession()`),this._ua.newRTCSession(this,{originator:e,session:this,request:t})}_connecting(e){v.debug(`session connecting`),v.debug(`emit "connecting"`),this.emit(`connecting`,{request:e})}_progress(e,t){v.debug(`session progress`),v.debug(`emit "progress"`),this.emit(`progress`,{originator:e,response:t||null})}_accepted(e,t){v.debug(`session accepted`),this._start_time=new Date,v.debug(`emit "accepted"`),this.emit(`accepted`,{originator:e,response:t||null})}_confirmed(e,t){v.debug(`session confirmed`),this._is_confirmed=!0,v.debug(`emit "confirmed"`),this.emit(`confirmed`,{originator:e,ack:t||null})}_ended(e,t,n){v.debug(`session ended`),this._end_time=new Date,this._close(),v.debug(`emit "ended"`),this.emit(`ended`,{originator:e,message:t||null,cause:n})}_failed(e,t,n){v.debug(`session failed`),v.debug(`emit "_failed"`),this.emit(`_failed`,{originator:e,message:t||null,cause:n}),this._close(),v.debug(`emit "failed"`),this.emit(`failed`,{originator:e,message:t||null,cause:n})}_onhold(e){v.debug(`session onhold`),this._setLocalMediaStatus(),v.debug(`emit "hold"`),this.emit(`hold`,{originator:e})}_onunhold(e){v.debug(`session onunhold`),this._setLocalMediaStatus(),v.debug(`emit "unhold"`),this.emit(`unhold`,{originator:e})}_onmute({audio:e,video:t}){v.debug(`session onmute`),this._setLocalMediaStatus(),v.debug(`emit "muted"`),this.emit(`muted`,{audio:e,video:t})}_onunmute({audio:e,video:t}){v.debug(`session onunmute`),this._setLocalMediaStatus(),v.debug(`emit "unmuted"`),this.emit(`unmuted`,{audio:e,video:t})}}})),rn=c(((e,t)=>{var n=K().EventEmitter,r=H(),i=q(),a=V(),o=G(),s=U(),c=J(),l=X(),u=Zt(),d=new i(`Subscriber`),f={SUBSCRIBE_RESPONSE_TIMEOUT:0,SUBSCRIBE_TRANSPORT_ERROR:1,SUBSCRIBE_NON_OK_RESPONSE:2,SUBSCRIBE_WRONG_OK_RESPONSE:3,SUBSCRIBE_AUTHENTICATION_FAILED:4,UNSUBSCRIBE_TIMEOUT:5,FINAL_NOTIFY_RECEIVED:6,WRONG_NOTIFY_RECEIVED:7,STATE_PENDING:0,STATE_ACTIVE:1,STATE_TERMINATED:2,STATE_INIT:3,STATE_WAITING_NOTIFY:4,DEFAULT_EXPIRES_SEC:900};t.exports=class extends n{static get C(){return f}constructor(e,t,n,r,{expires:i,contentType:a,allowEvents:c,params:l,extraHeaders:u}){if(d.debug(`new`),super(),!t)throw TypeError(`Not enough arguments: Missing target`);if(!n)throw TypeError(`Not enough arguments: Missing eventName`);if(!r)throw TypeError(`Not enough arguments: Missing accept`);let p=s.parse(n,`Event`);if(p===-1)throw TypeError(`Missing Event header field`);this._ua=e,this._target=t,(!o.isDecimal(i)||i<=0)&&(i=f.DEFAULT_EXPIRES_SEC),this._expires=i,this._content_type=a,this._params=o.cloneObject(l),this._params.from_uri||(this._params.from_uri=this._ua.configuration.uri),this._params.from_tag=o.newTag(),this._params.to_tag=null,this._params.call_id=o.createRandomToken(20),this._params.cseq===void 0&&(this._params.cseq=Math.floor(Math.random()*1e4+1)),this._state=f.STATE_INIT,this._dialog=null,this._expires_timer=null,this._expires_timestamp=null,this._terminated=!1,this._event_name=p.event,this._event_id=p.params&&p.params.id;let m=this._event_name;if(this._event_id&&(m+=`;id=${this._event_id}`),this._headers=o.cloneArray(u),this._headers=this._headers.concat([`Event: ${m}`,`Expires: ${this._expires}`,`Accept: ${r}`]),!this._headers.find(e=>e.startsWith(`Contact`))){let e=`Contact: ${this._ua._contact.toString()}`;this._headers.push(e)}c&&this._headers.push(`Allow-Events: ${c}`),this._queue=[],this._data={}}get C(){return f}get state(){return this._state}get id(){return this._dialog?this._dialog.id:null}get data(){return this._data}set data(e){this._data=e}onRequestTimeout(){this._terminateDialog(f.SUBSCRIBE_RESPONSE_TIMEOUT)}onTransportError(){this._terminateDialog(f.SUBSCRIBE_TRANSPORT_ERROR)}receiveRequest(e){if(e.method!==a.NOTIFY){d.warn(`received non-NOTIFY request`),e.reply(405);return}let t=e.parseHeader(`Event`);if(!t){d.warn(`missing Event header`),e.reply(400),this._terminateDialog(f.WRONG_NOTIFY_RECEIVED);return}let n=t.event,r=t.params&&t.params.id;if(n!==this._event_name||r!==this._event_id){d.warn(`Event header does not match the one in SUBSCRIBE request`),e.reply(489),this._terminateDialog(f.WRONG_NOTIFY_RECEIVED);return}let i=e.parseHeader(`subscription-state`);if(!i){d.warn(`missing Subscription-State header`),e.reply(400),this._terminateDialog(f.WRONG_NOTIFY_RECEIVED);return}let o=this._parseSubscriptionState(i.state);if(o===void 0){d.warn(`Invalid Subscription-State header value: ${i.state}`),e.reply(400),this._terminateDialog(f.WRONG_NOTIFY_RECEIVED);return}e.reply(200);let s=this._state;if(s!==f.STATE_TERMINATED&&o!==f.STATE_TERMINATED&&(this._state=o,i.expires!==void 0)){let e=i.expires,t=new Date().getTime()+e*1e3;this._expires_timestamp-t>2e3&&(d.debug(`update sending re-SUBSCRIBE time`),this._scheduleSubscribe(e))}s!==f.STATE_PENDING&&o===f.STATE_PENDING?(d.debug(`emit "pending"`),this.emit(`pending`)):s!==f.STATE_ACTIVE&&o===f.STATE_ACTIVE&&(d.debug(`emit "active"`),this.emit(`active`));let c=e.body,l=o===f.STATE_TERMINATED;if(c){let t=e.getHeader(`content-type`);d.debug(`emit "notify"`),this.emit(`notify`,l,e,c,t)}if(l){let e=i.reason,t;i.params&&i.params[`retry-after`]!==void 0&&(t=parseInt(i.params[`retry-after`])),this._terminateDialog(f.FINAL_NOTIFY_RECEIVED,e,t)}}subscribe(e=null){d.debug(`subscribe()`),this._state===f.STATE_INIT?this._sendInitialSubscribe(e,this._headers):this._sendSubsequentSubscribe(e,this._headers)}terminate(e=null){if(d.debug(`terminate()`),this._state===f.STATE_INIT)throw new r.InvalidStateError(this._state);if(this._terminated)return;this._terminated=!0;let t=this._headers.map(e=>e.startsWith(`Expires`)?`Expires: 0`:e);this._sendSubsequentSubscribe(e,t)}_terminateDialog(e,t=void 0,n=void 0){this._state!==f.STATE_TERMINATED&&(this._state=f.STATE_TERMINATED,clearTimeout(this._expires_timer),this._dialog&&=(this._dialog.terminate(),null),d.debug(`emit "terminated" code=${e}`),this.emit(`terminated`,e,t,n))}_sendInitialSubscribe(e,t){if(e){if(!this._content_type)throw TypeError(`content_type is undefined`);t=o.cloneArray(t),t.push(`Content-Type: ${this._content_type}`)}this._state=f.STATE_WAITING_NOTIFY;let n=new c.OutgoingRequest(a.SUBSCRIBE,this._ua.normalizeTarget(this._target),this._ua,this._params,t,e);new l(this._ua,n,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onReceiveResponse:e=>{this._receiveSubscribeResponse(e)}}).send()}_sendSubsequentSubscribe(e,t){if(this._state!==f.STATE_TERMINATED){if(!this._dialog){d.debug(`enqueue subscribe`),this._queue.push({body:e,headers:o.cloneArray(t)});return}if(e){if(!this._content_type)throw TypeError(`content_type is undefined`);t=o.cloneArray(t),t.push(`Content-Type: ${this._content_type}`)}this._dialog.sendRequest(a.SUBSCRIBE,{body:e,extraHeaders:t,eventHandlers:{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onSuccessResponse:e=>{this._receiveSubscribeResponse(e)},onErrorResponse:e=>{this._receiveSubscribeResponse(e)},onDialogError:e=>{this._receiveSubscribeResponse(e)}}})}}_receiveSubscribeResponse(e){if(this._state!==f.STATE_TERMINATED){if(e.status_code>=200&&e.status_code<300){if(this._dialog===null){let t=new u(this,e,`UAC`);if(t.error){d.warn(t.error),this._terminateDialog(f.SUBSCRIBE_WRONG_OK_RESPONSE);return}this._dialog=t,d.debug(`emit "accepted"`),this.emit(`accepted`);for(let e of this._queue)d.debug(`dequeue subscribe`),this._sendSubsequentSubscribe(e.body,e.headers)}let t=e.getHeader(`expires`),n=parseInt(t);(!o.isDecimal(n)||n<=0)&&(d.warn(`response without Expires header, setting a default value of ${f.DEFAULT_EXPIRES_SEC}`),n=f.DEFAULT_EXPIRES_SEC),n>0&&this._scheduleSubscribe(n)}else e.status_code===401||e.status_code===407?this._terminateDialog(f.SUBSCRIBE_AUTHENTICATION_FAILED):e.status_code>=300&&this._terminateDialog(f.SUBSCRIBE_NON_OK_RESPONSE)}}_scheduleSubscribe(e){let t=e>=140?e*1e3/2+Math.floor((e/2-70)*1e3*Math.random()):e*1e3-5e3;this._expires_timestamp=new Date().getTime()+e*1e3,d.debug(`next SUBSCRIBE will be sent in ${Math.floor(t/1e3)} sec`),clearTimeout(this._expires_timer),this._expires_timer=setTimeout(()=>{this._expires_timer=null,this._sendSubsequentSubscribe(null,this._headers)},t)}_parseSubscriptionState(e){switch(e){case`pending`:return f.STATE_PENDING;case`active`:return f.STATE_ACTIVE;case`terminated`:return f.STATE_TERMINATED;case`init`:return f.STATE_INIT;case`notify_wait`:return f.STATE_WAITING_NOTIFY;default:return}}}})),an=c(((e,t)=>{var n=K().EventEmitter,r=H(),i=q(),a=V(),o=G(),s=Zt(),c=new i(`Notifier`),l={NOTIFY_RESPONSE_TIMEOUT:0,NOTIFY_TRANSPORT_ERROR:1,NOTIFY_NON_OK_RESPONSE:2,NOTIFY_AUTHENTICATION_FAILED:3,FINAL_NOTIFY_SENT:4,UNSUBSCRIBE_RECEIVED:5,SUBSCRIPTION_EXPIRED:6,STATE_PENDING:0,STATE_ACTIVE:1,STATE_TERMINATED:2,DEFAULT_EXPIRES_SEC:900};t.exports=class e extends n{static get C(){return l}static init_incoming(t,n){try{e.checkSubscribe(t)}catch(e){c.warn(`Notifier.init_incoming: invalid request. Error: `,e.message),t.reply(405);return}n()}static checkSubscribe(e){if(!e)throw TypeError(`Not enough arguments. Missing subscribe request`);if(e.method!==a.SUBSCRIBE)throw TypeError(`Invalid method for Subscribe request`);if(!e.hasHeader(`contact`))throw TypeError(`Missing Contact header in subscribe request`);if(!e.hasHeader(`event`))throw TypeError(`Missing Event header in subscribe request`);let t=e.getHeader(`expires`);if(t){let e=parseInt(t);if(!o.isDecimal(e)||e<0)throw TypeError(`Invalid Expires header field in subscribe request`)}}constructor(t,n,r,{extraHeaders:i,allowEvents:a,pending:s,defaultExpires:u}){if(c.debug(`new`),super(),!r)throw TypeError(`Not enough arguments. Missing contentType`);e.checkSubscribe(n);let d=n.getHeader(`event`);this._ua=t,this._initial_subscribe=n,this._expires_timestamp=null,this._expires_timer=null,this._defaultExpires=u||l.DEFAULT_EXPIRES_SEC,this._state=s?l.STATE_PENDING:l.STATE_ACTIVE,this._content_type=r,this._headers=o.cloneArray(i),this._headers.push(`Event: ${d}`),this._contact=this._headers.find(e=>e.startsWith(`Contact`)),this._contact||(this._contact=`Contact: ${this._ua._contact.toString()}`,this._headers.push(this._contact)),a&&this._headers.push(`Allow-Events: ${a}`),this._target=n.from.uri.user,n.to_tag=o.newTag(),this._data={}}get C(){return l}get state(){return this._state}get id(){return this._dialog?this._dialog.id:null}get data(){return this._data}set data(e){this._data=e}receiveRequest(e){if(e.method!==a.SUBSCRIBE){e.reply(405);return}this._setExpires(e),this._dialog||=new s(this,e,`UAS`),e.reply(200,null,[`Expires: ${this._expires}`,`${this._contact}`]);let t=e.body,n=e.getHeader(`content-type`),r=this._expires===0;r||this._setExpiresTimer(),c.debug(`emit "subscribe"`),this.emit(`subscribe`,r,e,t,n),r&&this._terminateDialog(l.UNSUBSCRIBE_RECEIVED)}start(){if(c.debug(`start()`),this._state===l.STATE_TERMINATED)throw new r.InvalidStateError(this._state);this.receiveRequest(this._initial_subscribe)}setActiveState(){if(c.debug(`setActiveState()`),this._state===l.STATE_TERMINATED)throw new r.InvalidStateError(this._state);this._state===l.STATE_PENDING&&(this._state=l.STATE_ACTIVE)}notify(e=null){if(c.debug(`notify()`),this._state===l.STATE_TERMINATED)throw new r.InvalidStateError(this._state);let t=Math.floor((this._expires_timestamp-new Date().getTime())/1e3);t<=0?(this._expires_timer||c.error(`expires timer is not set`),clearTimeout(this._expires_timer),this.terminate(e,`timeout`)):this._sendNotify([`;expires=${t}`],e)}terminate(e=null,t=null,n=null){if(c.debug(`terminate()`),this._state===l.STATE_TERMINATED)return;let r=[];t&&r.push(`;reason=${t}`),n!==null&&r.push(`;retry-after=${n}`),this._sendNotify(r,e,null,`terminated`),this._terminateDialog(t===`timeout`?l.SUBSCRIPTION_EXPIRED:l.FINAL_NOTIFY_SENT)}_terminateDialog(e){this._state!==l.STATE_TERMINATED&&(this._state=l.STATE_TERMINATED,clearTimeout(this._expires_timer),this._dialog&&=(this._dialog.terminate(),null),c.debug(`emit "terminated" code=${e}`),this.emit(`terminated`,e))}_setExpires(e){e.hasHeader(`expires`)?this._expires=parseInt(e.getHeader(`expires`)):(this._expires=this._defaultExpires,c.debug(`missing Expires header field, default value set: ${this._expires}`))}_sendNotify(e,t=null,n=null,r=null){if(this._state===l.STATE_TERMINATED){c.warn(`final notify already sent`);return}let i=`Subscription-State: ${r||this._parseState()}`;for(let t of e)i+=t;let s=o.cloneArray(this._headers);s.push(i),n&&(s=s.concat(n)),t&&s.push(`Content-Type: ${this._content_type}`),this._dialog.sendRequest(a.NOTIFY,{body:t,extraHeaders:s,eventHandlers:{onRequestTimeout:()=>{this._terminateDialog(l.NOTIFY_RESPONSE_TIMEOUT)},onTransportError:()=>{this._terminateDialog(l.NOTIFY_TRANSPORT_ERROR)},onErrorResponse:e=>{e.status_code===401||e.status_code===407?this._terminateDialog(l.NOTIFY_AUTHENTICATION_FAILED):this._terminateDialog(l.NOTIFY_NON_OK_RESPONSE)},onDialogError:()=>{this._terminateDialog(l.NOTIFY_NON_OK_RESPONSE)}}})}_setExpiresTimer(){this._expires_timestamp=new Date().getTime()+this._expires*1e3,clearTimeout(this._expires_timer),this._expires_timer=setTimeout(()=>{this._state!==l.STATE_TERMINATED&&(c.debug(`emit "expired"`),this.emit(`expired`),this.terminate(null,`timeout`))},this._expires*1e3)}_parseState(){switch(this._state){case l.STATE_PENDING:return`pending`;case l.STATE_ACTIVE:return`active`;case l.STATE_TERMINATED:return`terminated`;default:throw TypeError(`wrong state value`)}}}})),on=c(((e,t)=>{var n=K().EventEmitter,r=q(),i=V(),a=J(),o=G(),s=X(),c=H(),l=W(),u=new r(`Message`);t.exports=class extends n{constructor(e){super(),this._ua=e,this._request=null,this._closed=!1,this._direction=null,this._local_identity=null,this._remote_identity=null,this._is_replied=!1,this._data={}}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}send(e,t,n={}){let r=e;if(e===void 0||t===void 0)throw TypeError(`Not enough arguments`);if(e=this._ua.normalizeTarget(e),!e)throw TypeError(`Invalid target: ${r}`);let c=o.cloneArray(n.extraHeaders),u=o.cloneObject(n.eventHandlers),d=n.contentType||`text/plain`,f={};n.fromUserName&&(f.from_uri=new l(`sip`,n.fromUserName,this._ua.configuration.uri.host),c.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),n.fromDisplayName&&(f.from_display_name=n.fromDisplayName);for(let e in u)Object.prototype.hasOwnProperty.call(u,e)&&this.on(e,u[e]);c.push(`Content-Type: ${d}`),this._request=new a.OutgoingRequest(i.MESSAGE,e,this._ua,f,c),t&&(this._request.body=t);let p=new s(this._ua,this._request,{onRequestTimeout:()=>{this._onRequestTimeout()},onTransportError:()=>{this._onTransportError()},onReceiveResponse:e=>{this._receiveResponse(e)}});this._newMessage(`local`,this._request),p.send()}init_incoming(e){this._request=e,this._newMessage(`remote`,e),this._is_replied||(this._is_replied=!0,e.reply(200)),this._close()}accept(e={}){let t=o.cloneArray(e.extraHeaders),n=e.body;if(this._direction!==`incoming`)throw new c.NotSupportedError(`"accept" not supported for outgoing Message`);if(this._is_replied)throw Error(`incoming Message already replied`);this._is_replied=!0,this._request.reply(200,null,t,n)}reject(e={}){let t=e.status_code||480,n=e.reason_phrase,r=o.cloneArray(e.extraHeaders),i=e.body;if(this._direction!==`incoming`)throw new c.NotSupportedError(`"reject" not supported for outgoing Message`);if(this._is_replied)throw Error(`incoming Message already replied`);if(t<300||t>=700)throw TypeError(`Invalid status_code: ${t}`);this._is_replied=!0,this._request.reply(t,n,r,i)}_receiveResponse(e){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(e.status_code):break;case/^2[0-9]{2}$/.test(e.status_code):this._succeeded(`remote`,e);break;default:{let t=o.sipErrorCause(e.status_code);this._failed(`remote`,e,t);break}}}_onRequestTimeout(){this._closed||this._failed(`system`,null,i.causes.REQUEST_TIMEOUT)}_onTransportError(){this._closed||this._failed(`system`,null,i.causes.CONNECTION_ERROR)}_close(){this._closed=!0,this._ua.destroyMessage(this)}_newMessage(e,t){e===`remote`?(this._direction=`incoming`,this._local_identity=t.to,this._remote_identity=t.from):e===`local`&&(this._direction=`outgoing`,this._local_identity=t.from,this._remote_identity=t.to),this._ua.newMessage(this,{originator:e,message:this,request:t})}_failed(e,t,n){u.debug(`MESSAGE failed`),this._close(),u.debug(`emit "failed"`),this.emit(`failed`,{originator:e,response:t||null,cause:n})}_succeeded(e,t){u.debug(`MESSAGE succeeded`),this._close(),u.debug(`emit "succeeded"`),this.emit(`succeeded`,{originator:e,response:t})}}})),sn=c(((e,t)=>{var n=K().EventEmitter,r=q(),i=V(),a=J(),o=G(),s=X(),c=H(),l=new r(`Options`);t.exports=class extends n{constructor(e){super(),this._ua=e,this._request=null,this._closed=!1,this._direction=null,this._local_identity=null,this._remote_identity=null,this._is_replied=!1,this._data={}}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}send(e,t,n={}){let r=e;if(e===void 0)throw TypeError(`A target is required for OPTIONS`);if(e=this._ua.normalizeTarget(e),!e)throw TypeError(`Invalid target: ${r}`);let c=o.cloneArray(n.extraHeaders),l=o.cloneObject(n.eventHandlers),u=n.contentType||`application/sdp`;for(let e in l)Object.prototype.hasOwnProperty.call(l,e)&&this.on(e,l[e]);c.push(`Content-Type: ${u}`),this._request=new a.OutgoingRequest(i.OPTIONS,e,this._ua,null,c),t&&(this._request.body=t);let d=new s(this._ua,this._request,{onRequestTimeout:()=>{this._onRequestTimeout()},onTransportError:()=>{this._onTransportError()},onReceiveResponse:e=>{this._receiveResponse(e)}});this._newOptions(`local`,this._request),d.send()}init_incoming(e){this._request=e,this._newOptions(`remote`,e),this._is_replied||(this._is_replied=!0,e.reply(200)),this._close()}accept(e={}){let t=o.cloneArray(e.extraHeaders),n=e.body;if(this._direction!==`incoming`)throw new c.NotSupportedError(`"accept" not supported for outgoing Options`);if(this._is_replied)throw Error(`incoming Options already replied`);this._is_replied=!0,this._request.reply(200,null,t,n)}reject(e={}){let t=e.status_code||480,n=e.reason_phrase,r=o.cloneArray(e.extraHeaders),i=e.body;if(this._direction!==`incoming`)throw new c.NotSupportedError(`"reject" not supported for outgoing Options`);if(this._is_replied)throw Error(`incoming Options already replied`);if(t<300||t>=700)throw TypeError(`Invalid status_code: ${t}`);this._is_replied=!0,this._request.reply(t,n,r,i)}_receiveResponse(e){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(e.status_code):break;case/^2[0-9]{2}$/.test(e.status_code):this._succeeded(`remote`,e);break;default:{let t=o.sipErrorCause(e.status_code);this._failed(`remote`,e,t);break}}}_onRequestTimeout(){this._closed||this._failed(`system`,null,i.causes.REQUEST_TIMEOUT)}_onTransportError(){this._closed||this._failed(`system`,null,i.causes.CONNECTION_ERROR)}_close(){this._closed=!0,this._ua.destroyMessage(this)}_newOptions(e,t){e===`remote`?(this._direction=`incoming`,this._local_identity=t.to,this._remote_identity=t.from):e===`local`&&(this._direction=`outgoing`,this._local_identity=t.from,this._remote_identity=t.to),this._ua.newOptions(this,{originator:e,message:this,request:t})}_failed(e,t,n){l.debug(`OPTIONS failed`),this._close(),l.debug(`emit "failed"`),this.emit(`failed`,{originator:e,response:t||null,cause:n})}_succeeded(e,t){l.debug(`OPTIONS succeeded`),this._close(),l.debug(`emit "succeeded"`),this.emit(`succeeded`,{originator:e,response:t})}}})),cn=c((e=>{var t=q(),n=G(),r=U(),i=new t(`Socket`);e.isSocket=e=>{if(Array.isArray(e))return!1;if(e===void 0)return i.warn(`undefined JsSIP.Socket instance`),!1;try{if(!n.isString(e.url))throw i.warn(`missing or invalid JsSIP.Socket url property`),Error(`Missing or invalid JsSIP.Socket url property`);if(!n.isString(e.via_transport))throw i.warn(`missing or invalid JsSIP.Socket via_transport property`),Error(`Missing or invalid JsSIP.Socket via_transport property`);if(r.parse(e.sip_uri,`SIP_URI`)===-1)throw i.warn(`missing or invalid JsSIP.Socket sip_uri property`),Error(`missing or invalid JsSIP.Socket sip_uri property`)}catch{return!1}try{[`connect`,`disconnect`,`send`].forEach(t=>{if(!n.isFunction(e[t]))throw i.warn(`missing or invalid JsSIP.Socket method: ${t}`),Error(`Missing or invalid JsSIP.Socket method: ${t}`)})}catch{return!1}return!0}})),ln=c(((e,t)=>{var n=q(),r=cn(),i=V(),a=new n(`Transport`),o={STATUS_CONNECTED:0,STATUS_CONNECTING:1,STATUS_DISCONNECTED:2,SOCKET_STATUS_READY:0,SOCKET_STATUS_ERROR:1,recovery_options:{min_interval:i.CONNECTION_RECOVERY_MIN_INTERVAL,max_interval:i.CONNECTION_RECOVERY_MAX_INTERVAL}};t.exports=class{constructor(e,t=o.recovery_options){a.debug(`new()`),this.status=o.STATUS_DISCONNECTED,this.socket=null,this.sockets=[],this.recovery_options=t,this.recover_attempts=0,this.recovery_timer=null,this.close_requested=!1;try{this.textDecoder=new TextDecoder(`utf8`)}catch(e){a.warn(`cannot use TextDecoder: ${e}`)}if(e===void 0)throw TypeError(`Invalid argument. undefined 'sockets' argument`);e instanceof Array||(e=[e]),e.forEach(function(e){if(!r.isSocket(e.socket))throw TypeError(`Invalid argument. invalid 'JsSIP.Socket' instance`);if(e.weight&&!Number(e.weight))throw TypeError(`Invalid argument. 'weight' attribute is not a number`);this.sockets.push({socket:e.socket,weight:e.weight||0,status:o.SOCKET_STATUS_READY})},this),this._getSocket()}get via_transport(){return this.socket.via_transport}get url(){return this.socket.url}get sip_uri(){return this.socket.sip_uri}connect(){if(a.debug(`connect()`),this.isConnected()){a.debug(`Transport is already connected`);return}if(this.isConnecting()){a.debug(`Transport is connecting`);return}this.close_requested=!1,this.status=o.STATUS_CONNECTING,this.onconnecting({socket:this.socket,attempts:this.recover_attempts}),this.close_requested||(this.socket.onconnect=this._onConnect.bind(this),this.socket.ondisconnect=this._onDisconnect.bind(this),this.socket.ondata=this._onData.bind(this),this.socket.connect())}disconnect(){a.debug(`close()`),this.close_requested=!0,this.recover_attempts=0,this.status=o.STATUS_DISCONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.socket.onconnect=()=>{},this.socket.ondisconnect=()=>{},this.socket.ondata=()=>{},this.socket.disconnect(),this.ondisconnect({socket:this.socket,error:!1})}send(e){if(a.debug(`send()`),!this.isConnected())return a.warn(`unable to send message, transport is not connected`),!1;let t=e.toString();return a.debug(`sending message:\n\n${t}\n`),this.socket.send(t)}isConnected(){return this.status===o.STATUS_CONNECTED}isConnecting(){return this.status===o.STATUS_CONNECTING}_reconnect(){this.recover_attempts+=1;let e=Math.floor(Math.random()*2**this.recover_attempts+1);e<this.recovery_options.min_interval?e=this.recovery_options.min_interval:e>this.recovery_options.max_interval&&(e=this.recovery_options.max_interval),a.debug(`reconnection attempt: ${this.recover_attempts}. next connection attempt in ${e} seconds`),this.recovery_timer=setTimeout(()=>{!this.close_requested&&!(this.isConnected()||this.isConnecting())&&(this._getSocket(),this.connect())},e*1e3)}_getSocket(){let e=[];if(this.sockets.forEach(t=>{t.status!==o.SOCKET_STATUS_ERROR&&(e.length===0?e.push(t):t.weight>e[0].weight?e=[t]:t.weight===e[0].weight&&e.push(t))}),e.length===0){this.sockets.forEach(e=>{e.status=o.SOCKET_STATUS_READY}),this._getSocket();return}let t=Math.floor(Math.random()*e.length);this.socket=e[t].socket}_onConnect(){this.recover_attempts=0,this.status=o.STATUS_CONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.onconnect({socket:this})}_onDisconnect(e,t,n){this.status=o.STATUS_DISCONNECTED,this.ondisconnect({socket:this.socket,error:e,code:t,reason:n}),!this.close_requested&&(this.sockets.forEach(function(e){this.socket===e.socket&&(e.status=o.SOCKET_STATUS_ERROR)},this),this._reconnect(e))}_onData(e){if(e===`\r
|
|
13
|
+
`,this.transport.send(r)}},IncomingResponse:class extends d{constructor(){super(),this.headers={},this.status_code=null,this.reason_phrase=null}}}})),qt=c(((e,t)=>{var n=J(),r=K(),i=new n(`DigestAuthentication`);t.exports=class{constructor(e){this._credentials=e,this._cnonce=null,this._nc=0,this._ncHex=`00000000`,this._algorithm=null,this._realm=null,this._nonce=null,this._opaque=null,this._stale=null,this._qop=null,this._method=null,this._uri=null,this._ha1=null,this._response=null}get(e){switch(e){case`realm`:return this._realm;case`ha1`:return this._ha1;default:i.warn(`get() | cannot get "%s" parameter`,e);return}}authenticate({method:e,ruri:t,body:n},a,o=null){if(this._algorithm=a.algorithm,this._realm=a.realm,this._nonce=a.nonce,this._opaque=a.opaque,this._stale=a.stale,this._algorithm){if(this._algorithm!==`MD5`)return i.warn(`authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted`),!1}else this._algorithm=`MD5`;if(!this._nonce)return i.warn(`authenticate() | challenge without Digest nonce, authentication aborted`),!1;if(!this._realm)return i.warn(`authenticate() | challenge without Digest realm, authentication aborted`),!1;if(!this._credentials.password){if(!this._credentials.ha1)return i.warn(`authenticate() | no plain SIP password nor ha1 provided, authentication aborted`),!1;if(this._credentials.realm!==this._realm)return i.warn('authenticate() | no plain SIP password, and stored `realm` does not match the given `realm`, cannot authenticate [stored:"%s", given:"%s"]',this._credentials.realm,this._realm),!1}if(a.qop){if(a.qop.indexOf(`auth-int`)>-1)this._qop=`auth-int`;else if(a.qop.indexOf(`auth`)>-1)this._qop=`auth`;else return i.warn(`authenticate() | challenge without Digest qop different than "auth" or "auth-int", authentication aborted`),!1}else this._qop=null;this._method=e,this._uri=t,this._cnonce=o||r.createRandomToken(12),this._nc+=1;let s=Number(this._nc).toString(16);this._ncHex=`00000000`.substr(0,8-s.length)+s,this._nc===4294967296&&(this._nc=1,this._ncHex=`00000001`),this._ha1=this._credentials.password?r.calculateMD5(`${this._credentials.username}:${this._realm}:${this._credentials.password}`):this._credentials.ha1;let c,l;return this._qop===`auth`?(c=`${this._method}:${this._uri}`,l=r.calculateMD5(c),i.debug(`authenticate() | using qop=auth [a2:"%s"]`,c),this._response=r.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth:${l}`)):this._qop===`auth-int`?(c=`${this._method}:${this._uri}:${r.calculateMD5(n||``)}`,l=r.calculateMD5(c),i.debug(`authenticate() | using qop=auth-int [a2:"%s"]`,c),this._response=r.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth-int:${l}`)):this._qop===null&&(c=`${this._method}:${this._uri}`,l=r.calculateMD5(c),i.debug(`authenticate() | using qop=null [a2:"%s"]`,c),this._response=r.calculateMD5(`${this._ha1}:${this._nonce}:${l}`)),i.debug(`authenticate() | response generated`),!0}toString(){let e=[];if(!this._response)throw Error(`response field does not exist, cannot generate Authorization header`);return e.push(`algorithm=${this._algorithm}`),e.push(`username="${this._credentials.username}"`),e.push(`realm="${this._realm}"`),e.push(`nonce="${this._nonce}"`),e.push(`uri="${this._uri}"`),e.push(`response="${this._response}"`),this._opaque&&e.push(`opaque="${this._opaque}"`),this._qop&&(e.push(`qop=${this._qop}`),e.push(`cnonce="${this._cnonce}"`),e.push(`nc=${this._ncHex}`)),`Digest ${e.join(`, `)}`}}})),Jt=c(((e,t)=>{var n=500;t.exports={T1:n,T2:4e3,T4:5e3,TIMER_B:64*n,TIMER_D:0,TIMER_F:64*n,TIMER_H:64*n,TIMER_I:0,TIMER_J:0,TIMER_K:0,TIMER_L:64*n,TIMER_M:64*n,PROVISIONAL_RESPONSE_INTERVAL:6e4}})),Yt=c(((e,t)=>{var n=q().EventEmitter,r=J(),i=H(),a=Y(),o=Jt(),s=new r(`NonInviteClientTransaction`),c=new r(`InviteClientTransaction`),l=new r(`AckClientTransaction`),u=new r(`NonInviteServerTransaction`),d=new r(`InviteServerTransaction`),f={STATUS_TRYING:1,STATUS_PROCEEDING:2,STATUS_CALLING:3,STATUS_ACCEPTED:4,STATUS_COMPLETED:5,STATUS_TERMINATED:6,STATUS_CONFIRMED:7,NON_INVITE_CLIENT:`nict`,NON_INVITE_SERVER:`nist`,INVITE_CLIENT:`ict`,INVITE_SERVER:`ist`},p=class extends n{constructor(e,t,n,r){super(),this.type=f.NON_INVITE_CLIENT,this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.ua=e,this.transport=t,this.request=n,this.eventHandlers=r;let i=`SIP/2.0/${t.via_transport}`;i+=` ${e.configuration.via_host};branch=${this.id}`,this.request.setHeader(`via`,i),this.ua.newTransaction(this)}get C(){return f}stateChanged(e){this.state=e,this.emit(`stateChanged`)}send(){this.stateChanged(f.STATUS_TRYING),this.F=setTimeout(()=>{this.timer_F()},o.TIMER_F),this.transport.send(this.request)||this.onTransportError()}onTransportError(){s.debug(`transport error occurred, deleting transaction ${this.id}`),clearTimeout(this.F),clearTimeout(this.K),this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onTransportError()}timer_F(){s.debug(`Timer F expired for transaction ${this.id}`),this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout()}timer_K(){this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this)}receiveResponse(e){let t=e.status_code;if(t<200)switch(this.state){case f.STATUS_TRYING:case f.STATUS_PROCEEDING:this.stateChanged(f.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(e)}else switch(this.state){case f.STATUS_TRYING:case f.STATUS_PROCEEDING:this.stateChanged(f.STATUS_COMPLETED),clearTimeout(this.F),t===408?this.eventHandlers.onRequestTimeout():this.eventHandlers.onReceiveResponse(e),this.K=setTimeout(()=>{this.timer_K()},o.TIMER_K);break;case f.STATUS_COMPLETED:}}},m=class extends n{constructor(e,t,n,r){super(),this.type=f.INVITE_CLIENT,this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.ua=e,this.transport=t,this.request=n,this.eventHandlers=r,n.transaction=this;let i=`SIP/2.0/${t.via_transport}`;i+=` ${e.configuration.via_host};branch=${this.id}`,this.request.setHeader(`via`,i),this.ua.newTransaction(this)}get C(){return f}stateChanged(e){this.state=e,this.emit(`stateChanged`)}send(){this.stateChanged(f.STATUS_CALLING),this.B=setTimeout(()=>{this.timer_B()},o.TIMER_B),this.transport.send(this.request)||this.onTransportError()}onTransportError(){clearTimeout(this.B),clearTimeout(this.D),clearTimeout(this.M),this.state!==f.STATUS_ACCEPTED&&(c.debug(`transport error occurred, deleting transaction ${this.id}`),this.eventHandlers.onTransportError()),this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_M(){c.debug(`Timer M expired for transaction ${this.id}`),this.state===f.STATUS_ACCEPTED&&(clearTimeout(this.B),this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this))}timer_B(){c.debug(`Timer B expired for transaction ${this.id}`),this.state===f.STATUS_CALLING&&(this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout())}timer_D(){c.debug(`Timer D expired for transaction ${this.id}`),clearTimeout(this.B),this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this)}sendACK(e){let t=new a.OutgoingRequest(i.ACK,this.request.ruri,this.ua,{route_set:this.request.getHeaders(`route`),call_id:this.request.getHeader(`call-id`),cseq:this.request.cseq});t.setHeader(`from`,this.request.getHeader(`from`)),t.setHeader(`via`,this.request.getHeader(`via`)),t.setHeader(`to`,e.getHeader(`to`)),this.D=setTimeout(()=>{this.timer_D()},o.TIMER_D),this.transport.send(t)}cancel(e){if(this.state!==f.STATUS_PROCEEDING)return;let t=new a.OutgoingRequest(i.CANCEL,this.request.ruri,this.ua,{route_set:this.request.getHeaders(`route`),call_id:this.request.getHeader(`call-id`),cseq:this.request.cseq});t.setHeader(`from`,this.request.getHeader(`from`)),t.setHeader(`via`,this.request.getHeader(`via`)),t.setHeader(`to`,this.request.getHeader(`to`)),e&&t.setHeader(`reason`,e),this.transport.send(t)}receiveResponse(e){let t=e.status_code;if(t>=100&&t<=199)switch(this.state){case f.STATUS_CALLING:this.stateChanged(f.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(e);break;case f.STATUS_PROCEEDING:this.eventHandlers.onReceiveResponse(e)}else if(t>=200&&t<=299)switch(this.state){case f.STATUS_CALLING:case f.STATUS_PROCEEDING:this.stateChanged(f.STATUS_ACCEPTED),this.M=setTimeout(()=>{this.timer_M()},o.TIMER_M),this.eventHandlers.onReceiveResponse(e);break;case f.STATUS_ACCEPTED:this.eventHandlers.onReceiveResponse(e)}else if(t>=300&&t<=699)switch(this.state){case f.STATUS_CALLING:case f.STATUS_PROCEEDING:this.stateChanged(f.STATUS_COMPLETED),this.sendACK(e),this.eventHandlers.onReceiveResponse(e);break;case f.STATUS_COMPLETED:this.sendACK(e)}}},h=class extends n{constructor(e,t,n,r){super(),this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.transport=t,this.request=n,this.eventHandlers=r;let i=`SIP/2.0/${t.via_transport}`;i+=` ${e.configuration.via_host};branch=${this.id}`,this.request.setHeader(`via`,i)}get C(){return f}send(){this.transport.send(this.request)||this.onTransportError()}onTransportError(){l.debug(`transport error occurred for transaction ${this.id}`),this.eventHandlers.onTransportError()}},g=class extends n{constructor(e,t,n){super(),this.type=f.NON_INVITE_SERVER,this.id=n.via_branch,this.ua=e,this.transport=t,this.request=n,this.last_response=``,n.server_transaction=this,this.state=f.STATUS_TRYING,e.newTransaction(this)}get C(){return f}stateChanged(e){this.state=e,this.emit(`stateChanged`)}timer_J(){u.debug(`Timer J expired for transaction ${this.id}`),this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this)}onTransportError(){this.transportError||(this.transportError=!0,u.debug(`transport error occurred, deleting transaction ${this.id}`),clearTimeout(this.J),this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this))}receiveResponse(e,t,n,r){if(e===100)switch(this.state){case f.STATUS_TRYING:this.stateChanged(f.STATUS_PROCEEDING),this.transport.send(t)||this.onTransportError();break;case f.STATUS_PROCEEDING:this.last_response=t,this.transport.send(t)?n&&n():(this.onTransportError(),r&&r())}else if(e>=200&&e<=699)switch(this.state){case f.STATUS_TRYING:case f.STATUS_PROCEEDING:this.stateChanged(f.STATUS_COMPLETED),this.last_response=t,this.J=setTimeout(()=>{this.timer_J()},o.TIMER_J),this.transport.send(t)?n&&n():(this.onTransportError(),r&&r());break;case f.STATUS_COMPLETED:}}},_=class extends n{constructor(e,t,n){super(),this.type=f.INVITE_SERVER,this.id=n.via_branch,this.ua=e,this.transport=t,this.request=n,this.last_response=``,n.server_transaction=this,this.state=f.STATUS_PROCEEDING,e.newTransaction(this),this.resendProvisionalTimer=null,n.reply(100)}get C(){return f}stateChanged(e){this.state=e,this.emit(`stateChanged`)}timer_H(){d.debug(`Timer H expired for transaction ${this.id}`),this.state===f.STATUS_COMPLETED&&d.debug(`ACK not received, dialog will be terminated`),this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_I(){this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_L(){d.debug(`Timer L expired for transaction ${this.id}`),this.state===f.STATUS_ACCEPTED&&(this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this))}onTransportError(){this.transportError||(this.transportError=!0,d.debug(`transport error occurred, deleting transaction ${this.id}`),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),clearTimeout(this.L),clearTimeout(this.H),clearTimeout(this.I),this.stateChanged(f.STATUS_TERMINATED),this.ua.destroyTransaction(this))}resend_provisional(){this.transport.send(this.last_response)||this.onTransportError()}receiveResponse(e,t,n,r){if(e>=100&&e<=199)switch(this.state){case f.STATUS_PROCEEDING:this.transport.send(t)||this.onTransportError(),this.last_response=t}if(e>100&&e<=199&&this.state===f.STATUS_PROCEEDING)this.resendProvisionalTimer===null&&(this.resendProvisionalTimer=setInterval(()=>{this.resend_provisional()},o.PROVISIONAL_RESPONSE_INTERVAL));else if(e>=200&&e<=299)switch(this.state){case f.STATUS_PROCEEDING:this.stateChanged(f.STATUS_ACCEPTED),this.last_response=t,this.L=setTimeout(()=>{this.timer_L()},o.TIMER_L),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null);case f.STATUS_ACCEPTED:this.transport.send(t)?n&&n():(this.onTransportError(),r&&r())}else if(e>=300&&e<=699)switch(this.state){case f.STATUS_PROCEEDING:this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),this.transport.send(t)?(this.stateChanged(f.STATUS_COMPLETED),this.H=setTimeout(()=>{this.timer_H()},o.TIMER_H),n&&n()):(this.onTransportError(),r&&r())}}};function v({_transactions:e},t){let n;switch(t.method){case i.INVITE:if(n=e.ist[t.via_branch],n){switch(n.state){case f.STATUS_PROCEEDING:n.transport.send(n.last_response);break;case f.STATUS_ACCEPTED:}return!0}break;case i.ACK:if(n=e.ist[t.via_branch],n){if(n.state===f.STATUS_ACCEPTED)return!1;if(n.state===f.STATUS_COMPLETED)return n.state=f.STATUS_CONFIRMED,n.I=setTimeout(()=>{n.timer_I()},o.TIMER_I),!0}else return!1;break;case i.CANCEL:return n=e.ist[t.via_branch],n?(t.reply_sl(200),n.state!==f.STATUS_PROCEEDING):(t.reply_sl(481),!0);default:if(n=e.nist[t.via_branch],n){switch(n.state){case f.STATUS_TRYING:break;case f.STATUS_PROCEEDING:case f.STATUS_COMPLETED:n.transport.send(n.last_response)}return!0}}}t.exports={C:f,NonInviteClientTransaction:p,InviteClientTransaction:m,AckClientTransaction:h,NonInviteServerTransaction:g,InviteServerTransaction:_,checkTransaction:v}})),X=c(((e,t)=>{var n=J(),r=H(),i=qt(),a=Yt(),o=new n(`RequestSender`),s={onRequestTimeout:()=>{},onTransportError:()=>{},onReceiveResponse:()=>{},onAuthenticated:()=>{}};t.exports=class{constructor(e,t,n){this._ua=e,this._eventHandlers=n,this._method=t.method,this._request=t,this._auth=null,this._challenged=!1,this._staled=!1;for(let e in s)Object.prototype.hasOwnProperty.call(s,e)&&(this._eventHandlers[e]||(this._eventHandlers[e]=s[e]));e.status===e.C.STATUS_USER_CLOSED&&(this._method!==r.BYE||this._method!==r.ACK)&&this._eventHandlers.onTransportError()}send(){let e={onRequestTimeout:()=>{this._eventHandlers.onRequestTimeout()},onTransportError:()=>{this._eventHandlers.onTransportError()},onReceiveResponse:e=>{this._receiveResponse(e)}};switch(this._method){case`INVITE`:this.clientTransaction=new a.InviteClientTransaction(this._ua,this._ua.transport,this._request,e);break;case`ACK`:this.clientTransaction=new a.AckClientTransaction(this._ua,this._ua.transport,this._request,e);break;default:this.clientTransaction=new a.NonInviteClientTransaction(this._ua,this._ua.transport,this._request,e)}this._ua._configuration.authorization_jwt&&this._request.setHeader(`Authorization`,this._ua._configuration.authorization_jwt),this.clientTransaction.send()}_receiveResponse(e){let t,n,r=e.status_code;if((r===401||r===407)&&(this._ua.configuration.password!==null||this._ua.configuration.ha1!==null)){if(e.status_code===401?(t=e.parseHeader(`www-authenticate`),n=`authorization`):(t=e.parseHeader(`proxy-authenticate`),n=`proxy-authorization`),!t){o.debug(`${e.status_code} with wrong or missing challenge, cannot authenticate`),this._eventHandlers.onReceiveResponse(e);return}if(!this._challenged||!this._staled&&t.stale===!0){if(this._auth||=new i({username:this._ua.configuration.authorization_user,password:this._ua.configuration.password,realm:this._ua.configuration.realm,ha1:this._ua.configuration.ha1}),!this._auth.authenticate(this._request,t)){this._eventHandlers.onReceiveResponse(e);return}this._challenged=!0,this._ua.set(`realm`,this._auth.get(`realm`)),this._ua.set(`ha1`,this._auth.get(`ha1`)),t.stale&&(this._staled=!0),this._request=this._request.clone(),this._request.cseq+=1,this._request.setHeader(`cseq`,`${this._request.cseq} ${this._method}`),this._request.setHeader(n,this._auth.toString()),this._eventHandlers.onAuthenticated(this._request),this.send()}else this._eventHandlers.onReceiveResponse(e)}else this._eventHandlers.onReceiveResponse(e)}}})),Xt=c(((e,t)=>{var n=J(),r=K(),i=H(),a=Y(),o=X(),s=new n(`Registrator`),c=10;t.exports=class{constructor(e,t){this._reg_id=1,this._ua=e,this._transport=t,this._registrar=e.configuration.registrar_server,this._expires=e.configuration.register_expires,this._call_id=r.createRandomToken(22),this._cseq=0,this._to_uri=e.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString(),this._contact+=`;+sip.ice`,this._extraHeaders=[],this._extraContactParams=``,this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._contact+=`;reg-id=${this._reg_id}`,this._contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(e){Array.isArray(e)||(e=[]),this._extraHeaders=e.slice()}setExtraContactParams(e){e instanceof Object||(e={}),this._extraContactParams=``;for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let n=e[t];this._extraContactParams+=`;${t}`,n&&(this._extraContactParams+=`=${n}`)}}register(){if(this._registering){s.debug(`Register request in progress...`);return}let e=r.cloneArray(this._extraHeaders),t;this._expires?(t=`${this._contact};expires=${this._expires}${this._extraContactParams}`,e.push(`Expires: ${this._expires}`)):t=`${this._contact}${this._extraContactParams}`,e.push(`Contact: ${t}`);let n=r.newTag();this._ua.configuration.register_from_tag_trail&&(typeof this._ua.configuration.register_from_tag_trail==`function`?n+=this._ua.configuration.register_from_tag_trail():n+=this._ua.configuration.register_from_tag_trail);let l=new a.OutgoingRequest(i.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1,from_tag:n},e),u=new o(this._ua,l,{onRequestTimeout:()=>{this._registrationFailure(null,i.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,i.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:e=>{if(e.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(e.status_code):break;case/^2[0-9]{2}$/.test(e.status_code):{if(this._registering=!1,!e.hasHeader(`Contact`)){s.debug(`no Contact header in response to REGISTER, response ignored`);break}let t=e.headers.Contact.reduce((e,t)=>e.concat(t.parsed),[]),n=t.find(e=>this._sipInstance===e.getParam(`+sip.instance`)&&this._reg_id===parseInt(e.getParam(`reg-id`)));if(n||=t.find(e=>e.uri.user===this._ua.contact.uri.user),!n){s.debug(`no Contact header pointing to us, response ignored`);break}let r=n.getParam(`expires`);!r&&e.hasHeader(`expires`)&&(r=e.getHeader(`expires`)),r||=this._expires,r=Number(r),r<c&&(r=c);let i=r>64?r*1e3/2+Math.floor((r/2-32)*1e3*Math.random()):r*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners(`registrationExpiring`).length===0?this.register():this._ua.emit(`registrationExpiring`)},i),n.hasParam(`temp-gruu`)&&(this._ua.contact.temp_gruu=n.getParam(`temp-gruu`).replace(/"/g,``)),n.hasParam(`pub-gruu`)&&(this._ua.contact.pub_gruu=n.getParam(`pub-gruu`).replace(/"/g,``)),this._registered||(this._registered=!0,this._ua.registered({response:e}));break}case/^423$/.test(e.status_code):e.hasHeader(`min-expires`)?(this._expires=Number(e.getHeader(`min-expires`)),this._expires<c&&(this._expires=c),this._registering=!1,this.register()):(s.debug(`423 response received for REGISTER without Min-Expires`),this._registrationFailure(e,i.causes.SIP_FAILURE_CODE));break;default:{let t=r.sipErrorCause(e.status_code);this._registrationFailure(e,t)}}}});this._registering=!0,u.send()}unregister(e={}){if(!this._registered){s.debug(`already unregistered`);return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);let t=r.cloneArray(this._extraHeaders);e.all?t.push(`Contact: *${this._extraContactParams}`):t.push(`Contact: ${this._contact};expires=0${this._extraContactParams}`),t.push(`Expires: 0`);let n=new a.OutgoingRequest(i.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},t);new o(this._ua,n,{onRequestTimeout:()=>{this._unregistered(null,i.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,i.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:e=>{switch(!0){case/^1[0-9]{2}$/.test(e.status_code):break;case/^2[0-9]{2}$/.test(e.status_code):this._unregistered(e);break;default:{let t=r.sipErrorCause(e.status_code);this._unregistered(e,t)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(e,t){this._registering=!1,this._ua.registrationFailed({response:e||null,cause:t}),this._registered&&(this._registered=!1,this._ua.unregistered({response:e||null,cause:t}))}_unregistered(e,t){this._registering=!1,this._registered=!1,this._ua.unregistered({response:e||null,cause:t||null})}}})),Zt=c(((e,t)=>{var n=H(),r=Yt(),i=X(),a={onRequestTimeout:()=>{},onTransportError:()=>{},onSuccessResponse:()=>{},onErrorResponse:()=>{},onAuthenticated:()=>{},onDialogError:()=>{}};t.exports=class{constructor(e,t,n){this._dialog=e,this._ua=e._ua,this._request=t,this._eventHandlers=n,this._reattempt=!1,this._reattemptTimer=null;for(let e in a)Object.prototype.hasOwnProperty.call(a,e)&&(this._eventHandlers[e]||(this._eventHandlers[e]=a[e]))}get request(){return this._request}send(){let e=new i(this._ua,this._request,{onRequestTimeout:()=>{this._eventHandlers.onRequestTimeout()},onTransportError:()=>{this._eventHandlers.onTransportError()},onAuthenticated:e=>{this._eventHandlers.onAuthenticated(e)},onReceiveResponse:e=>{this._receiveResponse(e)}});if(e.send(),(this._request.method===n.INVITE||this._request.method===n.UPDATE&&this._request.body)&&e.clientTransaction.state!==r.C.STATUS_TERMINATED){this._dialog.uac_pending_reply=!0;let t=()=>{(e.clientTransaction.state===r.C.STATUS_ACCEPTED||e.clientTransaction.state===r.C.STATUS_COMPLETED||e.clientTransaction.state===r.C.STATUS_TERMINATED)&&(e.clientTransaction.removeListener(`stateChanged`,t),this._dialog.uac_pending_reply=!1)};e.clientTransaction.on(`stateChanged`,t)}}_receiveResponse(e){e.status_code===408||e.status_code===481?this._eventHandlers.onDialogError(e):e.method===n.INVITE&&e.status_code===491?this._reattempt?this._eventHandlers.onErrorResponse(e):(this._request.cseq=this._dialog.local_seqnum+=1,this._reattemptTimer=setTimeout(()=>{this._dialog.isTerminated()||(this._reattempt=!0,this.send())},1e3)):e.status_code>=200&&e.status_code<300?this._eventHandlers.onSuccessResponse(e):e.status_code>=300&&this._eventHandlers.onErrorResponse(e)}}})),Qt=c(((e,t)=>{var n=J(),r=Y(),i=H(),a=Yt(),o=Zt(),s=K(),c=new n(`Dialog`),l={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3};t.exports=class{static get C(){return l}constructor(e,t,n,i=l.STATUS_CONFIRMED){if(this._owner=e,this._ua=e._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,!t.hasHeader(`contact`))return{error:`unable to create a Dialog without Contact header field`};t instanceof r.IncomingResponse&&(i=t.status_code<200?l.STATUS_EARLY:l.STATUS_CONFIRMED);let a=t.parseHeader(`contact`);n===`UAS`?(this._id={call_id:t.call_id,local_tag:t.to_tag,remote_tag:t.from_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=i,this._remote_seqnum=t.cseq,this._local_uri=t.parseHeader(`to`).uri,this._remote_uri=t.parseHeader(`from`).uri,this._remote_target=a.uri,this._route_set=t.getHeaders(`record-route`),this._incoming_ack_seqnum=t.cseq,this._outgoing_ack_seqnum=null):n===`UAC`&&(this._id={call_id:t.call_id,local_tag:t.from_tag,remote_tag:t.to_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=i,this._local_seqnum=t.cseq,this._local_uri=t.parseHeader(`from`).uri,this._remote_uri=t.parseHeader(`to`).uri,this._remote_target=a.uri,this._route_set=t.getHeaders(`record-route`).reverse(),this._incoming_ack_seqnum=null,this._outgoing_ack_seqnum=this._local_seqnum),this._ua.newDialog(this),c.debug(`new ${n} dialog created with status ${this._state===l.STATUS_EARLY?`EARLY`:`CONFIRMED`}`)}get id(){return this._id}get local_seqnum(){return this._local_seqnum}set local_seqnum(e){this._local_seqnum=e}get owner(){return this._owner}get uac_pending_reply(){return this._uac_pending_reply}set uac_pending_reply(e){this._uac_pending_reply=e}get uas_pending_reply(){return this._uas_pending_reply}isTerminated(){return this._status===l.STATUS_TERMINATED}update(e,t){this._state=l.STATUS_CONFIRMED,c.debug(`dialog ${this._id.toString()} changed to CONFIRMED state`),t===`UAC`&&(this._route_set=e.getHeaders(`record-route`).reverse())}terminate(){c.debug(`dialog ${this._id.toString()} deleted`),this._ua.destroyDialog(this),this._state=l.STATUS_TERMINATED}sendRequest(e,t={}){let n=s.cloneArray(t.extraHeaders),r=s.cloneObject(t.eventHandlers),a=t.body||null,c=this._createRequest(e,n,a),l=r.onAuthenticated||(()=>{});return r.onAuthenticated=e=>{this._local_seqnum+=1,c.method===i.INVITE&&(this._outgoing_ack_seqnum=this._local_seqnum),l(e)},new o(this,c,r).send(),c}receiveRequest(e){this._checkInDialogRequest(e)&&(e.method===i.ACK&&this._incoming_ack_seqnum!==null?this._incoming_ack_seqnum=null:e.method===i.INVITE&&(this._incoming_ack_seqnum=e.cseq),this._owner.receiveRequest(e))}_createRequest(e,t,n){t=s.cloneArray(t),this._local_seqnum||=Math.floor(Math.random()*1e4);let a=e===i.CANCEL||e===i.ACK?this._outgoing_ack_seqnum:this._local_seqnum+=1;return e===i.INVITE&&(this._outgoing_ack_seqnum=a),new r.OutgoingRequest(e,this._remote_target,this._ua,{cseq:a,call_id:this._id.call_id,from_uri:this._local_uri,from_tag:this._id.local_tag,to_uri:this._remote_uri,to_tag:this._id.remote_tag,route_set:this._route_set},t,n)}_checkInDialogRequest(e){if(!this._remote_seqnum)this._remote_seqnum=e.cseq;else if(e.cseq<this._remote_seqnum){if(e.method===i.ACK){if(this._incoming_ack_seqnum===null||e.cseq!==this._incoming_ack_seqnum)return!1}else return e.reply(500),!1}else e.cseq>this._remote_seqnum&&(this._remote_seqnum=e.cseq);if(e.method===i.INVITE||e.method===i.UPDATE&&e.body){if(this._uac_pending_reply===!0)e.reply(491);else if(this._uas_pending_reply===!0){let t=(Math.random()*10|0)+1;return e.reply(500,null,[`Retry-After:${t}`]),!1}else{this._uas_pending_reply=!0;let t=()=>{(e.server_transaction.state===a.C.STATUS_ACCEPTED||e.server_transaction.state===a.C.STATUS_COMPLETED||e.server_transaction.state===a.C.STATUS_TERMINATED)&&(e.server_transaction.removeListener(`stateChanged`,t),this._uas_pending_reply=!1)};e.server_transaction.on(`stateChanged`,t)}e.hasHeader(`contact`)&&e.server_transaction.on(`stateChanged`,()=>{e.server_transaction.state===a.C.STATUS_ACCEPTED&&(this._remote_target=e.parseHeader(`contact`).uri)})}else e.method===i.NOTIFY&&e.hasHeader(`contact`)&&e.server_transaction.on(`stateChanged`,()=>{e.server_transaction.state===a.C.STATUS_COMPLETED&&(this._remote_target=e.parseHeader(`contact`).uri)});return!0}}})),$t=c(((e,t)=>{var n=q().EventEmitter,r=J(),i=H(),a=U(),o=K(),s=new r(`RTCSession:DTMF`),c={MIN_DURATION:70,MAX_DURATION:6e3,DEFAULT_DURATION:100,MIN_INTER_TONE_GAP:50,DEFAULT_INTER_TONE_GAP:500};t.exports=class extends n{constructor(e){super(),this._session=e,this._direction=null,this._tone=null,this._duration=null,this._request=null}get tone(){return this._tone}get duration(){return this._duration}send(e,t={}){if(e===void 0)throw TypeError(`Not enough arguments`);if(this._direction=`outgoing`,this._session.status!==this._session.C.STATUS_CONFIRMED&&this._session.status!==this._session.C.STATUS_WAITING_FOR_ACK&&this._session.status!==this._session.C.STATUS_1XX_RECEIVED)throw new a.InvalidStateError(this._session.status);let n=o.cloneArray(t.extraHeaders);if(this.eventHandlers=o.cloneObject(t.eventHandlers),typeof e==`string`)e=e.toUpperCase();else if(typeof e==`number`)e=e.toString();else throw TypeError(`Invalid tone: ${e}`);if(e.match(/^[0-9A-DR#*]$/))this._tone=e;else throw TypeError(`Invalid tone: ${e}`);this._duration=t.duration,n.push(`Content-Type: application/dtmf-relay`);let r=`Signal=${this._tone}\r\n`;r+=`Duration=${this._duration}`,this._session.newDTMF({originator:`local`,dtmf:this,request:this._request}),this._session.sendRequest(i.INFO,{extraHeaders:n,eventHandlers:{onSuccessResponse:e=>{this.emit(`succeeded`,{originator:`remote`,response:e})},onErrorResponse:e=>{this.eventHandlers.onFailed&&this.eventHandlers.onFailed(),this.emit(`failed`,{originator:`remote`,response:e})},onRequestTimeout:()=>{this._session.onRequestTimeout()},onTransportError:()=>{this._session.onTransportError()},onDialogError:()=>{this._session.onDialogError()}},body:r})}init_incoming(e){let t=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/,n=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;if(this._direction=`incoming`,this._request=e,e.reply(200),e.body){let r=e.body.split(`
|
|
14
|
+
`);r.length>=1&&t.test(r[0])&&(this._tone=r[0].replace(t,`$2`)),r.length>=2&&n.test(r[1])&&(this._duration=parseInt(r[1].replace(n,`$2`),10))}this._duration||=c.DEFAULT_DURATION,this._tone?this._session.newDTMF({originator:`remote`,dtmf:this,request:e}):s.debug(`invalid INFO DTMF received, discarded`)}},t.exports.C=c})),en=c(((e,t)=>{var n=q().EventEmitter,r=H(),i=U(),a=K();t.exports=class extends n{constructor(e){super(),this._session=e,this._direction=null,this._contentType=null,this._body=null}get contentType(){return this._contentType}get body(){return this._body}send(e,t,n={}){if(this._direction=`outgoing`,e===void 0)throw TypeError(`Not enough arguments`);if(this._session.status!==this._session.C.STATUS_CONFIRMED&&this._session.status!==this._session.C.STATUS_WAITING_FOR_ACK)throw new i.InvalidStateError(this._session.status);this._contentType=e,this._body=t;let o=a.cloneArray(n.extraHeaders);o.push(`Content-Type: ${e}`),this._session.newInfo({originator:`local`,info:this,request:this.request}),this._session.sendRequest(r.INFO,{extraHeaders:o,eventHandlers:{onSuccessResponse:e=>{this.emit(`succeeded`,{originator:`remote`,response:e})},onErrorResponse:e=>{this.emit(`failed`,{originator:`remote`,response:e})},onTransportError:()=>{this._session.onTransportError()},onRequestTimeout:()=>{this._session.onRequestTimeout()},onDialogError:()=>{this._session.onDialogError()}},body:t})}init_incoming(e){this._direction=`incoming`,this.request=e,e.reply(200),this._contentType=e.hasHeader(`Content-Type`)?e.getHeader(`Content-Type`).toLowerCase():void 0,this._body=e.body,this._session.newInfo({originator:`remote`,info:this,request:e})}}})),tn=c(((e,t)=>{var n=J(),r=H(),i=new n(`RTCSession:ReferNotifier`),a={event_type:`refer`,body_type:`message/sipfrag;version=2.0`,expires:300};t.exports=class{constructor(e,t,n){this._session=e,this._id=t,this._expires=n||a.expires,this._active=!0,this.notify(100)}notify(e,t){if(i.debug(`notify()`),this._active===!1)return;t=t||r.REASON_PHRASE[e]||``;let n;n=e>=200?`terminated;reason=noresource`:`active;expires=${this._expires}`,this._session.sendRequest(r.NOTIFY,{extraHeaders:[`Event: ${a.event_type};id=${this._id}`,`Subscription-State: ${n}`,`Content-Type: ${a.body_type}`],body:`SIP/2.0 ${e} ${t}`,eventHandlers:{onErrorResponse(){this._active=!1}}})}}})),nn=c(((e,t)=>{var n=q().EventEmitter,r=J(),i=H(),a=W(),o=K(),s=new r(`RTCSession:ReferSubscriber`);t.exports=class extends n{constructor(e){super(),this._id=null,this._session=e}get id(){return this._id}sendRefer(e,t={}){s.debug(`sendRefer()`);let n=o.cloneArray(t.extraHeaders),r=o.cloneObject(t.eventHandlers);for(let e in r)Object.prototype.hasOwnProperty.call(r,e)&&this.on(e,r[e]);let a=null;t.replaces&&(a=t.replaces._request.call_id,a+=`;to-tag=${t.replaces._to_tag}`,a+=`;from-tag=${t.replaces._from_tag}`,a=encodeURIComponent(a));let c=`Refer-To: <${e}${a?`?Replaces=${a}`:``}>`;if(n.push(c),!n.some(e=>e.toLowerCase().startsWith(`referred-by:`))){let e=`Referred-By: <${this._session._ua._configuration.uri._scheme}:${this._session._ua._configuration.uri._user}@${this._session._ua._configuration.uri._host}>`;n.push(e)}n.push(`Contact: ${this._session.contact}`);let l=this._session.sendRequest(i.REFER,{extraHeaders:n,eventHandlers:{onSuccessResponse:e=>{this._requestSucceeded(e)},onErrorResponse:e=>{this._requestFailed(e,i.causes.REJECTED)},onTransportError:()=>{this._requestFailed(null,i.causes.CONNECTION_ERROR)},onRequestTimeout:()=>{this._requestFailed(null,i.causes.REQUEST_TIMEOUT)},onDialogError:()=>{this._requestFailed(null,i.causes.DIALOG_ERROR)},onAuthenticated:e=>{this._id=e.cseq,this.emit(`authenticated`)}}});this._id=l.cseq}receiveNotify(e){if(s.debug(`receiveNotify()`),!e.body)return;let t=a.parse(e.body.trim().split(`\r
|
|
15
|
+
`,1)[0],`Status_Line`);if(t===-1){s.debug(`receiveNotify() | error parsing NOTIFY body: "${e.body}"`);return}switch(!0){case/^100$/.test(t.status_code):this.emit(`trying`,{request:e,status_line:t});break;case/^1[0-9]{2}$/.test(t.status_code):this.emit(`progress`,{request:e,status_line:t});break;case/^2[0-9]{2}$/.test(t.status_code):this.emit(`accepted`,{request:e,status_line:t});break;default:this.emit(`failed`,{request:e,status_line:t})}}_requestSucceeded(e){s.debug(`REFER succeeded`),s.debug(`emit "requestSucceeded"`),this.emit(`requestSucceeded`,{response:e})}_requestFailed(e,t){s.debug(`REFER failed`),s.debug(`emit "requestFailed"`),this.emit(`requestFailed`,{response:e||null,cause:t})}}})),rn=c(((e,t)=>{var n=q().EventEmitter,r=Kt(),i=J(),a=H(),o=U(),s=Yt(),c=K(),l=Jt(),u=Y(),d=Qt(),f=X(),p=$t(),m=en(),h=tn(),g=nn(),_=G(),v=new i(`RTCSession`),y={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9},b=[`audio`,`video`];t.exports=class e extends n{static get C(){return y}constructor(e){v.debug(`new`),super(),this._id=null,this._ua=e,this._status=y.STATUS_NULL,this._dialog=null,this._earlyDialogs={},this._contact=null,this._from_tag=null,this._to_tag=null,this._connection=null,this._connectionPromiseQueue=Promise.resolve(),this._request=null,this._is_canceled=!1,this._cancel_reason=``,this._is_confirmed=!1,this._late_sdp=!1,this._rtcOfferConstraints=null,this._rtcAnswerConstraints=null,this._localMediaStream=null,this._localMediaStreamLocallyGenerated=!1,this._rtcReady=!0,this._iceReady=!1,this._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},this._direction=null,this._local_identity=null,this._remote_identity=null,this._start_time=null,this._end_time=null,this._tones=null,this._audioMuted=!1,this._videoMuted=!1,this._localHold=!1,this._remoteHold=!1,this._sessionTimers={enabled:this._ua.configuration.session_timers,refreshMethod:this._ua.configuration.session_timers_refresh_method,defaultExpires:a.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},this._referSubscribers={},this._data={}}get C(){return y}get causes(){return a.causes}get id(){return this._id}get connection(){return this._connection}get contact(){return this._contact}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}get start_time(){return this._start_time}get end_time(){return this._end_time}get data(){return this._data}set data(e){this._data=e}get status(){return this._status}isInProgress(){switch(this._status){case y.STATUS_NULL:case y.STATUS_INVITE_SENT:case y.STATUS_1XX_RECEIVED:case y.STATUS_INVITE_RECEIVED:case y.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}isEstablished(){switch(this._status){case y.STATUS_ANSWERED:case y.STATUS_WAITING_FOR_ACK:case y.STATUS_CONFIRMED:return!0;default:return!1}}isEnded(){switch(this._status){case y.STATUS_CANCELED:case y.STATUS_TERMINATED:return!0;default:return!1}}isMuted(){return{audio:this._audioMuted,video:this._videoMuted}}isOnHold(){return{local:this._localHold,remote:this._remoteHold}}connect(e,t={},n){v.debug(`connect()`);let r=e,i=c.cloneObject(t.eventHandlers),s=c.cloneArray(t.extraHeaders),l=c.cloneObject(t.mediaConstraints,{audio:!0,video:!0}),d=t.mediaStream||null,f=c.cloneObject(t.pcConfig,{iceServers:[]}),p=t.rtcConstraints||null,m=t.rtcOfferConstraints||null;if(this._rtcOfferConstraints=m,this._rtcAnswerConstraints=t.rtcAnswerConstraints||null,this._data=t.data||this._data,e===void 0)throw TypeError(`Not enough arguments`);if(this._status!==y.STATUS_NULL)throw new o.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new o.NotSupportedError(`WebRTC not supported`);if(e=this._ua.normalizeTarget(e),!e)throw TypeError(`Invalid target: ${r}`);this._sessionTimers.enabled&&c.isDecimal(t.sessionTimersExpires)&&(t.sessionTimersExpires>=a.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=t.sessionTimersExpires:this._sessionTimers.defaultExpires=a.SESSION_EXPIRES);for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&this.on(e,i[e]);this._from_tag=c.newTag();let h=t.anonymous||!1,g={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:h,outbound:!0}),h?(g.from_display_name=`Anonymous`,g.from_uri=new _(`sip`,`anonymous`,`anonymous.invalid`),s.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),s.push(`Privacy: id`)):t.fromUserName&&(g.from_uri=new _(`sip`,t.fromUserName,this._ua.configuration.uri.host),s.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),t.fromDisplayName&&(g.from_display_name=t.fromDisplayName),s.push(`Contact: ${this._contact}`),s.push(`Content-Type: application/sdp`),this._sessionTimers.enabled&&s.push(`Session-Expires: ${this._sessionTimers.defaultExpires}${this._ua.configuration.session_timers_force_refresher?`;refresher=uac`:``}`),this._request=new u.InitialOutgoingInviteRequest(e,this._ua,g,s),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(f,p),this._direction=`outgoing`,this._local_identity=this._request.from,this._remote_identity=this._request.to,n&&n(this),this._newRTCSession(`local`,this._request),this._sendInitialRequest(l,m,d)}init_incoming(e,t){v.debug(`init_incoming()`);let n,r=e.hasHeader(`Content-Type`)?e.getHeader(`Content-Type`).toLowerCase():void 0;if(e.body&&r!==`application/sdp`){e.reply(415);return}if(this._status=y.STATUS_INVITE_RECEIVED,this._from_tag=e.from_tag,this._id=e.call_id+this._from_tag,this._request=e,this._contact=this._ua.contact.toString(),e.hasHeader(`expires`)&&(n=e.getHeader(`expires`)*1e3),e.to_tag=c.newTag(),!this._createDialog(e,`UAS`,!0)){e.reply(500,`Missing Contact header field`);return}this._late_sdp=!e.body,this._status=y.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{e.reply(408),this._failed(`local`,null,a.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),n&&(this._timers.expiresTimer=setTimeout(()=>{this._status===y.STATUS_WAITING_FOR_ANSWER&&(e.reply(487),this._failed(`system`,null,a.causes.EXPIRES))},n)),this._direction=`incoming`,this._local_identity=e.to,this._remote_identity=e.from,t&&t(this),this._newRTCSession(`remote`,e),this._status!==y.STATUS_TERMINATED&&(e.reply(180,null,[`Contact: ${this._contact}`]),this._progress(`local`,null))}answer(e={}){v.debug(`answer()`);let t=this._request,n=c.cloneArray(e.extraHeaders),r=c.cloneObject(e.mediaConstraints),i=e.mediaStream||null,s=c.cloneObject(e.pcConfig,{iceServers:[]}),l=e.rtcConstraints||null,u=e.rtcAnswerConstraints||null,d=c.cloneObject(e.rtcOfferConstraints),f,p=!1,m=!1,h=!1,g=!1;if(this._rtcAnswerConstraints=u,this._rtcOfferConstraints=e.rtcOfferConstraints||null,this._data=e.data||this._data,this._direction!==`incoming`)throw new o.NotSupportedError(`"answer" not supported for outgoing RTCSession`);if(this._status!==y.STATUS_WAITING_FOR_ANSWER)throw new o.InvalidStateError(this._status);if(this._sessionTimers.enabled&&c.isDecimal(e.sessionTimersExpires)&&(e.sessionTimersExpires>=a.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=e.sessionTimersExpires:this._sessionTimers.defaultExpires=a.SESSION_EXPIRES),this._status=y.STATUS_ANSWERED,!this._createDialog(t,`UAS`)){t.reply(500,`Error creating dialog`);return}clearTimeout(this._timers.userNoAnswerTimer),n.unshift(`Contact: ${this._contact}`);let _=t.parseSDP();Array.isArray(_.media)||(_.media=[_.media]);for(let e of _.media)e.type===`audio`&&(p=!0,(!e.direction||e.direction===`sendrecv`)&&(h=!0)),e.type===`video`&&(m=!0,(!e.direction||e.direction===`sendrecv`)&&(g=!0));if(i&&r.audio===!1){f=i.getAudioTracks();for(let e of f)i.removeTrack(e)}if(i&&r.video===!1){f=i.getVideoTracks();for(let e of f)i.removeTrack(e)}!i&&r.audio===void 0&&(r.audio=h),!i&&r.video===void 0&&(r.video=g),!i&&!p&&!d.offerToReceiveAudio&&(r.audio=!1),!i&&!m&&!d.offerToReceiveVideo&&(r.video=!1),this._createRTCConnection(s,l),Promise.resolve().then(()=>{if(i)return i;if(r.audio||r.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(r).catch(e=>{throw this._status===y.STATUS_TERMINATED?Error(`terminated`):(t.reply(480),this._failed(`local`,null,a.causes.USER_DENIED_MEDIA_ACCESS),v.warn(`emit "getusermediafailed" [error:%o]`,e),this.emit(`getusermediafailed`,e),Error(`getUserMedia() failed`))})}).then(e=>{if(this._status===y.STATUS_TERMINATED)throw Error(`terminated`);this._localMediaStream=e,e&&e.getTracks().forEach(t=>{this._connection.addTrack(t,e)})}).then(()=>{if(this._late_sdp)return;let e={originator:`remote`,type:`offer`,sdp:t.body};v.debug(`emit "sdp"`),this.emit(`sdp`,e);let n=new RTCSessionDescription({type:`offer`,sdp:e.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(n)).catch(e=>{throw t.reply(488),this._failed(`system`,null,a.causes.WEBRTC_ERROR),v.warn(`emit "peerconnection:setremotedescriptionfailed" [error:%o]`,e),this.emit(`peerconnection:setremotedescriptionfailed`,e),Error(`peerconnection.setRemoteDescription() failed`)}),this._connectionPromiseQueue}).then(()=>{if(this._status===y.STATUS_TERMINATED)throw Error(`terminated`);return this._connecting(t),this._late_sdp?this._createLocalDescription(`offer`,this._rtcOfferConstraints).catch(()=>{throw t.reply(500),Error(`_createLocalDescription() failed`)}):this._createLocalDescription(`answer`,u).catch(()=>{throw t.reply(500),Error(`_createLocalDescription() failed`)})}).then(e=>{if(this._status===y.STATUS_TERMINATED)throw Error(`terminated`);this._handleSessionTimersInIncomingRequest(t,n),t.reply(200,null,n,e,()=>{this._status=y.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(t,e),this._setACKTimer(),this._accepted(`local`)},()=>{this._failed(`system`,null,a.causes.CONNECTION_ERROR)})}).catch(e=>{this._status!==y.STATUS_TERMINATED&&(v.warn(`answer() failed: ${e.message}`),this._failed(`system`,e.message,a.causes.INTERNAL_ERROR))})}terminate(e={}){v.debug(`terminate()`);let t=e.cause||a.causes.BYE,n=c.cloneArray(e.extraHeaders),r=e.body,i,l=e.status_code,u=e.reason_phrase;if(this._status===y.STATUS_TERMINATED)throw new o.InvalidStateError(this._status);switch(this._status){case y.STATUS_NULL:case y.STATUS_INVITE_SENT:case y.STATUS_1XX_RECEIVED:if(v.debug(`canceling session`),l&&(l<200||l>=700))throw TypeError(`Invalid status_code: ${l}`);l&&(u=u||a.REASON_PHRASE[l]||``,i=`SIP ;cause=${l} ;text="${u}"`),this._status===y.STATUS_NULL||this._status===y.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=i):this._status===y.STATUS_1XX_RECEIVED&&this._request.cancel(i),this._status=y.STATUS_CANCELED,this._failed(`local`,null,a.causes.CANCELED);break;case y.STATUS_WAITING_FOR_ANSWER:case y.STATUS_ANSWERED:if(v.debug(`rejecting session`),l||=480,l<300||l>=700)throw TypeError(`Invalid status_code: ${l}`);this._request.reply(l,u,n,r),this._failed(`local`,null,a.causes.REJECTED);break;case y.STATUS_WAITING_FOR_ACK:case y.STATUS_CONFIRMED:if(v.debug(`terminating session`),u=e.reason_phrase||a.REASON_PHRASE[l]||``,l&&(l<200||l>=700))throw TypeError(`Invalid status_code: ${l}`);if(l&&n.push(`Reason: SIP ;cause=${l}; text="${u}"`),this._status===y.STATUS_WAITING_FOR_ACK&&this._direction===`incoming`&&this._request.server_transaction.state!==s.C.STATUS_TERMINATED){let e=this._dialog;this.receiveRequest=({method:t})=>{t===a.ACK&&(this.sendRequest(a.BYE,{extraHeaders:n,body:r}),e.terminate())},this._request.server_transaction.on(`stateChanged`,()=>{this._request.server_transaction.state===s.C.STATUS_TERMINATED&&(this.sendRequest(a.BYE,{extraHeaders:n,body:r}),e.terminate())}),this._ended(`local`,null,t),this._dialog=e,this._ua.newDialog(e)}else this.sendRequest(a.BYE,{extraHeaders:n,body:r}),this._ended(`local`,null,t)}}sendDTMF(e,t={}){v.debug(`sendDTMF() | tones: %s`,e);let n=t.duration||null,r=t.interToneGap||null,i=t.transportType||a.DTMF_TRANSPORT.INFO;if(e===void 0)throw TypeError(`Not enough arguments`);if(this._status!==y.STATUS_CONFIRMED&&this._status!==y.STATUS_WAITING_FOR_ACK&&this._status!==y.STATUS_1XX_RECEIVED)throw new o.InvalidStateError(this._status);if(i!==a.DTMF_TRANSPORT.INFO&&i!==a.DTMF_TRANSPORT.RFC2833)throw TypeError(`invalid transportType: ${i}`);if(typeof e==`number`&&(e=e.toString()),!e||typeof e!=`string`||!e.match(/^[0-9A-DR#*,]+$/i))throw TypeError(`Invalid tones: ${e}`);if(n&&!c.isDecimal(n))throw TypeError(`Invalid tone duration: ${n}`);if(n?n<p.C.MIN_DURATION?(v.debug(`"duration" value is lower than the minimum allowed, setting it to ${p.C.MIN_DURATION} milliseconds`),n=p.C.MIN_DURATION):n>p.C.MAX_DURATION?(v.debug(`"duration" value is greater than the maximum allowed, setting it to ${p.C.MAX_DURATION} milliseconds`),n=p.C.MAX_DURATION):n=Math.abs(n):n=p.C.DEFAULT_DURATION,t.duration=n,r&&!c.isDecimal(r))throw TypeError(`Invalid interToneGap: ${r}`);if(r?r<p.C.MIN_INTER_TONE_GAP?(v.debug(`"interToneGap" value is lower than the minimum allowed, setting it to ${p.C.MIN_INTER_TONE_GAP} milliseconds`),r=p.C.MIN_INTER_TONE_GAP):r=Math.abs(r):r=p.C.DEFAULT_INTER_TONE_GAP,i===a.DTMF_TRANSPORT.RFC2833){let t=this._getDTMFRTPSender();t&&(e=t.toneBuffer+e,t.insertDTMF(e,n,r));return}if(this._tones){this._tones+=e;return}this._tones=e,s.call(this);function s(){let e;if(this._status===y.STATUS_TERMINATED||!this._tones){this._tones=null;return}let i=this._tones[0];if(this._tones=this._tones.substring(1),i===`,`)e=2e3;else{let a=new p(this);t.eventHandlers={onFailed:()=>{this._tones=null}},a.send(i,t),e=n+r}setTimeout(s.bind(this),e)}}sendInfo(e,t,n={}){if(v.debug(`sendInfo()`),this._status!==y.STATUS_CONFIRMED&&this._status!==y.STATUS_WAITING_FOR_ACK&&this._status!==y.STATUS_1XX_RECEIVED)throw new o.InvalidStateError(this._status);new m(this).send(e,t,n)}mute(e={audio:!0,video:!1}){v.debug(`mute()`);let t=!1,n=!1;this._audioMuted===!1&&e.audio&&(t=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&e.video&&(n=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(t===!0||n===!0)&&this._onmute({audio:t,video:n})}unmute(e={audio:!0,video:!0}){v.debug(`unmute()`);let t=!1,n=!1;this._audioMuted===!0&&e.audio&&(t=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&e.video&&(n=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(t===!0||n===!0)&&this._onunmute({audio:t,video:n})}hold(e={},t){if(v.debug(`hold()`),this._status!==y.STATUS_WAITING_FOR_ACK&&this._status!==y.STATUS_CONFIRMED||this._localHold===!0||!this.isReadyToReOffer())return!1;this._localHold=!0,this._onhold(`local`);let n={succeeded:()=>{t&&t()},failed:()=>{this.terminate({cause:a.causes.WEBRTC_ERROR,status_code:500,reason_phrase:`Hold Failed`})}};return e.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:n,extraHeaders:e.extraHeaders}):this._sendReinvite({eventHandlers:n,extraHeaders:e.extraHeaders}),!0}unhold(e={},t){if(v.debug(`unhold()`),this._status!==y.STATUS_WAITING_FOR_ACK&&this._status!==y.STATUS_CONFIRMED||this._localHold===!1||!this.isReadyToReOffer())return!1;this._localHold=!1,this._onunhold(`local`);let n={succeeded:()=>{t&&t()},failed:()=>{this.terminate({cause:a.causes.WEBRTC_ERROR,status_code:500,reason_phrase:`Unhold Failed`})}};return e.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:n,extraHeaders:e.extraHeaders}):this._sendReinvite({eventHandlers:n,extraHeaders:e.extraHeaders}),!0}renegotiate(e={},t){v.debug(`renegotiate()`);let n=e.rtcOfferConstraints||null;if(this._status!==y.STATUS_WAITING_FOR_ACK&&this._status!==y.STATUS_CONFIRMED||!this.isReadyToReOffer())return!1;let r={succeeded:()=>{t&&t()},failed:()=>{this.terminate({cause:a.causes.WEBRTC_ERROR,status_code:500,reason_phrase:`Media Renegotiation Failed`})}};return this._setLocalMediaStatus(),e.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:r,rtcOfferConstraints:n,extraHeaders:e.extraHeaders}):this._sendReinvite({eventHandlers:r,rtcOfferConstraints:n,extraHeaders:e.extraHeaders}),!0}refer(e,t){v.debug(`refer()`);let n=e;if(this._status!==y.STATUS_WAITING_FOR_ACK&&this._status!==y.STATUS_CONFIRMED)return!1;if(e=this._ua.normalizeTarget(e),!e)throw TypeError(`Invalid target: ${n}`);let r=new g(this);r.sendRefer(e,t);let i=r.id;return this._referSubscribers[i]=r,r.on(`requestFailed`,()=>{delete this._referSubscribers[i]}),r.on(`accepted`,()=>{delete this._referSubscribers[i]}),r.on(`failed`,()=>{delete this._referSubscribers[i]}),r.on(`authenticated`,()=>{delete this._referSubscribers[i],i=r.id,this._referSubscribers[i]=r}),r}sendRequest(e,t){if(v.debug(`sendRequest()`),this._dialog)return this._dialog.sendRequest(e,t);{let n=Object.values(this._earlyDialogs);if(n.length>0)return n[0].sendRequest(e,t);v.warn(`sendRequest() | no valid early dialog found`);return}}receiveRequest(e){if(v.debug(`receiveRequest()`),e.method===a.CANCEL)(this._status===y.STATUS_WAITING_FOR_ANSWER||this._status===y.STATUS_ANSWERED)&&(this._status=y.STATUS_CANCELED,this._request.reply(487),this._failed(`remote`,e,a.causes.CANCELED));else switch(e.method){case a.ACK:if(this._status!==y.STATUS_WAITING_FOR_ACK)return;if(this._status=y.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!e.body){this.terminate({cause:a.causes.MISSING_SDP,status_code:400});break}let t={originator:`remote`,type:`answer`,sdp:e.body};v.debug(`emit "sdp"`),this.emit(`sdp`,t);let n=new RTCSessionDescription({type:`answer`,sdp:t.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(n)).then(()=>{this._is_confirmed||this._confirmed(`remote`,e)}).catch(e=>{this.terminate({cause:a.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),v.warn(`emit "peerconnection:setremotedescriptionfailed" [error:%o]`,e),this.emit(`peerconnection:setremotedescriptionfailed`,e)})}else this._is_confirmed||this._confirmed(`remote`,e);break;case a.BYE:this._status===y.STATUS_CONFIRMED||this._status===y.STATUS_WAITING_FOR_ACK?(e.reply(200),this._ended(`remote`,e,a.causes.BYE)):this._status===y.STATUS_INVITE_RECEIVED||this._status===y.STATUS_WAITING_FOR_ANSWER?(e.reply(200),this._request.reply(487,`BYE Received`),this._ended(`remote`,e,a.causes.BYE)):e.reply(403,`Wrong Status`);break;case a.INVITE:this._status===y.STATUS_CONFIRMED?e.hasHeader(`replaces`)?this._receiveReplaces(e):this._receiveReinvite(e):e.reply(403,`Wrong Status`);break;case a.INFO:if(this._status===y.STATUS_1XX_RECEIVED||this._status===y.STATUS_WAITING_FOR_ANSWER||this._status===y.STATUS_ANSWERED||this._status===y.STATUS_WAITING_FOR_ACK||this._status===y.STATUS_CONFIRMED){let t=e.hasHeader(`Content-Type`)?e.getHeader(`Content-Type`).toLowerCase():void 0;t&&t.match(/^application\/dtmf-relay/i)?new p(this).init_incoming(e):t===void 0?e.reply(415):new m(this).init_incoming(e)}else e.reply(403,`Wrong Status`);break;case a.UPDATE:this._status===y.STATUS_CONFIRMED?this._receiveUpdate(e):e.reply(403,`Wrong Status`);break;case a.REFER:this._status===y.STATUS_CONFIRMED?this._receiveRefer(e):e.reply(403,`Wrong Status`);break;case a.NOTIFY:this._status===y.STATUS_CONFIRMED?this._receiveNotify(e):e.reply(403,`Wrong Status`);break;default:e.reply(501)}}onTransportError(){v.warn(`onTransportError()`),this._status!==y.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:a.causes.CONNECTION_ERROR,cause:a.causes.CONNECTION_ERROR})}onRequestTimeout(){v.warn(`onRequestTimeout()`),this._status!==y.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:a.causes.REQUEST_TIMEOUT,cause:a.causes.REQUEST_TIMEOUT})}onDialogError(){v.warn(`onDialogError()`),this._status!==y.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:a.causes.DIALOG_ERROR,cause:a.causes.DIALOG_ERROR})}newDTMF(e){v.debug(`newDTMF()`),this.emit(`newDTMF`,e)}newInfo(e){v.debug(`newInfo()`),this.emit(`newInfo`,e)}isReadyToReOffer(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(v.debug(`isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress`),!1):!0:(v.debug(`isReadyToReOffer() | session not established yet`),!1):(v.debug(`isReadyToReOffer() | internal WebRTC status not ready`),!1)}_close(){if(v.debug(`close()`),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(v.debug(`close() | closing local MediaStream`),c.closeMediaStream(this._localMediaStream)),this._status!==y.STATUS_TERMINATED){if(this._status=y.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(e){v.warn(`close() | error closing the RTCPeerConnection: %o`,e)}for(let e in this._timers)Object.prototype.hasOwnProperty.call(this._timers,e)&&clearTimeout(this._timers[e]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(let e in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,e)&&(this._earlyDialogs[e].terminate(),delete this._earlyDialogs[e]);for(let e in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,e)&&delete this._referSubscribers[e];this._ua.destroyRTCSession(this)}}_setInvite2xxTimer(e,t){let n=l.T1;function r(){this._status===y.STATUS_WAITING_FOR_ACK&&(e.reply(200,null,[`Contact: ${this._contact}`],t),n<l.T2&&(n*=2,n>l.T2&&(n=l.T2)),this._timers.invite2xxTimer=setTimeout(r.bind(this),n))}this._timers.invite2xxTimer=setTimeout(r.bind(this),n)}_setACKTimer(){this._timers.ackTimer=setTimeout(()=>{this._status===y.STATUS_WAITING_FOR_ACK&&(v.debug(`no ACK received, terminating the session`),clearTimeout(this._timers.invite2xxTimer),this.sendRequest(a.BYE),this._ended(`remote`,null,a.causes.NO_ACK))},l.TIMER_H)}_createRTCConnection(e,t){this._connection=new RTCPeerConnection(e,t),this._connection.addEventListener(`iceconnectionstatechange`,()=>{this._connection.iceConnectionState===`failed`&&this.terminate({cause:a.causes.RTP_TIMEOUT,status_code:408,reason_phrase:a.causes.RTP_TIMEOUT})}),v.debug(`emit "peerconnection"`),this.emit(`peerconnection`,{peerconnection:this._connection})}_createLocalDescription(e,t){if(v.debug(`createLocalDescription()`),e!==`offer`&&e!==`answer`)throw Error(`createLocalDescription() | invalid type "${e}"`);let n=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>e===`offer`?n.createOffer(t).catch(e=>(v.warn(`emit "peerconnection:createofferfailed" [error:%o]`,e),this.emit(`peerconnection:createofferfailed`,e),Promise.reject(e))):n.createAnswer(t).catch(e=>(v.warn(`emit "peerconnection:createanswerfailed" [error:%o]`,e),this.emit(`peerconnection:createanswerfailed`,e),Promise.reject(e)))).then(e=>n.setLocalDescription(e).catch(e=>(this._rtcReady=!0,v.warn(`emit "peerconnection:setlocaldescriptionfailed" [error:%o]`,e),this.emit(`peerconnection:setlocaldescriptionfailed`,e),Promise.reject(e)))).then(()=>{let r=t&&t.iceRestart;if(n.iceGatheringState===`complete`&&!r||n.iceGatheringState===`gathering`&&this._iceReady){this._rtcReady=!0;let t={originator:`local`,type:e,sdp:n.localDescription.sdp};return v.debug(`emit "sdp"`),this.emit(`sdp`,t),Promise.resolve(t.sdp)}return new Promise(t=>{let r=!1,i,a;this._iceReady=!1;let o=()=>{if(r)return;n.removeEventListener(`icecandidate`,i),n.removeEventListener(`icegatheringstatechange`,a),r=!0,this._rtcReady=!0,this._iceReady=!0;let o={originator:`local`,type:e,sdp:n.localDescription.sdp};v.debug(`emit "sdp"`),this.emit(`sdp`,o),t(o.sdp)};n.addEventListener(`icecandidate`,i=e=>{let t=e.candidate;t?this.emit(`icecandidate`,{candidate:t,ready:o}):o()}),n.addEventListener(`icegatheringstatechange`,a=()=>{n.iceGatheringState===`complete`&&o()})})})}_createDialog(e,t,n){let r=t===`UAS`?e.to_tag:e.from_tag,i=t===`UAS`?e.from_tag:e.to_tag,o=e.call_id+r+i,s=this._earlyDialogs[o];if(n)return s?!0:(s=new d(this,e,t,d.C.STATUS_EARLY),s.error?(v.debug(s.error),this._failed(`remote`,e,a.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[o]=s,!0));{if(this._from_tag=e.from_tag,this._to_tag=e.to_tag,s)return s.update(e,t),this._dialog=s,delete this._earlyDialogs[o],!0;let n=new d(this,e,t);return n.error?(v.debug(n.error),this._failed(`remote`,e,a.causes.INTERNAL_ERROR),!1):(this._dialog=n,!0)}}_receiveReinvite(e){v.debug(`receiveReinvite()`);let t=e.hasHeader(`Content-Type`)?e.getHeader(`Content-Type`).toLowerCase():void 0,n={request:e,callback:void 0,reject:i.bind(this)},r=!1;function i(t={}){r=!0;let n=t.status_code||403,i=t.reason_phrase||``,a=c.cloneArray(t.extraHeaders);if(this._status!==y.STATUS_CONFIRMED)return!1;if(n<300||n>=700)throw TypeError(`Invalid status_code: ${n}`);e.reply(n,i,a)}if(this.emit(`reinvite`,n),r)return;if(this._late_sdp=!1,!e.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold(`remote`)),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription(`offer`,this._rtcOfferConstraints)).then(e=>{a.call(this,e)}).catch(()=>{e.reply(500)});return}if(t!==`application/sdp`){v.debug(`invalid Content-Type`),e.reply(415);return}this._processInDialogSdpOffer(e).then(e=>{this._status!==y.STATUS_TERMINATED&&a.call(this,e)}).catch(e=>{v.warn(e)});function a(t){let r=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(e,r),this._late_sdp&&(t=this._mangleOffer(t)),e.reply(200,null,r,t,()=>{this._status=y.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(e,t),this._setACKTimer()}),typeof n.callback==`function`&&n.callback()}}_receiveUpdate(e){v.debug(`receiveUpdate()`);let t=e.hasHeader(`Content-Type`)?e.getHeader(`Content-Type`).toLowerCase():void 0,n={request:e,callback:void 0,reject:i.bind(this)},r=!1;function i(t={}){r=!0;let n=t.status_code||403,i=t.reason_phrase||``,a=c.cloneArray(t.extraHeaders);if(this._status!==y.STATUS_CONFIRMED)return!1;if(n<300||n>=700)throw TypeError(`Invalid status_code: ${n}`);e.reply(n,i,a)}if(this.emit(`update`,n),r)return;if(!e.body){a.call(this,null);return}if(t!==`application/sdp`){v.debug(`invalid Content-Type`),e.reply(415);return}this._processInDialogSdpOffer(e).then(e=>{this._status!==y.STATUS_TERMINATED&&a.call(this,e)}).catch(e=>{v.warn(e)});function a(t){let r=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(e,r),e.reply(200,null,r,t),typeof n.callback==`function`&&n.callback()}}_processInDialogSdpOffer(e){v.debug(`_processInDialogSdpOffer()`);let t=e.parseSDP(),n=!1;for(let e of t.media){if(b.indexOf(e.type)===-1)continue;let r=e.direction||t.direction||`sendrecv`;if(r===`sendonly`||r===`inactive`)n=!0;else{n=!1;break}}let r={originator:`remote`,type:`offer`,sdp:e.body};v.debug(`emit "sdp"`),this.emit(`sdp`,r);let i=new RTCSessionDescription({type:`offer`,sdp:r.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._status===y.STATUS_TERMINATED)throw Error(`terminated`);return this._connection.setRemoteDescription(i).catch(t=>{throw e.reply(488),v.warn(`emit "peerconnection:setremotedescriptionfailed" [error:%o]`,t),this.emit(`peerconnection:setremotedescriptionfailed`,t),t})}).then(()=>{if(this._status===y.STATUS_TERMINATED)throw Error(`terminated`);this._remoteHold===!0&&n===!1?(this._remoteHold=!1,this._onunhold(`remote`)):this._remoteHold===!1&&n===!0&&(this._remoteHold=!0,this._onhold(`remote`))}).then(()=>{if(this._status===y.STATUS_TERMINATED)throw Error(`terminated`);return this._createLocalDescription(`answer`,this._rtcAnswerConstraints).catch(t=>{throw e.reply(500),v.warn(`emit "peerconnection:createtelocaldescriptionfailed" [error:%o]`,t),t})}).catch(e=>{v.warn(`_processInDialogSdpOffer() failed [error: %o]`,e)}),this._connectionPromiseQueue}_receiveRefer(t){if(v.debug(`receiveRefer()`),!t.refer_to){v.debug(`no Refer-To header field present in REFER`),t.reply(400);return}if(t.refer_to.uri.scheme!==a.SIP){v.debug(`Refer-To header field points to a non-SIP URI scheme`),t.reply(416);return}t.reply(202);let n=new h(this,t.cseq);v.debug(`emit "refer"`),this.emit(`refer`,{request:t,accept:(e,t)=>{r.call(this,e,t)},reject:()=>{i.call(this)}});function r(r,i={}){if(r=typeof r==`function`?r:null,this._status!==y.STATUS_WAITING_FOR_ACK&&this._status!==y.STATUS_CONFIRMED)return!1;let a=new e(this._ua);if(a.on(`progress`,({response:e})=>{n.notify(e.status_code,e.reason_phrase)}),a.on(`accepted`,({response:e})=>{n.notify(e.status_code,e.reason_phrase)}),a.on(`_failed`,({message:e,cause:t})=>{e?n.notify(e.status_code,e.reason_phrase):n.notify(487,t)}),t.refer_to.uri.hasHeader(`replaces`)){let e=decodeURIComponent(t.refer_to.uri.getHeader(`replaces`));i.extraHeaders=c.cloneArray(i.extraHeaders),i.extraHeaders.push(`Replaces: ${e}`)}let o=t.refer_to.uri.clone();o.clearHeaders(),a.connect(o,i,r)}function i(){n.notify(603)}}_receiveNotify(e){switch(v.debug(`receiveNotify()`),e.event||e.reply(400),e.event.event){case`refer`:{let t,n;if(e.event.params&&e.event.params.id)t=e.event.params.id,n=this._referSubscribers[t];else if(Object.keys(this._referSubscribers).length===1)n=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{e.reply(400,`Missing event id parameter`);return}if(!n){e.reply(481,`Subscription does not exist`);return}n.receiveNotify(e),e.reply(200);break}default:e.reply(489)}}_receiveReplaces(t){v.debug(`receiveReplaces()`);function n(n){if(this._status!==y.STATUS_WAITING_FOR_ACK&&this._status!==y.STATUS_CONFIRMED)return!1;let r=new e(this._ua);r.on(`confirmed`,()=>{this.terminate()}),r.init_incoming(t,n)}function r(){v.debug(`Replaced INVITE rejected by the user`),t.reply(486)}this.emit(`replaces`,{request:t,accept:e=>{n.call(this,e)},reject:()=>{r.call(this)}})}_sendInitialRequest(e,t,n){let r=new f(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:e=>{this._request=e},onReceiveResponse:e=>{this._receiveInviteResponse(e)}});Promise.resolve().then(()=>{if(n)return n;if(e.audio||e.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(e).catch(e=>{throw this._status===y.STATUS_TERMINATED?Error(`terminated`):(this._failed(`local`,null,a.causes.USER_DENIED_MEDIA_ACCESS),v.warn(`emit "getusermediafailed" [error:%o]`,e),this.emit(`getusermediafailed`,e),e)})}).then(e=>{if(this._status===y.STATUS_TERMINATED)throw Error(`terminated`);return this._localMediaStream=e,e&&e.getTracks().forEach(t=>{this._connection.addTrack(t,e)}),this._connecting(this._request),this._createLocalDescription(`offer`,t).catch(e=>{throw this._failed(`local`,null,a.causes.WEBRTC_ERROR),e})}).then(e=>{if(this._is_canceled||this._status===y.STATUS_TERMINATED)throw Error(`terminated`);this._request.body=e,this._status=y.STATUS_INVITE_SENT,v.debug(`emit "sending" [request:%o]`,this._request),this.emit(`sending`,{request:this._request}),r.send()}).catch(e=>{this._status!==y.STATUS_TERMINATED&&v.warn(e)})}_getDTMFRTPSender(){let e=this._connection.getSenders().find(e=>e.track&&e.track.kind===`audio`);if(!(e&&e.dtmf)){v.warn(`sendDTMF() | no local audio track to send DTMF with`);return}return e.dtmf}_receiveInviteResponse(e){if(v.debug(`receiveInviteResponse()`),this._dialog&&e.status_code>=200&&e.status_code<=299){if(this._dialog.id.call_id===e.call_id&&this._dialog.id.local_tag===e.from_tag&&this._dialog.id.remote_tag===e.to_tag){this.sendRequest(a.ACK);return}{let t=new d(this,e,`UAC`);if(t.error!==void 0){v.debug(t.error);return}this.sendRequest(a.ACK),this.sendRequest(a.BYE);return}}if(this._is_canceled){e.status_code>=100&&e.status_code<200?this._request.cancel(this._cancel_reason):e.status_code>=200&&e.status_code<299&&this._acceptAndTerminate(e);return}if(this._status===y.STATUS_INVITE_SENT||this._status===y.STATUS_1XX_RECEIVED)switch(!0){case/^100$/.test(e.status_code):this._status=y.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(e.status_code):{if(!e.to_tag){v.debug(`1xx response received without to tag`);break}if(e.hasHeader(`contact`)&&!this._createDialog(e,`UAC`,!0))break;if(this._status=y.STATUS_1XX_RECEIVED,!e.body){this._progress(`remote`,e);break}let t={originator:`remote`,type:`answer`,sdp:e.body};v.debug(`emit "sdp"`),this.emit(`sdp`,t);let n=new RTCSessionDescription({type:`answer`,sdp:t.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(n)).then(()=>this._progress(`remote`,e)).catch(e=>{v.warn(`emit "peerconnection:setremotedescriptionfailed" [error:%o]`,e),this.emit(`peerconnection:setremotedescriptionfailed`,e)});break}case/^2[0-9]{2}$/.test(e.status_code):{if(this._status=y.STATUS_CONFIRMED,!e.body){this._acceptAndTerminate(e,400,a.causes.MISSING_SDP),this._failed(`remote`,e,a.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(e,`UAC`))break;let t={originator:`remote`,type:`answer`,sdp:e.body};v.debug(`emit "sdp"`),this.emit(`sdp`,t);let n=new RTCSessionDescription({type:`answer`,sdp:t.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState===`stable`)return this._connection.createOffer(this._rtcOfferConstraints).then(e=>this._connection.setLocalDescription(e)).catch(t=>{this._acceptAndTerminate(e,500,t.toString()),this._failed(`local`,e,a.causes.WEBRTC_ERROR)})}).then(()=>{this._connection.setRemoteDescription(n).then(()=>{this._handleSessionTimersInIncomingResponse(e),this._accepted(`remote`,e),this.sendRequest(a.ACK),this._confirmed(`local`,null)}).catch(t=>{this._acceptAndTerminate(e,488,`Not Acceptable Here`),this._failed(`remote`,e,a.causes.BAD_MEDIA_DESCRIPTION),v.warn(`emit "peerconnection:setremotedescriptionfailed" [error:%o]`,t),this.emit(`peerconnection:setremotedescriptionfailed`,t)})});break}default:{let t=c.sipErrorCause(e.status_code);this._failed(`remote`,e,t)}}}_sendReinvite(e={}){v.debug(`sendReinvite()`);let t=c.cloneArray(e.extraHeaders),n=c.cloneObject(e.eventHandlers),r=e.rtcOfferConstraints||this._rtcOfferConstraints||null,i=!1;t.push(`Contact: ${this._contact}`),t.push(`Content-Type: application/sdp`),this._sessionTimers.running&&t.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?`uac`:`uas`}`),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription(`offer`,r)).then(e=>{e=this._mangleOffer(e);let n={originator:`local`,type:`offer`,sdp:e};v.debug(`emit "sdp"`),this.emit(`sdp`,n),this.sendRequest(a.INVITE,{extraHeaders:t,body:e,eventHandlers:{onSuccessResponse:e=>{o.call(this,e),i=!0},onErrorResponse:e=>{s.call(this,e)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{s()});function o(e){if(this._status===y.STATUS_TERMINATED||(this.sendRequest(a.ACK),i))return;if(this._handleSessionTimersInIncomingResponse(e),!e.body){s.call(this);return}if(!e.hasHeader(`Content-Type`)||e.getHeader(`Content-Type`).toLowerCase()!==`application/sdp`){s.call(this);return}let t={originator:`remote`,type:`answer`,sdp:e.body};v.debug(`emit "sdp"`),this.emit(`sdp`,t);let r=new RTCSessionDescription({type:`answer`,sdp:t.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(r)).then(()=>{n.succeeded&&n.succeeded(e)}).catch(e=>{s.call(this),v.warn(`emit "peerconnection:setremotedescriptionfailed" [error:%o]`,e),this.emit(`peerconnection:setremotedescriptionfailed`,e)})}function s(e){n.failed&&n.failed(e)}}_sendUpdate(e={}){v.debug(`sendUpdate()`);let t=c.cloneArray(e.extraHeaders),n=c.cloneObject(e.eventHandlers),r=e.rtcOfferConstraints||this._rtcOfferConstraints||null,i=e.sdpOffer||!1,o=!1;t.push(`Contact: ${this._contact}`),this._sessionTimers.running&&t.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?`uac`:`uas`}`),i?(t.push(`Content-Type: application/sdp`),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription(`offer`,r)).then(e=>{e=this._mangleOffer(e);let n={originator:`local`,type:`offer`,sdp:e};v.debug(`emit "sdp"`),this.emit(`sdp`,n),this.sendRequest(a.UPDATE,{extraHeaders:t,body:e,eventHandlers:{onSuccessResponse:e=>{s.call(this,e),o=!0},onErrorResponse:e=>{l.call(this,e)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{l.call(this)})):this.sendRequest(a.UPDATE,{extraHeaders:t,eventHandlers:{onSuccessResponse:e=>{s.call(this,e)},onErrorResponse:e=>{l.call(this,e)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}});function s(e){if(this._status!==y.STATUS_TERMINATED&&!o){if(this._handleSessionTimersInIncomingResponse(e),i){if(!e.body){l.call(this);return}if(!e.hasHeader(`Content-Type`)||e.getHeader(`Content-Type`).toLowerCase()!==`application/sdp`){l.call(this);return}let t={originator:`remote`,type:`answer`,sdp:e.body};v.debug(`emit "sdp"`),this.emit(`sdp`,t);let r=new RTCSessionDescription({type:`answer`,sdp:t.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(r)).then(()=>{n.succeeded&&n.succeeded(e)}).catch(e=>{l.call(this),v.warn(`emit "peerconnection:setremotedescriptionfailed" [error:%o]`,e),this.emit(`peerconnection:setremotedescriptionfailed`,e)})}else n.succeeded&&n.succeeded(e)}}function l(e){n.failed&&n.failed(e)}}_acceptAndTerminate(e,t,n){v.debug(`acceptAndTerminate()`);let r=[];t&&(n=n||a.REASON_PHRASE[t]||``,r.push(`Reason: SIP ;cause=${t}; text="${n}"`)),(this._dialog||this._createDialog(e,`UAC`))&&(this.sendRequest(a.ACK),this.sendRequest(a.BYE,{extraHeaders:r})),this._status=y.STATUS_TERMINATED}_mangleOffer(e){if(!this._localHold&&!this._remoteHold)return e;if(e=r.parse(e),this._localHold&&!this._remoteHold){v.debug(`mangleOffer() | me on hold, mangling offer`);for(let t of e.media)b.indexOf(t.type)!==-1&&(t.direction?t.direction===`sendrecv`?t.direction=`sendonly`:t.direction===`recvonly`&&(t.direction=`inactive`):t.direction=`sendonly`)}else if(this._localHold&&this._remoteHold){v.debug(`mangleOffer() | both on hold, mangling offer`);for(let t of e.media)b.indexOf(t.type)!==-1&&(t.direction=`inactive`)}else if(this._remoteHold){v.debug(`mangleOffer() | remote on hold, mangling offer`);for(let t of e.media)b.indexOf(t.type)!==-1&&(t.direction?t.direction===`sendrecv`?t.direction=`recvonly`:t.direction===`recvonly`&&(t.direction=`inactive`):t.direction=`recvonly`)}return r.write(e)}_setLocalMediaStatus(){let e=!0,t=!0;(this._localHold||this._remoteHold)&&(e=!1,t=!1),this._audioMuted&&(e=!1),this._videoMuted&&(t=!1),this._toggleMuteAudio(!e),this._toggleMuteVideo(!t)}_handleSessionTimersInIncomingRequest(e,t){if(!this._sessionTimers.enabled)return;let n;e.session_expires&&e.session_expires>=a.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=e.session_expires,n=e.session_expires_refresher||`uas`):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,n=`uas`),t.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${n}`),this._sessionTimers.refresher=n===`uas`,this._runSessionTimer()}_handleSessionTimersInIncomingResponse(e){if(!this._sessionTimers.enabled)return;let t;e.session_expires&&e.session_expires>=a.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=e.session_expires,t=e.session_expires_refresher||`uac`):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,t=`uac`),this._sessionTimers.refresher=t===`uac`,this._runSessionTimer()}_runSessionTimer(){let e=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(()=>{this._status!==y.STATUS_TERMINATED&&this.isReadyToReOffer()&&(v.debug(`runSessionTimer() | sending session refresh request`),this._sessionTimers.refreshMethod===a.UPDATE?this._sendUpdate():this._sendReinvite())},e*500):this._sessionTimers.timer=setTimeout(()=>{this._status!==y.STATUS_TERMINATED&&(v.warn(`runSessionTimer() | timer expired, terminating the session`),this.terminate({cause:a.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:`Session Timer Expired`}))},e*1100)}_toggleMuteAudio(e){let t=this._connection.getSenders().filter(e=>e.track&&e.track.kind===`audio`);for(let n of t)n.track.enabled=!e}_toggleMuteVideo(e){let t=this._connection.getSenders().filter(e=>e.track&&e.track.kind===`video`);for(let n of t)n.track.enabled=!e}_newRTCSession(e,t){v.debug(`newRTCSession()`),this._ua.newRTCSession(this,{originator:e,session:this,request:t})}_connecting(e){v.debug(`session connecting`),v.debug(`emit "connecting"`),this.emit(`connecting`,{request:e})}_progress(e,t){v.debug(`session progress`),v.debug(`emit "progress"`),this.emit(`progress`,{originator:e,response:t||null})}_accepted(e,t){v.debug(`session accepted`),this._start_time=new Date,v.debug(`emit "accepted"`),this.emit(`accepted`,{originator:e,response:t||null})}_confirmed(e,t){v.debug(`session confirmed`),this._is_confirmed=!0,v.debug(`emit "confirmed"`),this.emit(`confirmed`,{originator:e,ack:t||null})}_ended(e,t,n){v.debug(`session ended`),this._end_time=new Date,this._close(),v.debug(`emit "ended"`),this.emit(`ended`,{originator:e,message:t||null,cause:n})}_failed(e,t,n){v.debug(`session failed`),v.debug(`emit "_failed"`),this.emit(`_failed`,{originator:e,message:t||null,cause:n}),this._close(),v.debug(`emit "failed"`),this.emit(`failed`,{originator:e,message:t||null,cause:n})}_onhold(e){v.debug(`session onhold`),this._setLocalMediaStatus(),v.debug(`emit "hold"`),this.emit(`hold`,{originator:e})}_onunhold(e){v.debug(`session onunhold`),this._setLocalMediaStatus(),v.debug(`emit "unhold"`),this.emit(`unhold`,{originator:e})}_onmute({audio:e,video:t}){v.debug(`session onmute`),this._setLocalMediaStatus(),v.debug(`emit "muted"`),this.emit(`muted`,{audio:e,video:t})}_onunmute({audio:e,video:t}){v.debug(`session onunmute`),this._setLocalMediaStatus(),v.debug(`emit "unmuted"`),this.emit(`unmuted`,{audio:e,video:t})}}})),an=c(((e,t)=>{var n=q().EventEmitter,r=U(),i=J(),a=H(),o=K(),s=W(),c=Y(),l=X(),u=Qt(),d=new i(`Subscriber`),f={SUBSCRIBE_RESPONSE_TIMEOUT:0,SUBSCRIBE_TRANSPORT_ERROR:1,SUBSCRIBE_NON_OK_RESPONSE:2,SUBSCRIBE_WRONG_OK_RESPONSE:3,SUBSCRIBE_AUTHENTICATION_FAILED:4,UNSUBSCRIBE_TIMEOUT:5,FINAL_NOTIFY_RECEIVED:6,WRONG_NOTIFY_RECEIVED:7,STATE_PENDING:0,STATE_ACTIVE:1,STATE_TERMINATED:2,STATE_INIT:3,STATE_WAITING_NOTIFY:4,DEFAULT_EXPIRES_SEC:900};t.exports=class extends n{static get C(){return f}constructor(e,t,n,r,{expires:i,contentType:a,allowEvents:c,params:l,extraHeaders:u}){if(d.debug(`new`),super(),!t)throw TypeError(`Not enough arguments: Missing target`);if(!n)throw TypeError(`Not enough arguments: Missing eventName`);if(!r)throw TypeError(`Not enough arguments: Missing accept`);let p=s.parse(n,`Event`);if(p===-1)throw TypeError(`Missing Event header field`);this._ua=e,this._target=t,(!o.isDecimal(i)||i<=0)&&(i=f.DEFAULT_EXPIRES_SEC),this._expires=i,this._content_type=a,this._params=o.cloneObject(l),this._params.from_uri||(this._params.from_uri=this._ua.configuration.uri),this._params.from_tag=o.newTag(),this._params.to_tag=null,this._params.call_id=o.createRandomToken(20),this._params.cseq===void 0&&(this._params.cseq=Math.floor(Math.random()*1e4+1)),this._state=f.STATE_INIT,this._dialog=null,this._expires_timer=null,this._expires_timestamp=null,this._terminated=!1,this._event_name=p.event,this._event_id=p.params&&p.params.id;let m=this._event_name;if(this._event_id&&(m+=`;id=${this._event_id}`),this._headers=o.cloneArray(u),this._headers=this._headers.concat([`Event: ${m}`,`Expires: ${this._expires}`,`Accept: ${r}`]),!this._headers.find(e=>e.startsWith(`Contact`))){let e=`Contact: ${this._ua._contact.toString()}`;this._headers.push(e)}c&&this._headers.push(`Allow-Events: ${c}`),this._queue=[],this._data={}}get C(){return f}get state(){return this._state}get id(){return this._dialog?this._dialog.id:null}get data(){return this._data}set data(e){this._data=e}onRequestTimeout(){this._terminateDialog(f.SUBSCRIBE_RESPONSE_TIMEOUT)}onTransportError(){this._terminateDialog(f.SUBSCRIBE_TRANSPORT_ERROR)}receiveRequest(e){if(e.method!==a.NOTIFY){d.warn(`received non-NOTIFY request`),e.reply(405);return}let t=e.parseHeader(`Event`);if(!t){d.warn(`missing Event header`),e.reply(400),this._terminateDialog(f.WRONG_NOTIFY_RECEIVED);return}let n=t.event,r=t.params&&t.params.id;if(n!==this._event_name||r!==this._event_id){d.warn(`Event header does not match the one in SUBSCRIBE request`),e.reply(489),this._terminateDialog(f.WRONG_NOTIFY_RECEIVED);return}let i=e.parseHeader(`subscription-state`);if(!i){d.warn(`missing Subscription-State header`),e.reply(400),this._terminateDialog(f.WRONG_NOTIFY_RECEIVED);return}let o=this._parseSubscriptionState(i.state);if(o===void 0){d.warn(`Invalid Subscription-State header value: ${i.state}`),e.reply(400),this._terminateDialog(f.WRONG_NOTIFY_RECEIVED);return}e.reply(200);let s=this._state;if(s!==f.STATE_TERMINATED&&o!==f.STATE_TERMINATED&&(this._state=o,i.expires!==void 0)){let e=i.expires,t=new Date().getTime()+e*1e3;this._expires_timestamp-t>2e3&&(d.debug(`update sending re-SUBSCRIBE time`),this._scheduleSubscribe(e))}s!==f.STATE_PENDING&&o===f.STATE_PENDING?(d.debug(`emit "pending"`),this.emit(`pending`)):s!==f.STATE_ACTIVE&&o===f.STATE_ACTIVE&&(d.debug(`emit "active"`),this.emit(`active`));let c=e.body,l=o===f.STATE_TERMINATED;if(c){let t=e.getHeader(`content-type`);d.debug(`emit "notify"`),this.emit(`notify`,l,e,c,t)}if(l){let e=i.reason,t;i.params&&i.params[`retry-after`]!==void 0&&(t=parseInt(i.params[`retry-after`])),this._terminateDialog(f.FINAL_NOTIFY_RECEIVED,e,t)}}subscribe(e=null){d.debug(`subscribe()`),this._state===f.STATE_INIT?this._sendInitialSubscribe(e,this._headers):this._sendSubsequentSubscribe(e,this._headers)}terminate(e=null){if(d.debug(`terminate()`),this._state===f.STATE_INIT)throw new r.InvalidStateError(this._state);if(this._terminated)return;this._terminated=!0;let t=this._headers.map(e=>e.startsWith(`Expires`)?`Expires: 0`:e);this._sendSubsequentSubscribe(e,t)}_terminateDialog(e,t=void 0,n=void 0){this._state!==f.STATE_TERMINATED&&(this._state=f.STATE_TERMINATED,clearTimeout(this._expires_timer),this._dialog&&=(this._dialog.terminate(),null),d.debug(`emit "terminated" code=${e}`),this.emit(`terminated`,e,t,n))}_sendInitialSubscribe(e,t){if(e){if(!this._content_type)throw TypeError(`content_type is undefined`);t=o.cloneArray(t),t.push(`Content-Type: ${this._content_type}`)}this._state=f.STATE_WAITING_NOTIFY;let n=new c.OutgoingRequest(a.SUBSCRIBE,this._ua.normalizeTarget(this._target),this._ua,this._params,t,e);new l(this._ua,n,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onReceiveResponse:e=>{this._receiveSubscribeResponse(e)}}).send()}_sendSubsequentSubscribe(e,t){if(this._state!==f.STATE_TERMINATED){if(!this._dialog){d.debug(`enqueue subscribe`),this._queue.push({body:e,headers:o.cloneArray(t)});return}if(e){if(!this._content_type)throw TypeError(`content_type is undefined`);t=o.cloneArray(t),t.push(`Content-Type: ${this._content_type}`)}this._dialog.sendRequest(a.SUBSCRIBE,{body:e,extraHeaders:t,eventHandlers:{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onSuccessResponse:e=>{this._receiveSubscribeResponse(e)},onErrorResponse:e=>{this._receiveSubscribeResponse(e)},onDialogError:e=>{this._receiveSubscribeResponse(e)}}})}}_receiveSubscribeResponse(e){if(this._state!==f.STATE_TERMINATED){if(e.status_code>=200&&e.status_code<300){if(this._dialog===null){let t=new u(this,e,`UAC`);if(t.error){d.warn(t.error),this._terminateDialog(f.SUBSCRIBE_WRONG_OK_RESPONSE);return}this._dialog=t,d.debug(`emit "accepted"`),this.emit(`accepted`);for(let e of this._queue)d.debug(`dequeue subscribe`),this._sendSubsequentSubscribe(e.body,e.headers)}let t=e.getHeader(`expires`),n=parseInt(t);(!o.isDecimal(n)||n<=0)&&(d.warn(`response without Expires header, setting a default value of ${f.DEFAULT_EXPIRES_SEC}`),n=f.DEFAULT_EXPIRES_SEC),n>0&&this._scheduleSubscribe(n)}else e.status_code===401||e.status_code===407?this._terminateDialog(f.SUBSCRIBE_AUTHENTICATION_FAILED):e.status_code>=300&&this._terminateDialog(f.SUBSCRIBE_NON_OK_RESPONSE)}}_scheduleSubscribe(e){let t=e>=140?e*1e3/2+Math.floor((e/2-70)*1e3*Math.random()):e*1e3-5e3;this._expires_timestamp=new Date().getTime()+e*1e3,d.debug(`next SUBSCRIBE will be sent in ${Math.floor(t/1e3)} sec`),clearTimeout(this._expires_timer),this._expires_timer=setTimeout(()=>{this._expires_timer=null,this._sendSubsequentSubscribe(null,this._headers)},t)}_parseSubscriptionState(e){switch(e){case`pending`:return f.STATE_PENDING;case`active`:return f.STATE_ACTIVE;case`terminated`:return f.STATE_TERMINATED;case`init`:return f.STATE_INIT;case`notify_wait`:return f.STATE_WAITING_NOTIFY;default:return}}}})),on=c(((e,t)=>{var n=q().EventEmitter,r=U(),i=J(),a=H(),o=K(),s=Qt(),c=new i(`Notifier`),l={NOTIFY_RESPONSE_TIMEOUT:0,NOTIFY_TRANSPORT_ERROR:1,NOTIFY_NON_OK_RESPONSE:2,NOTIFY_AUTHENTICATION_FAILED:3,FINAL_NOTIFY_SENT:4,UNSUBSCRIBE_RECEIVED:5,SUBSCRIPTION_EXPIRED:6,STATE_PENDING:0,STATE_ACTIVE:1,STATE_TERMINATED:2,DEFAULT_EXPIRES_SEC:900};t.exports=class e extends n{static get C(){return l}static init_incoming(t,n){try{e.checkSubscribe(t)}catch(e){c.warn(`Notifier.init_incoming: invalid request. Error: `,e.message),t.reply(405);return}n()}static checkSubscribe(e){if(!e)throw TypeError(`Not enough arguments. Missing subscribe request`);if(e.method!==a.SUBSCRIBE)throw TypeError(`Invalid method for Subscribe request`);if(!e.hasHeader(`contact`))throw TypeError(`Missing Contact header in subscribe request`);if(!e.hasHeader(`event`))throw TypeError(`Missing Event header in subscribe request`);let t=e.getHeader(`expires`);if(t){let e=parseInt(t);if(!o.isDecimal(e)||e<0)throw TypeError(`Invalid Expires header field in subscribe request`)}}constructor(t,n,r,{extraHeaders:i,allowEvents:a,pending:s,defaultExpires:u}){if(c.debug(`new`),super(),!r)throw TypeError(`Not enough arguments. Missing contentType`);e.checkSubscribe(n);let d=n.getHeader(`event`);this._ua=t,this._initial_subscribe=n,this._expires_timestamp=null,this._expires_timer=null,this._defaultExpires=u||l.DEFAULT_EXPIRES_SEC,this._state=s?l.STATE_PENDING:l.STATE_ACTIVE,this._content_type=r,this._headers=o.cloneArray(i),this._headers.push(`Event: ${d}`),this._contact=this._headers.find(e=>e.startsWith(`Contact`)),this._contact||(this._contact=`Contact: ${this._ua._contact.toString()}`,this._headers.push(this._contact)),a&&this._headers.push(`Allow-Events: ${a}`),this._target=n.from.uri.user,n.to_tag=o.newTag(),this._data={}}get C(){return l}get state(){return this._state}get id(){return this._dialog?this._dialog.id:null}get data(){return this._data}set data(e){this._data=e}receiveRequest(e){if(e.method!==a.SUBSCRIBE){e.reply(405);return}this._setExpires(e),this._dialog||=new s(this,e,`UAS`),e.reply(200,null,[`Expires: ${this._expires}`,`${this._contact}`]);let t=e.body,n=e.getHeader(`content-type`),r=this._expires===0;r||this._setExpiresTimer(),c.debug(`emit "subscribe"`),this.emit(`subscribe`,r,e,t,n),r&&this._terminateDialog(l.UNSUBSCRIBE_RECEIVED)}start(){if(c.debug(`start()`),this._state===l.STATE_TERMINATED)throw new r.InvalidStateError(this._state);this.receiveRequest(this._initial_subscribe)}setActiveState(){if(c.debug(`setActiveState()`),this._state===l.STATE_TERMINATED)throw new r.InvalidStateError(this._state);this._state===l.STATE_PENDING&&(this._state=l.STATE_ACTIVE)}notify(e=null){if(c.debug(`notify()`),this._state===l.STATE_TERMINATED)throw new r.InvalidStateError(this._state);let t=Math.floor((this._expires_timestamp-new Date().getTime())/1e3);t<=0?(this._expires_timer||c.error(`expires timer is not set`),clearTimeout(this._expires_timer),this.terminate(e,`timeout`)):this._sendNotify([`;expires=${t}`],e)}terminate(e=null,t=null,n=null){if(c.debug(`terminate()`),this._state===l.STATE_TERMINATED)return;let r=[];t&&r.push(`;reason=${t}`),n!==null&&r.push(`;retry-after=${n}`),this._sendNotify(r,e,null,`terminated`),this._terminateDialog(t===`timeout`?l.SUBSCRIPTION_EXPIRED:l.FINAL_NOTIFY_SENT)}_terminateDialog(e){this._state!==l.STATE_TERMINATED&&(this._state=l.STATE_TERMINATED,clearTimeout(this._expires_timer),this._dialog&&=(this._dialog.terminate(),null),c.debug(`emit "terminated" code=${e}`),this.emit(`terminated`,e))}_setExpires(e){e.hasHeader(`expires`)?this._expires=parseInt(e.getHeader(`expires`)):(this._expires=this._defaultExpires,c.debug(`missing Expires header field, default value set: ${this._expires}`))}_sendNotify(e,t=null,n=null,r=null){if(this._state===l.STATE_TERMINATED){c.warn(`final notify already sent`);return}let i=`Subscription-State: ${r||this._parseState()}`;for(let t of e)i+=t;let s=o.cloneArray(this._headers);s.push(i),n&&(s=s.concat(n)),t&&s.push(`Content-Type: ${this._content_type}`),this._dialog.sendRequest(a.NOTIFY,{body:t,extraHeaders:s,eventHandlers:{onRequestTimeout:()=>{this._terminateDialog(l.NOTIFY_RESPONSE_TIMEOUT)},onTransportError:()=>{this._terminateDialog(l.NOTIFY_TRANSPORT_ERROR)},onErrorResponse:e=>{e.status_code===401||e.status_code===407?this._terminateDialog(l.NOTIFY_AUTHENTICATION_FAILED):this._terminateDialog(l.NOTIFY_NON_OK_RESPONSE)},onDialogError:()=>{this._terminateDialog(l.NOTIFY_NON_OK_RESPONSE)}}})}_setExpiresTimer(){this._expires_timestamp=new Date().getTime()+this._expires*1e3,clearTimeout(this._expires_timer),this._expires_timer=setTimeout(()=>{this._state!==l.STATE_TERMINATED&&(c.debug(`emit "expired"`),this.emit(`expired`),this.terminate(null,`timeout`))},this._expires*1e3)}_parseState(){switch(this._state){case l.STATE_PENDING:return`pending`;case l.STATE_ACTIVE:return`active`;case l.STATE_TERMINATED:return`terminated`;default:throw TypeError(`wrong state value`)}}}})),sn=c(((e,t)=>{var n=q().EventEmitter,r=J(),i=H(),a=Y(),o=K(),s=X(),c=U(),l=G(),u=new r(`Message`);t.exports=class extends n{constructor(e){super(),this._ua=e,this._request=null,this._closed=!1,this._direction=null,this._local_identity=null,this._remote_identity=null,this._is_replied=!1,this._data={}}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}send(e,t,n={}){let r=e;if(e===void 0||t===void 0)throw TypeError(`Not enough arguments`);if(e=this._ua.normalizeTarget(e),!e)throw TypeError(`Invalid target: ${r}`);let c=o.cloneArray(n.extraHeaders),u=o.cloneObject(n.eventHandlers),d=n.contentType||`text/plain`,f={};n.fromUserName&&(f.from_uri=new l(`sip`,n.fromUserName,this._ua.configuration.uri.host),c.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),n.fromDisplayName&&(f.from_display_name=n.fromDisplayName);for(let e in u)Object.prototype.hasOwnProperty.call(u,e)&&this.on(e,u[e]);c.push(`Content-Type: ${d}`),this._request=new a.OutgoingRequest(i.MESSAGE,e,this._ua,f,c),t&&(this._request.body=t);let p=new s(this._ua,this._request,{onRequestTimeout:()=>{this._onRequestTimeout()},onTransportError:()=>{this._onTransportError()},onReceiveResponse:e=>{this._receiveResponse(e)}});this._newMessage(`local`,this._request),p.send()}init_incoming(e){this._request=e,this._newMessage(`remote`,e),this._is_replied||(this._is_replied=!0,e.reply(200)),this._close()}accept(e={}){let t=o.cloneArray(e.extraHeaders),n=e.body;if(this._direction!==`incoming`)throw new c.NotSupportedError(`"accept" not supported for outgoing Message`);if(this._is_replied)throw Error(`incoming Message already replied`);this._is_replied=!0,this._request.reply(200,null,t,n)}reject(e={}){let t=e.status_code||480,n=e.reason_phrase,r=o.cloneArray(e.extraHeaders),i=e.body;if(this._direction!==`incoming`)throw new c.NotSupportedError(`"reject" not supported for outgoing Message`);if(this._is_replied)throw Error(`incoming Message already replied`);if(t<300||t>=700)throw TypeError(`Invalid status_code: ${t}`);this._is_replied=!0,this._request.reply(t,n,r,i)}_receiveResponse(e){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(e.status_code):break;case/^2[0-9]{2}$/.test(e.status_code):this._succeeded(`remote`,e);break;default:{let t=o.sipErrorCause(e.status_code);this._failed(`remote`,e,t);break}}}_onRequestTimeout(){this._closed||this._failed(`system`,null,i.causes.REQUEST_TIMEOUT)}_onTransportError(){this._closed||this._failed(`system`,null,i.causes.CONNECTION_ERROR)}_close(){this._closed=!0,this._ua.destroyMessage(this)}_newMessage(e,t){e===`remote`?(this._direction=`incoming`,this._local_identity=t.to,this._remote_identity=t.from):e===`local`&&(this._direction=`outgoing`,this._local_identity=t.from,this._remote_identity=t.to),this._ua.newMessage(this,{originator:e,message:this,request:t})}_failed(e,t,n){u.debug(`MESSAGE failed`),this._close(),u.debug(`emit "failed"`),this.emit(`failed`,{originator:e,response:t||null,cause:n})}_succeeded(e,t){u.debug(`MESSAGE succeeded`),this._close(),u.debug(`emit "succeeded"`),this.emit(`succeeded`,{originator:e,response:t})}}})),cn=c(((e,t)=>{var n=q().EventEmitter,r=J(),i=H(),a=Y(),o=K(),s=X(),c=U(),l=new r(`Options`);t.exports=class extends n{constructor(e){super(),this._ua=e,this._request=null,this._closed=!1,this._direction=null,this._local_identity=null,this._remote_identity=null,this._is_replied=!1,this._data={}}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}send(e,t,n={}){let r=e;if(e===void 0)throw TypeError(`A target is required for OPTIONS`);if(e=this._ua.normalizeTarget(e),!e)throw TypeError(`Invalid target: ${r}`);let c=o.cloneArray(n.extraHeaders),l=o.cloneObject(n.eventHandlers),u=n.contentType||`application/sdp`;for(let e in l)Object.prototype.hasOwnProperty.call(l,e)&&this.on(e,l[e]);c.push(`Content-Type: ${u}`),this._request=new a.OutgoingRequest(i.OPTIONS,e,this._ua,null,c),t&&(this._request.body=t);let d=new s(this._ua,this._request,{onRequestTimeout:()=>{this._onRequestTimeout()},onTransportError:()=>{this._onTransportError()},onReceiveResponse:e=>{this._receiveResponse(e)}});this._newOptions(`local`,this._request),d.send()}init_incoming(e){this._request=e,this._newOptions(`remote`,e),this._is_replied||(this._is_replied=!0,e.reply(200)),this._close()}accept(e={}){let t=o.cloneArray(e.extraHeaders),n=e.body;if(this._direction!==`incoming`)throw new c.NotSupportedError(`"accept" not supported for outgoing Options`);if(this._is_replied)throw Error(`incoming Options already replied`);this._is_replied=!0,this._request.reply(200,null,t,n)}reject(e={}){let t=e.status_code||480,n=e.reason_phrase,r=o.cloneArray(e.extraHeaders),i=e.body;if(this._direction!==`incoming`)throw new c.NotSupportedError(`"reject" not supported for outgoing Options`);if(this._is_replied)throw Error(`incoming Options already replied`);if(t<300||t>=700)throw TypeError(`Invalid status_code: ${t}`);this._is_replied=!0,this._request.reply(t,n,r,i)}_receiveResponse(e){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(e.status_code):break;case/^2[0-9]{2}$/.test(e.status_code):this._succeeded(`remote`,e);break;default:{let t=o.sipErrorCause(e.status_code);this._failed(`remote`,e,t);break}}}_onRequestTimeout(){this._closed||this._failed(`system`,null,i.causes.REQUEST_TIMEOUT)}_onTransportError(){this._closed||this._failed(`system`,null,i.causes.CONNECTION_ERROR)}_close(){this._closed=!0,this._ua.destroyMessage(this)}_newOptions(e,t){e===`remote`?(this._direction=`incoming`,this._local_identity=t.to,this._remote_identity=t.from):e===`local`&&(this._direction=`outgoing`,this._local_identity=t.from,this._remote_identity=t.to),this._ua.newOptions(this,{originator:e,message:this,request:t})}_failed(e,t,n){l.debug(`OPTIONS failed`),this._close(),l.debug(`emit "failed"`),this.emit(`failed`,{originator:e,response:t||null,cause:n})}_succeeded(e,t){l.debug(`OPTIONS succeeded`),this._close(),l.debug(`emit "succeeded"`),this.emit(`succeeded`,{originator:e,response:t})}}})),ln=c((e=>{var t=J(),n=K(),r=W(),i=new t(`Socket`);e.isSocket=e=>{if(Array.isArray(e))return!1;if(e===void 0)return i.warn(`undefined JsSIP.Socket instance`),!1;try{if(!n.isString(e.url))throw i.warn(`missing or invalid JsSIP.Socket url property`),Error(`Missing or invalid JsSIP.Socket url property`);if(!n.isString(e.via_transport))throw i.warn(`missing or invalid JsSIP.Socket via_transport property`),Error(`Missing or invalid JsSIP.Socket via_transport property`);if(r.parse(e.sip_uri,`SIP_URI`)===-1)throw i.warn(`missing or invalid JsSIP.Socket sip_uri property`),Error(`missing or invalid JsSIP.Socket sip_uri property`)}catch{return!1}try{[`connect`,`disconnect`,`send`].forEach(t=>{if(!n.isFunction(e[t]))throw i.warn(`missing or invalid JsSIP.Socket method: ${t}`),Error(`Missing or invalid JsSIP.Socket method: ${t}`)})}catch{return!1}return!0}})),un=c(((e,t)=>{var n=J(),r=ln(),i=H(),a=new n(`Transport`),o={STATUS_CONNECTED:0,STATUS_CONNECTING:1,STATUS_DISCONNECTED:2,SOCKET_STATUS_READY:0,SOCKET_STATUS_ERROR:1,recovery_options:{min_interval:i.CONNECTION_RECOVERY_MIN_INTERVAL,max_interval:i.CONNECTION_RECOVERY_MAX_INTERVAL}};t.exports=class{constructor(e,t=o.recovery_options){a.debug(`new()`),this.status=o.STATUS_DISCONNECTED,this.socket=null,this.sockets=[],this.recovery_options=t,this.recover_attempts=0,this.recovery_timer=null,this.close_requested=!1;try{this.textDecoder=new TextDecoder(`utf8`)}catch(e){a.warn(`cannot use TextDecoder: ${e}`)}if(e===void 0)throw TypeError(`Invalid argument. undefined 'sockets' argument`);e instanceof Array||(e=[e]),e.forEach(function(e){if(!r.isSocket(e.socket))throw TypeError(`Invalid argument. invalid 'JsSIP.Socket' instance`);if(e.weight&&!Number(e.weight))throw TypeError(`Invalid argument. 'weight' attribute is not a number`);this.sockets.push({socket:e.socket,weight:e.weight||0,status:o.SOCKET_STATUS_READY})},this),this._getSocket()}get via_transport(){return this.socket.via_transport}get url(){return this.socket.url}get sip_uri(){return this.socket.sip_uri}connect(){if(a.debug(`connect()`),this.isConnected()){a.debug(`Transport is already connected`);return}if(this.isConnecting()){a.debug(`Transport is connecting`);return}this.close_requested=!1,this.status=o.STATUS_CONNECTING,this.onconnecting({socket:this.socket,attempts:this.recover_attempts}),this.close_requested||(this.socket.onconnect=this._onConnect.bind(this),this.socket.ondisconnect=this._onDisconnect.bind(this),this.socket.ondata=this._onData.bind(this),this.socket.connect())}disconnect(){a.debug(`close()`),this.close_requested=!0,this.recover_attempts=0,this.status=o.STATUS_DISCONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.socket.onconnect=()=>{},this.socket.ondisconnect=()=>{},this.socket.ondata=()=>{},this.socket.disconnect(),this.ondisconnect({socket:this.socket,error:!1})}send(e){if(a.debug(`send()`),!this.isConnected())return a.warn(`unable to send message, transport is not connected`),!1;let t=e.toString();return a.debug(`sending message:\n\n${t}\n`),this.socket.send(t)}isConnected(){return this.status===o.STATUS_CONNECTED}isConnecting(){return this.status===o.STATUS_CONNECTING}_reconnect(){this.recover_attempts+=1;let e=Math.floor(Math.random()*2**this.recover_attempts+1);e<this.recovery_options.min_interval?e=this.recovery_options.min_interval:e>this.recovery_options.max_interval&&(e=this.recovery_options.max_interval),a.debug(`reconnection attempt: ${this.recover_attempts}. next connection attempt in ${e} seconds`),this.recovery_timer=setTimeout(()=>{!this.close_requested&&!(this.isConnected()||this.isConnecting())&&(this._getSocket(),this.connect())},e*1e3)}_getSocket(){let e=[];if(this.sockets.forEach(t=>{t.status!==o.SOCKET_STATUS_ERROR&&(e.length===0?e.push(t):t.weight>e[0].weight?e=[t]:t.weight===e[0].weight&&e.push(t))}),e.length===0){this.sockets.forEach(e=>{e.status=o.SOCKET_STATUS_READY}),this._getSocket();return}let t=Math.floor(Math.random()*e.length);this.socket=e[t].socket}_onConnect(){this.recover_attempts=0,this.status=o.STATUS_CONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.onconnect({socket:this})}_onDisconnect(e,t,n){this.status=o.STATUS_DISCONNECTED,this.ondisconnect({socket:this.socket,error:e,code:t,reason:n}),!this.close_requested&&(this.sockets.forEach(function(e){this.socket===e.socket&&(e.status=o.SOCKET_STATUS_ERROR)},this),this._reconnect(e))}_onData(e){if(e===`\r
|
|
16
16
|
\r
|
|
17
17
|
`){a.debug(`received message with double-CRLF Keep Alive request`);try{this.socket.send(`\r
|
|
18
18
|
`)}catch(e){a.warn(`error sending Keep Alive response: ${e}`)}return}if(e===`\r
|
|
19
|
-
`){a.debug(`received message with CRLF Keep Alive response`);return}if(typeof e!=`string`){try{e=this.textDecoder?this.textDecoder.decode(e):String.fromCharCode.apply(null,new Uint8Array(e))}catch(e){a.debug(`received binary message failed to be converted into string: ${e}`);return}a.debug(`received binary message:\n\n${e}\n`)}else a.debug(`received text message:\n\n${e}\n`);this.ondata({transport:this,message:e})}}})),
|
|
19
|
+
`){a.debug(`received message with CRLF Keep Alive response`);return}if(typeof e!=`string`){try{e=this.textDecoder?this.textDecoder.decode(e):String.fromCharCode.apply(null,new Uint8Array(e))}catch(e){a.debug(`received binary message failed to be converted into string: ${e}`);return}a.debug(`received binary message:\n\n${e}\n`)}else a.debug(`received text message:\n\n${e}\n`);this.ondata({transport:this,message:e})}}})),dn=c((e=>{var t=J(),n=W(),r=Y(),i=new t(`Parser`);e.parseMessage=(e,t)=>{let s,c,l=e.indexOf(`\r
|
|
20
20
|
`);if(l===-1){i.warn(`parseMessage() | no CRLF found, not a SIP message`);return}let u=e.substring(0,l),d=n.parse(u,`Request_Response`);if(d===-1){i.warn(`parseMessage() | error parsing first line of SIP message: "${u}"`);return}d.status_code?(s=new r.IncomingResponse,s.status_code=d.status_code,s.reason_phrase=d.reason_phrase):(s=new r.IncomingRequest(t),s.method=d.method,s.ruri=d.uri),s.data=e;let f=l+2;for(;;){if(l=a(e,f),l===-2){c=f+2;break}if(l===-1){i.warn(`parseMessage() | malformed message`);return}if(d=o(s,e,f,l),d!==!0){i.warn(`parseMessage() |`,d.error);return}f=l+2}if(s.hasHeader(`content-length`)){let t=s.getHeader(`content-length`);s.body=e.substr(c,t)}else s.body=e.substring(c);return s};function a(e,t){let n=t,r=0,i=0;if(e.substring(n,n+2).match(/(^\r\n)/))return-2;for(;r===0;){if(i=e.indexOf(`\r
|
|
21
|
-
`,n),i===-1)return i;!e.substring(i+2,i+4).match(/(^\r\n)/)&&e.charAt(i+2).match(/(^\s+)/)?n=i+2:r=i}return r}function o(e,t,i,a){let o,s=t.indexOf(`:`,i),c=t.substring(i,s).trim(),l=t.substring(s+1,a).trim();switch(c.toLowerCase()){case`via`:case`v`:e.addHeader(`via`,l),e.getHeaders(`via`).length===1?(o=e.parseHeader(`Via`),o&&(e.via=o,e.via_branch=o.branch)):o=0;break;case`from`:case`f`:e.setHeader(`from`,l),o=e.parseHeader(`from`),o&&(e.from=o,e.from_tag=o.getParam(`tag`));break;case`to`:case`t`:e.setHeader(`to`,l),o=e.parseHeader(`to`),o&&(e.to=o,e.to_tag=o.getParam(`tag`));break;case`record-route`:if(o=n.parse(l,`Record_Route`),o===-1)o=void 0;else for(let t of o)e.addHeader(`record-route`,l.substring(t.possition,t.offset)),e.headers[`Record-Route`][e.getHeaders(`record-route`).length-1].parsed=t.parsed;break;case`call-id`:case`i`:e.setHeader(`call-id`,l),o=e.parseHeader(`call-id`),o&&(e.call_id=l);break;case`contact`:case`m`:if(o=n.parse(l,`Contact`),o===-1)o=void 0;else for(let t of o)e.addHeader(`contact`,l.substring(t.possition,t.offset)),e.headers.Contact[e.getHeaders(`contact`).length-1].parsed=t.parsed;break;case`content-length`:case`l`:e.setHeader(`content-length`,l),o=e.parseHeader(`content-length`);break;case`content-type`:case`c`:e.setHeader(`content-type`,l),o=e.parseHeader(`content-type`);break;case`cseq`:e.setHeader(`cseq`,l),o=e.parseHeader(`cseq`),o&&(e.cseq=o.value),e instanceof r.IncomingResponse&&(e.method=o.method);break;case`max-forwards`:e.setHeader(`max-forwards`,l),o=e.parseHeader(`max-forwards`);break;case`www-authenticate`:e.setHeader(`www-authenticate`,l),o=e.parseHeader(`www-authenticate`);break;case`proxy-authenticate`:e.setHeader(`proxy-authenticate`,l),o=e.parseHeader(`proxy-authenticate`);break;case`session-expires`:case`x`:e.setHeader(`session-expires`,l),o=e.parseHeader(`session-expires`),o&&(e.session_expires=o.expires,e.session_expires_refresher=o.refresher);break;case`refer-to`:case`r`:e.setHeader(`refer-to`,l),o=e.parseHeader(`refer-to`),o&&(e.refer_to=o);break;case`replaces`:e.setHeader(`replaces`,l),o=e.parseHeader(`replaces`),o&&(e.replaces=o);break;case`event`:case`o`:e.setHeader(`event`,l),o=e.parseHeader(`event`),o&&(e.event=o);break;default:e.addHeader(c,l),o=0}return o!==void 0||{error:`error parsing header "${c}"`}}})),
|
|
22
|
-
`,f.send(i)}})),fn=c((e=>{var t=G(),n=V(),r=U(),i=W(),a=cn(),o=H();e.settings={authorization_user:null,password:null,realm:null,ha1:null,authorization_jwt:null,display_name:null,uri:null,contact_uri:null,instance_id:null,use_preloaded_route:!1,session_timers:!0,session_timers_refresh_method:n.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,register_from_tag_trail:``,registrar_server:null,sockets:null,connection_recovery_max_interval:n.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:n.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:`${t.createRandomToken(12)}.invalid`};var s={mandatory:{sockets(e){let t=[];if(a.isSocket(e))t.push({socket:e});else if(Array.isArray(e)&&e.length)for(let n of e)Object.prototype.hasOwnProperty.call(n,`socket`)&&a.isSocket(n.socket)?t.push(n):a.isSocket(n)&&t.push({socket:n});else return;return t},uri(e){/^sip:/i.test(e)||(e=`${n.SIP}:${e}`);let t=i.parse(e);if(t&&t.user)return t}},optional:{authorization_user(e){if(r.parse(`"${e}"`,`quoted_string`)!==-1)return e},authorization_jwt(e){if(typeof e==`string`)return e},user_agent(e){if(typeof e==`string`)return e},connection_recovery_max_interval(e){if(t.isDecimal(e)){let t=Number(e);if(t>0)return t}},connection_recovery_min_interval(e){if(t.isDecimal(e)){let t=Number(e);if(t>0)return t}},contact_uri(e){if(typeof e==`string`){let t=r.parse(e,`SIP_URI`);if(t!==-1)return t}},display_name(e){return e},instance_id(e){if(/^uuid:/i.test(e)&&(e=e.substr(5)),r.parse(e,`uuid`)!==-1)return e},no_answer_timeout(e){if(t.isDecimal(e)){let t=Number(e);if(t>0)return t}},session_timers(e){if(typeof e==`boolean`)return e},session_timers_refresh_method(e){if(typeof e==`string`&&(e=e.toUpperCase(),e===n.INVITE||e===n.UPDATE))return e},session_timers_force_refresher(e){if(typeof e==`boolean`)return e},password(e){return String(e)},realm(e){return String(e)},ha1(e){return String(e)},register(e){if(typeof e==`boolean`)return e},register_expires(e){if(t.isDecimal(e)){let t=Number(e);if(t>=0)return t}},register_from_tag_trail(e){return typeof e==`function`?e:String(e)},registrar_server(e){/^sip:/i.test(e)||(e=`${n.SIP}:${e}`);let t=i.parse(e);if(t&&!t.user)return t},use_preloaded_route(e){if(typeof e==`boolean`)return e},extra_headers(e){let t=[];if(Array.isArray(e)&&e.length)for(let n of e)typeof n==`string`&&t.push(n);else return;return t}}};e.load=(e,n)=>{for(let t in s.mandatory)if(n.hasOwnProperty(t)){let r=n[t],i=s.mandatory[t](r);if(i!==void 0)e[t]=i;else throw new o.ConfigurationError(t,r)}else throw new o.ConfigurationError(t);for(let r in s.optional)if(n.hasOwnProperty(r)){let i=n[r];if(t.isEmpty(i))continue;let a=s.optional[r](i);if(a!==void 0)e[r]=a;else throw new o.ConfigurationError(r,i)}}})),pn=c(((e,t)=>{var n=K().EventEmitter,r=q(),i=V(),a=Yt(),o=nn(),s=rn(),c=an(),l=on(),u=sn(),d=Y(),f=ln(),p=G(),m=H(),h=W(),g=un(),_=J(),v=dn(),y=fn(),b=new r(`UA`),x={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2};t.exports=class extends n{static get C(){return x}constructor(e){if(!e)throw TypeError(`Not enough arguments`);let t=[`password`,`ha1`,`authorization_jwt`];b.debug(`new() [configuration:%o]`,Object.entries(e).filter(([e])=>!t.includes(e))),super(),this._cache={credentials:{}},this._configuration=Object.assign({},y.settings),this._dynConfiguration={},this._dialogs={},this._applicants={},this._sessions={},this._transport=null,this._contact=null,this._status=x.STATUS_INIT,this._error=null,this._transactions={nist:{},nict:{},ist:{},ict:{}},this._data={},this._closeTimer=null;try{this._loadConfig(e)}catch(e){throw this._status=x.STATUS_NOT_READY,this._error=x.CONFIGURATION_ERROR,e}this._registrator=new a(this)}get C(){return x}get status(){return this._status}get contact(){return this._contact}get configuration(){return this._configuration}get transport(){return this._transport}start(){b.debug(`start()`),this._status===x.STATUS_INIT?this._transport.connect():this._status===x.STATUS_USER_CLOSED?(b.debug(`restarting UA`),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=x.STATUS_INIT,this._transport.connect()):this._status===x.STATUS_READY?b.debug(`UA is in READY status, not restarted`):b.debug(`ERROR: connection is down, Auto-Recovery system is trying to reconnect`),this._dynConfiguration.register=this._configuration.register}register(){b.debug(`register()`),this._dynConfiguration.register=!0,this._registrator.register()}unregister(e){b.debug(`unregister()`),this._dynConfiguration.register=!1,this._registrator.unregister(e)}registrator(){return this._registrator}isRegistered(){return this._registrator.registered}isConnected(){return this._transport.isConnected()}call(e,t){b.debug(`call()`);let n=new o(this);return n.connect(e,t),n}sendMessage(e,t,n){b.debug(`sendMessage()`);let r=new l(this);return r.send(e,t,n),r}subscribe(e,t,n,r){return b.debug(`subscribe()`),new s(this,e,t,n,r)}notify(e,t,n){return b.debug(`notify()`),new c(this,e,t,n)}sendOptions(e,t,n){b.debug(`sendOptions()`);let r=new u(this);return r.send(e,t,n),r}terminateSessions(e){b.debug(`terminateSessions()`);for(let t in this._sessions)this._sessions[t].isEnded()||this._sessions[t].terminate(e)}stop(){if(b.debug(`stop()`),this._dynConfiguration={},this._status===x.STATUS_USER_CLOSED){b.debug(`UA already closed`);return}this._registrator.close();let e=Object.keys(this._sessions).length;for(let e in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,e)){b.debug(`closing session ${e}`);try{this._sessions[e].terminate()}catch{}}for(let e in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,e))try{this._applicants[e].close()}catch{}this._status=x.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&e===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}normalizeTarget(e){return p.normalizeTarget(e,this._configuration.hostport_params)}get(e){switch(e){case`authorization_user`:return this._configuration.authorization_user;case`realm`:return this._configuration.realm;case`ha1`:return this._configuration.ha1;case`authorization_jwt`:return this._configuration.authorization_jwt;default:b.warn(`get() | cannot get "%s" parameter in runtime`,e);return}}set(e,t){switch(e){case`authorization_user`:this._configuration.authorization_user=String(t);break;case`password`:this._configuration.password=String(t);break;case`realm`:this._configuration.realm=String(t);break;case`ha1`:this._configuration.ha1=String(t),this._configuration.password=null;break;case`authorization_jwt`:this._configuration.authorization_jwt=String(t);break;case`display_name`:this._configuration.display_name=t;break;case`extra_headers`:this._configuration.extra_headers=t;break;default:return b.warn(`set() | cannot set "%s" parameter in runtime`,e),!1}return!0}newTransaction(e){this._transactions[e.type][e.id]=e,this.emit(`newTransaction`,{transaction:e})}destroyTransaction(e){delete this._transactions[e.type][e.id],this.emit(`transactionDestroyed`,{transaction:e})}newDialog(e){this._dialogs[e.id]=e}destroyDialog(e){delete this._dialogs[e.id]}newMessage(e,t){this._applicants[e]=e,this.emit(`newMessage`,t)}newOptions(e,t){this._applicants[e]=e,this.emit(`newOptions`,t)}destroyMessage(e){delete this._applicants[e]}newRTCSession(e,t){this._sessions[e.id]=e,this.emit(`newRTCSession`,t)}destroyRTCSession(e){delete this._sessions[e.id]}registered(e){this.emit(`registered`,e)}unregistered(e){this.emit(`unregistered`,e)}registrationFailed(e){this.emit(`registrationFailed`,e)}receiveRequest(e){let t=e.method;if(e.ruri.user!==this._configuration.uri.user&&e.ruri.user!==this._contact.uri.user){b.debug(`Request-URI does not point to us`),e.method!==i.ACK&&e.reply_sl(404);return}if(e.ruri.scheme===i.SIPS){e.reply_sl(416);return}if(d.checkTransaction(this,e))return;if(t===i.INVITE?new d.InviteServerTransaction(this,this._transport,e):t!==i.ACK&&t!==i.CANCEL&&new d.NonInviteServerTransaction(this,this._transport,e),t===i.OPTIONS){if(this.listeners(`newOptions`).length===0){e.reply(200);return}new u(this).init_incoming(e)}else if(t===i.MESSAGE){if(this.listeners(`newMessage`).length===0){e.reply(405);return}new l(this).init_incoming(e)}else if(t===i.SUBSCRIBE){if(this.listeners(`newSubscribe`).length===0){e.reply(405);return}}else if(t===i.INVITE&&!e.to_tag&&this.listeners(`newRTCSession`).length===0){e.reply(405);return}let n,r;if(e.to_tag)n=this._findDialog(e.call_id,e.from_tag,e.to_tag),n?n.receiveRequest(e):t===i.NOTIFY?(r=this._findSession(e),r?r.receiveRequest(e):(b.debug(`received NOTIFY request for a non existent subscription`),e.reply(481,`Subscription does not exist`))):t!==i.ACK&&e.reply(481);else switch(t){case i.INVITE:if(window.RTCPeerConnection){if(e.hasHeader(`replaces`)){let t=e.replaces;n=this._findDialog(t.call_id,t.from_tag,t.to_tag),n?(r=n.owner,r.isEnded()?e.reply(603):r.receiveRequest(e)):e.reply(481)}else r=new o(this),r.init_incoming(e)}else b.warn(`INVITE received but WebRTC is not supported`),e.reply(488);break;case i.BYE:e.reply(481);break;case i.CANCEL:r=this._findSession(e),r?r.receiveRequest(e):b.debug(`received CANCEL request for a non existent session`);break;case i.ACK:break;case i.NOTIFY:this.emit(`sipEvent`,{event:e.event,request:e}),e.reply(200);break;case i.SUBSCRIBE:c.init_incoming(e,()=>{this.emit(`newSubscribe`,{event:e.event,request:e})});break;default:e.reply(405)}}_findSession({call_id:e,from_tag:t,to_tag:n}){let r=e+t,i=this._sessions[r],a=e+n,o=this._sessions[a];return i||o||null}_findDialog(e,t,n){let r=e+t+n,i=this._dialogs[r];return i||(r=e+n+t,i=this._dialogs[r],i||null)}_loadConfig(e){y.load(this._configuration,e),this._configuration.display_name===0&&(this._configuration.display_name=`0`),this._configuration.instance_id||(this._configuration.instance_id=p.newUUID()),this._configuration.jssip_id=p.createRandomToken(5);let t=this._configuration.uri.clone();t.user=null,this._configuration.hostport_params=t.toString().replace(/^sip:/i,``);try{this._transport=new f(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=S.bind(this),this._transport.onconnect=C.bind(this),this._transport.ondisconnect=w.bind(this),this._transport.ondata=ee.bind(this)}catch(e){throw b.warn(e),new m.ConfigurationError(`sockets`,this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){let e=this._configuration.uri.clone();e.user=null,e.clearParams(),e.clearHeaders(),this._configuration.registrar_server=e}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new h(`sip`,p.createRandomToken(8),this._configuration.via_host,null,{transport:`ws`}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(e={}){let t=e.anonymous||null,n=e.outbound||null,r=`<`;return r+=t?this.temp_gruu||`sip:anonymous@anonymous.invalid;transport=ws`:this.pub_gruu||this.uri.toString(),n&&(t?!this.temp_gruu:!this.pub_gruu)&&(r+=`;ob`),r+=`>`,r}};let n=[`authorization_user`,`password`,`realm`,`ha1`,`authorization_jwt`,`display_name`,`register`,`extra_headers`];for(let e in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,e)&&(n.indexOf(e)===-1?Object.defineProperty(this._configuration,e,{writable:!1,configurable:!1}):Object.defineProperty(this._configuration,e,{writable:!0,configurable:!1}));b.debug(`configuration parameters after validation:`);for(let e in this._configuration)if(Object.prototype.hasOwnProperty.call(y.settings,e))switch(e){case`uri`:case`registrar_server`:b.debug(`- ${e}: ${this._configuration[e]}`);break;case`password`:case`ha1`:case`authorization_jwt`:b.debug(`- ${e}: NOT SHOWN`);break;default:b.debug(`- ${e}: ${JSON.stringify(this._configuration[e])}`)}}};function S(e){this.emit(`connecting`,e)}function C(e){this._status!==x.STATUS_USER_CLOSED&&(this._status=x.STATUS_READY,this._error=null,this.emit(`connected`,e),this._dynConfiguration.register&&this._registrator.register())}function w(e){for(let e of[`nict`,`ict`,`nist`,`ist`])for(let t in this._transactions[e])Object.prototype.hasOwnProperty.call(this._transactions[e],t)&&this._transactions[e][t].onTransportError();this.emit(`disconnected`,e),this._registrator.onTransportClosed(),this._status!==x.STATUS_USER_CLOSED&&(this._status=x.STATUS_NOT_READY,this._error=x.NETWORK_ERROR)}function ee(e){let t=e.transport,n=e.message;if(n=g.parseMessage(n,this),n&&!(this._status===x.STATUS_USER_CLOSED&&n instanceof _.IncomingRequest)&&v(n,this,t)){if(n instanceof _.IncomingRequest)n.transport=t,this.receiveRequest(n);else if(n instanceof _.IncomingResponse){let e;switch(n.method){case i.INVITE:e=this._transactions.ict[n.via_branch],e&&e.receiveResponse(n);break;case i.ACK:break;default:e=this._transactions.nict[n.via_branch],e&&e.receiveResponse(n)}}}}})),mn=c(((e,t)=>{var n=q(),r=U(),i=new n(`WebSocketInterface`);t.exports=class{constructor(e){i.debug(`new() [url:"%s"]`,e),this._url=e,this._sip_uri=null,this._via_transport=null,this._ws=null;let t=r.parse(e,`absoluteURI`);if(t===-1)throw i.warn(`invalid WebSocket URI: ${e}`),TypeError(`Invalid argument: ${e}`);if(t.scheme!==`wss`&&t.scheme!==`ws`)throw i.warn(`invalid WebSocket URI scheme: ${t.scheme}`),TypeError(`Invalid argument: ${e}`);this._sip_uri=`sip:${t.host}${t.port?`:${t.port}`:``};transport=ws`,this._via_transport=t.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(e){this._via_transport=e.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(i.debug(`connect()`),this.isConnected()){i.debug(`WebSocket ${this._url} is already connected`);return}if(this.isConnecting()){i.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),i.debug(`connecting to WebSocket ${this._url}`);try{this._ws=new WebSocket(this._url,`sip`),this._ws.binaryType=`arraybuffer`,this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(e){this._onError(e)}}disconnect(){i.debug(`disconnect()`),this._ws&&=(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),null)}send(e){return i.debug(`send()`),this.isConnected()?(this._ws.send(e),!0):(i.warn(`unable to send message, WebSocket is not open`),!1)}isConnected(){return this._ws&&this._ws.readyState===this._ws.OPEN}isConnecting(){return this._ws&&this._ws.readyState===this._ws.CONNECTING}_onOpen(){i.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:e,code:t,reason:n}){i.debug(`WebSocket ${this._url} closed`),e===!1&&i.debug(`WebSocket abrupt disconnection`),this.ondisconnect(!e,t,n)}_onMessage({data:e}){i.debug(`received WebSocket message`),this.ondata(e)}_onError(e){i.warn(`WebSocket ${this._url} error: `,e)}}})),hn=c(((e,t)=>{var n=(Rt(),f(St).default),r=V(),i=H(),a=G(),o=pn(),s=W(),c=zt(),l=U(),u=mn(),d=Ht()(`JsSIP`),p=nn();d(`version %s`,n.version),t.exports={C:r,Exceptions:i,Utils:a,UA:o,URI:s,NameAddrHeader:c,WebSocketInterface:u,Grammar:l,RTCSession:p,debug:Ht(),get name(){return n.title},get version(){return n.version}}})),gn=l({createJsSipFactory:()=>_n});function _n(){return{createSocket:(e,t)=>new yn(e,t),createUa:e=>new vn.UA(e)}}var vn,yn,bn=s((()=>{vn=d(hn(),1),yn=class extends vn.WebSocketInterface{ticket;constructor(e,t){super(e),this.ticket=t}protocols(){return this.ticket===``?[`sip`]:[`xcall-ticket.${this.ticket}`,`sip`]}connect(){if(this.isConnected()||this.isConnecting())return;let e=this;e._ws&&this.disconnect();try{e._ws=new WebSocket(this.url,this.protocols()),e._ws.binaryType=`arraybuffer`,e._ws.onopen=e._onOpen.bind(this),e._ws.onclose=e._onClose.bind(this),e._ws.onmessage=e._onMessage.bind(this),e._ws.onerror=e._onError.bind(this)}catch(t){e._onError.call(this,t)}}}}));function xn(e){let t=new Map;return{peerConnection:{getSenders:()=>e.getSenders().map(n=>{let r=t.get(n);if(r!==void 0)return r;let i={get track(){return n.track},get senderKind(){let t=n.track;if(t!==null)return t.kind===`audio`||t.kind===`video`?t.kind:void 0;let r=e.getTransceivers().find(e=>e.sender===n)?.receiver.track;if(r?.kind===`audio`||r?.kind===`video`)return r.kind;let i=n.getParameters().codecs?.find(e=>typeof e.mimeType==`string`);if(i?.mimeType?.toLowerCase().startsWith(`video/`))return`video`;if(i?.mimeType?.toLowerCase().startsWith(`audio/`))return`audio`},replaceTrack:e=>n.replaceTrack(e)};return t.set(n,i),i}),close:()=>{e.connectionState!==`closed`&&e.close()}},trackSource:{onTrack(t){let n=e=>{let n=e.track;t({streams:[...e.streams],track:n})};return e.addEventListener(`track`,n),()=>e.removeEventListener(`track`,n)}}}}var Sn=s((()=>{}));function Cn(){return{runs:0,lastMs:null,udpOk:!1,tcpRelayOk:!1,convergedServers:null,unchanged:null,status:`idle`,lastProbeAt:null,cacheAgeMs:null,unknownCount:0,unavailableCount:0,dialMode:`original`}}function wn(e){if(!e)return``;let t=String(e.type??``);return t===``?/ typ (\w+)/.exec(String(e.candidate??``))?.[1]??``:t}function Tn(e){return/^turns:/i.test(e)?`tls`:/transport=tcp/i.test(e)?`tcp`:`udp`}function En(e,t){let n=t.flatMap(e=>(Array.isArray(e.urls)?e.urls:[e.urls]).map(t=>[String(t),e])),r=new Map(n),i=[];for(let t of e){let e=Array.isArray(t.urls)?t.urls:[t.urls];for(let t of e){let e=r.get(String(t));e&&i.push({...e,urls:[t]})}}return i}function Dn(e,t={}){let n=Number.isFinite(t.timeoutMs)&&t.timeoutMs>0?t.timeoutMs:kn;if(!Array.isArray(e))return Promise.resolve([]);let r=[];for(let t of e){if(!t)continue;let e=Array.isArray(t.urls)?t.urls:[t.urls];for(let n of e){let e=String(n??``).trim();/^(stun|turn|turns):/i.test(e)&&r.push({url:e,entry:t})}}return Promise.all(r.map(e=>new Promise(t=>{let r=!1,i=!1,a,o=Tn(e.url),s=(n,i)=>{if(!r){r=!0,clearTimeout(c);try{a?.close()}catch{}t({url:e.url,status:n,transport:o,reason:i})}},c=setTimeout(()=>s(i?`unavailable`:`unknown`,i?`server-error`:`timeout`),n);try{if(typeof RTCPeerConnection>`u`){s(`unknown`,`local-error`);return}let t={urls:[e.url]};e.entry.username&&(t.username=e.entry.username),e.entry.credential&&(t.credential=e.entry.credential),a=new RTCPeerConnection({iceServers:[t]}),a.createDataChannel(`webphone-ice-probe`),a.onicecandidate=e=>{if(!e||!e.candidate)return;let t=wn(e.candidate);(t===`srflx`||t===`relay`)&&s(`available`,`candidate`)},a.onicecandidateerror=t=>{t?.url&&t.url===e.url&&(i=!0)},a.createOffer().then(e=>a?.setLocalDescription(e)).catch(()=>s(`unknown`,`local-error`))}catch{s(`unknown`,`local-error`)}})))}function On(e,t){let n=new Map;for(let e of t)e&&e.url&&n.set(String(e.url),e.status===`available`);let r=[];for(let t of e??[]){if(!t)continue;let e=(Array.isArray(t.urls)?t.urls:[t.urls]).filter(Boolean).filter(e=>n.get(String(e))===!0);if(e.length===0)continue;let i={...t,urls:e};r.push(i)}return r}var kn,Z,An,jn=s((()=>{kn=2e3,Z=[5e3,15e3,6e4],An=class{availableList;lastGoodList;lastGoodAt;lastResults=[];snapshotState=Cn();running=!1;seq=0;consecutiveFailures=0;lastAttemptAt;retryTimer;pendingRequest;serversForDial(e,t=Date.now()){if(!e)return;if(!this.lastResults.length)return this.setDialMode(`original`),e;let n=this.lastGoodAt===void 0?null:Math.max(0,t-this.lastGoodAt);this.snapshotState={...this.snapshotState,cacheAgeMs:n};let r=n!==null&&n>3e5,i=this.snapshotState.lastProbeAt===null?null:Math.max(0,t-this.snapshotState.lastProbeAt);if(r||i!==null&&i>3e5)return this.snapshotState={...this.snapshotState,status:`stale`,cacheAgeMs:n??i},this.assess(e,`ttl-expired`),this.availableList&&this.availableList.length>0?(this.setDialMode(`original`),e):(this.setDialMode(`host-only`),[]);if(!r&&this.availableList&&this.availableList.length>0)return this.setDialMode(`known-available`),this.availableList.map(e=>({...e,urls:Array.isArray(e.urls)?[...e.urls]:e.urls}));if(this.lastGoodList&&n!==null&&n<=3e5){let t=En(this.lastGoodList,e);if(t.length>0)return this.setDialMode(`last-known-good`),t}return this.setDialMode(`host-only`),[]}snapshot(){return this.snapshotState}reset(){this.retryTimer!==void 0&&clearTimeout(this.retryTimer),this.retryTimer=void 0,this.pendingRequest=void 0,this.seq++,this.running=!1,this.availableList=void 0,this.lastGoodList=void 0,this.lastGoodAt=void 0,this.lastResults=[],this.consecutiveFailures=0,this.lastAttemptAt=void 0,this.snapshotState=Cn()}cancelInFlight(){this.seq++,this.running=!1,this.retryTimer!==void 0&&clearTimeout(this.retryTimer),this.retryTimer=void 0,this.pendingRequest=void 0}assess(e,t=`initial-registration`){if(e===void 0)return;if(e.length===0){this.reset();return}if(this.running){t!==`initial-registration`&&(this.pendingRequest={servers:e,trigger:t});return}let n=Date.now();if(t!==`initial-registration`&&this.consecutiveFailures>0&&this.lastAttemptAt!==void 0){let r=Z[Math.min(this.consecutiveFailures-1,Z.length-1)]-(n-this.lastAttemptAt);if(r>0){this.pendingRequest={servers:e,trigger:t},this.retryTimer===void 0&&(this.retryTimer=setTimeout(()=>{this.retryTimer=void 0;let e=this.pendingRequest;this.pendingRequest=void 0,e&&this.assess(e.servers,e.trigger)},r));return}}let r=e.map(e=>({...e,urls:Array.isArray(e.urls)?[...e.urls]:[e.urls]}));if(!r.some(e=>(Array.isArray(e.urls)?e.urls:[e.urls]).some(e=>/^(stun|turn|turns):/i.test(String(e??``)))))return;let i=++this.seq;this.running=!0,this.lastAttemptAt=n,this.availableList=void 0,this.snapshotState={...this.snapshotState,status:t===`ttl-expired`?`stale`:`probing`};let a=Date.now();Dn(r).then(e=>{if(i!==this.seq)return;this.lastResults=e;let t=r,n=On(t,e);this.availableList=n.length>0?n:void 0,this.availableList&&(this.lastGoodList=n.map(e=>({...e,urls:Array.isArray(e.urls)?[...e.urls]:e.urls})),this.lastGoodAt=Date.now());let o=e.filter(e=>e.status===`unknown`).length,s=e.filter(e=>e.status===`unavailable`).length;this.consecutiveFailures=n.length===0?this.consecutiveFailures+1:0,n.length===0&&this.consecutiveFailures<=Z.length&&this.pendingRequest===void 0&&(this.pendingRequest={servers:r,trigger:`retry-backoff`}),this.snapshotState={runs:this.snapshotState.runs+1,lastMs:Date.now()-a,udpOk:e.some(e=>e.status===`available`&&e.transport===`udp`),tcpRelayOk:e.some(e=>e.status===`available`&&(e.transport===`tcp`||e.transport===`tls`)),convergedServers:n.length,unchanged:JSON.stringify(n)===JSON.stringify(t),status:o+s>0?`degraded`:`healthy`,lastProbeAt:Date.now(),cacheAgeMs:0,unknownCount:o,unavailableCount:s,dialMode:n.length>0?`known-available`:`host-only`}}).catch(()=>{this.seq}).finally(()=>{if(i!==this.seq)return;this.running=!1;let e=this.pendingRequest;this.pendingRequest=void 0,e&&this.assess(e.servers,e.trigger)})}isRunning(){return this.running}setDialMode(e){let t=this.snapshotState.status;this.snapshotState={...this.snapshotState,dialMode:e,status:t===`healthy`&&e===`host-only`?`stale`:t}}}}));function Mn(e){if(!e)return``;let t=String(e.type??``);return t===``?/ typ (\w+)/.exec(String(e.candidate??``))?.[1]??``:t}function Nn(e,t={}){if(typeof e.on!=`function`)return()=>void 0;let n=Number.isFinite(t.timeoutMs)&&t.timeoutMs>0?t.timeoutMs:Pn,r=!1,i,a=()=>{if(!r){r=!0,clearTimeout(s);try{i?.()}catch{}}},o=e=>{let t=e;if(!t||typeof t.ready!=`function`)return;i=t.ready;let n=Mn(t.candidate);(n===`srflx`||n===`relay`)&&a()};e.on(`icecandidate`,o);let s=setTimeout(a,n);return()=>{clearTimeout(s);try{e.off?.(`icecandidate`,o)}catch{}}}var Pn,Fn=s((()=>{Pn=3e3})),In=l({JsSipAdapter:()=>Jn});function Ln(e){let t=Math.floor(Number(e.sip.registerExpires));return Number.isFinite(t)&&t>0?t:Un}function Rn(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.originator===`remote`&&zn(t.session)}function zn(e){return typeof e==`object`&&!!e&&`id`in e}function Bn(e){return typeof e==`object`&&e&&(e.via_transport=`WSS`),e}function Vn(e){let t=e.replace(/^\[|\]$/g,``).toLowerCase();return t===`localhost`||t===`127.0.0.1`||t===`::1`||t===`0:0:0:0:0:0:0:1`}function Hn(e){let t=e?.uri;if(t==null)return;if(typeof t.user==`string`&&t.user!==``)return t.user;let n=t.toString();return n.match(/^sips?:([^@;>]+)/i)?.[1]??(n===``?void 0:n)}var Un,Wn,Gn,Kn,qn,Jn,Yn,Xn=s((()=>{h(),Sn(),jn(),Fn(),Un=300,Wn=25,Gn=2,Kn=``,qn=120,Jn=class{factory;transportBaseUrl;keepaliveSeconds;agentTerminal;sessionTimers;ua;uaListeners;incomingHandlers;iceServers;pendingConnection;disposed=!1;warmPc;keepaliveTimer;keepaliveBusy=!1;registerExpiresSeconds=0;connectionHandlers=new Set;iceQuality=new An;constructor(e,t,n=Wn,r=Kn,i=!1){this.factory=e,this.transportBaseUrl=t,this.keepaliveSeconds=n,this.agentTerminal=r,this.sessionTimers=i}terminalHeaders(){return this.agentTerminal===``?[]:[`X-Agent-Terminal: ${this.agentTerminal}`]}warmIceCandidatePool(){if(this.closeWarmPc(),typeof RTCPeerConnection<`u`&&this.iceServers!==void 0)try{this.warmPc=new RTCPeerConnection({iceServers:[...this.iceServers],iceCandidatePoolSize:Gn})}catch{this.warmPc=void 0}}closeWarmPc(){try{this.warmPc?.close()}catch{}this.warmPc=void 0}keepaliveTick(e){if(this.isCurrentUa(e)&&!this.keepaliveBusy)try{if(typeof e.isConnected==`function`&&e.isConnected()===!1||typeof e.register!=`function`)return;this.keepaliveBusy=!0,e.register({extraHeaders:this.terminalHeaders()})}catch{}finally{this.keepaliveBusy=!1}}startKeepalive(e,t){if(this.stopKeepalive(),!Number.isFinite(this.keepaliveSeconds)||this.keepaliveSeconds<=0||t>0&&t<=this.keepaliveSeconds)return;let n=Math.max(10,Math.floor(this.keepaliveSeconds))*1e3;this.keepaliveTimer=setInterval(()=>this.keepaliveTick(e),n)}stopKeepalive(){this.keepaliveTimer!==void 0&&clearInterval(this.keepaliveTimer),this.keepaliveTimer=void 0}connect(e){this.assertNotDisposed();let t=this.iceQuality.snapshot().runs>0;this.disconnect(this.registrationError(`SIP connection replaced`),!t);try{let t=this.factory.createUa({sockets:Bn(this.factory.createSocket(this.withoutTicket(this.resolveWssUrl(e.transport.wssUrl)),e.transport.ticket)),uri:e.sip.uri,password:e.sip.registerTicket,registrar_server:e.sip.registrar,register:!0,register_expires:Ln(e),session_timers:this.sessionTimers,...this.agentTerminal===``?{}:{user_agent:this.agentTerminal}});return this.ua=t,this.registerExpiresSeconds=Ln(e),this.iceServers=e.iceServers,this.uaListeners=[],this.startRegistration(t)}catch(e){let t=e instanceof m&&e.code===`CONFIG_INVALID`?e:this.transportError(e);return this.disconnect(t),Promise.reject(t)}}disconnect(e=this.registrationError(`SIP connection disconnected`),t=!0){this.stopKeepalive(),this.closeWarmPc(),t?this.iceQuality.reset():this.iceQuality.cancelInFlight();let n=this.pendingConnection;this.pendingConnection=void 0,this.ua!==void 0&&(this.removeUaListeners(this.ua),this.ua.stop()),this.ua=void 0,this.uaListeners=void 0,this.iceServers=void 0,n?.reject(e)}dial(e,t){let n=this.requireUa();if(e.trim()===``)throw new m(`CALL_INVALID_DESTINATION`,`call`,!1);try{let r=t===void 0?{mediaConstraints:{audio:!0,video:!1},sessionTimersExpires:qn,pcConfig:{iceServers:this.dialIceServers(),iceCandidatePoolSize:Gn}}:{mediaConstraints:{audio:!0,video:!1},sessionTimersExpires:qn,pcConfig:{iceServers:[...t.iceServers],iceCandidatePoolSize:Gn},extraHeaders:[...this.terminalHeaders(),...t.extraHeaders,...t.type===`extension`?[`X-XCall-Destination-Type: extension`]:[]]};return this.createSessionHandle(n.call(e,r))}catch(e){throw new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{cause:e})}}onIncoming(e){this.assertNotDisposed();let t=this.incomingHandlers??new Set;return this.incomingHandlers=t,t.add(e),()=>t.delete(e)}onConnectionStateChanged(e){return this.disposed?()=>void 0:(this.connectionHandlers.add(e),()=>this.connectionHandlers.delete(e))}dispose(){this.disposed||(this.disposed=!0,this.disconnect(),this.incomingHandlers=void 0,this.connectionHandlers.clear())}dialIceServers(){return this.iceQuality.serversForDial(this.iceServers)}iceQualitySnapshot(){return this.iceQuality.snapshot()}reassessIceServers(e=`network-online`){this.iceQuality.assess(this.iceServers,e)}getResourceCounts(){return{listeners:(this.uaListeners?.length??0)+(this.incomingHandlers?.size??0)+this.connectionHandlers.size,webSockets:this.ua===void 0?0:1}}handleIncoming(e){if(!Rn(e))return;let t=e.session;if(t===void 0)return;let n=this.createSessionHandle(t);this.incomingHandlers?.forEach(e=>e(n))}createSessionHandle(e){return new Yn(e,()=>this.reassessIceServers(`ice-failed`))}startRegistration(e){let t=!0,n=!1,r=new Promise((t,n)=>{this.pendingConnection={ua:e,resolve:t,reject:n}});this.listen(e,`registered`,()=>{if(this.isCurrentUa(e)){if(t){n=!0;return}this.resolveConnection(e)}}),this.listen(e,`registrationFailed`,t=>{if(!this.isCurrentUa(e))return;let n=this.registrationError(this.registrationFailureCause(t));this.connectionHandlers.forEach(e=>e(`failed`,n)),this.disconnect(n)}),this.listen(e,`disconnected`,t=>{if(!this.isCurrentUa(e))return;let n=this.transportError(t);this.connectionHandlers.forEach(e=>e(`disconnected`,n)),this.disconnect(n,!1)}),this.listen(e,`newRTCSession`,t=>{this.isCurrentUa(e)&&this.handleIncoming(t)});try{e.start()}catch(e){let t=this.transportError(e);this.connectionHandlers.forEach(e=>e(`failed`,t)),this.disconnect(t)}finally{t=!1}return n&&this.resolveConnection(e),r}listen(e,t,n){e.on(t,n),this.uaListeners?.push({event:t,handler:n})}removeUaListeners(e){this.uaListeners?.forEach(({event:t,handler:n})=>e.off(t,n))}isCurrentUa(e){return this.ua===e}resolveConnection(e){let t=this.pendingConnection;if(t?.ua!==e)return;this.pendingConnection=void 0,t.resolve(),this.warmIceCandidatePool();let n=this.iceQuality.snapshot().runs>0?`sip-reconnected`:`initial-registration`;this.iceQuality.assess(this.iceServers,n),this.startKeepalive(e,this.registerExpiresSeconds),this.connectionHandlers.forEach(e=>e(`registered`))}resolveWssUrl(e){let t=this.transportBaseUrl?.trim()===``||this.transportBaseUrl===void 0?typeof location>`u`?`http://localhost`:location.origin:this.transportBaseUrl,n=e.startsWith(`/`)?new URL(e,t):new URL(e);return n.protocol===`http:`&&(n.protocol=`ws:`),n.protocol===`https:`&&(n.protocol=`wss:`),this.assertAllowedWssUrl(n),n.toString()}assertAllowedWssUrl(e){if(e.protocol!==`wss:`&&!(e.protocol===`ws:`&&Vn(e.hostname)))throw new m(`CONFIG_INVALID`,`configuration`,!1,{cause:e.origin})}withoutTicket(e){let t=new URL(e);return t.searchParams.delete(`ticket`),t.toString()}requireUa(){if(this.assertNotDisposed(),this.ua===void 0)throw new m(`CALL_NOT_CONNECTED`,`call`,!1);return this.ua}assertNotDisposed(){if(this.disposed)throw new m(`SDK_ALREADY_DISPOSED`,`internal`,!1)}registrationError(e){return new m(`REGISTRATION_FAILED`,`registration`,!0,{cause:e})}transportError(e){return new m(`SIP_WS_UNAVAILABLE`,`registration`,!0,{cause:e})}registrationFailureCause(e){return typeof e==`object`&&e&&`cause`in e?e.cause:e}},Yn=class{session;pendingHoldReject;mediaRegistration;mediaConnection;mediaHandlers=new Set;mediaWatchStarted=!1;sessionUnsubscribeFromPeerConnection;detachIceGatheringTimeout;detachIceFailureWatch;constructor(e,t){this.session=e,this.detachIceGatheringTimeout=Nn(e),t!==void 0&&this.watchIceFailure(t)}get id(){return this.session.id}get from(){return this.session.from??Hn(this.session.remote_identity)}getMediaRegistration(){let e=this.session.connection;if(e!=null)return this.mediaRegistration!==void 0&&this.mediaConnection===e?this.mediaRegistration:(this.mediaConnection=e,this.mediaRegistration=xn(e),this.mediaRegistration)}answer(e){this.session.answer({mediaConstraints:e.mediaConstraints,pcConfig:{iceServers:[...e.pcConfig.iceServers],iceCandidatePoolSize:Gn}})}terminate(){this.detachIceGatheringTimeout?.(),this.detachIceGatheringTimeout=void 0,this.detachIceFailureWatch?.(),this.detachIceFailureWatch=void 0,this.pendingHoldReject?.(Error(`SIP session terminated`)),this.session.terminate()}watchIceFailure(e){let t,n=()=>{t?.iceConnectionState===`failed`&&e()},r=e=>{e&&e!==t&&(t?.removeEventListener(`iceconnectionstatechange`,n),t=e,t.addEventListener(`iceconnectionstatechange`,n),n())},i=e=>{r(e?.peerconnection)},a=()=>{this.session.off(`peerconnection`,i),this.session.off(`ended`,a),this.session.off(`failed`,a),t?.removeEventListener(`iceconnectionstatechange`,n),t=void 0},o=this.session.connection;o!=null&&r(o),this.session.on(`peerconnection`,i),this.session.on(`ended`,a),this.session.on(`failed`,a),this.detachIceFailureWatch=a}hold(){return this.changeHoldState(`hold`)}unhold(){return this.changeHoldState(`unhold`)}mute(){this.session.mute()}unmute(){this.session.unmute()}sendDtmf(e){this.session.sendDTMF(e)}refer(e){this.session.refer(e)}on(e,t){return e===`mediaConnected`?(this.mediaHandlers.add(t),this.watchMediaConnection(),()=>{this.mediaHandlers.delete(t),this.mediaHandlers.size===0&&(this.sessionUnsubscribeFromPeerConnection?.(),this.sessionUnsubscribeFromPeerConnection=void 0)}):(this.session.on(e,t),()=>this.session.off(e,t))}watchMediaConnection(){if(this.mediaWatchStarted)return;this.mediaWatchStarted=!0;let e=!1,t=t=>{if(t==null)return;let n=()=>{if(e)return;let n=t.connectionState||t.iceConnectionState;if(n===`connected`){e=!0;for(let e of this.mediaHandlers)try{e({state:n})}catch{}}};t.addEventListener(`connectionstatechange`,n),n()},n=this.session.connection;if(n!=null){t(n);return}let r=e=>{t(e?.peerconnection??void 0)};this.session.on(`peerconnection`,r),this.sessionUnsubscribeFromPeerConnection=()=>this.session.off(`peerconnection`,r)}changeHoldState(e){return new Promise((t,n)=>{let r=!1,i=e=>{s(e)},a=()=>{try{this.session.off(`ended`,i)}catch{}try{this.session.off(`failed`,i)}catch{}this.pendingHoldReject===s&&(this.pendingHoldReject=void 0)},o=()=>{r||(r=!0,a(),t())},s=e=>{r||(r=!0,a(),n(new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{cause:e})))};try{this.session.on(`ended`,i),this.session.on(`failed`,i)}catch(e){s(e);return}this.pendingHoldReject=s;try{this.session[e](void 0,o)||s({reason:`jssip_operation_rejected`,operation:e})}catch(e){s(e)}})}}}));h();var Zn=class e{media;options;api;suppliedSip;sip;events=new g;mediaBridge;reconnect;diagnostics;callManager;session;state=`idle`;initialized=!1;disposed=!1;intentionalDisconnect=!1;deferredRebuild=!1;sessionRecoveryPending=!1;detectedPlatform;support;acceptingEvents=!0;connectOperation;disconnectOperation;refreshOperation;disposeOperation;refreshTimer;lifecycleGeneration=0;managerUnsubscribers=[];sipUnsubscribe;networkUnsubscribers=[];networkProbeTimer;sessionDeleteOperations=new Map;deletedSessions=new Set;ownedSessionIds=new Set;terminalReleaseOperations=new Map;sharedWorkerSelection;constructor(e){if(this.options=e,e.api===void 0&&e.sessionProvider===void 0)throw new m(`CONFIG_INVALID`,`configuration`,!1,{cause:`CCBarClient 需要 sessionProvider`});this.api=e.api===void 0?er(nr(e.sessionProvider)):er(e.api),this.suppliedSip=e.sip===void 0?void 0:rr(e.sip),this.mediaBridge=at(()=>this.getActiveMediaContext()),this.media=this.mediaBridge.publicMedia,this.reconnect=new dt({recover:()=>this.recoverConnection(),onAttempt:e=>{this.disposed||this.events.emit(`connection.reconnecting`,{attempt:e})}}),this.diagnostics=new ht({getSnapshot:()=>this.createDiagnosticsSnapshot(),getPermission:()=>this.readMicrophonePermission(),getDeviceNames:async()=>(await this.media.getDevices()).map(e=>e.label).filter(e=>e!==``)}),this.sharedWorkerSelection=e.sharedWorker===void 0?{mode:`single-tab`,reason:`disabled`}:I({...e.sharedWorker,...e.sharedWorkerHost??{}})}static async checkSupport(){let e=typeof navigator<`u`&&navigator.mediaDevices!==void 0,t=typeof WebSocket<`u`,n=$n(typeof navigator<`u`?navigator.userAgent:``);return{supported:e&&t,platform:n,hasMediaDevices:e,hasWebSocket:t,...e&&t?{}:{reason:`当前运行环境缺少 WebPhone 所需的浏览器能力`}}}async initialize(){if(this.assertNotDisposed(),this.initialized)return;let t=await e.checkSupport();this.support=t,this.options.platform===void 0&&(t.platform===`web`||t.platform===`mobile-web`)&&(this.detectedPlatform=t.platform),await this.awaitSharedWorkerReady(),this.assertNotDisposed(),this.initialized=!0}connect(){if(this.assertNotDisposed(),this.connectOperation!==void 0)return this.connectOperation;if(this.state===`connected`)return Promise.resolve();this.api.invalidateToken?.();let e=this.lifecycleGeneration,t=this.performConnect(e).finally(()=>{this.connectOperation===t&&(this.connectOperation=void 0)});return this.connectOperation=t,t}disconnect(){if(this.assertNotDisposed(),this.disconnectOperation!==void 0)return this.disconnectOperation;if(this.state===`idle`&&this.connectOperation===void 0||this.state===`disconnected`&&this.connectOperation===void 0)return Promise.resolve();this.lifecycleGeneration+=1,this.acceptingEvents=!1;let e=this.performDisconnect().finally(()=>{this.disconnectOperation===e&&(this.disconnectOperation=void 0)});return this.disconnectOperation=e,e}dispose(){if(this.disposeOperation!==void 0)return this.disposeOperation;this.disposed=!0,this.lifecycleGeneration+=1,this.intentionalDisconnect=!0,this.acceptingEvents=!1,this.reconnect.dispose(),this.clearRefreshTimer(),this.detachNetworkListeners(),this.releaseSharedWorker(),this.state=`disconnected`,this.diagnostics.log(`info`,`connection.stateChanged`,{state:`disconnected`}),this.detachSipListener(),this.detachManagerListeners();let e=!1,t=this.performDispose().then(()=>{e=!0}).finally(()=>{this.disposeOperation===t&&!e&&(this.disposeOperation=void 0)});return this.disposeOperation=t,t}recover(){return this.assertNotDisposed(),this.recoverConnection()}dial(e){this.assertConnected();let t=this.callManager,n=this.session;if(t===void 0||n===void 0)throw new m(`CALL_NOT_CONNECTED`,`call`,!1);return t.dial(e,n)}answer(e,t){this.assertConnected();let n=this.callManager,r=this.session;if(n===void 0||r===void 0)throw new m(`CALL_NOT_CONNECTED`,`call`,!1);return n.answer(e,r,t)}setActiveCall(e){this.assertConnected();let t=this.callManager;if(t===void 0)throw new m(`CALL_NOT_CONNECTED`,`call`,!1);return t.setActiveCall(e)}getCalls(){return this.callManager?.getCalls()??[]}getActiveCall(){return this.callManager?.getActiveCall()}getAgent(){return this.session?.agent}getSharedWorkerState(){let e=this.sharedWorkerSelection;return e.mode===`shared`?{mode:`shared`,tabId:e.tabId}:{mode:`single-tab`,reason:e.reason}}getDiagnostics(e={}){return this.diagnostics.getReport(e)}async setAgentStatus(e){if(this.assertNotDisposed(),e!==`available`&&e!==`offline`&&e!==`break`)throw new m(`CONFIG_INVALID`,`configuration`,!1,{cause:`Unsupported agent status: ${String(e)}`});let t=this.session?.transport.wssUrl;await this.api.setAgentStatus({status:e,reason:``},t===void 0?void 0:{wssUrl:t}),this.disposed||this.events.emit(`agent.statusChanged`,{status:e})}on(e,t){return this.disposed?()=>void 0:this.events.on(e,t)}off(e,t){this.events.off(e,t)}async performConnect(e){let t,n,r;try{await this.initialize(),this.assertGeneration(e);let i=this.resolvePlatform();this.intentionalDisconnect=!1,this.acceptingEvents=!0,this.setConnectionState(`connecting`),t=await this.api.createSession({sdkVersion:M,platform:i===`mobile-web`?`mobile_web`:`web`,...this.options.locale===void 0?{}:{locale:this.options.locale},requestedCapabilities:[...this.options.requestedCapabilities??ur(i)]}),this.ownedSessionIds.add(t.sessionId),this.assertGeneration(e),n=await this.getSip(),this.assertGeneration(e),this.session=t;let a=this.callManager??this.createCallManager(n,t,i);this.callManager===void 0&&(r=a),a.updateSession(t),this.callManager=a,this.attachSipListener(n),this.attachNetworkListeners(),await n.connect(t),this.assertGeneration(e),this.setConnectionState(`connected`),this.events.emit(`connection.registered`,{registered:!0}),this.scheduleRefresh(t)}catch(i){if(await this.rollbackConnect(t,n,r),this.disposed)throw this.disposedError();if(e!==this.lifecycleGeneration)throw i;let a=ir(i,`REGISTRATION_FAILED`,`registration`,!0);throw this.setConnectionState(`failed`),this.events.emit(`connection.failed`,{error:a}),a}}async performDisconnect(){let e,t=this.connectOperation;if(t!==void 0)try{await t}catch(t){sr(t)||(e??=t)}let n=this.refreshOperation;if(n!==void 0)try{await n}catch(t){sr(t)||(e??=t)}this.reconnect.cancel(),this.clearRefreshTimer(),this.intentionalDisconnect=!0,this.detachNetworkListeners(),this.detachSipListener(),this.detachManagerListeners();let r=this.callManager,i=this.sip;this.callManager=void 0;try{await r?.dispose({terminateCalls:!0})}catch(t){e??=t}try{await this.awaitMediaReleaseBarriers()}catch(t){e??=t}try{i!==void 0&&await i.disconnect()}catch(t){e??=t}this.session=void 0;try{await this.deleteOwnedSessions()}catch(t){e??=t}if(this.pruneDeletedSessionTombstones(),this.disposed||(this.acceptingEvents=!0,this.setConnectionState(`disconnected`)),e!==void 0)throw e}createCallManager(e,t,n){let r=new ae({sip:e,platform:n,session:t,maxConcurrentCalls:this.options.maxConcurrentCalls,autoHoldPreviousCall:this.options.autoHoldPreviousCall,onCallCreated:(e,t)=>this.handleCallCreated(e,t),onCallStateChanged:(e,t)=>this.handleCallStateChanged(e,t),onCallTerminal:e=>this.handleCallTerminal(e)});return this.bindManagerEvents(r),r}async rollbackConnect(e,t,n){if(n!==void 0){this.detachManagerListeners(),this.callManager===n&&(this.callManager=void 0);try{await n.dispose({terminateCalls:!0})}catch{}}if(t!==void 0){this.detachSipListener();try{await t.disconnect()}catch{}}if(this.session===e&&(this.session=void 0),e!==void 0)try{await this.deleteSession(e.sessionId)}catch{}}async performDispose(){let e,t=[this.connectOperation,this.disconnectOperation,this.refreshOperation].filter(e=>e!==void 0);for(let n of t)try{await n}catch(t){sr(t)||(e??=t)}let n=this.callManager;this.callManager=void 0;try{await n?.dispose({terminateCalls:!0})}catch(t){e??=t}try{await this.awaitMediaReleaseBarriers()}catch(t){e??=t}try{await this.media.releaseAll()}catch(t){or(t)||(e??=t)}try{await this.mediaBridge.dispose()}catch(t){e??=t}try{await this.sip?.dispose()}catch(t){e??=t}try{await this.deleteOwnedSessions()}catch(t){e??=t}if(this.pruneDeletedSessionTombstones(),this.session=void 0,this.sipUnsubscribe=void 0,this.events.clear(),e!==void 0)throw e}async awaitMediaReleaseBarriers(){let e;for(let[t,n]of[...this.terminalReleaseOperations])try{await n,this.terminalReleaseOperations.delete(t)}catch(n){try{await this.mediaBridge.releaseCall(t),this.terminalReleaseOperations.delete(t)}catch(t){e??=t??n}}if(e!==void 0)throw e}detachSipListener(){let e=this.sipUnsubscribe;this.sipUnsubscribe=void 0;try{e?.()}catch{}}detachManagerListeners(){this.managerUnsubscribers.splice(0).forEach(e=>{try{e()}catch{}})}bindManagerEvents(e){[`call.created`,`call.incoming`,`call.stateChanged`,`call.activeChanged`,`call.ended`,`call.failed`,`error`].forEach(t=>{let n=e.on(t,e=>{this.acceptingEvents&&!this.disposed&&(this.diagnostics.log(t===`error`||t===`call.failed`?`error`:`info`,String(t),e),this.events.emit(t,e))});this.managerUnsubscribers.push(n)})}handleCallCreated(e,t){this.acceptingEvents&&!this.disposed&&this.mediaBridge.registerCall(e,t)}handleCallStateChanged(e,t){this.acceptingEvents&&!this.disposed&&this.mediaBridge.registerCall(e,t)}handleCallTerminal(e){let t=this.startTerminalRelease(e);return this.deferredRebuild&&!this.hasNonTerminalCalls()&&this.startDeferredRecovery(),t}startTerminalRelease(e){let t=this.terminalReleaseOperations.get(e);if(t!==void 0)return t;let n=this.mediaBridge.releaseCall(e).then(()=>{this.terminalReleaseOperations.get(e)===n&&this.terminalReleaseOperations.delete(e)}).catch(t=>{throw this.acceptingEvents&&!this.disposed&&this.events.emit(`error`,{error:ir(t,`SDK_INTERNAL_ERROR`,`internal`,!0,e)}),t});return this.terminalReleaseOperations.set(e,n),n}async startDeferredRecovery(){try{if(await this.awaitMediaReleaseBarriers(),this.deferredRebuild&&!this.hasNonTerminalCalls()&&!this.disposed){if(this.sessionRecoveryPending){this.recoverInvalidSession();return}this.deferredRebuild=!1,this.clearRefreshTimer(),this.reconnect.start()}}catch{!this.disposed&&!this.sessionRecoveryPending&&this.reconnect.start()}}async refreshAndRebuild(){if(this.refreshOperation!==void 0)return this.refreshOperation;let e=this.performRefreshAndRebuild().finally(()=>{this.refreshOperation===e&&(this.refreshOperation=void 0),this.sessionRecoveryPending&&!this.hasNonTerminalCalls()&&!this.disposed&&this.recoverInvalidSession()});return this.refreshOperation=e,e}async performRefreshAndRebuild(){if(this.disposed||this.session===void 0)return;let e=this.lifecycleGeneration,t=this.session;try{let n=await this.api.refreshSession(t.sessionId);if(!this.isCurrentGeneration(e)||this.session!==t)return;if(this.session=n,this.callManager?.updateSession(n),this.events.emit(`token.refreshed`,{expiresAt:n.expiresAt}),this.hasNonTerminalCalls()){this.deferredRebuild=!0,this.scheduleRefresh(n);return}let r=await this.getSip();if(!this.isCurrentGeneration(e))return;await r.connect(n),this.isCurrentGeneration(e)&&(this.deferredRebuild=!1,this.setConnectionState(`connected`),this.scheduleRefresh(n))}catch(n){if(!this.isCurrentGeneration(e))return;throw this.handleRefreshFailure(t,n),n}}handleRefreshFailure(e,t){if(this.disposed)return;let n=ir(t,`NETWORK_OFFLINE`,`network`,!0);if(this.events.emit(`token.expiring`,{expiresAt:e.expiresAt}),this.events.emit(`error`,{error:n}),ar(t)){this.clearRefreshTimer(),this.reconnect.cancel(),this.deletedSessions.add(e.sessionId),this.sessionRecoveryPending=!0,this.deferredRebuild=!0,(n.code===`AUTH_TOKEN_UNAVAILABLE`||n.code===`AUTH_TOKEN_EXPIRED`||n.code===`AUTH_TOKEN_REJECTED`)&&this.api.invalidateToken?.();return}this.deferredRebuild=!0,this.hasNonTerminalCalls()||this.reconnect.start()}async recoverInvalidSession(){if(!(!this.sessionRecoveryPending||this.disposed||this.hasNonTerminalCalls())){this.sessionRecoveryPending=!1,this.deferredRebuild=!1;try{await this.performDisconnect()}catch(e){this.disposed||this.events.emit(`error`,{error:ir(e,`SDK_INTERNAL_ERROR`,`internal`,!0)});return}if(!this.disposed)try{await this.performConnect(this.lifecycleGeneration)}catch{this.reconnect.cancel()}}}scheduleRefresh(e){this.clearRefreshTimer();let t=e.expiresAt*1e3-Date.now()-6e4,n=Math.max(1e3,t);this.refreshTimer=setTimeout(()=>{this.refreshTimer=void 0,this.refreshAndRebuild().catch(()=>void 0)},n)}async recoverConnection(){this.disposed||this.intentionalDisconnect||this.hasNonTerminalCalls()||(await this.awaitMediaReleaseBarriers(),await this.refreshAndRebuild())}async getSip(){if(this.sip!==void 0)return this.sip;if(this.suppliedSip!==void 0)return this.sip=this.suppliedSip,this.sip;let[e,t]=await Promise.all([Promise.resolve().then(()=>(bn(),gn)),Promise.resolve().then(()=>(Xn(),In))]);return this.sip=new t.JsSipAdapter(e.createJsSipFactory(),this.options.baseUrl,this.options.sipKeepaliveSeconds,this.options.agentTerminal,this.options.sipSessionTimers??!1),this.sip}attachSipListener(e){this.sipUnsubscribe===void 0&&e.onConnectionStateChanged!==void 0&&(this.sipUnsubscribe=e.onConnectionStateChanged((e,t)=>{if(!(this.disposed||this.intentionalDisconnect||!this.acceptingEvents)){if(e===`registered`){this.setConnectionState(`connected`);return}this.state===`connected`&&(this.setConnectionState(`reconnecting`),this.reconnect.start(),t!==void 0&&this.events.emit(`error`,{error:ir(t,`SIP_WS_UNAVAILABLE`,`registration`,!0)}))}}))}attachNetworkListeners(){if(this.networkUnsubscribers.length>0||typeof window>`u`)return;let e=window,t=()=>{this.reconnect.notifyOnline(),this.scheduleIceReassessment()},n=()=>this.reconnect.notifyOffline(),r=()=>this.scheduleIceReassessment();e.addEventListener(`online`,t),e.addEventListener(`offline`,n);let i=(typeof navigator>`u`?void 0:navigator)?.connection;i?.addEventListener(`change`,r),this.networkUnsubscribers=[()=>e.removeEventListener(`online`,t),()=>e.removeEventListener(`offline`,n),...i===void 0?[]:[()=>i.removeEventListener(`change`,r)]]}scheduleIceReassessment(){this.networkProbeTimer!==void 0&&clearTimeout(this.networkProbeTimer),this.networkProbeTimer=setTimeout(()=>{this.networkProbeTimer=void 0,!this.disposed&&this.state===`connected`&&this.sip?.reassessIceServers?.(`network-online`)},2e3)}detachNetworkListeners(){this.networkProbeTimer!==void 0&&clearTimeout(this.networkProbeTimer),this.networkProbeTimer=void 0,this.networkUnsubscribers.splice(0).forEach(e=>e())}getActiveMediaContext(){let e=this.callManager?.getActiveCall();return e===void 0?void 0:this.mediaBridge.contextFor(e.id,e.state,new Set(this.session?.capabilities??[]))}hasNonTerminalCalls(){return this.callManager?.hasNonTerminalCalls()??!1}clearRefreshTimer(){this.refreshTimer!==void 0&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)}createDiagnosticsSnapshot(){let e=this.session;return{connectionState:this.state,calls:this.getCalls().map(e=>({callId:e.id,state:e.state,destination:e.destination})),permission:this.support?.hasMediaDevices===!1?`unsupported`:`unknown`,ice:Qn(e,this.sip?.iceQualitySnapshot?.()),wss:{configured:e!==void 0,secure:e?.transport.wssUrl.toLowerCase().startsWith(`wss://`)??!1,state:this.state},resources:this.getDiagnosticsResourceCounts()}}getDiagnosticsResourceCounts(){let e=this.mediaBridge.getResourceCounts(),t=this.callManager?.getResourceCounts()??{timers:0,listeners:0},n=this.sip?.getResourceCounts?.(),r=(this.callManager===void 0?0:1)+(this.sipUnsubscribe===void 0?0:1),i=this.session!==void 0&&this.state!==`idle`&&this.state!==`disconnected`;return{timers:(this.refreshTimer===void 0?0:1)+this.reconnect.getTimerCount()+t.timers,listeners:this.events.listenerCount()+t.listeners+e.listeners+this.networkUnsubscribers.length+(n?.listeners??r),tracks:e.tracks,peerConnections:e.peerConnections,audioElements:e.audioElements,webSockets:n?.webSockets??+!!i,deletedSessions:this.deletedSessions.size}}async readMicrophonePermission(){if(typeof navigator>`u`||navigator.mediaDevices===void 0)return`unsupported`;if(navigator.permissions===void 0)return`unknown`;try{return(await navigator.permissions.query({name:`microphone`})).state}catch{return`unknown`}}deleteSession(e){if(this.deletedSessions.has(e))return Promise.resolve();let t=this.sessionDeleteOperations.get(e);if(t!==void 0)return t;let n=this.api.deleteSession(e).then(()=>{this.deletedSessions.add(e)}).catch(t=>{if(ar(t)){this.deletedSessions.add(e);return}throw t}).finally(()=>{this.sessionDeleteOperations.get(e)===n&&this.sessionDeleteOperations.delete(e)});return this.sessionDeleteOperations.set(e,n),n}pruneDeletedSessionTombstones(){for(let e of[...this.deletedSessions])!this.ownedSessionIds.has(e)&&!this.sessionDeleteOperations.has(e)&&this.deletedSessions.delete(e)}async deleteOwnedSessions(){let e;for(let t of[...this.ownedSessionIds])try{await this.deleteSession(t),this.ownedSessionIds.delete(t)}catch(t){e??=t}if(e!==void 0)throw e}resolvePlatform(){let e=this.options.platform??this.detectedPlatform;if(e===void 0)throw new m(`CONFIG_INVALID`,`configuration`,!1,{cause:this.support?.platform??`unknown`});return e}setConnectionState(e){this.state===e||this.disposed||(this.state=e,this.diagnostics.log(`info`,`connection.stateChanged`,{state:e}),this.events.emit(`connection.stateChanged`,{state:e===`disconnected`||e===`idle`?`offline`:e}))}assertConnected(){if(this.assertNotDisposed(),this.state!==`connected`||this.callManager===void 0||this.session===void 0)throw new m(`CALL_NOT_CONNECTED`,`call`,!1)}assertGeneration(e){if(this.disposed)throw this.disposedError();if(e!==this.lifecycleGeneration)throw new m(`CALL_NOT_CONNECTED`,`call`,!1)}isCurrentGeneration(e){return!this.disposed&&e===this.lifecycleGeneration}async awaitSharedWorkerReady(){let e=this.sharedWorkerSelection;if(e.mode===`shared`)try{await e.ready}catch(e){if(this.disposed)return;if(this.options.sharedWorker?.fallback===`error`)throw e;this.sharedWorkerSelection={mode:`single-tab`,reason:e instanceof Error?e.message:`SharedWorker attach failed`}}}releaseSharedWorker(){let e=this.sharedWorkerSelection;if(this.sharedWorkerSelection={mode:`single-tab`,reason:`disposed`},e.mode===`shared`){try{e.client.request({version:1,type:`detach`,requestId:`detach-${e.tabId}`,tabId:e.tabId}).catch(()=>void 0)}catch{}e.client.close()}}assertNotDisposed(){if(this.disposed)throw this.disposedError()}disposedError(){return new m(`SDK_ALREADY_DISPOSED`,`internal`,!1)}};function Qn(e,t){if(e===void 0)return{configured:!1,serverCount:0,stunServerCount:0,turnServerCount:0,...t?{probe:t}:{}};let n=0,r=0;return e.iceServers.forEach(e=>{let t=e.urls.map(e=>e.toLowerCase());t.some(e=>e.startsWith(`stun:`))&&(n+=1),t.some(e=>e.startsWith(`turn:`)||e.startsWith(`turns:`))&&(r+=1)}),{...t?{probe:t}:{},configured:e.iceServers.length>0,serverCount:e.iceServers.length,stunServerCount:n,turnServerCount:r}}function $n(e){return e===``?`unknown`:/iPhone|iPad|Android/i.test(e)?`mobile-web`:`web`}function er(e){if(typeof e!=`object`||!e)throw new m(`CONFIG_INVALID`,`configuration`,!1);return e}async function tr(e){let t=e.sip?.registerTicket;if(typeof t!=`string`||t===``)return e;let n=await fe(t);return n===void 0||n===t?e:{...e,sip:{...e.sip,registerTicket:n}}}function nr(e){let t={createSession:async t=>tr(await e.createSession(t)),refreshSession:async t=>tr(e.refreshSession===void 0?await e.createSession({sdkVersion:M,platform:`web`}):await e.refreshSession(t)),deleteSession:async t=>{e.deleteSession!==void 0&&await e.deleteSession(t)},setAgentStatus:(t,n)=>e.setAgentStatus===void 0?Promise.reject(new m(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{cause:`当前会话来源不支持坐席状态设置(sessionProvider.setAgentStatus 未提供)`})):e.setAgentStatus(t,n)},n=e.invalidateToken;return n!==void 0&&(t.invalidateToken=()=>n()),t}function rr(e){if(typeof e!=`object`||!e)throw new m(`CONFIG_INVALID`,`configuration`,!1);return e}function ir(e,t,n,r,i){return e instanceof m?new m(e.code,e.category,e.retryable,{requestId:e.requestId,callId:i??e.callId,cause:e.cause??e,serverCode:e.serverCode,platformCode:e.platformCode,status:e.status}):new m(t,n,r,{callId:i,cause:e})}function ar(e){return e instanceof m?e.status!==void 0&&e.status>=400&&e.status<500||e.serverCode===`SESSION_NOT_FOUND`||e.serverCode===`SESSION_EXPIRED`||e.serverCode===`TOKEN_INVALID`||e.serverCode===`TOKEN_EXPIRED`||e.code===`AUTH_TOKEN_UNAVAILABLE`||e.code===`AUTH_TOKEN_EXPIRED`||e.code===`AUTH_TOKEN_REJECTED`:!1}function or(e){return e instanceof m&&e.code===`SDK_ALREADY_DISPOSED`}function sr(e){return e instanceof m&&(e.code===`SDK_ALREADY_DISPOSED`||e.code===`CALL_NOT_CONNECTED`)}var cr=[`outbound`,`inbound`,`mute`,`hold`,`dtmf`,`blind_transfer`,`device_selection`],lr=[`outbound`,`mute`,`dtmf`];function ur(e){return e===`mobile-web`?lr:cr}h(),h();function dr(e={}){return{version:`0.1.0`,options:e}}e.CCBarCall=ee,e.CCBarClient=Zn,e.CCBarError=m,e.CallManager=ae,e.CallStateError=b,e.Diagnostics=ht,e.RingBuffer=ft,e.TypedEventBus=g,e.assertCallTransition=y,e.canTransition=v,e.createSdk=dr,e.createSharedWorkerSelection=I,e.diagnosticsVersion=M,e.parseSessionResponse=S,e.redactText=we,e.redactValue=Te,e.resolveWorkerUrl=L,e.transition=x,e.transitions=_,e.version=`0.1.0`});
|
|
21
|
+
`,n),i===-1)return i;!e.substring(i+2,i+4).match(/(^\r\n)/)&&e.charAt(i+2).match(/(^\s+)/)?n=i+2:r=i}return r}function o(e,t,i,a){let o,s=t.indexOf(`:`,i),c=t.substring(i,s).trim(),l=t.substring(s+1,a).trim();switch(c.toLowerCase()){case`via`:case`v`:e.addHeader(`via`,l),e.getHeaders(`via`).length===1?(o=e.parseHeader(`Via`),o&&(e.via=o,e.via_branch=o.branch)):o=0;break;case`from`:case`f`:e.setHeader(`from`,l),o=e.parseHeader(`from`),o&&(e.from=o,e.from_tag=o.getParam(`tag`));break;case`to`:case`t`:e.setHeader(`to`,l),o=e.parseHeader(`to`),o&&(e.to=o,e.to_tag=o.getParam(`tag`));break;case`record-route`:if(o=n.parse(l,`Record_Route`),o===-1)o=void 0;else for(let t of o)e.addHeader(`record-route`,l.substring(t.possition,t.offset)),e.headers[`Record-Route`][e.getHeaders(`record-route`).length-1].parsed=t.parsed;break;case`call-id`:case`i`:e.setHeader(`call-id`,l),o=e.parseHeader(`call-id`),o&&(e.call_id=l);break;case`contact`:case`m`:if(o=n.parse(l,`Contact`),o===-1)o=void 0;else for(let t of o)e.addHeader(`contact`,l.substring(t.possition,t.offset)),e.headers.Contact[e.getHeaders(`contact`).length-1].parsed=t.parsed;break;case`content-length`:case`l`:e.setHeader(`content-length`,l),o=e.parseHeader(`content-length`);break;case`content-type`:case`c`:e.setHeader(`content-type`,l),o=e.parseHeader(`content-type`);break;case`cseq`:e.setHeader(`cseq`,l),o=e.parseHeader(`cseq`),o&&(e.cseq=o.value),e instanceof r.IncomingResponse&&(e.method=o.method);break;case`max-forwards`:e.setHeader(`max-forwards`,l),o=e.parseHeader(`max-forwards`);break;case`www-authenticate`:e.setHeader(`www-authenticate`,l),o=e.parseHeader(`www-authenticate`);break;case`proxy-authenticate`:e.setHeader(`proxy-authenticate`,l),o=e.parseHeader(`proxy-authenticate`);break;case`session-expires`:case`x`:e.setHeader(`session-expires`,l),o=e.parseHeader(`session-expires`),o&&(e.session_expires=o.expires,e.session_expires_refresher=o.refresher);break;case`refer-to`:case`r`:e.setHeader(`refer-to`,l),o=e.parseHeader(`refer-to`),o&&(e.refer_to=o);break;case`replaces`:e.setHeader(`replaces`,l),o=e.parseHeader(`replaces`),o&&(e.replaces=o);break;case`event`:case`o`:e.setHeader(`event`,l),o=e.parseHeader(`event`),o&&(e.event=o);break;default:e.addHeader(c,l),o=0}return o!==void 0||{error:`error parsing header "${c}"`}}})),fn=c(((e,t)=>{var n=J(),r=H(),i=Y(),a=K(),o=new n(`sanityCheck`),s=[y],c=[p,m,h,g],l=[_,v],u,d,f;t.exports=(e,t,n)=>{u=e,d=t,f=n;for(let e of s)if(e()===!1)return!1;if(u instanceof i.IncomingRequest){for(let e of c)if(e()===!1)return!1}else if(u instanceof i.IncomingResponse){for(let e of l)if(e()===!1)return!1}return!0};function p(){if(u.s(`to`).uri.scheme!==`sip`)return b(416),!1}function m(){if(!u.to_tag&&u.call_id.substr(0,5)===d.configuration.jssip_id)return b(482),!1}function h(){if(a.str_utf8_length(u.body)<u.getHeader(`content-length`))return b(400),!1}function g(){let e=u.from_tag,t=u.call_id,n=u.cseq,i;if(!u.to_tag){if(u.method===r.INVITE){if(d._transactions.ist[u.via_branch])return!1;for(let r in d._transactions.ist)if(Object.prototype.hasOwnProperty.call(d._transactions.ist,r)&&(i=d._transactions.ist[r],i.request.from_tag===e&&i.request.call_id===t&&i.request.cseq===n))return b(482),!1}else if(d._transactions.nist[u.via_branch])return!1;else for(let r in d._transactions.nist)if(Object.prototype.hasOwnProperty.call(d._transactions.nist,r)&&(i=d._transactions.nist[r],i.request.from_tag===e&&i.request.call_id===t&&i.request.cseq===n))return b(482),!1}}function _(){if(u.getHeaders(`via`).length>1)return o.debug(`more than one Via header field present in the response, dropping the response`),!1}function v(){if(a.str_utf8_length(u.body)<u.getHeader(`content-length`))return o.debug(`message body length is lower than the value in Content-Length header field, dropping the response`),!1}function y(){for(let e of[`from`,`to`,`call_id`,`cseq`,`via`])if(!u.hasHeader(e))return o.debug(`missing mandatory header field : ${e}, dropping the response`),!1}function b(e){let t=u.getHeaders(`via`),n,i=`SIP/2.0 ${e} ${r.REASON_PHRASE[e]}\r\n`;for(let e of t)i+=`Via: ${e}\r\n`;n=u.getHeader(`To`),u.to_tag||(n+=`;tag=${a.newTag()}`),i+=`To: ${n}\r\n`,i+=`From: ${u.getHeader(`From`)}\r\n`,i+=`Call-ID: ${u.call_id}\r\n`,i+=`CSeq: ${u.cseq} ${u.method}\r\n`,i+=`\r
|
|
22
|
+
`,f.send(i)}})),pn=c((e=>{var t=K(),n=H(),r=W(),i=G(),a=ln(),o=U();e.settings={authorization_user:null,password:null,realm:null,ha1:null,authorization_jwt:null,display_name:null,uri:null,contact_uri:null,instance_id:null,use_preloaded_route:!1,session_timers:!0,session_timers_refresh_method:n.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,register_from_tag_trail:``,registrar_server:null,sockets:null,connection_recovery_max_interval:n.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:n.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:`${t.createRandomToken(12)}.invalid`};var s={mandatory:{sockets(e){let t=[];if(a.isSocket(e))t.push({socket:e});else if(Array.isArray(e)&&e.length)for(let n of e)Object.prototype.hasOwnProperty.call(n,`socket`)&&a.isSocket(n.socket)?t.push(n):a.isSocket(n)&&t.push({socket:n});else return;return t},uri(e){/^sip:/i.test(e)||(e=`${n.SIP}:${e}`);let t=i.parse(e);if(t&&t.user)return t}},optional:{authorization_user(e){if(r.parse(`"${e}"`,`quoted_string`)!==-1)return e},authorization_jwt(e){if(typeof e==`string`)return e},user_agent(e){if(typeof e==`string`)return e},connection_recovery_max_interval(e){if(t.isDecimal(e)){let t=Number(e);if(t>0)return t}},connection_recovery_min_interval(e){if(t.isDecimal(e)){let t=Number(e);if(t>0)return t}},contact_uri(e){if(typeof e==`string`){let t=r.parse(e,`SIP_URI`);if(t!==-1)return t}},display_name(e){return e},instance_id(e){if(/^uuid:/i.test(e)&&(e=e.substr(5)),r.parse(e,`uuid`)!==-1)return e},no_answer_timeout(e){if(t.isDecimal(e)){let t=Number(e);if(t>0)return t}},session_timers(e){if(typeof e==`boolean`)return e},session_timers_refresh_method(e){if(typeof e==`string`&&(e=e.toUpperCase(),e===n.INVITE||e===n.UPDATE))return e},session_timers_force_refresher(e){if(typeof e==`boolean`)return e},password(e){return String(e)},realm(e){return String(e)},ha1(e){return String(e)},register(e){if(typeof e==`boolean`)return e},register_expires(e){if(t.isDecimal(e)){let t=Number(e);if(t>=0)return t}},register_from_tag_trail(e){return typeof e==`function`?e:String(e)},registrar_server(e){/^sip:/i.test(e)||(e=`${n.SIP}:${e}`);let t=i.parse(e);if(t&&!t.user)return t},use_preloaded_route(e){if(typeof e==`boolean`)return e},extra_headers(e){let t=[];if(Array.isArray(e)&&e.length)for(let n of e)typeof n==`string`&&t.push(n);else return;return t}}};e.load=(e,n)=>{for(let t in s.mandatory)if(n.hasOwnProperty(t)){let r=n[t],i=s.mandatory[t](r);if(i!==void 0)e[t]=i;else throw new o.ConfigurationError(t,r)}else throw new o.ConfigurationError(t);for(let r in s.optional)if(n.hasOwnProperty(r)){let i=n[r];if(t.isEmpty(i))continue;let a=s.optional[r](i);if(a!==void 0)e[r]=a;else throw new o.ConfigurationError(r,i)}}})),mn=c(((e,t)=>{var n=q().EventEmitter,r=J(),i=H(),a=Xt(),o=rn(),s=an(),c=on(),l=sn(),u=cn(),d=Yt(),f=un(),p=K(),m=U(),h=G(),g=dn(),_=Y(),v=fn(),y=pn(),b=new r(`UA`),x={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2};t.exports=class extends n{static get C(){return x}constructor(e){if(!e)throw TypeError(`Not enough arguments`);let t=[`password`,`ha1`,`authorization_jwt`];b.debug(`new() [configuration:%o]`,Object.entries(e).filter(([e])=>!t.includes(e))),super(),this._cache={credentials:{}},this._configuration=Object.assign({},y.settings),this._dynConfiguration={},this._dialogs={},this._applicants={},this._sessions={},this._transport=null,this._contact=null,this._status=x.STATUS_INIT,this._error=null,this._transactions={nist:{},nict:{},ist:{},ict:{}},this._data={},this._closeTimer=null;try{this._loadConfig(e)}catch(e){throw this._status=x.STATUS_NOT_READY,this._error=x.CONFIGURATION_ERROR,e}this._registrator=new a(this)}get C(){return x}get status(){return this._status}get contact(){return this._contact}get configuration(){return this._configuration}get transport(){return this._transport}start(){b.debug(`start()`),this._status===x.STATUS_INIT?this._transport.connect():this._status===x.STATUS_USER_CLOSED?(b.debug(`restarting UA`),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=x.STATUS_INIT,this._transport.connect()):this._status===x.STATUS_READY?b.debug(`UA is in READY status, not restarted`):b.debug(`ERROR: connection is down, Auto-Recovery system is trying to reconnect`),this._dynConfiguration.register=this._configuration.register}register(){b.debug(`register()`),this._dynConfiguration.register=!0,this._registrator.register()}unregister(e){b.debug(`unregister()`),this._dynConfiguration.register=!1,this._registrator.unregister(e)}registrator(){return this._registrator}isRegistered(){return this._registrator.registered}isConnected(){return this._transport.isConnected()}call(e,t){b.debug(`call()`);let n=new o(this);return n.connect(e,t),n}sendMessage(e,t,n){b.debug(`sendMessage()`);let r=new l(this);return r.send(e,t,n),r}subscribe(e,t,n,r){return b.debug(`subscribe()`),new s(this,e,t,n,r)}notify(e,t,n){return b.debug(`notify()`),new c(this,e,t,n)}sendOptions(e,t,n){b.debug(`sendOptions()`);let r=new u(this);return r.send(e,t,n),r}terminateSessions(e){b.debug(`terminateSessions()`);for(let t in this._sessions)this._sessions[t].isEnded()||this._sessions[t].terminate(e)}stop(){if(b.debug(`stop()`),this._dynConfiguration={},this._status===x.STATUS_USER_CLOSED){b.debug(`UA already closed`);return}this._registrator.close();let e=Object.keys(this._sessions).length;for(let e in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,e)){b.debug(`closing session ${e}`);try{this._sessions[e].terminate()}catch{}}for(let e in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,e))try{this._applicants[e].close()}catch{}this._status=x.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&e===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}normalizeTarget(e){return p.normalizeTarget(e,this._configuration.hostport_params)}get(e){switch(e){case`authorization_user`:return this._configuration.authorization_user;case`realm`:return this._configuration.realm;case`ha1`:return this._configuration.ha1;case`authorization_jwt`:return this._configuration.authorization_jwt;default:b.warn(`get() | cannot get "%s" parameter in runtime`,e);return}}set(e,t){switch(e){case`authorization_user`:this._configuration.authorization_user=String(t);break;case`password`:this._configuration.password=String(t);break;case`realm`:this._configuration.realm=String(t);break;case`ha1`:this._configuration.ha1=String(t),this._configuration.password=null;break;case`authorization_jwt`:this._configuration.authorization_jwt=String(t);break;case`display_name`:this._configuration.display_name=t;break;case`extra_headers`:this._configuration.extra_headers=t;break;default:return b.warn(`set() | cannot set "%s" parameter in runtime`,e),!1}return!0}newTransaction(e){this._transactions[e.type][e.id]=e,this.emit(`newTransaction`,{transaction:e})}destroyTransaction(e){delete this._transactions[e.type][e.id],this.emit(`transactionDestroyed`,{transaction:e})}newDialog(e){this._dialogs[e.id]=e}destroyDialog(e){delete this._dialogs[e.id]}newMessage(e,t){this._applicants[e]=e,this.emit(`newMessage`,t)}newOptions(e,t){this._applicants[e]=e,this.emit(`newOptions`,t)}destroyMessage(e){delete this._applicants[e]}newRTCSession(e,t){this._sessions[e.id]=e,this.emit(`newRTCSession`,t)}destroyRTCSession(e){delete this._sessions[e.id]}registered(e){this.emit(`registered`,e)}unregistered(e){this.emit(`unregistered`,e)}registrationFailed(e){this.emit(`registrationFailed`,e)}receiveRequest(e){let t=e.method;if(e.ruri.user!==this._configuration.uri.user&&e.ruri.user!==this._contact.uri.user){b.debug(`Request-URI does not point to us`),e.method!==i.ACK&&e.reply_sl(404);return}if(e.ruri.scheme===i.SIPS){e.reply_sl(416);return}if(d.checkTransaction(this,e))return;if(t===i.INVITE?new d.InviteServerTransaction(this,this._transport,e):t!==i.ACK&&t!==i.CANCEL&&new d.NonInviteServerTransaction(this,this._transport,e),t===i.OPTIONS){if(this.listeners(`newOptions`).length===0){e.reply(200);return}new u(this).init_incoming(e)}else if(t===i.MESSAGE){if(this.listeners(`newMessage`).length===0){e.reply(405);return}new l(this).init_incoming(e)}else if(t===i.SUBSCRIBE){if(this.listeners(`newSubscribe`).length===0){e.reply(405);return}}else if(t===i.INVITE&&!e.to_tag&&this.listeners(`newRTCSession`).length===0){e.reply(405);return}let n,r;if(e.to_tag)n=this._findDialog(e.call_id,e.from_tag,e.to_tag),n?n.receiveRequest(e):t===i.NOTIFY?(r=this._findSession(e),r?r.receiveRequest(e):(b.debug(`received NOTIFY request for a non existent subscription`),e.reply(481,`Subscription does not exist`))):t!==i.ACK&&e.reply(481);else switch(t){case i.INVITE:if(window.RTCPeerConnection){if(e.hasHeader(`replaces`)){let t=e.replaces;n=this._findDialog(t.call_id,t.from_tag,t.to_tag),n?(r=n.owner,r.isEnded()?e.reply(603):r.receiveRequest(e)):e.reply(481)}else r=new o(this),r.init_incoming(e)}else b.warn(`INVITE received but WebRTC is not supported`),e.reply(488);break;case i.BYE:e.reply(481);break;case i.CANCEL:r=this._findSession(e),r?r.receiveRequest(e):b.debug(`received CANCEL request for a non existent session`);break;case i.ACK:break;case i.NOTIFY:this.emit(`sipEvent`,{event:e.event,request:e}),e.reply(200);break;case i.SUBSCRIBE:c.init_incoming(e,()=>{this.emit(`newSubscribe`,{event:e.event,request:e})});break;default:e.reply(405)}}_findSession({call_id:e,from_tag:t,to_tag:n}){let r=e+t,i=this._sessions[r],a=e+n,o=this._sessions[a];return i||o||null}_findDialog(e,t,n){let r=e+t+n,i=this._dialogs[r];return i||(r=e+n+t,i=this._dialogs[r],i||null)}_loadConfig(e){y.load(this._configuration,e),this._configuration.display_name===0&&(this._configuration.display_name=`0`),this._configuration.instance_id||(this._configuration.instance_id=p.newUUID()),this._configuration.jssip_id=p.createRandomToken(5);let t=this._configuration.uri.clone();t.user=null,this._configuration.hostport_params=t.toString().replace(/^sip:/i,``);try{this._transport=new f(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=S.bind(this),this._transport.onconnect=C.bind(this),this._transport.ondisconnect=w.bind(this),this._transport.ondata=ee.bind(this)}catch(e){throw b.warn(e),new m.ConfigurationError(`sockets`,this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){let e=this._configuration.uri.clone();e.user=null,e.clearParams(),e.clearHeaders(),this._configuration.registrar_server=e}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new h(`sip`,p.createRandomToken(8),this._configuration.via_host,null,{transport:`ws`}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(e={}){let t=e.anonymous||null,n=e.outbound||null,r=`<`;return r+=t?this.temp_gruu||`sip:anonymous@anonymous.invalid;transport=ws`:this.pub_gruu||this.uri.toString(),n&&(t?!this.temp_gruu:!this.pub_gruu)&&(r+=`;ob`),r+=`>`,r}};let n=[`authorization_user`,`password`,`realm`,`ha1`,`authorization_jwt`,`display_name`,`register`,`extra_headers`];for(let e in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,e)&&(n.indexOf(e)===-1?Object.defineProperty(this._configuration,e,{writable:!1,configurable:!1}):Object.defineProperty(this._configuration,e,{writable:!0,configurable:!1}));b.debug(`configuration parameters after validation:`);for(let e in this._configuration)if(Object.prototype.hasOwnProperty.call(y.settings,e))switch(e){case`uri`:case`registrar_server`:b.debug(`- ${e}: ${this._configuration[e]}`);break;case`password`:case`ha1`:case`authorization_jwt`:b.debug(`- ${e}: NOT SHOWN`);break;default:b.debug(`- ${e}: ${JSON.stringify(this._configuration[e])}`)}}};function S(e){this.emit(`connecting`,e)}function C(e){this._status!==x.STATUS_USER_CLOSED&&(this._status=x.STATUS_READY,this._error=null,this.emit(`connected`,e),this._dynConfiguration.register&&this._registrator.register())}function w(e){for(let e of[`nict`,`ict`,`nist`,`ist`])for(let t in this._transactions[e])Object.prototype.hasOwnProperty.call(this._transactions[e],t)&&this._transactions[e][t].onTransportError();this.emit(`disconnected`,e),this._registrator.onTransportClosed(),this._status!==x.STATUS_USER_CLOSED&&(this._status=x.STATUS_NOT_READY,this._error=x.NETWORK_ERROR)}function ee(e){let t=e.transport,n=e.message;if(n=g.parseMessage(n,this),n&&!(this._status===x.STATUS_USER_CLOSED&&n instanceof _.IncomingRequest)&&v(n,this,t)){if(n instanceof _.IncomingRequest)n.transport=t,this.receiveRequest(n);else if(n instanceof _.IncomingResponse){let e;switch(n.method){case i.INVITE:e=this._transactions.ict[n.via_branch],e&&e.receiveResponse(n);break;case i.ACK:break;default:e=this._transactions.nict[n.via_branch],e&&e.receiveResponse(n)}}}}})),hn=c(((e,t)=>{var n=J(),r=W(),i=new n(`WebSocketInterface`);t.exports=class{constructor(e){i.debug(`new() [url:"%s"]`,e),this._url=e,this._sip_uri=null,this._via_transport=null,this._ws=null;let t=r.parse(e,`absoluteURI`);if(t===-1)throw i.warn(`invalid WebSocket URI: ${e}`),TypeError(`Invalid argument: ${e}`);if(t.scheme!==`wss`&&t.scheme!==`ws`)throw i.warn(`invalid WebSocket URI scheme: ${t.scheme}`),TypeError(`Invalid argument: ${e}`);this._sip_uri=`sip:${t.host}${t.port?`:${t.port}`:``};transport=ws`,this._via_transport=t.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(e){this._via_transport=e.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(i.debug(`connect()`),this.isConnected()){i.debug(`WebSocket ${this._url} is already connected`);return}if(this.isConnecting()){i.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),i.debug(`connecting to WebSocket ${this._url}`);try{this._ws=new WebSocket(this._url,`sip`),this._ws.binaryType=`arraybuffer`,this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(e){this._onError(e)}}disconnect(){i.debug(`disconnect()`),this._ws&&=(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),null)}send(e){return i.debug(`send()`),this.isConnected()?(this._ws.send(e),!0):(i.warn(`unable to send message, WebSocket is not open`),!1)}isConnected(){return this._ws&&this._ws.readyState===this._ws.OPEN}isConnecting(){return this._ws&&this._ws.readyState===this._ws.CONNECTING}_onOpen(){i.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:e,code:t,reason:n}){i.debug(`WebSocket ${this._url} closed`),e===!1&&i.debug(`WebSocket abrupt disconnection`),this.ondisconnect(!e,t,n)}_onMessage({data:e}){i.debug(`received WebSocket message`),this.ondata(e)}_onError(e){i.warn(`WebSocket ${this._url} error: `,e)}}})),gn=c(((e,t)=>{var n=(Rt(),f(St).default),r=H(),i=U(),a=K(),o=mn(),s=G(),c=zt(),l=W(),u=hn(),d=Ht()(`JsSIP`),p=rn();d(`version %s`,n.version),t.exports={C:r,Exceptions:i,Utils:a,UA:o,URI:s,NameAddrHeader:c,WebSocketInterface:u,Grammar:l,RTCSession:p,debug:Ht(),get name(){return n.title},get version(){return n.version}}})),_n=l({createJsSipFactory:()=>vn});function vn(){return{createSocket:(e,t)=>new bn(e,t),createUa:e=>new yn.UA(e)}}var yn,bn,xn=s((()=>{yn=d(gn(),1),bn=class extends yn.WebSocketInterface{ticket;constructor(e,t){super(e),this.ticket=t}protocols(){return this.ticket===``?[`sip`]:[`xcall-ticket.${this.ticket}`,`sip`]}connect(){if(this.isConnected()||this.isConnecting())return;let e=this;e._ws&&this.disconnect();try{e._ws=new WebSocket(this.url,this.protocols()),e._ws.binaryType=`arraybuffer`,e._ws.onopen=e._onOpen.bind(this),e._ws.onclose=e._onClose.bind(this),e._ws.onmessage=e._onMessage.bind(this),e._ws.onerror=e._onError.bind(this)}catch(t){e._onError.call(this,t)}}}}));function Sn(e){let t=new Map;return{peerConnection:{getSenders:()=>e.getSenders().map(n=>{let r=t.get(n);if(r!==void 0)return r;let i={get track(){return n.track},get senderKind(){let t=n.track;if(t!==null)return t.kind===`audio`||t.kind===`video`?t.kind:void 0;let r=e.getTransceivers().find(e=>e.sender===n)?.receiver.track;if(r?.kind===`audio`||r?.kind===`video`)return r.kind;let i=n.getParameters().codecs?.find(e=>typeof e.mimeType==`string`);if(i?.mimeType?.toLowerCase().startsWith(`video/`))return`video`;if(i?.mimeType?.toLowerCase().startsWith(`audio/`))return`audio`},replaceTrack:e=>n.replaceTrack(e)};return t.set(n,i),i}),close:()=>{e.connectionState!==`closed`&&e.close()}},trackSource:{onTrack(t){let n=e=>{let n=e.track;t({streams:[...e.streams],track:n})};return e.addEventListener(`track`,n),()=>e.removeEventListener(`track`,n)}}}}var Cn=s((()=>{}));function wn(){return{runs:0,lastMs:null,udpOk:!1,tcpRelayOk:!1,convergedServers:null,unchanged:null,status:`idle`,lastProbeAt:null,cacheAgeMs:null,unknownCount:0,unavailableCount:0,dialMode:`original`}}function Tn(e){if(!e)return``;let t=String(e.type??``);return t===``?/ typ (\w+)/.exec(String(e.candidate??``))?.[1]??``:t}function En(e){return/^turns:/i.test(e)?`tls`:/transport=tcp/i.test(e)?`tcp`:`udp`}function Dn(e,t){let n=t.flatMap(e=>(Array.isArray(e.urls)?e.urls:[e.urls]).map(t=>[String(t),e])),r=new Map(n),i=[];for(let t of e){let e=Array.isArray(t.urls)?t.urls:[t.urls];for(let t of e){let e=r.get(String(t));e&&i.push({...e,urls:[t]})}}return i}function On(e,t={}){let n=Number.isFinite(t.timeoutMs)&&t.timeoutMs>0?t.timeoutMs:An;if(!Array.isArray(e))return Promise.resolve([]);let r=[];for(let t of e){if(!t)continue;let e=Array.isArray(t.urls)?t.urls:[t.urls];for(let n of e){let e=String(n??``).trim();/^(stun|turn|turns):/i.test(e)&&r.push({url:e,entry:t})}}return Promise.all(r.map(e=>new Promise(t=>{let r=!1,i=!1,a,o=En(e.url),s=(n,i)=>{if(!r){r=!0,clearTimeout(c);try{a?.close()}catch{}t({url:e.url,status:n,transport:o,reason:i})}},c=setTimeout(()=>s(i?`unavailable`:`unknown`,i?`server-error`:`timeout`),n);try{if(typeof RTCPeerConnection>`u`){s(`unknown`,`local-error`);return}let t={urls:[e.url]};e.entry.username&&(t.username=e.entry.username),e.entry.credential&&(t.credential=e.entry.credential),a=new RTCPeerConnection({iceServers:[t]}),a.createDataChannel(`webphone-ice-probe`),a.onicecandidate=e=>{if(!e||!e.candidate)return;let t=Tn(e.candidate);(t===`srflx`||t===`relay`)&&s(`available`,`candidate`)},a.onicecandidateerror=t=>{t?.url&&t.url===e.url&&(i=!0)},a.createOffer().then(e=>a?.setLocalDescription(e)).catch(()=>s(`unknown`,`local-error`))}catch{s(`unknown`,`local-error`)}})))}function kn(e,t){let n=new Map;for(let e of t)e&&e.url&&n.set(String(e.url),e.status===`available`);let r=[];for(let t of e??[]){if(!t)continue;let e=(Array.isArray(t.urls)?t.urls:[t.urls]).filter(Boolean).filter(e=>n.get(String(e))===!0);if(e.length===0)continue;let i={...t,urls:e};r.push(i)}return r}var An,jn,Mn,Nn=s((()=>{An=2e3,jn=[5e3,15e3,6e4],Mn=class{availableList;lastGoodList;lastGoodAt;lastResults=[];snapshotState=wn();running=!1;seq=0;consecutiveFailures=0;lastAttemptAt;retryTimer;pendingRequest;serversForDial(e,t=Date.now()){if(!e)return;if(!this.lastResults.length)return this.setDialMode(`original`),e;let n=this.lastGoodAt===void 0?null:Math.max(0,t-this.lastGoodAt);this.snapshotState={...this.snapshotState,cacheAgeMs:n};let r=n!==null&&n>3e5,i=this.snapshotState.lastProbeAt===null?null:Math.max(0,t-this.snapshotState.lastProbeAt);if(r||i!==null&&i>3e5)return this.snapshotState={...this.snapshotState,status:`stale`,cacheAgeMs:n??i},this.assess(e,`ttl-expired`),this.availableList&&this.availableList.length>0?(this.setDialMode(`original`),e):(this.setDialMode(`host-only`),[]);if(!r&&this.availableList&&this.availableList.length>0)return this.setDialMode(`known-available`),this.availableList.map(e=>({...e,urls:Array.isArray(e.urls)?[...e.urls]:e.urls}));if(this.lastGoodList&&n!==null&&n<=3e5){let t=Dn(this.lastGoodList,e);if(t.length>0)return this.setDialMode(`last-known-good`),t}return this.setDialMode(`host-only`),[]}snapshot(){return this.snapshotState}reset(){this.retryTimer!==void 0&&clearTimeout(this.retryTimer),this.retryTimer=void 0,this.pendingRequest=void 0,this.seq++,this.running=!1,this.availableList=void 0,this.lastGoodList=void 0,this.lastGoodAt=void 0,this.lastResults=[],this.consecutiveFailures=0,this.lastAttemptAt=void 0,this.snapshotState=wn()}cancelInFlight(){this.seq++,this.running=!1,this.retryTimer!==void 0&&clearTimeout(this.retryTimer),this.retryTimer=void 0,this.pendingRequest=void 0}assess(e,t=`initial-registration`){if(e===void 0)return;if(e.length===0){this.reset();return}if(this.running){t!==`initial-registration`&&(this.pendingRequest={servers:e,trigger:t});return}let n=Date.now();if(t!==`initial-registration`&&this.consecutiveFailures>0&&this.lastAttemptAt!==void 0){let r=jn[Math.min(this.consecutiveFailures-1,jn.length-1)]-(n-this.lastAttemptAt);if(r>0){this.pendingRequest={servers:e,trigger:t},this.retryTimer===void 0&&(this.retryTimer=setTimeout(()=>{this.retryTimer=void 0;let e=this.pendingRequest;this.pendingRequest=void 0,e&&this.assess(e.servers,e.trigger)},r));return}}let r=e.map(e=>({...e,urls:Array.isArray(e.urls)?[...e.urls]:[e.urls]}));if(!r.some(e=>(Array.isArray(e.urls)?e.urls:[e.urls]).some(e=>/^(stun|turn|turns):/i.test(String(e??``)))))return;let i=++this.seq;this.running=!0,this.lastAttemptAt=n,this.availableList=void 0,this.snapshotState={...this.snapshotState,status:t===`ttl-expired`?`stale`:`probing`};let a=Date.now();On(r).then(e=>{if(i!==this.seq)return;this.lastResults=e;let t=r,n=kn(t,e);this.availableList=n.length>0?n:void 0,this.availableList&&(this.lastGoodList=n.map(e=>({...e,urls:Array.isArray(e.urls)?[...e.urls]:e.urls})),this.lastGoodAt=Date.now());let o=e.filter(e=>e.status===`unknown`).length,s=e.filter(e=>e.status===`unavailable`).length;this.consecutiveFailures=n.length===0?this.consecutiveFailures+1:0,n.length===0&&this.consecutiveFailures<=jn.length&&this.pendingRequest===void 0&&(this.pendingRequest={servers:r,trigger:`retry-backoff`}),this.snapshotState={runs:this.snapshotState.runs+1,lastMs:Date.now()-a,udpOk:e.some(e=>e.status===`available`&&e.transport===`udp`),tcpRelayOk:e.some(e=>e.status===`available`&&(e.transport===`tcp`||e.transport===`tls`)),convergedServers:n.length,unchanged:JSON.stringify(n)===JSON.stringify(t),status:o+s>0?`degraded`:`healthy`,lastProbeAt:Date.now(),cacheAgeMs:0,unknownCount:o,unavailableCount:s,dialMode:n.length>0?`known-available`:`host-only`}}).catch(()=>{this.seq}).finally(()=>{if(i!==this.seq)return;this.running=!1;let e=this.pendingRequest;this.pendingRequest=void 0,e&&this.assess(e.servers,e.trigger)})}isRunning(){return this.running}setDialMode(e){let t=this.snapshotState.status;this.snapshotState={...this.snapshotState,dialMode:e,status:t===`healthy`&&e===`host-only`?`stale`:t}}}}));function Pn(e){if(!e)return``;let t=String(e.type??``);return t===``?/ typ (\w+)/.exec(String(e.candidate??``))?.[1]??``:t}function Fn(e,t={}){if(typeof e.on!=`function`)return()=>void 0;let n=Number.isFinite(t.timeoutMs)&&t.timeoutMs>0?t.timeoutMs:In,r=!1,i,a=()=>{if(!r){r=!0,clearTimeout(s);try{i?.()}catch{}}},o=e=>{let t=e;if(!t||typeof t.ready!=`function`)return;i=t.ready;let n=Pn(t.candidate);(n===`srflx`||n===`relay`)&&a()};e.on(`icecandidate`,o);let s=setTimeout(a,n);return()=>{clearTimeout(s);try{e.off?.(`icecandidate`,o)}catch{}}}var In,Ln=s((()=>{In=3e3})),Rn=l({JsSipAdapter:()=>Xn});function zn(e){let t=Math.floor(Number(e.sip.registerExpires));return Number.isFinite(t)&&t>0?t:Gn}function Bn(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.originator===`remote`&&Vn(t.session)}function Vn(e){return typeof e==`object`&&!!e&&`id`in e}function Hn(e){return typeof e==`object`&&e&&(e.via_transport=`WSS`),e}function Un(e){let t=e.replace(/^\[|\]$/g,``).toLowerCase();return t===`localhost`||t===`127.0.0.1`||t===`::1`||t===`0:0:0:0:0:0:0:1`}function Wn(e){let t=e?.uri;if(t==null)return;if(typeof t.user==`string`&&t.user!==``)return t.user;let n=t.toString();return n.match(/^sips?:([^@;>]+)/i)?.[1]??(n===``?void 0:n)}var Gn,Kn,qn,Jn,Yn,Xn,Zn,Qn=s((()=>{h(),Cn(),Nn(),Ln(),Gn=300,Kn=25,qn=2,Jn=``,Yn=120,Xn=class{factory;transportBaseUrl;keepaliveSeconds;agentTerminal;sessionTimers;ua;uaListeners;incomingHandlers;iceServers;pendingConnection;disposed=!1;warmPc;keepaliveTimer;keepaliveBusy=!1;registerExpiresSeconds=0;connectionHandlers=new Set;iceQuality=new Mn;constructor(e,t,n=Kn,r=Jn,i=!1){this.factory=e,this.transportBaseUrl=t,this.keepaliveSeconds=n,this.agentTerminal=r,this.sessionTimers=i}terminalHeaders(){return this.agentTerminal===``?[]:[`X-Agent-Terminal: ${this.agentTerminal}`]}warmIceCandidatePool(){if(this.closeWarmPc(),typeof RTCPeerConnection<`u`&&this.iceServers!==void 0)try{this.warmPc=new RTCPeerConnection({iceServers:[...this.iceServers],iceCandidatePoolSize:qn})}catch{this.warmPc=void 0}}closeWarmPc(){try{this.warmPc?.close()}catch{}this.warmPc=void 0}keepaliveTick(e){if(this.isCurrentUa(e)&&!this.keepaliveBusy)try{if(typeof e.isConnected==`function`&&e.isConnected()===!1||typeof e.register!=`function`)return;this.keepaliveBusy=!0,e.register({extraHeaders:this.terminalHeaders()})}catch{}finally{this.keepaliveBusy=!1}}startKeepalive(e,t){if(this.stopKeepalive(),!Number.isFinite(this.keepaliveSeconds)||this.keepaliveSeconds<=0||t>0&&t<=this.keepaliveSeconds)return;let n=Math.max(10,Math.floor(this.keepaliveSeconds))*1e3;this.keepaliveTimer=setInterval(()=>this.keepaliveTick(e),n)}stopKeepalive(){this.keepaliveTimer!==void 0&&clearInterval(this.keepaliveTimer),this.keepaliveTimer=void 0}connect(e){this.assertNotDisposed();let t=this.iceQuality.snapshot().runs>0;this.disconnect(this.registrationError(`SIP connection replaced`),!t);try{let t=this.factory.createUa({sockets:Hn(this.factory.createSocket(this.withoutTicket(this.resolveWssUrl(e.transport.wssUrl)),e.transport.ticket)),uri:e.sip.uri,password:e.sip.registerTicket,registrar_server:e.sip.registrar,register:!0,register_expires:zn(e),session_timers:this.sessionTimers,...this.agentTerminal===``?{}:{user_agent:this.agentTerminal}});return this.ua=t,this.registerExpiresSeconds=zn(e),this.iceServers=e.iceServers,this.uaListeners=[],this.startRegistration(t)}catch(e){let t=e instanceof m&&e.code===`CONFIG_INVALID`?e:this.transportError(e);return this.disconnect(t),Promise.reject(t)}}disconnect(e=this.registrationError(`SIP connection disconnected`),t=!0){this.stopKeepalive(),this.closeWarmPc(),t?this.iceQuality.reset():this.iceQuality.cancelInFlight();let n=this.pendingConnection;this.pendingConnection=void 0,this.ua!==void 0&&(this.removeUaListeners(this.ua),this.ua.stop()),this.ua=void 0,this.uaListeners=void 0,this.iceServers=void 0,n?.reject(e)}dial(e,t){let n=this.requireUa();if(e.trim()===``)throw new m(`CALL_INVALID_DESTINATION`,`call`,!1);try{let r=t===void 0?{mediaConstraints:{audio:!0,video:!1},sessionTimersExpires:Yn,pcConfig:{iceServers:this.dialIceServers(),iceCandidatePoolSize:qn}}:{mediaConstraints:{audio:!0,video:!1},sessionTimersExpires:Yn,pcConfig:{iceServers:[...t.iceServers],iceCandidatePoolSize:qn},extraHeaders:[...this.terminalHeaders(),...t.extraHeaders,...t.type===`extension`?[`X-XCall-Destination-Type: extension`]:[]]};return this.createSessionHandle(n.call(e,r))}catch(e){throw new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{cause:e})}}onIncoming(e){this.assertNotDisposed();let t=this.incomingHandlers??new Set;return this.incomingHandlers=t,t.add(e),()=>t.delete(e)}onConnectionStateChanged(e){return this.disposed?()=>void 0:(this.connectionHandlers.add(e),()=>this.connectionHandlers.delete(e))}dispose(){this.disposed||(this.disposed=!0,this.disconnect(),this.incomingHandlers=void 0,this.connectionHandlers.clear())}dialIceServers(){return this.iceQuality.serversForDial(this.iceServers)}iceQualitySnapshot(){return this.iceQuality.snapshot()}reassessIceServers(e=`network-online`){this.iceQuality.assess(this.iceServers,e)}getResourceCounts(){return{listeners:(this.uaListeners?.length??0)+(this.incomingHandlers?.size??0)+this.connectionHandlers.size,webSockets:this.ua===void 0?0:1}}handleIncoming(e){if(!Bn(e))return;let t=e.session;if(t===void 0)return;let n=this.createSessionHandle(t);this.incomingHandlers?.forEach(e=>e(n))}createSessionHandle(e){return new Zn(e,()=>this.reassessIceServers(`ice-failed`))}startRegistration(e){let t=!0,n=!1,r=new Promise((t,n)=>{this.pendingConnection={ua:e,resolve:t,reject:n}});this.listen(e,`registered`,()=>{if(this.isCurrentUa(e)){if(t){n=!0;return}this.resolveConnection(e)}}),this.listen(e,`registrationFailed`,t=>{if(!this.isCurrentUa(e))return;let n=this.registrationError(this.registrationFailureCause(t));this.connectionHandlers.forEach(e=>e(`failed`,n)),this.disconnect(n)}),this.listen(e,`disconnected`,t=>{if(!this.isCurrentUa(e))return;let n=this.transportError(t);this.connectionHandlers.forEach(e=>e(`disconnected`,n)),this.disconnect(n,!1)}),this.listen(e,`newRTCSession`,t=>{this.isCurrentUa(e)&&this.handleIncoming(t)});try{e.start()}catch(e){let t=this.transportError(e);this.connectionHandlers.forEach(e=>e(`failed`,t)),this.disconnect(t)}finally{t=!1}return n&&this.resolveConnection(e),r}listen(e,t,n){e.on(t,n),this.uaListeners?.push({event:t,handler:n})}removeUaListeners(e){this.uaListeners?.forEach(({event:t,handler:n})=>e.off(t,n))}isCurrentUa(e){return this.ua===e}resolveConnection(e){let t=this.pendingConnection;if(t?.ua!==e)return;this.pendingConnection=void 0,t.resolve(),this.warmIceCandidatePool();let n=this.iceQuality.snapshot().runs>0?`sip-reconnected`:`initial-registration`;this.iceQuality.assess(this.iceServers,n),this.startKeepalive(e,this.registerExpiresSeconds),this.connectionHandlers.forEach(e=>e(`registered`))}resolveWssUrl(e){let t=this.transportBaseUrl?.trim()===``||this.transportBaseUrl===void 0?typeof location>`u`?`http://localhost`:location.origin:this.transportBaseUrl,n=e.startsWith(`/`)?new URL(e,t):new URL(e);return n.protocol===`http:`&&(n.protocol=`ws:`),n.protocol===`https:`&&(n.protocol=`wss:`),this.assertAllowedWssUrl(n),n.toString()}assertAllowedWssUrl(e){if(e.protocol!==`wss:`&&!(e.protocol===`ws:`&&Un(e.hostname)))throw new m(`CONFIG_INVALID`,`configuration`,!1,{cause:e.origin})}withoutTicket(e){let t=new URL(e);return t.searchParams.delete(`ticket`),t.toString()}requireUa(){if(this.assertNotDisposed(),this.ua===void 0)throw new m(`CALL_NOT_CONNECTED`,`call`,!1);return this.ua}assertNotDisposed(){if(this.disposed)throw new m(`SDK_ALREADY_DISPOSED`,`internal`,!1)}registrationError(e){return new m(`REGISTRATION_FAILED`,`registration`,!0,{cause:e})}transportError(e){return new m(`SIP_WS_UNAVAILABLE`,`registration`,!0,{cause:e})}registrationFailureCause(e){return typeof e==`object`&&e&&`cause`in e?e.cause:e}},Zn=class{session;pendingHoldReject;mediaRegistration;mediaConnection;mediaHandlers=new Set;mediaWatchStarted=!1;sessionUnsubscribeFromPeerConnection;detachIceGatheringTimeout;detachIceFailureWatch;constructor(e,t){this.session=e,this.detachIceGatheringTimeout=Fn(e),t!==void 0&&this.watchIceFailure(t)}get id(){return this.session.id}get from(){return this.session.from??Wn(this.session.remote_identity)}getMediaRegistration(){let e=this.session.connection;if(e!=null)return this.mediaRegistration!==void 0&&this.mediaConnection===e?this.mediaRegistration:(this.mediaConnection=e,this.mediaRegistration=Sn(e),this.mediaRegistration)}answer(e){this.session.answer({mediaConstraints:e.mediaConstraints,pcConfig:{iceServers:[...e.pcConfig.iceServers],iceCandidatePoolSize:qn}})}terminate(){this.detachIceGatheringTimeout?.(),this.detachIceGatheringTimeout=void 0,this.detachIceFailureWatch?.(),this.detachIceFailureWatch=void 0,this.pendingHoldReject?.(Error(`SIP session terminated`)),this.session.terminate()}watchIceFailure(e){let t,n=()=>{t?.iceConnectionState===`failed`&&e()},r=e=>{e&&e!==t&&(t?.removeEventListener(`iceconnectionstatechange`,n),t=e,t.addEventListener(`iceconnectionstatechange`,n),n())},i=e=>{r(e?.peerconnection)},a=()=>{this.session.off(`peerconnection`,i),this.session.off(`ended`,a),this.session.off(`failed`,a),t?.removeEventListener(`iceconnectionstatechange`,n),t=void 0},o=this.session.connection;o!=null&&r(o),this.session.on(`peerconnection`,i),this.session.on(`ended`,a),this.session.on(`failed`,a),this.detachIceFailureWatch=a}hold(){return this.changeHoldState(`hold`)}unhold(){return this.changeHoldState(`unhold`)}mute(){this.session.mute()}unmute(){this.session.unmute()}sendDtmf(e){this.session.sendDTMF(e)}refer(e){this.session.refer(e)}on(e,t){return e===`mediaConnected`?(this.mediaHandlers.add(t),this.watchMediaConnection(),()=>{this.mediaHandlers.delete(t),this.mediaHandlers.size===0&&(this.sessionUnsubscribeFromPeerConnection?.(),this.sessionUnsubscribeFromPeerConnection=void 0)}):(this.session.on(e,t),()=>this.session.off(e,t))}watchMediaConnection(){if(this.mediaWatchStarted)return;this.mediaWatchStarted=!0;let e=!1,t=t=>{if(t==null)return;let n=()=>{if(e)return;let n=t.connectionState||t.iceConnectionState;if(n===`connected`){e=!0;for(let e of this.mediaHandlers)try{e({state:n})}catch{}}};t.addEventListener(`connectionstatechange`,n),n()},n=this.session.connection;if(n!=null){t(n);return}let r=e=>{t(e?.peerconnection??void 0)};this.session.on(`peerconnection`,r),this.sessionUnsubscribeFromPeerConnection=()=>this.session.off(`peerconnection`,r)}changeHoldState(e){return new Promise((t,n)=>{let r=!1,i=e=>{s(e)},a=()=>{try{this.session.off(`ended`,i)}catch{}try{this.session.off(`failed`,i)}catch{}this.pendingHoldReject===s&&(this.pendingHoldReject=void 0)},o=()=>{r||(r=!0,a(),t())},s=e=>{r||(r=!0,a(),n(new m(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{cause:e})))};try{this.session.on(`ended`,i),this.session.on(`failed`,i)}catch(e){s(e);return}this.pendingHoldReject=s;try{this.session[e](void 0,o)||s({reason:`jssip_operation_rejected`,operation:e})}catch(e){s(e)}})}}}));h();var $n=12e4,er=5e3,tr=class e{media;options;api;suppliedSip;sip;events=new g;mediaBridge;reconnect;diagnostics;callManager;session;state=`idle`;initialized=!1;disposed=!1;intentionalDisconnect=!1;deferredRebuild=!1;sessionRecoveryPending=!1;detectedPlatform;support;acceptingEvents=!0;connectOperation;disconnectOperation;refreshOperation;disposeOperation;refreshTimer;lifecycleGeneration=0;managerUnsubscribers=[];sipUnsubscribe;networkUnsubscribers=[];networkProbeTimer;stuckCallsSince;sessionDeleteOperations=new Map;deletedSessions=new Set;ownedSessionIds=new Set;terminalReleaseOperations=new Map;sharedWorkerSelection;constructor(e){if(this.options=e,e.api===void 0&&e.sessionProvider===void 0)throw new m(`CONFIG_INVALID`,`configuration`,!1,{cause:`CCBarClient 需要 sessionProvider`});this.api=e.api===void 0?ir(or(e.sessionProvider)):ir(e.api),this.suppliedSip=e.sip===void 0?void 0:sr(e.sip),this.mediaBridge=at(()=>this.getActiveMediaContext()),this.media=this.mediaBridge.publicMedia,this.reconnect=new dt({recover:()=>this.recoverConnection(),isRecovered:()=>this.state===`connected`,onAttempt:e=>{this.disposed||this.events.emit(`connection.reconnecting`,{attempt:e})}}),this.diagnostics=new ht({getSnapshot:()=>this.createDiagnosticsSnapshot(),getPermission:()=>this.readMicrophonePermission(),getDeviceNames:async()=>(await this.media.getDevices()).map(e=>e.label).filter(e=>e!==``)}),this.sharedWorkerSelection=e.sharedWorker===void 0?{mode:`single-tab`,reason:`disabled`}:I({...e.sharedWorker,...e.sharedWorkerHost??{}})}static async checkSupport(){let e=typeof navigator<`u`&&navigator.mediaDevices!==void 0,t=typeof WebSocket<`u`,n=rr(typeof navigator<`u`?navigator.userAgent:``);return{supported:e&&t,platform:n,hasMediaDevices:e,hasWebSocket:t,...e&&t?{}:{reason:`当前运行环境缺少 WebPhone 所需的浏览器能力`}}}async initialize(){if(this.assertNotDisposed(),this.initialized)return;let t=await e.checkSupport();this.support=t,this.options.platform===void 0&&(t.platform===`web`||t.platform===`mobile-web`)&&(this.detectedPlatform=t.platform),await this.awaitSharedWorkerReady(),this.assertNotDisposed(),this.initialized=!0}connect(){if(this.assertNotDisposed(),this.connectOperation!==void 0)return this.connectOperation;if(this.state===`connected`)return Promise.resolve();this.api.invalidateToken?.();let e=this.lifecycleGeneration,t=this.performConnect(e).finally(()=>{this.connectOperation===t&&(this.connectOperation=void 0)});return this.connectOperation=t,t}disconnect(){if(this.assertNotDisposed(),this.disconnectOperation!==void 0)return this.disconnectOperation;if(this.state===`idle`&&this.connectOperation===void 0||this.state===`disconnected`&&this.connectOperation===void 0)return Promise.resolve();this.lifecycleGeneration+=1,this.acceptingEvents=!1;let e=this.performDisconnect().finally(()=>{this.disconnectOperation===e&&(this.disconnectOperation=void 0)});return this.disconnectOperation=e,e}dispose(){if(this.disposeOperation!==void 0)return this.disposeOperation;this.disposed=!0,this.lifecycleGeneration+=1,this.intentionalDisconnect=!0,this.acceptingEvents=!1,this.reconnect.dispose(),this.clearRefreshTimer(),this.detachNetworkListeners(),this.releaseSharedWorker(),this.state=`disconnected`,this.diagnostics.log(`info`,`connection.stateChanged`,{state:`disconnected`}),this.detachSipListener(),this.detachManagerListeners();let e=!1,t=this.performDispose().then(()=>{e=!0}).finally(()=>{this.disposeOperation===t&&!e&&(this.disposeOperation=void 0)});return this.disposeOperation=t,t}recover(){return this.assertNotDisposed(),this.recoverConnection()}dial(e){this.assertConnected();let t=this.callManager,n=this.session;if(t===void 0||n===void 0)throw new m(`CALL_NOT_CONNECTED`,`call`,!1);return t.dial(e,n)}answer(e,t){this.assertConnected();let n=this.callManager,r=this.session;if(n===void 0||r===void 0)throw new m(`CALL_NOT_CONNECTED`,`call`,!1);return n.answer(e,r,t)}setActiveCall(e){this.assertConnected();let t=this.callManager;if(t===void 0)throw new m(`CALL_NOT_CONNECTED`,`call`,!1);return t.setActiveCall(e)}getCalls(){return this.callManager?.getCalls()??[]}getActiveCall(){return this.callManager?.getActiveCall()}getAgent(){return this.session?.agent}getSharedWorkerState(){let e=this.sharedWorkerSelection;return e.mode===`shared`?{mode:`shared`,tabId:e.tabId}:{mode:`single-tab`,reason:e.reason}}getDiagnostics(e={}){return this.diagnostics.getReport(e)}async setAgentStatus(e){if(this.assertNotDisposed(),e!==`available`&&e!==`offline`&&e!==`break`)throw new m(`CONFIG_INVALID`,`configuration`,!1,{cause:`Unsupported agent status: ${String(e)}`});let t=this.session?.transport.wssUrl;await this.api.setAgentStatus({status:e,reason:``},t===void 0?void 0:{wssUrl:t}),this.disposed||this.events.emit(`agent.statusChanged`,{status:e})}on(e,t){return this.disposed?()=>void 0:this.events.on(e,t)}off(e,t){this.events.off(e,t)}async performConnect(e){let t,n,r;try{await this.initialize(),this.assertGeneration(e);let i=this.resolvePlatform();this.intentionalDisconnect=!1,this.acceptingEvents=!0,this.setConnectionState(`connecting`),t=await this.api.createSession({sdkVersion:M,platform:i===`mobile-web`?`mobile_web`:`web`,...this.options.locale===void 0?{}:{locale:this.options.locale},requestedCapabilities:[...this.options.requestedCapabilities??pr(i)]}),this.ownedSessionIds.add(t.sessionId),this.assertGeneration(e),n=await this.getSip(),this.assertGeneration(e),this.session=t;let a=this.callManager??this.createCallManager(n,t,i);this.callManager===void 0&&(r=a),a.updateSession(t),this.callManager=a,this.attachSipListener(n),this.attachNetworkListeners(),await n.connect(t),this.assertGeneration(e),this.setConnectionState(`connected`),this.events.emit(`connection.registered`,{registered:!0}),this.scheduleRefresh(t)}catch(i){if(await this.rollbackConnect(t,n,r),this.disposed)throw this.disposedError();if(e!==this.lifecycleGeneration)throw i;let a=Z(i,`REGISTRATION_FAILED`,`registration`,!0);throw this.setConnectionState(`failed`),this.events.emit(`connection.failed`,{error:a}),a}}async performDisconnect(){let e,t=this.connectOperation;if(t!==void 0)try{await t}catch(t){ur(t)||(e??=t)}let n=this.refreshOperation;if(n!==void 0)try{await n}catch(t){ur(t)||(e??=t)}this.reconnect.cancel(),this.stuckCallsSince=void 0,this.clearRefreshTimer(),this.intentionalDisconnect=!0,this.detachNetworkListeners(),this.detachSipListener(),this.detachManagerListeners();let r=this.callManager,i=this.sip;this.callManager=void 0;try{await r?.dispose({terminateCalls:!0})}catch(t){e??=t}try{await this.awaitMediaReleaseBarriers()}catch(t){e??=t}try{i!==void 0&&await i.disconnect()}catch(t){e??=t}this.session=void 0;try{await this.deleteOwnedSessions()}catch(t){e??=t}if(this.pruneDeletedSessionTombstones(),this.disposed||(this.acceptingEvents=!0,this.setConnectionState(`disconnected`)),e!==void 0)throw e}createCallManager(e,t,n){let r=new ae({sip:e,platform:n,session:t,maxConcurrentCalls:this.options.maxConcurrentCalls,autoHoldPreviousCall:this.options.autoHoldPreviousCall,onCallCreated:(e,t)=>this.handleCallCreated(e,t),onCallStateChanged:(e,t)=>this.handleCallStateChanged(e,t),onCallTerminal:e=>this.handleCallTerminal(e)});return this.bindManagerEvents(r),r}async rollbackConnect(e,t,n){if(n!==void 0){this.detachManagerListeners(),this.callManager===n&&(this.callManager=void 0);try{await n.dispose({terminateCalls:!0})}catch{}}if(t!==void 0){this.detachSipListener();try{await t.disconnect()}catch{}}if(this.session===e&&(this.session=void 0),e!==void 0)try{await this.deleteSession(e.sessionId)}catch{}}async performDispose(){let e,t=[this.connectOperation,this.disconnectOperation,this.refreshOperation].filter(e=>e!==void 0);for(let n of t)try{await n}catch(t){ur(t)||(e??=t)}let n=this.callManager;this.callManager=void 0;try{await n?.dispose({terminateCalls:!0})}catch(t){e??=t}try{await this.awaitMediaReleaseBarriers()}catch(t){e??=t}try{await this.media.releaseAll()}catch(t){lr(t)||(e??=t)}try{await this.mediaBridge.dispose()}catch(t){e??=t}try{await this.sip?.dispose()}catch(t){e??=t}try{await this.deleteOwnedSessions()}catch(t){e??=t}if(this.pruneDeletedSessionTombstones(),this.session=void 0,this.sipUnsubscribe=void 0,this.events.clear(),e!==void 0)throw e}async awaitMediaReleaseBarriers(){let e;for(let[t,n]of[...this.terminalReleaseOperations])try{await this.withBarrierTimeout(n,t),this.terminalReleaseOperations.delete(t)}catch(n){try{await this.withBarrierTimeout(this.mediaBridge.releaseCall(t),t),this.terminalReleaseOperations.delete(t)}catch(t){e??=t??n}}if(e!==void 0)throw e}withBarrierTimeout(e,t,n=er){return new Promise((r,i)=>{let a=setTimeout(()=>{i(new m(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:t,cause:`media release barrier timeout`}))},Math.max(0,n));e.then(e=>{clearTimeout(a),r(e)},e=>{clearTimeout(a),i(e)})})}detachSipListener(){let e=this.sipUnsubscribe;this.sipUnsubscribe=void 0;try{e?.()}catch{}}detachManagerListeners(){this.managerUnsubscribers.splice(0).forEach(e=>{try{e()}catch{}})}bindManagerEvents(e){[`call.created`,`call.incoming`,`call.stateChanged`,`call.activeChanged`,`call.ended`,`call.failed`,`error`].forEach(t=>{let n=e.on(t,e=>{this.acceptingEvents&&!this.disposed&&(this.diagnostics.log(t===`error`||t===`call.failed`?`error`:`info`,String(t),e),this.events.emit(t,e))});this.managerUnsubscribers.push(n)})}handleCallCreated(e,t){this.acceptingEvents&&!this.disposed&&this.mediaBridge.registerCall(e,t)}handleCallStateChanged(e,t){this.acceptingEvents&&!this.disposed&&this.mediaBridge.registerCall(e,t)}handleCallTerminal(e){let t=this.startTerminalRelease(e);return this.deferredRebuild&&!this.hasNonTerminalCalls()&&this.startDeferredRecovery(),t}startTerminalRelease(e){let t=this.terminalReleaseOperations.get(e);if(t!==void 0)return t;let n=this.mediaBridge.releaseCall(e).then(()=>{this.terminalReleaseOperations.get(e)===n&&this.terminalReleaseOperations.delete(e)}).catch(t=>{throw this.acceptingEvents&&!this.disposed&&this.events.emit(`error`,{error:Z(t,`SDK_INTERNAL_ERROR`,`internal`,!0,e)}),t});return this.terminalReleaseOperations.set(e,n),n}async startDeferredRecovery(){try{if(await this.awaitMediaReleaseBarriers(),this.deferredRebuild&&!this.hasNonTerminalCalls()&&!this.disposed){if(this.sessionRecoveryPending){this.recoverInvalidSession();return}this.deferredRebuild=!1,this.clearRefreshTimer(),this.reconnect.start()}}catch{!this.disposed&&!this.sessionRecoveryPending&&this.reconnect.start()}}async refreshAndRebuild(){if(this.refreshOperation!==void 0)return this.refreshOperation;let e=this.performRefreshAndRebuild().finally(()=>{this.refreshOperation===e&&(this.refreshOperation=void 0),this.sessionRecoveryPending&&!this.hasNonTerminalCalls()&&!this.disposed&&this.recoverInvalidSession()});return this.refreshOperation=e,e}async performRefreshAndRebuild(){if(this.disposed||this.session===void 0)return;let e=this.lifecycleGeneration,t=this.session;try{let n=await this.api.refreshSession(t.sessionId);if(!this.isCurrentGeneration(e)||this.session!==t)return;if(this.session=n,this.callManager?.updateSession(n),this.events.emit(`token.refreshed`,{expiresAt:n.expiresAt}),this.hasNonTerminalCalls()){this.deferredRebuild=!0,this.scheduleRefresh(n);return}let r=await this.getSip();if(!this.isCurrentGeneration(e))return;await r.connect(n),this.isCurrentGeneration(e)&&(this.deferredRebuild=!1,this.setConnectionState(`connected`),this.scheduleRefresh(n))}catch(n){if(!this.isCurrentGeneration(e))return;throw this.handleRefreshFailure(t,n),n}}handleRefreshFailure(e,t){if(this.disposed)return;let n=Z(t,`NETWORK_OFFLINE`,`network`,!0);if(this.events.emit(`token.expiring`,{expiresAt:e.expiresAt}),this.events.emit(`error`,{error:n}),cr(t)){this.clearRefreshTimer(),this.reconnect.cancel(),this.deletedSessions.add(e.sessionId),this.sessionRecoveryPending=!0,this.deferredRebuild=!0,(n.code===`AUTH_TOKEN_UNAVAILABLE`||n.code===`AUTH_TOKEN_EXPIRED`||n.code===`AUTH_TOKEN_REJECTED`)&&this.api.invalidateToken?.();return}this.deferredRebuild=!0,this.hasNonTerminalCalls()||this.reconnect.start()}async recoverInvalidSession(){if(!(!this.sessionRecoveryPending||this.disposed||this.hasNonTerminalCalls())){this.sessionRecoveryPending=!1,this.deferredRebuild=!1;try{await this.performDisconnect()}catch(e){this.disposed||this.events.emit(`error`,{error:Z(e,`SDK_INTERNAL_ERROR`,`internal`,!0)});return}if(!this.disposed)try{await this.performConnect(this.lifecycleGeneration)}catch{this.disposed||this.reconnect.start()}}}scheduleRefresh(e){this.clearRefreshTimer();let t=e.expiresAt*1e3-Date.now()-6e4,n=Math.max(1e3,t);this.refreshTimer=setTimeout(()=>{this.refreshTimer=void 0,this.refreshAndRebuild().catch(()=>void 0)},n)}async recoverConnection(){if(!(this.disposed||this.intentionalDisconnect)){if(this.hasNonTerminalCalls()){let e=Date.now();if(this.stuckCallsSince===void 0&&(this.stuckCallsSince=e),e-this.stuckCallsSince<$n)return;this.stuckCallsSince=void 0,await this.callManager?.forceTerminateCalls()}else this.stuckCallsSince=void 0;if(await this.awaitMediaReleaseBarriers(),this.session===void 0){await this.performConnect(this.lifecycleGeneration);return}await this.refreshAndRebuild()}}async getSip(){if(this.sip!==void 0)return this.sip;if(this.suppliedSip!==void 0)return this.sip=this.suppliedSip,this.sip;let[e,t]=await Promise.all([Promise.resolve().then(()=>(xn(),_n)),Promise.resolve().then(()=>(Qn(),Rn))]);return this.sip=new t.JsSipAdapter(e.createJsSipFactory(),this.options.baseUrl,this.options.sipKeepaliveSeconds,this.options.agentTerminal,this.options.sipSessionTimers??!1),this.sip}attachSipListener(e){this.sipUnsubscribe===void 0&&e.onConnectionStateChanged!==void 0&&(this.sipUnsubscribe=e.onConnectionStateChanged((e,t)=>{if(!(this.disposed||this.intentionalDisconnect||!this.acceptingEvents)){if(e===`registered`){this.setConnectionState(`connected`);return}this.state===`connected`&&(this.setConnectionState(`reconnecting`),this.reconnect.start(),t!==void 0&&this.events.emit(`error`,{error:Z(t,`SIP_WS_UNAVAILABLE`,`registration`,!0)}))}}))}attachNetworkListeners(){if(this.networkUnsubscribers.length>0||typeof window>`u`)return;let e=window,t=()=>{this.reconnect.notifyOnline(),this.scheduleIceReassessment()},n=()=>this.reconnect.notifyOffline(),r=()=>this.scheduleIceReassessment();e.addEventListener(`online`,t),e.addEventListener(`offline`,n);let i=(typeof navigator>`u`?void 0:navigator)?.connection;i?.addEventListener(`change`,r),this.networkUnsubscribers=[()=>e.removeEventListener(`online`,t),()=>e.removeEventListener(`offline`,n),...i===void 0?[]:[()=>i.removeEventListener(`change`,r)]]}scheduleIceReassessment(){this.networkProbeTimer!==void 0&&clearTimeout(this.networkProbeTimer),this.networkProbeTimer=setTimeout(()=>{this.networkProbeTimer=void 0,!this.disposed&&this.state===`connected`&&this.sip?.reassessIceServers?.(`network-online`)},2e3)}detachNetworkListeners(){this.networkProbeTimer!==void 0&&clearTimeout(this.networkProbeTimer),this.networkProbeTimer=void 0,this.networkUnsubscribers.splice(0).forEach(e=>e())}getActiveMediaContext(){let e=this.callManager?.getActiveCall();return e===void 0?void 0:this.mediaBridge.contextFor(e.id,e.state,new Set(this.session?.capabilities??[]))}hasNonTerminalCalls(){return this.callManager?.hasNonTerminalCalls()??!1}clearRefreshTimer(){this.refreshTimer!==void 0&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)}createDiagnosticsSnapshot(){let e=this.session;return{connectionState:this.state,calls:this.getCalls().map(e=>({callId:e.id,state:e.state,destination:e.destination})),permission:this.support?.hasMediaDevices===!1?`unsupported`:`unknown`,ice:nr(e,this.sip?.iceQualitySnapshot?.()),wss:{configured:e!==void 0,secure:e?.transport.wssUrl.toLowerCase().startsWith(`wss://`)??!1,state:this.state},resources:this.getDiagnosticsResourceCounts()}}getDiagnosticsResourceCounts(){let e=this.mediaBridge.getResourceCounts(),t=this.callManager?.getResourceCounts()??{timers:0,listeners:0},n=this.sip?.getResourceCounts?.(),r=(this.callManager===void 0?0:1)+(this.sipUnsubscribe===void 0?0:1),i=this.session!==void 0&&this.state!==`idle`&&this.state!==`disconnected`;return{timers:(this.refreshTimer===void 0?0:1)+this.reconnect.getTimerCount()+t.timers,listeners:this.events.listenerCount()+t.listeners+e.listeners+this.networkUnsubscribers.length+(n?.listeners??r),tracks:e.tracks,peerConnections:e.peerConnections,audioElements:e.audioElements,webSockets:n?.webSockets??+!!i,deletedSessions:this.deletedSessions.size}}async readMicrophonePermission(){if(typeof navigator>`u`||navigator.mediaDevices===void 0)return`unsupported`;if(navigator.permissions===void 0)return`unknown`;try{return(await navigator.permissions.query({name:`microphone`})).state}catch{return`unknown`}}deleteSession(e){if(this.deletedSessions.has(e))return Promise.resolve();let t=this.sessionDeleteOperations.get(e);if(t!==void 0)return t;let n=this.api.deleteSession(e).then(()=>{this.deletedSessions.add(e)}).catch(t=>{if(cr(t)){this.deletedSessions.add(e);return}throw t}).finally(()=>{this.sessionDeleteOperations.get(e)===n&&this.sessionDeleteOperations.delete(e)});return this.sessionDeleteOperations.set(e,n),n}pruneDeletedSessionTombstones(){for(let e of[...this.deletedSessions])!this.ownedSessionIds.has(e)&&!this.sessionDeleteOperations.has(e)&&this.deletedSessions.delete(e)}async deleteOwnedSessions(){let e;for(let t of[...this.ownedSessionIds])try{await this.deleteSession(t),this.ownedSessionIds.delete(t)}catch(t){e??=t}if(e!==void 0)throw e}resolvePlatform(){let e=this.options.platform??this.detectedPlatform;if(e===void 0)throw new m(`CONFIG_INVALID`,`configuration`,!1,{cause:this.support?.platform??`unknown`});return e}setConnectionState(e){this.state===e||this.disposed||(this.state=e,this.diagnostics.log(`info`,`connection.stateChanged`,{state:e}),this.events.emit(`connection.stateChanged`,{state:e===`disconnected`||e===`idle`?`offline`:e}))}assertConnected(){if(this.assertNotDisposed(),this.state!==`connected`||this.callManager===void 0||this.session===void 0)throw new m(`CALL_NOT_CONNECTED`,`call`,!1)}assertGeneration(e){if(this.disposed)throw this.disposedError();if(e!==this.lifecycleGeneration)throw new m(`CALL_NOT_CONNECTED`,`call`,!1)}isCurrentGeneration(e){return!this.disposed&&e===this.lifecycleGeneration}async awaitSharedWorkerReady(){let e=this.sharedWorkerSelection;if(e.mode===`shared`)try{await e.ready}catch(e){if(this.disposed)return;if(this.options.sharedWorker?.fallback===`error`)throw e;this.sharedWorkerSelection={mode:`single-tab`,reason:e instanceof Error?e.message:`SharedWorker attach failed`}}}releaseSharedWorker(){let e=this.sharedWorkerSelection;if(this.sharedWorkerSelection={mode:`single-tab`,reason:`disposed`},e.mode===`shared`){try{e.client.request({version:1,type:`detach`,requestId:`detach-${e.tabId}`,tabId:e.tabId}).catch(()=>void 0)}catch{}e.client.close()}}assertNotDisposed(){if(this.disposed)throw this.disposedError()}disposedError(){return new m(`SDK_ALREADY_DISPOSED`,`internal`,!1)}};function nr(e,t){if(e===void 0)return{configured:!1,serverCount:0,stunServerCount:0,turnServerCount:0,...t?{probe:t}:{}};let n=0,r=0;return e.iceServers.forEach(e=>{let t=e.urls.map(e=>e.toLowerCase());t.some(e=>e.startsWith(`stun:`))&&(n+=1),t.some(e=>e.startsWith(`turn:`)||e.startsWith(`turns:`))&&(r+=1)}),{...t?{probe:t}:{},configured:e.iceServers.length>0,serverCount:e.iceServers.length,stunServerCount:n,turnServerCount:r}}function rr(e){return e===``?`unknown`:/iPhone|iPad|Android/i.test(e)?`mobile-web`:`web`}function ir(e){if(typeof e!=`object`||!e)throw new m(`CONFIG_INVALID`,`configuration`,!1);return e}async function ar(e){let t=e.sip?.registerTicket;if(typeof t!=`string`||t===``)return e;let n=await pe(t);return n===void 0||n===t?e:{...e,sip:{...e.sip,registerTicket:n}}}function or(e){let t={createSession:async t=>ar(await e.createSession(t)),refreshSession:async t=>ar(e.refreshSession===void 0?await e.createSession({sdkVersion:M,platform:`web`}):await e.refreshSession(t)),deleteSession:async t=>{e.deleteSession!==void 0&&await e.deleteSession(t)},setAgentStatus:(t,n)=>e.setAgentStatus===void 0?Promise.reject(new m(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{cause:`当前会话来源不支持坐席状态设置(sessionProvider.setAgentStatus 未提供)`})):e.setAgentStatus(t,n)},n=e.invalidateToken;return n!==void 0&&(t.invalidateToken=()=>n()),t}function sr(e){if(typeof e!=`object`||!e)throw new m(`CONFIG_INVALID`,`configuration`,!1);return e}function Z(e,t,n,r,i){return e instanceof m?new m(e.code,e.category,e.retryable,{requestId:e.requestId,callId:i??e.callId,cause:e.cause??e,serverCode:e.serverCode,platformCode:e.platformCode,status:e.status}):new m(t,n,r,{callId:i,cause:e})}function cr(e){return e instanceof m?e.status!==void 0&&e.status>=400&&e.status<500||e.serverCode===`SESSION_NOT_FOUND`||e.serverCode===`SESSION_EXPIRED`||e.serverCode===`TOKEN_INVALID`||e.serverCode===`TOKEN_EXPIRED`||e.code===`AUTH_TOKEN_UNAVAILABLE`||e.code===`AUTH_TOKEN_EXPIRED`||e.code===`AUTH_TOKEN_REJECTED`:!1}function lr(e){return e instanceof m&&e.code===`SDK_ALREADY_DISPOSED`}function ur(e){return e instanceof m&&(e.code===`SDK_ALREADY_DISPOSED`||e.code===`CALL_NOT_CONNECTED`)}var dr=[`outbound`,`inbound`,`mute`,`hold`,`dtmf`,`blind_transfer`,`device_selection`],fr=[`outbound`,`mute`,`dtmf`];function pr(e){return e===`mobile-web`?fr:dr}h(),h();function Q(e={}){return{version:`0.1.0`,options:e}}e.CCBarCall=ee,e.CCBarClient=tr,e.CCBarError=m,e.CallManager=ae,e.CallStateError=b,e.Diagnostics=ht,e.RingBuffer=ft,e.TypedEventBus=g,e.assertCallTransition=y,e.canTransition=v,e.createSdk=Q,e.createSharedWorkerSelection=I,e.diagnosticsVersion=M,e.parseSessionResponse=S,e.redactText=Ee,e.redactValue=De,e.resolveWorkerUrl=Pe,e.transition=x,e.transitions=_,e.version=`0.1.0`});
|